From b98918e54138ac01e859004dbd41a16ac839ab74 Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Sun, 23 Nov 2025 13:00:42 +0100 Subject: [PATCH 01/70] unify(client): Move ParabolicEase, CameraShakeSystem to Core (#1904) --- Core/GameEngine/CMakeLists.txt | 4 ++-- .../GameEngine/Include/GameClient/ParabolicEase.h | 0 .../GameEngine/Source/GameClient/ParabolicEase.cpp | 0 Core/GameEngineDevice/CMakeLists.txt | 2 +- .../Include/W3DDevice/GameClient/CameraShakeSystem.h | 0 .../Source/W3DDevice/GameClient/CameraShakeSystem.cpp | 2 +- GeneralsMD/Code/GameEngine/CMakeLists.txt | 4 ++-- GeneralsMD/Code/GameEngineDevice/CMakeLists.txt | 4 ++-- .../GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp | 2 +- scripts/cpp/unify_move_files.py | 5 +++++ 10 files changed, 14 insertions(+), 9 deletions(-) rename {GeneralsMD/Code => Core}/GameEngine/Include/GameClient/ParabolicEase.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Source/GameClient/ParabolicEase.cpp (100%) rename GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/camerashakesystem.h => Core/GameEngineDevice/Include/W3DDevice/GameClient/CameraShakeSystem.h (100%) rename GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/camerashakesystem.cpp => Core/GameEngineDevice/Source/W3DDevice/GameClient/CameraShakeSystem.cpp (99%) diff --git a/Core/GameEngine/CMakeLists.txt b/Core/GameEngine/CMakeLists.txt index d1af9c1e69..30365854fd 100644 --- a/Core/GameEngine/CMakeLists.txt +++ b/Core/GameEngine/CMakeLists.txt @@ -210,7 +210,7 @@ set(GAMEENGINE_SRC # Include/GameClient/Module/BeaconClientUpdate.h # Include/GameClient/Module/SwayClientUpdate.h # Include/GameClient/Mouse.h -# Include/GameClient/ParabolicEase.h + Include/GameClient/ParabolicEase.h # Include/GameClient/ParticleSys.h # Include/GameClient/PlaceEventTranslator.h # Include/GameClient/ProcessAnimateWindow.h @@ -815,7 +815,7 @@ set(GAMEENGINE_SRC # Source/GameClient/MessageStream/PlaceEventTranslator.cpp # Source/GameClient/MessageStream/SelectionXlat.cpp # Source/GameClient/MessageStream/WindowXlat.cpp -# Source/GameClient/ParabolicEase.cpp + Source/GameClient/ParabolicEase.cpp # Source/GameClient/RadiusDecal.cpp # Source/GameClient/SelectionInfo.cpp # Source/GameClient/Snow.cpp diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ParabolicEase.h b/Core/GameEngine/Include/GameClient/ParabolicEase.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/GameClient/ParabolicEase.h rename to Core/GameEngine/Include/GameClient/ParabolicEase.h diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/ParabolicEase.cpp b/Core/GameEngine/Source/GameClient/ParabolicEase.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/GameClient/ParabolicEase.cpp rename to Core/GameEngine/Source/GameClient/ParabolicEase.cpp diff --git a/Core/GameEngineDevice/CMakeLists.txt b/Core/GameEngineDevice/CMakeLists.txt index 6c390f7d84..fa4a7fd713 100644 --- a/Core/GameEngineDevice/CMakeLists.txt +++ b/Core/GameEngineDevice/CMakeLists.txt @@ -98,7 +98,7 @@ set(GAMEENGINEDEVICE_SRC # Source/W3DDevice/Common/Thing/W3DThingFactory.cpp # Source/W3DDevice/Common/W3DConvert.cpp # Source/W3DDevice/GameClient/BaseHeightMap.cpp -# Source/W3DDevice/GameClient/camerashakesystem.cpp + Source/W3DDevice/GameClient/CameraShakeSystem.cpp # Source/W3DDevice/GameClient/Drawable/Draw/W3DDebrisDraw.cpp # Source/W3DDevice/GameClient/Drawable/Draw/W3DDefaultDraw.cpp # Source/W3DDevice/GameClient/Drawable/Draw/W3DDependencyModelDraw.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/camerashakesystem.h b/Core/GameEngineDevice/Include/W3DDevice/GameClient/CameraShakeSystem.h similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/camerashakesystem.h rename to Core/GameEngineDevice/Include/W3DDevice/GameClient/CameraShakeSystem.h diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/camerashakesystem.cpp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/CameraShakeSystem.cpp similarity index 99% rename from GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/camerashakesystem.cpp rename to Core/GameEngineDevice/Source/W3DDevice/GameClient/CameraShakeSystem.cpp index 32922d8514..71d7124a47 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/camerashakesystem.cpp +++ b/Core/GameEngineDevice/Source/W3DDevice/GameClient/CameraShakeSystem.cpp @@ -75,7 +75,7 @@ #include "W3DDevice/GameClient/W3DPoly.h" #include "W3DDevice/GameClient/W3DCustomScene.h" -#include "W3DDevice/GameClient/camerashakesystem.h" +#include "W3DDevice/GameClient/CameraShakeSystem.h" #include "WW3D2/camera.h" //#include "W3DDevice/GameClient/camera.h" diff --git a/GeneralsMD/Code/GameEngine/CMakeLists.txt b/GeneralsMD/Code/GameEngine/CMakeLists.txt index 0e11b9021a..fb10906885 100644 --- a/GeneralsMD/Code/GameEngine/CMakeLists.txt +++ b/GeneralsMD/Code/GameEngine/CMakeLists.txt @@ -206,7 +206,7 @@ set(GAMEENGINE_SRC Include/GameClient/Module/BeaconClientUpdate.h Include/GameClient/Module/SwayClientUpdate.h Include/GameClient/Mouse.h - Include/GameClient/ParabolicEase.h +# Include/GameClient/ParabolicEase.h Include/GameClient/ParticleSys.h Include/GameClient/PlaceEventTranslator.h Include/GameClient/ProcessAnimateWindow.h @@ -807,7 +807,7 @@ set(GAMEENGINE_SRC Source/GameClient/MessageStream/PlaceEventTranslator.cpp Source/GameClient/MessageStream/SelectionXlat.cpp Source/GameClient/MessageStream/WindowXlat.cpp - Source/GameClient/ParabolicEase.cpp +# Source/GameClient/ParabolicEase.cpp Source/GameClient/RadiusDecal.cpp Source/GameClient/SelectionInfo.cpp Source/GameClient/Snow.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/CMakeLists.txt b/GeneralsMD/Code/GameEngineDevice/CMakeLists.txt index 40c75076c3..4d32d9dd1f 100644 --- a/GeneralsMD/Code/GameEngineDevice/CMakeLists.txt +++ b/GeneralsMD/Code/GameEngineDevice/CMakeLists.txt @@ -7,7 +7,7 @@ set(GAMEENGINEDEVICE_SRC # Include/W3DDevice/Common/W3DRadar.h Include/W3DDevice/Common/W3DThingFactory.h Include/W3DDevice/GameClient/BaseHeightMap.h - Include/W3DDevice/GameClient/camerashakesystem.h +# Include/W3DDevice/GameClient/camerashakesystem.h Include/W3DDevice/GameClient/FlatHeightMap.h Include/W3DDevice/GameClient/HeightMap.h Include/W3DDevice/GameClient/Module/W3DDebrisDraw.h @@ -98,7 +98,7 @@ set(GAMEENGINEDEVICE_SRC Source/W3DDevice/Common/Thing/W3DThingFactory.cpp Source/W3DDevice/Common/W3DConvert.cpp Source/W3DDevice/GameClient/BaseHeightMap.cpp - Source/W3DDevice/GameClient/camerashakesystem.cpp +# Source/W3DDevice/GameClient/camerashakesystem.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DDebrisDraw.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DDefaultDraw.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DDependencyModelDraw.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp index a9009cdc70..28ed342548 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp @@ -93,7 +93,7 @@ #include "WW3D2/predlod.h" #include "WW3D2/ww3d.h" -#include "W3DDevice/GameClient/camerashakesystem.h" +#include "W3DDevice/GameClient/CameraShakeSystem.h" #include "WinMain.h" /** @todo Remove this, it's only here because we are using timeGetTime, but we can remove that diff --git a/scripts/cpp/unify_move_files.py b/scripts/cpp/unify_move_files.py index c7e80a9325..9e874ad3a0 100644 --- a/scripts/cpp/unify_move_files.py +++ b/scripts/cpp/unify_move_files.py @@ -180,6 +180,11 @@ def main(): #unify_file(Game.ZEROHOUR, "GameEngineDevice/Include/W3DDevice/GameClient/W3DShaderManager.h", Game.CORE, "GameEngineDevice/Include/W3DDevice/GameClient/W3DShaderManager.h") #unify_file(Game.ZEROHOUR, "GameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cpp", Game.CORE, "GameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cpp") + #unify_move_file(Game.ZEROHOUR, "GameEngine/Include/GameClient/ParabolicEase.h", Game.CORE, "GameEngine/Include/GameClient/ParabolicEase.h") + #unify_move_file(Game.ZEROHOUR, "GameEngine/Source/GameClient/ParabolicEase.cpp", Game.CORE, "GameEngine/Source/GameClient/ParabolicEase.cpp") + #unify_move_file(Game.ZEROHOUR, "GameEngineDevice/Include/W3DDevice/GameClient/camerashakesystem.h", Game.CORE, "GameEngineDevice/Include/W3DDevice/GameClient/CameraShakeSystem.h") + #unify_move_file(Game.ZEROHOUR, "GameEngineDevice/Source/W3DDevice/GameClient/camerashakesystem.cpp", Game.CORE, "GameEngineDevice/Source/W3DDevice/GameClient/CameraShakeSystem.cpp") + return From a40d246bcc93cc9bdf41392992dfa0e7e0a73ff9 Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Mon, 24 Nov 2025 19:41:33 +0100 Subject: [PATCH 02/70] unify(view): Merge View and closely related code (#1904) --- .../GameEngine/Include/Common/DrawModule.h | 5 + .../GameEngine/Include/GameClient/Display.h | 5 +- .../Code/GameEngine/Include/GameClient/View.h | 24 +- .../GameClient/Module/W3DModelDraw.h | 2 + .../Include/W3DDevice/GameClient/W3DDisplay.h | 1 + .../Include/W3DDevice/GameClient/W3DView.h | 66 ++- .../GameClient/Drawable/Draw/W3DModelDraw.cpp | 42 ++ .../W3DDevice/GameClient/W3DDisplay.cpp | 6 + .../Source/W3DDevice/GameClient/W3DView.cpp | 547 +++++++++++++----- .../GameEngine/Include/GameClient/Display.h | 4 +- .../Code/GameEngine/Include/GameClient/View.h | 20 +- .../Source/W3DDevice/GameClient/W3DView.cpp | 25 +- 12 files changed, 544 insertions(+), 203 deletions(-) diff --git a/Generals/Code/GameEngine/Include/Common/DrawModule.h b/Generals/Code/GameEngine/Include/Common/DrawModule.h index b9e458a64a..e13310fa18 100644 --- a/Generals/Code/GameEngine/Include/Common/DrawModule.h +++ b/Generals/Code/GameEngine/Include/Common/DrawModule.h @@ -38,6 +38,7 @@ // FORWARD REFERENCES ///////////////////////////////////////////////////////////////////////////// class Matrix3D; class RenderCost; +class OBBoxClass; // TYPES ////////////////////////////////////////////////////////////////////////////////////////// @@ -154,6 +155,10 @@ class ObjectDrawInterface // this method must ONLY be called from the client, NEVER From the logic, not even indirectly. virtual Bool clientOnly_getRenderObjInfo(Coord3D* pos, Real* boundingSphereRadius, Matrix3D* transform) const = 0; + + // (gth) C&C3 adding these accessors to render object properties + virtual Bool clientOnly_getRenderObjBoundBox(OBBoxClass * boundbox) const = 0; + virtual Bool clientOnly_getRenderObjBoneTransform(const AsciiString & boneName,Matrix3D * set_tm) const = 0; /** Find the bone(s) with the given name and return their positions and/or transforms in the given arrays. We look for a bone named "boneNamePrefixQQ", where QQ is 01, 02, 03, etc, starting at the diff --git a/Generals/Code/GameEngine/Include/GameClient/Display.h b/Generals/Code/GameEngine/Include/GameClient/Display.h index 4d12e246e3..5823e8aef6 100644 --- a/Generals/Code/GameEngine/Include/GameClient/Display.h +++ b/Generals/Code/GameEngine/Include/GameClient/Display.h @@ -29,11 +29,9 @@ #pragma once #include "Common/SubsystemInterface.h" -#include "View.h" #include "GameClient/Color.h" #include "GameClient/GameFont.h" - -class View; +#include "GameClient/View.h" struct ShroudLevel { @@ -173,6 +171,7 @@ class Display : public SubsystemInterface virtual void toggleLetterBox(void) = 0; ///< enabled letter-boxed display virtual void enableLetterBox(Bool enable) = 0; ///< forces letter-boxed display on/off virtual Bool isLetterBoxFading( void ) { return FALSE; } ///< returns true while letterbox fades in/out + virtual Bool isLetterBoxed( void ) { return FALSE; } //WST 10/2/2002. Added query interface virtual void setCinematicText( AsciiString string ) { m_cinematicText = string; } virtual void setCinematicFont( GameFont *font ) { m_cinematicFont = font; } diff --git a/Generals/Code/GameEngine/Include/GameClient/View.h b/Generals/Code/GameEngine/Include/GameClient/View.h index 9882babcc3..a175dcc908 100644 --- a/Generals/Code/GameEngine/Include/GameClient/View.h +++ b/Generals/Code/GameEngine/Include/GameClient/View.h @@ -135,19 +135,23 @@ class View : public Snapshot virtual void initHeightForMap( void ) {}; ///< Init the camera height for the map at the current position. virtual void scrollBy( Coord2D *delta ); ///< Shift the view by the given delta - virtual void moveCameraTo(const Coord3D *o, Int frames, Int shutter, Bool orient) { lookAt( o ); } - virtual void moveCameraAlongWaypointPath(Waypoint *way, Int frames, Int shutter, Bool orient) { } + virtual void moveCameraTo(const Coord3D *o, Int frames, Int shutter, Bool orient, Real easeIn=0.0f, Real easeOut=0.0f) { lookAt( o ); } + virtual void moveCameraAlongWaypointPath(Waypoint *way, Int frames, Int shutter, Bool orient, Real easeIn=0.0f, Real easeOut=0.0f) { } virtual Bool isCameraMovementFinished( void ) { return TRUE; } - virtual void cameraModFinalZoom(Real finalZoom){}; ///< Final zoom for current camera movement. + virtual void cameraModFinalZoom(Real finalZoom, Real easeIn=0.0f, Real easeOut=0.0f){}; ///< Final zoom for current camera movement. virtual void cameraModRollingAverage(Int framesToAverage){}; ///< Number of frames to average movement for current camera movement. virtual void cameraModFinalTimeMultiplier(Int finalMultiplier){}; ///< Final time multiplier for current camera movement. - virtual void cameraModFinalPitch(Real finalPitch){}; ///< Final pitch for current camera movement. + virtual void cameraModFinalPitch(Real finalPitch, Real easeIn=0.0f, Real easeOut=0.0f){}; ///< Final pitch for current camera movement. virtual void cameraModFreezeTime(void){ } ///< Freezes time during the next camera movement. virtual void cameraModFreezeAngle(void){ } ///< Freezes time during the next camera movement. virtual void cameraModLookToward(Coord3D *pLoc){} ///< Sets a look at point during camera movement. virtual void cameraModFinalLookToward(Coord3D *pLoc){} ///< Sets a look at point during camera movement. virtual void cameraModFinalMoveTo(Coord3D *pLoc){ }; ///< Sets a final move to. + // (gth) C&C3 animation controled camera feature + virtual void cameraEnableSlaveMode(const AsciiString & thingtemplateName, const AsciiString & boneName) {} + virtual void cameraDisableSlaveMode(void) {} + virtual void Add_Camera_Shake(const Coord3D & position,float radius, float duration, float power) {} virtual FilterModes getViewFilterMode(void) {return (FilterModes)0;} ///< Turns on viewport special effect (black & white mode) virtual FilterTypes getViewFilterType(void) {return (FilterTypes)0;} ///< Turns on viewport special effect (black & white mode) virtual Bool setViewFilterMode(FilterModes filterMode) { return FALSE; } ///< Turns on viewport special effect (black & white mode) @@ -157,16 +161,16 @@ class View : public Snapshot virtual void setFadeParameters(Int fadeFrames, Int direction) { }; virtual void set3DWireFrameMode(Bool enable) { }; - virtual void resetCamera(const Coord3D *location, Int frames) {}; ///< Move camera to location, and reset to default angle & zoom. - virtual void rotateCamera(Real rotations, Int frames) {}; ///< Rotate camera about current viewpoint. - virtual void rotateCameraTowardObject(ObjectID id, Int milliseconds, Int holdMilliseconds) {}; ///< Rotate camera to face an object, and hold on it - virtual void rotateCameraTowardPosition(const Coord3D *pLoc, Int milliseconds) {}; ///< Rotate camera to face a location. + virtual void resetCamera(const Coord3D *location, Int frames, Real easeIn=0.0f, Real easeOut=0.0f) {}; ///< Move camera to location, and reset to default angle & zoom. + virtual void rotateCamera(Real rotations, Int frames, Real easeIn=0.0f, Real easeOut=0.0f) {}; ///< Rotate camera about current viewpoint. + virtual void rotateCameraTowardObject(ObjectID id, Int milliseconds, Int holdMilliseconds, Real easeIn=0.0f, Real easeOut=0.0f) {}; ///< Rotate camera to face an object, and hold on it + virtual void rotateCameraTowardPosition(const Coord3D *pLoc, Int milliseconds, Real easeIn=0.0f, Real easeOut=0.0f, Bool reverseRotation=FALSE) {}; ///< Rotate camera to face a location. virtual Bool isTimeFrozen(void){ return false;} ///< Freezes time during the next camera movement. virtual Int getTimeMultiplier(void) {return 1;}; ///< Get the time multiplier. virtual void setTimeMultiplier(Int multiple) {}; ///< Set the time multiplier. virtual void setDefaultView(Real pitch, Real angle, Real maxHeight) {}; - virtual void zoomCamera( Real finalZoom, Int milliseconds ) {}; - virtual void pitchCamera( Real finalPitch, Int milliseconds ) {}; + virtual void zoomCamera( Real finalZoom, Int milliseconds, Real easeIn=0.0f, Real easeOut=0.0f ) {}; + virtual void pitchCamera( Real finalPitch, Int milliseconds, Real easeIn=0.0f, Real easeOut=0.0f ) {}; virtual void setAngle( Real angle ); ///< Rotate the view around the up axis to the given angle virtual Real getAngle( void ) { return m_angle; } diff --git a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h index 2589bcb7c4..293ca4bc07 100644 --- a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h +++ b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h @@ -363,6 +363,8 @@ class W3DModelDraw : public DrawModule, public ObjectDrawInterface // this method must ONLY be called from the client, NEVER From the logic, not even indirectly. virtual Bool clientOnly_getRenderObjInfo(Coord3D* pos, Real* boundingSphereRadius, Matrix3D* transform) const; + virtual Bool clientOnly_getRenderObjBoundBox(OBBoxClass * boundbox) const; + virtual Bool clientOnly_getRenderObjBoneTransform(const AsciiString & boneName,Matrix3D * set_tm) const; virtual Int getPristineBonePositionsForConditionState(const ModelConditionFlags& condition, const char* boneNamePrefix, Int startIndex, Coord3D* positions, Matrix3D* transforms, Int maxBones) const; virtual Int getCurrentBonePositions(const char* boneNamePrefix, Int startIndex, Coord3D* positions, Matrix3D* transforms, Int maxBones) const; virtual Bool getCurrentWorldspaceClientBonePositions(const char* boneName, Matrix3D& transform) const; diff --git a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDisplay.h b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDisplay.h index 018e27ef81..472d9d31bc 100644 --- a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDisplay.h +++ b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDisplay.h @@ -127,6 +127,7 @@ class W3DDisplay : public Display virtual void enableLetterBox(Bool enable); ///Get_Obj_Space_Bounding_Box(aabox); + + Matrix3D tm = m_renderObject->Get_Transform(); + + // build an OBB for this AAB,transform + OBBoxClass box0(aabox.Center,aabox.Extent); + OBBoxClass::Transform(tm,box0,boundbox); + + return true; +} + + +//------------------------------------------------------------------------------------------------- +// (gth) C&C3 Added this accessor for a bone transform in the render object +// this method must ONLY be called from the client, NEVER From the logic, not even indirectly. +Bool W3DModelDraw::clientOnly_getRenderObjBoneTransform(const AsciiString & boneName,Matrix3D * set_tm) const +{ + if (!m_renderObject) { + return false; + } + + int idx = m_renderObject->Get_Bone_Index(boneName.str()); + if (idx == 0) { + set_tm->Make_Identity(); + return false; + } else { + *set_tm = m_renderObject->Get_Bone_Transform(idx); + return true; + } +} + + //------------------------------------------------------------------------------------------------- Bool W3DModelDraw::getCurrentWorldspaceClientBonePositions(const char* boneName, Matrix3D& transform) const { diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp index 90a1efd54c..9767f32c29 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp @@ -1940,6 +1940,12 @@ Bool W3DDisplay::isLetterBoxFading(void) return FALSE; } +//WST 10/2/2002 added query function. JSC Integrated 5/20/03 +Bool W3DDisplay::isLetterBoxed(void) +{ + return (m_letterBoxEnabled); +} + // W3DDisplay::createLightPulse =============================================== /** Create a "light pulse" which is a dynamic light that grows, decays * and vanishes over several frames */ diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp index 703673a96f..b149463541 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp @@ -93,6 +93,8 @@ #include "WW3D2/predlod.h" #include "WW3D2/ww3d.h" +#include "W3DDevice/GameClient/CameraShakeSystem.h" + #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 */ @@ -150,8 +152,8 @@ W3DView::W3DView() m_cameraOffset.y = -(m_cameraOffset.z / tan(TheGlobalData->m_cameraPitch * (PI / 180.0))); m_cameraOffset.x = -(m_cameraOffset.y * tan(TheGlobalData->m_cameraYaw * (PI / 180.0))); - m_viewFilterMode = FM_NULL_MODE; - m_viewFilter = FT_NULL_FILTER; + m_viewFilterMode = FM_VIEW_DEFAULT; + m_viewFilter = FT_VIEW_DEFAULT; m_isWireFrameEnabled = m_nextWireFrameEnabled = FALSE; m_shakeOffset.x = 0.0f; m_shakeOffset.y = 0.0f; @@ -162,6 +164,14 @@ W3DView::W3DView() m_locationRequests.clear(); m_locationRequests.reserve(MAX_REQUEST_CACHE_SIZE + 10); // This prevents the vector from ever re-allocing + //Enhancements from CNC3 WST 4/15/2003. JSC Integrated 5/20/03. + m_CameraArrivedAtWaypointOnPathFlag = false; // Scripts for polling camera reached targets + m_isCameraSlaved = false; // This is for 3DSMax camera playback + m_useRealZoomCam = false; // true; //WST 10/18/2002 + m_shakerAngles.X =0.0f; // Proper camera shake generator & sources + m_shakerAngles.Y =0.0f; + m_shakerAngles.Z =0.0f; + } //------------------------------------------------------------------------------------------------- @@ -231,6 +241,7 @@ void W3DView::setOrigin( Int x, Int y) //------------------------------------------------------------------------------------------------- /** @todo This is inefficient. We should construct the matrix directly using vectors. */ //------------------------------------------------------------------------------------------------- +#define MIN_CAPPED_ZOOM (0.5f) //WST 10.19.2002. JSC integrated 5/20/03. void W3DView::buildCameraTransform( Matrix3D *transform ) { Vector3 sourcePos, targetPos; @@ -255,10 +266,28 @@ void W3DView::buildCameraTransform( Matrix3D *transform ) } // set position of camera itself - sourcePos.X = m_cameraOffset.x*zoom; - sourcePos.Y = m_cameraOffset.y*zoom; - sourcePos.Z = m_cameraOffset.z*zoom; - + if (m_useRealZoomCam) //WST 10/10/2002 Real Zoom using FOV + { + sourcePos.X = m_cameraOffset.x; + sourcePos.Y = m_cameraOffset.y; + sourcePos.Z = m_cameraOffset.z; + Real capped_zoom = zoom; + if (capped_zoom > 1.0f) + { + capped_zoom= 1.0f; + } + if (capped_zoom < MIN_CAPPED_ZOOM) + { + capped_zoom = MIN_CAPPED_ZOOM; + } + m_FOV = 50.0f * PI/180.0f * capped_zoom * capped_zoom; + } + else + { + sourcePos.X = m_cameraOffset.x*zoom; + sourcePos.Y = m_cameraOffset.y*zoom; + sourcePos.Z = m_cameraOffset.z*zoom; + } #ifdef NOT_IN_USE if (TheGlobalData->m_isOffsetCameraZ && TheTerrainLogic) @@ -311,13 +340,124 @@ void W3DView::buildCameraTransform( Matrix3D *transform ) targetPos.Z += groundLevel; // do m_FXPitch adjustment. - Real height = sourcePos.Z - targetPos.Z; - height *= m_FXPitch; - targetPos.Z = sourcePos.Z - height; + //WST Real height = sourcePos.Z - targetPos.Z; + //WST height *= m_FXPitch; + //WST targetPos.Z = sourcePos.Z - height; + + + // The following code moves camera down and pitch up when player zooms in. + // Use scripts to switch to useRealZoomCam + if (m_useRealZoomCam) + { + Real pitch_adjust = 1.0f; + + if (!TheDisplay->isLetterBoxed()) + { + Real capped_zoom = zoom; + if (capped_zoom > 1.0f) + { + capped_zoom= 1.0f; + } + if (capped_zoom < MIN_CAPPED_ZOOM) + { + capped_zoom = MIN_CAPPED_ZOOM; + } + sourcePos.Z = sourcePos.Z * ( 0.5f + capped_zoom * 0.5f); // move camera down physically + pitch_adjust = capped_zoom; // adjust camera to pitch up + } + m_FXPitch = 1.0f * (0.25f + pitch_adjust*0.75f); + } + + + // do fxPitch adjustment + if (m_useRealZoomCam) + { + sourcePos.X = targetPos.X + ((sourcePos.X - targetPos.X) / m_FXPitch); + sourcePos.Y = targetPos.Y + ((sourcePos.Y - targetPos.Y) / m_FXPitch); + } + else + { + // TheSuperHackers @todo Investigate whether the non Generals code is correct for Zero Hour. + // It certainly is incorrect for Generals when m_FXPitch goes above 1: + // Seen in USA mission 1 second cut scene with SCUD Storm. +#if RTS_GENERALS + Real height = sourcePos.Z - targetPos.Z; + height *= m_FXPitch; + targetPos.Z = sourcePos.Z - height; +#else + if (m_FXPitch <= 1.0f) + { + Real height = sourcePos.Z - targetPos.Z; + height *= m_FXPitch; + targetPos.Z = sourcePos.Z - height; + } + else + { + sourcePos.X = targetPos.X + ((sourcePos.X - targetPos.X) / m_FXPitch); + sourcePos.Y = targetPos.Y + ((sourcePos.Y - targetPos.Y) / m_FXPitch); + } +#endif + } + + //m_3DCamera->Set_View_Plane(DEG_TO_RADF(50.0f)); + //DEBUG_LOG(("zoom %f, SourceZ %f, posZ %f, groundLevel %f CamOffZ %f", + // zoom, sourcePos.Z, pos.z, groundLevel,m_cameraOffset.z)); // build new camera transform transform->Make_Identity(); transform->Look_At( sourcePos, targetPos, 0 ); + + //WST 11/12/2002 New camera shaker system + // TheSuperHackers @tweak The camera shaker is now decoupled from the render update. + CameraShakerSystem.Timestep(TheFramePacer->getLogicTimeStepMilliseconds()); + CameraShakerSystem.Update_Camera_Shaker(sourcePos, &m_shakerAngles); + transform->Rotate_X(m_shakerAngles.X); + transform->Rotate_Y(m_shakerAngles.Y); + transform->Rotate_Z(m_shakerAngles.Z); + + //if (m_shakerAngles.X >= 0.0f) + //{ + // DEBUG_LOG(("m_shakerAngles %f, %f, %f", m_shakerAngles.X, m_shakerAngles.Y, m_shakerAngles.Z)); + //} + + // (gth) check if the camera is being controlled by an animation + if (m_isCameraSlaved) { + // find object named m_cameraSlaveObjectName + Object * obj = TheScriptEngine->getUnitNamed(m_cameraSlaveObjectName); + + if (obj != NULL) { + // dig out the drawable + Drawable * draw = obj->getDrawable(); + if (draw != NULL) { + + // dig out the first draw module with an ObjectDrawInterface + for (DrawModule ** dm = draw->getDrawModules(); *dm; ++dm) { + const ObjectDrawInterface* di = (*dm)->getObjectDrawInterface(); + if (di) { + Matrix3D tm; + di->clientOnly_getRenderObjBoneTransform(m_cameraSlaveObjectBoneName,&tm); + + // Ok, slam it into the camera! + *transform = tm; + + //-------------------------------------------------------------------- + // WST 10.22.2002. Update the Listener positions used by audio system + //-------------------------------------------------------------------- + Vector3 position = transform->Get_Translation(); + Coord3D coord; + coord.set(position.X, position.Y, position.Z); + View::setPosition(&coord); + break; + } + } + + } else { + m_isCameraSlaved = false; + } + } else { + m_isCameraSlaved = false; + } + } } //------------------------------------------------------------------------------------------------- @@ -422,14 +562,24 @@ void W3DView::setCameraTransform( void ) Matrix3D cameraTransform( 1 ); Real nearZ, farZ; - m_3DCamera->Get_Clip_Planes(nearZ, farZ); + // m_3DCamera->Get_Clip_Planes(nearZ, farZ); // Set the near to MAP_XY_FACTOR. Improves zbuffer resolution. nearZ = MAP_XY_FACTOR; farZ = 1200.0f; - if ((TheGlobalData && TheGlobalData->m_drawEntireTerrain) || (m_FXPitch<0.95f || m_zoom>1.05)) - { //need to extend far clip plane so entire terrain can be visible - farZ *= MAP_XY_FACTOR; + if (m_useRealZoomCam) //WST 10.19.2002 + { + if (m_FXPitch<0.95f) + { + farZ = farZ / m_FXPitch; //Extend far Z when we pitch up for RealZoomCam + } + } + else + { + if ((TheGlobalData && TheGlobalData->m_drawEntireTerrain) || (m_FXPitch<0.95f || m_zoom>1.05)) + { //need to extend far clip plane so entire terrain can be visible + farZ *= MAP_XY_FACTOR; + } } m_3DCamera->Set_Clip_Planes(nearZ, farZ); @@ -535,9 +685,9 @@ void W3DView::reset( void ) Coord3D arbitraryPos = { 0, 0, 0 }; // Just move the camera to 0, 0, 0. It'll get repositioned at the beginning of the next game // anyways. - resetCamera(&arbitraryPos, 1); + resetCamera(&arbitraryPos, 1, 0.0f, 0.0f); - setViewFilter((FilterTypes)0); + setViewFilter(FT_VIEW_DEFAULT); Coord2D gb = { 0,0 }; setGuardBandBias( &gb ); @@ -998,6 +1148,8 @@ void W3DView::update(void) if (cameraLock != INVALID_ID) { m_doingMoveCameraOnWaypointPath = false; + m_CameraArrivedAtWaypointOnPathFlag = false; + Object* cameraLockObj = TheGameLogic->findObjectByID(cameraLock); Bool loseLock = false; @@ -1175,6 +1327,12 @@ void W3DView::update(void) recalcCamera = true; } + //Process New C3 Camera Shaker system + if (CameraShakerSystem.IsCameraShaking()) + { + recalcCamera = true; + } + /* * In order to have the camera follow the terrain in a non-dizzying way, we will have a * "desired height" value that the user sets. While scrolling, the actual height (set by @@ -1194,7 +1352,7 @@ void W3DView::update(void) Real desiredHeight = (m_terrainHeightUnderCamera + m_heightAboveGround); Real desiredZoom = desiredHeight / m_cameraOffset.z; - if (didScriptedMovement) + if (didScriptedMovement) { // if we are in a scripted camera movement, take its height above ground as our desired height. m_heightAboveGround = m_currentHeightAboveGround; @@ -1231,8 +1389,17 @@ void W3DView::update(void) if (TheScriptEngine->isTimeFast()) { return; // don't draw - makes it faster :) jba. } - if (recalcCamera) + + // (gth) C&C3 if m_isCameraSlaved then force the camera to update each frame + if ((recalcCamera) || (m_isCameraSlaved)) { setCameraTransform(); + } + + +#ifdef DO_SEISMIC_SIMULATIONS + // Give the terrain a chance to refresh animating (Seismic) regions, if any. + TheTerrainVisual->updateSeismicSimulations(); +#endif Region3D axisAlignedRegion; getAxisAlignedViewRegion(axisAlignedRegion); @@ -1386,13 +1553,14 @@ void W3DView::draw( void ) Bool skipRender = false; Bool doExtraRender = false; CustomScenePassModes customScenePassMode = SCENE_PASS_DEFAULT; + Bool preRenderResult = false; if (m_viewFilterMode && m_viewFilter > FT_NULL_FILTER && m_viewFilter < FT_MAX) { // Most likely will redirect rendering to a texture. - W3DShaderManager::filterPreRender(m_viewFilter, skipRender, customScenePassMode); + preRenderResult=W3DShaderManager::filterPreRender(m_viewFilter, skipRender, customScenePassMode); if (!skipRender && getCameraLock()) { Object* cameraLockObj = TheGameLogic->findObjectByID(getCameraLock()); @@ -1421,8 +1589,9 @@ void W3DView::draw( void ) { Coord2D deltaScroll; calcDeltaScroll(deltaScroll); - Bool continueTheEffect; - continueTheEffect = W3DShaderManager::filterPostRender(m_viewFilter, m_viewFilterMode, deltaScroll,doExtraRender); + Bool continueTheEffect = false; + if (preRenderResult) //if prerender passed, do the post render. + continueTheEffect = W3DShaderManager::filterPostRender(m_viewFilter, m_viewFilterMode, deltaScroll,doExtraRender); if (!skipRender && getCameraLock()) { Object* cameraLockObj = TheGameLogic->findObjectByID(getCameraLock()); @@ -1441,8 +1610,8 @@ void W3DView::draw( void ) if (!continueTheEffect) { // shut it down. - m_viewFilter = FT_NULL_FILTER; - m_viewFilterMode = FM_NULL_MODE; + m_viewFilter = FT_VIEW_DEFAULT; + m_viewFilterMode = FM_VIEW_DEFAULT; } } @@ -1719,6 +1888,8 @@ void W3DView::setAngle( Real angle ) m_doingMoveCameraOnWaypointPath = false; + m_CameraArrivedAtWaypointOnPathFlag = false; + m_doingRotateCamera = false; m_doingPitchCamera = false; m_doingZoomCamera = false; @@ -1778,6 +1949,7 @@ void W3DView::setHeightAboveGround(Real z) View::setHeightAboveGround(z); m_doingMoveCameraOnWaypointPath = false; + m_CameraArrivedAtWaypointOnPathFlag = false; m_doingRotateCamera = false; m_doingPitchCamera = false; m_doingZoomCamera = false; @@ -1797,6 +1969,7 @@ void W3DView::setZoom(Real z) View::setZoom(z); m_doingMoveCameraOnWaypointPath = false; + m_CameraArrivedAtWaypointOnPathFlag = false; m_doingRotateCamera = false; m_doingPitchCamera = false; m_doingZoomCamera = false; @@ -1818,13 +1991,13 @@ void W3DView::setZoomToDefault( void ) Real desiredHeight = (terrainHeightMax + m_maxHeightAboveGround); Real desiredZoom = desiredHeight / m_cameraOffset.z; - m_mcwpInfo.cameraZoom[2] = desiredZoom;//m_maxZoom; - DEBUG_LOG(("W3DView::setZoomToDefault() Current zoom: %g Desired zoom: %g", m_zoom, desiredZoom)); + //DEBUG_LOG(("W3DView::setZoomToDefault() Current zoom: %g Desired zoom: %g", m_zoom, desiredZoom)); m_zoom = desiredZoom; m_heightAboveGround = m_maxHeightAboveGround; m_doingMoveCameraOnWaypointPath = false; + m_CameraArrivedAtWaypointOnPathFlag = false; m_doingRotateCamera = false; m_doingPitchCamera = false; m_doingZoomCamera = false; @@ -2200,6 +2373,7 @@ void W3DView::lookAt( const Coord3D *o ) setPosition(&pos); m_doingRotateCamera = false; m_doingMoveCameraOnWaypointPath = false; + m_CameraArrivedAtWaypointOnPathFlag = false; m_doingScriptedCameraLock = false; setCameraTransform(); @@ -2228,7 +2402,7 @@ void W3DView::initHeightForMap( void ) /** Move camera to in an interesting fashion. Sets up parameters that get * evaluated in draw(). */ //------------------------------------------------------------------------------------------------- -void W3DView::moveCameraTo(const Coord3D *o, Int milliseconds, Int shutter, Bool orient) +void W3DView::moveCameraTo(const Coord3D *o, Int milliseconds, Int shutter, Bool orient, Real easeIn, Real easeOut) { m_mcwpInfo.waypoints[0] = *getPosition(); m_mcwpInfo.cameraAngle[0] = getAngle(); @@ -2244,6 +2418,7 @@ void W3DView::moveCameraTo(const Coord3D *o, Int milliseconds, Int shutter, Bool if (milliseconds<1) milliseconds = 1; m_mcwpInfo.totalTimeMilliseconds = milliseconds; m_mcwpInfo.shutter = 1; + m_mcwpInfo.ease.setEaseTimes(easeIn/milliseconds, easeOut/milliseconds); m_mcwpInfo.curSegment = 1; m_mcwpInfo.curSegDistance = 0; m_mcwpInfo.totalDistance = 0; @@ -2253,13 +2428,14 @@ void W3DView::moveCameraTo(const Coord3D *o, Int milliseconds, Int shutter, Bool // do it instantly. moveAlongWaypointPath(1); m_doingMoveCameraOnWaypointPath = true; + m_CameraArrivedAtWaypointOnPathFlag = false; } } //------------------------------------------------------------------------------------------------- /** Rotate the camera */ //------------------------------------------------------------------------------------------------- -void W3DView::rotateCamera(Real rotations, Int milliseconds) +void W3DView::rotateCamera(Real rotations, Int milliseconds, Real easeIn, Real easeOut) { m_rcInfo.numHoldFrames = 0; m_rcInfo.trackObject = FALSE; @@ -2271,17 +2447,20 @@ void W3DView::rotateCamera(Real rotations, Int milliseconds) } m_rcInfo.curFrame = 0; m_doingRotateCamera = true; - m_rcInfo.angle = 2*PI*rotations/m_rcInfo.numFrames; + m_rcInfo.angle.startAngle = m_angle; + m_rcInfo.angle.endAngle = m_angle + 2*PI*rotations; m_rcInfo.startTimeMultiplier = m_timeMultiplier; m_rcInfo.endTimeMultiplier = m_timeMultiplier; + m_rcInfo.ease.setEaseTimes(easeIn/milliseconds, easeOut/milliseconds); m_doingMoveCameraOnWaypointPath = false; + m_CameraArrivedAtWaypointOnPathFlag = false; } //------------------------------------------------------------------------------------------------- /** Rotate the camera to follow a unit */ //------------------------------------------------------------------------------------------------- -void W3DView::rotateCameraTowardObject(ObjectID id, Int milliseconds, Int holdMilliseconds) +void W3DView::rotateCameraTowardObject(ObjectID id, Int milliseconds, Int holdMilliseconds, Real easeIn, Real easeOut) { m_rcInfo.trackObject = TRUE; if (holdMilliseconds<1) holdMilliseconds = 0; @@ -2297,53 +2476,69 @@ void W3DView::rotateCameraTowardObject(ObjectID id, Int milliseconds, Int holdMi } m_rcInfo.curFrame = 0; m_doingRotateCamera = true; - m_rcInfo.angle = m_angle; // not used here - m_rcInfo.targetObjectID = id; + m_rcInfo.target.targetObjectID = id; m_rcInfo.startTimeMultiplier = m_timeMultiplier; m_rcInfo.endTimeMultiplier = m_timeMultiplier; + m_rcInfo.ease.setEaseTimes(easeIn/milliseconds, easeOut/milliseconds); m_doingMoveCameraOnWaypointPath = false; + m_CameraArrivedAtWaypointOnPathFlag = false; } //------------------------------------------------------------------------------------------------- /** Rotate camera to face a location */ //------------------------------------------------------------------------------------------------- -void W3DView::rotateCameraTowardPosition(const Coord3D *pLoc, Int milliseconds) +void W3DView::rotateCameraTowardPosition(const Coord3D *pLoc, Int milliseconds, Real easeIn, Real easeOut, Bool reverseRotation) { m_rcInfo.numHoldFrames = 0; m_rcInfo.trackObject = FALSE; - if (milliseconds<1) milliseconds = 1; m_rcInfo.numFrames = milliseconds/TheW3DFrameLengthInMsec; if (m_rcInfo.numFrames < 1) { m_rcInfo.numFrames = 1; } Coord3D curPos = *getPosition(); - Vector3 dir(pLoc->x-curPos.x, pLoc->y-curPos.y, 0); - if (dir.Length()<0.1) return; - dir.Normalize(); - Real angle = WWMath::Acos(dir.X); - if (dir.Y<0) { + Vector2 dir(pLoc->x-curPos.x, pLoc->y-curPos.y); + const Real dirLength = dir.Length(); + if (dirLength<0.1f) return; + Real angle = WWMath::Acos(dir.X/dirLength); + if (dir.Y<0.0f) { angle = -angle; } // Default camera is rotated 90 degrees, so match. angle -= PI/2; normAngle(angle); + if (reverseRotation) { + if (m_angle < angle) { + angle -= 2.0f*WWMATH_PI; + } else { + angle += 2.0f*WWMATH_PI; + } + } + m_rcInfo.curFrame = 0; m_doingRotateCamera = true; - m_rcInfo.angle = angle/m_rcInfo.numFrames; // not used here - m_rcInfo.targetObjectID = INVALID_ID; + m_rcInfo.angle.startAngle = m_angle; + // TheSuperHackers @todo Investigate whether the non Generals code is correct for Zero Hour. + // It certainly is incorrect for Generals: Seen in GLA mission 1 opening cut scene. +#if RTS_GENERALS + m_rcInfo.angle.endAngle = m_angle + angle; +#else + m_rcInfo.angle.endAngle = angle; +#endif m_rcInfo.startTimeMultiplier = m_timeMultiplier; m_rcInfo.endTimeMultiplier = m_timeMultiplier; + m_rcInfo.ease.setEaseTimes(easeIn/milliseconds, easeOut/milliseconds); m_doingMoveCameraOnWaypointPath = false; + m_CameraArrivedAtWaypointOnPathFlag = false; } //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- -void W3DView::zoomCamera( Real finalZoom, Int milliseconds ) +void W3DView::zoomCamera( Real finalZoom, Int milliseconds, Real easeIn, Real easeOut ) { if (milliseconds<1) milliseconds = 1; m_zcInfo.numFrames = milliseconds/TheW3DFrameLengthInMsec; @@ -2354,11 +2549,12 @@ void W3DView::zoomCamera( Real finalZoom, Int milliseconds ) m_doingZoomCamera = TRUE; m_zcInfo.startZoom = m_zoom; m_zcInfo.endZoom = finalZoom; + m_zcInfo.ease.setEaseTimes(easeIn/milliseconds, easeOut/milliseconds); } //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- -void W3DView::pitchCamera( Real finalPitch, Int milliseconds ) +void W3DView::pitchCamera( Real finalPitch, Int milliseconds, Real easeIn, Real easeOut ) { if (milliseconds<1) milliseconds = 1; m_pcInfo.numFrames = milliseconds/TheW3DFrameLengthInMsec; @@ -2369,12 +2565,13 @@ void W3DView::pitchCamera( Real finalPitch, Int milliseconds ) m_doingPitchCamera = TRUE; m_pcInfo.startPitch = m_FXPitch; m_pcInfo.endPitch = finalPitch; + m_pcInfo.ease.setEaseTimes(easeIn/milliseconds, easeOut/milliseconds); } //------------------------------------------------------------------------------------------------- /** Sets the final zoom for a camera movement. */ //------------------------------------------------------------------------------------------------- -void W3DView::cameraModFinalZoom( Real finalZoom ) +void W3DView::cameraModFinalZoom( Real finalZoom, Real easeIn, Real easeOut ) { if (m_doingRotateCamera) @@ -2383,7 +2580,8 @@ void W3DView::cameraModFinalZoom( Real finalZoom ) Real maxHeight = (terrainHeightMax + m_maxHeightAboveGround); Real maxZoom = maxHeight / m_cameraOffset.z; - zoomCamera( finalZoom*maxZoom, (m_rcInfo.numFrames + m_rcInfo.numHoldFrames - m_rcInfo.curFrame)*TheW3DFrameLengthInMsec ); + Real time = (m_rcInfo.numFrames + m_rcInfo.numHoldFrames - m_rcInfo.curFrame)*TheW3DFrameLengthInMsec; + zoomCamera( finalZoom*maxZoom, time, time*easeIn, time*easeOut ); } if (m_doingMoveCameraOnWaypointPath) { @@ -2392,7 +2590,8 @@ void W3DView::cameraModFinalZoom( Real finalZoom ) Real maxHeight = (terrainHeightMax + m_maxHeightAboveGround); Real maxZoom = maxHeight / m_cameraOffset.z; - zoomCamera( finalZoom*maxZoom, m_mcwpInfo.totalTimeMilliseconds - m_mcwpInfo.elapsedTimeMilliseconds ); + Real time = m_mcwpInfo.totalTimeMilliseconds - m_mcwpInfo.elapsedTimeMilliseconds; + zoomCamera( finalZoom*maxZoom, time, time*easeIn, time*easeOut ); } } @@ -2402,8 +2601,11 @@ void W3DView::cameraModFinalZoom( Real finalZoom ) void W3DView::cameraModFreezeAngle(void) { if (m_doingRotateCamera) { - m_rcInfo.angle = 0; // Silly, but consistent. - m_rcInfo.targetObjectID = INVALID_ID; + if (m_rcInfo.trackObject) { + m_rcInfo.target.targetObjectID = INVALID_ID; + } else { + m_rcInfo.angle.startAngle = m_rcInfo.angle.endAngle = m_angle; // Silly, but consistent. + } } if (m_doingMoveCameraOnWaypointPath) { Int i; @@ -2445,11 +2647,11 @@ void W3DView::cameraModLookToward(Coord3D *pLoc) result.x += (1-factor)*factor*(mid.x-end.x + mid.x-start.x); result.y += (1-factor)*factor*(mid.y-end.y + mid.y-start.y); result.z = 0; - Vector3 dir(pLoc->x-result.x, pLoc->y-result.y, 0); - if (dir.Length()<0.1) continue; - dir.Normalize(); - Real angle = WWMath::Acos(dir.X); - if (dir.Y<0) { + Vector2 dir(pLoc->x-result.x, pLoc->y-result.y); + const Real dirLength = dir.Length(); + if (dirLength<0.1f) continue; + Real angle = WWMath::Acos(dir.X/dirLength); + if (dir.Y<0.0f) { angle = -angle; } // Default camera is rotated 90 degrees, so match. @@ -2461,6 +2663,7 @@ void W3DView::cameraModLookToward(Coord3D *pLoc) // do it instantly. moveAlongWaypointPath(1); m_doingMoveCameraOnWaypointPath = true; + m_CameraArrivedAtWaypointOnPathFlag = false; } } } @@ -2521,11 +2724,11 @@ void W3DView::cameraModFinalLookToward(Coord3D *pLoc) result.x += (1-factor)*factor*(mid.x-end.x + mid.x-start.x); result.y += (1-factor)*factor*(mid.y-end.y + mid.y-start.y); result.z = 0; - Vector3 dir(pLoc->x-result.x, pLoc->y-result.y, 0); - if (dir.Length()<0.1) continue; - dir.Normalize(); - Real angle = WWMath::Acos(dir.X); - if (dir.Y<0) { + Vector2 dir(pLoc->x-result.x, pLoc->y-result.y); + const Real dirLength = dir.Length(); + if (dirLength<0.1f) continue; + Real angle = WWMath::Acos(dir.X/dirLength); + if (dir.Y<0.0f) { angle = -angle; } // Default camera is rotated 90 degrees, so match. @@ -2582,43 +2785,40 @@ void W3DView::cameraModRollingAverage(Int framesToAverage) // ------------------------------------------------------------------------------------------------ /** Sets the final pitch for a camera movement. */ // ------------------------------------------------------------------------------------------------ -void W3DView::cameraModFinalPitch(Real finalPitch) { +void W3DView::cameraModFinalPitch(Real finalPitch, Real easeIn, Real easeOut) { if (m_doingRotateCamera) { - pitchCamera( finalPitch, ((m_rcInfo.numFrames + m_rcInfo.numHoldFrames) - m_rcInfo.curFrame) * TheW3DFrameLengthInMsec ); + Real time = (m_rcInfo.numFrames + m_rcInfo.numHoldFrames - m_rcInfo.curFrame)*TheW3DFrameLengthInMsec; + pitchCamera( finalPitch, time, time*easeIn, time*easeOut ); } if (m_doingMoveCameraOnWaypointPath) { - pitchCamera( finalPitch, m_mcwpInfo.totalTimeMilliseconds - m_mcwpInfo.elapsedTimeMilliseconds ); + Real time = m_mcwpInfo.totalTimeMilliseconds - m_mcwpInfo.elapsedTimeMilliseconds; + pitchCamera( finalPitch, time, time*easeIn, time*easeOut ); } } // ------------------------------------------------------------------------------------------------ /** Move camera to a waypoint, resetting the default angle, pitch & zoom along the way.. */ // ------------------------------------------------------------------------------------------------ -void W3DView::resetCamera(const Coord3D *location, Int milliseconds) +void W3DView::resetCamera(const Coord3D *location, Int milliseconds, Real easeIn, Real easeOut) { - moveCameraTo(location, milliseconds, 0, false); + moveCameraTo(location, milliseconds, 0, false, easeIn, easeOut); m_mcwpInfo.cameraAngle[2] = 0.0; // default angle. + // m_mcwpInfo.cameraAngle[2] = m_defaultAngle; m_angle = m_mcwpInfo.cameraAngle[0]; - m_mcwpInfo.cameraFXPitch[2] = 1.0; // terrain height + desired height offset == cameraOffset * actual zoom // find best approximation of max terrain height we can see //Real terrainHeightMax = getHeightAroundPos(m_pos.x, m_pos.y); Real terrainHeightMax = getHeightAroundPos(location->x, location->y); - Real desiredHeight = (terrainHeightMax + m_maxHeightAboveGround); Real desiredZoom = desiredHeight / m_cameraOffset.z; - m_mcwpInfo.cameraZoom[2] = desiredZoom;//m_maxZoom; - - //Real terrainHeightMax = getHeightAroundPos(location->x, location->y); - //Real desiredHeight = (terrainHeightMax + m_maxHeightAboveGround); - //Real desiredZoom = desiredHeight / m_cameraOffset.z; - zoomCamera( desiredZoom, milliseconds ); // this isn't right... or is it? + zoomCamera( desiredZoom, milliseconds, easeIn, easeOut ); // this isn't right... or is it? - pitchCamera( 1.0, milliseconds ); - DEBUG_LOG(("W3DView::resetCamera() Current zoom: %g Desired zoom: %g Current pitch: %g Desired pitch: %g", - m_zoom, desiredZoom, m_pitchAngle, m_defaultPitchAngle)); + pitchCamera( 1.0, milliseconds, easeIn, easeOut ); + // pitchCamera( m_defaultPitchAngle, milliseconds, easeIn, easeOut ); + //DEBUG_LOG(("W3DView::resetCamera() Current zoom: %g Desired zoom: %g Current pitch: %g Desired pitch: %g", + // m_zoom, desiredZoom, m_pitchAngle, m_defaultPitchAngle)); } // ------------------------------------------------------------------------------------------------ @@ -2639,11 +2839,22 @@ Bool W3DView::isCameraMovementFinished(void) return !m_doingMoveCameraOnWaypointPath && !m_doingRotateCamera && !m_doingPitchCamera && !m_doingZoomCamera; } + +Bool W3DView::isCameraMovementAtWaypointAlongPath(void) +{ + // WWDEBUG_SAY((( "MBL: Polling W3DView::isCameraMovementAtWaypointAlongPath" ))); + + Bool return_value = m_CameraArrivedAtWaypointOnPathFlag; + #pragma message( "MBL: Clearing variable after polling - for scripting - see Adam.\n" ) + m_CameraArrivedAtWaypointOnPathFlag = false; + return( return_value ); +} + // ------------------------------------------------------------------------------------------------ /** Move camera along a waypoint path in an interesting fashion. Sets up parameters that get * evaluated in draw(). */ // ------------------------------------------------------------------------------------------------ -void W3DView::moveCameraAlongWaypointPath(Waypoint *pWay, Int milliseconds, Int shutter, Bool orient) +void W3DView::moveCameraAlongWaypointPath(Waypoint *pWay, Int milliseconds, Int shutter, Bool orient, Real easeIn, Real easeOut) { const Real MIN_DELTA = MAP_XY_FACTOR; @@ -2656,6 +2867,7 @@ void W3DView::moveCameraAlongWaypointPath(Waypoint *pWay, Int milliseconds, Int m_mcwpInfo.totalTimeMilliseconds = milliseconds; m_mcwpInfo.shutter = shutter/TheW3DFrameLengthInMsec; if (m_mcwpInfo.shutter<1) m_mcwpInfo.shutter = 1; + m_mcwpInfo.ease.setEaseTimes(easeIn/milliseconds, easeOut/milliseconds); while (pWay && m_mcwpInfo.numWaypoints 1; i--) { m_mcwpInfo.cameraAngle[i] = (m_mcwpInfo.cameraAngle[i] + m_mcwpInfo.cameraAngle[i-1]) / 2; } - m_mcwpInfo.waySegLength[m_mcwpInfo.numWaypoints+1] = m_mcwpInfo.waySegLength[m_mcwpInfo.numWaypoints+1]; + m_mcwpInfo.waySegLength[m_mcwpInfo.numWaypoints+1] = m_mcwpInfo.waySegLength[m_mcwpInfo.numWaypoints]; + + // Prevent a possible divide by zero. if (m_mcwpInfo.totalDistance<1.0) { m_mcwpInfo.waySegLength[m_mcwpInfo.numWaypoints-1] += 1.0-m_mcwpInfo.totalDistance; m_mcwpInfo.totalDistance = 1.0; } + Real curDistance = 0; Coord3D finalPos = m_mcwpInfo.waypoints[m_mcwpInfo.numWaypoints]; Real newGround = TheTerrainLogic->getGroundHeight(finalPos.x, finalPos.y); for (i=0; i<=m_mcwpInfo.numWaypoints+1; i++) { Real factor2 = curDistance / m_mcwpInfo.totalDistance; Real factor1 = 1.0-factor2; - m_mcwpInfo.cameraFXPitch[i] = m_FXPitch; - m_mcwpInfo.cameraZoom[i] = m_zoom; m_mcwpInfo.timeMultiplier[i] = m_timeMultiplier; m_mcwpInfo.groundHeight[i] = m_groundLevel*factor1 + newGround*factor2; curDistance += m_mcwpInfo.waySegLength[i]; @@ -2748,6 +2960,7 @@ void W3DView::setupWaypointPath(Bool orient) m_mcwpInfo.waypoints[0].y -= cur.y-prev.y; m_doingMoveCameraOnWaypointPath = m_mcwpInfo.numWaypoints>1; + m_CameraArrivedAtWaypointOnPathFlag = false; m_doingRotateCamera = false; m_mcwpInfo.elapsedTimeMilliseconds = 0; @@ -2783,79 +2996,62 @@ void W3DView::rotateCameraOneFrame(void) return; } - if (m_rcInfo.curFrame <= m_rcInfo.numFrames) + if (m_rcInfo.trackObject) { - // not just holding; do the camera adjustment - Real factor = ((Real)m_rcInfo.curFrame)/m_rcInfo.numFrames; - if (m_rcInfo.trackObject) + if (m_rcInfo.curFrame <= m_rcInfo.numFrames + m_rcInfo.numHoldFrames) { - const Object *obj = TheGameLogic->findObjectByID(m_rcInfo.targetObjectID); + const Object *obj = TheGameLogic->findObjectByID(m_rcInfo.target.targetObjectID); if (obj) { // object has not been destroyed - m_rcInfo.targetObjectPos = *obj->getPosition(); + m_rcInfo.target.targetObjectPos = *obj->getPosition(); } - Vector3 dir(m_rcInfo.targetObjectPos.x - m_pos.x, m_rcInfo.targetObjectPos.y - m_pos.y, 0); - if (dir.Length()>=0.1) + const Vector2 dir(m_rcInfo.target.targetObjectPos.x - m_pos.x, m_rcInfo.target.targetObjectPos.y - m_pos.y); + const Real dirLength = dir.Length(); + if (dirLength>=0.1f) { - dir.Normalize(); - Real angle = WWMath::Acos(dir.X); - if (dir.Y<0) { + Real angle = WWMath::Acos(dir.X/dirLength); + if (dir.Y<0.0f) { angle = -angle; } // Default camera is rotated 90 degrees, so match. angle -= PI/2; normAngle(angle); - factor = 1.0f / (m_rcInfo.numFrames - m_rcInfo.curFrame + 1); - Real angleDiff = (angle - m_angle); - normAngle(angleDiff); - angleDiff *= factor; - - m_angle += angleDiff; + if (m_rcInfo.curFrame <= m_rcInfo.numFrames) + { + Real factor = m_rcInfo.ease(((Real)m_rcInfo.curFrame)/m_rcInfo.numFrames); + Real angleDiff = angle - m_angle; + normAngle(angleDiff); + angleDiff *= factor; + m_angle += angleDiff; + normAngle(m_angle); + m_timeMultiplier = m_rcInfo.startTimeMultiplier + REAL_TO_INT_FLOOR(0.5 + (m_rcInfo.endTimeMultiplier-m_rcInfo.startTimeMultiplier)*factor); + } + else + { + m_angle = angle; + } } } - else - { - m_angle += m_rcInfo.angle; - } - //m_zoom = m_rcInfo.startZoom + (m_rcInfo.endZoom-m_rcInfo.startZoom)*factor; - //m_FXPitch = m_rcInfo.startPitch + (m_rcInfo.endPitch-m_rcInfo.startPitch)*factor; - normAngle(m_angle); - //DEBUG_LOG(("\tm_angle:%g", m_angle)); - m_timeMultiplier = m_rcInfo.startTimeMultiplier + REAL_TO_INT_FLOOR(0.5 + (m_rcInfo.endTimeMultiplier-m_rcInfo.startTimeMultiplier)*factor); } - else if (m_rcInfo.curFrame <= m_rcInfo.numFrames + m_rcInfo.numHoldFrames && m_rcInfo.trackObject) + else if (m_rcInfo.curFrame <= m_rcInfo.numFrames) { - const Object *obj = TheGameLogic->findObjectByID(m_rcInfo.targetObjectID); - if (obj) - { - // object has not been destroyed - m_rcInfo.targetObjectPos = *obj->getPosition(); - } - - Vector3 dir(m_rcInfo.targetObjectPos.x - m_pos.x, m_rcInfo.targetObjectPos.y - m_pos.y, 0); - if (dir.Length()>=0.1) - { - dir.Normalize(); - Real angle = WWMath::Acos(dir.X); - if (dir.Y<0) { - angle = -angle; - } - // Default camera is rotated 90 degrees, so match. - angle -= PI/2; - normAngle(angle); - m_angle = angle; - } + Real factor = m_rcInfo.ease(((Real)m_rcInfo.curFrame)/m_rcInfo.numFrames); + m_angle = WWMath::Lerp(m_rcInfo.angle.startAngle, m_rcInfo.angle.endAngle, factor); + normAngle(m_angle); + m_timeMultiplier = m_rcInfo.startTimeMultiplier + REAL_TO_INT_FLOOR(0.5 + (m_rcInfo.endTimeMultiplier-m_rcInfo.startTimeMultiplier)*factor); } if (m_rcInfo.curFrame >= m_rcInfo.numFrames + m_rcInfo.numHoldFrames) { m_doingRotateCamera = false; m_freezeTimeForCameraMovement = false; - //m_zoom = m_rcInfo.endZoom; - //m_FXPitch = m_rcInfo.endPitch; + if (! m_rcInfo.trackObject) + { + m_angle = m_rcInfo.angle.endAngle; + } } } @@ -2873,8 +3069,8 @@ void W3DView::zoomCameraOneFrame(void) if (m_zcInfo.curFrame <= m_zcInfo.numFrames) { // not just holding; do the camera adjustment - Real factor = ((Real)m_zcInfo.curFrame)/m_zcInfo.numFrames; - m_zoom = m_zcInfo.startZoom + (m_zcInfo.endZoom-m_zcInfo.startZoom)*factor; + Real factor = m_zcInfo.ease(((Real)m_zcInfo.curFrame)/m_zcInfo.numFrames); + m_zoom = WWMath::Lerp(m_zcInfo.startZoom, m_zcInfo.endZoom, factor); } if (m_zcInfo.curFrame >= m_zcInfo.numFrames) { @@ -2899,8 +3095,8 @@ void W3DView::pitchCameraOneFrame(void) if (m_pcInfo.curFrame <= m_pcInfo.numFrames) { // not just holding; do the camera adjustment - Real factor = ((Real)m_pcInfo.curFrame)/m_pcInfo.numFrames; - m_FXPitch = m_pcInfo.startPitch + (m_pcInfo.endPitch-m_pcInfo.startPitch)*factor; + Real factor = m_pcInfo.ease(((Real)m_pcInfo.curFrame)/m_pcInfo.numFrames); + m_FXPitch = WWMath::Lerp(m_pcInfo.startPitch, m_pcInfo.endPitch, factor); } if (m_pcInfo.curFrame >= m_pcInfo.numFrames) { @@ -2923,10 +3119,10 @@ void W3DView::moveAlongWaypointPath(Real milliseconds) } if (m_mcwpInfo.elapsedTimeMilliseconds>m_mcwpInfo.totalTimeMilliseconds) { m_doingMoveCameraOnWaypointPath = false; + m_CameraArrivedAtWaypointOnPathFlag = false; + m_freezeTimeForCameraMovement = false; m_angle = m_mcwpInfo.cameraAngle[m_mcwpInfo.numWaypoints]; - //m_zoom = m_mcwpInfo.cameraZoom[m_mcwpInfo.numWaypoints]; - //m_FXPitch = m_mcwpInfo.cameraFXPitch[m_mcwpInfo.numWaypoints]; m_groundLevel = m_mcwpInfo.groundHeight[m_mcwpInfo.numWaypoints]; /////////////////////m_cameraOffset.z = m_groundLevel+TheGlobalData->m_cameraHeight; @@ -2944,11 +3140,25 @@ void W3DView::moveAlongWaypointPath(Real milliseconds) m_cameraConstraint.hi.y = maxf(m_cameraConstraint.hi.y, pos.y); return; } - Int deltaTime = milliseconds; - Real distance = m_mcwpInfo.totalDistance * deltaTime / m_mcwpInfo.totalTimeMilliseconds; - m_mcwpInfo.curSegDistance += distance; - while (m_mcwpInfo.curSegDistance > m_mcwpInfo.waySegLength[m_mcwpInfo.curSegment]) { + const Real totalTime = m_mcwpInfo.totalTimeMilliseconds; + const Real deltaTime = m_mcwpInfo.ease(m_mcwpInfo.elapsedTimeMilliseconds/totalTime) - + m_mcwpInfo.ease((m_mcwpInfo.elapsedTimeMilliseconds - milliseconds)/totalTime); + m_mcwpInfo.curSegDistance += deltaTime*m_mcwpInfo.totalDistance; + // TheSuperHackers @todo Investigate which one is really correct. + // The non Generals condition causes camera bug in Generals Shell Map. +#if RTS_GENERALS + while (m_mcwpInfo.curSegDistance > m_mcwpInfo.waySegLength[m_mcwpInfo.curSegment]) +#else + while (m_mcwpInfo.curSegDistance >= m_mcwpInfo.waySegLength[m_mcwpInfo.curSegment]) +#endif + { + if ( m_doingMoveCameraOnWaypointPath ) + { + //WWDEBUG_SAY(( "MBL TEST: Camera waypoint along path reached!" )); + m_CameraArrivedAtWaypointOnPathFlag = true; + } + m_mcwpInfo.curSegDistance -= m_mcwpInfo.waySegLength[m_mcwpInfo.curSegment]; m_mcwpInfo.curSegment++; if (m_mcwpInfo.curSegment >= m_mcwpInfo.numWaypoints) { @@ -2966,7 +3176,6 @@ void W3DView::moveAlongWaypointPath(Real milliseconds) if (m_mcwpInfo.curSegment == m_mcwpInfo.numWaypoints-1) { avgFactor = avgFactor + (1.0-avgFactor)*factor; } - Real angle = getAngle(); Real factor1; Real factor2; factor1 = 1.0-factor; @@ -2976,7 +3185,7 @@ void W3DView::moveAlongWaypointPath(Real milliseconds) Real angle2 = m_mcwpInfo.cameraAngle[m_mcwpInfo.curSegment+1]; if (angle2-angle1 > PI) angle1 += 2*PI; if (angle2-angle1 < -PI) angle1 -= 2*PI; - angle = angle1 * (factor1) + angle2 * (factor2); + Real angle = angle1 * (factor1) + angle2 * (factor2); normAngle(angle); Real deltaAngle = angle-m_angle; @@ -2987,16 +3196,6 @@ void W3DView::moveAlongWaypointPath(Real milliseconds) m_angle += avgFactor*(deltaAngle); normAngle(m_angle); - /* - Real pitchFX = m_mcwpInfo.cameraFXPitch[m_mcwpInfo.curSegment]*factor1 + - m_mcwpInfo.cameraFXPitch[m_mcwpInfo.curSegment+1]*factor2; - m_FXPitch += avgFactor*(pitchFX-m_FXPitch); - - Real cameraZoom = m_mcwpInfo.cameraZoom[m_mcwpInfo.curSegment]*factor1 + - m_mcwpInfo.cameraZoom[m_mcwpInfo.curSegment+1]*factor2; - m_zoom += avgFactor*(cameraZoom-m_zoom); - */ - Real timeMultiplier = m_mcwpInfo.timeMultiplier[m_mcwpInfo.curSegment]*factor1 + m_mcwpInfo.timeMultiplier[m_mcwpInfo.curSegment+1]*factor2; m_timeMultiplier = REAL_TO_INT_FLOOR(0.5 + timeMultiplier); @@ -3139,3 +3338,45 @@ void W3DView::screenToWorldAtZ( const ICoord2D *s, Coord3D *w, Real z ) } +void W3DView::cameraEnableSlaveMode(const AsciiString & objectName, const AsciiString & boneName) +{ + m_isCameraSlaved = true; + m_cameraSlaveObjectName = objectName; + m_cameraSlaveObjectBoneName = boneName; +} + +void W3DView::cameraDisableSlaveMode(void) +{ + m_isCameraSlaved = false; +} + +void W3DView::cameraEnableRealZoomMode(void) //WST added 10/18/2002 +{ + m_useRealZoomCam = true; + m_FXPitch = 1.0f; //Reset to default + //m_zoom = 1.0f; + updateView(); +} + +void W3DView::cameraDisableRealZoomMode(void) //WST added 10/18/2002 +{ + m_useRealZoomCam = false; + m_FXPitch = 1.0f; //Reset to default + //m_zoom = 1.0f; + m_FOV = 50.0f * PI/180.0f; + setCameraTransform(); + updateView(); +} + +void W3DView::Add_Camera_Shake (const Coord3D & position,float radius,float duration,float power) //WST added 11/13/02 +{ + Vector3 vpos; + + vpos.X = position.x; + vpos.Y = position.y; + vpos.Z = position.z; + + + CameraShakerSystem.Add_Camera_Shake(vpos,radius,duration,power); +} + diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Display.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Display.h index 3f3a783946..7a100795c1 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/Display.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Display.h @@ -29,11 +29,9 @@ #pragma once #include "Common/SubsystemInterface.h" -#include "View.h" #include "GameClient/Color.h" #include "GameClient/GameFont.h" - -class View; +#include "GameClient/View.h" struct ShroudLevel { diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/View.h b/GeneralsMD/Code/GameEngine/Include/GameClient/View.h index 1e0f72fbae..f61a1db60d 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/View.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/View.h @@ -135,13 +135,13 @@ class View : public Snapshot virtual void initHeightForMap( void ) {}; ///< Init the camera height for the map at the current position. virtual void scrollBy( Coord2D *delta ); ///< Shift the view by the given delta - virtual void moveCameraTo(const Coord3D *o, Int frames, Int shutter, Bool orient, Real easeIn, Real easeOut) { lookAt( o ); } - virtual void moveCameraAlongWaypointPath(Waypoint *way, Int frames, Int shutter, Bool orient, Real easeIn, Real easeOut) { } + virtual void moveCameraTo(const Coord3D *o, Int frames, Int shutter, Bool orient, Real easeIn=0.0f, Real easeOut=0.0f) { lookAt( o ); } + virtual void moveCameraAlongWaypointPath(Waypoint *way, Int frames, Int shutter, Bool orient, Real easeIn=0.0f, Real easeOut=0.0f) { } virtual Bool isCameraMovementFinished( void ) { return TRUE; } - virtual void cameraModFinalZoom(Real finalZoom, Real easeIn, Real easeOut){}; ///< Final zoom for current camera movement. + virtual void cameraModFinalZoom(Real finalZoom, Real easeIn=0.0f, Real easeOut=0.0f){}; ///< Final zoom for current camera movement. virtual void cameraModRollingAverage(Int framesToAverage){}; ///< Number of frames to average movement for current camera movement. virtual void cameraModFinalTimeMultiplier(Int finalMultiplier){}; ///< Final time multiplier for current camera movement. - virtual void cameraModFinalPitch(Real finalPitch, Real easeIn, Real easeOut){}; ///< Final pitch for current camera movement. + virtual void cameraModFinalPitch(Real finalPitch, Real easeIn=0.0f, Real easeOut=0.0f){}; ///< Final pitch for current camera movement. virtual void cameraModFreezeTime(void){ } ///< Freezes time during the next camera movement. virtual void cameraModFreezeAngle(void){ } ///< Freezes time during the next camera movement. virtual void cameraModLookToward(Coord3D *pLoc){} ///< Sets a look at point during camera movement. @@ -161,16 +161,16 @@ class View : public Snapshot virtual void setFadeParameters(Int fadeFrames, Int direction) { }; virtual void set3DWireFrameMode(Bool enable) { }; - virtual void resetCamera(const Coord3D *location, Int frames, Real easeIn, Real easeOut) {}; ///< Move camera to location, and reset to default angle & zoom. - virtual void rotateCamera(Real rotations, Int frames, Real easeIn, Real easeOut) {}; ///< Rotate camera about current viewpoint. - virtual void rotateCameraTowardObject(ObjectID id, Int milliseconds, Int holdMilliseconds, Real easeIn, Real easeOut) {}; ///< Rotate camera to face an object, and hold on it - virtual void rotateCameraTowardPosition(const Coord3D *pLoc, Int milliseconds, Real easeIn, Real easeOut, Bool reverseRotation) {}; ///< Rotate camera to face a location. + virtual void resetCamera(const Coord3D *location, Int frames, Real easeIn=0.0f, Real easeOut=0.0f) {}; ///< Move camera to location, and reset to default angle & zoom. + virtual void rotateCamera(Real rotations, Int frames, Real easeIn=0.0f, Real easeOut=0.0f) {}; ///< Rotate camera about current viewpoint. + virtual void rotateCameraTowardObject(ObjectID id, Int milliseconds, Int holdMilliseconds, Real easeIn=0.0f, Real easeOut=0.0f) {}; ///< Rotate camera to face an object, and hold on it + virtual void rotateCameraTowardPosition(const Coord3D *pLoc, Int milliseconds, Real easeIn=0.0f, Real easeOut=0.0f, Bool reverseRotation=FALSE) {}; ///< Rotate camera to face a location. virtual Bool isTimeFrozen(void){ return false;} ///< Freezes time during the next camera movement. virtual Int getTimeMultiplier(void) {return 1;}; ///< Get the time multiplier. virtual void setTimeMultiplier(Int multiple) {}; ///< Set the time multiplier. virtual void setDefaultView(Real pitch, Real angle, Real maxHeight) {}; - virtual void zoomCamera( Real finalZoom, Int milliseconds, Real easeIn, Real easeOut ) {}; - virtual void pitchCamera( Real finalPitch, Int milliseconds, Real easeIn, Real easeOut ) {}; + virtual void zoomCamera( Real finalZoom, Int milliseconds, Real easeIn=0.0f, Real easeOut=0.0f ) {}; + virtual void pitchCamera( Real finalPitch, Int milliseconds, Real easeIn=0.0f, Real easeOut=0.0f ) {}; virtual void setAngle( Real angle ); ///< Rotate the view around the up axis to the given angle virtual Real getAngle( void ) { return m_angle; } diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp index 28ed342548..704f000e25 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp @@ -377,6 +377,14 @@ void W3DView::buildCameraTransform( Matrix3D *transform ) } else { + // TheSuperHackers @todo Investigate whether the non Generals code is correct for Zero Hour. + // It certainly is incorrect for Generals when m_FXPitch goes above 1: + // Seen in USA mission 1 second cut scene with SCUD Storm. +#if RTS_GENERALS + Real height = sourcePos.Z - targetPos.Z; + height *= m_FXPitch; + targetPos.Z = sourcePos.Z - height; +#else if (m_FXPitch <= 1.0f) { Real height = sourcePos.Z - targetPos.Z; @@ -388,6 +396,7 @@ void W3DView::buildCameraTransform( Matrix3D *transform ) sourcePos.X = targetPos.X + ((sourcePos.X - targetPos.X) / m_FXPitch); sourcePos.Y = targetPos.Y + ((sourcePos.Y - targetPos.Y) / m_FXPitch); } +#endif } //m_3DCamera->Set_View_Plane(DEG_TO_RADF(50.0f)); @@ -2512,7 +2521,13 @@ void W3DView::rotateCameraTowardPosition(const Coord3D *pLoc, Int milliseconds, m_rcInfo.curFrame = 0; m_doingRotateCamera = true; m_rcInfo.angle.startAngle = m_angle; + // TheSuperHackers @todo Investigate if the non Generals code is correct for Zero Hour. + // It certainly is incorrect for Generals: Seen in GLA mission 1 opening cut scene. +#if RTS_GENERALS + m_rcInfo.angle.endAngle = m_angle + angle; +#else m_rcInfo.angle.endAngle = angle; +#endif m_rcInfo.startTimeMultiplier = m_timeMultiplier; m_rcInfo.endTimeMultiplier = m_timeMultiplier; m_rcInfo.ease.setEaseTimes(easeIn/milliseconds, easeOut/milliseconds); @@ -3130,8 +3145,14 @@ void W3DView::moveAlongWaypointPath(Real milliseconds) const Real deltaTime = m_mcwpInfo.ease(m_mcwpInfo.elapsedTimeMilliseconds/totalTime) - m_mcwpInfo.ease((m_mcwpInfo.elapsedTimeMilliseconds - milliseconds)/totalTime); m_mcwpInfo.curSegDistance += deltaTime*m_mcwpInfo.totalDistance; - while (m_mcwpInfo.curSegDistance >= m_mcwpInfo.waySegLength[m_mcwpInfo.curSegment]) { - + // TheSuperHacker @todo Investigate which one is really correct. + // The non Generals condition causes camera bug in Generals Shell Map. +#if RTS_GENERALS + while (m_mcwpInfo.curSegDistance > m_mcwpInfo.waySegLength[m_mcwpInfo.curSegment]) +#else + while (m_mcwpInfo.curSegDistance >= m_mcwpInfo.waySegLength[m_mcwpInfo.curSegment]) +#endif + { if ( m_doingMoveCameraOnWaypointPath ) { //WWDEBUG_SAY(( "MBL TEST: Camera waypoint along path reached!" )); From fe4a589993471c880f37cadb8a37b6973bfca727 Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Thu, 27 Nov 2025 23:33:39 +0100 Subject: [PATCH 03/70] unify(view): Move View, W3DView to Core (#1904) --- Core/GameEngine/CMakeLists.txt | 4 +- .../GameEngine/Include/GameClient/View.h | 0 .../GameEngine/Source/GameClient/View.cpp | 0 Core/GameEngineDevice/CMakeLists.txt | 4 +- .../Include/W3DDevice/GameClient/W3DView.h | 0 .../Source/W3DDevice/GameClient/W3DView.cpp | 0 Generals/Code/GameEngine/CMakeLists.txt | 4 +- .../Code/GameEngine/Include/GameClient/View.h | 340 -- .../GameEngine/Source/GameClient/View.cpp | 287 -- Generals/Code/GameEngineDevice/CMakeLists.txt | 4 +- .../Include/W3DDevice/GameClient/W3DView.h | 302 -- .../Source/W3DDevice/GameClient/W3DView.cpp | 3382 ----------------- GeneralsMD/Code/GameEngine/CMakeLists.txt | 4 +- .../Code/GameEngineDevice/CMakeLists.txt | 4 +- scripts/cpp/unify_move_files.py | 5 + 15 files changed, 17 insertions(+), 4323 deletions(-) rename {GeneralsMD/Code => Core}/GameEngine/Include/GameClient/View.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Source/GameClient/View.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Include/W3DDevice/GameClient/W3DView.h (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp (100%) delete mode 100644 Generals/Code/GameEngine/Include/GameClient/View.h delete mode 100644 Generals/Code/GameEngine/Source/GameClient/View.cpp delete mode 100644 Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DView.h delete mode 100644 Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp diff --git a/Core/GameEngine/CMakeLists.txt b/Core/GameEngine/CMakeLists.txt index 30365854fd..1c2ca6c6b1 100644 --- a/Core/GameEngine/CMakeLists.txt +++ b/Core/GameEngine/CMakeLists.txt @@ -228,7 +228,7 @@ set(GAMEENGINE_SRC # Include/GameClient/TerrainRoads.h # Include/GameClient/TerrainVisual.h Include/GameClient/VideoPlayer.h -# Include/GameClient/View.h + Include/GameClient/View.h # Include/GameClient/Water.h # Include/GameClient/WindowLayout.h Include/GameClient/WindowVideoManager.h @@ -832,7 +832,7 @@ set(GAMEENGINE_SRC # Source/GameClient/Terrain/TerrainVisual.cpp Source/GameClient/VideoPlayer.cpp Source/GameClient/VideoStream.cpp -# Source/GameClient/View.cpp + Source/GameClient/View.cpp # Source/GameClient/Water.cpp # Source/GameLogic/AI/AI.cpp # Source/GameLogic/AI/AIDock.cpp diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/View.h b/Core/GameEngine/Include/GameClient/View.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/GameClient/View.h rename to Core/GameEngine/Include/GameClient/View.h diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/View.cpp b/Core/GameEngine/Source/GameClient/View.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/GameClient/View.cpp rename to Core/GameEngine/Source/GameClient/View.cpp diff --git a/Core/GameEngineDevice/CMakeLists.txt b/Core/GameEngineDevice/CMakeLists.txt index fa4a7fd713..c53c29220f 100644 --- a/Core/GameEngineDevice/CMakeLists.txt +++ b/Core/GameEngineDevice/CMakeLists.txt @@ -71,7 +71,7 @@ set(GAMEENGINEDEVICE_SRC # Include/W3DDevice/GameClient/W3DTerrainVisual.h # Include/W3DDevice/GameClient/W3DTreeBuffer.h Include/W3DDevice/GameClient/W3DVideoBuffer.h -# Include/W3DDevice/GameClient/W3DView.h + Include/W3DDevice/GameClient/W3DView.h # Include/W3DDevice/GameClient/W3DVolumetricShadow.h # Include/W3DDevice/GameClient/W3DWater.h # Include/W3DDevice/GameClient/W3DWaterTracks.h @@ -173,7 +173,7 @@ set(GAMEENGINEDEVICE_SRC # Source/W3DDevice/GameClient/W3DTerrainVisual.cpp # Source/W3DDevice/GameClient/W3DTreeBuffer.cpp Source/W3DDevice/GameClient/W3DVideoBuffer.cpp -# Source/W3DDevice/GameClient/W3DView.cpp + Source/W3DDevice/GameClient/W3DView.cpp # Source/W3DDevice/GameClient/W3dWaypointBuffer.cpp # Source/W3DDevice/GameClient/W3DWebBrowser.cpp # Source/W3DDevice/GameClient/Water/W3DWater.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DView.h b/Core/GameEngineDevice/Include/W3DDevice/GameClient/W3DView.h similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DView.h rename to Core/GameEngineDevice/Include/W3DDevice/GameClient/W3DView.h diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp rename to Core/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp diff --git a/Generals/Code/GameEngine/CMakeLists.txt b/Generals/Code/GameEngine/CMakeLists.txt index 01912ede6e..730e1ec6be 100644 --- a/Generals/Code/GameEngine/CMakeLists.txt +++ b/Generals/Code/GameEngine/CMakeLists.txt @@ -214,7 +214,7 @@ set(GAMEENGINE_SRC Include/GameClient/TerrainRoads.h Include/GameClient/TerrainVisual.h # Include/GameClient/VideoPlayer.h - Include/GameClient/View.h +# Include/GameClient/View.h Include/GameClient/Water.h Include/GameClient/WindowLayout.h # Include/GameClient/WindowVideoManager.h @@ -776,7 +776,7 @@ set(GAMEENGINE_SRC Source/GameClient/Terrain/TerrainRoads.cpp Source/GameClient/Terrain/TerrainVisual.cpp # Source/GameClient/VideoPlayer.cpp - Source/GameClient/View.cpp +# Source/GameClient/View.cpp Source/GameClient/Water.cpp Source/GameLogic/AI/AI.cpp Source/GameLogic/AI/AIDock.cpp diff --git a/Generals/Code/GameEngine/Include/GameClient/View.h b/Generals/Code/GameEngine/Include/GameClient/View.h deleted file mode 100644 index a175dcc908..0000000000 --- a/Generals/Code/GameEngine/Include/GameClient/View.h +++ /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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// View.h ///////////////////////////////////////////////////////////////////////////////////////// -// A "view", or window, into the World -// Author: Michael S. Booth, February 2001 -/////////////////////////////////////////////////////////////////////////////////////////////////// - -#pragma once - -// INCLUDES /////////////////////////////////////////////////////////////////////////////////////// -#include "Common/GameType.h" -#include "Common/Snapshot.h" -#include "Lib/BaseType.h" -#include "WW3D2/coltype.h" ///< we don't generally do this, but we need the W3D collision types - -#define DEFAULT_VIEW_WIDTH 640 -#define DEFAULT_VIEW_HEIGHT 480 -#define DEFAULT_VIEW_ORIGIN_X 0 -#define DEFAULT_VIEW_ORIGIN_Y 0 - -// FORWARD DECLARATIONS /////////////////////////////////////////////////////////////////////////// -class Drawable; -class ViewLocation; -class Thing; -class Waypoint; -class LookAtTranslator; -enum FilterTypes CPP_11(: Int); -enum FilterModes CPP_11(: Int); - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -enum PickType CPP_11(: Int) -{ - PICK_TYPE_TERRAIN = COLL_TYPE_0, - PICK_TYPE_SELECTABLE = COLL_TYPE_1, - PICK_TYPE_SHRUBBERY = COLL_TYPE_2, - PICK_TYPE_MINES = COLL_TYPE_3, // mines aren't normally selectable, but workers/dozers need to - PICK_TYPE_FORCEATTACKABLE = COLL_TYPE_4, - PICK_TYPE_ALL_DRAWABLES = (PICK_TYPE_SELECTABLE | PICK_TYPE_SHRUBBERY | PICK_TYPE_MINES | PICK_TYPE_FORCEATTACKABLE) -}; - -// ------------------------------------------------------------------------------------------------ -/** The implementation of common view functionality. */ -// ------------------------------------------------------------------------------------------------ -class View : public Snapshot -{ - -public: - - enum - { - ZoomHeightPerSecond = 10, - }; - - /// Add an impulse force to shake the camera - enum CameraShakeType - { - SHAKE_SUBTLE = 0, - SHAKE_NORMAL, - SHAKE_STRONG, - SHAKE_SEVERE, - SHAKE_CINE_EXTREME, //Added for cinematics ONLY - SHAKE_CINE_INSANE, //Added for cinematics ONLY - 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 - }; - -public: - - View( void ); - virtual ~View( void ); - - virtual void init( void ); - virtual void reset( void ); - virtual UnsignedInt getID( void ) { return m_id; } - - virtual void setZoomLimited( Bool limit ) { m_zoomLimited = limit; } ///< limit the zoom height - virtual Bool isZoomLimited( void ) { return m_zoomLimited; } ///< get status of zoom limit - - /// pick drawable given the screen pixel coords. If force attack, picks bridges as well. - virtual Drawable *pickDrawable( const ICoord2D *screen, Bool forceAttack, PickType pickType ) = 0; - - /// all drawables in the 2D screen region will call the 'callback' - virtual Int iterateDrawablesInRegion( IRegion2D *screenRegion, - Bool (*callback)( Drawable *draw, void *userData ), - void *userData ) = 0; - - /** project the 4 corners of this view into the world and return each point as a parameter, - the world points are at the requested Z */ - virtual void getScreenCornerWorldPointsAtZ( Coord3D *topLeft, Coord3D *topRight, - Coord3D *bottomLeft, Coord3D *bottomRight, - Real z ); - - virtual void setWidth( Int width ) { m_width = width; } - virtual Int getWidth( void ) { return m_width; } - virtual void setHeight( Int height ) { m_height = height; } - virtual Int getHeight( void ) { return m_height; } - virtual void setOrigin( Int x, Int y) { m_originX=x; m_originY=y;} ///< Sets location of top-left view corner on display - virtual void getOrigin( Int *x, Int *y) { *x=m_originX; *y=m_originY;} ///< Return location of top-left view corner on display - - virtual void lockViewUntilFrame(UnsignedInt frame); ///< Locks the current view until the given frame is reached. - virtual void forceRedraw() = 0; - - virtual void lookAt( const Coord3D *o ); ///< Center the view on the given coordinate - virtual void initHeightForMap( void ) {}; ///< Init the camera height for the map at the current position. - virtual void scrollBy( Coord2D *delta ); ///< Shift the view by the given delta - - virtual void moveCameraTo(const Coord3D *o, Int frames, Int shutter, Bool orient, Real easeIn=0.0f, Real easeOut=0.0f) { lookAt( o ); } - virtual void moveCameraAlongWaypointPath(Waypoint *way, Int frames, Int shutter, Bool orient, Real easeIn=0.0f, Real easeOut=0.0f) { } - virtual Bool isCameraMovementFinished( void ) { return TRUE; } - virtual void cameraModFinalZoom(Real finalZoom, Real easeIn=0.0f, Real easeOut=0.0f){}; ///< Final zoom for current camera movement. - virtual void cameraModRollingAverage(Int framesToAverage){}; ///< Number of frames to average movement for current camera movement. - virtual void cameraModFinalTimeMultiplier(Int finalMultiplier){}; ///< Final time multiplier for current camera movement. - virtual void cameraModFinalPitch(Real finalPitch, Real easeIn=0.0f, Real easeOut=0.0f){}; ///< Final pitch for current camera movement. - virtual void cameraModFreezeTime(void){ } ///< Freezes time during the next camera movement. - virtual void cameraModFreezeAngle(void){ } ///< Freezes time during the next camera movement. - virtual void cameraModLookToward(Coord3D *pLoc){} ///< Sets a look at point during camera movement. - virtual void cameraModFinalLookToward(Coord3D *pLoc){} ///< Sets a look at point during camera movement. - virtual void cameraModFinalMoveTo(Coord3D *pLoc){ }; ///< Sets a final move to. - - // (gth) C&C3 animation controled camera feature - virtual void cameraEnableSlaveMode(const AsciiString & thingtemplateName, const AsciiString & boneName) {} - virtual void cameraDisableSlaveMode(void) {} - virtual void Add_Camera_Shake(const Coord3D & position,float radius, float duration, float power) {} - virtual FilterModes getViewFilterMode(void) {return (FilterModes)0;} ///< Turns on viewport special effect (black & white mode) - virtual FilterTypes getViewFilterType(void) {return (FilterTypes)0;} ///< Turns on viewport special effect (black & white mode) - virtual Bool setViewFilterMode(FilterModes filterMode) { return FALSE; } ///< Turns on viewport special effect (black & white mode) - virtual void setViewFilterPos(const Coord3D *pos) { }; ///< Passes a position to the special effect filter. - virtual Bool setViewFilter( FilterTypes filter) { return FALSE;} ///< Turns on viewport special effect (black & white mode) - - virtual void setFadeParameters(Int fadeFrames, Int direction) { }; - virtual void set3DWireFrameMode(Bool enable) { }; - - virtual void resetCamera(const Coord3D *location, Int frames, Real easeIn=0.0f, Real easeOut=0.0f) {}; ///< Move camera to location, and reset to default angle & zoom. - virtual void rotateCamera(Real rotations, Int frames, Real easeIn=0.0f, Real easeOut=0.0f) {}; ///< Rotate camera about current viewpoint. - virtual void rotateCameraTowardObject(ObjectID id, Int milliseconds, Int holdMilliseconds, Real easeIn=0.0f, Real easeOut=0.0f) {}; ///< Rotate camera to face an object, and hold on it - virtual void rotateCameraTowardPosition(const Coord3D *pLoc, Int milliseconds, Real easeIn=0.0f, Real easeOut=0.0f, Bool reverseRotation=FALSE) {}; ///< Rotate camera to face a location. - virtual Bool isTimeFrozen(void){ return false;} ///< Freezes time during the next camera movement. - virtual Int getTimeMultiplier(void) {return 1;}; ///< Get the time multiplier. - virtual void setTimeMultiplier(Int multiple) {}; ///< Set the time multiplier. - virtual void setDefaultView(Real pitch, Real angle, Real maxHeight) {}; - virtual void zoomCamera( Real finalZoom, Int milliseconds, Real easeIn=0.0f, Real easeOut=0.0f ) {}; - virtual void pitchCamera( Real finalPitch, Int milliseconds, Real easeIn=0.0f, Real easeOut=0.0f ) {}; - - virtual void setAngle( Real angle ); ///< Rotate the view around the up axis to the given angle - virtual Real getAngle( void ) { return m_angle; } - virtual void setPitch( Real angle ); ///< Rotate the view around the horizontal axis to the given angle - virtual Real getPitch( void ) { return m_pitchAngle; } ///< Return current camera pitch - virtual void setAngleAndPitchToDefault( void ); ///< Set the view angle back to default - virtual void getPosition(Coord3D *pos) { *pos=m_pos;} ///< Returns position camera is looking at (z will be zero) - - virtual const Coord3D& get3DCameraPosition() const = 0; ///< Returns the actual camera position - - virtual Real getZoom() { return m_zoom; } - virtual void setZoom(Real z) { m_zoom = z; } - virtual Real getHeightAboveGround() { return m_heightAboveGround; } - virtual void setHeightAboveGround(Real z); - virtual void zoom( Real height ); ///< Zoom in/out, closer to the ground, limit to min, or farther away from the ground, limit to max - virtual void setZoomToDefault( void ) { m_zoom = 1.0f; } ///< Set zoom to default value - virtual void setOkToAdjustHeight( Bool val ) { m_okToAdjustHeight = val; } ///< Set this to adjust camera height - - // for debugging - virtual Real getTerrainHeightUnderCamera() { return m_terrainHeightUnderCamera; } - virtual void setTerrainHeightUnderCamera(Real z) { m_terrainHeightUnderCamera = z; } - virtual Real getCurrentHeightAboveGround() { return m_currentHeightAboveGround; } - virtual void setCurrentHeightAboveGround(Real z) { m_currentHeightAboveGround = z; } - - 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 - - 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 - - virtual void getLocation ( ViewLocation *location ); ///< write the view's current location in to the view location object - virtual void setLocation ( const ViewLocation *location ); ///< set the view's current location from to the view location object - - - virtual void drawView( void ) = 0; ///< Render the world visible in this view. - virtual void updateView(void) = 0; ///. -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// View.cpp /////////////////////////////////////////////////////////////////// -// A "view", or window, into the World -// Author: Michael S. Booth, February 2001 - -#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine - -#include "Common/GameEngine.h" -#include "Common/Xfer.h" -#include "GameClient/View.h" -#include "GameClient/Drawable.h" - -UnsignedInt View::m_idNext = 1; - -// the tactical view singleton -View *TheTacticalView = NULL; - - -View::View( void ) -{ - //Added By Sadullah Nader - //Initialization(s) inserted - m_viewLockedUntilFrame = 0u; - m_currentHeightAboveGround = 0.0f; - m_defaultAngle = 0.0f; - m_defaultPitchAngle = 0.0f; - m_heightAboveGround = 0.0f; - m_lockDist = 0.0f; - m_maxHeightAboveGround = 0.0f; - m_minHeightAboveGround = 0.0f; - m_next = NULL; - m_okToAdjustHeight = TRUE; - m_originX = 0; - m_originY = 0; - m_snapImmediate = FALSE; - m_terrainHeightUnderCamera = 0.0f; - m_zoom = 0.0f; - // - m_pos.x = 0; - m_pos.y = 0; - m_width = 0; - m_height = 0; - m_angle = 0.0f; - m_pitchAngle = 0.0f; - m_cameraLock = INVALID_ID; - m_cameraLockDrawable = NULL; - m_zoomLimited = TRUE; - - // create unique view ID - m_id = m_idNext++; - - // default field of view - m_FOV = 50.0f * PI/180.0f; - - m_mouseLocked = FALSE; - - m_guardBandBias.x = 0.0f; - m_guardBandBias.y = 0.0f; -} - -View::~View() -{ -} - -void View::init( void ) -{ - m_width = DEFAULT_VIEW_WIDTH; - m_height = DEFAULT_VIEW_HEIGHT; - m_originX = DEFAULT_VIEW_ORIGIN_X; - m_originY = DEFAULT_VIEW_ORIGIN_Y; - m_pos.x = 0; - m_pos.y = 0; - m_angle = 0.0f; - m_cameraLock = INVALID_ID; - m_cameraLockDrawable = NULL; - m_zoomLimited = TRUE; - - m_zoom = 1.0f; - m_maxHeightAboveGround = TheGlobalData->m_maxCameraHeight; - m_minHeightAboveGround = TheGlobalData->m_minCameraHeight; - m_okToAdjustHeight = FALSE; - - m_defaultAngle = 0.0f; - m_defaultPitchAngle = 0.0f; -} - -void View::reset( void ) -{ - // Only fixing the reported bug. Who knows what side effects resetting the rest could have. - m_zoomLimited = TRUE; - - m_viewLockedUntilFrame = 0u; -} - -/** - * Prepend this view to the given list, return the new list. - */ -View *View::prependViewToList( View *list ) -{ - m_next = list; - return this; -} - -void View::zoom( Real height ) -{ - setHeightAboveGround(getHeightAboveGround() + height); -} - -void View::lockViewUntilFrame(UnsignedInt frame) -{ - m_viewLockedUntilFrame = frame; -} - -/** - * Center the view on the given coordinate. - */ -void View::lookAt( const Coord3D *o ) -{ - - /// @todo this needs to be changed to be 3D, this is still old 2D stuff - Coord3D pos = *getPosition(); - pos.x = o->x - m_width * 0.5f; - pos.y = o->y - m_height * 0.5f; - setPosition(&pos); -} - -/** - * Shift the view by the given delta. - */ -void View::scrollBy( Coord2D *delta ) -{ - // update view's world position - m_pos.x += delta->x; - m_pos.y += delta->y; -} - -/** - * Rotate the view around the up axis by the given angle. - */ -void View::setAngle( Real angle ) -{ - m_angle = angle; -} - -/** - * Rotate the view around the horizontal (X) axis to the given angle. - */ -void View::setPitch( Real angle ) -{ - constexpr Real limit = PI/5.0f; - m_pitchAngle = clamp(-limit, angle, limit); -} - -/** - * Set the view angle back to default - */ -void View::setAngleAndPitchToDefault( void ) -{ - m_angle = m_defaultAngle; - m_pitchAngle = m_defaultPitchAngle; -} - -void View::setHeightAboveGround(Real z) -{ - // if our zoom is limited, we will stay within a predefined distance from the terrain - if( m_zoomLimited ) - { - m_heightAboveGround = clamp(m_minHeightAboveGround, z, m_maxHeightAboveGround); - } - else - { - m_heightAboveGround = z; - } -} - -/** - * write the view's current location in to the view location object - */ -void View::getLocation( ViewLocation *location ) -{ - - const Coord3D *pos = getPosition(); - location->init( pos->x, pos->y, pos->z, getAngle(), getPitch(), getZoom() ); - -} - - -/** - * set the view's current location from to the view location object - */ -void View::setLocation( const ViewLocation *location ) -{ - if ( location->m_valid ) - { - setPosition(&location->m_pos); - setAngle(location->m_angle); - setPitch(location->m_pitch); - setZoom(location->m_zoom); - forceRedraw(); - } - -} - -//------------------------------------------------------------------------------------------------- -/** project the 4 corners of this view into the world and return each point as a parameter, - the world points are at the requested Z */ -//------------------------------------------------------------------------------------------------- -void View::getScreenCornerWorldPointsAtZ( Coord3D *topLeft, Coord3D *topRight, - Coord3D *bottomLeft, Coord3D *bottomRight, - Real z ) -{ - ICoord2D screenTopLeft, screenTopRight, screenBottomLeft, screenBottomRight; - ICoord2D origin; - Int viewWidth = getWidth(); - Int viewHeight = getHeight(); - - // sanity - if( topLeft == NULL || topRight == NULL || bottomLeft == NULL || bottomRight == NULL ) - return; - - // setup the screen coords for the 4 corners of the viewable display - getOrigin( &origin.x, &origin.y ); - screenTopLeft.x = origin.x; // upper left - screenTopLeft.y = origin.y; // upper left - screenTopRight.x = origin.x + viewWidth; // upper right - screenTopRight.y = origin.y; // upper right - screenBottomLeft.x = origin.x + viewWidth; // lower right - screenBottomLeft.y = origin.y + viewHeight; // lower right - screenBottomRight.x = origin.x; // lower left - screenBottomRight.y = origin.y + viewHeight; // lower left - - // project - screenToWorldAtZ( &screenTopLeft, topLeft, z ); - screenToWorldAtZ( &screenTopRight, topRight, z ); - screenToWorldAtZ( &screenBottomLeft, bottomLeft, z ); - screenToWorldAtZ( &screenBottomRight, bottomRight, z ); - -} - -// ------------------------------------------------------------------------------------------------ -/** Xfer method for a view */ -// ------------------------------------------------------------------------------------------------ -void View::xfer( Xfer *xfer ) -{ - - // version - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // camera angle - Real angle = getAngle(); - xfer->xferReal( &angle ); - setAngle( angle ); - - // view position - Coord3D viewPos; - getPosition( &viewPos ); - xfer->xferReal( &viewPos.x ); - xfer->xferReal( &viewPos.y ); - xfer->xferReal( &viewPos.z ); - lookAt( &viewPos ); - -} diff --git a/Generals/Code/GameEngineDevice/CMakeLists.txt b/Generals/Code/GameEngineDevice/CMakeLists.txt index 7d91eaf43e..de6e7bd69a 100644 --- a/Generals/Code/GameEngineDevice/CMakeLists.txt +++ b/Generals/Code/GameEngineDevice/CMakeLists.txt @@ -60,7 +60,7 @@ set(GAMEENGINEDEVICE_SRC Include/W3DDevice/GameClient/W3DTerrainVisual.h Include/W3DDevice/GameClient/W3DTreeBuffer.h # Include/W3DDevice/GameClient/W3DVideoBuffer.h - Include/W3DDevice/GameClient/W3DView.h +# Include/W3DDevice/GameClient/W3DView.h Include/W3DDevice/GameClient/W3DVolumetricShadow.h Include/W3DDevice/GameClient/W3DWater.h Include/W3DDevice/GameClient/W3DWaterTracks.h @@ -158,7 +158,7 @@ set(GAMEENGINEDEVICE_SRC Source/W3DDevice/GameClient/W3DTerrainVisual.cpp Source/W3DDevice/GameClient/W3DTreeBuffer.cpp # Source/W3DDevice/GameClient/W3DVideoBuffer.cpp - Source/W3DDevice/GameClient/W3DView.cpp +# Source/W3DDevice/GameClient/W3DView.cpp Source/W3DDevice/GameClient/W3dWaypointBuffer.cpp Source/W3DDevice/GameClient/W3DWebBrowser.cpp Source/W3DDevice/GameClient/Water/W3DWater.cpp diff --git a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DView.h b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DView.h deleted file mode 100644 index 12f7215d46..0000000000 --- a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DView.h +++ /dev/null @@ -1,302 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public 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: W3DView.h //////////////////////////////////////////////////////////////////////////////// -// -// W3D implementation of the game view window. View windows are literally -// a window into the game world that have width, height, and camera -// controls for what to look at -// -// Author: Colin Day, April 2001 -// -/////////////////////////////////////////////////////////////////////////////////////////////////// - -#pragma once - -// SYSTEM INCLUDES //////////////////////////////////////////////////////////////////////////////// - -// USER INCLUDES ////////////////////////////////////////////////////////////////////////////////// -#include "Common/STLTypedefs.h" -#include "GameClient/ParabolicEase.h" -#include "GameClient/View.h" -#include "WW3D2/camera.h" - -// FORWARD REFERENCES ///////////////////////////////////////////////////////////////////////////// -class Drawable; - -/////////////////////////////////////////////////////////////////////////////////////////////////// -enum {MAX_WAYPOINTS=25}; - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -typedef struct -{ - Int numWaypoints; - Coord3D waypoints[MAX_WAYPOINTS+2]; // We pad first & last for interpolation. - Real waySegLength[MAX_WAYPOINTS+2]; // Length of each segment; - Real cameraAngle[MAX_WAYPOINTS+2]; // Camera Angle; - Int timeMultiplier[MAX_WAYPOINTS+2]; // Time speedup factor. - Real groundHeight[MAX_WAYPOINTS+1]; // Ground height. - Real totalTimeMilliseconds; // Num of ms to do this movement. - Real elapsedTimeMilliseconds; // Time since start. - Real totalDistance; // Total length of paths. - Real curSegDistance; // How far we are along the current seg. - Int shutter; - Int curSegment; // The current segment. - Int curShutter; // The current shutter. - Int rollingAverageFrames; // Number of frames to roll. - ParabolicEase ease; // Ease in/out function. -} TMoveAlongWaypointPathInfo; - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -typedef struct -{ - Int numFrames; ///< Number of frames to rotate. - Int curFrame; ///< Current frame. - Int startTimeMultiplier; - Int endTimeMultiplier; - Int numHoldFrames; ///< Number of frames to hold the camera before finishing the movement - ParabolicEase ease; - Bool trackObject; ///< Are we tracking an object or just rotating? - struct Target { - ObjectID targetObjectID; ///< Target if we are tracking an object instead of just rotating - Coord3D targetObjectPos; ///< Target's position (so we can stay looking at that spot if he dies) - }; - struct Angle { - Real startAngle; - Real endAngle; - }; - union { - Target target; - Angle angle; - }; -} TRotateCameraInfo; - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -typedef struct -{ - Int numFrames; ///< Number of frames to pitch. - Int curFrame; ///< Current frame. - Real angle; - Real startPitch; - Real endPitch; - Int startTimeMultiplier; - Int endTimeMultiplier; - ParabolicEase ease; -} TPitchCameraInfo; - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -typedef struct -{ - Int numFrames; ///< Number of frames to zoom. - Int curFrame; ///< Current frame. - Real startZoom; - Real endZoom; - Int startTimeMultiplier; - Int endTimeMultiplier; - ParabolicEase ease; -} TZoomCameraInfo; - -// ------------------------------------------------------------------------------------------------ -/** W3DView implementation of the game view class. This allows us to create - * a "window" into the game world that can be sized and contains controls - * for manipulating the camera */ -// ------------------------------------------------------------------------------------------------ -class W3DView : public View, public SubsystemInterface -{ - -public: - W3DView(); - ~W3DView(); - - virtual void init( void ); ///< init/re-init the W3DView - virtual void reset( void ); - virtual void drawView( void ); ///< draw this view - virtual void updateView(void); ///x; m_guardBandBias.y = gb->y; } - - -private: - - CameraClass *m_3DCamera; ///< camera representation for 3D scene - CameraClass *m_2DCamera; ///< camera for UI overlayed on top of 3D scene - FilterModes m_viewFilterMode; - FilterTypes m_viewFilter; - Bool m_isWireFrameEnabled; - Bool m_nextWireFrameEnabled; ///< used to delay wireframe changes by 1 frame (needed for transitions). - - - Coord2D m_shakeOffset; ///< the offset to add to the camera position - Real m_shakeAngleCos; ///< the cosine of the orientation of the oscillation - Real m_shakeAngleSin; ///< the sine of the orientation of the oscillation - Real m_shakeIntensity; ///< the intensity of the oscillation - Vector3 m_shakerAngles; //WST 11/12/2002 new multiple instance camera shaker system - - TRotateCameraInfo m_rcInfo; - Bool m_doingRotateCamera; ///< True if we are doing a camera rotate. - - TPitchCameraInfo m_pcInfo; - Bool m_doingPitchCamera; - TZoomCameraInfo m_zcInfo; - Bool m_doingZoomCamera; - - Bool m_doingScriptedCameraLock; ///< True if we are following a unit via script - - Real m_FXPitch; ///< Camera effects pitch. 0 = flat, infinite = look down, 1 = normal. - - TMoveAlongWaypointPathInfo m_mcwpInfo; ///< Move camera along waypoint path info. - Bool m_doingMoveCameraOnWaypointPath; ///< If true, moving camera along waypoint path. - Bool m_CameraArrivedAtWaypointOnPathFlag; - - Bool m_freezeTimeForCameraMovement; - Int m_timeMultiplier; ///< Time speedup multiplier. - - Bool m_cameraHasMovedSinceRequest; ///< If true, throw out all saved locations - VecPosRequests m_locationRequests; ///< These are cached. New requests are added here - - Coord3D m_cameraOffset; ///< offset for camera from view center - Coord3D m_previousLookAtPosition; ///< offset for camera from view center - Coord2D m_scrollAmount; ///< scroll speed - Real m_scrollAmountCutoff; ///< scroll speed at which we do not adjust height - - Real m_groundLevel; ///< height of ground. - - Region2D m_cameraConstraint; ///< m_pos should be constrained to be within this area - Bool m_cameraConstraintValid; ///< if f, recalc cam constraints - - void setCameraTransform( void ); ///< set the transform matrix of m_3DCamera, based on m_pos & m_angle - void buildCameraTransform( Matrix3D *transform ) ; ///< calculate (but do not set) the transform matrix of m_3DCamera, based on m_pos & m_angle - void calcCameraConstraints() ; ///< recalc m_cameraConstraint - void moveAlongWaypointPath(Real milliseconds); ///< Move camera along path. - void getPickRay(const ICoord2D *screen, Vector3 *rayStart, Vector3 *rayEnd); ///. -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: W3DView.cpp ////////////////////////////////////////////////////////////////////////////// -// -// W3D implementation of the game view class. This view allows us to have -// a "window" into the game world that can change its width, height as -// well as camera positioning controls -// -// Author: Colin Day, April 2001 -// -/////////////////////////////////////////////////////////////////////////////////////////////////// - -// SYSTEM INCLUDES //////////////////////////////////////////////////////////////////////////////// -#include -#include - -// USER INCLUDES ////////////////////////////////////////////////////////////////////////////////// -#include "Common/BuildAssistant.h" -#include "Common/FramePacer.h" -#include "Common/GameUtility.h" -#include "Common/GlobalData.h" -#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" - -#include "GameClient/Color.h" -#include "GameClient/CommandXlat.h" -#include "GameClient/Drawable.h" -#include "GameClient/GameClient.h" -#include "GameClient/GameWindowManager.h" -#include "GameClient/Image.h" -#include "GameClient/InGameUI.h" -#include "GameClient/Line2D.h" -#include "GameClient/SelectionInfo.h" -#include "GameClient/Shell.h" -#include "GameClient/TerrainVisual.h" -#include "GameClient/Water.h" - -#include "GameLogic/AI.h" ///< For AI debug (yes, I'm cheating for now) -#include "GameLogic/AIPathfind.h" ///< For AI debug (yes, I'm cheating for now) -#include "GameLogic/ExperienceTracker.h" -#include "GameLogic/GameLogic.h" -#include "GameLogic/Module/AIUpdate.h" -#include "GameLogic/Module/BodyModule.h" -#include "GameLogic/Module/ContainModule.h" -#include "GameLogic/Module/OpenContain.h" -#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" -#include "W3DDevice/GameClient/W3DAssetManager.h" -#include "W3DDevice/GameClient/W3DDisplay.h" -#include "W3DDevice/GameClient/W3DScene.h" -#include "W3DDevice/GameClient/W3DView.h" -#include "d3dx8math.h" -#include "W3DDevice/GameClient/W3DShaderManager.h" -#include "W3DDevice/GameClient/Module/W3DModelDraw.h" -#include "W3DDevice/GameClient/W3DCustomScene.h" - -#include "WW3D2/dx8renderer.h" -#include "WW3D2/light.h" -#include "WW3D2/camera.h" -#include "WW3D2/coltype.h" -#include "WW3D2/predlod.h" -#include "WW3D2/ww3d.h" - -#include "W3DDevice/GameClient/CameraShakeSystem.h" - -#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 */ - - - -// 30 fps -Real TheW3DFrameLengthInMsec = MSEC_PER_LOGICFRAME_REAL; // default is 33msec/frame == 30fps. but we may change it depending on sys config. -static const Int MAX_REQUEST_CACHE_SIZE = 40; // Any size larger than 10, or examine code below for changes. jkmcd. -static const Real DRAWABLE_OVERSCAN = 75.0f; ///< 3D world coords of how much to overscan in the 3D screen region - - - - - - -//================================================================================================= -inline Real minf(Real a, Real b) { if (a < b) return a; else return b; } -inline Real maxf(Real a, Real b) { if (a > b) return a; else return b; } - -//------------------------------------------------------------------------------------------------- -// Normalizes angle to +- PI. -//------------------------------------------------------------------------------------------------- -static void normAngle(Real &angle) -{ - angle = WWMath::Normalize_Angle(angle); -} - -#define TERRAIN_SAMPLE_SIZE 40.0f -static Real getHeightAroundPos(Real x, Real y) -{ - // terrain height + desired height offset == cameraOffset * actual zoom - Real terrainHeight = TheTerrainLogic->getGroundHeight(x, y); - - // find best approximation of max terrain height we can see - Real terrainHeightMax = terrainHeight; - terrainHeightMax = max(terrainHeightMax, TheTerrainLogic->getGroundHeight(x+TERRAIN_SAMPLE_SIZE, y-TERRAIN_SAMPLE_SIZE)); - terrainHeightMax = max(terrainHeightMax, TheTerrainLogic->getGroundHeight(x-TERRAIN_SAMPLE_SIZE, y-TERRAIN_SAMPLE_SIZE)); - terrainHeightMax = max(terrainHeightMax, TheTerrainLogic->getGroundHeight(x+TERRAIN_SAMPLE_SIZE, y+TERRAIN_SAMPLE_SIZE)); - terrainHeightMax = max(terrainHeightMax, TheTerrainLogic->getGroundHeight(x-TERRAIN_SAMPLE_SIZE, y+TERRAIN_SAMPLE_SIZE)); - - return terrainHeightMax; -} - - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -W3DView::W3DView() -{ - - m_3DCamera = NULL; - m_2DCamera = NULL; - m_groundLevel = 10.0; - m_cameraOffset.z = TheGlobalData->m_cameraHeight; - m_cameraOffset.y = -(m_cameraOffset.z / tan(TheGlobalData->m_cameraPitch * (PI / 180.0))); - m_cameraOffset.x = -(m_cameraOffset.y * tan(TheGlobalData->m_cameraYaw * (PI / 180.0))); - - m_viewFilterMode = FM_VIEW_DEFAULT; - m_viewFilter = FT_VIEW_DEFAULT; - m_isWireFrameEnabled = m_nextWireFrameEnabled = FALSE; - m_shakeOffset.x = 0.0f; - m_shakeOffset.y = 0.0f; - m_shakeIntensity = 0.0f; - m_FXPitch = 1.0f; - m_freezeTimeForCameraMovement = false; - m_cameraHasMovedSinceRequest = true; - m_locationRequests.clear(); - m_locationRequests.reserve(MAX_REQUEST_CACHE_SIZE + 10); // This prevents the vector from ever re-allocing - - //Enhancements from CNC3 WST 4/15/2003. JSC Integrated 5/20/03. - m_CameraArrivedAtWaypointOnPathFlag = false; // Scripts for polling camera reached targets - m_isCameraSlaved = false; // This is for 3DSMax camera playback - m_useRealZoomCam = false; // true; //WST 10/18/2002 - m_shakerAngles.X =0.0f; // Proper camera shake generator & sources - m_shakerAngles.Y =0.0f; - m_shakerAngles.Z =0.0f; - -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -W3DView::~W3DView() -{ - - REF_PTR_RELEASE( m_2DCamera ); - REF_PTR_RELEASE( m_3DCamera ); - -} - -//------------------------------------------------------------------------------------------------- -/** Sets the height of the viewport, while maintaining original camera perspective. */ -//------------------------------------------------------------------------------------------------- -void W3DView::setHeight(Int height) -{ - // extend View functionality - View::setHeight(height); - - Vector2 vMin,vMax; - m_3DCamera->Set_Aspect_Ratio((Real)getWidth()/(Real)height); - m_3DCamera->Get_Viewport(vMin,vMax); - vMax.Y=(Real)(m_originY+height)/(Real)TheDisplay->getHeight(); - m_3DCamera->Set_Viewport(vMin,vMax); -} - -//------------------------------------------------------------------------------------------------- -/** Sets the width of the viewport, while maintaining original camera perspective. */ -//------------------------------------------------------------------------------------------------- -void W3DView::setWidth(Int width) -{ - // extend View functionality - View::setWidth(width); - - Vector2 vMin,vMax; - m_3DCamera->Set_Aspect_Ratio((Real)width/(Real)getHeight()); - m_3DCamera->Get_Viewport(vMin,vMax); - vMax.X=(Real)(m_originX+width)/(Real)TheDisplay->getWidth(); - m_3DCamera->Set_Viewport(vMin,vMax); - - //we want to maintain the same scale, so we'll need to adjust the fov. - //default W3D fov for full-screen is 50 degrees. - m_3DCamera->Set_View_Plane((Real)width/(Real)TheDisplay->getWidth()*DEG_TO_RADF(50.0f),-1); -} - -//------------------------------------------------------------------------------------------------- -/** Sets location of top-left view corner on display */ -//------------------------------------------------------------------------------------------------- -void W3DView::setOrigin( Int x, Int y) -{ - // extend View functionality - View::setOrigin(x,y); - - Vector2 vMin,vMax; - - m_3DCamera->Get_Viewport(vMin,vMax); - vMin.X=(Real)x/(Real)TheDisplay->getWidth(); - vMin.Y=(Real)y/(Real)TheDisplay->getHeight(); - m_3DCamera->Set_Viewport(vMin,vMax); - - // bottom-right border was also moved my this call, so force an update of extents. - setWidth(m_width); - setHeight(m_height); -} - -//------------------------------------------------------------------------------------------------- -/** @todo This is inefficient. We should construct the matrix directly using vectors. */ -//------------------------------------------------------------------------------------------------- -#define MIN_CAPPED_ZOOM (0.5f) //WST 10.19.2002. JSC integrated 5/20/03. -void W3DView::buildCameraTransform( Matrix3D *transform ) -{ - Vector3 sourcePos, targetPos; - - Real groundLevel = m_groundLevel; // 93.0f; - - Real zoom = getZoom(); - Real angle = getAngle(); - Real pitch = getPitch(); - Coord3D pos = *getPosition(); - - // add in the camera shake, if any - pos.x += m_shakeOffset.x; - pos.y += m_shakeOffset.y; - - if (m_cameraConstraintValid) - { - pos.x = maxf(m_cameraConstraint.lo.x, pos.x); - pos.x = minf(m_cameraConstraint.hi.x, pos.x); - pos.y = maxf(m_cameraConstraint.lo.y, pos.y); - pos.y = minf(m_cameraConstraint.hi.y, pos.y); - } - - // set position of camera itself - if (m_useRealZoomCam) //WST 10/10/2002 Real Zoom using FOV - { - sourcePos.X = m_cameraOffset.x; - sourcePos.Y = m_cameraOffset.y; - sourcePos.Z = m_cameraOffset.z; - Real capped_zoom = zoom; - if (capped_zoom > 1.0f) - { - capped_zoom= 1.0f; - } - if (capped_zoom < MIN_CAPPED_ZOOM) - { - capped_zoom = MIN_CAPPED_ZOOM; - } - m_FOV = 50.0f * PI/180.0f * capped_zoom * capped_zoom; - } - else - { - sourcePos.X = m_cameraOffset.x*zoom; - sourcePos.Y = m_cameraOffset.y*zoom; - sourcePos.Z = m_cameraOffset.z*zoom; - } - -#ifdef NOT_IN_USE - if (TheGlobalData->m_isOffsetCameraZ && TheTerrainLogic) - { - sourcePos.Z += TheTerrainLogic->getGroundHeight(pos.x, pos.y); - if (m_prevSourcePosZ != SOURCEPOS_INVALID) - { - const Real MAX_SPZ_VARIATION = 0.05f; - Real spzMin = m_prevSourcePosZ*(1.0-MAX_SPZ_VARIATION); - Real spzMax Coord3D center; - = m_prevSourcePosZ*(1.0+MAX_SPZ_VARIATION); - if (sourcePos.Z < spzMin) sourcePos.Z = spzMin; - if (sourcePos.Z > spzMax) sourcePos.Z = spzMax; - } - m_prevSourcePosZ = sourcePos.Z; - } -#endif - - // camera looking at origin - targetPos.X = 0; - targetPos.Y = 0; - targetPos.Z = 0; - - - Real factor = 1.0 - (groundLevel/sourcePos.Z ); - - // construct a matrix to rotate around the up vector by the given angle - Matrix3D angleTransform( Vector3( 0.0f, 0.0f, 1.0f ), angle ); - - // construct a matrix to rotate around the horizontal vector by the given angle - Matrix3D pitchTransform( Vector3( 1.0f, 0.0f, 0.0f ), pitch ); - - // rotate camera position (pitch, then angle) -#ifdef ALLOW_TEMPORARIES - sourcePos = pitchTransform * sourcePos; - sourcePos = angleTransform * sourcePos; -#else - pitchTransform.mulVector3(sourcePos); - angleTransform.mulVector3(sourcePos); -#endif - sourcePos *= factor; - - // translate to current XY position - sourcePos.X += pos.x; - sourcePos.Y += pos.y; - sourcePos.Z += groundLevel; - - targetPos.X += pos.x; - targetPos.Y += pos.y; - targetPos.Z += groundLevel; - - // do m_FXPitch adjustment. - //WST Real height = sourcePos.Z - targetPos.Z; - //WST height *= m_FXPitch; - //WST targetPos.Z = sourcePos.Z - height; - - - // The following code moves camera down and pitch up when player zooms in. - // Use scripts to switch to useRealZoomCam - if (m_useRealZoomCam) - { - Real pitch_adjust = 1.0f; - - if (!TheDisplay->isLetterBoxed()) - { - Real capped_zoom = zoom; - if (capped_zoom > 1.0f) - { - capped_zoom= 1.0f; - } - if (capped_zoom < MIN_CAPPED_ZOOM) - { - capped_zoom = MIN_CAPPED_ZOOM; - } - sourcePos.Z = sourcePos.Z * ( 0.5f + capped_zoom * 0.5f); // move camera down physically - pitch_adjust = capped_zoom; // adjust camera to pitch up - } - m_FXPitch = 1.0f * (0.25f + pitch_adjust*0.75f); - } - - - // do fxPitch adjustment - if (m_useRealZoomCam) - { - sourcePos.X = targetPos.X + ((sourcePos.X - targetPos.X) / m_FXPitch); - sourcePos.Y = targetPos.Y + ((sourcePos.Y - targetPos.Y) / m_FXPitch); - } - else - { - // TheSuperHackers @todo Investigate whether the non Generals code is correct for Zero Hour. - // It certainly is incorrect for Generals when m_FXPitch goes above 1: - // Seen in USA mission 1 second cut scene with SCUD Storm. -#if RTS_GENERALS - Real height = sourcePos.Z - targetPos.Z; - height *= m_FXPitch; - targetPos.Z = sourcePos.Z - height; -#else - if (m_FXPitch <= 1.0f) - { - Real height = sourcePos.Z - targetPos.Z; - height *= m_FXPitch; - targetPos.Z = sourcePos.Z - height; - } - else - { - sourcePos.X = targetPos.X + ((sourcePos.X - targetPos.X) / m_FXPitch); - sourcePos.Y = targetPos.Y + ((sourcePos.Y - targetPos.Y) / m_FXPitch); - } -#endif - } - - //m_3DCamera->Set_View_Plane(DEG_TO_RADF(50.0f)); - //DEBUG_LOG(("zoom %f, SourceZ %f, posZ %f, groundLevel %f CamOffZ %f", - // zoom, sourcePos.Z, pos.z, groundLevel,m_cameraOffset.z)); - - // build new camera transform - transform->Make_Identity(); - transform->Look_At( sourcePos, targetPos, 0 ); - - //WST 11/12/2002 New camera shaker system - // TheSuperHackers @tweak The camera shaker is now decoupled from the render update. - CameraShakerSystem.Timestep(TheFramePacer->getLogicTimeStepMilliseconds()); - CameraShakerSystem.Update_Camera_Shaker(sourcePos, &m_shakerAngles); - transform->Rotate_X(m_shakerAngles.X); - transform->Rotate_Y(m_shakerAngles.Y); - transform->Rotate_Z(m_shakerAngles.Z); - - //if (m_shakerAngles.X >= 0.0f) - //{ - // DEBUG_LOG(("m_shakerAngles %f, %f, %f", m_shakerAngles.X, m_shakerAngles.Y, m_shakerAngles.Z)); - //} - - // (gth) check if the camera is being controlled by an animation - if (m_isCameraSlaved) { - // find object named m_cameraSlaveObjectName - Object * obj = TheScriptEngine->getUnitNamed(m_cameraSlaveObjectName); - - if (obj != NULL) { - // dig out the drawable - Drawable * draw = obj->getDrawable(); - if (draw != NULL) { - - // dig out the first draw module with an ObjectDrawInterface - for (DrawModule ** dm = draw->getDrawModules(); *dm; ++dm) { - const ObjectDrawInterface* di = (*dm)->getObjectDrawInterface(); - if (di) { - Matrix3D tm; - di->clientOnly_getRenderObjBoneTransform(m_cameraSlaveObjectBoneName,&tm); - - // Ok, slam it into the camera! - *transform = tm; - - //-------------------------------------------------------------------- - // WST 10.22.2002. Update the Listener positions used by audio system - //-------------------------------------------------------------------- - Vector3 position = transform->Get_Translation(); - Coord3D coord; - coord.set(position.X, position.Y, position.Z); - View::setPosition(&coord); - break; - } - } - - } else { - m_isCameraSlaved = false; - } - } else { - m_isCameraSlaved = false; - } - } -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -void W3DView::calcCameraConstraints() -{ -// const Matrix3D& cameraTransform = m_3DCamera->Get_Transform(); - -// DEBUG_LOG(("*** rebuilding cam constraints")); - - // ok, now check to ensure that we can't see outside the map region, - // and twiddle the camera if needed - if (TheTerrainLogic) - { - Region3D mapRegion; - TheTerrainLogic->getExtent( &mapRegion ); - - /* - Note the following restrictions on camera constraints! - - -- they assume that all maps are height 'm_groundLevel' at the edges. - (since you need to add some "buffer" around the edges of your map - anyway, this shouldn't be an issue.) - - -- for angles/pitches other than zero, it may show boundaries. - since we currently plan the game to be restricted to this, - it shouldn't be an issue. - - */ - Real maxEdgeZ = m_groundLevel; -// const Real BORDER_FUDGE = MAP_XY_FACTOR * 1.414f; - Coord3D center, bottom; - ICoord2D screen; - - //Pick at the center - screen.x=0.5f*getWidth()+m_originX; - screen.y=0.5f*getHeight()+m_originY; - - Vector3 rayStart,rayEnd; - - getPickRay(&screen,&rayStart,&rayEnd); - - center.x = Vector3::Find_X_At_Z(maxEdgeZ, rayStart, rayEnd); - center.y = Vector3::Find_Y_At_Z(maxEdgeZ, rayStart, rayEnd); - center.z = maxEdgeZ; - - screen.y = m_originY+ 0.95f*getHeight(); - getPickRay(&screen,&rayStart,&rayEnd); - bottom.x = Vector3::Find_X_At_Z(maxEdgeZ, rayStart, rayEnd); - bottom.y = Vector3::Find_Y_At_Z(maxEdgeZ, rayStart, rayEnd); - bottom.z = maxEdgeZ; - center.x -= bottom.x; - center.y -= bottom.y; - - Real offset = center.length(); - - if (TheGlobalData->m_debugAI) { - offset = -1000; // push out the constraints so we can look at staging areas. - } - - m_cameraConstraint.lo.x = mapRegion.lo.x + offset; - m_cameraConstraint.hi.x = mapRegion.hi.x - offset; - // this looks inverted, but is correct - m_cameraConstraint.lo.y = mapRegion.lo.y + offset; - m_cameraConstraint.hi.y = mapRegion.hi.y - offset; - m_cameraConstraintValid = true; - } -} - -//------------------------------------------------------------------------------------------------- -/** Returns a world-space ray originating at a given screen pixel position - and ending at the far clip plane for current camera. Screen coordinates - assumed in absolute values relative to full display resolution.*/ -//------------------------------------------------------------------------------------------------- -void W3DView::getPickRay(const ICoord2D *screen, Vector3 *rayStart, Vector3 *rayEnd) -{ - Real logX,logY; - - //W3D Screen coordinates are -1 to 1, so we need to do some conversion: - PixelScreenToW3DLogicalScreen(screen->x - m_originX,screen->y - m_originY, &logX, &logY,getWidth(),getHeight()); - - *rayStart = m_3DCamera->Get_Position(); //get camera location - m_3DCamera->Un_Project(*rayEnd,Vector2(logX,logY)); //get world space point - *rayEnd -= *rayStart; //vector camera to world space point - rayEnd->Normalize(); //make unit vector - *rayEnd *= m_3DCamera->Get_Depth(); //adjust length to reach far clip plane - *rayEnd += *rayStart; //get point on far clip plane along ray from camera. -} - -//------------------------------------------------------------------------------------------------- -/** set the transform matrix of m_3DCamera, based on m_pos & m_angle */ -//------------------------------------------------------------------------------------------------- -void W3DView::setCameraTransform( void ) -{ - if (TheGlobalData->m_headless) - return; - - if (m_viewLockedUntilFrame > TheGameClient->getFrame()) - return; - - m_cameraHasMovedSinceRequest = true; - Matrix3D cameraTransform( 1 ); - - Real nearZ, farZ; - // m_3DCamera->Get_Clip_Planes(nearZ, farZ); - // Set the near to MAP_XY_FACTOR. Improves zbuffer resolution. - nearZ = MAP_XY_FACTOR; - farZ = 1200.0f; - - if (m_useRealZoomCam) //WST 10.19.2002 - { - if (m_FXPitch<0.95f) - { - farZ = farZ / m_FXPitch; //Extend far Z when we pitch up for RealZoomCam - } - } - else - { - if ((TheGlobalData && TheGlobalData->m_drawEntireTerrain) || (m_FXPitch<0.95f || m_zoom>1.05)) - { //need to extend far clip plane so entire terrain can be visible - farZ *= MAP_XY_FACTOR; - } - } - - m_3DCamera->Set_Clip_Planes(nearZ, farZ); -#if defined(RTS_DEBUG) - if (TheGlobalData->m_useCameraConstraints) -#endif - { - if (!m_cameraConstraintValid) - { - buildCameraTransform(&cameraTransform); - m_3DCamera->Set_Transform( cameraTransform ); - calcCameraConstraints(); - } - DEBUG_ASSERTLOG(m_cameraConstraintValid,("*** cam constraints are not valid!!!")); - - if (m_cameraConstraintValid) - { - Coord3D pos = *getPosition(); - pos.x = maxf(m_cameraConstraint.lo.x, pos.x); - pos.x = minf(m_cameraConstraint.hi.x, pos.x); - pos.y = maxf(m_cameraConstraint.lo.y, pos.y); - pos.y = minf(m_cameraConstraint.hi.y, pos.y); - setPosition(&pos); - } - } - -#if defined(RTS_DEBUG) - m_3DCamera->Set_View_Plane( m_FOV, -1 ); -#endif - - // rebuild it (even if we just did it due to camera constraints) - buildCameraTransform( &cameraTransform ); - m_3DCamera->Set_Transform( cameraTransform ); - - if (TheTerrainRenderObject) - { - RefRenderObjListIterator *it = W3DDisplay::m_3DScene->createLightsIterator(); - TheTerrainRenderObject->updateCenter(m_3DCamera, it); - if (it) - { - W3DDisplay::m_3DScene->destroyLightsIterator(it); - it = NULL; - } - } -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -void W3DView::init( void ) -{ - // extend View functionality - View::init(); - setName("W3DView"); - // set default camera "lookat" point - Coord3D pos; - pos.x = 87.0f; - pos.y = 77.0f; - pos.z = 0; - - pos.x *= MAP_XY_FACTOR; - pos.y *= MAP_XY_FACTOR; - - setPosition(&pos); - - // create our 3D camera - m_3DCamera = NEW_REF( CameraClass, () ); - - - setCameraTransform(); - - // create our 2D camera for the GUI overlay - m_2DCamera = NEW_REF( CameraClass, () ); - m_2DCamera->Set_Position( Vector3( 0, 0, 1 ) ); - Vector2 min = Vector2( -1, -0.75f ); - Vector2 max = Vector2( +1, +0.75f ); - m_2DCamera->Set_View_Plane( min, max ); - m_2DCamera->Set_Clip_Planes( 0.995f, 2.0f ); - - m_cameraConstraintValid = false; - - m_scrollAmountCutoff = TheGlobalData->m_scrollAmountCutoff; - -} - -//------------------------------------------------------------------------------------------------- -const Coord3D& W3DView::get3DCameraPosition() const -{ - Vector3 camera = m_3DCamera->Get_Position(); - static Coord3D pos; - pos.set( camera.X, camera.Y, camera.Z ); - return pos; -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -void W3DView::reset( void ) -{ - View::reset(); - - // Just in case... - setTimeMultiplier(1); // Set time rate back to 1. - - Coord3D arbitraryPos = { 0, 0, 0 }; - // Just move the camera to 0, 0, 0. It'll get repositioned at the beginning of the next game - // anyways. - resetCamera(&arbitraryPos, 1, 0.0f, 0.0f); - - setViewFilter(FT_VIEW_DEFAULT); - - Coord2D gb = { 0,0 }; - setGuardBandBias( &gb ); -} - -//------------------------------------------------------------------------------------------------- -/** draw worker for drawables in the view region */ -//------------------------------------------------------------------------------------------------- -static void drawDrawable( Drawable *draw, void *userData ) -{ - - draw->draw(); - -} - -// ------------------------------------------------------------------------------------------------ -//------------------------------------------------------------------------------------------------- -static void drawTerrainNormal( Drawable *draw, void *userData ) -{ - UnsignedInt color = GameMakeColor( 255, 255, 0, 255 ); - if (TheTerrainLogic) - { - Coord3D pos = *draw->getPosition(); - Coord3D normal; - pos.z = TheTerrainLogic->getGroundHeight(pos.x, pos.y, &normal); - const Real NORMLEN = 20; - normal.x = pos.x + normal.x * NORMLEN; - normal.y = pos.y + normal.y * NORMLEN; - normal.z = pos.z + normal.z * NORMLEN; - ICoord2D start, end; - TheTacticalView->worldToScreen(&pos, &start); - TheTacticalView->worldToScreen(&normal, &end); - TheDisplay->drawLine(start.x, start.y, end.x, end.y, 1.0f, color); - } -} - -#if defined(RTS_DEBUG) -// ------------------------------------------------------------------------------------------------ -// 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 -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -static void drawContainedDrawable( Object *obj, void *userData ) -{ - Drawable *draw = obj->getDrawable(); - - if( draw ) - drawDrawableExtents( draw, userData ); - -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -static void drawDrawableExtents( Drawable *draw, void *userData ) -{ - UnsignedInt color = GameMakeColor( 0, 255, 0, 255 ); - - switch( draw->getDrawableGeometryInfo().getGeomType() ) - { - - //--------------------------------------------------------------------------------------------- - case GEOMETRY_BOX: - { - Real angle = draw->getOrientation(); - Real c = (Real)cos(angle); - Real s = (Real)sin(angle); - Real exc = draw->getDrawableGeometryInfo().getMajorRadius()*c; - Real eyc = draw->getDrawableGeometryInfo().getMinorRadius()*c; - Real exs = draw->getDrawableGeometryInfo().getMajorRadius()*s; - Real eys = draw->getDrawableGeometryInfo().getMinorRadius()*s; - Coord3D pts[4]; - pts[0].x = draw->getPosition()->x - exc - eys; - pts[0].y = draw->getPosition()->y + eyc - exs; - pts[0].z = 0; - pts[1].x = draw->getPosition()->x + exc - eys; - pts[1].y = draw->getPosition()->y + eyc + exs; - pts[1].z = 0; - pts[2].x = draw->getPosition()->x + exc + eys; - pts[2].y = draw->getPosition()->y - eyc + exs; - pts[2].z = 0; - pts[3].x = draw->getPosition()->x - exc + eys; - pts[3].y = draw->getPosition()->y - eyc - exs; - pts[3].z = 0; - Real z = draw->getPosition()->z; - for( int i = 0; i < 2; i++ ) - { - - for (int corner = 0; corner < 4; corner++) - { - ICoord2D start, end; - pts[corner].z = z; - pts[(corner+1)&3].z = z; - TheTacticalView->worldToScreen(&pts[corner], &start); - TheTacticalView->worldToScreen(&pts[(corner+1)&3], &end); - TheDisplay->drawLine(start.x, start.y, end.x, end.y, 1.0f, color); - } - - z += draw->getDrawableGeometryInfo().getMaxHeightAbovePosition(); - - } - - break; - - } - - //--------------------------------------------------------------------------------------------- - case GEOMETRY_SPHERE: // not quite right, but close enough - case GEOMETRY_CYLINDER: - { - 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 ); - - // next time 'round, draw the top of the cylinder - center.z += draw->getDrawableGeometryInfo().getMaxHeightAbovePosition(); - } - - // draw centerline - 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; - - } - - } - - // draw any extents for things that are contained by this - Object *obj = draw->getObject(); - if( obj ) - { - ContainModuleInterface *contain = obj->getContain(); - - if( contain ) - contain->iterateContained( drawContainedDrawable, userData, FALSE ); - - } - -} - - -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 ); - -} - - -//------------------------------------------------------------------------------------------------- -// 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 ); - - } - - 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 - -//------------------------------------------------------------------------------------------------- -/** An opportunity to draw something after all drawables have been drawn once */ -//------------------------------------------------------------------------------------------------- -static void drawablePostDraw( Drawable *draw, void *userData ) -{ - Real FXPitch = TheTacticalView->getFXPitch(); - if (draw->isDrawableEffectivelyHidden() || FXPitch < 0.0f) - return; - - Object* obj = draw->getObject(); - const Int localPlayerIndex = rts::getObservedOrLocalPlayerIndex_Safe(); -#if ENABLE_CONFIGURABLE_SHROUD - ObjectShroudStatus ss = (!obj || !TheGlobalData->m_shroudOn) ? OBJECTSHROUD_CLEAR : obj->getShroudedStatus(localPlayerIndex); -#else - ObjectShroudStatus ss = (!obj) ? OBJECTSHROUD_CLEAR : obj->getShroudedStatus(localPlayerIndex); -#endif - if (ss > OBJECTSHROUD_PARTIAL_CLEAR) - return; - - // draw the any "icon" UI for a drawable (health bars, veterency, etc); - - //***** - //@TODO: Create a way to reject this call easily -- like objects that have no compatible modules. - //***** - //if( draw->getStatusBits() ) - //{ - draw->drawIconUI(); - //} - -#if defined(RTS_DEBUG) - // debug collision extents - if( TheGlobalData->m_showCollisionExtents ) - drawDrawableExtents( draw, userData ); - - if ( TheGlobalData->m_showAudioLocations ) - drawAudioLocations( draw, userData ); -#endif - - // debug terrain normals at object positions - if( TheGlobalData->m_showTerrainNormals ) - drawTerrainNormal( draw, userData ); - - TheGameClient->incrementRenderedObjectCount(); - -} - -//------------------------------------------------------------------------------------------------- -// Display AI debug visuals -//------------------------------------------------------------------------------------------------- -static void renderAIDebug( void ) -{ -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -Bool W3DView::updateCameraMovements() -{ - Bool didUpdate = false; - - if (m_doingZoomCamera) - { - zoomCameraOneFrame(); - didUpdate = true; - } - if (m_doingPitchCamera) - { - pitchCameraOneFrame(); - didUpdate = true; - } - if (m_doingRotateCamera) { - m_previousLookAtPosition = *getPosition(); - rotateCameraOneFrame(); - didUpdate = true; - } else if (m_doingMoveCameraOnWaypointPath) { - m_previousLookAtPosition = *getPosition(); - // TheSuperHackers @tweak The scripted camera movement is now decoupled from the render update. - // The scripted camera will still move when the time is frozen, but not when the game is halted. - moveAlongWaypointPath(TheFramePacer->getLogicTimeStepMilliseconds(FramePacer::IgnoreFrozenTime)); - didUpdate = true; - } - if (m_doingScriptedCameraLock) - { - didUpdate = true; - } - return didUpdate; -} - - -/** This function performs all actions which affect the camera transform or 3D objects - rendered in this frame. - - MW: I moved this code out out W3DView::draw() so that we can get final camera and object - positions before any rendering begins. This was necessary so that reflection textures - (which update before the main rendering loop) could get a correct version of the scene. - Without this change, the reflections were always 1 frame behind the non-reflected view. -*/ -void W3DView::updateView(void) -{ - UPDATE(); -} - -// TheSuperHackers @tweak xezon 12/08/2025 The camera shaker is no longer tied to the render -// update. The shake does sharp shakes on every fixed time step, and is not intended to have -// linear interpolation during the render update. -void W3DView::stepView() -{ - // - // Process camera shake - // - if (m_shakeIntensity > 0.01f) - { - m_shakeOffset.x = m_shakeIntensity * m_shakeAngleCos; - m_shakeOffset.y = m_shakeIntensity * m_shakeAngleSin; - - // fake a stiff spring/damper - const Real dampingCoeff = 0.75f; - m_shakeIntensity *= dampingCoeff; - - // spring is so "stiff", it pulls 180 degrees opposite each frame - m_shakeAngleCos = -m_shakeAngleCos; - m_shakeAngleSin = -m_shakeAngleSin; - } - else - { - m_shakeIntensity = 0.0f; - m_shakeOffset.x = 0.0f; - m_shakeOffset.y = 0.0f; - } -} - -//DECLARE_PERF_TIMER(W3DView_updateView) -void W3DView::update(void) -{ - //USE_PERF_TIMER(W3DView_updateView) - Bool recalcCamera = false; - Bool didScriptedMovement = false; -#ifdef LOG_FRAME_TIMES - __int64 curTime64,freq64; - static __int64 prevTime64=0; - QueryPerformanceFrequency((LARGE_INTEGER *)&freq64); - QueryPerformanceCounter((LARGE_INTEGER *)&curTime64); - freq64 /= 1000; - - Int elapsedTimeMs = (curTime64 - prevTime64)/freq64; - prevTime64 = curTime64; - -#endif - -// Int elapsedTimeMs = TheW3DFrameLengthInMsec; // Assume a constant time flow. It just works out better. jba. - - if (TheTerrainRenderObject->doesNeedFullUpdate()) { - RefRenderObjListIterator *it = W3DDisplay::m_3DScene->createLightsIterator(); - TheTerrainRenderObject->updateCenter(m_3DCamera, it); - if (it) - { - W3DDisplay::m_3DScene->destroyLightsIterator(it); - it = NULL; - } - } - - static Real followFactor = -1; - ObjectID cameraLock = getCameraLock(); - if (cameraLock == INVALID_ID) - { - followFactor = -1; - } - if (cameraLock != INVALID_ID) - { - m_doingMoveCameraOnWaypointPath = false; - m_CameraArrivedAtWaypointOnPathFlag = false; - - Object* cameraLockObj = TheGameLogic->findObjectByID(cameraLock); - Bool loseLock = false; - - // check if object has been destroyed or is dead -> lose lock - if (cameraLockObj == NULL) - { - loseLock = true; - } -#if 0 - else - { - AIUpdateInterface *ai = cameraLockObj->getAIUpdateInterface(); - if (ai && ai->isDead()) - loseLock = true; - } -#endif - - - if (loseLock) - { - setCameraLock(INVALID_ID); - setCameraLockDrawable(NULL); - followFactor = -1; - } - else - { - if (followFactor<0) { - followFactor = 0.05f; - } else { - followFactor += 0.05f; - if (followFactor>1.0f) followFactor = 1.0f; - } - if (getCameraLockDrawable() != NULL) - { - Drawable* cameraLockDrawable = (Drawable *)getCameraLockDrawable(); - - if (!cameraLockDrawable) - { - setCameraLockDrawable(NULL); - } - else - { - Coord3D pos; - Real boundingSphereRadius; - Matrix3D transform; - // this method must ONLY be called from the client, NEVER From the logic, not even indirectly. - if (cameraLockDrawable->clientOnly_getFirstRenderObjInfo(&pos, &boundingSphereRadius, &transform)) - { - Vector3 zaxis(0,0,1); - - Vector3 objPos; - objPos.X = pos.x; - objPos.Y = pos.y; - objPos.Z = pos.z; - - //get position of top of object, assuming world z roughly along local z. - objPos += boundingSphereRadius * 1.0f * zaxis; - Vector3 objview = transform.Get_X_Vector(); //get view vector of object - //move camera back behind object far enough not to intersect bounding sphere - Vector3 camtran = objPos - objview * boundingSphereRadius*4.5f; - - Vector3 prevCamTran = m_3DCamera->Get_Position(); //get current camera position. - - Vector3 tranDiff = (camtran - prevCamTran); //vector old position to new position. - - camtran = prevCamTran + tranDiff * 0.1f; //slowly move camera to new position. - - Matrix3D camXForm; - camXForm.Look_At(camtran,objPos,0); - m_3DCamera->Set_Transform(camXForm); - - recalcCamera = false; //we already did it - } - } - } - else - { Coord3D objpos = *cameraLockObj->getPosition(); - Coord3D curpos = *getPosition(); - // don't "snap" directly to the pos, but move there smoothly. - Real snapThreshSqr = sqr(TheGlobalData->m_partitionCellSize); - Real curDistSqr = sqr(curpos.x - objpos.x) + sqr(curpos.y - objpos.y); - if ( m_snapImmediate) - { - // close enough. - curpos.x = objpos.x; - curpos.y = objpos.y; - } - else - { -// Real ratio = 1.0f - snapThreshSqr/curDistSqr; - Real dx = objpos.x-curpos.x; - Real dy = objpos.y-curpos.y; - if (m_lockType == LOCK_TETHER) - { - //snapThreshSqr = sqr( m_lockDist * TheGlobalData->m_partitionCellSize ); - if (curDistSqr >= snapThreshSqr) - { - Real ratio = 1.0f - snapThreshSqr/curDistSqr; - - // move halfway there. - curpos.x += dx*ratio*0.5f; - curpos.y += dy*ratio*0.5f; - } - else - { - // we're inside our 'play' tolerance. Move slowly to the obj - Real ratio = 0.01f * m_lockDist; - Real dx = objpos.x-curpos.x; - Real dy = objpos.y-curpos.y; - curpos.x += dx*ratio; - curpos.y += dy*ratio; - } - } - else - { - curpos.x += dx*followFactor; - curpos.y += dy*followFactor; - } - } - if (!(TheScriptEngine->isTimeFrozenDebug() || TheScriptEngine->isTimeFrozenScript()) && !TheGameLogic->isGamePaused()) { - m_previousLookAtPosition = *getPosition(); - } - setPosition(&curpos); - - if (m_lockType == LOCK_FOLLOW) - { - // camera follow objects if they are flying - if (cameraLockObj->isUsingAirborneLocomotor() && cameraLockObj->isAboveTerrainOrWater()) - { - Matrix3D camXForm; - Real oldZRot = m_angle; - Real idealZRot = cameraLockObj->getOrientation() - M_PI_2; - normAngle(oldZRot); - normAngle(idealZRot); - Real diff = idealZRot - oldZRot; - normAngle(diff); - - if (m_snapImmediate) - { - m_angle = idealZRot; - } - else - { - m_angle += diff * 0.1f; - } - normAngle(m_angle); - } - } - if (m_snapImmediate) - m_snapImmediate = FALSE; - - m_groundLevel = objpos.z; - didScriptedMovement = true; - recalcCamera = true; - } - } - } - - if (!(TheScriptEngine->isTimeFrozenDebug()/* || TheScriptEngine->isTimeFrozenScript()*/) && !TheGameLogic->isGamePaused()) { - // If we aren't frozen for debug, allow the camera to follow scripted movements. - if (updateCameraMovements()) { - didScriptedMovement = true; - recalcCamera = true; - } - } else { - if (m_doingRotateCamera || m_doingMoveCameraOnWaypointPath || m_doingPitchCamera || m_doingZoomCamera || m_doingScriptedCameraLock) { - didScriptedMovement = true; // don't mess up the scripted movement - } - } - // - // Process camera shake - // - if (m_shakeIntensity > 0.01f) - { - recalcCamera = true; - } - - //Process New C3 Camera Shaker system - if (CameraShakerSystem.IsCameraShaking()) - { - recalcCamera = true; - } - - /* - * In order to have the camera follow the terrain in a non-dizzying way, we will have a - * "desired height" value that the user sets. While scrolling, the actual height (set by - * zoom) will not get updated unless we are scrolling uphill and our view either goes - * underground or higher than the max allowed height. When the camera is at rest (not - * scrolling), the zoom will move toward matching the desired height. - */ - // TheSuperHackers @tweak Can now also zoom when the game is paused. - // TheSuperHackers @tweak The camera zoom speed is now decoupled from the render update. - // TheSuperHackers @bugfix The camera terrain height adjustment now also works in replay playback. - - m_terrainHeightUnderCamera = getHeightAroundPos(m_pos.x, m_pos.y); - m_currentHeightAboveGround = m_cameraOffset.z * m_zoom - m_terrainHeightUnderCamera; - - if (TheTerrainLogic && TheGlobalData && TheInGameUI && m_okToAdjustHeight) - { - Real desiredHeight = (m_terrainHeightUnderCamera + m_heightAboveGround); - Real desiredZoom = desiredHeight / m_cameraOffset.z; - - if (didScriptedMovement) - { - // if we are in a scripted camera movement, take its height above ground as our desired height. - m_heightAboveGround = m_currentHeightAboveGround; - //DEBUG_LOG(("Frame %d: height above ground: %g %g %g %g", TheGameLogic->getFrame(), m_heightAboveGround, - // m_cameraOffset.z, m_zoom, m_terrainHeightUnderCamera)); - } - - if (TheInGameUI->isScrolling()) - { - // if scrolling, only adjust if we're too close or too far - if (m_scrollAmount.length() < m_scrollAmountCutoff || (m_currentHeightAboveGround < m_minHeightAboveGround) || (TheGlobalData->m_enforceMaxCameraHeight && m_currentHeightAboveGround > m_maxHeightAboveGround)) - { - const Real fpsRatio = TheFramePacer->getBaseOverUpdateFpsRatio(); - const Real zoomAdj = (desiredZoom - m_zoom) * TheGlobalData->m_cameraAdjustSpeed * fpsRatio; - if (fabs(zoomAdj) >= 0.0001f) // only do positive - { - m_zoom += zoomAdj; - recalcCamera = true; - } - } - } - else if (!didScriptedMovement) - { - // we're not scrolling; settle toward desired height above ground - const Real fpsRatio = TheFramePacer->getBaseOverUpdateFpsRatio(); - const Real zoomAdj = (m_zoom - desiredZoom) * TheGlobalData->m_cameraAdjustSpeed * fpsRatio; - if (fabs(zoomAdj) >= 0.0001f) - { - m_zoom -= zoomAdj; - recalcCamera = true; - } - } - } - if (TheScriptEngine->isTimeFast()) { - return; // don't draw - makes it faster :) jba. - } - - // (gth) C&C3 if m_isCameraSlaved then force the camera to update each frame - if ((recalcCamera) || (m_isCameraSlaved)) { - setCameraTransform(); - } - - -#ifdef DO_SEISMIC_SIMULATIONS - // Give the terrain a chance to refresh animating (Seismic) regions, if any. - TheTerrainVisual->updateSeismicSimulations(); -#endif - - Region3D axisAlignedRegion; - getAxisAlignedViewRegion(axisAlignedRegion); - - // render all of the visible Drawables - /// @todo this needs to use a real region partition or something - TheGameClient->iterateDrawablesInRegion( &axisAlignedRegion, drawDrawable, NULL ); -} - -//------------------------------------------------------------------------------------------------- -/** Find region which contains all drawables in 3D space. */ -//------------------------------------------------------------------------------------------------- -void W3DView::getAxisAlignedViewRegion(Region3D &axisAlignedRegion) -{ - // - // get the 4 points in 3D space of the 4 corners of the view, we will use a z = 0.0f - // value so that we can get everything ... even stuff below the terrain - // - Coord3D box[ 4 ]; - getScreenCornerWorldPointsAtZ( &box[ 0 ], &box[ 1 ], &box[ 2 ], &box[ 3 ], 0.0f ); - - // - // take those 4 corners projected into the world and create an axis aligned bounding - // box, we will use this box to iterate the drawables in 3D space - // - axisAlignedRegion.lo = box[ 0 ]; - axisAlignedRegion.hi = box[ 0 ]; - for( Int i = 0; i < 4; i++ ) - { - - if( box[ i ].x < axisAlignedRegion.lo.x ) - axisAlignedRegion.lo.x = box[ i ].x; - if( box[ i ].y < axisAlignedRegion.lo.y ) - axisAlignedRegion.lo.y = box[ i ].y; - if( box[ i ].x > axisAlignedRegion.hi.x ) - axisAlignedRegion.hi.x = box[ i ].x; - if( box[ i ].y > axisAlignedRegion.hi.y ) - axisAlignedRegion.hi.y = box[ i ].y; - - } - - // low and high regions will be based of the extent of the map - Region3D mapExtent; - Real safeValue = 999999; - TheTerrainLogic->getExtent( &mapExtent ); - axisAlignedRegion.lo.z = mapExtent.lo.z - safeValue; - axisAlignedRegion.hi.z = mapExtent.hi.z + safeValue; - - // we want to overscan a little bit so that we get objects that are partially offscreen - axisAlignedRegion.lo.x -= (DRAWABLE_OVERSCAN + m_guardBandBias.x); - axisAlignedRegion.lo.y -= (DRAWABLE_OVERSCAN + m_guardBandBias.y + 60.0f ); - axisAlignedRegion.hi.x += (DRAWABLE_OVERSCAN + m_guardBandBias.x); - axisAlignedRegion.hi.y += (DRAWABLE_OVERSCAN + m_guardBandBias.y); - -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void W3DView::setFadeParameters(Int fadeFrames, Int direction) -{ - ScreenBWFilter::setFadeParameters(fadeFrames, direction); - ScreenCrossFadeFilter::setFadeParameters(fadeFrames,direction); -} - -void W3DView::set3DWireFrameMode(Bool enable) -{ - m_nextWireFrameEnabled = enable; -} - -//------------------------------------------------------------------------------------------------- -/** Sets the view filter mode. */ -//------------------------------------------------------------------------------------------------- -void W3DView::setViewFilterPos(const Coord3D *pos) -{ - ScreenMotionBlurFilter::setZoomToPos(pos); -} -//------------------------------------------------------------------------------------------------- -/** Sets the view filter mode. */ -//------------------------------------------------------------------------------------------------- -Bool W3DView::setViewFilterMode(FilterModes filterMode) -{ - FilterModes oldMode = m_viewFilterMode; //save previous mode in case setup fails. - - m_viewFilterMode = filterMode; - if (m_viewFilterMode != FM_NULL_MODE && - m_viewFilter != FT_NULL_FILTER) { - if (!W3DShaderManager::filterSetup(m_viewFilter, m_viewFilterMode)) - { //setup failed so restore previous mode. - m_viewFilterMode = oldMode; - return FALSE; - } - } - return TRUE; -} -//------------------------------------------------------------------------------------------------- -/** Sets the view filter. */ -//------------------------------------------------------------------------------------------------- -Bool W3DView::setViewFilter(FilterTypes filter) -{ - FilterTypes oldFilter = m_viewFilter; //save previous filter in case setup fails. - - m_viewFilter = filter; - if (m_viewFilterMode != FM_NULL_MODE && - m_viewFilter != FT_NULL_FILTER) { - if (!W3DShaderManager::filterSetup(m_viewFilter, m_viewFilterMode)) - { //setup failed so restore previous mode. - m_viewFilter = oldFilter; - return FALSE; - }; - } - return TRUE; -} - -//------------------------------------------------------------------------------------------------- -/** Calculates how many pixels we scrolled since last frame for motion blur calculations. */ -//------------------------------------------------------------------------------------------------- -void W3DView::calcDeltaScroll(Coord2D &screenDelta) -{ - screenDelta.x = 0; - screenDelta.y = 0; - Vector3 prevPos(m_previousLookAtPosition.x,m_previousLookAtPosition.y, m_groundLevel); - Vector3 prevScreen; - if (m_3DCamera->Project( prevScreen, prevPos ) != CameraClass::INSIDE_FRUSTUM) - { - return; - } - Vector3 pos(m_pos.x,m_pos.y, m_groundLevel); - Vector3 screen; - if (m_3DCamera->Project( screen, pos ) != CameraClass::INSIDE_FRUSTUM) - { - return; - } - screenDelta.x = screen.X-prevScreen.X; - screenDelta.y = screen.Y-prevScreen.Y; -} - - -//------------------------------------------------------------------------------------------------- -/** Draw member for the W3D window, this will literally draw the window - * for this view */ -//------------------------------------------------------------------------------------------------- -void W3DView::drawView( void ) -{ - DRAW(); -} - -//DECLARE_PERF_TIMER(W3DView_drawView) -void W3DView::draw( void ) -{ - //USE_PERF_TIMER(W3DView_drawView) - Bool skipRender = false; - Bool doExtraRender = false; - CustomScenePassModes customScenePassMode = SCENE_PASS_DEFAULT; - Bool preRenderResult = false; - - if (m_viewFilterMode && - m_viewFilter > FT_NULL_FILTER && - m_viewFilter < FT_MAX) - { - // Most likely will redirect rendering to a texture. - preRenderResult=W3DShaderManager::filterPreRender(m_viewFilter, skipRender, customScenePassMode); - if (!skipRender && getCameraLock()) - { - Object* cameraLockObj = TheGameLogic->findObjectByID(getCameraLock()); - if (cameraLockObj) - { - Drawable *drawable = cameraLockObj->getDrawable(); - drawable->setDrawableHidden(true); - } - } - } - - if (!skipRender) - { - // Render 3D scene from our camera - W3DDisplay::m_3DScene->setCustomPassMode(customScenePassMode); - if (m_isWireFrameEnabled) - W3DDisplay::m_3DScene->Set_Extra_Pass_Polygon_Mode(SceneClass::EXTRA_PASS_CLEAR_LINE); - W3DDisplay::m_3DScene->doRender( m_3DCamera ); - W3DDisplay::m_3DScene->Set_Extra_Pass_Polygon_Mode(SceneClass::EXTRA_PASS_DISABLE); - m_isWireFrameEnabled = m_nextWireFrameEnabled; - } - - if (m_viewFilterMode && - m_viewFilter > FT_NULL_FILTER && - m_viewFilter < FT_MAX) - { - Coord2D deltaScroll; - calcDeltaScroll(deltaScroll); - Bool continueTheEffect = false; - if (preRenderResult) //if prerender passed, do the post render. - continueTheEffect = W3DShaderManager::filterPostRender(m_viewFilter, m_viewFilterMode, deltaScroll,doExtraRender); - if (!skipRender && getCameraLock()) - { - Object* cameraLockObj = TheGameLogic->findObjectByID(getCameraLock()); - if (cameraLockObj) - { - Drawable *drawable = cameraLockObj->getDrawable(); - drawable->setDrawableHidden(false); - RenderInfoClass rinfo(*m_3DCamera); - // Apply the camera and viewport (including depth range) - m_3DCamera->Apply(); - TheDX8MeshRenderer.Set_Camera(&rinfo.Camera); - W3DDisplay::m_3DScene->renderSpecificDrawables(rinfo, 1, &drawable); - WW3D::Flush(rinfo); - } - } - if (!continueTheEffect) - { - // shut it down. - m_viewFilter = FT_VIEW_DEFAULT; - m_viewFilterMode = FM_VIEW_DEFAULT; - } - } - - //Some effects require that we render a modified version of the scene into a texture but also require - //an unaltered version in the framebuffer. So we re-render again into framebuffer after texture rendering - //was turned off by filterPostRender(). - if (doExtraRender) - { - //Reset to normal scene rendering. - //The pass that rendered into a texture may have left the z-buffer in a weird state - //so clear it before rendering normal scene. - ///@todo: Don't clear z-buffer unless shader uses z-bias or anything else that would cause <= z to fail on normal render. - DX8Wrapper::Clear(false, true, Vector3(0.0f,0.0f,0.0f), TheWaterTransparency->m_minWaterOpacity); // Clear z but not color - W3DDisplay::m_3DScene->setCustomPassMode(SCENE_PASS_DEFAULT); - W3DDisplay::m_3DScene->doRender( m_3DCamera ); - Coord2D deltaScroll; - W3DShaderManager::filterPostRender(m_viewFilter, m_viewFilterMode, deltaScroll, doExtraRender); - } - - if( TheGlobalData->m_debugAI ) - { - if (TheAI->pathfinder()->getDebugPath()) - { - // setup screen clipping region - IRegion2D clipRegion; - clipRegion.lo.x = 0; - clipRegion.lo.y = 0; - clipRegion.hi.x = getWidth(); - clipRegion.hi.y = getHeight(); - - UnsignedInt color = 0xFFFFFF00; //0xAARRGGBB - ICoord2D start, end; - PathNode *prevNode = TheAI->pathfinder()->getDebugPath()->getFirstNode(); - - if (worldToScreen( prevNode->getPosition(), &start )) { - TheDisplay->drawLine( start.x-3, start.y-3, start.x+3, start.y-3, 1.0f, color ); - TheDisplay->drawLine( start.x+3, start.y-3, start.x+3, start.y+3, 1.0f, color ); - TheDisplay->drawLine( start.x+3, start.y+3, start.x-3, start.y+3, 1.0f, color ); - TheDisplay->drawLine( start.x-3, start.y+3, start.x-3, start.y-3, 1.0f, color ); - } - for( PathNode *node = prevNode->getNext(); node; node = node->getNext() ) - { - Int k; - Coord3D s, e; - Coord3D delta; - s = *node->getPosition(); - e = *prevNode->getPosition(); - delta.x = e.x-s.x; - delta.y = e.y-s.y; - delta.z = e.z-s.z; - for (k = 0; k<10; k++) { - Real factor1 = (k)/10.0; - Real factor2 = (k+1)/10.0; - s = *node->getPosition(); - e = *node->getPosition(); - s.x += delta.x*factor1; - s.y += delta.y*factor1; - s.z += delta.z*factor1; - e.x += delta.x*factor2; - e.y += delta.y*factor2; - e.z += delta.z*factor2; - Bool onScreen1 = worldToScreen( &e, &end ); - Bool onScreen2 = worldToScreen( &s, &start ); - if (!onScreen1 && !onScreen2) { - continue; // neither point visible. - } - ICoord2D clipStart, clipEnd; - - if( ClipLine2D( &start, &end, &clipStart, &clipEnd, &clipRegion ) ) { - TheDisplay->drawLine( clipStart.x, clipStart.y, clipEnd.x, clipEnd.y, 1.0f, color ); - } - } - prevNode = node; - if (node->getNext()) { - if (worldToScreen( node->getPosition(), &start )) { - TheDisplay->drawLine( start.x-4, start.y, start.x+3, start.y, 1.0f, color ); - } - } - } - if (prevNode && worldToScreen( prevNode->getPosition(), &start )) { - TheDisplay->drawLine( start.x-4, start.y, start.x+3, start.y, 1.0f, color ); - TheDisplay->drawLine( start.x, start.y-4, start.x, start.y+3, 1.0f, color ); - } - color = 0xFFFF0000; //0xAARRGGBB - if (worldToScreen( TheAI->pathfinder()->getDebugPathPosition(), &start )) { - TheDisplay->drawLine( start.x-3, start.y, start.x+3, start.y, 1.0f, color ); - TheDisplay->drawLine( start.x, start.y-3, start.x, start.y+3, 1.0f, color ); - } - } - - } - -#if defined(RTS_DEBUG) - if( TheGlobalData->m_debugCamera ) - { - UnsignedInt c = 0xaaffffff; - Coord3D worldPos = *getPosition(); - worldPos.z = TheTerrainLogic->getGroundHeight(worldPos.x, worldPos.y); - - Coord3D p1, p2; - ICoord2D s1, s2; - p1 = worldPos; - p1.x += TERRAIN_SAMPLE_SIZE; - p1.y += TERRAIN_SAMPLE_SIZE; - p1.z = TheTerrainLogic->getGroundHeight(p1.x, p1.y); - p2 = worldPos; - p2.x += TERRAIN_SAMPLE_SIZE; - p2.y -= TERRAIN_SAMPLE_SIZE; - p2.z = TheTerrainLogic->getGroundHeight(p2.x, p2.y); - worldToScreen( &p1, &s1 ); - worldToScreen( &p2, &s2 ); - TheDisplay->drawLine(s1.x, s1.y, s2.x, s2.y, 1.0f, c); - - p1 = worldPos; - p1.x += TERRAIN_SAMPLE_SIZE; - p1.y -= TERRAIN_SAMPLE_SIZE; - p1.z = TheTerrainLogic->getGroundHeight(p1.x, p1.y); - p2 = worldPos; - p2.x -= TERRAIN_SAMPLE_SIZE; - p2.y -= TERRAIN_SAMPLE_SIZE; - p2.z = TheTerrainLogic->getGroundHeight(p2.x, p2.y); - worldToScreen( &p1, &s1 ); - worldToScreen( &p2, &s2 ); - TheDisplay->drawLine(s1.x, s1.y, s2.x, s2.y, 1.0f, c); - - p1 = worldPos; - p1.x -= TERRAIN_SAMPLE_SIZE; - p1.y -= TERRAIN_SAMPLE_SIZE; - p1.z = TheTerrainLogic->getGroundHeight(p1.x, p1.y); - p2 = worldPos; - p2.x -= TERRAIN_SAMPLE_SIZE; - p2.y += TERRAIN_SAMPLE_SIZE; - p2.z = TheTerrainLogic->getGroundHeight(p2.x, p2.y); - worldToScreen( &p1, &s1 ); - worldToScreen( &p2, &s2 ); - TheDisplay->drawLine(s1.x, s1.y, s2.x, s2.y, 1.0f, c); - - p1 = worldPos; - p1.x -= TERRAIN_SAMPLE_SIZE; - p1.y += TERRAIN_SAMPLE_SIZE; - p1.z = TheTerrainLogic->getGroundHeight(p1.x, p1.y); - p2 = worldPos; - p2.x += TERRAIN_SAMPLE_SIZE; - p2.y += TERRAIN_SAMPLE_SIZE; - p2.z = TheTerrainLogic->getGroundHeight(p2.x, p2.y); - worldToScreen( &p1, &s1 ); - worldToScreen( &p2, &s2 ); - TheDisplay->drawLine(s1.x, s1.y, s2.x, s2.y, 1.0f, c); - - } - - 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 // RTS_DEBUG - - Region3D axisAlignedRegion; - getAxisAlignedViewRegion(axisAlignedRegion); - - // - // there are several things we might want to do as a post pass on the objects after - // they are all drawn - /// @todo we might want to consider wiping this iterate out if there is nothing to post draw - // - TheGameClient->resetRenderedObjectCount(); - TheGameClient->iterateDrawablesInRegion( &axisAlignedRegion, drawablePostDraw, this ); - - TheGameClient->flushTextBearingDrawables(); - - // Render 2D scene - W3DDisplay::m_2DScene->doRender( m_2DCamera ); -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void W3DView::setCameraLock(ObjectID id) -{ - // If we're disabling camera movements, don't lock onto the object. - if (TheGlobalData->m_disableCameraMovement && id!=INVALID_ID) { - return; - } - View::setCameraLock(id); - m_doingScriptedCameraLock = FALSE; -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void W3DView::setSnapMode( CameraLockType lockType, Real lockDist ) -{ - View::setSnapMode(lockType, lockDist); - m_doingScriptedCameraLock = TRUE; -} - -//------------------------------------------------------------------------------------------------- -// Scroll the view by the given delta in SCREEN COORDINATES, this interface -// assumes we will be scrolling along the X,Y plane -// -// TheSuperHackers @bugfix Now rotates the view plane on the Z axis only to properly discard the -// camera pitch. The aspect ratio also no longer modifies the vertical scroll speed. -//------------------------------------------------------------------------------------------------- -void W3DView::scrollBy( Coord2D *delta ) -{ - // if we haven't moved, ignore - if( delta && (delta->x != 0 || delta->y != 0) ) - { - constexpr const Real SCROLL_RESOLUTION = 250.0f; - - Vector3 world, worldStart, worldEnd; - Vector2 start, end; - - m_scrollAmount = *delta; - - start.X = getWidth(); - start.Y = getHeight(); - - end.X = start.X + delta->x * SCROLL_RESOLUTION; - end.Y = start.Y + delta->y * SCROLL_RESOLUTION; - - m_3DCamera->Device_To_View_Space( start, &worldStart ); - m_3DCamera->Device_To_View_Space( end, &worldEnd ); - - const Real zRotation = m_3DCamera->Get_Transform().Get_Z_Rotation(); - worldStart.Rotate_Z(zRotation); - worldEnd.Rotate_Z(zRotation); - - world.X = worldEnd.X - worldStart.X; - world.Y = worldEnd.Y - worldStart.Y; - world.Z = worldEnd.Z - worldStart.Z; - - // scroll by delta - Coord3D pos = *getPosition(); - pos.x += world.X; - pos.y += world.Y; - //DEBUG_LOG(("Delta %.2f, %.2f", world.X, world.Z)); - // no change to z - setPosition(&pos); - - //m_cameraConstraintValid = false; // pos change does NOT invalidate cam constraints - - m_doingRotateCamera = false; - // set new camera position - setCameraTransform(); - - } - -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -void W3DView::forceRedraw() -{ - - // set the camera - setCameraTransform(); -} - -//------------------------------------------------------------------------------------------------- -/** Rotate the view around the up axis to the given angle. */ -//------------------------------------------------------------------------------------------------- -void W3DView::setAngle( Real angle ) -{ - // Normalize to +-PI. - normAngle(angle); - // call our base class, we are adding functionality - View::setAngle( angle ); - - - m_doingMoveCameraOnWaypointPath = false; - m_CameraArrivedAtWaypointOnPathFlag = false; - - m_doingRotateCamera = false; - m_doingPitchCamera = false; - m_doingZoomCamera = false; - m_doingScriptedCameraLock = false; - // set the camera - setCameraTransform(); -} - -//------------------------------------------------------------------------------------------------- -/** Rotate the view around the horizontal (X) axis to the given angle. */ -//------------------------------------------------------------------------------------------------- -void W3DView::setPitch( Real angle ) -{ - // call our base class, we are extending functionality - View::setPitch( angle ); - - - m_doingMoveCameraOnWaypointPath = false; - m_doingRotateCamera = false; - m_doingPitchCamera = false; - m_doingZoomCamera = false; - m_doingScriptedCameraLock = false; - // set the camera - setCameraTransform(); -} - -//------------------------------------------------------------------------------------------------- -/** Set the view angle & pitch back to default */ -//------------------------------------------------------------------------------------------------- -void W3DView::setAngleAndPitchToDefault( void ) -{ - // call our base class, we are adding functionality - View::setAngleAndPitchToDefault(); - - m_FXPitch = 1.0; - - // set the camera - setCameraTransform(); -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -void W3DView::setDefaultView(Real pitch, Real angle, Real maxHeight) -{ - // MDC - we no longer want to rotate maps (design made all of them right to begin with) - // m_defaultAngle = angle * M_PI/180.0f; - m_defaultPitchAngle = pitch; - m_maxHeightAboveGround = TheGlobalData->m_maxCameraHeight*maxHeight; - if (m_minHeightAboveGround > m_maxHeightAboveGround) - m_maxHeightAboveGround = m_minHeightAboveGround; -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -void W3DView::setHeightAboveGround(Real z) -{ - View::setHeightAboveGround(z); - - m_doingMoveCameraOnWaypointPath = false; - m_CameraArrivedAtWaypointOnPathFlag = false; - m_doingRotateCamera = false; - m_doingPitchCamera = false; - m_doingZoomCamera = false; - m_doingScriptedCameraLock = false; - m_cameraConstraintValid = false; // recalc it. - setCameraTransform(); -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -// TheSuperHackers @bugfix xezon 18/09/2025 setZoom is no longer clamped by a min and max zoom. -// Instead the min and max camera height will be clamped elsewhere. Clamping the zoom would cause -// issues with camera playback in replay playback where changes in terrain elevation would not raise -// the camera height. -void W3DView::setZoom(Real z) -{ - View::setZoom(z); - - m_doingMoveCameraOnWaypointPath = false; - m_CameraArrivedAtWaypointOnPathFlag = false; - m_doingRotateCamera = false; - m_doingPitchCamera = false; - m_doingZoomCamera = false; - m_doingScriptedCameraLock = false; - m_cameraConstraintValid = false; // recalc it. - setCameraTransform(); -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -void W3DView::setZoomToDefault( void ) -{ - // default zoom has to be max, otherwise players will just zoom to max always - - // terrain height + desired height offset == cameraOffset * actual zoom - // find best approximation of max terrain height we can see - Real terrainHeightMax = getHeightAroundPos(m_pos.x, m_pos.y); - - Real desiredHeight = (terrainHeightMax + m_maxHeightAboveGround); - Real desiredZoom = desiredHeight / m_cameraOffset.z; - - //DEBUG_LOG(("W3DView::setZoomToDefault() Current zoom: %g Desired zoom: %g", m_zoom, desiredZoom)); - - m_zoom = desiredZoom; - m_heightAboveGround = m_maxHeightAboveGround; - - m_doingMoveCameraOnWaypointPath = false; - m_CameraArrivedAtWaypointOnPathFlag = false; - m_doingRotateCamera = false; - m_doingPitchCamera = false; - m_doingZoomCamera = false; - m_doingScriptedCameraLock = false; - m_cameraConstraintValid = false; // recalc it. - setCameraTransform(); -} - -//------------------------------------------------------------------------------------------------- -/** Set the horizontal field of view angle */ -//------------------------------------------------------------------------------------------------- -void W3DView::setFieldOfView( Real angle ) -{ - View::setFieldOfView( angle ); - -#if defined(RTS_DEBUG) - // this is only for testing, and recalculating the - // camera every frame is wasteful - setCameraTransform(); -#endif -} - -//------------------------------------------------------------------------------------------------- -/** Using the W3D camera translate the world coordinate to a screen coord. - Screen coordinates returned in absolute values relative to full display resolution. - Returns if the point is on screen, off screen, or not transformable */ -//------------------------------------------------------------------------------------------------- -View::WorldToScreenReturn W3DView::worldToScreenTriReturn( const Coord3D *w, ICoord2D *s ) -{ - // sanity - if( w == NULL || s == NULL ) - return WTS_INVALID; - - if( m_3DCamera ) - { - Vector3 world; - Vector3 screen; - - world.Set( w->x, w->y, w->z ); - enum CameraClass::ProjectionResType projection = m_3DCamera->Project( screen, world ); - if (projection != CameraClass::INSIDE_FRUSTUM && projection!=CameraClass::OUTSIDE_FRUSTUM) - { - // Can't get a valid number if it's beyond the clip planes. jba - s->x = 0; - s->y = 0; - return WTS_INVALID; - } - - // - // note that the screen coord returned from the project W3D camera - // gave us a screen coords that range from (-1,-1) bottom left to - // (1,1) top right ... we are turning that into (0,0) upper left - // coords now - // - W3DLogicalScreenToPixelScreen( screen.X, screen.Y, - &s->x, &s->y, - getWidth(), getHeight()); - s->x += m_originX; //convert viewport coordinates to full screen coordinates - s->y += m_originY; - -// s->x = (getWidth() * (screen.X + 1.0f)) / 2.0f; -// s->y = (getHeight() * (-screen.Y + 1.0f)) / 2.0f; - if (projection != CameraClass::INSIDE_FRUSTUM) - { - return WTS_OUTSIDE_FRUSTUM; - } - - return WTS_INSIDE_FRUSTUM; - - } - - return WTS_INVALID; -} - -//------------------------------------------------------------------------------------------------- -/** Using the W3D camera translate the screen coord to world coord */ -//------------------------------------------------------------------------------------------------- -void W3DView::screenToWorld( const ICoord2D *s, Coord3D *w ) -{ - - // sanity - if( s == NULL || w == NULL ) - return; - - if( m_3DCamera ) - { - DEBUG_CRASH(("implement me")); - } - -} - -//------------------------------------------------------------------------------------------------- -/** all the drawables in the view, that fall within the 2D screen region - * will call the callback function. The number of drawables that passed - * the test are returned. - Screen coordinates assumed in absolute values relative to full display resolution. */ -//------------------------------------------------------------------------------------------------- -Int W3DView::iterateDrawablesInRegion( IRegion2D *screenRegion, - Bool (*callback)( Drawable *draw, void *userData ), - void *userData ) -{ - Bool inside = FALSE; - Int count = 0; - Drawable *draw; - Vector3 screen, world; - Coord3D pos; - Region2D normalizedRegion; - - /** @todo we need to have partitions of which drawables are in the - view so we don't have to march through the whole list */ - - // - // to do this we are projecting the drawable centers onto the screen, - // the W3D camera->project method is used to do this and that method - // will return normalized screen coords from (-1,-1) bottom left to - // (1,1) top right, normalize our screen region for comparison - // - /// @todo use fast int->real type casts here later - - Bool regionIsPoint = FALSE; - - if( screenRegion ) - { - if (screenRegion->height() == 0 && screenRegion->width() == 0) - { - regionIsPoint = TRUE; - } - - normalizedRegion.lo.x = ((Real)(screenRegion->lo.x - m_originX) / (Real)getWidth()) * 2.0f - 1.0f; - normalizedRegion.lo.y = -(((Real)(screenRegion->hi.y - m_originY) / (Real)getHeight()) * 2.0f - 1.0f); - normalizedRegion.hi.x = ((Real)(screenRegion->hi.x - m_originX) / (Real)getWidth()) * 2.0f - 1.0f; - normalizedRegion.hi.y = -(((Real)(screenRegion->lo.y - m_originY) / (Real)getHeight()) * 2.0f - 1.0f); - - } - - - Drawable *onlyDrawableToTest = NULL; - if (regionIsPoint) - { - // Allow all drawables to be picked. - onlyDrawableToTest = pickDrawable(&screenRegion->lo, TRUE, (PickType) getPickTypesForContext(TheInGameUI->isInForceAttackMode())); - if (onlyDrawableToTest == NULL) { - return 0; - } - } - - for( draw = TheGameClient->firstDrawable(); - draw; - draw = draw->getNextDrawable() ) - { - if (onlyDrawableToTest) - { - draw = onlyDrawableToTest; - inside = TRUE; - } - else - { - - // not inside - inside = FALSE; - - // no screen region, means all drawbles - if( screenRegion == NULL ) - inside = TRUE; - else - { - - // project the center of the drawable to the screen - /// @todo use a real 3D position in the drawable - pos = *draw->getPosition(); - world.X = pos.x; - world.Y = pos.y; - world.Z = pos.z; - - // project the world point to the screen - if( m_3DCamera->Project( screen, world ) == CameraClass::INSIDE_FRUSTUM && - screen.X >= normalizedRegion.lo.x && - screen.X <= normalizedRegion.hi.x && - screen.Y >= normalizedRegion.lo.y && - screen.Y <= normalizedRegion.hi.y ) - { - - inside = TRUE; - - } - } - - } - - // if inside do the callback and count up - if( inside ) - { - - if( callback( draw, userData ) ) - ++count; - - } - - // If onlyDrawableToTest, then we should bail out now. - if (onlyDrawableToTest != NULL) - break; - - } - - return count; - -} - -//------------------------------------------------------------------------------------------------- -/** cast a ray from the screen coords into the scene and return a drawable - * there if present. Screen coordinates assumed in absolute values relative - * to full display resolution. */ -//------------------------------------------------------------------------------------------------- -Drawable *W3DView::pickDrawable( const ICoord2D *screen, Bool forceAttack, PickType pickType ) -{ - RenderObjClass *renderObj = NULL; - Drawable *draw = NULL; - DrawableInfo *drawInfo = NULL; - - // sanity - if( screen == NULL ) - return NULL; - - // don't pick a drawable if there is a window under the cursor - GameWindow *window = NULL; - if (TheWindowManager) - window = TheWindowManager->getWindowUnderCursor(screen->x, screen->y); - - while (window) - { - // check to see if it or any of its parents are opaque. If so, we can't select anything. - if (!BitIsSet( window->winGetStatus(), WIN_STATUS_SEE_THRU )) - return NULL; - - window = window->winGetParent(); - } - - Vector3 rayStart,rayEnd; - getPickRay(screen,&rayStart,&rayEnd); - - LineSegClass lineseg; - lineseg.Set(rayStart,rayEnd); - - CastResultStruct result; - - if (forceAttack) - result.ComputeContactPoint = true; - - //Don't check against translucent or hidden objects - RayCollisionTestClass raytest(lineseg,&result,COLL_TYPE_ALL,false,false); - - if( W3DDisplay::m_3DScene->castRay( raytest, false, (Int)pickType ) ) - renderObj = raytest.CollidedRenderObj; - - // for right now there is no drawable data in a render object which is // if we've found a render object, return our drawable associated with it, - - // the terrain, therefore the userdata is NULL - /// @todo terrain and picking! - if( renderObj ) - drawInfo = (DrawableInfo *)renderObj->Get_User_Data(); - if (drawInfo) - draw=drawInfo->m_drawable; - - return draw; - -} - -//------------------------------------------------------------------------------------------------- -/** convert a pixel (x,y) to a location in the world on the terrain. - Screen coordinates assumed in absolute values relative to full display resolution. */ -//------------------------------------------------------------------------------------------------- -void W3DView::screenToTerrain( const ICoord2D *screen, Coord3D *world ) -{ - // sanity - if( screen == NULL || world == NULL || TheTerrainRenderObject == NULL ) - return; - - if (m_cameraHasMovedSinceRequest) { - m_locationRequests.clear(); - m_cameraHasMovedSinceRequest = false; - } - - if (m_locationRequests.size() > MAX_REQUEST_CACHE_SIZE) { - m_locationRequests.erase(m_locationRequests.begin(), m_locationRequests.begin() + 10); - } - - - // We insert them at the end for speed (no copies needed), but using the princ of locality, we should - // start searching where we most recently inserted - for (int i = m_locationRequests.size() - 1; i >= 0; --i) { - if (m_locationRequests[i].first.x == screen->x && m_locationRequests[i].first.y == screen->y) { - (*world) = m_locationRequests[i].second; - return; - } - } - - Vector3 rayStart,rayEnd; - LineSegClass lineseg; - CastResultStruct result; - Vector3 intersection(0,0,0); - - getPickRay(screen,&rayStart,&rayEnd); - - lineseg.Set(rayStart,rayEnd); - - RayCollisionTestClass raytest(lineseg,&result); - - if( TheTerrainRenderObject->Cast_Ray(raytest) ) - { - // get the point of intersection according to W3D - intersection = result.ContactPoint; - - } - - // Pick bridges. - Vector3 bridgePt; - Drawable *bridge = TheTerrainLogic->pickBridge(rayStart, rayEnd, &bridgePt); - if (bridge && bridgePt.Z > intersection.Z) { - intersection = bridgePt; - } - - world->x = intersection.X; - world->y = intersection.Y; - world->z = intersection.Z; - - PosRequest req; - req.first = (*screen); - req.second = (*world); - m_locationRequests.push_back(req); // Insert this request at the end, requires no extra copies - -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -void W3DView::lookAt( const Coord3D *o ) -{ - Coord3D pos = *o; - - -// no, don't call the super-lookAt, since it will munge our coords -// as for a 2d view. just call setPosition. -//View::lookAt(&pos); - - if (o->z > PATHFIND_CELL_SIZE_F+TheTerrainLogic->getGroundHeight(pos.x, pos.y)) { - // Pos.z is not used, so if we want to look at something off the ground, - // we have to look at the spot on the ground such that the object intersects - // with the look at vector in the center of the screen. jba. - Vector3 rayStart,rayEnd; - LineSegClass lineseg; - CastResultStruct result; - Vector3 intersection(0,0,0); - - rayStart = m_3DCamera->Get_Position(); //get camera location - m_3DCamera->Un_Project(rayEnd,Vector2(0.0f,0.0f)); //get world space point - rayEnd -= rayStart; //vector camera to world space point - rayEnd.Normalize(); //make unit vector - rayEnd *= m_3DCamera->Get_Depth(); //adjust length to reach far clip plane - rayStart.Set(pos.x, pos.y, pos.z); - rayEnd += rayStart; //get point on far clip plane along ray from camera. - lineseg.Set(rayStart,rayEnd); - - RayCollisionTestClass raytest(lineseg,&result); - - if( TheTerrainRenderObject->Cast_Ray(raytest) ) - { - // get the point of intersection according to W3D - pos.x = result.ContactPoint.X; - pos.y = result.ContactPoint.Y; - - } - } - pos.z = 0; - setPosition(&pos); - m_doingRotateCamera = false; - m_doingMoveCameraOnWaypointPath = false; - m_CameraArrivedAtWaypointOnPathFlag = false; - m_doingScriptedCameraLock = false; - - setCameraTransform(); - -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -void W3DView::initHeightForMap( void ) -{ - m_groundLevel = TheTerrainLogic->getGroundHeight(m_pos.x, m_pos.y); - const Real MAX_GROUND_LEVEL = 120.0; // jba - starting ground level can't exceed this height. - if (m_groundLevel>MAX_GROUND_LEVEL) { - m_groundLevel = MAX_GROUND_LEVEL; - } - - m_cameraOffset.z = m_groundLevel+TheGlobalData->m_cameraHeight; - m_cameraOffset.y = -(m_cameraOffset.z / tan(TheGlobalData->m_cameraPitch * (PI / 180.0))); - m_cameraOffset.x = -(m_cameraOffset.y * tan(TheGlobalData->m_cameraYaw * (PI / 180.0))); - m_cameraConstraintValid = false; // possible ground level change invalidates cam constraints - setCameraTransform(); - -} - -//------------------------------------------------------------------------------------------------- -/** Move camera to in an interesting fashion. Sets up parameters that get - * evaluated in draw(). */ -//------------------------------------------------------------------------------------------------- -void W3DView::moveCameraTo(const Coord3D *o, Int milliseconds, Int shutter, Bool orient, Real easeIn, Real easeOut) -{ - m_mcwpInfo.waypoints[0] = *getPosition(); - m_mcwpInfo.cameraAngle[0] = getAngle(); - m_mcwpInfo.waySegLength[0] = 0; - - m_mcwpInfo.waypoints[1] = *getPosition(); - m_mcwpInfo.waySegLength[1] = 0; - - m_mcwpInfo.waypoints[2] = *o; - m_mcwpInfo.waySegLength[2] = 0; - - m_mcwpInfo.numWaypoints = 2; - if (milliseconds<1) milliseconds = 1; - m_mcwpInfo.totalTimeMilliseconds = milliseconds; - m_mcwpInfo.shutter = 1; - m_mcwpInfo.ease.setEaseTimes(easeIn/milliseconds, easeOut/milliseconds); - m_mcwpInfo.curSegment = 1; - m_mcwpInfo.curSegDistance = 0; - m_mcwpInfo.totalDistance = 0; - - setupWaypointPath(orient); - if (m_mcwpInfo.totalTimeMilliseconds==1) { - // do it instantly. - moveAlongWaypointPath(1); - m_doingMoveCameraOnWaypointPath = true; - m_CameraArrivedAtWaypointOnPathFlag = false; - } -} - -//------------------------------------------------------------------------------------------------- -/** Rotate the camera */ -//------------------------------------------------------------------------------------------------- -void W3DView::rotateCamera(Real rotations, Int milliseconds, Real easeIn, Real easeOut) -{ - m_rcInfo.numHoldFrames = 0; - m_rcInfo.trackObject = FALSE; - - if (milliseconds<1) milliseconds = 1; - m_rcInfo.numFrames = milliseconds/TheW3DFrameLengthInMsec; - if (m_rcInfo.numFrames < 1) { - m_rcInfo.numFrames = 1; - } - m_rcInfo.curFrame = 0; - m_doingRotateCamera = true; - m_rcInfo.angle.startAngle = m_angle; - m_rcInfo.angle.endAngle = m_angle + 2*PI*rotations; - m_rcInfo.startTimeMultiplier = m_timeMultiplier; - m_rcInfo.endTimeMultiplier = m_timeMultiplier; - m_rcInfo.ease.setEaseTimes(easeIn/milliseconds, easeOut/milliseconds); - - m_doingMoveCameraOnWaypointPath = false; - m_CameraArrivedAtWaypointOnPathFlag = false; -} - -//------------------------------------------------------------------------------------------------- -/** Rotate the camera to follow a unit */ -//------------------------------------------------------------------------------------------------- -void W3DView::rotateCameraTowardObject(ObjectID id, Int milliseconds, Int holdMilliseconds, Real easeIn, Real easeOut) -{ - m_rcInfo.trackObject = TRUE; - if (holdMilliseconds<1) holdMilliseconds = 0; - m_rcInfo.numHoldFrames = holdMilliseconds/TheW3DFrameLengthInMsec; - if (m_rcInfo.numHoldFrames < 1) { - m_rcInfo.numHoldFrames = 0; - } - - if (milliseconds<1) milliseconds = 1; - m_rcInfo.numFrames = milliseconds/TheW3DFrameLengthInMsec; - if (m_rcInfo.numFrames < 1) { - m_rcInfo.numFrames = 1; - } - m_rcInfo.curFrame = 0; - m_doingRotateCamera = true; - m_rcInfo.target.targetObjectID = id; - m_rcInfo.startTimeMultiplier = m_timeMultiplier; - m_rcInfo.endTimeMultiplier = m_timeMultiplier; - m_rcInfo.ease.setEaseTimes(easeIn/milliseconds, easeOut/milliseconds); - - m_doingMoveCameraOnWaypointPath = false; - m_CameraArrivedAtWaypointOnPathFlag = false; -} - -//------------------------------------------------------------------------------------------------- -/** Rotate camera to face a location */ -//------------------------------------------------------------------------------------------------- -void W3DView::rotateCameraTowardPosition(const Coord3D *pLoc, Int milliseconds, Real easeIn, Real easeOut, Bool reverseRotation) -{ - m_rcInfo.numHoldFrames = 0; - m_rcInfo.trackObject = FALSE; - - if (milliseconds<1) milliseconds = 1; - m_rcInfo.numFrames = milliseconds/TheW3DFrameLengthInMsec; - if (m_rcInfo.numFrames < 1) { - m_rcInfo.numFrames = 1; - } - Coord3D curPos = *getPosition(); - Vector2 dir(pLoc->x-curPos.x, pLoc->y-curPos.y); - const Real dirLength = dir.Length(); - if (dirLength<0.1f) return; - Real angle = WWMath::Acos(dir.X/dirLength); - if (dir.Y<0.0f) { - angle = -angle; - } - // Default camera is rotated 90 degrees, so match. - angle -= PI/2; - normAngle(angle); - - if (reverseRotation) { - if (m_angle < angle) { - angle -= 2.0f*WWMATH_PI; - } else { - angle += 2.0f*WWMATH_PI; - } - } - - m_rcInfo.curFrame = 0; - m_doingRotateCamera = true; - m_rcInfo.angle.startAngle = m_angle; - // TheSuperHackers @todo Investigate whether the non Generals code is correct for Zero Hour. - // It certainly is incorrect for Generals: Seen in GLA mission 1 opening cut scene. -#if RTS_GENERALS - m_rcInfo.angle.endAngle = m_angle + angle; -#else - m_rcInfo.angle.endAngle = angle; -#endif - m_rcInfo.startTimeMultiplier = m_timeMultiplier; - m_rcInfo.endTimeMultiplier = m_timeMultiplier; - m_rcInfo.ease.setEaseTimes(easeIn/milliseconds, easeOut/milliseconds); - - m_doingMoveCameraOnWaypointPath = false; - m_CameraArrivedAtWaypointOnPathFlag = false; -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -void W3DView::zoomCamera( Real finalZoom, Int milliseconds, Real easeIn, Real easeOut ) -{ - if (milliseconds<1) milliseconds = 1; - m_zcInfo.numFrames = milliseconds/TheW3DFrameLengthInMsec; - if (m_zcInfo.numFrames < 1) { - m_zcInfo.numFrames = 1; - } - m_zcInfo.curFrame = 0; - m_doingZoomCamera = TRUE; - m_zcInfo.startZoom = m_zoom; - m_zcInfo.endZoom = finalZoom; - m_zcInfo.ease.setEaseTimes(easeIn/milliseconds, easeOut/milliseconds); -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -void W3DView::pitchCamera( Real finalPitch, Int milliseconds, Real easeIn, Real easeOut ) -{ - if (milliseconds<1) milliseconds = 1; - m_pcInfo.numFrames = milliseconds/TheW3DFrameLengthInMsec; - if (m_pcInfo.numFrames < 1) { - m_pcInfo.numFrames = 1; - } - m_pcInfo.curFrame = 0; - m_doingPitchCamera = TRUE; - m_pcInfo.startPitch = m_FXPitch; - m_pcInfo.endPitch = finalPitch; - m_pcInfo.ease.setEaseTimes(easeIn/milliseconds, easeOut/milliseconds); -} - -//------------------------------------------------------------------------------------------------- -/** Sets the final zoom for a camera movement. */ -//------------------------------------------------------------------------------------------------- -void W3DView::cameraModFinalZoom( Real finalZoom, Real easeIn, Real easeOut ) -{ - - if (m_doingRotateCamera) - { - Real terrainHeightMax = getHeightAroundPos(m_pos.x, m_pos.y); - Real maxHeight = (terrainHeightMax + m_maxHeightAboveGround); - Real maxZoom = maxHeight / m_cameraOffset.z; - - Real time = (m_rcInfo.numFrames + m_rcInfo.numHoldFrames - m_rcInfo.curFrame)*TheW3DFrameLengthInMsec; - zoomCamera( finalZoom*maxZoom, time, time*easeIn, time*easeOut ); - } - if (m_doingMoveCameraOnWaypointPath) - { - Coord3D pos = m_mcwpInfo.waypoints[m_mcwpInfo.numWaypoints]; - Real terrainHeightMax = getHeightAroundPos(pos.x, pos.y); - Real maxHeight = (terrainHeightMax + m_maxHeightAboveGround); - Real maxZoom = maxHeight / m_cameraOffset.z; - - Real time = m_mcwpInfo.totalTimeMilliseconds - m_mcwpInfo.elapsedTimeMilliseconds; - zoomCamera( finalZoom*maxZoom, time, time*easeIn, time*easeOut ); - } -} - -//------------------------------------------------------------------------------------------------- -/** Sets the final zoom for a camera movement. */ -//------------------------------------------------------------------------------------------------- -void W3DView::cameraModFreezeAngle(void) -{ - if (m_doingRotateCamera) { - if (m_rcInfo.trackObject) { - m_rcInfo.target.targetObjectID = INVALID_ID; - } else { - m_rcInfo.angle.startAngle = m_rcInfo.angle.endAngle = m_angle; // Silly, but consistent. - } - } - if (m_doingMoveCameraOnWaypointPath) { - Int i; -// Real curDistance = 0; - for (i=0; ix-result.x, pLoc->y-result.y); - const Real dirLength = dir.Length(); - if (dirLength<0.1f) continue; - Real angle = WWMath::Acos(dir.X/dirLength); - if (dir.Y<0.0f) { - angle = -angle; - } - // Default camera is rotated 90 degrees, so match. - angle -= PI/2; - normAngle(angle); - m_mcwpInfo.cameraAngle[i] = angle; - } - if (m_mcwpInfo.totalTimeMilliseconds==1) { - // do it instantly. - moveAlongWaypointPath(1); - m_doingMoveCameraOnWaypointPath = true; - m_CameraArrivedAtWaypointOnPathFlag = false; - } - } -} - -// ------------------------------------------------------------------------------------------------ -/** Sets the look toward point for the end of a camera movement. */ -// ------------------------------------------------------------------------------------------------ -void W3DView::cameraModFinalMoveTo(Coord3D *pLoc) -{ - if (m_doingRotateCamera) { - return; // Doesn't apply to rotate about a point. - } - if (m_doingMoveCameraOnWaypointPath) { - Int i; - Coord3D start, delta; - start = m_mcwpInfo.waypoints[m_mcwpInfo.numWaypoints]; - delta.x = pLoc->x - start.x; - delta.y = pLoc->y - start.y; - for (i=2; i<=m_mcwpInfo.numWaypoints; i++) { - Coord3D result = m_mcwpInfo.waypoints[i]; - result.x += delta.x; - result.y += delta.y; - m_mcwpInfo.waypoints[i] = result; - } - } -} - -// ------------------------------------------------------------------------------------------------ -/** Sets the look toward point for the end of a camera movement. */ -// ------------------------------------------------------------------------------------------------ -void W3DView::cameraModFinalLookToward(Coord3D *pLoc) -{ - if (m_doingRotateCamera) { - return; // Doesn't apply to rotate about a point. - } - if (m_doingMoveCameraOnWaypointPath) { - Int i; - Int min = m_mcwpInfo.numWaypoints-1; - if (min<2) min=2; -// Real curDistance = 0; - for (i=min; i<=m_mcwpInfo.numWaypoints; i++) { - Coord3D start, mid, end; - Real factor = 0.5; - start = m_mcwpInfo.waypoints[i-1]; - start.x += m_mcwpInfo.waypoints[i].x; - start.y += m_mcwpInfo.waypoints[i].y; - start.x /= 2; - start.y /= 2; - mid = m_mcwpInfo.waypoints[i]; - end = m_mcwpInfo.waypoints[i]; - end.x += m_mcwpInfo.waypoints[i+1].x; - end.y += m_mcwpInfo.waypoints[i+1].y; - end.x /= 2; - end.y /= 2; - Coord3D result = start; - result.x += factor*(end.x-start.x); - result.y += factor*(end.y-start.y); - result.x += (1-factor)*factor*(mid.x-end.x + mid.x-start.x); - result.y += (1-factor)*factor*(mid.y-end.y + mid.y-start.y); - result.z = 0; - Vector2 dir(pLoc->x-result.x, pLoc->y-result.y); - const Real dirLength = dir.Length(); - if (dirLength<0.1f) continue; - Real angle = WWMath::Acos(dir.X/dirLength); - if (dir.Y<0.0f) { - angle = -angle; - } - // Default camera is rotated 90 degrees, so match. - angle -= PI/2; - normAngle(angle); - if (i==m_mcwpInfo.numWaypoints) { - m_mcwpInfo.cameraAngle[i] = angle; - } else { - Real deltaAngle = angle - m_mcwpInfo.cameraAngle[i]; - normAngle(deltaAngle); - angle = m_mcwpInfo.cameraAngle[i] + deltaAngle/2; - normAngle(angle); - m_mcwpInfo.cameraAngle[i] = angle; - } - } - } -} - -// ------------------------------------------------------------------------------------------------ -/** Sets the final time multiplier for a camera movement. */ -// ------------------------------------------------------------------------------------------------ -void W3DView::cameraModFinalTimeMultiplier(Int finalMultiplier) -{ - if (m_doingZoomCamera) - m_zcInfo.endTimeMultiplier = finalMultiplier; - if (m_doingPitchCamera) - m_pcInfo.endTimeMultiplier = finalMultiplier; - if (m_doingRotateCamera) { - m_rcInfo.endTimeMultiplier = finalMultiplier; - } else if (m_doingMoveCameraOnWaypointPath) { - Int i; - Real curDistance = 0; - for (i=0; ix, location->y); - Real desiredHeight = (terrainHeightMax + m_maxHeightAboveGround); - Real desiredZoom = desiredHeight / m_cameraOffset.z; - - zoomCamera( desiredZoom, milliseconds, easeIn, easeOut ); // this isn't right... or is it? - - pitchCamera( 1.0, milliseconds, easeIn, easeOut ); - // pitchCamera( m_defaultPitchAngle, milliseconds, easeIn, easeOut ); - //DEBUG_LOG(("W3DView::resetCamera() Current zoom: %g Desired zoom: %g Current pitch: %g Desired pitch: %g", - // m_zoom, desiredZoom, m_pitchAngle, m_defaultPitchAngle)); -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -Bool W3DView::isCameraMovementFinished(void) -{ - if (m_viewFilter == FT_VIEW_MOTION_BLUR_FILTER) { - // Several of the motion blur effects are similar to camera movements. - if (m_viewFilterMode == FM_VIEW_MB_IN_AND_OUT_ALPHA || - m_viewFilterMode == FM_VIEW_MB_IN_AND_OUT_SATURATE || - m_viewFilterMode == FM_VIEW_MB_IN_ALPHA || - m_viewFilterMode == FM_VIEW_MB_OUT_ALPHA || - m_viewFilterMode == FM_VIEW_MB_IN_SATURATE || - m_viewFilterMode == FM_VIEW_MB_OUT_SATURATE ) { - return true; - } - } - return !m_doingMoveCameraOnWaypointPath && !m_doingRotateCamera && !m_doingPitchCamera && !m_doingZoomCamera; -} - - -Bool W3DView::isCameraMovementAtWaypointAlongPath(void) -{ - // WWDEBUG_SAY((( "MBL: Polling W3DView::isCameraMovementAtWaypointAlongPath" ))); - - Bool return_value = m_CameraArrivedAtWaypointOnPathFlag; - #pragma message( "MBL: Clearing variable after polling - for scripting - see Adam.\n" ) - m_CameraArrivedAtWaypointOnPathFlag = false; - return( return_value ); -} - -// ------------------------------------------------------------------------------------------------ -/** Move camera along a waypoint path in an interesting fashion. Sets up parameters that get - * evaluated in draw(). */ - // ------------------------------------------------------------------------------------------------ -void W3DView::moveCameraAlongWaypointPath(Waypoint *pWay, Int milliseconds, Int shutter, Bool orient, Real easeIn, Real easeOut) -{ - const Real MIN_DELTA = MAP_XY_FACTOR; - - m_mcwpInfo.waypoints[0] = *getPosition(); - m_mcwpInfo.cameraAngle[0] = getAngle(); - m_mcwpInfo.waySegLength[0] = 0; - m_mcwpInfo.waypoints[1] = *getPosition(); - m_mcwpInfo.numWaypoints = 1; - if (milliseconds<1) milliseconds = 1; - m_mcwpInfo.totalTimeMilliseconds = milliseconds; - m_mcwpInfo.shutter = shutter/TheW3DFrameLengthInMsec; - if (m_mcwpInfo.shutter<1) m_mcwpInfo.shutter = 1; - m_mcwpInfo.ease.setEaseTimes(easeIn/milliseconds, easeOut/milliseconds); - - while (pWay && m_mcwpInfo.numWaypoints getLocation(); - if (pWay->getNumLinks()>0) { - pWay = pWay->getLink(0); - } else { - pWay = NULL; - } - Vector2 dir(m_mcwpInfo.waypoints[m_mcwpInfo.numWaypoints].x-m_mcwpInfo.waypoints[m_mcwpInfo.numWaypoints-1].x, m_mcwpInfo.waypoints[m_mcwpInfo.numWaypoints].y-m_mcwpInfo.waypoints[m_mcwpInfo.numWaypoints-1].y); - if (dir.Length()1; i--) { - m_mcwpInfo.cameraAngle[i] = (m_mcwpInfo.cameraAngle[i] + m_mcwpInfo.cameraAngle[i-1]) / 2; - } - m_mcwpInfo.waySegLength[m_mcwpInfo.numWaypoints+1] = m_mcwpInfo.waySegLength[m_mcwpInfo.numWaypoints]; - - // Prevent a possible divide by zero. - if (m_mcwpInfo.totalDistance<1.0) { - m_mcwpInfo.waySegLength[m_mcwpInfo.numWaypoints-1] += 1.0-m_mcwpInfo.totalDistance; - m_mcwpInfo.totalDistance = 1.0; - } - - Real curDistance = 0; - Coord3D finalPos = m_mcwpInfo.waypoints[m_mcwpInfo.numWaypoints]; - Real newGround = TheTerrainLogic->getGroundHeight(finalPos.x, finalPos.y); - for (i=0; i<=m_mcwpInfo.numWaypoints+1; i++) { - Real factor2 = curDistance / m_mcwpInfo.totalDistance; - Real factor1 = 1.0-factor2; - m_mcwpInfo.timeMultiplier[i] = m_timeMultiplier; - m_mcwpInfo.groundHeight[i] = m_groundLevel*factor1 + newGround*factor2; - curDistance += m_mcwpInfo.waySegLength[i]; - //DEBUG_LOG(("New Index %d, angle %.2f", i, m_mcwpInfo.cameraAngle[i]*180/PI)); - } - - // Pad the end. - m_mcwpInfo.waypoints[m_mcwpInfo.numWaypoints+1] = m_mcwpInfo.waypoints[m_mcwpInfo.numWaypoints]; - Coord3D cur = m_mcwpInfo.waypoints[m_mcwpInfo.numWaypoints]; - Coord3D prev = m_mcwpInfo.waypoints[m_mcwpInfo.numWaypoints-1]; - m_mcwpInfo.waypoints[m_mcwpInfo.numWaypoints+1].x += cur.x-prev.x; - m_mcwpInfo.waypoints[m_mcwpInfo.numWaypoints+1].y += cur.y-prev.y; - m_mcwpInfo.cameraAngle[m_mcwpInfo.numWaypoints+1] = m_mcwpInfo.cameraAngle[m_mcwpInfo.numWaypoints]; - m_mcwpInfo.groundHeight[m_mcwpInfo.numWaypoints+1] = newGround; - - - cur = m_mcwpInfo.waypoints[2]; - prev = m_mcwpInfo.waypoints[1]; - m_mcwpInfo.waypoints[0].x -= cur.x-prev.x; - m_mcwpInfo.waypoints[0].y -= cur.y-prev.y; - - m_doingMoveCameraOnWaypointPath = m_mcwpInfo.numWaypoints>1; - m_CameraArrivedAtWaypointOnPathFlag = false; - m_doingRotateCamera = false; - - m_mcwpInfo.elapsedTimeMilliseconds = 0; - m_mcwpInfo.curShutter = m_mcwpInfo.shutter; -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -static Real makeQuadraticS(Real t) -{ - // for t = linear 0-1, convert to quadratic s where 0==0, 0.5==0.5 && 1.0 == 1.0. - Real tPrime = t; - if (t<0.5) { - tPrime = 0.5 * (2*t*2*t); - } else { - tPrime = (t-0.5)*2; - tPrime = WWMath::Sqrt(tPrime); - tPrime = 0.5 + 0.5*(tPrime); - } - return tPrime*0.5 + t*0.5; -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void W3DView::rotateCameraOneFrame(void) -{ - m_rcInfo.curFrame++; - if (TheGlobalData->m_disableCameraMovement) { - if (m_rcInfo.curFrame >= m_rcInfo.numFrames + m_rcInfo.numHoldFrames) { - m_doingRotateCamera = false; - m_freezeTimeForCameraMovement = false; - } - return; - } - - if (m_rcInfo.trackObject) - { - if (m_rcInfo.curFrame <= m_rcInfo.numFrames + m_rcInfo.numHoldFrames) - { - const Object *obj = TheGameLogic->findObjectByID(m_rcInfo.target.targetObjectID); - if (obj) - { - // object has not been destroyed - m_rcInfo.target.targetObjectPos = *obj->getPosition(); - } - - const Vector2 dir(m_rcInfo.target.targetObjectPos.x - m_pos.x, m_rcInfo.target.targetObjectPos.y - m_pos.y); - const Real dirLength = dir.Length(); - if (dirLength>=0.1f) - { - Real angle = WWMath::Acos(dir.X/dirLength); - if (dir.Y<0.0f) { - angle = -angle; - } - // Default camera is rotated 90 degrees, so match. - angle -= PI/2; - normAngle(angle); - - if (m_rcInfo.curFrame <= m_rcInfo.numFrames) - { - Real factor = m_rcInfo.ease(((Real)m_rcInfo.curFrame)/m_rcInfo.numFrames); - Real angleDiff = angle - m_angle; - normAngle(angleDiff); - angleDiff *= factor; - m_angle += angleDiff; - normAngle(m_angle); - m_timeMultiplier = m_rcInfo.startTimeMultiplier + REAL_TO_INT_FLOOR(0.5 + (m_rcInfo.endTimeMultiplier-m_rcInfo.startTimeMultiplier)*factor); - } - else - { - m_angle = angle; - } - } - } - } - else if (m_rcInfo.curFrame <= m_rcInfo.numFrames) - { - Real factor = m_rcInfo.ease(((Real)m_rcInfo.curFrame)/m_rcInfo.numFrames); - m_angle = WWMath::Lerp(m_rcInfo.angle.startAngle, m_rcInfo.angle.endAngle, factor); - normAngle(m_angle); - m_timeMultiplier = m_rcInfo.startTimeMultiplier + REAL_TO_INT_FLOOR(0.5 + (m_rcInfo.endTimeMultiplier-m_rcInfo.startTimeMultiplier)*factor); - } - - - if (m_rcInfo.curFrame >= m_rcInfo.numFrames + m_rcInfo.numHoldFrames) { - m_doingRotateCamera = false; - m_freezeTimeForCameraMovement = false; - if (! m_rcInfo.trackObject) - { - m_angle = m_rcInfo.angle.endAngle; - } - } -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void W3DView::zoomCameraOneFrame(void) -{ - m_zcInfo.curFrame++; - if (TheGlobalData->m_disableCameraMovement) { - if (m_zcInfo.curFrame >= m_zcInfo.numFrames) { - m_doingZoomCamera = false; - } - return; - } - if (m_zcInfo.curFrame <= m_zcInfo.numFrames) - { - // not just holding; do the camera adjustment - Real factor = m_zcInfo.ease(((Real)m_zcInfo.curFrame)/m_zcInfo.numFrames); - m_zoom = WWMath::Lerp(m_zcInfo.startZoom, m_zcInfo.endZoom, factor); - } - - if (m_zcInfo.curFrame >= m_zcInfo.numFrames) { - m_doingZoomCamera = false; - m_zoom = m_zcInfo.endZoom; - } - - //DEBUG_LOG(("W3DView::zoomCameraOneFrame() - m_zoom = %g", m_zoom)); -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void W3DView::pitchCameraOneFrame(void) -{ - m_pcInfo.curFrame++; - if (TheGlobalData->m_disableCameraMovement) { - if (m_pcInfo.curFrame >= m_pcInfo.numFrames) { - m_doingPitchCamera = false; - } - return; - } - if (m_pcInfo.curFrame <= m_pcInfo.numFrames) - { - // not just holding; do the camera adjustment - Real factor = m_pcInfo.ease(((Real)m_pcInfo.curFrame)/m_pcInfo.numFrames); - m_FXPitch = WWMath::Lerp(m_pcInfo.startPitch, m_pcInfo.endPitch, factor); - } - - if (m_pcInfo.curFrame >= m_pcInfo.numFrames) { - m_doingPitchCamera = false; - m_FXPitch = m_pcInfo.endPitch; - } -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void W3DView::moveAlongWaypointPath(Real milliseconds) -{ - m_mcwpInfo.elapsedTimeMilliseconds += milliseconds; - if (TheGlobalData->m_disableCameraMovement) { - if (m_mcwpInfo.elapsedTimeMilliseconds>m_mcwpInfo.totalTimeMilliseconds) { - m_doingMoveCameraOnWaypointPath = false; - m_freezeTimeForCameraMovement = false; - } - return; - } - if (m_mcwpInfo.elapsedTimeMilliseconds>m_mcwpInfo.totalTimeMilliseconds) { - m_doingMoveCameraOnWaypointPath = false; - m_CameraArrivedAtWaypointOnPathFlag = false; - - m_freezeTimeForCameraMovement = false; - m_angle = m_mcwpInfo.cameraAngle[m_mcwpInfo.numWaypoints]; - - m_groundLevel = m_mcwpInfo.groundHeight[m_mcwpInfo.numWaypoints]; - /////////////////////m_cameraOffset.z = m_groundLevel+TheGlobalData->m_cameraHeight; - m_cameraOffset.y = -(m_cameraOffset.z / tan(TheGlobalData->m_cameraPitch * (PI / 180.0))); - m_cameraOffset.x = -(m_cameraOffset.y * tan(TheGlobalData->m_cameraYaw * (PI / 180.0))); - - Coord3D pos = m_mcwpInfo.waypoints[m_mcwpInfo.numWaypoints]; - pos.z = 0; - setPosition(&pos); - // Note - assuming that the scripter knows what he is doing, we adjust the constraints so that - // the scripted action can occur. - m_cameraConstraint.lo.x = minf(m_cameraConstraint.lo.x, pos.x); - m_cameraConstraint.hi.x = maxf(m_cameraConstraint.hi.x, pos.x); - m_cameraConstraint.lo.y = minf(m_cameraConstraint.lo.y, pos.y); - m_cameraConstraint.hi.y = maxf(m_cameraConstraint.hi.y, pos.y); - return; - } - - const Real totalTime = m_mcwpInfo.totalTimeMilliseconds; - const Real deltaTime = m_mcwpInfo.ease(m_mcwpInfo.elapsedTimeMilliseconds/totalTime) - - m_mcwpInfo.ease((m_mcwpInfo.elapsedTimeMilliseconds - milliseconds)/totalTime); - m_mcwpInfo.curSegDistance += deltaTime*m_mcwpInfo.totalDistance; - // TheSuperHackers @todo Investigate which one is really correct. - // The non Generals condition causes camera bug in Generals Shell Map. -#if RTS_GENERALS - while (m_mcwpInfo.curSegDistance > m_mcwpInfo.waySegLength[m_mcwpInfo.curSegment]) -#else - while (m_mcwpInfo.curSegDistance >= m_mcwpInfo.waySegLength[m_mcwpInfo.curSegment]) -#endif - { - if ( m_doingMoveCameraOnWaypointPath ) - { - //WWDEBUG_SAY(( "MBL TEST: Camera waypoint along path reached!" )); - m_CameraArrivedAtWaypointOnPathFlag = true; - } - - m_mcwpInfo.curSegDistance -= m_mcwpInfo.waySegLength[m_mcwpInfo.curSegment]; - m_mcwpInfo.curSegment++; - if (m_mcwpInfo.curSegment >= m_mcwpInfo.numWaypoints) { - m_mcwpInfo.totalTimeMilliseconds = 0; // Will end following next frame. - return; - } - } - Real avgFactor = 1.0/m_mcwpInfo.rollingAverageFrames; - m_mcwpInfo.curShutter--; - if (m_mcwpInfo.curShutter>0) { - return; - } - m_mcwpInfo.curShutter = m_mcwpInfo.shutter; - Real factor = m_mcwpInfo.curSegDistance / m_mcwpInfo.waySegLength[m_mcwpInfo.curSegment]; - if (m_mcwpInfo.curSegment == m_mcwpInfo.numWaypoints-1) { - avgFactor = avgFactor + (1.0-avgFactor)*factor; - } - Real factor1; - Real factor2; - factor1 = 1.0-factor; - //factor1 = makeQuadraticS(factor1); - factor2 = 1.0-factor1; - Real angle1 = m_mcwpInfo.cameraAngle[m_mcwpInfo.curSegment]; - Real angle2 = m_mcwpInfo.cameraAngle[m_mcwpInfo.curSegment+1]; - if (angle2-angle1 > PI) angle1 += 2*PI; - if (angle2-angle1 < -PI) angle1 -= 2*PI; - Real angle = angle1 * (factor1) + angle2 * (factor2); - - normAngle(angle); - Real deltaAngle = angle-m_angle; - normAngle(deltaAngle); - if (fabs(deltaAngle) > PI/10) { - DEBUG_LOG(("Huh.")); - } - m_angle += avgFactor*(deltaAngle); - normAngle(m_angle); - - Real timeMultiplier = m_mcwpInfo.timeMultiplier[m_mcwpInfo.curSegment]*factor1 + - m_mcwpInfo.timeMultiplier[m_mcwpInfo.curSegment+1]*factor2; - m_timeMultiplier = REAL_TO_INT_FLOOR(0.5 + timeMultiplier); - - m_groundLevel = m_mcwpInfo.groundHeight[m_mcwpInfo.curSegment]*factor1 + - m_mcwpInfo.groundHeight[m_mcwpInfo.curSegment+1]*factor2; - //////////////m_cameraOffset.z = m_groundLevel+TheGlobalData->m_cameraHeight; - m_cameraOffset.y = -(m_cameraOffset.z / tan(TheGlobalData->m_cameraPitch * (PI / 180.0))); - m_cameraOffset.x = -(m_cameraOffset.y * tan(TheGlobalData->m_cameraYaw * (PI / 180.0))); - - Coord3D start, mid, end; - if (factor<0.5) { - start = m_mcwpInfo.waypoints[m_mcwpInfo.curSegment-1]; - start.x += m_mcwpInfo.waypoints[m_mcwpInfo.curSegment].x; - start.y += m_mcwpInfo.waypoints[m_mcwpInfo.curSegment].y; - start.x /= 2; - start.y /= 2; - mid = m_mcwpInfo.waypoints[m_mcwpInfo.curSegment]; - end = m_mcwpInfo.waypoints[m_mcwpInfo.curSegment]; - end.x += m_mcwpInfo.waypoints[m_mcwpInfo.curSegment+1].x; - end.y += m_mcwpInfo.waypoints[m_mcwpInfo.curSegment+1].y; - end.x /= 2; - end.y /= 2; - factor += 0.5; - } else { - start = m_mcwpInfo.waypoints[m_mcwpInfo.curSegment]; - start.x += m_mcwpInfo.waypoints[m_mcwpInfo.curSegment+1].x; - start.y += m_mcwpInfo.waypoints[m_mcwpInfo.curSegment+1].y; - start.x /= 2; - start.y /= 2; - mid = m_mcwpInfo.waypoints[m_mcwpInfo.curSegment+1]; - end = m_mcwpInfo.waypoints[m_mcwpInfo.curSegment+1]; - end.x += m_mcwpInfo.waypoints[m_mcwpInfo.curSegment+2].x; - end.y += m_mcwpInfo.waypoints[m_mcwpInfo.curSegment+2].y; - end.x /= 2; - end.y /= 2; - factor -= 0.5; - } - - Coord3D result = start; - result.x += factor*(end.x-start.x); - result.y += factor*(end.y-start.y); - result.x += (1-factor)*factor*(mid.x-end.x + mid.x-start.x); - result.y += (1-factor)*factor*(mid.y-end.y + mid.y-start.y); - result.z = 0; -/* - static Real prevGround = 0; - DEBUG_LOG(("Dx %.2f, dy %.2f, DeltaANgle = %.2f, %.2f DeltaGround %.2f", m_pos.x-result.x, m_pos.y-result.y, deltaAngle, m_groundLevel, m_groundLevel-prevGround)); - prevGround = m_groundLevel; -*/ - setPosition(&result); - // Note - assuming that the scripter knows what he is doing, we adjust the constraints so that - // the scripted action can occur. - m_cameraConstraint.lo.x = minf(m_cameraConstraint.lo.x, result.x); - m_cameraConstraint.hi.x = maxf(m_cameraConstraint.hi.x, result.x); - m_cameraConstraint.lo.y = minf(m_cameraConstraint.lo.y, result.y); - m_cameraConstraint.hi.y = maxf(m_cameraConstraint.hi.y, result.y); - -} - - -// ------------------------------------------------------------------------------------------------ -/** Add an impulse force to shake the camera. - * The camera shake is a simple simulation of an oscillating spring/damper. - * The idea is that some sort of shock has "pushed" the camera once, as an - * impluse, after which the camera vibrates back to its rest position. - * @todo This should be part of "View", not "W3DView". */ -// ------------------------------------------------------------------------------------------------ -void W3DView::shake( const Coord3D *epicenter, CameraShakeType shakeType ) -{ - Real angle = GameClientRandomValueReal( 0, 2*PI ); - - m_shakeAngleCos = (Real)cos( angle ); - m_shakeAngleSin = (Real)sin( angle ); - - Real intensity = 0.0f; - switch( shakeType ) - { - case SHAKE_SUBTLE: - intensity = TheGlobalData->m_shakeSubtleIntensity; - break; - - case SHAKE_NORMAL: - intensity = TheGlobalData->m_shakeNormalIntensity; - break; - - case SHAKE_STRONG: - intensity = TheGlobalData->m_shakeStrongIntensity; - break; - - case SHAKE_SEVERE: - intensity = TheGlobalData->m_shakeSevereIntensity; - break; - - case SHAKE_CINE_EXTREME: - intensity = TheGlobalData->m_shakeCineExtremeIntensity; - break; - - case SHAKE_CINE_INSANE: - intensity = TheGlobalData->m_shakeCineInsaneIntensity; - break; - } - - // intensity falls off with distance - const Coord3D *viewPos = getPosition(); - Coord3D d; - d.x = epicenter->x - viewPos->x; - d.y = epicenter->y - viewPos->y; - /// @todo make this 3D once we have the real "lookat" spot - //d.z = epicenter->z - viewPos->z; - - Real dist = (Real)sqrt( d.x*d.x + d.y*d.y ); - - if (dist > TheGlobalData->m_maxShakeRange) - return; - - intensity *= 1.0f - (dist/TheGlobalData->m_maxShakeRange); - - // add intensity and clamp - m_shakeIntensity += intensity; - - //const Real maxIntensity = 10.0f; - const Real maxIntensity = 3.0f; - if (m_shakeIntensity > TheGlobalData->m_maxShakeIntensity) - m_shakeIntensity = maxIntensity; -} - -//------------------------------------------------------------------------------------------------- -/** Transformt he screen pixel coord passed in, to a world coordinate at the specified - * z value */ -//------------------------------------------------------------------------------------------------- -void W3DView::screenToWorldAtZ( const ICoord2D *s, Coord3D *w, Real z ) -{ - Vector3 rayStart, rayEnd; - - getPickRay( s, &rayStart, &rayEnd ); - w->x = Vector3::Find_X_At_Z( z, rayStart, rayEnd ); - w->y = Vector3::Find_Y_At_Z( z, rayStart, rayEnd ); - w->z = z; - -} - -void W3DView::cameraEnableSlaveMode(const AsciiString & objectName, const AsciiString & boneName) -{ - m_isCameraSlaved = true; - m_cameraSlaveObjectName = objectName; - m_cameraSlaveObjectBoneName = boneName; -} - -void W3DView::cameraDisableSlaveMode(void) -{ - m_isCameraSlaved = false; -} - -void W3DView::cameraEnableRealZoomMode(void) //WST added 10/18/2002 -{ - m_useRealZoomCam = true; - m_FXPitch = 1.0f; //Reset to default - //m_zoom = 1.0f; - updateView(); -} - -void W3DView::cameraDisableRealZoomMode(void) //WST added 10/18/2002 -{ - m_useRealZoomCam = false; - m_FXPitch = 1.0f; //Reset to default - //m_zoom = 1.0f; - m_FOV = 50.0f * PI/180.0f; - setCameraTransform(); - updateView(); -} - -void W3DView::Add_Camera_Shake (const Coord3D & position,float radius,float duration,float power) //WST added 11/13/02 -{ - Vector3 vpos; - - vpos.X = position.x; - vpos.Y = position.y; - vpos.Z = position.z; - - - CameraShakerSystem.Add_Camera_Shake(vpos,radius,duration,power); -} - diff --git a/GeneralsMD/Code/GameEngine/CMakeLists.txt b/GeneralsMD/Code/GameEngine/CMakeLists.txt index fb10906885..b77b4292e5 100644 --- a/GeneralsMD/Code/GameEngine/CMakeLists.txt +++ b/GeneralsMD/Code/GameEngine/CMakeLists.txt @@ -224,7 +224,7 @@ set(GAMEENGINE_SRC Include/GameClient/TerrainRoads.h Include/GameClient/TerrainVisual.h # Include/GameClient/VideoPlayer.h - Include/GameClient/View.h +# Include/GameClient/View.h Include/GameClient/Water.h Include/GameClient/WindowLayout.h # Include/GameClient/WindowVideoManager.h @@ -824,7 +824,7 @@ set(GAMEENGINE_SRC Source/GameClient/Terrain/TerrainVisual.cpp # Source/GameClient/VideoPlayer.cpp # Source/GameClient/VideoStream.cpp - Source/GameClient/View.cpp +# Source/GameClient/View.cpp Source/GameClient/Water.cpp Source/GameLogic/AI/AI.cpp Source/GameLogic/AI/AIDock.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/CMakeLists.txt b/GeneralsMD/Code/GameEngineDevice/CMakeLists.txt index 4d32d9dd1f..e1bb05cdb1 100644 --- a/GeneralsMD/Code/GameEngineDevice/CMakeLists.txt +++ b/GeneralsMD/Code/GameEngineDevice/CMakeLists.txt @@ -71,7 +71,7 @@ set(GAMEENGINEDEVICE_SRC Include/W3DDevice/GameClient/W3DTerrainVisual.h Include/W3DDevice/GameClient/W3DTreeBuffer.h # Include/W3DDevice/GameClient/W3DVideoBuffer.h - Include/W3DDevice/GameClient/W3DView.h +# Include/W3DDevice/GameClient/W3DView.h Include/W3DDevice/GameClient/W3DVolumetricShadow.h Include/W3DDevice/GameClient/W3DWater.h Include/W3DDevice/GameClient/W3DWaterTracks.h @@ -173,7 +173,7 @@ set(GAMEENGINEDEVICE_SRC Source/W3DDevice/GameClient/W3DTerrainVisual.cpp Source/W3DDevice/GameClient/W3DTreeBuffer.cpp # Source/W3DDevice/GameClient/W3DVideoBuffer.cpp - Source/W3DDevice/GameClient/W3DView.cpp +# Source/W3DDevice/GameClient/W3DView.cpp Source/W3DDevice/GameClient/W3dWaypointBuffer.cpp Source/W3DDevice/GameClient/W3DWebBrowser.cpp Source/W3DDevice/GameClient/Water/W3DWater.cpp diff --git a/scripts/cpp/unify_move_files.py b/scripts/cpp/unify_move_files.py index 9e874ad3a0..6d401ef28f 100644 --- a/scripts/cpp/unify_move_files.py +++ b/scripts/cpp/unify_move_files.py @@ -185,6 +185,11 @@ def main(): #unify_move_file(Game.ZEROHOUR, "GameEngineDevice/Include/W3DDevice/GameClient/camerashakesystem.h", Game.CORE, "GameEngineDevice/Include/W3DDevice/GameClient/CameraShakeSystem.h") #unify_move_file(Game.ZEROHOUR, "GameEngineDevice/Source/W3DDevice/GameClient/camerashakesystem.cpp", Game.CORE, "GameEngineDevice/Source/W3DDevice/GameClient/CameraShakeSystem.cpp") + #unify_file(Game.ZEROHOUR, "GameEngine/Include/GameClient/View.h", Game.CORE, "GameEngine/Include/GameClient/View.h") + #unify_file(Game.ZEROHOUR, "GameEngine/Source/GameClient/View.cpp", Game.CORE, "GameEngine/Source/GameClient/View.cpp") + #unify_file(Game.ZEROHOUR, "GameEngineDevice/Include/W3DDevice/GameClient/W3DView.h", Game.CORE, "GameEngineDevice/Include/W3DDevice/GameClient/W3DView.h") + #unify_file(Game.ZEROHOUR, "GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp", Game.CORE, "GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp") + return From 7751544eba3bd042991f5db9ff91cd614cde80b3 Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Sun, 30 Nov 2025 17:21:38 +0100 Subject: [PATCH 04/70] refactor: Remove all explicit AsciiString instantiations from C strings (#1916) --- .../Source/Common/Audio/GameAudio.cpp | 22 +- .../Common/System/ArchiveFileSystem.cpp | 2 +- .../Source/GameClient/VideoPlayer.cpp | 4 +- .../Source/GameNetwork/FirewallHelper.cpp | 2 +- .../Source/GameNetwork/GameInfo.cpp | 2 +- .../Source/GameNetwork/GameSpy/LadderDefs.cpp | 2 +- .../GameNetwork/GameSpy/MainMenuUtils.cpp | 6 +- .../Source/GameNetwork/LANAPICallbacks.cpp | 4 +- .../GameNetwork/WOLBrowser/WebBrowser.cpp | 2 +- .../StdDevice/Common/StdBIGFileSystem.cpp | 2 +- .../Win32Device/Common/Win32BIGFileSystem.cpp | 2 +- Core/Tools/Autorun/autorun.cpp | 24 +- .../GameEngine/Include/GameLogic/ArmorSet.h | 2 +- .../GameEngine/Include/GameLogic/WeaponSet.h | 2 +- .../GameEngine/Source/Common/GameEngine.cpp | 8 +- .../Code/GameEngine/Source/Common/GameLOD.cpp | 4 +- .../GameEngine/Source/Common/Recorder.cpp | 2 +- .../Source/Common/System/DataChunk.cpp | 4 +- .../Common/System/SaveGame/GameState.cpp | 2 +- .../GameEngine/Source/Common/TerrainTypes.cpp | 2 +- .../Source/Common/Thing/ThingFactory.cpp | 4 +- .../GameEngine/Source/GameClient/Credits.cpp | 2 +- .../Code/GameEngine/Source/GameClient/Eva.cpp | 2 +- .../GameClient/GUI/ControlBar/ControlBar.cpp | 12 +- .../GUI/ControlBar/ControlBarObserver.cpp | 2 +- .../GUI/ControlBar/ControlBarResizer.cpp | 2 +- .../GUI/ControlBar/ControlBarScheme.cpp | 4 +- .../GUI/GUICallbacks/ControlBarCallback.cpp | 8 +- .../ControlBarPopupDescription.cpp | 2 +- .../GUI/GUICallbacks/ExtendedMessageBox.cpp | 22 +- .../GUI/GUICallbacks/InGameChat.cpp | 4 +- .../GUI/GUICallbacks/InGamePopupMessage.cpp | 6 +- .../GUI/GUICallbacks/Menus/CreditsMenu.cpp | 4 +- .../GUICallbacks/Menus/DifficultySelect.cpp | 6 +- .../GUICallbacks/Menus/DisconnectWindow.cpp | 20 +- .../Menus/EstablishConnectionsWindow.cpp | 2 +- .../GUI/GUICallbacks/Menus/GameInfoWindow.cpp | 2 +- .../Menus/KeyboardOptionsMenu.cpp | 2 +- .../GUICallbacks/Menus/LanGameOptionsMenu.cpp | 20 +- .../GUI/GUICallbacks/Menus/LanLobbyMenu.cpp | 32 +- .../GUICallbacks/Menus/LanMapSelectMenu.cpp | 8 +- .../GUI/GUICallbacks/Menus/MainMenu.cpp | 98 ++-- .../GUI/GUICallbacks/Menus/MapSelectMenu.cpp | 26 +- .../Menus/NetworkDirectConnect.cpp | 12 +- .../GUI/GUICallbacks/Menus/OptionsMenu.cpp | 110 ++-- .../GUICallbacks/Menus/PopupCommunicator.cpp | 2 +- .../GUI/GUICallbacks/Menus/PopupHostGame.cpp | 18 +- .../GUI/GUICallbacks/Menus/PopupJoinGame.cpp | 6 +- .../GUICallbacks/Menus/PopupLadderSelect.cpp | 2 +- .../GUI/GUICallbacks/Menus/QuitMenu.cpp | 26 +- .../GUI/GUICallbacks/Menus/ReplayMenu.cpp | 12 +- .../GUI/GUICallbacks/Menus/ScoreScreen.cpp | 20 +- .../GUICallbacks/Menus/SinglePlayerMenu.cpp | 14 +- .../Menus/SkirmishGameOptionsMenu.cpp | 32 +- .../Menus/SkirmishMapSelectMenu.cpp | 8 +- .../GUICallbacks/Menus/WOLBuddyOverlay.cpp | 52 +- .../Menus/WOLCustomScoreScreen.cpp | 6 +- .../GUICallbacks/Menus/WOLGameSetupMenu.cpp | 22 +- .../GUICallbacks/Menus/WOLLadderScreen.cpp | 6 +- .../GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp | 32 +- .../Menus/WOLLocaleSelectPopup.cpp | 6 +- .../GUICallbacks/Menus/WOLMapSelectMenu.cpp | 8 +- .../GUICallbacks/Menus/WOLMessageWindow.cpp | 4 +- .../GUICallbacks/Menus/WOLQMScoreScreen.cpp | 6 +- .../GUI/GUICallbacks/Menus/WOLStatusMenu.cpp | 6 +- .../GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp | 18 +- .../GUI/GUICallbacks/MessageBox.cpp | 16 +- .../GameClient/GUI/GameWindowManager.cpp | 10 +- .../GameClient/GUI/GameWindowTransitions.cpp | 2 +- .../Source/GameClient/GUI/IMEManager.cpp | 10 +- .../Source/GameClient/GUI/LoadScreen.cpp | 34 +- .../Source/GameClient/GUI/Shell/Shell.cpp | 12 +- .../GameClient/GUI/Shell/ShellMenuScheme.cpp | 4 +- .../GameEngine/Source/GameClient/InGameUI.cpp | 18 +- .../Source/GameClient/Input/Mouse.cpp | 2 +- .../GameEngine/Source/GameClient/MapUtil.cpp | 14 +- .../GameClient/MessageStream/CommandXlat.cpp | 6 +- .../GameClient/System/CampaignManager.cpp | 2 +- .../Source/GameClient/System/ParticleSys.cpp | 2 +- .../GameClient/Terrain/TerrainRoads.cpp | 4 +- .../Source/GameLogic/Map/SidesList.cpp | 16 +- .../Source/GameLogic/Map/TerrainLogic.cpp | 2 +- .../Source/GameLogic/ScriptEngine/Scripts.cpp | 16 +- .../Source/GameLogic/System/CrateSystem.cpp | 2 +- .../Source/GameLogic/System/GameLogic.cpp | 4 +- .../GameLogic/System/GameLogicDispatch.cpp | 2 +- .../GameEngine/Source/GameNetwork/GameSpy.cpp | 2 +- .../GUI/GUICallbacks/W3DControlBar.cpp | 8 +- .../GUI/GUICallbacks/W3DMainMenu.cpp | 8 +- .../GameClient/GUI/W3DGameWindow.cpp | 24 +- .../W3DDevice/GameClient/W3DDisplay.cpp | 6 +- .../GameClient/W3DDisplayStringManager.cpp | 2 +- .../W3DDevice/GameClient/W3DInGameUI.cpp | 2 +- .../W3DDevice/GameClient/WorldHeightMap.cpp | 20 +- .../Tools/GUIEdit/Source/LayoutScheme.cpp | 494 +++++++++--------- .../Code/Tools/WorldBuilder/src/GroveTool.cpp | 2 +- .../Tools/WorldBuilder/src/ScorchTool.cpp | 2 +- .../Tools/WorldBuilder/src/ScriptDialog.cpp | 14 +- .../WorldBuilder/src/SelectMacrotexture.cpp | 2 +- .../Tools/WorldBuilder/src/WHeightMapEdit.cpp | 2 +- .../Tools/WorldBuilder/src/WaypointTool.cpp | 8 +- .../Tools/WorldBuilder/src/WorldBuilder.cpp | 8 +- .../WorldBuilder/src/WorldBuilderDoc.cpp | 2 +- .../Tools/WorldBuilder/src/playerlistdlg.cpp | 20 +- .../GameEngine/Include/GameLogic/ArmorSet.h | 2 +- .../GameEngine/Include/GameLogic/WeaponSet.h | 2 +- .../GameEngine/Source/Common/GameEngine.cpp | 12 +- .../Code/GameEngine/Source/Common/GameLOD.cpp | 4 +- .../GameEngine/Source/Common/Recorder.cpp | 2 +- .../Source/Common/System/DataChunk.cpp | 4 +- .../Common/System/SaveGame/GameState.cpp | 2 +- .../GameEngine/Source/Common/TerrainTypes.cpp | 2 +- .../Source/Common/Thing/ThingFactory.cpp | 4 +- .../GameEngine/Source/GameClient/Credits.cpp | 2 +- .../Code/GameEngine/Source/GameClient/Eva.cpp | 2 +- .../GameClient/GUI/ChallengeGenerals.cpp | 2 +- .../GameClient/GUI/ControlBar/ControlBar.cpp | 12 +- .../GUI/ControlBar/ControlBarObserver.cpp | 2 +- .../GUI/ControlBar/ControlBarResizer.cpp | 2 +- .../GUI/ControlBar/ControlBarScheme.cpp | 4 +- .../GUI/GUICallbacks/ControlBarCallback.cpp | 8 +- .../ControlBarPopupDescription.cpp | 2 +- .../GUI/GUICallbacks/ExtendedMessageBox.cpp | 22 +- .../GUI/GUICallbacks/InGameChat.cpp | 4 +- .../GUI/GUICallbacks/InGamePopupMessage.cpp | 6 +- .../GUI/GUICallbacks/Menus/ChallengeMenu.cpp | 20 +- .../GUI/GUICallbacks/Menus/CreditsMenu.cpp | 4 +- .../GUICallbacks/Menus/DifficultySelect.cpp | 6 +- .../GUICallbacks/Menus/DisconnectWindow.cpp | 20 +- .../Menus/EstablishConnectionsWindow.cpp | 2 +- .../GUI/GUICallbacks/Menus/GameInfoWindow.cpp | 2 +- .../Menus/KeyboardOptionsMenu.cpp | 2 +- .../GUICallbacks/Menus/LanGameOptionsMenu.cpp | 24 +- .../GUI/GUICallbacks/Menus/LanLobbyMenu.cpp | 32 +- .../GUICallbacks/Menus/LanMapSelectMenu.cpp | 8 +- .../GUI/GUICallbacks/Menus/MainMenu.cpp | 102 ++-- .../GUI/GUICallbacks/Menus/MapSelectMenu.cpp | 26 +- .../Menus/NetworkDirectConnect.cpp | 12 +- .../GUI/GUICallbacks/Menus/OptionsMenu.cpp | 122 ++--- .../GUICallbacks/Menus/PopupCommunicator.cpp | 2 +- .../GUI/GUICallbacks/Menus/PopupHostGame.cpp | 22 +- .../GUI/GUICallbacks/Menus/PopupJoinGame.cpp | 6 +- .../GUICallbacks/Menus/PopupLadderSelect.cpp | 2 +- .../GUI/GUICallbacks/Menus/QuitMenu.cpp | 26 +- .../GUI/GUICallbacks/Menus/ReplayMenu.cpp | 12 +- .../GUI/GUICallbacks/Menus/ScoreScreen.cpp | 26 +- .../GUICallbacks/Menus/SinglePlayerMenu.cpp | 14 +- .../Menus/SkirmishGameOptionsMenu.cpp | 36 +- .../Menus/SkirmishMapSelectMenu.cpp | 8 +- .../GUICallbacks/Menus/WOLBuddyOverlay.cpp | 52 +- .../Menus/WOLCustomScoreScreen.cpp | 6 +- .../GUICallbacks/Menus/WOLGameSetupMenu.cpp | 34 +- .../GUICallbacks/Menus/WOLLadderScreen.cpp | 6 +- .../GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp | 32 +- .../Menus/WOLLocaleSelectPopup.cpp | 6 +- .../GUICallbacks/Menus/WOLMapSelectMenu.cpp | 8 +- .../GUICallbacks/Menus/WOLMessageWindow.cpp | 4 +- .../GUICallbacks/Menus/WOLQMScoreScreen.cpp | 6 +- .../GUI/GUICallbacks/Menus/WOLStatusMenu.cpp | 6 +- .../GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp | 18 +- .../GUI/GUICallbacks/MessageBox.cpp | 16 +- .../GameClient/GUI/GameWindowManager.cpp | 10 +- .../GameClient/GUI/GameWindowTransitions.cpp | 2 +- .../Source/GameClient/GUI/IMEManager.cpp | 10 +- .../Source/GameClient/GUI/LoadScreen.cpp | 106 ++-- .../Source/GameClient/GUI/Shell/Shell.cpp | 12 +- .../GameClient/GUI/Shell/ShellMenuScheme.cpp | 4 +- .../GameEngine/Source/GameClient/InGameUI.cpp | 18 +- .../Source/GameClient/Input/Mouse.cpp | 2 +- .../GameEngine/Source/GameClient/MapUtil.cpp | 14 +- .../GameClient/MessageStream/CommandXlat.cpp | 6 +- .../GameClient/System/CampaignManager.cpp | 2 +- .../Source/GameClient/System/ParticleSys.cpp | 2 +- .../GameClient/Terrain/TerrainRoads.cpp | 4 +- .../Source/GameLogic/Map/SidesList.cpp | 16 +- .../Source/GameLogic/Map/TerrainLogic.cpp | 2 +- .../Source/GameLogic/ScriptEngine/Scripts.cpp | 16 +- .../Source/GameLogic/System/CrateSystem.cpp | 2 +- .../Source/GameLogic/System/GameLogic.cpp | 4 +- .../GameLogic/System/GameLogicDispatch.cpp | 2 +- .../GUI/GUICallbacks/W3DControlBar.cpp | 8 +- .../GUI/GUICallbacks/W3DMainMenu.cpp | 8 +- .../GameClient/GUI/W3DGameWindow.cpp | 24 +- .../W3DDevice/GameClient/W3DDisplay.cpp | 6 +- .../GameClient/W3DDisplayStringManager.cpp | 2 +- .../W3DDevice/GameClient/W3DInGameUI.cpp | 2 +- .../W3DDevice/GameClient/WorldHeightMap.cpp | 20 +- .../Tools/GUIEdit/Source/LayoutScheme.cpp | 494 +++++++++--------- .../Tools/WorldBuilder/src/CameraOptions.cpp | 6 +- .../Code/Tools/WorldBuilder/src/GroveTool.cpp | 2 +- .../Tools/WorldBuilder/src/ScorchTool.cpp | 2 +- .../Tools/WorldBuilder/src/ScriptDialog.cpp | 14 +- .../WorldBuilder/src/SelectMacrotexture.cpp | 2 +- .../Tools/WorldBuilder/src/WHeightMapEdit.cpp | 2 +- .../Tools/WorldBuilder/src/WaypointTool.cpp | 8 +- .../Tools/WorldBuilder/src/WorldBuilder.cpp | 10 +- .../WorldBuilder/src/WorldBuilderDoc.cpp | 4 +- .../Tools/WorldBuilder/src/playerlistdlg.cpp | 8 +- ...asciistring_unicodestring_instantiation.py | 50 ++ 199 files changed, 1705 insertions(+), 1655 deletions(-) create mode 100644 scripts/cpp/refactor_asciistring_unicodestring_instantiation.py diff --git a/Core/GameEngine/Source/Common/Audio/GameAudio.cpp b/Core/GameEngine/Source/Common/Audio/GameAudio.cpp index 99d2a649c9..a5844c063b 100644 --- a/Core/GameEngine/Source/Common/Audio/GameAudio.cpp +++ b/Core/GameEngine/Source/Common/Audio/GameAudio.cpp @@ -210,22 +210,22 @@ AudioManager::~AudioManager() void AudioManager::init() { INI ini; - ini.loadFileDirectory( AsciiString( "Data\\INI\\AudioSettings" ), INI_LOAD_OVERWRITE, NULL); + ini.loadFileDirectory( "Data\\INI\\AudioSettings", INI_LOAD_OVERWRITE, NULL); - ini.loadFileDirectory( AsciiString( "Data\\INI\\Default\\Music" ), INI_LOAD_OVERWRITE, NULL ); - ini.loadFileDirectory( AsciiString( "Data\\INI\\Music" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Default\\Music", INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Music", INI_LOAD_OVERWRITE, NULL ); - ini.loadFileDirectory( AsciiString( "Data\\INI\\Default\\SoundEffects" ), INI_LOAD_OVERWRITE, NULL ); - ini.loadFileDirectory( AsciiString( "Data\\INI\\SoundEffects" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Default\\SoundEffects", INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\SoundEffects", INI_LOAD_OVERWRITE, NULL ); - ini.loadFileDirectory( AsciiString( "Data\\INI\\Default\\Speech" ), INI_LOAD_OVERWRITE, NULL ); - ini.loadFileDirectory( AsciiString( "Data\\INI\\Speech" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Default\\Speech", INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Speech", INI_LOAD_OVERWRITE, NULL ); - ini.loadFileDirectory( AsciiString( "Data\\INI\\Default\\Voice" ), INI_LOAD_OVERWRITE, NULL ); - ini.loadFileDirectory( AsciiString( "Data\\INI\\Voice" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Default\\Voice", INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Voice", INI_LOAD_OVERWRITE, NULL ); // do the miscellaneous sound files last so that we find the AudioEventRTS associated with the events. - ini.loadFileDirectory( AsciiString( "Data\\INI\\MiscAudio" ), INI_LOAD_OVERWRITE, NULL); + ini.loadFileDirectory( "Data\\INI\\MiscAudio", INI_LOAD_OVERWRITE, NULL); // determine if one of the music tracks exists. Since their now BIGd, one implies all. // If they don't exist, then attempt to load them from the CD. @@ -407,7 +407,7 @@ void AudioManager::getInfoForAudioEvent( const AudioEventRTS *eventToFindAndFill //------------------------------------------------------------------------------------------------- AudioHandle AudioManager::addAudioEvent(const AudioEventRTS *eventToAdd) { - if (eventToAdd->getEventName().isEmpty() || eventToAdd->getEventName() == AsciiString("NoSound")) { + if (eventToAdd->getEventName().isEmpty() || eventToAdd->getEventName() == "NoSound") { return AHSV_NoSound; } diff --git a/Core/GameEngine/Source/Common/System/ArchiveFileSystem.cpp b/Core/GameEngine/Source/Common/System/ArchiveFileSystem.cpp index 02f3552e9a..1d8223a014 100644 --- a/Core/GameEngine/Source/Common/System/ArchiveFileSystem.cpp +++ b/Core/GameEngine/Source/Common/System/ArchiveFileSystem.cpp @@ -120,7 +120,7 @@ void ArchiveFileSystem::loadIntoDirectoryTree(ArchiveFile *archiveFile, Bool ove FilenameList filenameList; - archiveFile->getFileListInDirectory(AsciiString(""), AsciiString(""), AsciiString("*"), filenameList, TRUE); + archiveFile->getFileListInDirectory("", "", "*", filenameList, TRUE); FilenameListIter it = filenameList.begin(); diff --git a/Core/GameEngine/Source/GameClient/VideoPlayer.cpp b/Core/GameEngine/Source/GameClient/VideoPlayer.cpp index d79a7e26d4..a756d3c456 100644 --- a/Core/GameEngine/Source/GameClient/VideoPlayer.cpp +++ b/Core/GameEngine/Source/GameClient/VideoPlayer.cpp @@ -182,8 +182,8 @@ void VideoPlayer::init( void ) // Load this here so that WB doesn't have to link to BinkLib, costing us (potentially) // an extra license. INI ini; - ini.loadFileDirectory( AsciiString( "Data\\INI\\Default\\Video" ), INI_LOAD_OVERWRITE, NULL ); - ini.loadFileDirectory( AsciiString( "Data\\INI\\Video" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Default\\Video", INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Video", INI_LOAD_OVERWRITE, NULL ); } //============================================================================ diff --git a/Core/GameEngine/Source/GameNetwork/FirewallHelper.cpp b/Core/GameEngine/Source/GameNetwork/FirewallHelper.cpp index f173050b63..e650c3c272 100644 --- a/Core/GameEngine/Source/GameNetwork/FirewallHelper.cpp +++ b/Core/GameEngine/Source/GameNetwork/FirewallHelper.cpp @@ -541,7 +541,7 @@ void FirewallHelperClass::flagNeedToRefresh(Bool flag) { OptionPreferences pref; - (pref)["FirewallNeedToRefresh"] = flag ? AsciiString("TRUE") : AsciiString("FALSE"); + (pref)["FirewallNeedToRefresh"] = flag ? "TRUE" : "FALSE"; pref.write(); } diff --git a/Core/GameEngine/Source/GameNetwork/GameInfo.cpp b/Core/GameEngine/Source/GameNetwork/GameInfo.cpp index 747d3ec083..20bc7e334b 100644 --- a/Core/GameEngine/Source/GameNetwork/GameInfo.cpp +++ b/Core/GameEngine/Source/GameNetwork/GameInfo.cpp @@ -301,7 +301,7 @@ void GameInfo::reset( void ) m_inGame = false; m_inProgress = false; m_gameID = 0; - m_mapName = AsciiString("NOMAP"); + m_mapName = "NOMAP"; m_mapMask = 0; m_seed = GetTickCount(); //GameClientRandomValue(0, INT_MAX - 1); m_useStats = TRUE; diff --git a/Core/GameEngine/Source/GameNetwork/GameSpy/LadderDefs.cpp b/Core/GameEngine/Source/GameNetwork/GameSpy/LadderDefs.cpp index b6cb5da0d8..5c566feb60 100644 --- a/Core/GameEngine/Source/GameNetwork/GameSpy/LadderDefs.cpp +++ b/Core/GameEngine/Source/GameNetwork/GameSpy/LadderDefs.cpp @@ -444,7 +444,7 @@ void LadderList::loadLocalLadders( void ) AsciiString dirname; dirname.format("%sGeneralsOnline\\Ladders\\", TheGlobalData->getPath_UserData().str()); FilenameList filenameList; - TheFileSystem->getFileListInDirectory(dirname, AsciiString("*.ini"), filenameList, TRUE); + TheFileSystem->getFileListInDirectory(dirname, "*.ini", filenameList, TRUE); Int index = -1; diff --git a/Core/GameEngine/Source/GameNetwork/GameSpy/MainMenuUtils.cpp b/Core/GameEngine/Source/GameNetwork/GameSpy/MainMenuUtils.cpp index 0e8c8ed2e3..81c8ebcc69 100644 --- a/Core/GameEngine/Source/GameNetwork/GameSpy/MainMenuUtils.cpp +++ b/Core/GameEngine/Source/GameNetwork/GameSpy/MainMenuUtils.cpp @@ -95,7 +95,7 @@ void StartDownloadingPatches( void ) } WindowLayout *layout; - layout = TheWindowManager->winCreateLayout( AsciiString( "Menus/DownloadMenu.wnd" ) ); + layout = TheWindowManager->winCreateLayout( "Menus/DownloadMenu.wnd" ); layout->runInit(); layout->hide( FALSE ); layout->bringForward(); @@ -233,10 +233,10 @@ static void startOnline( void ) UserPreferences::const_iterator it = pref.find("useProfiles"); if (it != pref.end() && it->second.compareNoCase("yes") == 0) #endif // ALLOW_NON_PROFILED_LOGIN - TheShell->push( AsciiString("Menus/GameSpyLoginProfile.wnd") ); + TheShell->push( "Menus/GameSpyLoginProfile.wnd" ); #ifdef ALLOW_NON_PROFILED_LOGIN else - TheShell->push( AsciiString("Menus/GameSpyLoginQuick.wnd") ); + TheShell->push( "Menus/GameSpyLoginQuick.wnd" ); #endif // ALLOW_NON_PROFILED_LOGIN } diff --git a/Core/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp b/Core/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp index 90e344331d..8c17920205 100644 --- a/Core/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp +++ b/Core/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp @@ -506,7 +506,7 @@ void LANAPI::OnGameJoin( ReturnType ret, LANGameInfo *theGame ) if (ret == RET_OK) { LANbuttonPushed = true; - TheShell->push( AsciiString("Menus/LanGameOptionsMenu.wnd") ); + TheShell->push( "Menus/LanGameOptionsMenu.wnd" ); //lanUpdateSlotList(); LANPreferences pref; @@ -597,7 +597,7 @@ void LANAPI::OnGameCreate( ReturnType ret ) { LANbuttonPushed = true; - TheShell->push( AsciiString("Menus/LanGameOptionsMenu.wnd") ); + TheShell->push( "Menus/LanGameOptionsMenu.wnd" ); RequestLobbyLeave( false ); //RequestGameAnnounce( ); // can't do this here, since we don't have a map set diff --git a/Core/GameEngine/Source/GameNetwork/WOLBrowser/WebBrowser.cpp b/Core/GameEngine/Source/GameNetwork/WOLBrowser/WebBrowser.cpp index 7bbe8325b4..d644725d48 100644 --- a/Core/GameEngine/Source/GameNetwork/WOLBrowser/WebBrowser.cpp +++ b/Core/GameEngine/Source/GameNetwork/WOLBrowser/WebBrowser.cpp @@ -167,7 +167,7 @@ void WebBrowser::init() { m_urlList = NULL; INI ini; - ini.loadFileDirectory( AsciiString( "Data\\INI\\Webpages" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Webpages", INI_LOAD_OVERWRITE, NULL ); } /****************************************************************************** diff --git a/Core/GameEngineDevice/Source/StdDevice/Common/StdBIGFileSystem.cpp b/Core/GameEngineDevice/Source/StdDevice/Common/StdBIGFileSystem.cpp index 2470d66912..bfd2bd094d 100644 --- a/Core/GameEngineDevice/Source/StdDevice/Common/StdBIGFileSystem.cpp +++ b/Core/GameEngineDevice/Source/StdDevice/Common/StdBIGFileSystem.cpp @@ -210,7 +210,7 @@ void StdBIGFileSystem::closeAllFiles() { Bool StdBIGFileSystem::loadBigFilesFromDirectory(AsciiString dir, AsciiString fileMask, Bool overwrite) { FilenameList filenameList; - TheLocalFileSystem->getFileListInDirectory(dir, AsciiString(""), fileMask, filenameList, TRUE); + TheLocalFileSystem->getFileListInDirectory(dir, "", fileMask, filenameList, TRUE); Bool actuallyAdded = FALSE; FilenameListIter it = filenameList.begin(); diff --git a/Core/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp b/Core/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp index 95f9e7ef0e..27491ab758 100644 --- a/Core/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp +++ b/Core/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp @@ -211,7 +211,7 @@ void Win32BIGFileSystem::closeAllFiles() { Bool Win32BIGFileSystem::loadBigFilesFromDirectory(AsciiString dir, AsciiString fileMask, Bool overwrite) { FilenameList filenameList; - TheLocalFileSystem->getFileListInDirectory(dir, AsciiString(""), fileMask, filenameList, TRUE); + TheLocalFileSystem->getFileListInDirectory(dir, "", fileMask, filenameList, TRUE); Bool actuallyAdded = FALSE; FilenameListIter it = filenameList.begin(); diff --git a/Core/Tools/Autorun/autorun.cpp b/Core/Tools/Autorun/autorun.cpp index c4b27b39f0..fefdd6ed6e 100644 --- a/Core/Tools/Autorun/autorun.cpp +++ b/Core/Tools/Autorun/autorun.cpp @@ -2276,7 +2276,7 @@ void MainWindow::Create_Buttons( HWND hWnd, RECT *dlg_rect ) #ifdef LEAN_AND_MEAN Locale_GetString( "Autorun:Install" ), #else - AsciiString("Autorun:Install"), + "Autorun:Install", #endif TTButtonFontPtr ); @@ -2295,7 +2295,7 @@ void MainWindow::Create_Buttons( HWND hWnd, RECT *dlg_rect ) #ifdef LEAN_AND_MEAN Locale_GetString( "Autorun:Play" ), #else - AsciiString("Autorun:Play"), + "Autorun:Play", #endif TTButtonFontPtr ); /* @@ -2314,7 +2314,7 @@ void MainWindow::Create_Buttons( HWND hWnd, RECT *dlg_rect ) #ifdef LEAN_AND_MEAN Locale_GetString( "Autorun:Worldbuilder" ), #else - AsciiString("Autorun:Worldbuilder"), + "Autorun:Worldbuilder", #endif TTButtonFontPtr ); */ @@ -2333,7 +2333,7 @@ void MainWindow::Create_Buttons( HWND hWnd, RECT *dlg_rect ) #ifdef LEAN_AND_MEAN Locale_GetString( "Autorun:CheckForUpdates" ), #else - AsciiString("Autorun:CheckForUpdates"), + "Autorun:CheckForUpdates", #endif TTButtonFontPtr ); } @@ -2351,7 +2351,7 @@ void MainWindow::Create_Buttons( HWND hWnd, RECT *dlg_rect ) #ifdef LEAN_AND_MEAN Locale_GetString( "Autorun:ExploreCD" ), #else - AsciiString("Autorun:ExploreCD"), + "Autorun:ExploreCD", #endif TTButtonFontPtr ); // strcpy( next_button_name, ButtonImages[button_index] ); @@ -2372,7 +2372,7 @@ void MainWindow::Create_Buttons( HWND hWnd, RECT *dlg_rect ) #ifdef LEAN_AND_MEAN Locale_GetString( "Autorun:Website" ), #else - AsciiString("Autorun:Website"), + "Autorun:Website", #endif TTButtonFontPtr ); @@ -2395,7 +2395,7 @@ void MainWindow::Create_Buttons( HWND hWnd, RECT *dlg_rect ) #ifdef LEAN_AND_MEAN Locale_GetString( "Autorun:Uninstall" ), #else - AsciiString("Autorun:Uninstall"), + "Autorun:Uninstall", #endif TTButtonFontPtr ); @@ -2417,7 +2417,7 @@ void MainWindow::Create_Buttons( HWND hWnd, RECT *dlg_rect ) #ifdef LEAN_AND_MEAN Locale_GetString( "Autorun:Previews" ), #else - AsciiString("Autorun:Previews"), + "Autorun:Previews", #endif TTButtonFontPtr ); @@ -2434,7 +2434,7 @@ void MainWindow::Create_Buttons( HWND hWnd, RECT *dlg_rect ) #ifdef LEAN_AND_MEAN Locale_GetString( "Autorun:Help" ), #else - AsciiString("Autorun:Help"), + "Autorun:Help", #endif TTButtonFontPtr ); @@ -2451,7 +2451,7 @@ void MainWindow::Create_Buttons( HWND hWnd, RECT *dlg_rect ) #ifdef LEAN_AND_MEAN Locale_GetString( "Autorun:Cancel" ), #else - AsciiString("Autorun:Cancel"), + "Autorun:Cancel", #endif TTButtonFontPtr ); @@ -3856,7 +3856,7 @@ BOOL CALLBACK Dialog_Box_Proc( HWND window_handle, UINT message, WPARAM w_param 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 ); + result = Prompt_For_CD( window_handle, volume_to_match, "Autorun:InsertCDROMWithVolume2", "Autorun:ExitMessage2", &cd_drive ); } if ( result ) { @@ -3883,7 +3883,7 @@ BOOL CALLBACK Dialog_Box_Proc( HWND window_handle, UINT message, WPARAM w_param } else { - Error_Message( Main::hInstance, AsciiString("Autorun:Generals"), AsciiString("Autorun:CantFindExplorer"), GAME_WEBSITE ); + Error_Message( Main::hInstance, "Autorun:Generals", "Autorun:CantFindExplorer", GAME_WEBSITE ); } break; #endif diff --git a/Generals/Code/GameEngine/Include/GameLogic/ArmorSet.h b/Generals/Code/GameEngine/Include/GameLogic/ArmorSet.h index ec6dd1e442..e644defdf6 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/ArmorSet.h +++ b/Generals/Code/GameEngine/Include/GameLogic/ArmorSet.h @@ -81,7 +81,7 @@ class ArmorTemplateSet inline Int getConditionsYesCount() const { return 1; } inline const ArmorSetFlags& getNthConditionsYes(Int i) const { return m_types; } #if defined(RTS_DEBUG) - inline AsciiString getDescription() const { return AsciiString("ArmorTemplateSet"); } + inline AsciiString getDescription() const { return "ArmorTemplateSet"; } #endif void parseArmorTemplateSet( INI* ini ); diff --git a/Generals/Code/GameEngine/Include/GameLogic/WeaponSet.h b/Generals/Code/GameEngine/Include/GameLogic/WeaponSet.h index 30af7e2edf..c2e8ecefe6 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(RTS_DEBUG) - inline AsciiString getDescription() const { return AsciiString("ArmorTemplateSet"); } + inline AsciiString getDescription() const { return "ArmorTemplateSet"; } #endif }; diff --git a/Generals/Code/GameEngine/Source/Common/GameEngine.cpp b/Generals/Code/GameEngine/Source/Common/GameEngine.cpp index e4a20be08c..f8ce2dd61c 100644 --- a/Generals/Code/GameEngine/Source/Common/GameEngine.cpp +++ b/Generals/Code/GameEngine/Source/Common/GameEngine.cpp @@ -394,7 +394,7 @@ void GameEngine::init() #if defined(RTS_DEBUG) // If we're in Debug, load the Debug settings as well. - ini.loadFileDirectory( AsciiString( "Data\\INI\\GameDataDebug" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\GameDataDebug", INI_LOAD_OVERWRITE, NULL ); #endif // special-case: parse command-line parameters after loading global data @@ -421,8 +421,8 @@ void GameEngine::init() #endif // read the water settings from INI (must do prior to initing GameClient, apparently) - ini.loadFileDirectory( AsciiString( "Data\\INI\\Default\\Water" ), INI_LOAD_OVERWRITE, &xferCRC ); - ini.loadFileDirectory( AsciiString( "Data\\INI\\Water" ), INI_LOAD_OVERWRITE, &xferCRC ); + ini.loadFileDirectory( "Data\\INI\\Default\\Water", INI_LOAD_OVERWRITE, &xferCRC ); + ini.loadFileDirectory( "Data\\INI\\Water", INI_LOAD_OVERWRITE, &xferCRC ); #ifdef DEBUG_CRC initSubsystem(TheDeepCRCSanityCheck, "TheDeepCRCSanityCheck", MSGNEW("GameEngineSubystem") DeepCRCSanityCheck, NULL); @@ -522,7 +522,7 @@ void GameEngine::init() } // load the initial shell screen - //TheShell->push( AsciiString("Menus/MainMenu.wnd") ); + //TheShell->push( "Menus/MainMenu.wnd" ); // This allows us to run a map from the command line if (TheGlobalData->m_initialFile.isEmpty() == FALSE) diff --git a/Generals/Code/GameEngine/Source/Common/GameLOD.cpp b/Generals/Code/GameEngine/Source/Common/GameLOD.cpp index 8eee50b6fa..b4f4592ed2 100644 --- a/Generals/Code/GameEngine/Source/Common/GameLOD.cpp +++ b/Generals/Code/GameEngine/Source/Common/GameLOD.cpp @@ -300,10 +300,10 @@ void GameLODManager::init(void) { INI ini; //Get Presets for each LOD level. - ini.loadFileDirectory( AsciiString( "Data\\INI\\GameLOD" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\GameLOD", INI_LOAD_OVERWRITE, NULL ); //Get presets for each known hardware configuration - ini.loadFileDirectory( AsciiString( "Data\\INI\\GameLODPresets"), INI_LOAD_OVERWRITE, NULL); + ini.loadFileDirectory( "Data\\INI\\GameLODPresets", INI_LOAD_OVERWRITE, NULL); //Get Presets for custom LOD level by pulling them out of initial globaldata (which should //have all settings already applied). diff --git a/Generals/Code/GameEngine/Source/Common/Recorder.cpp b/Generals/Code/GameEngine/Source/Common/Recorder.cpp index 04be1d230e..75d8a31ec0 100644 --- a/Generals/Code/GameEngine/Source/Common/Recorder.cpp +++ b/Generals/Code/GameEngine/Source/Common/Recorder.cpp @@ -1766,7 +1766,7 @@ RecorderModeType RecorderClass::getMode() { ///< Show or Hide the Replay controls void RecorderClass::initControls() { - NameKeyType parentReplayControlID = TheNameKeyGenerator->nameToKey( AsciiString("ReplayControl.wnd:ParentReplayControl") ); + NameKeyType parentReplayControlID = TheNameKeyGenerator->nameToKey( "ReplayControl.wnd:ParentReplayControl" ); GameWindow *parentReplayControl = TheWindowManager->winGetWindowFromId( NULL, parentReplayControlID ); Bool show = (getMode() != RECORDERMODETYPE_PLAYBACK); diff --git a/Generals/Code/GameEngine/Source/Common/System/DataChunk.cpp b/Generals/Code/GameEngine/Source/Common/System/DataChunk.cpp index 6a775a5e90..c1cd2400a6 100644 --- a/Generals/Code/GameEngine/Source/Common/System/DataChunk.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/DataChunk.cpp @@ -743,7 +743,7 @@ AsciiString DataChunkInput::openDataChunk(DataChunkVersionType *ver ) c->next = m_chunkStack; m_chunkStack = c; if (this->atEndOfFile()) { - return (AsciiString("")); + return AsciiString::TheEmptyString; } return m_contents.getName( c->id ); } @@ -779,7 +779,7 @@ AsciiString DataChunkInput::getChunkLabel( void ) { // TODO: Throw exception DEBUG_CRASH(("Bad.")); - return AsciiString(""); + return AsciiString::TheEmptyString; } return m_contents.getName( m_chunkStack->id ); diff --git a/Generals/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp b/Generals/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp index ee1d58a385..0d0229142d 100644 --- a/Generals/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp @@ -636,7 +636,7 @@ SaveCode GameState::missionSave( void ) desc.format( format, TheGameText->fetch( campaign->m_campaignNameLabel ).str(), missionNumber ); // do an automatic mission save - return TheGameState->saveGame( AsciiString(""), desc, SAVE_FILE_TYPE_MISSION ); + return TheGameState->saveGame( "", desc, SAVE_FILE_TYPE_MISSION ); } diff --git a/Generals/Code/GameEngine/Source/Common/TerrainTypes.cpp b/Generals/Code/GameEngine/Source/Common/TerrainTypes.cpp index 5f4386420b..796f2fcc90 100644 --- a/Generals/Code/GameEngine/Source/Common/TerrainTypes.cpp +++ b/Generals/Code/GameEngine/Source/Common/TerrainTypes.cpp @@ -139,7 +139,7 @@ TerrainType *TerrainTypeCollection::newTerrain( AsciiString name ) terrain = newInstance(TerrainType); // copy default values from the default terrain entry - TerrainType *defaultTerrain = findTerrain( AsciiString( "DefaultTerrain" ) ); + TerrainType *defaultTerrain = findTerrain( "DefaultTerrain" ); if( defaultTerrain ) *terrain = *defaultTerrain; /* diff --git a/Generals/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp b/Generals/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp index 5c946d31c6..8c75ab0f3d 100644 --- a/Generals/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp +++ b/Generals/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp @@ -134,7 +134,7 @@ ThingTemplate *ThingFactory::newTemplate( const AsciiString& name ) newTemplate = newInstance(ThingTemplate); // if the default template is present, get it and copy over any data to the new template - const ThingTemplate *defaultT = findTemplate( AsciiString( "DefaultThingTemplate" ) ); + const ThingTemplate *defaultT = findTemplate( "DefaultThingTemplate" ); if( defaultT ) { @@ -276,7 +276,7 @@ ThingTemplate *ThingFactory::findTemplateInternal( const AsciiString& name ) #ifdef LOAD_TEST_ASSETS if (!strncmp(name.str(), TEST_STRING, strlen(TEST_STRING))) { - ThingTemplate *tmplate = newTemplate( AsciiString( "Un-namedTemplate" ) ); + ThingTemplate *tmplate = newTemplate( "Un-namedTemplate" ); // load the values tmplate->initForLTA( name ); diff --git a/Generals/Code/GameEngine/Source/GameClient/Credits.cpp b/Generals/Code/GameEngine/Source/GameClient/Credits.cpp index 9289e313c8..7d132eae2b 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Credits.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Credits.cpp @@ -155,7 +155,7 @@ void CreditsManager::load(void ) { INI ini; // Read from INI all the ControlBarSchemes - ini.loadFileDirectory( AsciiString( "Data\\INI\\Credits" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Credits", INI_LOAD_OVERWRITE, NULL ); if(m_scrollRatePerFrames <=0) m_scrollRatePerFrames = 1; diff --git a/Generals/Code/GameEngine/Source/GameClient/Eva.cpp b/Generals/Code/GameEngine/Source/GameClient/Eva.cpp index da880e3c54..f2e86d0498 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Eva.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Eva.cpp @@ -182,7 +182,7 @@ void Eva::init() { // parse the INI here, etc. INI ini; - ini.loadFileDirectory( AsciiString( "Data\\INI\\Eva" ), INI_LOAD_OVERWRITE, NULL); + ini.loadFileDirectory( "Data\\INI\\Eva", INI_LOAD_OVERWRITE, NULL); } //------------------------------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp index 2b79ac726b..c08c490fc9 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp @@ -1039,11 +1039,11 @@ void ControlBar::init( void ) INI ini; m_sideSelectAnimateDown = FALSE; // load the command buttons - ini.loadFileDirectory( AsciiString( "Data\\INI\\Default\\CommandButton" ), INI_LOAD_OVERWRITE, NULL ); - ini.loadFileDirectory( AsciiString( "Data\\INI\\CommandButton" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Default\\CommandButton", INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\CommandButton", INI_LOAD_OVERWRITE, NULL ); // load the command sets - ini.loadFileDirectory( AsciiString( "Data\\INI\\CommandSet" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\CommandSet", INI_LOAD_OVERWRITE, NULL ); // post process step after loading the command buttons and command sets postProcessCommands(); @@ -1230,9 +1230,9 @@ void ControlBar::init( void ) m_radarAttackGlowWindow = TheWindowManager->winGetWindowFromId(NULL, TheNameKeyGenerator->nameToKey("ControlBar.wnd:WinUAttack")); - win = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( AsciiString( "ControlBar.wnd:BackgroundMarker" ) )); + win = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( "ControlBar.wnd:BackgroundMarker" )); win->winGetScreenPosition(&m_controlBarForegroundMarkerPos.x, &m_controlBarForegroundMarkerPos.y); - win = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( AsciiString( "ControlBar.wnd:BackgroundMarker" ) )); + win = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( "ControlBar.wnd:BackgroundMarker" )); win->winGetScreenPosition(&m_controlBarBackgroundMarkerPos.x,&m_controlBarBackgroundMarkerPos.y); if(!m_videoManager) @@ -1388,7 +1388,7 @@ void ControlBar::update( void ) { if (m_animateWindowManager->isFinished() && m_animateWindowManager->isReversed()) { - Int id = (Int)TheNameKeyGenerator->nameToKey(AsciiString("ControlBar.wnd:ControlBarParent")); + Int id = (Int)TheNameKeyGenerator->nameToKey("ControlBar.wnd:ControlBarParent"); GameWindow *window = TheWindowManager->winGetWindowFromId(NULL, id); if (window && !window->winIsHidden()) window->winHide(TRUE); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarObserver.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarObserver.cpp index c9858ec477..d15d40b7d2 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarObserver.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarObserver.cpp @@ -224,7 +224,7 @@ WindowMsgHandledType ControlBarObserverSystem( GameWindow *window, UnsignedInt m // if( controlID == buttonCommunicator && TheGameLogic->getGameMode() == GAME_INTERNET ) /* { - popupCommunicatorLayout = TheWindowManager->winCreateLayout( AsciiString( "Menus/PopupCommunicator.wnd" ) ); + popupCommunicatorLayout = TheWindowManager->winCreateLayout( "Menus/PopupCommunicator.wnd" ); popupCommunicatorLayout->runInit(); popupCommunicatorLayout->hide( FALSE ); popupCommunicatorLayout->bringForward(); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarResizer.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarResizer.cpp index 04aace41dc..fc8b35ad5f 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarResizer.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarResizer.cpp @@ -103,7 +103,7 @@ void ControlBarResizer::init( void ) { INI ini; // Read from INI all the ControlBarSchemes - ini.loadFileDirectory( AsciiString( "Data\\INI\\ControlBarResizer" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\ControlBarResizer", INI_LOAD_OVERWRITE, NULL ); } diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp index 46e14bb6a0..6554aa8746 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp @@ -1007,8 +1007,8 @@ void ControlBarSchemeManager::init( void ) INI ini; // Read from INI all the ControlBarSchemes - ini.loadFileDirectory( AsciiString( "Data\\INI\\Default\\ControlBarScheme" ), INI_LOAD_OVERWRITE, NULL ); - ini.loadFileDirectory( AsciiString( "Data\\INI\\ControlBarScheme" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Default\\ControlBarScheme", INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\ControlBarScheme", INI_LOAD_OVERWRITE, NULL ); // //Load the user modified control bar schemes // WIN32_FIND_DATA findData; diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarCallback.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarCallback.cpp index 9c55aecd5e..75704c557d 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarCallback.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarCallback.cpp @@ -358,7 +358,7 @@ WindowMsgHandledType ControlBarSystem( GameWindow *window, UnsignedInt msg, { // get ids for our children controls - buttonCommunicator = TheNameKeyGenerator->nameToKey( AsciiString("ControlBar.wnd:PopupCommunicator") ); + buttonCommunicator = TheNameKeyGenerator->nameToKey( "ControlBar.wnd:PopupCommunicator" ); break; @@ -503,7 +503,7 @@ void ShowControlBar( Bool immediate ) TheControlBar->showSpecialPowerShortcut(); - Int id = (Int)TheNameKeyGenerator->nameToKey(AsciiString("ControlBar.wnd:ControlBarParent")); + Int id = (Int)TheNameKeyGenerator->nameToKey("ControlBar.wnd:ControlBarParent"); GameWindow *window = TheWindowManager->winGetWindowFromId(NULL, id); if (window) @@ -538,7 +538,7 @@ void HideControlBar( Bool immediate ) TheControlBar->hideSpecialPowerShortcut(); - Int id = (Int)TheNameKeyGenerator->nameToKey(AsciiString("ControlBar.wnd:ControlBarParent")); + Int id = (Int)TheNameKeyGenerator->nameToKey("ControlBar.wnd:ControlBarParent"); GameWindow *window = TheWindowManager->winGetWindowFromId(NULL, id); if (window) @@ -574,7 +574,7 @@ void ToggleControlBar( Bool immediate ) toggleReplayControls(); - Int id = (Int)TheNameKeyGenerator->nameToKey(AsciiString("ControlBar.wnd:ControlBarParent")); + Int id = (Int)TheNameKeyGenerator->nameToKey("ControlBar.wnd:ControlBarParent"); GameWindow *window = TheWindowManager->winGetWindowFromId(NULL, id); if (window) diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp index 55fbfd98ff..91483cdfaf 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp @@ -557,7 +557,7 @@ void ControlBar::populateBuildTooltipLayout( const CommandButton *commandButton, if(win) { - static NameKeyType winNamekey = TheNameKeyGenerator->nameToKey( AsciiString( "ControlBar.wnd:BackgroundMarker" ) ); + static NameKeyType winNamekey = TheNameKeyGenerator->nameToKey( "ControlBar.wnd:BackgroundMarker" ); static ICoord2D lastOffset = { 0, 0 }; ICoord2D size, newSize, pos; diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ExtendedMessageBox.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ExtendedMessageBox.cpp index 13747434ec..67357c600c 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ExtendedMessageBox.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ExtendedMessageBox.cpp @@ -62,7 +62,7 @@ static GameWindow *gogoExMessageBox(Int x, Int y, Int width, Int height, Unsigne return NULL; } - GameWindow *parent = TheWindowManager->winCreateFromScript( AsciiString("Menus/MessageBox.wnd") ); + GameWindow *parent = TheWindowManager->winCreateFromScript( "Menus/MessageBox.wnd" ); TheWindowManager->winSetModal( parent ); TheWindowManager->winSetFocus( NULL ); // make sure we lose focus from other windows even if we refuse focus ourselves TheWindowManager->winSetFocus( parent ); @@ -104,19 +104,19 @@ static GameWindow *gogoExMessageBox(Int x, Int y, Int width, Int height, Unsigne Int buttonX[3], buttonY[3]; //In the layout, buttonOk will be in the first button position - NameKeyType buttonOkID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonOk" ) ); + NameKeyType buttonOkID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonOk" ); GameWindow *buttonOk = TheWindowManager->winGetWindowFromId(parent, buttonOkID); buttonOk->winGetPosition(&buttonX[0], &buttonY[0]); - NameKeyType buttonYesID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonYes" ) ); + NameKeyType buttonYesID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonYes" ); GameWindow *buttonYes = TheWindowManager->winGetWindowFromId(parent, buttonYesID); //buttonNo in the second position - NameKeyType buttonNoID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonNo" ) ); + NameKeyType buttonNoID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonNo" ); GameWindow *buttonNo = TheWindowManager->winGetWindowFromId(parent, buttonNoID); buttonNo->winGetPosition(&buttonX[1], &buttonY[1]); //and buttonCancel in the third - NameKeyType buttonCancelID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonCancel" ) ); + NameKeyType buttonCancelID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonCancel" ); GameWindow *buttonCancel = TheWindowManager->winGetWindowFromId(parent, buttonCancelID); buttonCancel->winGetPosition(&buttonX[2], &buttonY[2]); @@ -161,11 +161,11 @@ static GameWindow *gogoExMessageBox(Int x, Int y, Int width, Int height, Unsigne } // Fill the text into the text boxes - NameKeyType staticTextTitleID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:StaticTextTitle" ) ); + NameKeyType staticTextTitleID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:StaticTextTitle" ); GameWindow *staticTextTitle = TheWindowManager->winGetWindowFromId(parent, staticTextTitleID); GadgetStaticTextSetText(staticTextTitle,titleString); - NameKeyType staticTextMessageID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:StaticTextMessage" ) ); + NameKeyType staticTextMessageID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:StaticTextMessage" ); GameWindow *staticTextMessage = TheWindowManager->winGetWindowFromId(parent, staticTextMessageID); GadgetStaticTextSetText(staticTextMessage,bodyString); @@ -261,10 +261,10 @@ WindowMsgHandledType ExtendedMessageBoxSystem( GameWindow *window, UnsignedInt m { GameWindow *control = (GameWindow *)mData1; Int controlID = control->winGetWindowId(); - static NameKeyType buttonOkID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonOk" ) ); - static NameKeyType buttonYesID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonYes" ) ); - static NameKeyType buttonNoID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonNo" ) ); - static NameKeyType buttonCancelID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonCancel" ) ); + static NameKeyType buttonOkID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonOk" ); + static NameKeyType buttonYesID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonYes" ); + static NameKeyType buttonNoID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonNo" ); + static NameKeyType buttonCancelID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonCancel" ); WindowExMessageBoxData *MsgBoxCallbacks = (WindowExMessageBoxData *)window->winGetUserData(); MessageBoxReturnType ret = MB_RETURN_CLOSE; diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/InGameChat.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/InGameChat.cpp index 12988daaa8..9311f81063 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/InGameChat.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/InGameChat.cpp @@ -76,7 +76,7 @@ void ShowInGameChat( Bool immediate ) } else { - chatWindow = TheWindowManager->winCreateFromScript( AsciiString("InGameChat.wnd") ); + chatWindow = TheWindowManager->winCreateFromScript( "InGameChat.wnd" ); static NameKeyType textEntryChatID = TheNameKeyGenerator->nameToKey( "InGameChat.wnd:TextEntryChat" ); chatTextEntry = TheWindowManager->winGetWindowFromId( NULL, textEntryChatID ); @@ -338,7 +338,7 @@ WindowMsgHandledType InGameChatSystem( GameWindow *window, UnsignedInt msg, case GBM_SELECTED: { GameWindow *control = (GameWindow *)mData1; - static NameKeyType buttonClearID = TheNameKeyGenerator->nameToKey( AsciiString( "InGameChat.wnd:ButtonClear" ) ); + static NameKeyType buttonClearID = TheNameKeyGenerator->nameToKey( "InGameChat.wnd:ButtonClear" ); if (control && control->winGetWindowId() == buttonClearID) { if (chatTextEntry) diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/InGamePopupMessage.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/InGamePopupMessage.cpp index a5e4d2aa2a..dda3a72f76 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/InGamePopupMessage.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/InGamePopupMessage.cpp @@ -89,12 +89,12 @@ static Bool pause = FALSE; void InGamePopupMessageInit( WindowLayout *layout, void *userData ) { - parentID = TheNameKeyGenerator->nameToKey(AsciiString("InGamePopupMessage.wnd:InGamePopupMessageParent")); + parentID = TheNameKeyGenerator->nameToKey("InGamePopupMessage.wnd:InGamePopupMessageParent"); parent = TheWindowManager->winGetWindowFromId(NULL, parentID); - staticTextMessageID = TheNameKeyGenerator->nameToKey(AsciiString("InGamePopupMessage.wnd:StaticTextMessage")); + staticTextMessageID = TheNameKeyGenerator->nameToKey("InGamePopupMessage.wnd:StaticTextMessage"); staticTextMessage = TheWindowManager->winGetWindowFromId(parent, staticTextMessageID); - buttonOkID = TheNameKeyGenerator->nameToKey(AsciiString("InGamePopupMessage.wnd:ButtonOk")); + buttonOkID = TheNameKeyGenerator->nameToKey("InGamePopupMessage.wnd:ButtonOk"); buttonOk = TheWindowManager->winGetWindowFromId(parent, buttonOkID); PopupMessageData *pMData = TheInGameUI->getPopupMessageData(); 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 cbb8a8c5a0..133d11a141 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/CreditsMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/CreditsMenu.cpp @@ -86,7 +86,7 @@ void CreditsMenuInit( WindowLayout *layout, void *userData ) TheCredits->load(); TheCredits->init(); - parentMainMenuID = TheNameKeyGenerator->nameToKey( AsciiString("CreditsMenu.wnd:ParentCreditsWindow") ); + parentMainMenuID = TheNameKeyGenerator->nameToKey( "CreditsMenu.wnd:ParentCreditsWindow" ); parentMainMenu = TheWindowManager->winGetWindowFromId( NULL, parentMainMenuID ); @@ -99,7 +99,7 @@ void CreditsMenuInit( WindowLayout *layout, void *userData ) TheAudio->removeAudioEvent( AHSV_StopTheMusicFade ); - AudioEventRTS event( AsciiString( "Credits" ) ); + AudioEventRTS event( "Credits" ); event.setShouldFade( TRUE ); TheAudio->addAudioEvent( &event ); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DifficultySelect.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DifficultySelect.cpp index 886e92cd1e..46446f8dbd 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DifficultySelect.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DifficultySelect.cpp @@ -133,11 +133,11 @@ void DifficultySelectInit( WindowLayout *layout, void *userData ) buttonOk = TheWindowManager->winGetWindowFromId( parent, buttonOkID ); buttonCancelID = TheNameKeyGenerator->nameToKey( "DifficultySelect.wnd:ButtonCancel" ); buttonCancel = TheWindowManager->winGetWindowFromId( parent, buttonCancelID ); - radioButtonEasyAIID = TheNameKeyGenerator->nameToKey( AsciiString("DifficultySelect.wnd:RadioButtonEasy") ); + radioButtonEasyAIID = TheNameKeyGenerator->nameToKey( "DifficultySelect.wnd:RadioButtonEasy" ); radioButtonEasyAI = TheWindowManager->winGetWindowFromId( parent, radioButtonEasyAIID ); - radioButtonMediumAIID = TheNameKeyGenerator->nameToKey( AsciiString("DifficultySelect.wnd:RadioButtonMedium") ); + radioButtonMediumAIID = TheNameKeyGenerator->nameToKey( "DifficultySelect.wnd:RadioButtonMedium" ); radioButtonMediumAI = TheWindowManager->winGetWindowFromId( parent, radioButtonMediumAIID ); - radioButtonHardAIID = TheNameKeyGenerator->nameToKey( AsciiString("DifficultySelect.wnd:RadioButtonHard") ); + radioButtonHardAIID = TheNameKeyGenerator->nameToKey( "DifficultySelect.wnd:RadioButtonHard" ); radioButtonHardAI = TheWindowManager->winGetWindowFromId( parent, radioButtonHardAIID ); s_AIDiff = DIFFICULTY_NORMAL; diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DisconnectWindow.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DisconnectWindow.cpp index 8b6d0e6820..1c3ce0ea66 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DisconnectWindow.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DisconnectWindow.cpp @@ -70,8 +70,8 @@ static GameWindow *buttonVotePlayer6Window = NULL; static GameWindow *buttonVotePlayer7Window = NULL; static void InitDisconnectWindow( void ) { - textEntryID = TheNameKeyGenerator->nameToKey( AsciiString("DisconnectScreen.wnd:TextEntry")); - textDisplayID = TheNameKeyGenerator->nameToKey( AsciiString("DisconnectScreen.wnd:ListboxTextDisplay")); + textEntryID = TheNameKeyGenerator->nameToKey( "DisconnectScreen.wnd:TextEntry"); + textDisplayID = TheNameKeyGenerator->nameToKey( "DisconnectScreen.wnd:ListboxTextDisplay"); textEntryWindow = TheWindowManager->winGetWindowFromId(NULL, textEntryID); textDisplayWindow = TheWindowManager->winGetWindowFromId(NULL, textDisplayID); @@ -81,16 +81,16 @@ static void InitDisconnectWindow( void ) { TheWindowManager->winSetFocus(textEntryWindow); } - buttonQuitID = TheNameKeyGenerator->nameToKey( AsciiString("DisconnectScreen.wnd:ButtonQuitGame")); + buttonQuitID = TheNameKeyGenerator->nameToKey( "DisconnectScreen.wnd:ButtonQuitGame"); buttonQuitWindow = TheWindowManager->winGetWindowFromId(NULL, buttonQuitID); - buttonVotePlayer1ID = TheNameKeyGenerator->nameToKey( AsciiString("DisconnectScreen.wnd:ButtonKickPlayer1")); - buttonVotePlayer2ID = TheNameKeyGenerator->nameToKey( AsciiString("DisconnectScreen.wnd:ButtonKickPlayer2")); - buttonVotePlayer3ID = TheNameKeyGenerator->nameToKey( AsciiString("DisconnectScreen.wnd:ButtonKickPlayer3")); - buttonVotePlayer4ID = TheNameKeyGenerator->nameToKey( AsciiString("DisconnectScreen.wnd:ButtonKickPlayer4")); - buttonVotePlayer5ID = TheNameKeyGenerator->nameToKey( AsciiString("DisconnectScreen.wnd:ButtonKickPlayer5")); - buttonVotePlayer6ID = TheNameKeyGenerator->nameToKey( AsciiString("DisconnectScreen.wnd:ButtonKickPlayer6")); - buttonVotePlayer7ID = TheNameKeyGenerator->nameToKey( AsciiString("DisconnectScreen.wnd:ButtonKickPlayer7")); + buttonVotePlayer1ID = TheNameKeyGenerator->nameToKey( "DisconnectScreen.wnd:ButtonKickPlayer1"); + buttonVotePlayer2ID = TheNameKeyGenerator->nameToKey( "DisconnectScreen.wnd:ButtonKickPlayer2"); + buttonVotePlayer3ID = TheNameKeyGenerator->nameToKey( "DisconnectScreen.wnd:ButtonKickPlayer3"); + buttonVotePlayer4ID = TheNameKeyGenerator->nameToKey( "DisconnectScreen.wnd:ButtonKickPlayer4"); + buttonVotePlayer5ID = TheNameKeyGenerator->nameToKey( "DisconnectScreen.wnd:ButtonKickPlayer5"); + buttonVotePlayer6ID = TheNameKeyGenerator->nameToKey( "DisconnectScreen.wnd:ButtonKickPlayer6"); + buttonVotePlayer7ID = TheNameKeyGenerator->nameToKey( "DisconnectScreen.wnd:ButtonKickPlayer7"); buttonVotePlayer1Window = TheWindowManager->winGetWindowFromId(NULL, buttonVotePlayer1ID); buttonVotePlayer2Window = TheWindowManager->winGetWindowFromId(NULL, buttonVotePlayer2ID); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/EstablishConnectionsWindow.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/EstablishConnectionsWindow.cpp index 5d27a4aada..b04aeb377a 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/EstablishConnectionsWindow.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/EstablishConnectionsWindow.cpp @@ -126,7 +126,7 @@ static void showGameSpyQMUnderlyingGUIElements( Bool show ) } static void InitEstablishConnectionsDialog( void ) { - buttonQuitID = TheNameKeyGenerator->nameToKey( AsciiString("EstablishConnectionsScreen.wnd:ButtonQuit") ); + buttonQuitID = TheNameKeyGenerator->nameToKey( "EstablishConnectionsScreen.wnd:ButtonQuit" ); buttonQuitWindow = TheWindowManager->winGetWindowFromId(NULL, buttonQuitID); } 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 65d6d57e03..b11e605499 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/GameInfoWindow.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/GameInfoWindow.cpp @@ -67,7 +67,7 @@ static WindowLayout *gameInfoWindowLayout = NULL; void CreateLANGameInfoWindow( GameWindow *sizeAndPosWin ) { if( !gameInfoWindowLayout ) - gameInfoWindowLayout = TheWindowManager->winCreateLayout( AsciiString( "Menus/GameInfoWindow.wnd" ) ); + gameInfoWindowLayout = TheWindowManager->winCreateLayout( "Menus/GameInfoWindow.wnd" ); gameInfoWindowLayout->runInit(); gameInfoWindowLayout->bringForward(); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/KeyboardOptionsMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/KeyboardOptionsMenu.cpp index 7b16087011..1bc075b6f2 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/KeyboardOptionsMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/KeyboardOptionsMenu.cpp @@ -395,7 +395,7 @@ void KeyboardOptionsMenuInit( WindowLayout *layout, void *userData ) parentKeyboardOptionsMenu = TheWindowManager->winGetWindowFromId( NULL, parentKeyboardOptionsMenuID ); // get ids for our children controls - buttonBackID = TheNameKeyGenerator->nameToKey( AsciiString("KeyboardOptionsMenu.wnd:ButtonBack") ); + buttonBackID = TheNameKeyGenerator->nameToKey( "KeyboardOptionsMenu.wnd:ButtonBack" ); buttonBack = TheWindowManager->winGetWindowFromId( parentKeyboardOptionsMenu, buttonBackID ); comboBoxCategoryListID = TheNameKeyGenerator->nameToKey( "KeyboardOptionsMenu.wnd:ComboBoxCategoryList" ); 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 ac415e0229..b884e58bdf 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp @@ -615,15 +615,15 @@ void lanUpdateSlotList( void ) void InitLanGameGadgets( void ) { //Initialize the gadget IDs - parentLanGameOptionsID = TheNameKeyGenerator->nameToKey( AsciiString( "LanGameOptionsMenu.wnd:LanGameOptionsMenuParent" ) ); - buttonBackID = TheNameKeyGenerator->nameToKey( AsciiString( "LanGameOptionsMenu.wnd:ButtonBack" ) ); - buttonStartID = TheNameKeyGenerator->nameToKey( AsciiString( "LanGameOptionsMenu.wnd:ButtonStart" ) ); - textEntryChatID = TheNameKeyGenerator->nameToKey( AsciiString( "LanGameOptionsMenu.wnd:TextEntryChat" ) ); - textEntryMapDisplayID = TheNameKeyGenerator->nameToKey( AsciiString( "LanGameOptionsMenu.wnd:TextEntryMapDisplay" ) ); - listboxChatWindowLanGameID = TheNameKeyGenerator->nameToKey( AsciiString( "LanGameOptionsMenu.wnd:ListboxChatWindowLanGame" ) ); - buttonEmoteID = TheNameKeyGenerator->nameToKey( AsciiString( "LanGameOptionsMenu.wnd:ButtonEmote" ) ); - buttonSelectMapID = TheNameKeyGenerator->nameToKey( AsciiString( "LanGameOptionsMenu.wnd:ButtonSelectMap" ) ); - windowMapID = TheNameKeyGenerator->nameToKey( AsciiString( "LanGameOptionsMenu.wnd:MapWindow" ) ); + parentLanGameOptionsID = TheNameKeyGenerator->nameToKey( "LanGameOptionsMenu.wnd:LanGameOptionsMenuParent" ); + buttonBackID = TheNameKeyGenerator->nameToKey( "LanGameOptionsMenu.wnd:ButtonBack" ); + buttonStartID = TheNameKeyGenerator->nameToKey( "LanGameOptionsMenu.wnd:ButtonStart" ); + textEntryChatID = TheNameKeyGenerator->nameToKey( "LanGameOptionsMenu.wnd:TextEntryChat" ); + textEntryMapDisplayID = TheNameKeyGenerator->nameToKey( "LanGameOptionsMenu.wnd:TextEntryMapDisplay" ); + listboxChatWindowLanGameID = TheNameKeyGenerator->nameToKey( "LanGameOptionsMenu.wnd:ListboxChatWindowLanGame" ); + buttonEmoteID = TheNameKeyGenerator->nameToKey( "LanGameOptionsMenu.wnd:ButtonEmote" ); + buttonSelectMapID = TheNameKeyGenerator->nameToKey( "LanGameOptionsMenu.wnd:ButtonSelectMap" ); + windowMapID = TheNameKeyGenerator->nameToKey( "LanGameOptionsMenu.wnd:MapWindow" ); // Initialize the pointers to our gadgets parentLanGameOptions = TheWindowManager->winGetWindowFromId( NULL, parentLanGameOptionsID ); @@ -1159,7 +1159,7 @@ WindowMsgHandledType LanGameOptionsMenuSystem( GameWindow *window, UnsignedInt m { //buttonBack->winEnable( false ); - mapSelectLayout = TheWindowManager->winCreateLayout( AsciiString( "Menus/LanMapSelectMenu.wnd" ) ); + mapSelectLayout = TheWindowManager->winCreateLayout( "Menus/LanMapSelectMenu.wnd" ); mapSelectLayout->runInit(); mapSelectLayout->hide( FALSE ); mapSelectLayout->bringForward(); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp index bfc8d63263..9f65481880 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp @@ -367,20 +367,20 @@ void LanLobbyMenuInit( WindowLayout *layout, void *userData ) LANisShuttingDown = false; // get the ids for our controls - parentLanLobbyID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:LanLobbyMenuParent" ) ); - buttonBackID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:ButtonBack" ) ); - buttonClearID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:ButtonClear" ) ); - buttonHostID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:ButtonHost" ) ); - buttonJoinID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:ButtonJoin" ) ); - buttonDirectConnectID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:ButtonDirectConnect" ) ); - buttonEmoteID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:ButtonEmote" ) ); - staticToolTipID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:StaticToolTip" ) ); - textEntryPlayerNameID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:TextEntryPlayerName" ) ); - textEntryChatID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:TextEntryChat" ) ); - listboxPlayersID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:ListboxPlayers" ) ); - listboxChatWindowID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:ListboxChatWindowLanLobby" ) ); - listboxGamesID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:ListboxGames" ) ); - staticTextGameInfoID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:StaticTextGameInfo" ) ); + parentLanLobbyID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:LanLobbyMenuParent" ); + buttonBackID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:ButtonBack" ); + buttonClearID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:ButtonClear" ); + buttonHostID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:ButtonHost" ); + buttonJoinID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:ButtonJoin" ); + buttonDirectConnectID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:ButtonDirectConnect" ); + buttonEmoteID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:ButtonEmote" ); + staticToolTipID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:StaticToolTip" ); + textEntryPlayerNameID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:TextEntryPlayerName" ); + textEntryChatID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:TextEntryChat" ); + listboxPlayersID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:ListboxPlayers" ); + listboxChatWindowID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:ListboxChatWindowLanLobby" ); + listboxGamesID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:ListboxGames" ); + staticTextGameInfoID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:StaticTextGameInfo" ); // Get pointers to the window buttons @@ -786,7 +786,7 @@ WindowMsgHandledType LanLobbyMenuSystem( GameWindow *window, UnsignedInt msg, else if ( controlID == buttonJoinID ) { - //TheShell->push( AsciiString("Menus/LanGameOptionsMenu.wnd") ); + //TheShell->push( "Menus/LanGameOptionsMenu.wnd" ); int rowSelected = -1; GadgetListBoxGetSelected( listboxGames, &rowSelected ); @@ -822,7 +822,7 @@ WindowMsgHandledType LanLobbyMenuSystem( GameWindow *window, UnsignedInt msg, else if (controlID == buttonDirectConnectID) { TheLAN->RequestLobbyLeave( false ); - TheShell->push(AsciiString("Menus/NetworkDirectConnect.wnd")); + TheShell->push("Menus/NetworkDirectConnect.wnd"); } break; 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 0fc2d8483b..ff48c172f7 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanMapSelectMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanMapSelectMenu.cpp @@ -138,10 +138,10 @@ void LanMapSelectMenuInit( WindowLayout *layout, void *userData ) } - buttonBack = TheNameKeyGenerator->nameToKey( AsciiString("LanMapSelectMenu.wnd:ButtonBack") ); - buttonOK = TheNameKeyGenerator->nameToKey( AsciiString("LanMapSelectMenu.wnd:ButtonOK") ); - listboxMap = TheNameKeyGenerator->nameToKey( AsciiString("LanMapSelectMenu.wnd:ListboxMap") ); - winMapPreviewID = TheNameKeyGenerator->nameToKey( AsciiString("LanMapSelectMenu.wnd:WinMapPreview") ); + buttonBack = TheNameKeyGenerator->nameToKey( "LanMapSelectMenu.wnd:ButtonBack" ); + buttonOK = TheNameKeyGenerator->nameToKey( "LanMapSelectMenu.wnd:ButtonOK" ); + listboxMap = TheNameKeyGenerator->nameToKey( "LanMapSelectMenu.wnd:ListboxMap" ); + winMapPreviewID = TheNameKeyGenerator->nameToKey( "LanMapSelectMenu.wnd:WinMapPreview" ); radioButtonSystemMapsID = TheNameKeyGenerator->nameToKey( "LanMapSelectMenu.wnd:RadioButtonSystemMaps" ); radioButtonUserMapsID = TheNameKeyGenerator->nameToKey( "LanMapSelectMenu.wnd:RadioButtonUserMaps" ); 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 c6df2bd82e..11d3090148 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp @@ -412,7 +412,7 @@ GameWindow *win = NULL; // Originally this label does not exist in the Main Menu. It can be copied from the Options Menu. static void initLabelVersion() { - NameKeyType versionID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:LabelVersion") ); + NameKeyType versionID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:LabelVersion" ); GameWindow *labelVersion = TheWindowManager->winGetWindowFromId( NULL, versionID ); if (labelVersion) @@ -449,40 +449,40 @@ void MainMenuInit( WindowLayout *layout, void *userData ) dropDownWindows[i] = NULL; // get ids for our windows - mainMenuID = TheNameKeyGenerator->nameToKey( AsciiString( "MainMenu.wnd:MainMenuParent" ) ); -// campaignID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonCampaign") ); - skirmishID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonSkirmish") ); - onlineID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonOnline") ); - networkID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonNetwork") ); - optionsID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonOptions") ); - exitID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonExit") ); - motdID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonMOTD") ); - worldBuilderID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonWorldBuilder") ); - getUpdateID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonGetUpdate") ); - buttonTRAININGID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonTRAINING") ); - buttonUSAID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonUSA") ); - buttonGLAID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonGLA") ); - buttonChinaID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonChina") ); - buttonUSARecentSaveID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonUSARecentSave") ); - buttonUSALoadGameID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonUSALoadGame") ); - buttonGLARecentSaveID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonGLARecentSave") ); - buttonGLALoadGameID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonGLALoadGame") ); - buttonChinaRecentSaveID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonChinaRecentSave") ); - buttonChinaLoadGameID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonChinaLoadGame") ); - buttonSinglePlayerID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonSinglePlayer") ); - buttonMultiPlayerID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonMultiplayer") ); - buttonMultiBackID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonMultiBack") ); - buttonSingleBackID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonSingleBack") ); - buttonLoadReplayBackID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonLoadReplayBack") ); - buttonReplayID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonReplay") ); - buttonLoadReplayID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonLoadReplay") ); - buttonLoadID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonLoadGame") ); - buttonCreditsID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonCredits") ); - - buttonEasyID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonEasy") ); - buttonMediumID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonMedium") ); - buttonHardID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonHard") ); - buttonDiffBackID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonDiffBack") ); + mainMenuID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:MainMenuParent" ); +// campaignID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonCampaign" ); + skirmishID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonSkirmish" ); + onlineID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonOnline" ); + networkID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonNetwork" ); + optionsID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonOptions" ); + exitID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonExit" ); + motdID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonMOTD" ); + worldBuilderID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonWorldBuilder" ); + getUpdateID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonGetUpdate" ); + buttonTRAININGID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonTRAINING" ); + buttonUSAID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonUSA" ); + buttonGLAID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonGLA" ); + buttonChinaID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonChina" ); + buttonUSARecentSaveID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonUSARecentSave" ); + buttonUSALoadGameID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonUSALoadGame" ); + buttonGLARecentSaveID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonGLARecentSave" ); + buttonGLALoadGameID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonGLALoadGame" ); + buttonChinaRecentSaveID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonChinaRecentSave" ); + buttonChinaLoadGameID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonChinaLoadGame" ); + buttonSinglePlayerID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonSinglePlayer" ); + buttonMultiPlayerID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonMultiplayer" ); + buttonMultiBackID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonMultiBack" ); + buttonSingleBackID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonSingleBack" ); + buttonLoadReplayBackID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonLoadReplayBack" ); + buttonReplayID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonReplay" ); + buttonLoadReplayID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonLoadReplay" ); + buttonLoadID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonLoadGame" ); + buttonCreditsID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonCredits" ); + + buttonEasyID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonEasy" ); + buttonMediumID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonMedium" ); + buttonHardID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonHard" ); + buttonDiffBackID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonDiffBack" ); // get pointers to the window buttons parentMainMenu = TheWindowManager->winGetWindowFromId( NULL, mainMenuID ); @@ -518,11 +518,11 @@ void MainMenuInit( WindowLayout *layout, void *userData ) buttonChinaRecentSave = TheWindowManager->winGetWindowFromId( parentMainMenu, buttonChinaRecentSaveID ); buttonChinaLoadGame = TheWindowManager->winGetWindowFromId( parentMainMenu, buttonChinaLoadGameID ); - dropDownWindows[DROPDOWN_SINGLE] = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:MapBorder") )); - dropDownWindows[DROPDOWN_MULTIPLAYER] = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:MapBorder1") ) ); - dropDownWindows[DROPDOWN_MAIN] = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:MapBorder2") ) ); - dropDownWindows[DROPDOWN_LOADREPLAY] = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:MapBorder3") ) ); - dropDownWindows[DROPDOWN_DIFFICULTY] = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:MapBorder4") ) ); + dropDownWindows[DROPDOWN_SINGLE] = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( "MainMenu.wnd:MapBorder" )); + dropDownWindows[DROPDOWN_MULTIPLAYER] = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( "MainMenu.wnd:MapBorder1" ) ); + dropDownWindows[DROPDOWN_MAIN] = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( "MainMenu.wnd:MapBorder2" ) ); + dropDownWindows[DROPDOWN_LOADREPLAY] = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( "MainMenu.wnd:MapBorder3" ) ); + dropDownWindows[DROPDOWN_DIFFICULTY] = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( "MainMenu.wnd:MapBorder4" ) ); for(i = 1; i < DROPDOWN_COUNT; ++i) dropDownWindows[i]->winHide(TRUE); @@ -613,7 +613,7 @@ void MainMenuInit( WindowLayout *layout, void *userData ) //pendingDropDown =DROPDOWN_MAIN; - GameWindow *rule = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:MainMenuRuler") ) ); + GameWindow *rule = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( "MainMenu.wnd:MainMenuRuler" ) ); if(rule) rule->winHide(TRUE); campaignSelected = FALSE; @@ -1245,7 +1245,7 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, if( control == buttonCampaign ) { buttonPushed = TRUE; - TheShell->push(AsciiString( "Menus/MapSelectMenu.wnd" )); + TheShell->push("Menus/MapSelectMenu.wnd"); // As soon as we have a campaign, add it in here!; } #ifdef TEST_COMPRESSION @@ -1350,7 +1350,7 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, buttonPushed = TRUE; dropDownWindows[DROPDOWN_LOADREPLAY]->winHide(FALSE); TheTransitionHandler->reverse("MainMenuLoadReplayMenuBackTransition"); - TheShell->push(AsciiString("Menus/SaveLoad.wnd")); + TheShell->push("Menus/SaveLoad.wnd"); } else if( controlID == buttonReplayID ) @@ -1361,7 +1361,7 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, buttonPushed = TRUE; dropDownWindows[DROPDOWN_LOADREPLAY]->winHide(FALSE); TheTransitionHandler->reverse("MainMenuLoadReplayMenuBackTransition"); - TheShell->push(AsciiString("Menus/ReplayMenu.wnd")); + TheShell->push("Menus/ReplayMenu.wnd"); } else if( controlID == skirmishID ) { @@ -1373,7 +1373,7 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, TheTransitionHandler->remove("MainMenuFactionSkirmish"); TheTransitionHandler->reverse("MainMenuSinglePlayerMenuBackSkirmish"); - TheShell->push( AsciiString("Menus/SkirmishGameOptionsMenu.wnd") ); + TheShell->push( "Menus/SkirmishGameOptionsMenu.wnd" ); TheScriptEngine->signalUIInteract(TheShellHookNames[SHELL_SCRIPT_HOOK_MAIN_MENU_SKIRMISH_SELECTED]); } else if( controlID == onlineID ) @@ -1398,7 +1398,7 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, buttonPushed = TRUE; dropDownWindows[DROPDOWN_MULTIPLAYER]->winHide(FALSE); TheTransitionHandler->reverse("MainMenuMultiPlayerMenuTransitionToNext"); - TheShell->push( AsciiString("Menus/LanLobbyMenu.wnd") ); + TheShell->push( "Menus/LanLobbyMenu.wnd" ); TheScriptEngine->signalUIInteract(TheShellHookNames[SHELL_SCRIPT_HOOK_MAIN_MENU_NETWORK_SELECTED]); } @@ -1486,7 +1486,7 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, showLogo = FALSE; showSide = SHOW_USA; // WindowLayout *layout = NULL; -// layout = TheWindowManager->winCreateLayout( AsciiString( "Menus/DifficultySelect.wnd" ) ); +// layout = TheWindowManager->winCreateLayout( "Menus/DifficultySelect.wnd" ); // layout->runInit(); // layout->hide( FALSE ); // layout->bringForward(); @@ -1510,7 +1510,7 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, showLogo = FALSE; showSide = SHOW_GLA; // WindowLayout *layout = NULL; -// layout = TheWindowManager->winCreateLayout( AsciiString( "Menus/DifficultySelect.wnd" ) ); +// layout = TheWindowManager->winCreateLayout( "Menus/DifficultySelect.wnd" ); // layout->runInit(); // layout->hide( FALSE ); // layout->bringForward(); @@ -1535,7 +1535,7 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, showSide = SHOW_CHINA; // WindowLayout *layout = NULL; -// layout = TheWindowManager->winCreateLayout( AsciiString( "Menus/DifficultySelect.wnd" ) ); +// layout = TheWindowManager->winCreateLayout( "Menus/DifficultySelect.wnd" ); // layout->runInit(); // layout->hide( FALSE ); // layout->bringForward(); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MapSelectMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MapSelectMenu.cpp index 8f9ccf3c86..563f242a47 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MapSelectMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MapSelectMenu.cpp @@ -122,7 +122,7 @@ void SetDifficultyRadioButton( void ) { case DIFFICULTY_EASY: { - NameKeyType radioButtonEasyAIID = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:RadioButtonEasyAI") ); + NameKeyType radioButtonEasyAIID = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:RadioButtonEasyAI" ); GameWindow *radioButtonEasyAI = TheWindowManager->winGetWindowFromId( parent, radioButtonEasyAIID ); GadgetRadioSetSelection(radioButtonEasyAI, FALSE); s_AIDiff = DIFFICULTY_EASY; @@ -130,7 +130,7 @@ void SetDifficultyRadioButton( void ) } case DIFFICULTY_NORMAL: { - NameKeyType radioButtonMediumAIID = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:RadioButtonMediumAI") ); + NameKeyType radioButtonMediumAIID = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:RadioButtonMediumAI" ); GameWindow *radioButtonMediumAI = TheWindowManager->winGetWindowFromId( parent, radioButtonMediumAIID ); GadgetRadioSetSelection(radioButtonMediumAI, FALSE); s_AIDiff = DIFFICULTY_NORMAL; @@ -138,7 +138,7 @@ void SetDifficultyRadioButton( void ) } case DIFFICULTY_HARD: { - NameKeyType radioButtonHardAIID = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:RadioButtonHardAI") ); + NameKeyType radioButtonHardAIID = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:RadioButtonHardAI" ); GameWindow *radioButtonHardAI = TheWindowManager->winGetWindowFromId( parent, radioButtonHardAIID ); GadgetRadioSetSelection(radioButtonHardAI, FALSE); s_AIDiff = DIFFICULTY_HARD; @@ -188,10 +188,10 @@ void MapSelectMenuInit( WindowLayout *layout, void *userData ) GameWindow *parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); TheWindowManager->winSetFocus( parent ); - NameKeyType buttonBackID = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:ButtonBack") ); + NameKeyType buttonBackID = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:ButtonBack" ); GameWindow *buttonBack = TheWindowManager->winGetWindowFromId( NULL, buttonBackID ); - NameKeyType buttonOKID = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:ButtonOK") ); + NameKeyType buttonOKID = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:ButtonOK" ); GameWindow *buttonOK = TheWindowManager->winGetWindowFromId( NULL, buttonOKID ); @@ -324,12 +324,12 @@ WindowMsgHandledType MapSelectMenuSystem( GameWindow *window, UnsignedInt msg, { // get ids for our children controls - buttonBack = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:ButtonBack") ); - buttonOK = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:ButtonOK") ); - listboxMap = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:ListboxMap") ); - radioButtonEasyAI = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:RadioButtonEasyAI") ); - radioButtonMediumAI = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:RadioButtonMediumAI") ); - radioButtonHardAI = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:RadioButtonHardAI") ); + buttonBack = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:ButtonBack" ); + buttonOK = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:ButtonOK" ); + listboxMap = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:ListboxMap" ); + radioButtonEasyAI = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:RadioButtonEasyAI" ); + radioButtonMediumAI = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:RadioButtonMediumAI" ); + radioButtonHardAI = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:RadioButtonHardAI" ); break; } @@ -418,7 +418,7 @@ WindowMsgHandledType MapSelectMenuSystem( GameWindow *window, UnsignedInt msg, buttonPushed = true; // reset the campaign manager to empty if( TheCampaignManager ) - TheCampaignManager->setCampaign( AsciiString( "" ) ); + TheCampaignManager->setCampaign( "" ); // get text of the map to load const char *mapFname = (const char *)GadgetListBoxGetItemData( mapWindow, selected ); DEBUG_ASSERTCRASH(mapFname, ("No map item data")); @@ -457,7 +457,7 @@ WindowMsgHandledType MapSelectMenuSystem( GameWindow *window, UnsignedInt msg, { //buttonPushed = true; GadgetListBoxSetSelected( control, rowSelected ); - NameKeyType buttonOKID = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:ButtonOK") ); + NameKeyType buttonOKID = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:ButtonOK" ); GameWindow *buttonOK = TheWindowManager->winGetWindowFromId( NULL, buttonOKID ); TheWindowManager->winSendSystemMsg( window, GBM_SELECTED, 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 0579a917f9..32cd126db5 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp @@ -262,12 +262,12 @@ void NetworkDirectConnectInit( WindowLayout *layout, void *userData ) buttonPushed = false; isShuttingDown = false; TheShell->showShellMap(TRUE); - buttonBackID = TheNameKeyGenerator->nameToKey( AsciiString( "NetworkDirectConnect.wnd:ButtonBack" ) ); - buttonHostID = TheNameKeyGenerator->nameToKey( AsciiString( "NetworkDirectConnect.wnd:ButtonHost" ) ); - buttonJoinID = TheNameKeyGenerator->nameToKey( AsciiString( "NetworkDirectConnect.wnd:ButtonJoin" ) ); - editPlayerNameID = TheNameKeyGenerator->nameToKey( AsciiString( "NetworkDirectConnect.wnd:EditPlayerName" ) ); - comboboxRemoteIPID = TheNameKeyGenerator->nameToKey( AsciiString( "NetworkDirectConnect.wnd:ComboboxRemoteIP" ) ); - staticLocalIPID = TheNameKeyGenerator->nameToKey( AsciiString( "NetworkDirectConnect.wnd:StaticLocalIP" ) ); + buttonBackID = TheNameKeyGenerator->nameToKey( "NetworkDirectConnect.wnd:ButtonBack" ); + buttonHostID = TheNameKeyGenerator->nameToKey( "NetworkDirectConnect.wnd:ButtonHost" ); + buttonJoinID = TheNameKeyGenerator->nameToKey( "NetworkDirectConnect.wnd:ButtonJoin" ); + editPlayerNameID = TheNameKeyGenerator->nameToKey( "NetworkDirectConnect.wnd:EditPlayerName" ); + comboboxRemoteIPID = TheNameKeyGenerator->nameToKey( "NetworkDirectConnect.wnd:ComboboxRemoteIP" ); + staticLocalIPID = TheNameKeyGenerator->nameToKey( "NetworkDirectConnect.wnd:StaticLocalIP" ); buttonBack = TheWindowManager->winGetWindowFromId( NULL, buttonBackID); buttonHost = TheWindowManager->winGetWindowFromId( NULL, buttonHostID); 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 60ff6cbcee..8cffa3c435 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp @@ -1144,9 +1144,9 @@ static void saveOptions( void ) { TheWritableGlobalData->m_firewallSendDelay = GadgetCheckBoxIsChecked(checkSendDelay); if (TheGlobalData->m_firewallSendDelay) { - (*pref)["SendDelay"] = AsciiString("yes"); + (*pref)["SendDelay"] = "yes"; } else { - (*pref)["SendDelay"] = AsciiString("no"); + (*pref)["SendDelay"] = "no"; } } @@ -1169,36 +1169,36 @@ static void saveOptions( void ) } TheWritableGlobalData->m_useShadowVolumes = GadgetCheckBoxIsChecked( check3DShadows ); - (*pref)["UseShadowVolumes"] = TheWritableGlobalData->m_useShadowVolumes ? AsciiString("yes") : AsciiString("no"); + (*pref)["UseShadowVolumes"] = TheWritableGlobalData->m_useShadowVolumes ? "yes" : "no"; TheWritableGlobalData->m_useShadowDecals = GadgetCheckBoxIsChecked( check2DShadows ); - (*pref)["UseShadowDecals"] = TheWritableGlobalData->m_useShadowDecals ? AsciiString("yes") : AsciiString("no"); + (*pref)["UseShadowDecals"] = TheWritableGlobalData->m_useShadowDecals ? "yes" : "no"; TheWritableGlobalData->m_useCloudMap = GadgetCheckBoxIsChecked( checkCloudShadows ); - (*pref)["UseCloudMap"] = TheGlobalData->m_useCloudMap ? AsciiString("yes") : AsciiString("no"); + (*pref)["UseCloudMap"] = TheGlobalData->m_useCloudMap ? "yes" : "no"; TheWritableGlobalData->m_useLightMap = GadgetCheckBoxIsChecked( checkGroundLighting ); - (*pref)["UseLightMap"] = TheGlobalData->m_useLightMap ? AsciiString("yes") : AsciiString("no"); + (*pref)["UseLightMap"] = TheGlobalData->m_useLightMap ? "yes" : "no"; TheWritableGlobalData->m_showSoftWaterEdge = GadgetCheckBoxIsChecked( checkSmoothWater ); - (*pref)["ShowSoftWaterEdge"] = TheGlobalData->m_showSoftWaterEdge ? AsciiString("yes") : AsciiString("no"); + (*pref)["ShowSoftWaterEdge"] = TheGlobalData->m_showSoftWaterEdge ? "yes" : "no"; TheWritableGlobalData->m_useDrawModuleLOD = !GadgetCheckBoxIsChecked( checkExtraAnimations ); TheWritableGlobalData->m_useTreeSway = !TheWritableGlobalData->m_useDrawModuleLOD; //borrow same setting. - (*pref)["ExtraAnimations"] = TheGlobalData->m_useDrawModuleLOD ? AsciiString("no") : AsciiString("yes"); + (*pref)["ExtraAnimations"] = TheGlobalData->m_useDrawModuleLOD ? "no" : "yes"; TheWritableGlobalData->m_enableDynamicLOD = !GadgetCheckBoxIsChecked( checkNoDynamicLod ); - (*pref)["DynamicLOD"] = TheGlobalData->m_enableDynamicLOD ? AsciiString("yes") : AsciiString("no"); + (*pref)["DynamicLOD"] = TheGlobalData->m_enableDynamicLOD ? "yes" : "no"; // Never write this out //TheWritableGlobalData->m_useFpsLimit = !GadgetCheckBoxIsChecked( checkUnlockFps ); - //(*pref)["FPSLimit"] = TheGlobalData->m_useFpsLimit ? AsciiString("yes") : AsciiString("no"); + //(*pref)["FPSLimit"] = TheGlobalData->m_useFpsLimit ? "yes" : "no"; TheWritableGlobalData->m_enableBehindBuildingMarkers = GadgetCheckBoxIsChecked( checkBuildingOcclusion ); - (*pref)["BuildingOcclusion"] = TheWritableGlobalData->m_enableBehindBuildingMarkers ? AsciiString("yes") : AsciiString("no"); + (*pref)["BuildingOcclusion"] = TheWritableGlobalData->m_enableBehindBuildingMarkers ? "yes" : "no"; TheWritableGlobalData->m_useTrees = GadgetCheckBoxIsChecked( checkProps); - (*pref)["ShowTrees"] = TheWritableGlobalData->m_useTrees ? AsciiString("yes") : AsciiString("no"); + (*pref)["ShowTrees"] = TheWritableGlobalData->m_useTrees ? "yes" : "no"; //------------------------------------------------------------------------------------------------- // Particle Cap slider @@ -1295,7 +1295,7 @@ static void saveOptions( void ) //------------------------------------------------------------------------------------------------- // mouse mode TheWritableGlobalData->m_useAlternateMouse = GadgetCheckBoxIsChecked(checkAlternateMouse); - (*pref)["UseAlternateMouse"] = TheWritableGlobalData->m_useAlternateMouse ? AsciiString("yes") : AsciiString("no"); + (*pref)["UseAlternateMouse"] = TheWritableGlobalData->m_useAlternateMouse ? "yes" : "no"; // TheSuperHackers @todo Add combo box ? { @@ -1598,7 +1598,7 @@ static void cancelAdvancedOptions() // TheSuperHackers @tweak Now prints additional version information in the version label. static void initLabelVersion() { - NameKeyType versionID = TheNameKeyGenerator->nameToKey( AsciiString("OptionsMenu.wnd:LabelVersion") ); + NameKeyType versionID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:LabelVersion" ); GameWindow *labelVersion = TheWindowManager->winGetWindowFromId( NULL, versionID ); if (labelVersion) @@ -1631,100 +1631,100 @@ void OptionsMenuInit( WindowLayout *layout, void *userData ) SignalUIInteraction(SHELL_SCRIPT_HOOK_OPTIONS_OPENED); - comboBoxLANIPID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ComboBoxIP" ) ); + comboBoxLANIPID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ComboBoxIP" ); comboBoxLANIP = TheWindowManager->winGetWindowFromId( NULL, comboBoxLANIPID); - comboBoxOnlineIPID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ComboBoxOnlineIP" ) ); + comboBoxOnlineIPID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ComboBoxOnlineIP" ); comboBoxOnlineIP = TheWindowManager->winGetWindowFromId( NULL, comboBoxOnlineIPID); - checkAlternateMouseID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckAlternateMouse" ) ); + checkAlternateMouseID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckAlternateMouse" ); checkAlternateMouse = TheWindowManager->winGetWindowFromId( NULL, checkAlternateMouseID); - sliderScrollSpeedID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:SliderScrollSpeed" ) ); + sliderScrollSpeedID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:SliderScrollSpeed" ); sliderScrollSpeed = TheWindowManager->winGetWindowFromId( NULL, sliderScrollSpeedID); - comboBoxAntiAliasingID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ComboBoxAntiAliasing" ) ); + comboBoxAntiAliasingID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ComboBoxAntiAliasing" ); comboBoxAntiAliasing = TheWindowManager->winGetWindowFromId( NULL, comboBoxAntiAliasingID ); - comboBoxResolutionID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ComboBoxResolution" ) ); + comboBoxResolutionID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ComboBoxResolution" ); comboBoxResolution = TheWindowManager->winGetWindowFromId( NULL, comboBoxResolutionID ); - comboBoxDetailID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ComboBoxDetail" ) ); + comboBoxDetailID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ComboBoxDetail" ); comboBoxDetail = TheWindowManager->winGetWindowFromId( NULL, comboBoxDetailID ); - checkLanguageFilterID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckLanguageFilter" ) ); + checkLanguageFilterID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckLanguageFilter" ); checkLanguageFilter = TheWindowManager->winGetWindowFromId( NULL, checkLanguageFilterID ); - checkSendDelayID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckSendDelay" ) ); + checkSendDelayID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckSendDelay" ); checkSendDelay = TheWindowManager->winGetWindowFromId( NULL, checkSendDelayID); - buttonFirewallRefreshID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ButtonFirewallRefresh" ) ); + buttonFirewallRefreshID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ButtonFirewallRefresh" ); buttonFirewallRefresh = TheWindowManager->winGetWindowFromId( NULL, buttonFirewallRefreshID); - checkDrawAnchorID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckBoxDrawAnchor" ) ); + checkDrawAnchorID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckBoxDrawAnchor" ); checkDrawAnchor = TheWindowManager->winGetWindowFromId( NULL, checkDrawAnchorID); - checkMoveAnchorID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckBoxMoveAnchor" ) ); + checkMoveAnchorID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckBoxMoveAnchor" ); checkMoveAnchor = TheWindowManager->winGetWindowFromId( NULL, checkMoveAnchorID); // Replay camera - checkSaveCameraID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckBoxSaveCamera" ) ); + checkSaveCameraID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckBoxSaveCamera" ); checkSaveCamera = TheWindowManager->winGetWindowFromId( NULL, checkSaveCameraID ); - checkUseCameraID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckBoxUseCamera" ) ); + checkUseCameraID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckBoxUseCamera" ); checkUseCamera = TheWindowManager->winGetWindowFromId( NULL, checkUseCameraID ); // // Speakers and 3-D Audio -// checkAudioSurroundID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckAudioSurround" ) ); +// checkAudioSurroundID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckAudioSurround" ); // checkAudioSurround = TheWindowManager->winGetWindowFromId( NULL, checkAudioSurroundID ); -// checkAudioHardwareID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckAudioHardware" ) ); +// checkAudioHardwareID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckAudioHardware" ); // checkAudioHardware = TheWindowManager->winGetWindowFromId( NULL, checkAudioHardwareID ); // // Volume Controls - sliderMusicVolumeID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:SliderMusicVolume" ) ); + sliderMusicVolumeID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:SliderMusicVolume" ); sliderMusicVolume = TheWindowManager->winGetWindowFromId( NULL, sliderMusicVolumeID ); - sliderSFXVolumeID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:SliderSFXVolume" ) ); + sliderSFXVolumeID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:SliderSFXVolume" ); sliderSFXVolume = TheWindowManager->winGetWindowFromId( NULL, sliderSFXVolumeID ); - sliderVoiceVolumeID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:SliderVoiceVolume" ) ); + sliderVoiceVolumeID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:SliderVoiceVolume" ); sliderVoiceVolume = TheWindowManager->winGetWindowFromId( NULL, sliderVoiceVolumeID ); - sliderGammaID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:SliderGamma" ) ); + sliderGammaID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:SliderGamma" ); sliderGamma = TheWindowManager->winGetWindowFromId( NULL, sliderGammaID ); -// checkBoxLowTextureDetailID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckLowTextureDetail" ) ); +// checkBoxLowTextureDetailID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckLowTextureDetail" ); // checkBoxLowTextureDetail = TheWindowManager->winGetWindowFromId( NULL, checkBoxLowTextureDetailID ); - WinAdvancedDisplayID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:WinAdvancedDisplayOptions" ) ); + WinAdvancedDisplayID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:WinAdvancedDisplayOptions" ); WinAdvancedDisplay = TheWindowManager->winGetWindowFromId( NULL, WinAdvancedDisplayID ); - ButtonAdvancedAcceptID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ButtonAdvanceAccept" ) ); + ButtonAdvancedAcceptID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ButtonAdvanceAccept" ); ButtonAdvancedAccept = TheWindowManager->winGetWindowFromId( NULL, ButtonAdvancedAcceptID ); - ButtonAdvancedCancelID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ButtonAdvanceBack" ) ); + ButtonAdvancedCancelID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ButtonAdvanceBack" ); ButtonAdvancedCancel = TheWindowManager->winGetWindowFromId( NULL, ButtonAdvancedCancelID ); - sliderTextureResolutionID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:LowResSlider" ) ); + sliderTextureResolutionID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:LowResSlider" ); sliderTextureResolution = TheWindowManager->winGetWindowFromId( NULL, sliderTextureResolutionID ); - check3DShadowsID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:Check3DShadows" ) ); + check3DShadowsID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:Check3DShadows" ); check3DShadows = TheWindowManager->winGetWindowFromId( NULL, check3DShadowsID); - check2DShadowsID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:Check2DShadows" ) ); + check2DShadowsID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:Check2DShadows" ); check2DShadows = TheWindowManager->winGetWindowFromId( NULL, check2DShadowsID); - checkCloudShadowsID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckCloudShadows" ) ); + checkCloudShadowsID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckCloudShadows" ); checkCloudShadows = TheWindowManager->winGetWindowFromId( NULL, checkCloudShadowsID); - checkGroundLightingID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckGroundLighting" ) ); + checkGroundLightingID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckGroundLighting" ); checkGroundLighting = TheWindowManager->winGetWindowFromId( NULL, checkGroundLightingID); - checkSmoothWaterID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckSmoothWater" ) ); + checkSmoothWaterID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckSmoothWater" ); checkSmoothWater = TheWindowManager->winGetWindowFromId( NULL, checkSmoothWaterID); - checkExtraAnimationsID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckExtraAnimations" ) ); + checkExtraAnimationsID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckExtraAnimations" ); checkExtraAnimations = TheWindowManager->winGetWindowFromId( NULL, checkExtraAnimationsID); - checkNoDynamicLodID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckNoDynamicLOD" ) ); + checkNoDynamicLodID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckNoDynamicLOD" ); checkNoDynamicLod = TheWindowManager->winGetWindowFromId( NULL, checkNoDynamicLodID); - checkUnlockFpsID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckUnlockFPS" ) ); + checkUnlockFpsID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckUnlockFPS" ); checkUnlockFps = TheWindowManager->winGetWindowFromId( NULL, checkUnlockFpsID); - checkBuildingOcclusionID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckBehindBuilding" ) ); + checkBuildingOcclusionID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckBehindBuilding" ); checkBuildingOcclusion = TheWindowManager->winGetWindowFromId( NULL, checkBuildingOcclusionID); - checkPropsID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckShowProps" ) ); + checkPropsID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckShowProps" ); checkProps = TheWindowManager->winGetWindowFromId( NULL, checkPropsID); - sliderParticleCapID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ParticleCapSlider" ) ); + sliderParticleCapID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ParticleCapSlider" ); sliderParticleCap = TheWindowManager->winGetWindowFromId( NULL, sliderParticleCapID ); WinAdvancedDisplay->winHide(TRUE); @@ -2197,10 +2197,10 @@ WindowMsgHandledType OptionsMenuSystem( GameWindow *window, UnsignedInt msg, { // get ids for our children controls - buttonBack = TheNameKeyGenerator->nameToKey( AsciiString("OptionsMenu.wnd:ButtonBack") ); - buttonDefaults = TheNameKeyGenerator->nameToKey( AsciiString("OptionsMenu.wnd:ButtonDefaults") ); - buttonAccept = TheNameKeyGenerator->nameToKey( AsciiString("OptionsMenu.wnd:ButtonAccept") ); - buttonKeyboardOptionsMenu = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ButtonKeyboardOptions" ) ); + buttonBack = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ButtonBack" ); + buttonDefaults = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ButtonDefaults" ); + buttonAccept = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ButtonAccept" ); + buttonKeyboardOptionsMenu = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ButtonKeyboardOptions" ); break; @@ -2318,7 +2318,7 @@ WindowMsgHandledType OptionsMenuSystem( GameWindow *window, UnsignedInt msg, } else if ( controlID == buttonKeyboardOptionsMenu ) { - TheShell->push( AsciiString( "Menus/KeyboardOptionsMenu.wnd" ) ); + TheShell->push( "Menus/KeyboardOptionsMenu.wnd" ); } else if(controlID == checkDrawAnchorID ) { diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupCommunicator.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupCommunicator.cpp index a7bc28656a..be6aaaee59 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupCommunicator.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupCommunicator.cpp @@ -69,7 +69,7 @@ void PopupCommunicatorInit( WindowLayout *layout, void *userData ) TheWindowManager->winSetModal( parent ); // get ids for our children controls - buttonOkID = TheNameKeyGenerator->nameToKey( AsciiString("PopupCommunicator.wnd:ButtonOk") ); + buttonOkID = TheNameKeyGenerator->nameToKey( "PopupCommunicator.wnd:ButtonOk" ); buttonOk = TheWindowManager->winGetWindowFromId( parent, buttonOkID ); } 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 ac8a8c08d1..4d9081deca 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupHostGame.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupHostGame.cpp @@ -306,39 +306,39 @@ void PopulateCustomLadderComboBox( void ) //------------------------------------------------------------------------------------------------- void PopupHostGameInit( WindowLayout *layout, void *userData ) { - parentPopupID = TheNameKeyGenerator->nameToKey(AsciiString("PopupHostGame.wnd:ParentHostPopUp")); + parentPopupID = TheNameKeyGenerator->nameToKey("PopupHostGame.wnd:ParentHostPopUp"); parentPopup = TheWindowManager->winGetWindowFromId(NULL, parentPopupID); - textEntryGameNameID = TheNameKeyGenerator->nameToKey(AsciiString("PopupHostGame.wnd:TextEntryGameName")); + textEntryGameNameID = TheNameKeyGenerator->nameToKey("PopupHostGame.wnd:TextEntryGameName"); textEntryGameName = TheWindowManager->winGetWindowFromId(parentPopup, textEntryGameNameID); UnicodeString name; name.translate(TheGameSpyInfo->getLocalName()); GadgetTextEntrySetText(textEntryGameName, name); - textEntryGameDescriptionID = TheNameKeyGenerator->nameToKey(AsciiString("PopupHostGame.wnd:TextEntryGameDescription")); + textEntryGameDescriptionID = TheNameKeyGenerator->nameToKey("PopupHostGame.wnd:TextEntryGameDescription"); textEntryGameDescription = TheWindowManager->winGetWindowFromId(parentPopup, textEntryGameDescriptionID); GadgetTextEntrySetText(textEntryGameDescription, UnicodeString::TheEmptyString); - textEntryLadderPasswordID = TheNameKeyGenerator->nameToKey(AsciiString("PopupHostGame.wnd:TextEntryLadderPassword")); + textEntryLadderPasswordID = TheNameKeyGenerator->nameToKey("PopupHostGame.wnd:TextEntryLadderPassword"); textEntryLadderPassword = TheWindowManager->winGetWindowFromId(parentPopup, textEntryLadderPasswordID); GadgetTextEntrySetText(textEntryLadderPassword, UnicodeString::TheEmptyString); - textEntryGamePasswordID = TheNameKeyGenerator->nameToKey(AsciiString("PopupHostGame.wnd:TextEntryGamePassword")); + textEntryGamePasswordID = TheNameKeyGenerator->nameToKey("PopupHostGame.wnd:TextEntryGamePassword"); textEntryGamePassword = TheWindowManager->winGetWindowFromId(parentPopup, textEntryGamePasswordID); GadgetTextEntrySetText(textEntryGamePassword, UnicodeString::TheEmptyString); - buttonCreateGameID = TheNameKeyGenerator->nameToKey(AsciiString("PopupHostGame.wnd:ButtonCreateGame")); + buttonCreateGameID = TheNameKeyGenerator->nameToKey("PopupHostGame.wnd:ButtonCreateGame"); buttonCreateGame = TheWindowManager->winGetWindowFromId(parentPopup, buttonCreateGameID); - buttonCancelID = TheNameKeyGenerator->nameToKey(AsciiString("PopupHostGame.wnd:ButtonCancel")); + buttonCancelID = TheNameKeyGenerator->nameToKey("PopupHostGame.wnd:ButtonCancel"); buttonCancel = TheWindowManager->winGetWindowFromId(parentPopup, buttonCancelID); - checkBoxAllowObserversID = TheNameKeyGenerator->nameToKey(AsciiString("PopupHostGame.wnd:CheckBoxAllowObservers")); + checkBoxAllowObserversID = TheNameKeyGenerator->nameToKey("PopupHostGame.wnd:CheckBoxAllowObservers"); checkBoxAllowObservers = TheWindowManager->winGetWindowFromId(parentPopup, checkBoxAllowObserversID); CustomMatchPreferences customPref; GadgetCheckBoxSetChecked(checkBoxAllowObservers, customPref.allowsObservers()); - comboBoxLadderNameID = TheNameKeyGenerator->nameToKey(AsciiString("PopupHostGame.wnd:ComboBoxLadderName")); + comboBoxLadderNameID = TheNameKeyGenerator->nameToKey("PopupHostGame.wnd:ComboBoxLadderName"); comboBoxLadderName = TheWindowManager->winGetWindowFromId(parentPopup, comboBoxLadderNameID); if (comboBoxLadderName) GadgetComboBoxReset(comboBoxLadderName); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupJoinGame.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupJoinGame.cpp index ab3c066ae5..c34c196690 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupJoinGame.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupJoinGame.cpp @@ -86,14 +86,14 @@ static void joinGame( AsciiString password ); //------------------------------------------------------------------------------------------------- void PopupJoinGameInit( WindowLayout *layout, void *userData ) { - parentPopupID = TheNameKeyGenerator->nameToKey(AsciiString("PopupJoinGame.wnd:ParentJoinPopUp")); + parentPopupID = TheNameKeyGenerator->nameToKey("PopupJoinGame.wnd:ParentJoinPopUp"); parentPopup = TheWindowManager->winGetWindowFromId(NULL, parentPopupID); - textEntryGamePasswordID = TheNameKeyGenerator->nameToKey(AsciiString("PopupJoinGame.wnd:TextEntryGamePassword")); + textEntryGamePasswordID = TheNameKeyGenerator->nameToKey("PopupJoinGame.wnd:TextEntryGamePassword"); textEntryGamePassword = TheWindowManager->winGetWindowFromId(parentPopup, textEntryGamePasswordID); GadgetTextEntrySetText(textEntryGamePassword, UnicodeString::TheEmptyString); - NameKeyType staticTextGameNameID = TheNameKeyGenerator->nameToKey(AsciiString("PopupJoinGame.wnd:StaticTextGameName")); + NameKeyType staticTextGameNameID = TheNameKeyGenerator->nameToKey("PopupJoinGame.wnd:StaticTextGameName"); GameWindow *staticTextGameName = TheWindowManager->winGetWindowFromId(parentPopup, staticTextGameNameID); GadgetStaticTextSetText(staticTextGameName, UnicodeString::TheEmptyString); 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 5322a005fc..30a86122e1 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupLadderSelect.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupLadderSelect.cpp @@ -648,7 +648,7 @@ WindowMsgHandledType RCGameDetailsMenuSystem( GameWindow *window, UnsignedInt ms const LadderInfo *linfo = TheLadderList->findLadder(theRoom->getLadderIP(), theRoom->getLadderPort()); if (linfo) { - WindowLayout *rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/PopupLadderDetails.wnd")); + WindowLayout *rcLayout = TheWindowManager->winCreateLayout("Menus/PopupLadderDetails.wnd"); if (!rcLayout) break; 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 3fffa9d000..8ea39e4230 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/QuitMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/QuitMenu.cpp @@ -81,11 +81,11 @@ static NameKeyType buttonSaveLoad = NAMEKEY_INVALID; static void initGadgetsFullQuit( void ) { - buttonExit = TheNameKeyGenerator->nameToKey( AsciiString( "QuitMenu.wnd:ButtonExit" ) ); - buttonRestart = TheNameKeyGenerator->nameToKey( AsciiString( "QuitMenu.wnd:ButtonRestart" ) ); - buttonReturn = TheNameKeyGenerator->nameToKey( AsciiString( "QuitMenu.wnd:ButtonReturn" ) ); - buttonOptions = TheNameKeyGenerator->nameToKey( AsciiString( "QuitMenu.wnd:ButtonOptions" ) ); - buttonSaveLoad = TheNameKeyGenerator->nameToKey( AsciiString( "QuitMenu.wnd:ButtonSaveLoad" ) ); + buttonExit = TheNameKeyGenerator->nameToKey( "QuitMenu.wnd:ButtonExit" ); + buttonRestart = TheNameKeyGenerator->nameToKey( "QuitMenu.wnd:ButtonRestart" ); + buttonReturn = TheNameKeyGenerator->nameToKey( "QuitMenu.wnd:ButtonReturn" ); + buttonOptions = TheNameKeyGenerator->nameToKey( "QuitMenu.wnd:ButtonOptions" ); + buttonSaveLoad = TheNameKeyGenerator->nameToKey( "QuitMenu.wnd:ButtonSaveLoad" ); buttonRestartWin = TheWindowManager->winGetWindowFromId( NULL, buttonRestart ); buttonSaveLoadWin = TheWindowManager->winGetWindowFromId( NULL, buttonSaveLoad ); @@ -95,10 +95,10 @@ static void initGadgetsFullQuit( void ) static void initGadgetsNoSaveQuit( void ) { - buttonExit = TheNameKeyGenerator->nameToKey( AsciiString( "QuitNoSave.wnd:ButtonExit" ) ); - buttonRestart = TheNameKeyGenerator->nameToKey( AsciiString( "QuitNoSave.wnd:ButtonRestart" ) ); - buttonReturn = TheNameKeyGenerator->nameToKey( AsciiString( "QuitNoSave.wnd:ButtonReturn" ) ); - buttonOptions = TheNameKeyGenerator->nameToKey( AsciiString( "QuitNoSave.wnd:ButtonOptions" ) ); + buttonExit = TheNameKeyGenerator->nameToKey( "QuitNoSave.wnd:ButtonExit" ); + buttonRestart = TheNameKeyGenerator->nameToKey( "QuitNoSave.wnd:ButtonRestart" ); + buttonReturn = TheNameKeyGenerator->nameToKey( "QuitNoSave.wnd:ButtonReturn" ); + buttonOptions = TheNameKeyGenerator->nameToKey( "QuitNoSave.wnd:ButtonOptions" ); buttonSaveLoad = NAMEKEY_INVALID; buttonRestartWin = TheWindowManager->winGetWindowFromId( NULL, buttonRestart ); @@ -301,7 +301,7 @@ void ToggleQuitMenu() WindowLayout *optLayout = TheShell->getOptionsLayout(FALSE); GameWindow *optionsParent = optLayout->getFirstWindow(); DEBUG_ASSERTCRASH(optionsParent != NULL, ("Not able to get the options layout parent window")); - GameWindow *optionsBack = TheWindowManager->winGetWindowFromId(optionsParent, TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ButtonBack" ) )); + GameWindow *optionsBack = TheWindowManager->winGetWindowFromId(optionsParent, TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ButtonBack" )); DEBUG_ASSERTCRASH(optionsBack != NULL, ("Not able to get the back button window from the options menu")); TheWindowManager->winSendSystemMsg(optLayout->getFirstWindow(), GBM_SELECTED, (WindowMsgData)optionsBack, NULL); return; @@ -310,7 +310,7 @@ void ToggleQuitMenu() { GameWindow *saveLoadParent = saveLoadMenuLayout->getFirstWindow(); DEBUG_ASSERTCRASH(saveLoadParent != NULL, ("Not able to get the save/load layout parent window")); - GameWindow *saveLoadBack = TheWindowManager->winGetWindowFromId(saveLoadParent, TheNameKeyGenerator->nameToKey( AsciiString( "PopupSaveLoad.wnd:ButtonBack" ) )); + GameWindow *saveLoadBack = TheWindowManager->winGetWindowFromId(saveLoadParent, TheNameKeyGenerator->nameToKey( "PopupSaveLoad.wnd:ButtonBack" )); DEBUG_ASSERTCRASH(saveLoadBack != NULL, ("Not able to get the back button window from the save/load menu")); TheWindowManager->winSendSystemMsg(saveLoadMenuLayout->getFirstWindow(), GBM_SELECTED, (WindowMsgData)saveLoadBack, NULL); saveLoadMenuLayout = NULL; @@ -362,7 +362,7 @@ void ToggleQuitMenu() { // we don't want to show the save load button. if(!noSaveLoadQuitMenuLayout) - noSaveLoadQuitMenuLayout = TheWindowManager->winCreateLayout( AsciiString( "Menus/QuitNoSave.wnd" ) ); + noSaveLoadQuitMenuLayout = TheWindowManager->winCreateLayout( "Menus/QuitNoSave.wnd" ); quitMenuLayout = noSaveLoadQuitMenuLayout; initGadgetsNoSaveQuit(); TheTransitionHandler->remove("QuitNoSave"); @@ -371,7 +371,7 @@ void ToggleQuitMenu() else { if(!fullQuitMenuLayout) - fullQuitMenuLayout= TheWindowManager->winCreateLayout( AsciiString( "Menus/QuitMenu.wnd" ) ); + fullQuitMenuLayout= TheWindowManager->winCreateLayout( "Menus/QuitMenu.wnd" ); quitMenuLayout = fullQuitMenuLayout; initGadgetsFullQuit(); TheTransitionHandler->remove("QuitFull"); 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 65b999a688..3571ff025d 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ReplayMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ReplayMenu.cpp @@ -373,12 +373,12 @@ void ReplayMenuInit( WindowLayout *layout, void *userData ) TheShell->showShellMap(TRUE); // get ids for our children controls - parentReplayMenuID = TheNameKeyGenerator->nameToKey( AsciiString("ReplayMenu.wnd:ParentReplayMenu") ); - buttonLoadID = TheNameKeyGenerator->nameToKey( AsciiString("ReplayMenu.wnd:ButtonLoadReplay") ); - buttonBackID = TheNameKeyGenerator->nameToKey( AsciiString("ReplayMenu.wnd:ButtonBack") ); - listboxReplayFilesID = TheNameKeyGenerator->nameToKey( AsciiString("ReplayMenu.wnd:ListboxReplayFiles") ); - buttonDeleteID = TheNameKeyGenerator->nameToKey( AsciiString("ReplayMenu.wnd:ButtonDeleteReplay") ); - buttonCopyID = TheNameKeyGenerator->nameToKey( AsciiString("ReplayMenu.wnd:ButtonCopyReplay") ); + parentReplayMenuID = TheNameKeyGenerator->nameToKey( "ReplayMenu.wnd:ParentReplayMenu" ); + buttonLoadID = TheNameKeyGenerator->nameToKey( "ReplayMenu.wnd:ButtonLoadReplay" ); + buttonBackID = TheNameKeyGenerator->nameToKey( "ReplayMenu.wnd:ButtonBack" ); + listboxReplayFilesID = TheNameKeyGenerator->nameToKey( "ReplayMenu.wnd:ListboxReplayFiles" ); + buttonDeleteID = TheNameKeyGenerator->nameToKey( "ReplayMenu.wnd:ButtonDeleteReplay" ); + buttonCopyID = TheNameKeyGenerator->nameToKey( "ReplayMenu.wnd:ButtonCopyReplay" ); parentReplayMenu = TheWindowManager->winGetWindowFromId( NULL, parentReplayMenuID ); buttonLoad = TheWindowManager->winGetWindowFromId( parentReplayMenu, buttonLoadID ); 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 ce27b26372..18d33cfaba 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp @@ -226,16 +226,16 @@ void ScoreScreenInit( WindowLayout *layout, void *userData ) buttonIsFinishCampaign = FALSE; //Store the keys so we have them later - parentID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:ParentScoreScreen" ) ); - buttonOkID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:ButtonOk" ) ); - textEntryChatID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:TextEntryChat" ) ); - buttonEmoteID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:ButtonEmote" ) ); - listboxChatWindowScoreScreenID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:ListboxChatWindowScoreScreen" ) ); -// buttonRehostID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:ButtonRehost" ) ); - chatBoxBorderID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:ChatBoxBorder" ) ); - buttonBuddiesID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:ButtonBuddy" ) ); - buttonContinueID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:ButtonContinue" ) ); - buttonSaveReplayID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:ButtonSaveReplay" ) ); + parentID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:ParentScoreScreen" ); + buttonOkID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:ButtonOk" ); + textEntryChatID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:TextEntryChat" ); + buttonEmoteID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:ButtonEmote" ); + listboxChatWindowScoreScreenID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:ListboxChatWindowScoreScreen" ); +// buttonRehostID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:ButtonRehost" ); + chatBoxBorderID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:ChatBoxBorder" ); + buttonBuddiesID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:ButtonBuddy" ); + buttonContinueID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:ButtonContinue" ); + buttonSaveReplayID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:ButtonSaveReplay" ); parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); buttonOk = TheWindowManager->winGetWindowFromId( parent, buttonOkID ); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SinglePlayerMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SinglePlayerMenu.cpp index 5763f05bcf..43b4bc6f62 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SinglePlayerMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SinglePlayerMenu.cpp @@ -74,15 +74,15 @@ void SinglePlayerMenuInit( WindowLayout *layout, void *userData ) GameWindow *parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); TheWindowManager->winSetFocus( parent ); - NameKeyType buttonNewID = TheNameKeyGenerator->nameToKey( AsciiString("SinglePlayerMenu.wnd:ButtonNew") ); + NameKeyType buttonNewID = TheNameKeyGenerator->nameToKey( "SinglePlayerMenu.wnd:ButtonNew" ); GameWindow *buttonNew = TheWindowManager->winGetWindowFromId( NULL, buttonNewID ); TheShell->registerWithAnimateManager(buttonNew, WIN_ANIMATION_SLIDE_LEFT, TRUE,1); - NameKeyType buttonLoadID = TheNameKeyGenerator->nameToKey( AsciiString("SinglePlayerMenu.wnd:ButtonLoad") ); + NameKeyType buttonLoadID = TheNameKeyGenerator->nameToKey( "SinglePlayerMenu.wnd:ButtonLoad" ); GameWindow *buttonLoad = TheWindowManager->winGetWindowFromId( NULL, buttonLoadID ); TheShell->registerWithAnimateManager(buttonLoad, WIN_ANIMATION_SLIDE_LEFT, TRUE,200); - NameKeyType buttonBackID = TheNameKeyGenerator->nameToKey( AsciiString("SinglePlayerMenu.wnd:ButtonBack") ); + NameKeyType buttonBackID = TheNameKeyGenerator->nameToKey( "SinglePlayerMenu.wnd:ButtonBack" ); GameWindow *buttonBack = TheWindowManager->winGetWindowFromId( NULL, buttonBackID ); TheShell->registerWithAnimateManager(buttonBack, WIN_ANIMATION_SLIDE_RIGHT, TRUE,1); @@ -197,9 +197,9 @@ WindowMsgHandledType SinglePlayerMenuSystem( GameWindow *window, UnsignedInt msg { // get ids for our children controls - buttonNew = TheNameKeyGenerator->nameToKey( AsciiString("SinglePlayerMenu.wnd:ButtonNew") ); - buttonLoad = TheNameKeyGenerator->nameToKey( AsciiString("SinglePlayerMenu.wnd:ButtonLoad") ); - buttonBack = TheNameKeyGenerator->nameToKey( AsciiString("SinglePlayerMenu.wnd:ButtonBack") ); + buttonNew = TheNameKeyGenerator->nameToKey( "SinglePlayerMenu.wnd:ButtonNew" ); + buttonLoad = TheNameKeyGenerator->nameToKey( "SinglePlayerMenu.wnd:ButtonLoad" ); + buttonBack = TheNameKeyGenerator->nameToKey( "SinglePlayerMenu.wnd:ButtonBack" ); break; @@ -237,7 +237,7 @@ WindowMsgHandledType SinglePlayerMenuSystem( GameWindow *window, UnsignedInt msg { // open up the map select menu - TheShell->push( AsciiString( "Menus/MapSelectMenu.wnd" ) ); + TheShell->push( "Menus/MapSelectMenu.wnd" ); buttonPushed = true; } 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 cd1a137a76..2cfd273c55 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp @@ -357,7 +357,7 @@ Bool SkirmishPreferences::write(void) setSlotList(); -// NameKeyType sliderGameSpeedID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:SliderGameSpeed" ) ); +// NameKeyType sliderGameSpeedID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:SliderGameSpeed" ); GameWindow *sliderGameSpeed = TheWindowManager->winGetWindowFromId( parentSkirmishGameOptions, sliderGameSpeedID ); Int maxFPS = GadgetSliderGetPosition( sliderGameSpeed ); setInt("FPS", maxFPS); @@ -416,7 +416,7 @@ void reallyDoStart( void ) if (TheGameLogic->isInGame()) TheGameLogic->clearGameData(FALSE); - //NameKeyType sliderGameSpeedID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:SliderGameSpeed" ) ); + //NameKeyType sliderGameSpeedID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:SliderGameSpeed" ); GameWindow *sliderGameSpeed = TheWindowManager->winGetWindowFromId( parentSkirmishGameOptions, sliderGameSpeedID ); Int maxFPS = GadgetSliderGetPosition( sliderGameSpeed ); DEBUG_LOG(("GameSpeedSlider was at %d", maxFPS)); @@ -1028,14 +1028,14 @@ static void handleTeamSelection(int index) void InitSkirmishGameGadgets( void ) { //Initialize the gadget IDs - parentSkirmishGameOptionsID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:SkirmishGameOptionsMenuParent" ) ); - buttonExitID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:ButtonBack" ) ); - buttonStartID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:ButtonStart" ) ); - textEntryMapDisplayID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:TextEntryMapDisplay" ) ); - buttonSelectMapID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:ButtonSelectMap" ) ); - buttonResetID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:ButtonReset" ) ); - windowMapID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:MapWindow" ) ); - staticTextGameSpeedID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:StaticTextGameSpeed" ) ); + parentSkirmishGameOptionsID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:SkirmishGameOptionsMenuParent" ); + buttonExitID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:ButtonBack" ); + buttonStartID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:ButtonStart" ); + textEntryMapDisplayID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:TextEntryMapDisplay" ); + buttonSelectMapID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:ButtonSelectMap" ); + buttonResetID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:ButtonReset" ); + windowMapID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:MapWindow" ); + staticTextGameSpeedID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:StaticTextGameSpeed" ); // Initialize the pointers to our gadgets parentSkirmishGameOptions = TheWindowManager->winGetWindowFromId( NULL, parentSkirmishGameOptionsID ); DEBUG_ASSERTCRASH(parentSkirmishGameOptions, ("Could not find the parentSkirmishGameOptions" )); @@ -1052,7 +1052,7 @@ void InitSkirmishGameGadgets( void ) staticTextGameSpeed = TheWindowManager->winGetWindowFromId( parentSkirmishGameOptions, staticTextGameSpeedID ); DEBUG_ASSERTCRASH(staticTextGameSpeed, ("Could not find the staticTextGameSpeed")); - textEntryPlayerNameID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:TextEntryPlayerName" ) ); + textEntryPlayerNameID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:TextEntryPlayerName" ); textEntryPlayerName = TheWindowManager->winGetWindowFromId( NULL, textEntryPlayerNameID ); DEBUG_ASSERTCRASH(textEntryPlayerName, ("Could not find the textEntryPlayerName" )); @@ -1235,7 +1235,7 @@ void SkirmishGameOptionsMenuInit( WindowLayout *layout, void *userData ) if (TheGameEngine->getQuitting()) return; - sliderGameSpeedID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:SliderGameSpeed" ) ); + sliderGameSpeedID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:SliderGameSpeed" ); sandboxOk = FALSE; doUpdateSlotList = FALSE; @@ -1318,7 +1318,7 @@ void SkirmishGameOptionsMenuInit( WindowLayout *layout, void *userData ) //initSkirmishGameOptions(); // set up the game speed slider -// NameKeyType sliderGameSpeedID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:SliderGameSpeed" ) ); +// NameKeyType sliderGameSpeedID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:SliderGameSpeed" ); GameWindow *sliderGameSpeed = TheWindowManager->winGetWindowFromId( parentSkirmishGameOptions, sliderGameSpeedID ); Int sliderPos = max(15,min(61,prefs.getInt("FPS", TheGlobalData->m_framesPerSecondLimit))); GadgetSliderSetPosition( sliderGameSpeed, sliderPos ); @@ -1551,7 +1551,7 @@ WindowMsgHandledType SkirmishGameOptionsMenuSystem( GameWindow *window, Unsigned GameWindow *control = (GameWindow *)mData1; Int controlID = control->winGetWindowId(); -/// static NameKeyType buttonResetFPSID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:ButtonResetFPS" ) ); +/// static NameKeyType buttonResetFPSID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:ButtonResetFPS" ); if(buttonPushed) break; if ( controlID == buttonExitID ) @@ -1572,7 +1572,7 @@ WindowMsgHandledType SkirmishGameOptionsMenuSystem( GameWindow *window, Unsigned } // else if ( controlID == buttonResetFPSID ) // { -// static NameKeyType sliderGameSpeedID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:SliderGameSpeed" ) ); +// static NameKeyType sliderGameSpeedID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:SliderGameSpeed" ); // GameWindow *sliderGameSpeed = TheWindowManager->winGetWindowFromId( parentSkirmishGameOptions, sliderGameSpeedID ); // GadgetSliderSetPosition( sliderGameSpeed, TheGlobalData->m_framesPerSecondLimit ); // } @@ -1580,7 +1580,7 @@ WindowMsgHandledType SkirmishGameOptionsMenuSystem( GameWindow *window, Unsigned { sandboxOk = FALSE; //buttonBack->winEnable( false ); - skirmishMapSelectLayout = TheWindowManager->winCreateLayout( AsciiString( "Menus/SkirmishMapSelectMenu.wnd" ) ); + skirmishMapSelectLayout = TheWindowManager->winCreateLayout( "Menus/SkirmishMapSelectMenu.wnd" ); skirmishMapSelectLayout->runInit(); skirmishMapSelectLayout->hide( FALSE ); skirmishMapSelectLayout->bringForward(); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp index 29060a32e1..1bf54db904 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp @@ -264,13 +264,13 @@ void SkirmishMapSelectMenuInit( WindowLayout *layout, void *userData ) usesSystemMapDir = mmd->m_isOfficial; } - winMapPreviewID = TheNameKeyGenerator->nameToKey( AsciiString("SkirmishMapSelectMenu.wnd:WinMapPreview") ); + winMapPreviewID = TheNameKeyGenerator->nameToKey( "SkirmishMapSelectMenu.wnd:WinMapPreview" ); winMapPreview = TheWindowManager->winGetWindowFromId(parent, winMapPreviewID); - buttonBack = TheNameKeyGenerator->nameToKey( AsciiString("SkirmishMapSelectMenu.wnd:ButtonBack") ); - buttonOK = TheNameKeyGenerator->nameToKey( AsciiString("SkirmishMapSelectMenu.wnd:ButtonOK") ); - listboxMap = TheNameKeyGenerator->nameToKey( AsciiString("SkirmishMapSelectMenu.wnd:ListboxMap") ); + buttonBack = TheNameKeyGenerator->nameToKey( "SkirmishMapSelectMenu.wnd:ButtonBack" ); + buttonOK = TheNameKeyGenerator->nameToKey( "SkirmishMapSelectMenu.wnd:ButtonOK" ); + listboxMap = TheNameKeyGenerator->nameToKey( "SkirmishMapSelectMenu.wnd:ListboxMap" ); radioButtonSystemMapsID = TheNameKeyGenerator->nameToKey( "SkirmishMapSelectMenu.wnd:RadioButtonSystemMaps" ); radioButtonUserMapsID = TheNameKeyGenerator->nameToKey( "SkirmishMapSelectMenu.wnd:RadioButtonUserMaps" ); 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 67eee3d1d3..6da46946c0 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLBuddyOverlay.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLBuddyOverlay.cpp @@ -166,20 +166,20 @@ void InitBuddyControls(Int type) buddyControls.isInit = FALSE; break; case BUDDY_WINDOW_BUDDIES: - buddyControls.textEntryEditID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:TextEntryChat" ) ); + buddyControls.textEntryEditID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:TextEntryChat" ); buddyControls.textEntryEdit = TheWindowManager->winGetWindowFromId(NULL, buddyControls.textEntryEditID); - buddyControls.listboxBuddiesID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:ListboxBuddies" ) ); - buddyControls.listboxChatID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:ListboxBuddyChat" ) ); + buddyControls.listboxBuddiesID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:ListboxBuddies" ); + buddyControls.listboxChatID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:ListboxBuddyChat" ); buddyControls.listboxBuddies = TheWindowManager->winGetWindowFromId( NULL, buddyControls.listboxBuddiesID ); buddyControls.listboxChat = TheWindowManager->winGetWindowFromId( NULL, buddyControls.listboxChatID); GadgetTextEntrySetText(buddyControls.textEntryEdit, UnicodeString::TheEmptyString); buddyControls.isInit = TRUE; break; case BUDDY_WINDOW_DIPLOMACY: - buddyControls.textEntryEditID = TheNameKeyGenerator->nameToKey( AsciiString( "Diplomacy.wnd:TextEntryChat" ) ); + buddyControls.textEntryEditID = TheNameKeyGenerator->nameToKey( "Diplomacy.wnd:TextEntryChat" ); buddyControls.textEntryEdit = TheWindowManager->winGetWindowFromId(NULL, buddyControls.textEntryEditID); - buddyControls.listboxBuddiesID = TheNameKeyGenerator->nameToKey( AsciiString( "Diplomacy.wnd:ListboxBuddies" ) ); - buddyControls.listboxChatID = TheNameKeyGenerator->nameToKey( AsciiString( "Diplomacy.wnd:ListboxBuddyChat" ) ); + buddyControls.listboxBuddiesID = TheNameKeyGenerator->nameToKey( "Diplomacy.wnd:ListboxBuddies" ); + buddyControls.listboxChatID = TheNameKeyGenerator->nameToKey( "Diplomacy.wnd:ListboxBuddyChat" ); buddyControls.listboxBuddies = TheWindowManager->winGetWindowFromId( NULL, buddyControls.listboxBuddiesID ); buddyControls.listboxChat = TheWindowManager->winGetWindowFromId( NULL, buddyControls.listboxChatID); GadgetTextEntrySetText(buddyControls.textEntryEdit, UnicodeString::TheEmptyString); @@ -221,11 +221,11 @@ WindowMsgHandledType BuddyControlSystem( GameWindow *window, UnsignedInt msg, GadgetListBoxSetSelected(control, rc->pos); if (itemType == ITEM_BUDDY) - rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/RCBuddiesMenu.wnd")); + rcLayout = TheWindowManager->winCreateLayout("Menus/RCBuddiesMenu.wnd"); else if (itemType == ITEM_REQUEST) - rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/RCBuddyRequestMenu.wnd")); + rcLayout = TheWindowManager->winCreateLayout("Menus/RCBuddyRequestMenu.wnd"); else - rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/RCNonBuddiesMenu.wnd")); + rcLayout = TheWindowManager->winCreateLayout("Menus/RCNonBuddiesMenu.wnd"); rcMenu = rcLayout->getFirstWindow(); rcMenu->winGetLayout()->runInit(); rcMenu->winBringToTop(); @@ -708,20 +708,20 @@ void PopulateOldBuddyMessages(void) //------------------------------------------------------------------------------------------------- void WOLBuddyOverlayInit( WindowLayout *layout, void *userData ) { - parentID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:BuddyMenuParent" ) ); - buttonHideID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:ButtonHide" ) ); - buttonAddBuddyID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:ButtonAdd" ) ); - buttonDeleteBuddyID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:ButtonDelete" ) ); - //textEntryID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:TextEntryChat" ) ); - //listboxBuddyID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:ListboxBuddies" ) ); - //listboxChatID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:ListboxBuddyChat" ) ); - buttonAcceptBuddyID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:ButtonYes" ) ); - buttonDenyBuddyID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:ButtonNo" ) ); - radioButtonBuddiesID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:RadioButtonBuddies" ) ); - radioButtonIgnoreID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:RadioButtonIgnore" ) ); - parentBuddiesID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:BuddiesParent" ) ); - parentIgnoreID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:IgnoreParent" ) ); - listboxIgnoreID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:ListboxIgnore" ) ); + parentID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:BuddyMenuParent" ); + buttonHideID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:ButtonHide" ); + buttonAddBuddyID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:ButtonAdd" ); + buttonDeleteBuddyID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:ButtonDelete" ); + //textEntryID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:TextEntryChat" ); + //listboxBuddyID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:ListboxBuddies" ); + //listboxChatID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:ListboxBuddyChat" ); + buttonAcceptBuddyID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:ButtonYes" ); + buttonDenyBuddyID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:ButtonNo" ); + radioButtonBuddiesID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:RadioButtonBuddies" ); + radioButtonIgnoreID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:RadioButtonIgnore" ); + parentBuddiesID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:BuddiesParent" ); + parentIgnoreID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:IgnoreParent" ); + listboxIgnoreID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:ListboxIgnore" ); parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); @@ -909,11 +909,11 @@ WindowMsgHandledType WOLBuddyOverlaySystem( GameWindow *window, UnsignedInt msg, GadgetListBoxSetSelected(control, rc->pos); if (isBuddy) - rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/RCBuddiesMenu.wnd")); + rcLayout = TheWindowManager->winCreateLayout("Menus/RCBuddiesMenu.wnd"); else if (isRequest) - rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/RCBuddyRequestMenu.wnd")); + rcLayout = TheWindowManager->winCreateLayout("Menus/RCBuddyRequestMenu.wnd"); else - rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/RCNonBuddiesMenu.wnd")); + rcLayout = TheWindowManager->winCreateLayout("Menus/RCNonBuddiesMenu.wnd"); rcMenu = rcLayout->getFirstWindow(); rcMenu->winGetLayout()->runInit(); rcMenu->winBringToTop(); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLCustomScoreScreen.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLCustomScoreScreen.cpp index 2f59652ade..5767ddfa13 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLCustomScoreScreen.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLCustomScoreScreen.cpp @@ -63,9 +63,9 @@ static GameWindow *buttonLobby = NULL; //------------------------------------------------------------------------------------------------- void WOLCustomScoreScreenInit( WindowLayout *layout, void *userData ) { - parentWOLCustomScoreID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLCustomScoreScreen.wnd:WOLCustomScoreScreenParent" ) ); - buttonDisconnectID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLCustomScoreScreen.wnd:ButtonDisconnect" ) ); - buttonLobbyID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLCustomScoreScreen.wnd:ButtonLobby" ) ); + parentWOLCustomScoreID = TheNameKeyGenerator->nameToKey( "WOLCustomScoreScreen.wnd:WOLCustomScoreScreenParent" ); + buttonDisconnectID = TheNameKeyGenerator->nameToKey( "WOLCustomScoreScreen.wnd:ButtonDisconnect" ); + buttonLobbyID = TheNameKeyGenerator->nameToKey( "WOLCustomScoreScreen.wnd:ButtonLobby" ); parentWOLCustomScore = TheWindowManager->winGetWindowFromId( NULL, parentWOLCustomScoreID ); buttonDisconnect = TheWindowManager->winGetWindowFromId( NULL, buttonDisconnectID); buttonLobby = TheWindowManager->winGetWindowFromId( NULL, buttonLobbyID); 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 ab56b66268..e0d0f03cc4 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp @@ -262,7 +262,7 @@ void WOLPositionStartSpots( void ) win = TheWindowManager->winGetWindowFromId(NULL, windowMapSelectMapID); // get the controls. - NameKeyType listboxMapID = TheNameKeyGenerator->nameToKey( AsciiString("WOLMapSelectMenu.wnd:ListboxMap") ); + NameKeyType listboxMapID = TheNameKeyGenerator->nameToKey( "WOLMapSelectMenu.wnd:ListboxMap" ); GameWindow *listboxMap = TheWindowManager->winGetWindowFromId( NULL, listboxMapID ); if (listboxMap != NULL) { @@ -999,16 +999,16 @@ void InitWOLGameGadgets( void ) DEBUG_ASSERTCRASH(pingImages[2], ("Can't find ping image!")); //Initialize the gadget IDs - parentWOLGameSetupID = TheNameKeyGenerator->nameToKey( AsciiString( "GameSpyGameOptionsMenu.wnd:GameSpyGameOptionsMenuParent" ) ); - buttonBackID = TheNameKeyGenerator->nameToKey( AsciiString( "GameSpyGameOptionsMenu.wnd:ButtonBack" ) ); - buttonStartID = TheNameKeyGenerator->nameToKey( AsciiString( "GameSpyGameOptionsMenu.wnd:ButtonStart" ) ); - textEntryChatID = TheNameKeyGenerator->nameToKey( AsciiString( "GameSpyGameOptionsMenu.wnd:TextEntryChat" ) ); - textEntryMapDisplayID = TheNameKeyGenerator->nameToKey( AsciiString( "GameSpyGameOptionsMenu.wnd:TextEntryMapDisplay" ) ); - listboxGameSetupChatID = TheNameKeyGenerator->nameToKey( AsciiString( "GameSpyGameOptionsMenu.wnd:ListboxChatWindowGameSpyGameSetup" ) ); - buttonEmoteID = TheNameKeyGenerator->nameToKey( AsciiString( "GameSpyGameOptionsMenu.wnd:ButtonEmote" ) ); - buttonSelectMapID = TheNameKeyGenerator->nameToKey( AsciiString( "GameSpyGameOptionsMenu.wnd:ButtonSelectMap" ) ); - windowMapID = TheNameKeyGenerator->nameToKey( AsciiString( "GameSpyGameOptionsMenu.wnd:MapWindow" ) ); - windowMapSelectMapID = TheNameKeyGenerator->nameToKey(AsciiString("WOLMapSelectMenu.wnd:WinMapPreview")); + parentWOLGameSetupID = TheNameKeyGenerator->nameToKey( "GameSpyGameOptionsMenu.wnd:GameSpyGameOptionsMenuParent" ); + buttonBackID = TheNameKeyGenerator->nameToKey( "GameSpyGameOptionsMenu.wnd:ButtonBack" ); + buttonStartID = TheNameKeyGenerator->nameToKey( "GameSpyGameOptionsMenu.wnd:ButtonStart" ); + textEntryChatID = TheNameKeyGenerator->nameToKey( "GameSpyGameOptionsMenu.wnd:TextEntryChat" ); + textEntryMapDisplayID = TheNameKeyGenerator->nameToKey( "GameSpyGameOptionsMenu.wnd:TextEntryMapDisplay" ); + listboxGameSetupChatID = TheNameKeyGenerator->nameToKey( "GameSpyGameOptionsMenu.wnd:ListboxChatWindowGameSpyGameSetup" ); + buttonEmoteID = TheNameKeyGenerator->nameToKey( "GameSpyGameOptionsMenu.wnd:ButtonEmote" ); + buttonSelectMapID = TheNameKeyGenerator->nameToKey( "GameSpyGameOptionsMenu.wnd:ButtonSelectMap" ); + windowMapID = TheNameKeyGenerator->nameToKey( "GameSpyGameOptionsMenu.wnd:MapWindow" ); + windowMapSelectMapID = TheNameKeyGenerator->nameToKey("WOLMapSelectMenu.wnd:WinMapPreview"); NameKeyType staticTextTitleID = NAMEKEY("GameSpyGameOptionsMenu.wnd:StaticTextGameName"); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLadderScreen.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLadderScreen.cpp index 7e1b42a877..48437a6f36 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLadderScreen.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLadderScreen.cpp @@ -58,9 +58,9 @@ void WOLLadderScreenInit( WindowLayout *layout, void *userData ) TheShell->showShellMap(TRUE); // get ids for our children controls - parentWindowID = TheNameKeyGenerator->nameToKey( AsciiString("WOLLadderScreen.wnd:LadderParent") ); - buttonBackID = TheNameKeyGenerator->nameToKey( AsciiString("WOLLadderScreen.wnd:ButtonBack") ); - windowLadderID = TheNameKeyGenerator->nameToKey( AsciiString("WOLLadderScreen.wnd:WindowLadder") ); + parentWindowID = TheNameKeyGenerator->nameToKey( "WOLLadderScreen.wnd:LadderParent" ); + buttonBackID = TheNameKeyGenerator->nameToKey( "WOLLadderScreen.wnd:ButtonBack" ); + windowLadderID = TheNameKeyGenerator->nameToKey( "WOLLadderScreen.wnd:WindowLadder" ); parentWindow = TheWindowManager->winGetWindowFromId( NULL, parentWindowID ); buttonBack = TheWindowManager->winGetWindowFromId( parentWindow, buttonBackID ); 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 411804f237..a86b514f67 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp @@ -605,40 +605,40 @@ void WOLLobbyMenuInit( WindowLayout *layout, void *userData ) gameListRefreshTime = 0; playerListRefreshTime = 0; - parentWOLLobbyID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLCustomLobby.wnd:WOLLobbyMenuParent" ) ); + parentWOLLobbyID = TheNameKeyGenerator->nameToKey( "WOLCustomLobby.wnd:WOLLobbyMenuParent" ); parent = TheWindowManager->winGetWindowFromId(NULL, parentWOLLobbyID); - buttonBackID = TheNameKeyGenerator->nameToKey(AsciiString("WOLCustomLobby.wnd:ButtonBack")); + buttonBackID = TheNameKeyGenerator->nameToKey("WOLCustomLobby.wnd:ButtonBack"); buttonBack = TheWindowManager->winGetWindowFromId(parent, buttonBackID); - buttonHostID = TheNameKeyGenerator->nameToKey(AsciiString("WOLCustomLobby.wnd:ButtonHost")); + buttonHostID = TheNameKeyGenerator->nameToKey("WOLCustomLobby.wnd:ButtonHost"); buttonHost = TheWindowManager->winGetWindowFromId(parent, buttonHostID); - buttonRefreshID = TheNameKeyGenerator->nameToKey(AsciiString("WOLCustomLobby.wnd:ButtonRefresh")); + buttonRefreshID = TheNameKeyGenerator->nameToKey("WOLCustomLobby.wnd:ButtonRefresh"); buttonRefresh = TheWindowManager->winGetWindowFromId(parent, buttonRefreshID); - buttonJoinID = TheNameKeyGenerator->nameToKey(AsciiString("WOLCustomLobby.wnd:ButtonJoin")); + buttonJoinID = TheNameKeyGenerator->nameToKey("WOLCustomLobby.wnd:ButtonJoin"); buttonJoin = TheWindowManager->winGetWindowFromId(parent, buttonJoinID); buttonJoin->winEnable(FALSE); - buttonBuddyID = TheNameKeyGenerator->nameToKey(AsciiString("WOLCustomLobby.wnd:ButtonBuddy")); + buttonBuddyID = TheNameKeyGenerator->nameToKey("WOLCustomLobby.wnd:ButtonBuddy"); buttonBuddy = TheWindowManager->winGetWindowFromId(parent, buttonBuddyID); - buttonEmoteID = TheNameKeyGenerator->nameToKey(AsciiString("WOLCustomLobby.wnd:ButtonEmote")); + buttonEmoteID = TheNameKeyGenerator->nameToKey("WOLCustomLobby.wnd:ButtonEmote"); buttonEmote = TheWindowManager->winGetWindowFromId(parent, buttonEmoteID); - textEntryChatID = TheNameKeyGenerator->nameToKey(AsciiString("WOLCustomLobby.wnd:TextEntryChat")); + textEntryChatID = TheNameKeyGenerator->nameToKey("WOLCustomLobby.wnd:TextEntryChat"); textEntryChat = TheWindowManager->winGetWindowFromId(parent, textEntryChatID); - listboxLobbyPlayersID = TheNameKeyGenerator->nameToKey(AsciiString("WOLCustomLobby.wnd:ListboxPlayers")); + listboxLobbyPlayersID = TheNameKeyGenerator->nameToKey("WOLCustomLobby.wnd:ListboxPlayers"); listboxLobbyPlayers = TheWindowManager->winGetWindowFromId(parent, listboxLobbyPlayersID); listboxLobbyPlayers->winSetTooltipFunc(playerTooltip); - listboxLobbyChatID = TheNameKeyGenerator->nameToKey(AsciiString("WOLCustomLobby.wnd:ListboxChat")); + listboxLobbyChatID = TheNameKeyGenerator->nameToKey("WOLCustomLobby.wnd:ListboxChat"); listboxLobbyChat = TheWindowManager->winGetWindowFromId(parent, listboxLobbyChatID); TheGameSpyInfo->registerTextWindow(listboxLobbyChat); - comboLobbyGroupRoomsID = TheNameKeyGenerator->nameToKey(AsciiString("WOLCustomLobby.wnd:ComboBoxGroupRooms")); + comboLobbyGroupRoomsID = TheNameKeyGenerator->nameToKey("WOLCustomLobby.wnd:ComboBoxGroupRooms"); comboLobbyGroupRooms = TheWindowManager->winGetWindowFromId(parent, comboLobbyGroupRoomsID); GadgetTextEntrySetText(textEntryChat, UnicodeString::TheEmptyString); @@ -1726,20 +1726,20 @@ WindowMsgHandledType WOLLobbyMenuSystem( GameWindow *window, UnsignedInt msg, Bool isBuddy = FALSE; if (profileID <= 0) - rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/RCNoProfileMenu.wnd")); + rcLayout = TheWindowManager->winCreateLayout("Menus/RCNoProfileMenu.wnd"); else { if (profileID == TheGameSpyInfo->getLocalProfileID()) { - rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/RCLocalPlayerMenu.wnd")); + rcLayout = TheWindowManager->winCreateLayout("Menus/RCLocalPlayerMenu.wnd"); } else if(TheGameSpyInfo->isBuddy(profileID)) { - rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/RCBuddiesMenu.wnd")); + rcLayout = TheWindowManager->winCreateLayout("Menus/RCBuddiesMenu.wnd"); isBuddy = TRUE; } else - rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/RCNonBuddiesMenu.wnd")); + rcLayout = TheWindowManager->winCreateLayout("Menus/RCNonBuddiesMenu.wnd"); } if(!rcLayout) break; @@ -1792,7 +1792,7 @@ WindowMsgHandledType WOLLobbyMenuSystem( GameWindow *window, UnsignedInt msg, const LadderInfo *linfo = TheLadderList->findLadder(theRoom->getLadderIP(), theRoom->getLadderPort()); if (linfo) { - rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/RCGameDetailsMenu.wnd")); + rcLayout = TheWindowManager->winCreateLayout("Menus/RCGameDetailsMenu.wnd"); if (!rcLayout) break; 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 c213bc989e..59d80e4051 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLocaleSelectPopup.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLocaleSelectPopup.cpp @@ -65,9 +65,9 @@ static GameWindow *listboxLocale = NULL; //------------------------------------------------------------------------------------------------- void WOLLocaleSelectInit( WindowLayout *layout, void *userData ) { - parentLocaleSelectID = TheNameKeyGenerator->nameToKey( AsciiString( "PopupLocaleSelect.wnd:ParentLocaleSelect" ) ); - buttonOkID = TheNameKeyGenerator->nameToKey( AsciiString( "PopupLocaleSelect.wnd:ButtonOk" ) ); - listboxLocaleID = TheNameKeyGenerator->nameToKey( AsciiString( "PopupLocaleSelect.wnd:ListBoxLocaleSelect" ) ); + parentLocaleSelectID = TheNameKeyGenerator->nameToKey( "PopupLocaleSelect.wnd:ParentLocaleSelect" ); + buttonOkID = TheNameKeyGenerator->nameToKey( "PopupLocaleSelect.wnd:ButtonOk" ); + listboxLocaleID = TheNameKeyGenerator->nameToKey( "PopupLocaleSelect.wnd:ListBoxLocaleSelect" ); parentLocaleSelect = TheWindowManager->winGetWindowFromId( NULL, parentLocaleSelectID ); buttonOk = TheWindowManager->winGetWindowFromId( NULL, buttonOkID); listboxLocale = TheWindowManager->winGetWindowFromId( NULL, listboxLocaleID); 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 a3de7865ca..98d1d12fa5 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMapSelectMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMapSelectMenu.cpp @@ -135,7 +135,7 @@ void WOLMapSelectMenuInit( WindowLayout *layout, void *userData ) CustomMatchPreferences pref; Bool usesSystemMapDir = pref.usesSystemMapDir(); - winMapPreviewID = TheNameKeyGenerator->nameToKey( AsciiString("WOLMapSelectMenu.wnd:WinMapPreview") ); + winMapPreviewID = TheNameKeyGenerator->nameToKey( "WOLMapSelectMenu.wnd:WinMapPreview" ); winMapPreview = TheWindowManager->winGetWindowFromId(parent, winMapPreviewID); const MapMetaData *mmd = TheMapCache->findMap(TheGameSpyGame->getMap()); @@ -144,9 +144,9 @@ void WOLMapSelectMenuInit( WindowLayout *layout, void *userData ) usesSystemMapDir = mmd->m_isOfficial; } - buttonBack = TheNameKeyGenerator->nameToKey( AsciiString("WOLMapSelectMenu.wnd:ButtonBack") ); - buttonOK = TheNameKeyGenerator->nameToKey( AsciiString("WOLMapSelectMenu.wnd:ButtonOK") ); - listboxMap = TheNameKeyGenerator->nameToKey( AsciiString("WOLMapSelectMenu.wnd:ListboxMap") ); + buttonBack = TheNameKeyGenerator->nameToKey( "WOLMapSelectMenu.wnd:ButtonBack" ); + buttonOK = TheNameKeyGenerator->nameToKey( "WOLMapSelectMenu.wnd:ButtonOK" ); + listboxMap = TheNameKeyGenerator->nameToKey( "WOLMapSelectMenu.wnd:ListboxMap" ); radioButtonSystemMapsID = TheNameKeyGenerator->nameToKey( "WOLMapSelectMenu.wnd:RadioButtonSystemMaps" ); radioButtonUserMapsID = TheNameKeyGenerator->nameToKey( "WOLMapSelectMenu.wnd:RadioButtonUserMaps" ); winMapWindow = TheWindowManager->winGetWindowFromId( parent, listboxMap ); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMessageWindow.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMessageWindow.cpp index f457b21553..23b023b156 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMessageWindow.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMessageWindow.cpp @@ -59,8 +59,8 @@ static GameWindow *buttonCancel = NULL; //------------------------------------------------------------------------------------------------- void WOLMessageWindowInit( WindowLayout *layout, void *userData ) { - parentWOLMessageWindowID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLMessageWindow.wnd:WOLMessageWindowParent" ) ); - buttonCancelID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLMessageWindow.wnd:ButtonCancel" ) ); + parentWOLMessageWindowID = TheNameKeyGenerator->nameToKey( "WOLMessageWindow.wnd:WOLMessageWindowParent" ); + buttonCancelID = TheNameKeyGenerator->nameToKey( "WOLMessageWindow.wnd:ButtonCancel" ); parentWOLMessageWindow = TheWindowManager->winGetWindowFromId( NULL, parentWOLMessageWindowID ); buttonCancel = TheWindowManager->winGetWindowFromId( NULL, buttonCancelID); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQMScoreScreen.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQMScoreScreen.cpp index d7d8f205b0..784bbe3ffd 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQMScoreScreen.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQMScoreScreen.cpp @@ -60,9 +60,9 @@ static GameWindow *buttonQuickmatch = NULL; //------------------------------------------------------------------------------------------------- void WOLQMScoreScreenInit( WindowLayout *layout, void *userData ) { - parentWOLQMScoreID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLQMScoreScreen.wnd:WOLQMScoreScreenParent" ) ); - buttonDisconnectID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLQMScoreScreen.wnd:ButtonDisconnect" ) ); - buttonQuickmatchID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLQMScoreScreen.wnd:ButtonQuickMatch" ) ); + parentWOLQMScoreID = TheNameKeyGenerator->nameToKey( "WOLQMScoreScreen.wnd:WOLQMScoreScreenParent" ); + buttonDisconnectID = TheNameKeyGenerator->nameToKey( "WOLQMScoreScreen.wnd:ButtonDisconnect" ); + buttonQuickmatchID = TheNameKeyGenerator->nameToKey( "WOLQMScoreScreen.wnd:ButtonQuickMatch" ); parentWOLQMScore = TheWindowManager->winGetWindowFromId( NULL, parentWOLQMScoreID ); buttonDisconnect = TheWindowManager->winGetWindowFromId( NULL, buttonDisconnectID); buttonQuickmatch = TheWindowManager->winGetWindowFromId( NULL, buttonQuickmatchID); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLStatusMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLStatusMenu.cpp index 2f4bb86cac..cb202a734f 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLStatusMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLStatusMenu.cpp @@ -59,13 +59,13 @@ GameWindow *progressTextWindow = NULL; //------------------------------------------------------------------------------------------------- void WOLStatusMenuInit( WindowLayout *layout, void *userData ) { - parentWOLStatusID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLStatusMenu.wnd:WOLStatusMenuParent" ) ); - buttonDisconnectID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLStatusMenu.wnd:ButtonDisconnect" ) ); + parentWOLStatusID = TheNameKeyGenerator->nameToKey( "WOLStatusMenu.wnd:WOLStatusMenuParent" ); + buttonDisconnectID = TheNameKeyGenerator->nameToKey( "WOLStatusMenu.wnd:ButtonDisconnect" ); parentWOLStatus = TheWindowManager->winGetWindowFromId( NULL, parentWOLStatusID ); buttonDisconnect = TheWindowManager->winGetWindowFromId( NULL, buttonDisconnectID); progressTextWindow = TheWindowManager->winGetWindowFromId( NULL, - TheNameKeyGenerator->nameToKey( AsciiString( "WOLStatusMenu.wnd:ListboxStatus" ) ) ); + TheNameKeyGenerator->nameToKey( "WOLStatusMenu.wnd:ListboxStatus" ) ); // Show Menu layout->hide( FALSE ); 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 6acf402ef8..0a011d40c6 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp @@ -408,13 +408,13 @@ void WOLWelcomeMenuInit( WindowLayout *layout, void *userData ) //TheWOL->reset(); - parentWOLWelcomeID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLWelcomeMenu.wnd:WOLWelcomeMenuParent" ) ); - buttonBackID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLWelcomeMenu.wnd:ButtonBack" ) ); + parentWOLWelcomeID = TheNameKeyGenerator->nameToKey( "WOLWelcomeMenu.wnd:WOLWelcomeMenuParent" ); + buttonBackID = TheNameKeyGenerator->nameToKey( "WOLWelcomeMenu.wnd:ButtonBack" ); parentWOLWelcome = TheWindowManager->winGetWindowFromId( NULL, parentWOLWelcomeID ); buttonBack = TheWindowManager->winGetWindowFromId( NULL, buttonBackID); buttonOptionsID = TheNameKeyGenerator->nameToKey( "WOLWelcomeMenu.wnd:ButtonOptions" ); buttonbuttonOptions = TheWindowManager->winGetWindowFromId( NULL, buttonOptionsID); - listboxInfoID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLWelcomeMenu.wnd:InfoListbox" ) ); + listboxInfoID = TheNameKeyGenerator->nameToKey( "WOLWelcomeMenu.wnd:InfoListbox" ); listboxInfo = TheWindowManager->winGetWindowFromId( NULL, listboxInfoID); @@ -473,19 +473,19 @@ void WOLWelcomeMenuInit( WindowLayout *layout, void *userData ) //DEBUG_ASSERTCRASH(listboxInfo, ("No control found!")); - buttonQuickMatchID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLWelcomeMenu.wnd:ButtonQuickMatch" ) ); + buttonQuickMatchID = TheNameKeyGenerator->nameToKey( "WOLWelcomeMenu.wnd:ButtonQuickMatch" ); buttonQuickMatch = TheWindowManager->winGetWindowFromId( parentWOLWelcome, buttonQuickMatchID ); - buttonLobbyID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLWelcomeMenu.wnd:ButtonCustomMatch" ) ); + buttonLobbyID = TheNameKeyGenerator->nameToKey( "WOLWelcomeMenu.wnd:ButtonCustomMatch" ); buttonLobby = TheWindowManager->winGetWindowFromId( parentWOLWelcome, buttonLobbyID ); - buttonBuddiesID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLWelcomeMenu.wnd:ButtonBuddies" ) ); + buttonBuddiesID = TheNameKeyGenerator->nameToKey( "WOLWelcomeMenu.wnd:ButtonBuddies" ); buttonBuddies = TheWindowManager->winGetWindowFromId( parentWOLWelcome, buttonBuddiesID ); - buttonMyInfoID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLWelcomeMenu.wnd:ButtonMyInfo" ) ); + buttonMyInfoID = TheNameKeyGenerator->nameToKey( "WOLWelcomeMenu.wnd:ButtonMyInfo" ); buttonMyInfo = TheWindowManager->winGetWindowFromId( parentWOLWelcome, buttonMyInfoID ); - buttonLadderID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLWelcomeMenu.wnd:ButtonLadder" ) ); + buttonLadderID = TheNameKeyGenerator->nameToKey( "WOLWelcomeMenu.wnd:ButtonLadder" ); buttonLadder = TheWindowManager->winGetWindowFromId( parentWOLWelcome, buttonLadderID ); if (TheFirewallHelper == NULL) { @@ -863,7 +863,7 @@ WindowMsgHandledType WOLWelcomeMenuSystem( GameWindow *window, UnsignedInt msg, } else if (controlID == buttonLadderID) { - TheShell->push(AsciiString("Menus/WOLLadderScreen.wnd")); + TheShell->push("Menus/WOLLadderScreen.wnd"); } break; } diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/MessageBox.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/MessageBox.cpp index 06bff14542..8dcf8aa581 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/MessageBox.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/MessageBox.cpp @@ -132,10 +132,10 @@ WindowMsgHandledType MessageBoxSystem( GameWindow *window, UnsignedInt msg, { GameWindow *control = (GameWindow *)mData1; Int controlID = control->winGetWindowId(); - static NameKeyType buttonOkID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonOk" ) ); - static NameKeyType buttonYesID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonYes" ) ); - static NameKeyType buttonNoID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonNo" ) ); - static NameKeyType buttonCancelID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonCancel" ) ); + static NameKeyType buttonOkID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonOk" ); + static NameKeyType buttonYesID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonYes" ); + static NameKeyType buttonNoID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonNo" ); + static NameKeyType buttonCancelID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonCancel" ); WindowMessageBoxData *MsgBoxCallbacks = (WindowMessageBoxData *)window->winGetUserData(); if( controlID == buttonOkID ) @@ -216,10 +216,10 @@ WindowMsgHandledType QuitMessageBoxSystem( GameWindow *window, UnsignedInt msg, { GameWindow *control = (GameWindow *)mData1; Int controlID = control->winGetWindowId(); - static NameKeyType buttonOkID = TheNameKeyGenerator->nameToKey( AsciiString( "QuitMessageBox.wnd:ButtonOk" ) ); - static NameKeyType buttonYesID = TheNameKeyGenerator->nameToKey( AsciiString( "QuitMessageBox.wnd:ButtonYes" ) ); - static NameKeyType buttonNoID = TheNameKeyGenerator->nameToKey( AsciiString( "QuitMessageBox.wnd:ButtonNo" ) ); - static NameKeyType buttonCancelID = TheNameKeyGenerator->nameToKey( AsciiString( "QuitMessageBox.wnd:ButtonCancel" ) ); + static NameKeyType buttonOkID = TheNameKeyGenerator->nameToKey( "QuitMessageBox.wnd:ButtonOk" ); + static NameKeyType buttonYesID = TheNameKeyGenerator->nameToKey( "QuitMessageBox.wnd:ButtonYes" ); + static NameKeyType buttonNoID = TheNameKeyGenerator->nameToKey( "QuitMessageBox.wnd:ButtonNo" ); + static NameKeyType buttonCancelID = TheNameKeyGenerator->nameToKey( "QuitMessageBox.wnd:ButtonCancel" ); WindowMessageBoxData *MsgBoxCallbacks = (WindowMessageBoxData *)window->winGetUserData(); if( controlID == buttonOkID ) diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp index d80bb789d6..9a52580044 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp @@ -1386,7 +1386,7 @@ GameWindow *GameWindowManager::winCreate( GameWindow *parent, TheGlobalLanguageData->m_defaultWindowFont.bold) ); } else - window->winSetFont( winFindFont( AsciiString("Times New Roman"), 14, FALSE ) ); + window->winSetFont( winFindFont( "Times New Roman", 14, FALSE ) ); return window; @@ -1618,9 +1618,9 @@ GameWindow *GameWindowManager::gogoMessageBox(Int x, Int y, Int width, Int heigh GameWindow *trueParent = NULL; //Changed by Chris if(useLogo) - trueParent = winCreateFromScript( AsciiString("Menus/QuitMessageBox.wnd") ); + trueParent = winCreateFromScript( "Menus/QuitMessageBox.wnd" ); else - trueParent = winCreateFromScript( AsciiString("Menus/MessageBox.wnd") ); + trueParent = winCreateFromScript( "Menus/MessageBox.wnd" ); //Added By Chris AsciiString menuName; if(useLogo) @@ -2854,7 +2854,7 @@ void GameWindowManager::assignDefaultGadgetLook( GameWindow *gadget, TheGlobalLanguageData->m_defaultWindowFont.bold) ); } else - gadget->winSetFont( TheWindowManager->winFindFont( AsciiString("Times New Roman"), 14, FALSE ) ); + gadget->winSetFont( TheWindowManager->winFindFont( "Times New Roman", 14, FALSE ) ); } // if we don't want to assign default colors/images get out of here @@ -3802,7 +3802,7 @@ Bool GameWindowManager::initTestGUI( void ) TheWindowManager->winMakeColor( 235, 105, 255, 255 ), -1, 0 ); GadgetListBoxAddEntryText( window, UnicodeString(L"Natural"), TheWindowManager->winMakeColor( 105, 205, 45, 255 ), -1, 0 ); - window->winSetFont( TheFontLibrary->getFont( AsciiString("Times New Roman"), 12, FALSE ) ); + window->winSetFont( TheFontLibrary->getFont( "Times New Roman", 12, FALSE ) ); // make a listbox memset( &listData, 0, sizeof( ListboxData ) ); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitions.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitions.cpp index 59282d711c..deb9c35465 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitions.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitions.cpp @@ -394,7 +394,7 @@ void GameWindowTransitionsHandler::load(void ) { INI ini; // Read from INI all the ControlBarSchemes - ini.loadFileDirectory( AsciiString( "Data\\INI\\WindowTransitions" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\WindowTransitions", INI_LOAD_OVERWRITE, NULL ); } diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp index 4aa40eb645..0857283fed 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp @@ -566,7 +566,7 @@ void IMEManager::init( void ) m_context = ImmCreateContext(); m_oldContext = ImmGetContext( ApplicationHWnd ); m_disabled = 0; - m_candidateWindow = TheWindowManager->winCreateFromScript( AsciiString("IMECandidateWindow.wnd")); + m_candidateWindow = TheWindowManager->winCreateFromScript( "IMECandidateWindow.wnd"); m_candidateWindow->winSetStatus(WIN_STATUS_ABOVE); if ( m_candidateWindow ) @@ -574,14 +574,14 @@ void IMEManager::init( void ) m_candidateWindow->winHide( TRUE ); // find text area window - NameKeyType id = TheNameKeyGenerator->nameToKey( AsciiString( "IMECandidateWindow.wnd:TextArea" ) ); + NameKeyType id = TheNameKeyGenerator->nameToKey( "IMECandidateWindow.wnd:TextArea" ); m_candidateTextArea = TheWindowManager->winGetWindowFromId(m_candidateWindow, id); // find arrows - id = TheNameKeyGenerator->nameToKey( AsciiString( "IMECandidateWindow.wnd:UpArrow" ) ); + id = TheNameKeyGenerator->nameToKey( "IMECandidateWindow.wnd:UpArrow" ); m_candidateUpArrow = TheWindowManager->winGetWindowFromId(m_candidateWindow, id); - id = TheNameKeyGenerator->nameToKey( AsciiString( "IMECandidateWindow.wnd:DownArrow" ) ); + id = TheNameKeyGenerator->nameToKey( "IMECandidateWindow.wnd:DownArrow" ); m_candidateDownArrow = TheWindowManager->winGetWindowFromId(m_candidateWindow, id); @@ -593,7 +593,7 @@ void IMEManager::init( void ) } } - m_statusWindow = TheWindowManager->winCreateFromScript( AsciiString("IMEStatusWindow.wnd")); + m_statusWindow = TheWindowManager->winCreateFromScript( "IMEStatusWindow.wnd"); if ( m_statusWindow ) { diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp index 0c453dce3e..755395afce 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp @@ -370,22 +370,22 @@ void SinglePlayerLoadScreen::init( GameInfo *game ) //No music in SinglePlayerLoadScreen // create the layout of the load screen - m_loadScreen = TheWindowManager->winCreateFromScript( AsciiString( "Menus/SinglePlayerLoadScreen.wnd" ) ); + m_loadScreen = TheWindowManager->winCreateFromScript( "Menus/SinglePlayerLoadScreen.wnd" ); DEBUG_ASSERTCRASH(m_loadScreen, ("Can't initialize the single player loadscreen")); m_loadScreen->winHide(FALSE); m_loadScreen->winBringToTop(); // Mission *mission = TheCampaignManager->getCurrentMission(); // Store the pointer to the progress bar on the loadscreen - m_progressBar = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "SinglePlayerLoadScreen.wnd:ProgressLoad" ) )); + m_progressBar = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:ProgressLoad" )); DEBUG_ASSERTCRASH(m_progressBar, ("Can't initialize the progressbar for the single player loadscreen")); GadgetProgressBarSetProgress(m_progressBar, 0 ); - m_percent = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "SinglePlayerLoadScreen.wnd:Percent" ) )); + m_percent = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:Percent" )); DEBUG_ASSERTCRASH(m_percent, ("Can't initialize the m_percent for the single player loadscreen")); GadgetStaticTextSetText(m_percent,UnicodeString(L"0%")); m_percent->winHide(TRUE); - m_objectiveWin = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "SinglePlayerLoadScreen.wnd:ObjectivesWin" ) )); + m_objectiveWin = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:ObjectivesWin" )); DEBUG_ASSERTCRASH(m_objectiveWin, ("Can't initialize the m_objectiveWin for the single player loadscreen")); m_objectiveWin->winHide(TRUE); @@ -413,7 +413,7 @@ void SinglePlayerLoadScreen::init( GameInfo *game ) GadgetStaticTextSetText(m_unitDesc[i],TheGameText->fetch(mission->m_unitNames[i])); m_unitDesc[i]->winHide(TRUE); } - m_location = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "SinglePlayerLoadScreen.wnd:StaticTextCameoText3" ) )); + m_location = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:StaticTextCameoText3" )); DEBUG_ASSERTCRASH(m_location, ("Can't initialize the m_objectiveWin for the single player loadscreen")); m_location->winHide(TRUE); GadgetStaticTextSetText(m_location, TheGameText->fetch(mission->m_locationNameLabel)); @@ -425,34 +425,34 @@ void SinglePlayerLoadScreen::init( GameInfo *game ) m_currentObjectiveLineCharacter = 0; m_finishedObjectiveText = FALSE; /* - m_cameoWindow1 = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "SinglePlayerLoadScreen.wnd:WindowCameo1" ) )); + m_cameoWindow1 = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:WindowCameo1" )); DEBUG_ASSERTCRASH(m_cameoWindow1, ("Can't initialize the m_cameoWindow1 for the single player loadscreen")); m_cameoWindow1->winHide(TRUE); m_cameoWindow1->winEnable(FALSE); m_cameoWindow1->winSetEnabledImage(0, mission->m_cameoImage[0]); m_cameoWindow1->winSetDisabledImage(0, mission->m_cameoDisabledImage[0]); - m_cameoWindow2 = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "SinglePlayerLoadScreen.wnd:WindowCameo2" ) )); + m_cameoWindow2 = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:WindowCameo2" )); DEBUG_ASSERTCRASH(m_cameoWindow2, ("Can't initialize the m_cameoWindow2 for the single player loadscreen")); m_cameoWindow2->winHide(TRUE); m_cameoWindow2->winEnable(FALSE); m_cameoWindow2->winSetEnabledImage(0, mission->m_cameoImage[1]); m_cameoWindow2->winSetDisabledImage(0, mission->m_cameoDisabledImage[1]); - m_cameoWindow3 = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "SinglePlayerLoadScreen.wnd:WindowCameo3" ) )); + m_cameoWindow3 = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:WindowCameo3" )); DEBUG_ASSERTCRASH(m_cameoWindow3, ("Can't initialize the m_cameoWindow3 for the single player loadscreen")); m_cameoWindow3->winHide(TRUE); m_cameoWindow3->winEnable(FALSE); m_cameoWindow3->winSetEnabledImage(0, mission->m_cameoImage[2]); m_cameoWindow3->winSetDisabledImage(0, mission->m_cameoDisabledImage[2]); - m_headMovie = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "SinglePlayerLoadScreen.wnd:WindowHead" ) )); + m_headMovie = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:WindowHead" )); DEBUG_ASSERTCRASH(m_headMovie, ("Can't initialize the m_headMovie for the single player loadscreen")); m_headMovie->winHide(TRUE); - m_cameoFrame = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "SinglePlayerLoadScreen.wnd:WindowHiliteCameo" ) )); + m_cameoFrame = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:WindowHiliteCameo" )); DEBUG_ASSERTCRASH(m_cameoFrame, ("Can't initialize the m_cameoFrame for the single player loadscreen")); m_cameoFrame->winHide(TRUE); - m_cameoText = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "SinglePlayerLoadScreen.wnd:StaticTextCameoText" ) )); + m_cameoText = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:StaticTextCameoText" )); DEBUG_ASSERTCRASH(m_cameoText, ("Can't initialize the m_cameoText for the single player loadscreen")); */ @@ -626,13 +626,13 @@ void ShellGameLoadScreen::init( GameInfo *game ) // create the layout of the load screen - m_loadScreen = TheWindowManager->winCreateFromScript( AsciiString( "Menus/ShellGameLoadScreen.wnd" ) ); + m_loadScreen = TheWindowManager->winCreateFromScript( "Menus/ShellGameLoadScreen.wnd" ); DEBUG_ASSERTCRASH(m_loadScreen, ("Can't initialize the ShellGame loadscreen")); m_loadScreen->winHide(FALSE); m_loadScreen->winBringToTop(); // Store the pointer to the progress bar on the loadscreen - m_progressBar = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "ShellGameLoadScreen.wnd:ProgressLoad" ) )); + m_progressBar = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "ShellGameLoadScreen.wnd:ProgressLoad" )); DEBUG_ASSERTCRASH(m_progressBar, ("Can't initialize the progressbar for the single player loadscreen")); GadgetProgressBarSetProgress(m_progressBar, 0 ); m_progressBar->winHide(TRUE); @@ -642,7 +642,7 @@ void ShellGameLoadScreen::init( GameInfo *game ) m_loadScreen->winSetEnabledImage(0, TheMappedImageCollection->findImageByName("TitleScreen")); TheWritableGlobalData->m_breakTheMovie = FALSE; - GameWindow *win = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "ShellGameLoadScreen.wnd:StaticTextLegal" ) )); + GameWindow *win = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "ShellGameLoadScreen.wnd:StaticTextLegal" )); if(win) win->winHide(FALSE); firstLoad = FALSE; @@ -709,7 +709,7 @@ MultiPlayerLoadScreen::~MultiPlayerLoadScreen( void ) void MultiPlayerLoadScreen::init( GameInfo *game ) { // create the layout of the load screen - m_loadScreen = TheWindowManager->winCreateFromScript( AsciiString( "Menus/MultiplayerLoadScreen.wnd" ) ); + m_loadScreen = TheWindowManager->winCreateFromScript( "Menus/MultiplayerLoadScreen.wnd" ); DEBUG_ASSERTCRASH(m_loadScreen, ("Can't initialize the Multiplayer loadscreen")); m_loadScreen->winHide(FALSE); m_loadScreen->winBringToTop(); @@ -943,7 +943,7 @@ extern Int GetAdditionalDisconnectsFromUserFile(Int playerID); void GameSpyLoadScreen::init( GameInfo *game ) { // create the layout of the load screen - m_loadScreen = TheWindowManager->winCreateFromScript( AsciiString( "Menus/GameSpyLoadScreen.wnd" ) ); + m_loadScreen = TheWindowManager->winCreateFromScript( "Menus/GameSpyLoadScreen.wnd" ); DEBUG_ASSERTCRASH(m_loadScreen, ("Can't initialize the Multiplayer loadscreen")); m_loadScreen->winHide(FALSE); m_loadScreen->winBringToTop(); @@ -1252,7 +1252,7 @@ MapTransferLoadScreen::~MapTransferLoadScreen( void ) void MapTransferLoadScreen::init( GameInfo *game ) { // create the layout of the load screen - m_loadScreen = TheWindowManager->winCreateFromScript( AsciiString( "Menus/MapTransferScreen.wnd" ) ); + m_loadScreen = TheWindowManager->winCreateFromScript( "Menus/MapTransferScreen.wnd" ); DEBUG_ASSERTCRASH(m_loadScreen, ("Can't initialize the map transfer loadscreen")); if (!m_loadScreen) return; diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp index 1ce4500245..d5fe8efa31 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp @@ -148,8 +148,8 @@ void Shell::init( void ) { INI ini; // Read from INI all the ShellMenuScheme - ini.loadFileDirectory( AsciiString( "Data\\INI\\Default\\ShellMenuScheme" ), INI_LOAD_OVERWRITE, NULL ); - ini.loadFileDirectory( AsciiString( "Data\\INI\\ShellMenuScheme" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Default\\ShellMenuScheme", INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\ShellMenuScheme", INI_LOAD_OVERWRITE, NULL ); if( m_schemeManager ) m_schemeManager->init(); @@ -519,7 +519,7 @@ void Shell::showShell( Bool runInit ) if (!TheGlobalData->m_shellMapOn && m_screenCount == 0) //else - push( AsciiString("Menus/MainMenu.wnd") ); + push( "Menus/MainMenu.wnd" ); m_isShellActive = TRUE; } @@ -842,7 +842,7 @@ WindowLayout *Shell::getSaveLoadMenuLayout( void ) // if layout has not been created, create it now if( m_saveLoadMenuLayout == NULL ) - m_saveLoadMenuLayout = TheWindowManager->winCreateLayout( AsciiString( "Menus/PopupSaveLoad.wnd" ) ); + m_saveLoadMenuLayout = TheWindowManager->winCreateLayout( "Menus/PopupSaveLoad.wnd" ); // sanity DEBUG_ASSERTCRASH( m_saveLoadMenuLayout, ("Unable to create save/load menu layout") ); @@ -859,7 +859,7 @@ WindowLayout *Shell::getPopupReplayLayout( void ) // if layout has not been created, create it now if( m_popupReplayLayout == NULL ) - m_popupReplayLayout = TheWindowManager->winCreateLayout( AsciiString( "Menus/PopupReplay.wnd" ) ); + m_popupReplayLayout = TheWindowManager->winCreateLayout( "Menus/PopupReplay.wnd" ); // sanity DEBUG_ASSERTCRASH( m_popupReplayLayout, ("Unable to create replay save menu layout") ); @@ -876,7 +876,7 @@ WindowLayout *Shell::getOptionsLayout( Bool create ) // if layout has not been created, create it now if ((m_optionsLayout == NULL) && (create == TRUE)) { - m_optionsLayout = TheWindowManager->winCreateLayout( AsciiString( "Menus/OptionsMenu.wnd" ) ); + m_optionsLayout = TheWindowManager->winCreateLayout( "Menus/OptionsMenu.wnd" ); // sanity DEBUG_ASSERTCRASH( m_optionsLayout, ("Unable to create options menu layout") ); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/Shell/ShellMenuScheme.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/Shell/ShellMenuScheme.cpp index 82754f8525..1bcabcdc4b 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/Shell/ShellMenuScheme.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/Shell/ShellMenuScheme.cpp @@ -279,8 +279,8 @@ void ShellMenuSchemeManager::init( void ) { INI ini; // Read from INI all the ControlBarSchemes - ini.loadFileDirectory( AsciiString( "Data\\INI\\Default\\ShellMenuScheme" ), INI_LOAD_OVERWRITE, NULL ); - ini.loadFileDirectory( AsciiString( "Data\\INI\\ShellMenuScheme" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Default\\ShellMenuScheme", INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\ShellMenuScheme", INI_LOAD_OVERWRITE, NULL ); } diff --git a/Generals/Code/GameEngine/Source/GameClient/InGameUI.cpp b/Generals/Code/GameEngine/Source/GameClient/InGameUI.cpp index 3facfcb757..d4bf6b296a 100644 --- a/Generals/Code/GameEngine/Source/GameClient/InGameUI.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/InGameUI.cpp @@ -1183,7 +1183,7 @@ InGameUI::~InGameUI() void InGameUI::init( void ) { INI ini; - ini.loadFileDirectory( AsciiString( "Data\\INI\\InGameUI" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\InGameUI", INI_LOAD_OVERWRITE, NULL ); //override INI values with language localized values: if (TheGlobalLanguageData) @@ -3949,7 +3949,7 @@ void InGameUI::expireHint( HintType type, UnsignedInt hintIndex ) void InGameUI::createControlBar( void ) { - TheWindowManager->winCreateFromScript( AsciiString("ControlBar.wnd") ); + TheWindowManager->winCreateFromScript( "ControlBar.wnd" ); HideControlBar(); /* // hide all windows created from this layout @@ -3966,7 +3966,7 @@ void InGameUI::createControlBar( void ) void InGameUI::createReplayControl( void ) { - m_replayWindow = TheWindowManager->winCreateFromScript( AsciiString("ReplayControl.wnd") ); + m_replayWindow = TheWindowManager->winCreateFromScript( "ReplayControl.wnd" ); /* // hide all windows created from this layout @@ -4057,7 +4057,7 @@ void InGameUI::playCameoMovie( const AsciiString& movieName ) stopCameoMovie(); return; } - GameWindow *window = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( AsciiString("ControlBar.wnd:RightHUD") )); + GameWindow *window = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( "ControlBar.wnd:RightHUD" )); WinInstanceData *winData = window->winGetInstanceData(); winData->setVideoBuffer(m_cameoVideoBuffer); // window->winHide(FALSE); @@ -4068,8 +4068,8 @@ void InGameUI::playCameoMovie( const AsciiString& movieName ) void InGameUI::stopCameoMovie( void ) { //RightHUD - //GameWindow *window = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( AsciiString("ControlBar.wnd:CameoMovieWindow") )); - GameWindow *window = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( AsciiString("ControlBar.wnd:RightHUD") )); + //GameWindow *window = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( "ControlBar.wnd:CameoMovieWindow" )); + GameWindow *window = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( "ControlBar.wnd:RightHUD" )); // window->winHide(FALSE); WinInstanceData *winData = window->winGetInstanceData(); winData->setVideoBuffer(NULL); @@ -5101,7 +5101,7 @@ void InGameUI::DEBUG_addFloatingText(const AsciiString& text, const Coord3D * po translate.translate(text); newFTD->m_text = translate; newFTD->m_dString->setText(translate); - newFTD->m_dString->setFont(TheWindowManager->winFindFont( AsciiString("Arial"), POINTSIZE, FALSE )); + newFTD->m_dString->setFont(TheWindowManager->winFindFont( "Arial", POINTSIZE, FALSE )); if(m_floatingTextTimeOut <= 0) newFTD->m_frameTimeOut = TheGameLogic->getFrame() + DEFAULT_FLOATING_TEXT_TIMEOUT; @@ -5266,7 +5266,7 @@ void InGameUI::popupMessage( const AsciiString& identifier, Int x, Int y, Int wi if( pause ) TheGameLogic->setGamePaused(TRUE, pauseMusic); - m_popupMessageData->layout = TheWindowManager->winCreateLayout(AsciiString("InGamePopupMessage.wnd")); + m_popupMessageData->layout = TheWindowManager->winCreateLayout("InGamePopupMessage.wnd"); m_popupMessageData->layout->runInit(); } @@ -5719,7 +5719,7 @@ void InGameUI::resetIdleWorker( void ) void InGameUI::recreateControlBar( void ) { - GameWindow *win = TheWindowManager->winGetWindowFromId(NULL, TheNameKeyGenerator->nameToKey(AsciiString("ControlBar.wnd"))); + GameWindow *win = TheWindowManager->winGetWindowFromId(NULL, TheNameKeyGenerator->nameToKey("ControlBar.wnd")); deleteInstance(win); m_idleWorkerWin = NULL; diff --git a/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp b/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp index 5cf797257e..2ae572300f 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp @@ -567,7 +567,7 @@ the Win32 version of the mouse (by preloading resources before D3D device is cre void Mouse::parseIni(void) { INI ini; - ini.loadFileDirectory( AsciiString( "Data\\INI\\Mouse" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Mouse", INI_LOAD_OVERWRITE, NULL ); } //------------------------------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Source/GameClient/MapUtil.cpp b/Generals/Code/GameEngine/Source/GameClient/MapUtil.cpp index 8a8fec3dfd..41fcbb2578 100644 --- a/Generals/Code/GameEngine/Source/GameClient/MapUtil.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/MapUtil.cpp @@ -158,7 +158,7 @@ static Bool ParseObjectDataChunk(DataChunkInput &file, DataChunkInfo *info, void static Bool ParseObjectsDataChunk(DataChunkInput &file, DataChunkInfo *info, void *userData) { file.m_currentObject = NULL; - file.registerParser( AsciiString("Object"), info->label, ParseObjectDataChunk ); + file.registerParser( "Object", info->label, ParseObjectDataChunk ); return (file.parse(userData)); } @@ -230,9 +230,9 @@ static Bool loadMap( AsciiString filename ) m_waypoints = NEW WaypointMap; - file.registerParser( AsciiString("HeightMapData"), AsciiString::TheEmptyString, ParseSizeOnlyInChunk ); - file.registerParser( AsciiString("WorldInfo"), AsciiString::TheEmptyString, ParseWorldDictDataChunk ); - file.registerParser( AsciiString("ObjectsList"), AsciiString::TheEmptyString, ParseObjectsDataChunk ); + file.registerParser( "HeightMapData", AsciiString::TheEmptyString, ParseSizeOnlyInChunk ); + file.registerParser( "WorldInfo", AsciiString::TheEmptyString, ParseWorldDictDataChunk ); + file.registerParser( "ObjectsList", AsciiString::TheEmptyString, ParseObjectsDataChunk ); if (!file.parse(NULL)) { throw(ERROR_CORRUPT_FILE_FORMAT); } @@ -314,7 +314,7 @@ const char *const MapCache::m_mapCacheName = "MapCache.ini"; AsciiString MapCache::getMapDir() const { - return AsciiString("Maps"); + return "Maps"; } AsciiString MapCache::getUserMapDir() const @@ -326,7 +326,7 @@ AsciiString MapCache::getUserMapDir() const AsciiString MapCache::getMapExtension() const { - return AsciiString("map"); + return "map"; } void MapCache::writeCacheINI( const AsciiString &mapDir ) @@ -1254,7 +1254,7 @@ Image *getMapPreviewImage( AsciiString mapName ) DataChunkInput file( pStrm ); if (file.isValidFileType()) { // Backwards compatible files aren't valid data chunk files. // Read the waypoints. - file.registerParser( AsciiString("MapPreview"), AsciiString::TheEmptyString, parseMapPreviewChunk ); + file.registerParser( "MapPreview", AsciiString::TheEmptyString, parseMapPreviewChunk ); if (!file.parse(NULL)) { DEBUG_ASSERTCRASH(false,("Unable to read MapPreview info.")); deleteInstance(mapPreviewImage); diff --git a/Generals/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp b/Generals/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp index 2920179a63..f0590f22b3 100644 --- a/Generals/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp @@ -3223,7 +3223,7 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage Bool hide = false; if (TheWindowManager) { - Int id = (Int)TheNameKeyGenerator->nameToKey(AsciiString("ControlBar.wnd:ControlBarParent")); + Int id = (Int)TheNameKeyGenerator->nameToKey("ControlBar.wnd:ControlBarParent"); GameWindow *window = TheWindowManager->winGetWindowFromId(NULL, id); if (window) @@ -3824,7 +3824,7 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage /* if (TheWindowManager && TheNameKeyGenerator) { - GameWindow *motd = TheWindowManager->winGetWindowFromId(NULL, (Int)TheNameKeyGenerator->nameToKey(AsciiString("MOTD.wnd:MOTD"))); + GameWindow *motd = TheWindowManager->winGetWindowFromId(NULL, (Int)TheNameKeyGenerator->nameToKey("MOTD.wnd:MOTD")); if (motd) motd->winHide(!motd->winIsHidden()); }*/ @@ -3873,7 +3873,7 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage Bool hide = false; if (TheWindowManager) { - Int id = (Int)TheNameKeyGenerator->nameToKey(AsciiString("ControlBar.wnd:ControlBarParent")); + Int id = (Int)TheNameKeyGenerator->nameToKey("ControlBar.wnd:ControlBarParent"); GameWindow *window = TheWindowManager->winGetWindowFromId(NULL, id); if (window) diff --git a/Generals/Code/GameEngine/Source/GameClient/System/CampaignManager.cpp b/Generals/Code/GameEngine/Source/GameClient/System/CampaignManager.cpp index a4200dfefe..97ed8527e8 100644 --- a/Generals/Code/GameEngine/Source/GameClient/System/CampaignManager.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/System/CampaignManager.cpp @@ -236,7 +236,7 @@ void CampaignManager::init( void ) { INI ini; // Read from INI all the CampaignManager - ini.loadFileDirectory( AsciiString( "Data\\INI\\Campaign" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Campaign", INI_LOAD_OVERWRITE, NULL ); } //----------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp b/Generals/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp index 4e890d00b9..1ec4a0ca72 100644 --- a/Generals/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp @@ -2963,7 +2963,7 @@ void ParticleSystemManager::init( void ) { /// Read INI data and build templates INI ini; - ini.loadFileDirectory( AsciiString( "Data\\INI\\ParticleSystem" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\ParticleSystem", INI_LOAD_OVERWRITE, NULL ); // sanity, our lists must be empty!! for( Int i = 0; i < NUM_PARTICLE_PRIORITIES; ++i ) diff --git a/Generals/Code/GameEngine/Source/GameClient/Terrain/TerrainRoads.cpp b/Generals/Code/GameEngine/Source/GameClient/Terrain/TerrainRoads.cpp index b00105ee37..03f3054a91 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Terrain/TerrainRoads.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Terrain/TerrainRoads.cpp @@ -353,7 +353,7 @@ TerrainRoadType *TerrainRoadCollection::newRoad( AsciiString name ) road->friend_setBridge( FALSE ); // set defaults from the default road - TerrainRoadType *defaultRoad = findRoad( AsciiString( "DefaultRoad" ) ); + TerrainRoadType *defaultRoad = findRoad( "DefaultRoad" ); if( defaultRoad ) { @@ -389,7 +389,7 @@ TerrainRoadType *TerrainRoadCollection::newBridge( AsciiString name ) bridge->friend_setBridge( TRUE ); // set defaults from the default bridge - TerrainRoadType *defaultBridge = findBridge( AsciiString( "DefaultBridge" ) ); + TerrainRoadType *defaultBridge = findBridge( "DefaultBridge" ); if( defaultBridge ) { diff --git a/Generals/Code/GameEngine/Source/GameLogic/Map/SidesList.cpp b/Generals/Code/GameEngine/Source/GameLogic/Map/SidesList.cpp index 1743e25613..3c8e496b29 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Map/SidesList.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Map/SidesList.cpp @@ -296,7 +296,7 @@ Bool SidesList::ParseSidesDataChunk(DataChunkInput &file, DataChunkInfo *info, v } } - file.registerParser( AsciiString("PlayerScriptsList"), info->label, ScriptList::ParseScriptsDataChunk ); + file.registerParser( "PlayerScriptsList", info->label, ScriptList::ParseScriptsDataChunk ); if (!file.parse(NULL)) { throw(ERROR_CORRUPT_FILE_FORMAT); } @@ -514,9 +514,9 @@ void SidesList::prepareForMP_or_Skirmish(void) if (theInputStream.open(path)) { ChunkInputStream *pStrm = &theInputStream; DataChunkInput file( pStrm ); - file.registerParser( AsciiString("PlayerScriptsList"), AsciiString::TheEmptyString, ScriptList::ParseScriptsDataChunk ); - file.registerParser( AsciiString("ScriptsPlayers"), AsciiString::TheEmptyString, ParsePlayersDataChunk ); - file.registerParser( AsciiString("ScriptTeams"), AsciiString::TheEmptyString, ParseTeamsDataChunk ); + file.registerParser( "PlayerScriptsList", AsciiString::TheEmptyString, ScriptList::ParseScriptsDataChunk ); + file.registerParser( "ScriptsPlayers", AsciiString::TheEmptyString, ParsePlayersDataChunk ); + file.registerParser( "ScriptTeams", AsciiString::TheEmptyString, ParseTeamsDataChunk ); if (!file.parse(this)) { DEBUG_LOG(("ERROR - Unable to read in skirmish scripts.")); return; @@ -816,10 +816,10 @@ Bool SidesList::validateSides() tdict->setAsciiString(TheKey_teamOwner, AsciiString::TheEmptyString); modified = true; } -// if (tdict->getType(NAMEKEY(AsciiString("teamAllies"))) != Dict::DICT_NONE) -// tdict->remove(NAMEKEY(AsciiString("teamAllies"))); -// if (tdict->getType(NAMEKEY(AsciiString("teamEnemies"))) != Dict::DICT_NONE) -// tdict->remove(NAMEKEY(AsciiString("teamEnemies"))); +// if (tdict->getType(NAMEKEY("teamAllies")) != Dict::DICT_NONE) +// tdict->remove(NAMEKEY("teamAllies")); +// if (tdict->getType(NAMEKEY("teamEnemies")) != Dict::DICT_NONE) +// tdict->remove(NAMEKEY("teamEnemies")); } diff --git a/Generals/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp b/Generals/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp index 168f12307c..88baf0b0ae 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp @@ -1272,7 +1272,7 @@ Bool TerrainLogic::loadMap( AsciiString filename, Bool query ) DataChunkInput file( pStrm ); if (file.isValidFileType()) { // Backwards compatible files aren't valid data chunk files. // Read the waypoints. - file.registerParser( AsciiString("WaypointsList"), AsciiString::TheEmptyString, parseWaypointDataChunk ); + file.registerParser( "WaypointsList", AsciiString::TheEmptyString, parseWaypointDataChunk ); if (!file.parse(this)) { DEBUG_CRASH(("Unable to read waypoint info.")); return false; diff --git a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp index 41b671c5fd..b8b13754c6 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp @@ -522,7 +522,7 @@ void ScriptList::deleteGroup(ScriptGroup *pGrp) Bool ScriptList::ParseScriptsDataChunk(DataChunkInput &file, DataChunkInfo *info, void *userData) { Int i; - file.registerParser( AsciiString("ScriptList"), info->label, ScriptList::ParseScriptListDataChunk ); + file.registerParser( "ScriptList", info->label, ScriptList::ParseScriptListDataChunk ); DEBUG_ASSERTCRASH(s_numInReadList==0, ("Leftover scripts floating aroung.")); for (i=0; ireadLists[pInfo->numLists] = newInstance(ScriptList); Int cur = pInfo->numLists; pInfo->numLists++; - file.registerParser( AsciiString("Script"), info->label, Script::ParseScriptFromListDataChunk ); - file.registerParser( AsciiString("ScriptGroup"), info->label, ScriptGroup::ParseGroupDataChunk ); + file.registerParser( "Script", info->label, Script::ParseScriptFromListDataChunk ); + file.registerParser( "ScriptGroup", info->label, ScriptGroup::ParseGroupDataChunk ); return file.parse(pInfo->readLists[cur]); } @@ -880,7 +880,7 @@ Bool ScriptGroup::ParseGroupDataChunk(DataChunkInput &file, DataChunkInfo *info, pGroup->m_isGroupSubroutine= file.readByte(); } pList->addGroup(pGroup, AT_END); - file.registerParser( AsciiString("Script"), info->label, Script::ParseScriptFromGroupDataChunk ); + file.registerParser( "Script", info->label, Script::ParseScriptFromGroupDataChunk ); return file.parse(pGroup); } @@ -1245,9 +1245,9 @@ Script *Script::ParseScript(DataChunkInput &file, unsigned short version) if (version>=K_SCRIPT_DATA_VERSION_2) { pScript->m_delayEvaluationSeconds = file.readInt(); } - file.registerParser( AsciiString("OrCondition"), AsciiString("Script"), OrCondition::ParseOrConditionDataChunk ); - file.registerParser( AsciiString("ScriptAction"), AsciiString("Script"), ScriptAction::ParseActionDataChunk ); - file.registerParser( AsciiString("ScriptActionFalse"), AsciiString("Script"), ScriptAction::ParseActionFalseDataChunk ); + file.registerParser( "OrCondition", "Script", OrCondition::ParseOrConditionDataChunk ); + file.registerParser( "ScriptAction", "Script", ScriptAction::ParseActionDataChunk ); + file.registerParser( "ScriptActionFalse", "Script", ScriptAction::ParseActionFalseDataChunk ); if (! file.parse(pScript) ) { return NULL; @@ -1441,7 +1441,7 @@ Bool OrCondition::ParseOrConditionDataChunk(DataChunkInput &file, DataChunkInfo } else { pScript->setOrCondition(pOrCondition); } - file.registerParser( AsciiString("Condition"), info->label, Condition::ParseConditionDataChunk ); + file.registerParser( "Condition", info->label, Condition::ParseConditionDataChunk ); return file.parse(pOrCondition); } diff --git a/Generals/Code/GameEngine/Source/GameLogic/System/CrateSystem.cpp b/Generals/Code/GameEngine/Source/GameLogic/System/CrateSystem.cpp index 45736d9d9e..8865ffbf9e 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/System/CrateSystem.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/System/CrateSystem.cpp @@ -119,7 +119,7 @@ CrateTemplate *CrateSystem::newCrateTemplate( AsciiString name ) CrateTemplate *ct = newInstance(CrateTemplate); // if the default template is present, get it and copy over any data to the new template - const CrateTemplate *defaultCT = findCrateTemplate(AsciiString("DefaultCrate")); + const CrateTemplate *defaultCT = findCrateTemplate("DefaultCrate"); if(defaultCT) { *ct = *defaultCT; diff --git a/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp index 44f527814d..03321c2be2 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp @@ -1421,7 +1421,7 @@ void GameLogic::startNewGame( Bool saveGame ) { ChunkInputStream *pStrm = &theInputStream; DataChunkInput file( pStrm ); - file.registerParser( AsciiString("PlayerScriptsList"), AsciiString::TheEmptyString, ScriptList::ParseScriptsDataChunk ); + file.registerParser( "PlayerScriptsList", AsciiString::TheEmptyString, ScriptList::ParseScriptsDataChunk ); if (!file.parse(NULL)) { DEBUG_LOG(("ERROR - Unable to read in multiplayer scripts.")); return; @@ -1980,7 +1980,7 @@ void GameLogic::startNewGame( Bool saveGame ) if (!TheGlobalData->m_headless) { if(TheShell->getScreenCount() == 0) - TheShell->push( AsciiString("Menus/MainMenu.wnd") ); + TheShell->push( "Menus/MainMenu.wnd" ); else if (TheShell->top()) { TheShell->top()->hide(FALSE); diff --git a/Generals/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp b/Generals/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp index 6c58b9aa53..2e67453c02 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp @@ -1442,7 +1442,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // place the sound for putting a building down - static AudioEventRTS placeBuilding(AsciiString("PlaceBuilding")); + static AudioEventRTS placeBuilding("PlaceBuilding"); placeBuilding.setObjectID(constructorObject->getID()); TheAudio->addAudioEvent( &placeBuilding ); diff --git a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy.cpp b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy.cpp index df613e5f18..6939d74029 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy.cpp @@ -256,7 +256,7 @@ void GameSpyChat::update( void ) { TheGameSpyThread->setShowLocaleSelect(false); WindowLayout *layout = NULL; - layout = TheWindowManager->winCreateLayout( AsciiString( "Menus/PopupLocaleSelect.wnd" ) ); + layout = TheWindowManager->winCreateLayout( "Menus/PopupLocaleSelect.wnd" ); layout->runInit(); layout->hide( FALSE ); layout->bringForward(); 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 338fc8ca37..1a99fe9ac1 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DControlBar.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DControlBar.cpp @@ -624,13 +624,13 @@ void W3DCommandBarBackgroundDraw( GameWindow *window, WinInstanceData *instData ControlBarSchemeManager *man = TheControlBar->getControlBarSchemeManager(); if(!man) return; - static NameKeyType winNamekey = TheNameKeyGenerator->nameToKey( AsciiString( "ControlBar.wnd:BackgroundMarker" ) ); + static NameKeyType winNamekey = TheNameKeyGenerator->nameToKey( "ControlBar.wnd:BackgroundMarker" ); GameWindow *win = TheWindowManager->winGetWindowFromId(NULL,winNamekey); static ICoord2D basePos; if(!win) { return; - //win = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( AsciiString( "ControlBar.wnd:BackgroundMarker" ) )); + //win = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( "ControlBar.wnd:BackgroundMarker" )); } TheControlBar->getBackgroundMarkerPos(&basePos.x, &basePos.y); ICoord2D pos, offset; @@ -649,13 +649,13 @@ void W3DCommandBarForegroundDraw( GameWindow *window, WinInstanceData *instData if(!man) return; - static NameKeyType winNamekey = TheNameKeyGenerator->nameToKey( AsciiString( "ControlBar.wnd:BackgroundMarker" ) ); + static NameKeyType winNamekey = TheNameKeyGenerator->nameToKey( "ControlBar.wnd:BackgroundMarker" ); GameWindow *win = TheWindowManager->winGetWindowFromId(NULL,winNamekey); static ICoord2D basePos; if(!win) { return; - //win = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( AsciiString( "ControlBar.wnd:BackgroundMarker" ) )); + //win = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( "ControlBar.wnd:BackgroundMarker" )); } TheControlBar->getForegroundMarkerPos(&basePos.x, &basePos.y); ICoord2D pos, offset; diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DMainMenu.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DMainMenu.cpp index 07e4dfa5bb..6579e5d595 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DMainMenu.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DMainMenu.cpp @@ -916,9 +916,9 @@ void W3DMainMenuInit( WindowLayout *layout, void *userData ) NameKeyType buttonUSAID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonUSA" ); NameKeyType buttonGLAID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonGLA" ); NameKeyType buttonChinaID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonChina" ); - NameKeyType skirmishID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonSkirmish") ); - NameKeyType onlineID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonOnline") ); - NameKeyType networkID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonNetwork") ); + NameKeyType skirmishID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonSkirmish" ); + NameKeyType onlineID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonOnline" ); + NameKeyType networkID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonNetwork" ); GameWindow *button = TheWindowManager->winGetWindowFromId( parent, skirmishID ); if (button) @@ -984,7 +984,7 @@ void W3DMainMenuInit( WindowLayout *layout, void *userData ) if(win) win->winSetDrawFunc(W3DMainMenuButtonDropShadowDraw); - GameWindow *clipRegionWin = TheWindowManager->winGetWindowFromId( parent, TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:MapBorder") )); + GameWindow *clipRegionWin = TheWindowManager->winGetWindowFromId( parent, TheNameKeyGenerator->nameToKey( "MainMenu.wnd:MapBorder" )); Int x,y,width,height; clipRegionWin->winGetScreenPosition(&x, &y); clipRegionWin->winGetSize(&width, &height); diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/W3DGameWindow.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/W3DGameWindow.cpp index 8222274004..7fa36bca02 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/W3DGameWindow.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/W3DGameWindow.cpp @@ -82,40 +82,40 @@ static void initBorders( void ) { borderPieces[ BORDER_CORNER_UL ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderCornerUL" ) ); + TheMappedImageCollection->findImageByName( "BorderCornerUL" ); borderPieces[ BORDER_CORNER_UR ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderCornerUR" ) ); + TheMappedImageCollection->findImageByName( "BorderCornerUR" ); borderPieces[ BORDER_CORNER_LL ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderCornerLL" ) ); + TheMappedImageCollection->findImageByName( "BorderCornerLL" ); borderPieces[ BORDER_CORNER_LR ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderCornerLR" ) ); + TheMappedImageCollection->findImageByName( "BorderCornerLR" ); borderPieces[ BORDER_VERTICAL_LEFT ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderLeft" ) ); + TheMappedImageCollection->findImageByName( "BorderLeft" ); borderPieces[ BORDER_VERTICAL_LEFT_SHORT ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderLeftShort" ) ); + TheMappedImageCollection->findImageByName( "BorderLeftShort" ); borderPieces[ BORDER_HORIZONTAL_TOP ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderTop" ) ); + TheMappedImageCollection->findImageByName( "BorderTop" ); borderPieces[ BORDER_HORIZONTAL_TOP_SHORT ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderTopShort" ) ); + TheMappedImageCollection->findImageByName( "BorderTopShort" ); borderPieces[ BORDER_VERTICAL_RIGHT ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderRight" ) ); + TheMappedImageCollection->findImageByName( "BorderRight" ); borderPieces[ BORDER_VERTICAL_RIGHT_SHORT ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderRightShort" ) ); + TheMappedImageCollection->findImageByName( "BorderRightShort" ); borderPieces[ BORDER_HORIZONTAL_BOTTOM ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderBottom" ) ); + TheMappedImageCollection->findImageByName( "BorderBottom" ); borderPieces[ BORDER_HORIZONTAL_BOTTOM_SHORT ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderBottomShort" ) ); + TheMappedImageCollection->findImageByName( "BorderBottomShort" ); bordersInit = TRUE; diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp index 9767f32c29..42dcd033db 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp @@ -772,7 +772,7 @@ void W3DDisplay::init( void ) TheGlobalLanguageData->m_nativeDebugDisplay.bold); } else - font=TheFontLibrary->getFont( AsciiString("FixedSys"), 8, FALSE ); + font=TheFontLibrary->getFont( "FixedSys", 8, FALSE ); m_nativeDebugDisplay->setFont( font ); m_nativeDebugDisplay->setFontHeight( 13 ); @@ -891,7 +891,7 @@ void W3DDisplay::gatherDebugStats( void ) TheGlobalLanguageData->m_nativeDebugDisplay.bold); } else - font = TheFontLibrary->getFont( AsciiString("FixedSys"), 8, FALSE ); + font = TheFontLibrary->getFont( "FixedSys", 8, FALSE ); for (int i = 0; i < DisplayStringCount; i++) { @@ -907,7 +907,7 @@ void W3DDisplay::gatherDebugStats( void ) if (m_benchmarkDisplayString == NULL) { - GameFont *thisFont = TheFontLibrary->getFont( AsciiString("FixedSys"), 8, FALSE ); + GameFont *thisFont = TheFontLibrary->getFont( "FixedSys", 8, FALSE ); m_benchmarkDisplayString = TheDisplayStringManager->newDisplayString(); DEBUG_ASSERTCRASH( m_benchmarkDisplayString, ("Failed to create DisplayString") ); m_benchmarkDisplayString->setFont( thisFont ); diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayStringManager.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayStringManager.cpp index 9b5058abd4..459fc1be20 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayStringManager.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayStringManager.cpp @@ -131,7 +131,7 @@ DisplayString *W3DDisplayStringManager::newDisplayString( void ) TheGlobalLanguageData->m_defaultDisplayStringFont.bold) ); } else - newString->setFont( TheFontLibrary->getFont( AsciiString("Times New Roman"), 12, FALSE ) ); + newString->setFont( TheFontLibrary->getFont( "Times New Roman", 12, FALSE ) ); // link string to list link( newString ); diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp index 129256c801..b88d231996 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp @@ -344,7 +344,7 @@ void W3DInGameUI::init( void ) // comment because we'll probably want to add this back in. /* // create the MOTD - GameWindow *motd = TheWindowManager->winCreateFromScript( AsciiString("MOTD.wnd") ); + GameWindow *motd = TheWindowManager->winCreateFromScript( "MOTD.wnd" ); if( motd ) { NameKeyType listboxTextID = TheNameKeyGenerator->nameToKey( "MOTD.wnd:ListboxMOTD" ); diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp index 8a2066b561..38eb63b462 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp @@ -493,21 +493,21 @@ WorldHeightMap::WorldHeightMap(ChunkInputStream *pStrm, Bool logicalDataOnly): DataChunkInput file( pStrm ); if (logicalDataOnly) { - file.registerParser( AsciiString("HeightMapData"), AsciiString::TheEmptyString, ParseSizeOnlyInChunk ); - file.registerParser( AsciiString("WorldInfo"), AsciiString::TheEmptyString, ParseWorldDictDataChunk ); - file.registerParser( AsciiString("ObjectsList"), AsciiString::TheEmptyString, ParseObjectsDataChunk ); + file.registerParser( "HeightMapData", AsciiString::TheEmptyString, ParseSizeOnlyInChunk ); + file.registerParser( "WorldInfo", AsciiString::TheEmptyString, ParseWorldDictDataChunk ); + file.registerParser( "ObjectsList", AsciiString::TheEmptyString, ParseObjectsDataChunk ); freeListOfMapObjects(); // just in case. - file.registerParser( AsciiString("PolygonTriggers"), AsciiString::TheEmptyString, PolygonTrigger::ParsePolygonTriggersDataChunk ); + file.registerParser( "PolygonTriggers", AsciiString::TheEmptyString, PolygonTrigger::ParsePolygonTriggersDataChunk ); PolygonTrigger::deleteTriggers(); // just in case. TheSidesList->emptySides(); - file.registerParser(AsciiString("SidesList"), AsciiString::TheEmptyString, SidesList::ParseSidesDataChunk ); + file.registerParser("SidesList", AsciiString::TheEmptyString, SidesList::ParseSidesDataChunk ); } else { - file.registerParser( AsciiString("HeightMapData"), AsciiString::TheEmptyString, ParseHeightMapDataChunk ); - file.registerParser( AsciiString("BlendTileData"), AsciiString::TheEmptyString, ParseBlendTileDataChunk ); + file.registerParser( "HeightMapData", AsciiString::TheEmptyString, ParseHeightMapDataChunk ); + file.registerParser( "BlendTileData", AsciiString::TheEmptyString, ParseBlendTileDataChunk ); #ifdef EVAL_TILING_MODES - file.registerParser( AsciiString("FUNKY_TILING"), AsciiString::TheEmptyString, ParseFunkyTilingDataChunk ); + file.registerParser( "FUNKY_TILING", AsciiString::TheEmptyString, ParseFunkyTilingDataChunk ); #endif - file.registerParser( AsciiString("GlobalLighting"), AsciiString::TheEmptyString, ParseLightingDataChunk ); + file.registerParser( "GlobalLighting", AsciiString::TheEmptyString, ParseLightingDataChunk ); } if (!file.parse(this)) { throw(ERROR_CORRUPT_FILE_FORMAT); @@ -687,7 +687,7 @@ Bool WorldHeightMap::ParseLightingDataChunk(DataChunkInput &file, DataChunkInfo Bool WorldHeightMap::ParseObjectsDataChunk(DataChunkInput &file, DataChunkInfo *info, void *userData) { file.m_currentObject = NULL; - file.registerParser( AsciiString("Object"), info->label, ParseObjectDataChunk ); + file.registerParser( "Object", info->label, ParseObjectDataChunk ); return (file.parse(userData)); } diff --git a/Generals/Code/Tools/GUIEdit/Source/LayoutScheme.cpp b/Generals/Code/Tools/GUIEdit/Source/LayoutScheme.cpp index a69dbaf887..f9f674f930 100644 --- a/Generals/Code/Tools/GUIEdit/Source/LayoutScheme.cpp +++ b/Generals/Code/Tools/GUIEdit/Source/LayoutScheme.cpp @@ -1570,563 +1570,563 @@ void LayoutScheme::init( void ) const Image *image; // push button - image = TheMappedImageCollection->findImageByName( AsciiString( "PushButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "PushButtonEnabled" ); storeImageAndColor( BUTTON_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "PushButtonEnabledSelected" ) ); + image = TheMappedImageCollection->findImageByName( "PushButtonEnabledSelected" ); storeImageAndColor( BUTTON_ENABLED_PUSHED, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "PushButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "PushButtonDisabled" ); storeImageAndColor( BUTTON_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "PushButtonDisabledSelected" ) ); + image = TheMappedImageCollection->findImageByName( "PushButtonDisabledSelected" ); storeImageAndColor( BUTTON_DISABLED_PUSHED, image, lightGray, gray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "PushButtonHilite" ) ); + image = TheMappedImageCollection->findImageByName( "PushButtonHilite" ); storeImageAndColor( BUTTON_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "PushButtonHiliteSelected" ) ); + image = TheMappedImageCollection->findImageByName( "PushButtonHiliteSelected" ); storeImageAndColor( BUTTON_HILITE_PUSHED, image, yellow, white ); // radio button - image = TheMappedImageCollection->findImageByName( AsciiString( "RadioButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "RadioButtonEnabled" ); storeImageAndColor( RADIO_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "RadioButtonEnabledBoxUnselected" ) ); + image = TheMappedImageCollection->findImageByName( "RadioButtonEnabledBoxUnselected" ); storeImageAndColor( RADIO_ENABLED_UNCHECKED_BOX, image, darkRed, black ); - image = TheMappedImageCollection->findImageByName( AsciiString( "RadioButtonEnabledBoxSelected" ) ); + image = TheMappedImageCollection->findImageByName( "RadioButtonEnabledBoxSelected" ); storeImageAndColor( RADIO_ENABLED_CHECKED_BOX, image, blue, lightBlue ); - image = TheMappedImageCollection->findImageByName( AsciiString( "RadioButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "RadioButtonDisabled" ); storeImageAndColor( RADIO_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "RadioButtonDisabledBoxUnselected" ) ); + image = TheMappedImageCollection->findImageByName( "RadioButtonDisabledBoxUnselected" ); storeImageAndColor( RADIO_DISABLED_UNCHECKED_BOX, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "RadioButtonDisabledBoxSelected" ) ); + image = TheMappedImageCollection->findImageByName( "RadioButtonDisabledBoxSelected" ); storeImageAndColor( RADIO_DISABLED_CHECKED_BOX, image, darkGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "RadioButtonHilite" ) ); + image = TheMappedImageCollection->findImageByName( "RadioButtonHilite" ); storeImageAndColor( RADIO_HILITE, image, green, lightGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "RadioButtonHiliteBoxUnselected" ) ); + image = TheMappedImageCollection->findImageByName( "RadioButtonHiliteBoxUnselected" ); storeImageAndColor( RADIO_HILITE_UNCHECKED_BOX, image, darkGreen, lightGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "RadioButtonHiliteBoxSelected" ) ); + image = TheMappedImageCollection->findImageByName( "RadioButtonHiliteBoxSelected" ); storeImageAndColor( RADIO_HILITE_CHECKED_BOX, image, yellow, white ); // check box - image = TheMappedImageCollection->findImageByName( AsciiString( "CheckBoxEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "CheckBoxEnabled" ); storeImageAndColor( CHECK_BOX_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "CheckBoxEnabledBoxUnselected" ) ); + image = TheMappedImageCollection->findImageByName( "CheckBoxEnabledBoxUnselected" ); storeImageAndColor( CHECK_BOX_ENABLED_UNCHECKED_BOX, image, WIN_COLOR_UNDEFINED, lightBlue ); - image = TheMappedImageCollection->findImageByName( AsciiString( "CheckBoxEnabledBoxSelected" ) ); + image = TheMappedImageCollection->findImageByName( "CheckBoxEnabledBoxSelected" ); storeImageAndColor( CHECK_BOX_ENABLED_CHECKED_BOX, image, blue, lightBlue ); - image = TheMappedImageCollection->findImageByName( AsciiString( "CheckBoxDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "CheckBoxDisabled" ); storeImageAndColor( CHECK_BOX_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "CheckBoxDisabledBoxUnselected" ) ); + image = TheMappedImageCollection->findImageByName( "CheckBoxDisabledBoxUnselected" ); storeImageAndColor( CHECK_BOX_DISABLED_UNCHECKED_BOX, image, WIN_COLOR_UNDEFINED, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "CheckBoxDisabledBoxSelected" ) ); + image = TheMappedImageCollection->findImageByName( "CheckBoxDisabledBoxSelected" ); storeImageAndColor( CHECK_BOX_DISABLED_CHECKED_BOX, image, darkGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "CheckBoxHilite" ) ); + image = TheMappedImageCollection->findImageByName( "CheckBoxHilite" ); storeImageAndColor( CHECK_BOX_HILITE, image, green, lightGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "CheckBoxHiliteBoxUnselected" ) ); + image = TheMappedImageCollection->findImageByName( "CheckBoxHiliteBoxUnselected" ); storeImageAndColor( CHECK_BOX_HILITE_UNCHECKED_BOX, image, WIN_COLOR_UNDEFINED, lightBlue ); - image = TheMappedImageCollection->findImageByName( AsciiString( "CheckBoxHiliteBoxSelected" ) ); + image = TheMappedImageCollection->findImageByName( "CheckBoxHiliteBoxSelected" ); storeImageAndColor( CHECK_BOX_HILITE_CHECKED_BOX, image, yellow, white ); // horz slider - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderEnabledLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderEnabledLeftEnd" ); storeImageAndColor( HSLIDER_ENABLED_LEFT, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderEnabledRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderEnabledRightEnd" ); storeImageAndColor( HSLIDER_ENABLED_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderEnabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderEnabledRepeatingCenter" ); storeImageAndColor( HSLIDER_ENABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderEnabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderEnabledSmallRepeatingCenter" ); storeImageAndColor( HSLIDER_ENABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderDisabledLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderDisabledLeftEnd" ); storeImageAndColor( HSLIDER_DISABLED_LEFT, image, gray, darkGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderDisabledRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderDisabledRightEnd" ); storeImageAndColor( HSLIDER_DISABLED_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderDisabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderDisabledRepeatingCenter" ); storeImageAndColor( HSLIDER_DISABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderDisabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderDisabledSmallRepeatingCenter" ); storeImageAndColor( HSLIDER_DISABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderHiliteLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderHiliteLeftEnd" ); storeImageAndColor( HSLIDER_HILITE_LEFT, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderHiliteRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderHiliteRightEnd" ); storeImageAndColor( HSLIDER_HILITE_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderHiliteRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderHiliteRepeatingCenter" ); storeImageAndColor( HSLIDER_HILITE_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderHiliteSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderHiliteSmallRepeatingCenter" ); storeImageAndColor( HSLIDER_HILITE_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderThumbEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderThumbEnabled" ); storeImageAndColor( HSLIDER_THUMB_ENABLED, image, lightRed, red ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderThumbEnabledSelected" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderThumbEnabledSelected" ); storeImageAndColor( HSLIDER_THUMB_ENABLED_PUSHED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderThumbDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderThumbDisabled" ); storeImageAndColor( HSLIDER_THUMB_DISABLED, image, darkGray, gray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderThumbDisabledSelected" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderThumbDisabledSelected" ); storeImageAndColor( HSLIDER_THUMB_DISABLED_PUSHED, image, black, darkGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderThumbHilite" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderThumbHilite" ); storeImageAndColor( HSLIDER_THUMB_HILITE, image, green, lightGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderThumbHiliteSelected" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderThumbHiliteSelected" ); storeImageAndColor( HSLIDER_THUMB_HILITE_PUSHED, image, blue, lightBlue ); // vert slider - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderEnabledTopEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderEnabledTopEnd" ); storeImageAndColor( VSLIDER_ENABLED_TOP, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderEnabledBottomEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderEnabledBottomEnd" ); storeImageAndColor( VSLIDER_ENABLED_BOTTOM, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderEnabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderEnabledRepeatingCenter" ); storeImageAndColor( VSLIDER_ENABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderEnabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderEnabledSmallRepeatingCenter" ); storeImageAndColor( VSLIDER_ENABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderDisabledTopEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderDisabledTopEnd" ); storeImageAndColor( VSLIDER_DISABLED_TOP, image, gray, darkGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderDisabledBottomEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderDisabledBottomEnd" ); storeImageAndColor( VSLIDER_DISABLED_BOTTOM, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderDisabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderDisabledRepeatingCenter" ); storeImageAndColor( VSLIDER_DISABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderDisabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderDisabledSmallRepeatingCenter" ); storeImageAndColor( VSLIDER_DISABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderHiliteTopEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderHiliteTopEnd" ); storeImageAndColor( VSLIDER_HILITE_TOP, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderHiliteBottomEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderHiliteBottomEnd" ); storeImageAndColor( VSLIDER_HILITE_BOTTOM, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderHiliteRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderHiliteRepeatingCenter" ); storeImageAndColor( VSLIDER_HILITE_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderHiliteSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderHiliteSmallRepeatingCenter" ); storeImageAndColor( VSLIDER_HILITE_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderThumbEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderThumbEnabled" ); storeImageAndColor( VSLIDER_THUMB_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderThumbEnabledSelected" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderThumbEnabledSelected" ); storeImageAndColor( VSLIDER_THUMB_ENABLED_PUSHED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderThumbDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderThumbDisabled" ); storeImageAndColor( VSLIDER_THUMB_DISABLED, image, darkGray, gray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderThumbDisabledSelected" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderThumbDisabledSelected" ); storeImageAndColor( VSLIDER_THUMB_DISABLED_PUSHED, image, black, darkGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderThumbHilite" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderThumbHilite" ); storeImageAndColor( VSLIDER_THUMB_HILITE, image, green, lightGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderThumbHiliteSelected" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderThumbHiliteSelected" ); storeImageAndColor( VSLIDER_THUMB_HILITE_PUSHED, image, blue, lightBlue ); // listbox - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabled" ); storeImageAndColor( LISTBOX_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemLeftEnd" ); storeImageAndColor( LISTBOX_ENABLED_SELECTED_ITEM_LEFT, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemRightEnd" ); storeImageAndColor( LISTBOX_ENABLED_SELECTED_ITEM_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemRepeatingCenter" ); storeImageAndColor( LISTBOX_ENABLED_SELECTED_ITEM_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemSmallRepeatingCenter" ); storeImageAndColor( LISTBOX_ENABLED_SELECTED_ITEM_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabled" ); storeImageAndColor( LISTBOX_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemLeftEnd" ); storeImageAndColor( LISTBOX_DISABLED_SELECTED_ITEM_LEFT, image, lightGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemRightEnd" ); storeImageAndColor( LISTBOX_DISABLED_SELECTED_ITEM_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemRepeatingCenter" ); storeImageAndColor( LISTBOX_DISABLED_SELECTED_ITEM_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemSmallRepeatingCenter" ); storeImageAndColor( LISTBOX_DISABLED_SELECTED_ITEM_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHilite" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHilite" ); storeImageAndColor( LISTBOX_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemLeftEnd" ); storeImageAndColor( LISTBOX_HILITE_SELECTED_ITEM_LEFT, image, white, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemRightEnd" ); storeImageAndColor( LISTBOX_HILITE_SELECTED_ITEM_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemRepeatingCenter" ); storeImageAndColor( LISTBOX_HILITE_SELECTED_ITEM_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemSmallRepeatingCenter" ); storeImageAndColor( LISTBOX_HILITE_SELECTED_ITEM_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonEnabled" ); storeImageAndColor( LISTBOX_UP_BUTTON_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonEnabled" ); storeImageAndColor( LISTBOX_UP_BUTTON_ENABLED_PUSHED, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonDisabled" ); storeImageAndColor( LISTBOX_UP_BUTTON_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonDisabled" ); storeImageAndColor( LISTBOX_UP_BUTTON_DISABLED_PUSHED, image, lightGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonHilite" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonHilite" ); storeImageAndColor( LISTBOX_UP_BUTTON_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonHiliteSelected" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonHiliteSelected" ); storeImageAndColor( LISTBOX_UP_BUTTON_HILITE_PUSHED, image, white, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonEnabled" ); storeImageAndColor( LISTBOX_DOWN_BUTTON_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonEnabled" ); storeImageAndColor( LISTBOX_DOWN_BUTTON_ENABLED_PUSHED, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonDisabled" ); storeImageAndColor( LISTBOX_DOWN_BUTTON_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonDisabled" ); storeImageAndColor( LISTBOX_DOWN_BUTTON_DISABLED_PUSHED, image, lightGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonHilite" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonHilite" ); storeImageAndColor( LISTBOX_DOWN_BUTTON_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonHiliteSelected" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonHiliteSelected" ); storeImageAndColor( LISTBOX_DOWN_BUTTON_HILITE_PUSHED, image, white, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeEnabledTopEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeEnabledTopEnd" ); storeImageAndColor( LISTBOX_SLIDER_ENABLED_TOP, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeEnabledBottomEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeEnabledBottomEnd" ); storeImageAndColor( LISTBOX_SLIDER_ENABLED_BOTTOM, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeEnabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeEnabledRepeatingCenter" ); storeImageAndColor( LISTBOX_SLIDER_ENABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeEnabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeEnabledSmallRepeatingCenter" ); storeImageAndColor( LISTBOX_SLIDER_ENABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDisabledTopEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDisabledTopEnd" ); storeImageAndColor( LISTBOX_SLIDER_DISABLED_TOP, image, gray, darkGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDisabledBottomEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDisabledBottomEnd" ); storeImageAndColor( LISTBOX_SLIDER_DISABLED_BOTTOM, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDisabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDisabledRepeatingCenter" ); storeImageAndColor( LISTBOX_SLIDER_DISABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDisabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDisabledSmallRepeatingCenter" ); storeImageAndColor( LISTBOX_SLIDER_DISABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeHiliteTopEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeHiliteTopEnd" ); storeImageAndColor( LISTBOX_SLIDER_HILITE_TOP, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeHiliteBottomEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeHiliteBottomEnd" ); storeImageAndColor( LISTBOX_SLIDER_HILITE_BOTTOM, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeHiliteRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeHiliteRepeatingCenter" ); storeImageAndColor( LISTBOX_SLIDER_HILITE_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeHiliteSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeHiliteSmallRepeatingCenter" ); storeImageAndColor( LISTBOX_SLIDER_HILITE_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbEnabled" ); storeImageAndColor( LISTBOX_SLIDER_THUMB_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbEnabled" ); storeImageAndColor( LISTBOX_SLIDER_THUMB_ENABLED_PUSHED, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbDisabled" ); storeImageAndColor( LISTBOX_SLIDER_THUMB_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbDisabled" ); storeImageAndColor( LISTBOX_SLIDER_THUMB_DISABLED_PUSHED, image, lightGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbHilite" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbHilite" ); storeImageAndColor( LISTBOX_SLIDER_THUMB_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbHiliteSelected" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbHiliteSelected" ); storeImageAndColor( LISTBOX_SLIDER_THUMB_HILITE_PUSHED, image, white, darkGreen ); // Combo Box //--------------------------------------------------------------------------- - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabled" ); storeImageAndColor( COMBOBOX_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemLeftEnd" ); storeImageAndColor( COMBOBOX_ENABLED_SELECTED_ITEM_LEFT, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemRightEnd" ); storeImageAndColor( COMBOBOX_ENABLED_SELECTED_ITEM_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemRepeatingCenter" ); storeImageAndColor( COMBOBOX_ENABLED_SELECTED_ITEM_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_ENABLED_SELECTED_ITEM_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabled" ); storeImageAndColor( COMBOBOX_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemLeftEnd" ); storeImageAndColor( COMBOBOX_DISABLED_SELECTED_ITEM_LEFT, image, lightGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemRightEnd" ); storeImageAndColor( COMBOBOX_DISABLED_SELECTED_ITEM_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemRepeatingCenter" ); storeImageAndColor( COMBOBOX_DISABLED_SELECTED_ITEM_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_DISABLED_SELECTED_ITEM_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHilite" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHilite" ); storeImageAndColor( COMBOBOX_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemLeftEnd" ); storeImageAndColor( COMBOBOX_HILITE_SELECTED_ITEM_LEFT, image, white, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemRightEnd" ); storeImageAndColor( COMBOBOX_HILITE_SELECTED_ITEM_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemRepeatingCenter" ); storeImageAndColor( COMBOBOX_HILITE_SELECTED_ITEM_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_HILITE_SELECTED_ITEM_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonEnabled" ); storeImageAndColor( COMBOBOX_DROP_DOWN_BUTTON_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonEnabled" ); storeImageAndColor( COMBOBOX_DROP_DOWN_BUTTON_ENABLED_PUSHED, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonDisabled" ); storeImageAndColor( COMBOBOX_DROP_DOWN_BUTTON_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonDisabled" ); storeImageAndColor( COMBOBOX_DROP_DOWN_BUTTON_DISABLED_PUSHED, image, lightGray, gray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonHilite" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonHilite" ); storeImageAndColor( COMBOBOX_DROP_DOWN_BUTTON_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonHilite" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonHilite" ); storeImageAndColor( COMBOBOX_DROP_DOWN_BUTTON_HILITE_PUSHED, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryEnabledLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryEnabledLeftEnd" ); storeImageAndColor( COMBOBOX_EDIT_BOX_ENABLED_LEFT, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryEnabledRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryEnabledRightEnd" ); storeImageAndColor( COMBOBOX_EDIT_BOX_ENABLED_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryEnabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryEnabledRepeatingCenter" ); storeImageAndColor( COMBOBOX_EDIT_BOX_ENABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryEnabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryEnabledSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_EDIT_BOX_ENABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryDisabledLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryDisabledLeftEnd" ); storeImageAndColor( COMBOBOX_EDIT_BOX_DISABLED_LEFT, image, gray, black ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryDisabledRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryDisabledRightEnd" ); storeImageAndColor( COMBOBOX_EDIT_BOX_DISABLED_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryDisabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryDisabledRepeatingCenter" ); storeImageAndColor( COMBOBOX_EDIT_BOX_DISABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryDisabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryDisabledSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_EDIT_BOX_DISABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryHiliteLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryHiliteLeftEnd" ); storeImageAndColor( COMBOBOX_EDIT_BOX_HILITE_LEFT, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryHiliteRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryHiliteRightEnd" ); storeImageAndColor( COMBOBOX_EDIT_BOX_HILITE_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryHiliteRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryHiliteRepeatingCenter" ); storeImageAndColor( COMBOBOX_EDIT_BOX_HILITE_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryHiliteSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryHiliteSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_EDIT_BOX_HILITE_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabled" ); storeImageAndColor( COMBOBOX_LISTBOX_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemLeftEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_ENABLED_SELECTED_ITEM_LEFT, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemRightEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_ENABLED_SELECTED_ITEM_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_ENABLED_SELECTED_ITEM_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_ENABLED_SELECTED_ITEM_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabled" ); storeImageAndColor( COMBOBOX_LISTBOX_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemLeftEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_DISABLED_SELECTED_ITEM_LEFT, image, lightGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemRightEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_DISABLED_SELECTED_ITEM_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_DISABLED_SELECTED_ITEM_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_DISABLED_SELECTED_ITEM_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHilite" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHilite" ); storeImageAndColor( COMBOBOX_LISTBOX_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemLeftEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_HILITE_SELECTED_ITEM_LEFT, image, white, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemRightEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_HILITE_SELECTED_ITEM_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_HILITE_SELECTED_ITEM_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_HILITE_SELECTED_ITEM_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonEnabled" ); storeImageAndColor( COMBOBOX_LISTBOX_UP_BUTTON_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonEnabled" ); storeImageAndColor( COMBOBOX_LISTBOX_UP_BUTTON_ENABLED_PUSHED, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonDisabled" ); storeImageAndColor( COMBOBOX_LISTBOX_UP_BUTTON_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonDisabled" ); storeImageAndColor( COMBOBOX_LISTBOX_UP_BUTTON_DISABLED_PUSHED, image, lightGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonHilite" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonHilite" ); storeImageAndColor( COMBOBOX_LISTBOX_UP_BUTTON_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonHiliteSelected" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonHiliteSelected" ); storeImageAndColor( COMBOBOX_LISTBOX_UP_BUTTON_HILITE_PUSHED, image, white, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonEnabled" ); storeImageAndColor( COMBOBOX_LISTBOX_DOWN_BUTTON_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonEnabled" ); storeImageAndColor( COMBOBOX_LISTBOX_DOWN_BUTTON_ENABLED_PUSHED, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonDisabled" ); storeImageAndColor( COMBOBOX_LISTBOX_DOWN_BUTTON_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonDisabled" ); storeImageAndColor( COMBOBOX_LISTBOX_DOWN_BUTTON_DISABLED_PUSHED, image, lightGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonHilite" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonHilite" ); storeImageAndColor( COMBOBOX_LISTBOX_DOWN_BUTTON_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonHiliteSelected" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonHiliteSelected" ); storeImageAndColor( COMBOBOX_LISTBOX_DOWN_BUTTON_HILITE_PUSHED, image, white, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeEnabledTopEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeEnabledTopEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_ENABLED_TOP, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeEnabledBottomEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeEnabledBottomEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_ENABLED_BOTTOM, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeEnabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeEnabledRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_ENABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeEnabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeEnabledSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_ENABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDisabledTopEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDisabledTopEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_DISABLED_TOP, image, gray, darkGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDisabledBottomEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDisabledBottomEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_DISABLED_BOTTOM, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDisabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDisabledRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_DISABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDisabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDisabledSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_DISABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeHiliteTopEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeHiliteTopEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_HILITE_TOP, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeHiliteBottomEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeHiliteBottomEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_HILITE_BOTTOM, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeHiliteRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeHiliteRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_HILITE_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeHiliteSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeHiliteSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_HILITE_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbEnabled" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_THUMB_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbEnabled" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_THUMB_ENABLED_PUSHED, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbDisabled" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_THUMB_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbDisabled" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_THUMB_DISABLED_PUSHED, image, lightGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbHilite" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbHilite" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_THUMB_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbHiliteSelected" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbHiliteSelected" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_THUMB_HILITE_PUSHED, image, white, darkGreen ); // progress bar //--------------------------------------------------------------------------- - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarEnabledLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarEnabledLeftEnd" ); storeImageAndColor( PROGRESS_BAR_ENABLED_LEFT, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarEnabledRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarEnabledRightEnd" ); storeImageAndColor( PROGRESS_BAR_ENABLED_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarEnabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarEnabledRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_ENABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarEnabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarEnabledSmallRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_ENABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarEnabledBarLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarEnabledBarLeftEnd" ); storeImageAndColor( PROGRESS_BAR_ENABLED_BAR_LEFT, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarEnabledBarRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarEnabledBarRightEnd" ); storeImageAndColor( PROGRESS_BAR_ENABLED_BAR_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarEnabledBarRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarEnabledBarRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_ENABLED_BAR_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarEnabledBarSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarEnabledBarSmallRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_ENABLED_BAR_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); //--------------------------------------------------------------------------- - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarDisabledLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarDisabledLeftEnd" ); storeImageAndColor( PROGRESS_BAR_DISABLED_LEFT, image, darkGray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarDisabledRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarDisabledRightEnd" ); storeImageAndColor( PROGRESS_BAR_DISABLED_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarDisabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarDisabledRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_DISABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarDisabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarDisabledSmallRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_DISABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarDisabledBarLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarDisabledBarLeftEnd" ); storeImageAndColor( PROGRESS_BAR_DISABLED_BAR_LEFT, image, lightGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarDisabledBarRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarDisabledBarRightEnd" ); storeImageAndColor( PROGRESS_BAR_DISABLED_BAR_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarDisabledBarRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarDisabledBarRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_DISABLED_BAR_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarDisabledBarSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarDisabledBarSmallRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_DISABLED_BAR_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); //--------------------------------------------------------------------------- - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarHiliteLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarHiliteLeftEnd" ); storeImageAndColor( PROGRESS_BAR_HILITE_LEFT, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarHiliteRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarHiliteRightEnd" ); storeImageAndColor( PROGRESS_BAR_HILITE_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarHiliteRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarHiliteRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_HILITE_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarHiliteSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarHiliteSmallRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_HILITE_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarHiliteBarLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarHiliteBarLeftEnd" ); storeImageAndColor( PROGRESS_BAR_HILITE_BAR_LEFT, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarHiliteBarRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarHiliteBarRightEnd" ); storeImageAndColor( PROGRESS_BAR_HILITE_BAR_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarHiliteBarRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarHiliteBarRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_HILITE_BAR_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarHiliteBarSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarHiliteBarSmallRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_HILITE_BAR_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); // static text //--------------------------------------------------------------------------- - image = TheMappedImageCollection->findImageByName( AsciiString( "StaticTextEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "StaticTextEnabled" ); storeImageAndColor( STATIC_TEXT_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "StaticTextDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "StaticTextDisabled" ); storeImageAndColor( STATIC_TEXT_DISABLED, image, darkGray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "StaticTextHilite" ) ); + image = TheMappedImageCollection->findImageByName( "StaticTextHilite" ); storeImageAndColor( STATIC_TEXT_HILITE, image, darkGreen, lightGreen ); // text entry - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryEnabledLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryEnabledLeftEnd" ); storeImageAndColor( TEXT_ENTRY_ENABLED_LEFT, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryEnabledRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryEnabledRightEnd" ); storeImageAndColor( TEXT_ENTRY_ENABLED_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryEnabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryEnabledRepeatingCenter" ); storeImageAndColor( TEXT_ENTRY_ENABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryEnabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryEnabledSmallRepeatingCenter" ); storeImageAndColor( TEXT_ENTRY_ENABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryDisabledLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryDisabledLeftEnd" ); storeImageAndColor( TEXT_ENTRY_DISABLED_LEFT, image, gray, black ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryDisabledRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryDisabledRightEnd" ); storeImageAndColor( TEXT_ENTRY_DISABLED_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryDisabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryDisabledRepeatingCenter" ); storeImageAndColor( TEXT_ENTRY_DISABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryDisabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryDisabledSmallRepeatingCenter" ); storeImageAndColor( TEXT_ENTRY_DISABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryHiliteLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryHiliteLeftEnd" ); storeImageAndColor( TEXT_ENTRY_HILITE_LEFT, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryHiliteRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryHiliteRightEnd" ); storeImageAndColor( TEXT_ENTRY_HILITE_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryHiliteRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryHiliteRepeatingCenter" ); storeImageAndColor( TEXT_ENTRY_HILITE_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryHiliteSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryHiliteSmallRepeatingCenter" ); storeImageAndColor( TEXT_ENTRY_HILITE_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); // Tab Control - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlZeroEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlZeroEnabled" ); storeImageAndColor( TC_TAB_0_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlZeroDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlZeroDisabled" ); storeImageAndColor( TC_TAB_0_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlZeroHilite" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlZeroHilite" ); storeImageAndColor( TC_TAB_0_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlOneEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlOneEnabled" ); storeImageAndColor( TC_TAB_1_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlOneDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlOneDisabled" ); storeImageAndColor( TC_TAB_1_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlOneHilite" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlOneHilite" ); storeImageAndColor( TC_TAB_1_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlTwoEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlTwoEnabled" ); storeImageAndColor( TC_TAB_2_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlTwoDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlTwoDisabled" ); storeImageAndColor( TC_TAB_2_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlTwoHilite" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlTwoHilite" ); storeImageAndColor( TC_TAB_2_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlThreeEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlThreeEnabled" ); storeImageAndColor( TC_TAB_3_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlThreeDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlThreeDisabled" ); storeImageAndColor( TC_TAB_3_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlThreeHilite" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlThreeHilite" ); storeImageAndColor( TC_TAB_3_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlFourEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlFourEnabled" ); storeImageAndColor( TC_TAB_4_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlFourDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlFourDisabled" ); storeImageAndColor( TC_TAB_4_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlFourHilite" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlFourHilite" ); storeImageAndColor( TC_TAB_4_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlFiveEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlFiveEnabled" ); storeImageAndColor( TC_TAB_5_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlFiveDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlFiveDisabled" ); storeImageAndColor( TC_TAB_5_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlFiveHilite" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlFiveHilite" ); storeImageAndColor( TC_TAB_5_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlSixEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlSixEnabled" ); storeImageAndColor( TC_TAB_6_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlSixDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlSixDisabled" ); storeImageAndColor( TC_TAB_6_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlSixHilite" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlSixHilite" ); storeImageAndColor( TC_TAB_6_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlSevenEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlSevenEnabled" ); storeImageAndColor( TC_TAB_7_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlSevenDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlSevenDisabled" ); storeImageAndColor( TC_TAB_7_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlSevenHilite" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlSevenHilite" ); storeImageAndColor( TC_TAB_7_HILITE, image, green, darkGreen ); storeImageAndColor( TAB_CONTROL_ENABLED, NULL, black, white ); @@ -2147,7 +2147,7 @@ void LayoutScheme::init( void ) m_hiliteText.borderColor = darkBlue; // default font - m_font = TheWindowManager->winFindFont( AsciiString("Times New Roman"), 14, FALSE ); + m_font = TheWindowManager->winFindFont( "Times New Roman", 14, FALSE ); } // LayoutScheme::openDialog =================================================== diff --git a/Generals/Code/Tools/WorldBuilder/src/GroveTool.cpp b/Generals/Code/Tools/WorldBuilder/src/GroveTool.cpp index f83132b42a..c53bc119d5 100644 --- a/Generals/Code/Tools/WorldBuilder/src/GroveTool.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/GroveTool.cpp @@ -108,7 +108,7 @@ void GroveTool::activate() void GroveTool::plantShrub( Coord3D *pos ) { // TODO: Determine when we can tell something is a shurubbery, and plant it here - jkmcd -// addObj(pos, AsciiString("Shrub")); +// addObj(pos, "Shrub"); } void GroveTool::_plantGroveInBox(CPoint tl, CPoint br, WbView* pView) diff --git a/Generals/Code/Tools/WorldBuilder/src/ScorchTool.cpp b/Generals/Code/Tools/WorldBuilder/src/ScorchTool.cpp index 0e218f1128..7dc51c9a8d 100644 --- a/Generals/Code/Tools/WorldBuilder/src/ScorchTool.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/ScorchTool.cpp @@ -111,7 +111,7 @@ void ScorchTool::mouseDown(TTrackingMode m, CPoint viewPt, WbView* pView, CWorld ScorchOptions::update(); } else { pView->snapPoint(&docPt); - MapObject *pNew = newInstance(MapObject)(docPt, AsciiString("Scorch"), 0, 0, NULL, NULL ); + MapObject *pNew = newInstance(MapObject)(docPt, "Scorch", 0, 0, NULL, NULL ); pNew->getProperties()->setAsciiString(TheKey_originalOwner, NEUTRAL_TEAM_INTERNAL_STR); pNew->setSelected(true); pNew->setIsScorch(); diff --git a/Generals/Code/Tools/WorldBuilder/src/ScriptDialog.cpp b/Generals/Code/Tools/WorldBuilder/src/ScriptDialog.cpp index 44b8dbad83..1cfdb69b09 100644 --- a/Generals/Code/Tools/WorldBuilder/src/ScriptDialog.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/ScriptDialog.cpp @@ -1372,12 +1372,12 @@ void ScriptDialog::OnLoad() m_firstTrigger = NULL; m_waypointBase = pDoc->getNextWaypointID(); m_maxWaypoint = m_waypointBase; - file.registerParser( AsciiString("PlayerScriptsList"), AsciiString::TheEmptyString, ScriptList::ParseScriptsDataChunk ); - file.registerParser( AsciiString("ObjectsList"), AsciiString::TheEmptyString, ParseObjectsDataChunk ); - file.registerParser( AsciiString("PolygonTriggers"), AsciiString::TheEmptyString, ParsePolygonTriggersDataChunk ); - file.registerParser( AsciiString("WaypointsList"), AsciiString::TheEmptyString, ParseWaypointDataChunk ); - file.registerParser( AsciiString("ScriptTeams"), AsciiString::TheEmptyString, ParseTeamsDataChunk ); - file.registerParser( AsciiString("ScriptsPlayers"), AsciiString::TheEmptyString, ParsePlayersDataChunk ); + file.registerParser( "PlayerScriptsList", AsciiString::TheEmptyString, ScriptList::ParseScriptsDataChunk ); + file.registerParser( "ObjectsList", AsciiString::TheEmptyString, ParseObjectsDataChunk ); + file.registerParser( "PolygonTriggers", AsciiString::TheEmptyString, ParsePolygonTriggersDataChunk ); + file.registerParser( "WaypointsList", AsciiString::TheEmptyString, ParseWaypointDataChunk ); + file.registerParser( "ScriptTeams", AsciiString::TheEmptyString, ParseTeamsDataChunk ); + file.registerParser( "ScriptsPlayers", AsciiString::TheEmptyString, ParsePlayersDataChunk ); if (!file.parse(this)) { throw(ERROR_CORRUPT_FILE_FORMAT); } @@ -1474,7 +1474,7 @@ void ScriptDialog::OnLoad() Bool ScriptDialog::ParseObjectsDataChunk(DataChunkInput &file, DataChunkInfo *info, void *userData) { file.m_currentObject = NULL; - file.registerParser( AsciiString("Object"), info->label, ParseObjectDataChunk ); + file.registerParser( "Object", info->label, ParseObjectDataChunk ); return (file.parse(userData)); } diff --git a/Generals/Code/Tools/WorldBuilder/src/SelectMacrotexture.cpp b/Generals/Code/Tools/WorldBuilder/src/SelectMacrotexture.cpp index 9abdd6d479..fe8584c298 100644 --- a/Generals/Code/Tools/WorldBuilder/src/SelectMacrotexture.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/SelectMacrotexture.cpp @@ -131,7 +131,7 @@ BOOL SelectMacrotexture::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult item.cchTextMax = sizeof(buffer)-2; m_textureTreeView.GetItem(&item); if (0==strcmp(buffer, DEFAULT)) { - TheTerrainRenderObject->updateMacroTexture(AsciiString("")); + TheTerrainRenderObject->updateMacroTexture(""); } else { TheTerrainRenderObject->updateMacroTexture(AsciiString(buffer)); } diff --git a/Generals/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp b/Generals/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp index e9327dfa98..78fd55aeec 100644 --- a/Generals/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp @@ -425,7 +425,7 @@ void WorldHeightMapEdit::loadDirectoryOfImages(const char *pFilePath) } FilenameList filenameList; - TheFileSystem->getFileListInDirectory(AsciiString(dirBuf), AsciiString("*.*"), filenameList, TRUE); + TheFileSystem->getFileListInDirectory(AsciiString(dirBuf), "*.*", filenameList, TRUE); if (filenameList.size() == 0) { return; diff --git a/Generals/Code/Tools/WorldBuilder/src/WaypointTool.cpp b/Generals/Code/Tools/WorldBuilder/src/WaypointTool.cpp index ee7f4bb25a..2456882821 100644 --- a/Generals/Code/Tools/WorldBuilder/src/WaypointTool.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/WaypointTool.cpp @@ -119,14 +119,14 @@ void WaypointTool::mouseDown(TTrackingMode m, CPoint viewPt, WbView* pView, CWor WaypointOptions::update(); } else { pView->snapPoint(&docPt); - MapObject *pNew = newInstance( MapObject)(docPt, AsciiString("*Waypoints/Waypoint"), 0, 0, NULL, NULL ); + MapObject *pNew = newInstance( MapObject)(docPt, "*Waypoints/Waypoint", 0, 0, NULL, NULL ); Int id = pDoc->getNextWaypointID(); AsciiString name = WaypointOptions::GenerateUniqueName(id); pNew->setSelected(true); pNew->setIsWaypoint(); pNew->setWaypointID(id); pNew->setWaypointName(name); - pNew->getProperties()->setAsciiString(TheKey_originalOwner, AsciiString("team")); + pNew->getProperties()->setAsciiString(TheKey_originalOwner, "team"); AddObjectUndoable *pUndo = new AddObjectUndoable(pDoc, pNew); pDoc->AddAndDoUndoable(pUndo); REF_PTR_RELEASE(pUndo); // belongs to pDoc now. @@ -166,7 +166,7 @@ void WaypointTool::mouseUp(TTrackingMode m, CPoint viewPt, WbView* pView, CWorld pObj = pickWaypoint(docPt); if (pObj == NULL) { pView->snapPoint(&docPt); - MapObject *pNew = newInstance( MapObject)(docPt, AsciiString("*Waypoints/Waypoint"), 0, 0, NULL, NULL ); + MapObject *pNew = newInstance( MapObject)(docPt, "*Waypoints/Waypoint", 0, 0, NULL, NULL ); Int id = pDoc->getNextWaypointID(); AsciiString name; name.format("Waypoint %d", id); @@ -174,7 +174,7 @@ void WaypointTool::mouseUp(TTrackingMode m, CPoint viewPt, WbView* pView, CWorld pNew->setIsWaypoint(); pNew->setWaypointID(id); pNew->setWaypointName(name); - pNew->getProperties()->setAsciiString(TheKey_originalOwner, AsciiString("team")); + pNew->getProperties()->setAsciiString(TheKey_originalOwner, "team"); AddObjectUndoable *pUndo = new AddObjectUndoable(pDoc, pNew); pDoc->AddAndDoUndoable(pUndo); REF_PTR_RELEASE(pUndo); // belongs to pDoc now. diff --git a/Generals/Code/Tools/WorldBuilder/src/WorldBuilder.cpp b/Generals/Code/Tools/WorldBuilder/src/WorldBuilder.cpp index a756f622f7..577eedc7d4 100644 --- a/Generals/Code/Tools/WorldBuilder/src/WorldBuilder.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/WorldBuilder.cpp @@ -337,7 +337,7 @@ BOOL CWorldBuilderApp::InitInstance() TheFramePacer = new FramePacer(); #if defined(RTS_DEBUG) - ini.loadFileDirectory( AsciiString( "Data\\INI\\GameDataDebug" ), INI_LOAD_MULTIFILE, NULL ); + ini.loadFileDirectory( "Data\\INI\\GameDataDebug", INI_LOAD_MULTIFILE, NULL ); #endif #ifdef DEBUG_CRASHING @@ -362,8 +362,8 @@ BOOL CWorldBuilderApp::InitInstance() CreateDirectory(buf, NULL); // read the water settings from INI (must do prior to initing GameClient, apparently) - ini.loadFileDirectory( AsciiString( "Data\\INI\\Default\\Water" ), INI_LOAD_OVERWRITE, NULL ); - ini.loadFileDirectory( AsciiString( "Data\\INI\\Water" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Default\\Water", INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Water", INI_LOAD_OVERWRITE, NULL ); initSubsystem(TheGameText, CreateGameTextInterface()); initSubsystem(TheScienceStore, new ScienceStore(), "Data\\INI\\Default\\Science", "Data\\INI\\Science"); @@ -681,7 +681,7 @@ void CWorldBuilderApp::OnFileOpen() #endif CFileStatus status; - if (m_currentDirectory != AsciiString("")) try { + if (m_currentDirectory != "") try { if (CFile::GetStatus(m_currentDirectory.str(), status)) { if (status.m_attribute & CFile::directory) { ::SetCurrentDirectory(m_currentDirectory.str()); diff --git a/Generals/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp b/Generals/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp index c94bf3d688..833e10e66c 100644 --- a/Generals/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp @@ -332,7 +332,7 @@ void CWorldBuilderDoc::Serialize(CArchive& ar) DataChunkInput file( pStrm ); if (file.isValidFileType()) { // Backwards compatible files aren't valid data chunk files. // Read the waypoints. - file.registerParser( AsciiString("WaypointsList"), AsciiString::TheEmptyString, ParseWaypointDataChunk ); + file.registerParser( "WaypointsList", AsciiString::TheEmptyString, ParseWaypointDataChunk ); if (!file.parse(this)) { throw(ERROR_CORRUPT_FILE_FORMAT); } diff --git a/Generals/Code/Tools/WorldBuilder/src/playerlistdlg.cpp b/Generals/Code/Tools/WorldBuilder/src/playerlistdlg.cpp index 5a62979733..ec1855d77a 100644 --- a/Generals/Code/Tools/WorldBuilder/src/playerlistdlg.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/playerlistdlg.cpp @@ -305,8 +305,8 @@ void PlayerListDlg::OnNewplayer() newPlayerDict.setBool(TheKey_playerIsHuman, true); newPlayerDict.setUnicodeString(TheKey_playerDisplayName, pnameu); newPlayerDict.setAsciiString(TheKey_playerFaction, addedPTName); - newPlayerDict.setAsciiString(TheKey_playerEnemies, AsciiString("")); - newPlayerDict.setAsciiString(TheKey_playerAllies, AsciiString("")); + newPlayerDict.setAsciiString(TheKey_playerEnemies, ""); + newPlayerDict.setAsciiString(TheKey_playerAllies, ""); #ifdef NOT_IN_USE // auto-open the advanced prop editor @@ -859,8 +859,8 @@ void PlayerListDlg::OnAddskirmishplayers() newPlayerDict.setBool(TheKey_playerIsHuman, false); newPlayerDict.setUnicodeString(TheKey_playerDisplayName, pnameu); newPlayerDict.setAsciiString(TheKey_playerFaction, addedPTName); - newPlayerDict.setAsciiString(TheKey_playerEnemies, AsciiString("")); - newPlayerDict.setAsciiString(TheKey_playerAllies, AsciiString("")); + newPlayerDict.setAsciiString(TheKey_playerEnemies, ""); + newPlayerDict.setAsciiString(TheKey_playerAllies, ""); ensureValidPlayerName(&newPlayerDict); m_sides.addSide(&newPlayerDict); @@ -881,8 +881,8 @@ void PlayerListDlg::OnAddskirmishplayers() newPlayerDict.setBool(TheKey_playerIsHuman, false); newPlayerDict.setUnicodeString(TheKey_playerDisplayName, pnameu); newPlayerDict.setAsciiString(TheKey_playerFaction, addedPTName); - newPlayerDict.setAsciiString(TheKey_playerEnemies, AsciiString("")); - newPlayerDict.setAsciiString(TheKey_playerAllies, AsciiString("")); + newPlayerDict.setAsciiString(TheKey_playerEnemies, ""); + newPlayerDict.setAsciiString(TheKey_playerAllies, ""); ensureValidPlayerName(&newPlayerDict); m_sides.addSide(&newPlayerDict); @@ -903,8 +903,8 @@ void PlayerListDlg::OnAddskirmishplayers() newPlayerDict.setBool(TheKey_playerIsHuman, false); newPlayerDict.setUnicodeString(TheKey_playerDisplayName, pnameu); newPlayerDict.setAsciiString(TheKey_playerFaction, addedPTName); - newPlayerDict.setAsciiString(TheKey_playerEnemies, AsciiString("")); - newPlayerDict.setAsciiString(TheKey_playerAllies, AsciiString("")); + newPlayerDict.setAsciiString(TheKey_playerEnemies, ""); + newPlayerDict.setAsciiString(TheKey_playerAllies, ""); ensureValidPlayerName(&newPlayerDict); m_sides.addSide(&newPlayerDict); @@ -925,8 +925,8 @@ void PlayerListDlg::OnAddskirmishplayers() newPlayerDict.setBool(TheKey_playerIsHuman, false); newPlayerDict.setUnicodeString(TheKey_playerDisplayName, pnameu); newPlayerDict.setAsciiString(TheKey_playerFaction, addedPTName); - newPlayerDict.setAsciiString(TheKey_playerEnemies, AsciiString("")); - newPlayerDict.setAsciiString(TheKey_playerAllies, AsciiString("")); + newPlayerDict.setAsciiString(TheKey_playerEnemies, ""); + newPlayerDict.setAsciiString(TheKey_playerAllies, ""); ensureValidPlayerName(&newPlayerDict); m_sides.addSide(&newPlayerDict); diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/ArmorSet.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/ArmorSet.h index 9dccd0cf0e..00204fa0eb 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/ArmorSet.h +++ b/GeneralsMD/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(RTS_DEBUG) - inline AsciiString getDescription() const { return AsciiString("ArmorTemplateSet"); } + inline AsciiString getDescription() const { return "ArmorTemplateSet"; } #endif void parseArmorTemplateSet( INI* ini ); diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/WeaponSet.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/WeaponSet.h index 75ad9b72df..707d5fffc1 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/WeaponSet.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/WeaponSet.h @@ -158,7 +158,7 @@ class WeaponTemplateSet inline Int getConditionsYesCount() const { return 1; } inline const WeaponSetFlags& getNthConditionsYes(Int i) const { return m_types; } #if defined(RTS_DEBUG) - inline AsciiString getDescription() const { return AsciiString("ArmorTemplateSet"); } + inline AsciiString getDescription() const { return "ArmorTemplateSet"; } #endif }; diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp index 7c7418a6a5..186b54ac33 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp @@ -467,7 +467,7 @@ void GameEngine::init() #if defined(RTS_DEBUG) // If we're in Debug, load the Debug settings as well. - ini.loadFileDirectory( AsciiString( "Data\\INI\\GameDataDebug" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\GameDataDebug", INI_LOAD_OVERWRITE, NULL ); #endif // special-case: parse command-line parameters after loading global data @@ -486,10 +486,10 @@ void GameEngine::init() } // read the water settings from INI (must do prior to initing GameClient, apparently) - ini.loadFileDirectory( AsciiString( "Data\\INI\\Default\\Water" ), INI_LOAD_OVERWRITE, &xferCRC ); - ini.loadFileDirectory( AsciiString( "Data\\INI\\Water" ), INI_LOAD_OVERWRITE, &xferCRC ); - ini.loadFileDirectory( AsciiString( "Data\\INI\\Default\\Weather" ), INI_LOAD_OVERWRITE, &xferCRC ); - ini.loadFileDirectory( AsciiString( "Data\\INI\\Weather" ), INI_LOAD_OVERWRITE, &xferCRC ); + ini.loadFileDirectory( "Data\\INI\\Default\\Water", INI_LOAD_OVERWRITE, &xferCRC ); + ini.loadFileDirectory( "Data\\INI\\Water", INI_LOAD_OVERWRITE, &xferCRC ); + ini.loadFileDirectory( "Data\\INI\\Default\\Weather", INI_LOAD_OVERWRITE, &xferCRC ); + ini.loadFileDirectory( "Data\\INI\\Weather", INI_LOAD_OVERWRITE, &xferCRC ); @@ -695,7 +695,7 @@ void GameEngine::init() } // load the initial shell screen - //TheShell->push( AsciiString("Menus/MainMenu.wnd") ); + //TheShell->push( "Menus/MainMenu.wnd" ); // This allows us to run a map from the command line if (TheGlobalData->m_initialFile.isEmpty() == FALSE) diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameLOD.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameLOD.cpp index 7a227a67f5..4594265789 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/GameLOD.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/GameLOD.cpp @@ -303,10 +303,10 @@ void GameLODManager::init(void) { INI ini; //Get Presets for each LOD level. - ini.loadFileDirectory( AsciiString( "Data\\INI\\GameLOD" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\GameLOD", INI_LOAD_OVERWRITE, NULL ); //Get presets for each known hardware configuration - ini.loadFileDirectory( AsciiString( "Data\\INI\\GameLODPresets"), INI_LOAD_OVERWRITE, NULL); + ini.loadFileDirectory( "Data\\INI\\GameLODPresets", INI_LOAD_OVERWRITE, NULL); //Get Presets for custom LOD level by pulling them out of initial globaldata (which should //have all settings already applied). diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp index a9d064db43..a02e47e3c0 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp @@ -1769,7 +1769,7 @@ RecorderModeType RecorderClass::getMode() { ///< Show or Hide the Replay controls void RecorderClass::initControls() { - NameKeyType parentReplayControlID = TheNameKeyGenerator->nameToKey( AsciiString("ReplayControl.wnd:ParentReplayControl") ); + NameKeyType parentReplayControlID = TheNameKeyGenerator->nameToKey( "ReplayControl.wnd:ParentReplayControl" ); GameWindow *parentReplayControl = TheWindowManager->winGetWindowFromId( NULL, parentReplayControlID ); Bool show = (getMode() != RECORDERMODETYPE_PLAYBACK); diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/DataChunk.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/DataChunk.cpp index c1378ffeaf..01bc174f2f 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/DataChunk.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/DataChunk.cpp @@ -743,7 +743,7 @@ AsciiString DataChunkInput::openDataChunk(DataChunkVersionType *ver ) c->next = m_chunkStack; m_chunkStack = c; if (this->atEndOfFile()) { - return (AsciiString("")); + return AsciiString::TheEmptyString; } return m_contents.getName( c->id ); } @@ -779,7 +779,7 @@ AsciiString DataChunkInput::getChunkLabel( void ) { // TODO: Throw exception DEBUG_CRASH(("Bad.")); - return AsciiString(""); + return AsciiString::TheEmptyString; } return m_contents.getName( m_chunkStack->id ); diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp index 5b6bd01a26..b8add65553 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp @@ -636,7 +636,7 @@ SaveCode GameState::missionSave( void ) desc.format( format, TheGameText->fetch( campaign->m_campaignNameLabel ).str(), missionNumber ); // do an automatic mission save - return TheGameState->saveGame( AsciiString(""), desc, SAVE_FILE_TYPE_MISSION ); + return TheGameState->saveGame( "", desc, SAVE_FILE_TYPE_MISSION ); } diff --git a/GeneralsMD/Code/GameEngine/Source/Common/TerrainTypes.cpp b/GeneralsMD/Code/GameEngine/Source/Common/TerrainTypes.cpp index 150e3579a8..43b5186f62 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/TerrainTypes.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/TerrainTypes.cpp @@ -139,7 +139,7 @@ TerrainType *TerrainTypeCollection::newTerrain( AsciiString name ) terrain = newInstance(TerrainType); // copy default values from the default terrain entry - TerrainType *defaultTerrain = findTerrain( AsciiString( "DefaultTerrain" ) ); + TerrainType *defaultTerrain = findTerrain( "DefaultTerrain" ); if( defaultTerrain ) *terrain = *defaultTerrain; /* diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp index 3a3f5a02a1..1aa09afad2 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp @@ -134,7 +134,7 @@ ThingTemplate *ThingFactory::newTemplate( const AsciiString& name ) newTemplate = newInstance(ThingTemplate); // if the default template is present, get it and copy over any data to the new template - const ThingTemplate *defaultT = findTemplate( AsciiString( "DefaultThingTemplate" ), FALSE ); + const ThingTemplate *defaultT = findTemplate( "DefaultThingTemplate", FALSE ); if( defaultT ) { @@ -276,7 +276,7 @@ ThingTemplate *ThingFactory::findTemplateInternal( const AsciiString& name, Bool #ifdef LOAD_TEST_ASSETS if (!strncmp(name.str(), TEST_STRING, strlen(TEST_STRING))) { - ThingTemplate *tmplate = newTemplate( AsciiString( "Un-namedTemplate" ) ); + ThingTemplate *tmplate = newTemplate( "Un-namedTemplate" ); // load the values tmplate->initForLTA( name ); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Credits.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Credits.cpp index ec6218e8b2..a26d9eee66 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Credits.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Credits.cpp @@ -155,7 +155,7 @@ void CreditsManager::load(void ) { INI ini; // Read from INI all the ControlBarSchemes - ini.loadFileDirectory( AsciiString( "Data\\INI\\Credits" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Credits", INI_LOAD_OVERWRITE, NULL ); if(m_scrollRatePerFrames <=0) m_scrollRatePerFrames = 1; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Eva.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Eva.cpp index bb5d863ed5..25b02f109a 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Eva.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Eva.cpp @@ -254,7 +254,7 @@ void Eva::init() { // parse the INI here, etc. INI ini; - ini.loadFileDirectory( AsciiString( "Data\\INI\\Eva" ), INI_LOAD_OVERWRITE, NULL); + ini.loadFileDirectory( "Data\\INI\\Eva", INI_LOAD_OVERWRITE, NULL); } //------------------------------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ChallengeGenerals.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ChallengeGenerals.cpp index fdee657e02..d270e95daf 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ChallengeGenerals.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ChallengeGenerals.cpp @@ -55,7 +55,7 @@ ChallengeGenerals::~ChallengeGenerals() void ChallengeGenerals::init( void ) { INI ini; - ini.loadFileDirectory( AsciiString( "Data\\INI\\ChallengeMode" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\ChallengeMode", INI_LOAD_OVERWRITE, NULL ); } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp index 9f7d0e1053..a526844127 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp @@ -1062,11 +1062,11 @@ void ControlBar::init( void ) INI ini; m_sideSelectAnimateDown = FALSE; // load the command buttons - ini.loadFileDirectory( AsciiString( "Data\\INI\\Default\\CommandButton" ), INI_LOAD_OVERWRITE, NULL ); - ini.loadFileDirectory( AsciiString( "Data\\INI\\CommandButton" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Default\\CommandButton", INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\CommandButton", INI_LOAD_OVERWRITE, NULL ); // load the command sets - ini.loadFileDirectory( AsciiString( "Data\\INI\\CommandSet" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\CommandSet", INI_LOAD_OVERWRITE, NULL ); // post process step after loading the command buttons and command sets postProcessCommands(); @@ -1253,9 +1253,9 @@ void ControlBar::init( void ) m_radarAttackGlowWindow = TheWindowManager->winGetWindowFromId(NULL, TheNameKeyGenerator->nameToKey("ControlBar.wnd:WinUAttack")); - win = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( AsciiString( "ControlBar.wnd:BackgroundMarker" ) )); + win = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( "ControlBar.wnd:BackgroundMarker" )); win->winGetScreenPosition(&m_controlBarForegroundMarkerPos.x, &m_controlBarForegroundMarkerPos.y); - win = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( AsciiString( "ControlBar.wnd:BackgroundMarker" ) )); + win = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( "ControlBar.wnd:BackgroundMarker" )); win->winGetScreenPosition(&m_controlBarBackgroundMarkerPos.x,&m_controlBarBackgroundMarkerPos.y); if(!m_videoManager) @@ -1411,7 +1411,7 @@ void ControlBar::update( void ) { if (m_animateWindowManager->isFinished() && m_animateWindowManager->isReversed()) { - Int id = (Int)TheNameKeyGenerator->nameToKey(AsciiString("ControlBar.wnd:ControlBarParent")); + Int id = (Int)TheNameKeyGenerator->nameToKey("ControlBar.wnd:ControlBarParent"); GameWindow *window = TheWindowManager->winGetWindowFromId(NULL, id); if (window && !window->winIsHidden()) window->winHide(TRUE); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarObserver.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarObserver.cpp index ab5ae384ad..bd7a154d68 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarObserver.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarObserver.cpp @@ -224,7 +224,7 @@ WindowMsgHandledType ControlBarObserverSystem( GameWindow *window, UnsignedInt m // if( controlID == buttonCommunicator && TheGameLogic->getGameMode() == GAME_INTERNET ) /* { - popupCommunicatorLayout = TheWindowManager->winCreateLayout( AsciiString( "Menus/PopupCommunicator.wnd" ) ); + popupCommunicatorLayout = TheWindowManager->winCreateLayout( "Menus/PopupCommunicator.wnd" ); popupCommunicatorLayout->runInit(); popupCommunicatorLayout->hide( FALSE ); popupCommunicatorLayout->bringForward(); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarResizer.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarResizer.cpp index 56594e991a..2eee2dd531 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarResizer.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarResizer.cpp @@ -103,7 +103,7 @@ void ControlBarResizer::init( void ) { INI ini; // Read from INI all the ControlBarSchemes - ini.loadFileDirectory( AsciiString( "Data\\INI\\ControlBarResizer" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\ControlBarResizer", INI_LOAD_OVERWRITE, NULL ); } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp index 72018691d7..c6be2fa7fa 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp @@ -1020,8 +1020,8 @@ void ControlBarSchemeManager::init( void ) INI ini; // Read from INI all the ControlBarSchemes - ini.loadFileDirectory( AsciiString( "Data\\INI\\Default\\ControlBarScheme" ), INI_LOAD_OVERWRITE, NULL ); - ini.loadFileDirectory( AsciiString( "Data\\INI\\ControlBarScheme" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Default\\ControlBarScheme", INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\ControlBarScheme", INI_LOAD_OVERWRITE, NULL ); // //Load the user modified control bar schemes // WIN32_FIND_DATA findData; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarCallback.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarCallback.cpp index 964a93915a..fef643087a 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarCallback.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarCallback.cpp @@ -357,7 +357,7 @@ WindowMsgHandledType ControlBarSystem( GameWindow *window, UnsignedInt msg, { // get ids for our children controls - buttonCommunicator = TheNameKeyGenerator->nameToKey( AsciiString("ControlBar.wnd:PopupCommunicator") ); + buttonCommunicator = TheNameKeyGenerator->nameToKey( "ControlBar.wnd:PopupCommunicator" ); break; @@ -502,7 +502,7 @@ void ShowControlBar( Bool immediate ) TheControlBar->showSpecialPowerShortcut(); - Int id = (Int)TheNameKeyGenerator->nameToKey(AsciiString("ControlBar.wnd:ControlBarParent")); + Int id = (Int)TheNameKeyGenerator->nameToKey("ControlBar.wnd:ControlBarParent"); GameWindow *window = TheWindowManager->winGetWindowFromId(NULL, id); if (window) @@ -537,7 +537,7 @@ void HideControlBar( Bool immediate ) TheControlBar->hideSpecialPowerShortcut(); - Int id = (Int)TheNameKeyGenerator->nameToKey(AsciiString("ControlBar.wnd:ControlBarParent")); + Int id = (Int)TheNameKeyGenerator->nameToKey("ControlBar.wnd:ControlBarParent"); GameWindow *window = TheWindowManager->winGetWindowFromId(NULL, id); if (window) @@ -573,7 +573,7 @@ void ToggleControlBar( Bool immediate ) toggleReplayControls(); - Int id = (Int)TheNameKeyGenerator->nameToKey(AsciiString("ControlBar.wnd:ControlBarParent")); + Int id = (Int)TheNameKeyGenerator->nameToKey("ControlBar.wnd:ControlBarParent"); GameWindow *window = TheWindowManager->winGetWindowFromId(NULL, id); if (window) diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp index 2803730c0a..8d2659db83 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp @@ -615,7 +615,7 @@ void ControlBar::populateBuildTooltipLayout( const CommandButton *commandButton, if(win) { - static NameKeyType winNamekey = TheNameKeyGenerator->nameToKey( AsciiString( "ControlBar.wnd:BackgroundMarker" ) ); + static NameKeyType winNamekey = TheNameKeyGenerator->nameToKey( "ControlBar.wnd:BackgroundMarker" ); static ICoord2D lastOffset = { 0, 0 }; ICoord2D size, newSize, pos; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ExtendedMessageBox.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ExtendedMessageBox.cpp index 158d9779e5..ec5c383e37 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ExtendedMessageBox.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ExtendedMessageBox.cpp @@ -62,7 +62,7 @@ static GameWindow *gogoExMessageBox(Int x, Int y, Int width, Int height, Unsigne return NULL; } - GameWindow *parent = TheWindowManager->winCreateFromScript( AsciiString("Menus/MessageBox.wnd") ); + GameWindow *parent = TheWindowManager->winCreateFromScript( "Menus/MessageBox.wnd" ); TheWindowManager->winSetModal( parent ); TheWindowManager->winSetFocus( NULL ); // make sure we lose focus from other windows even if we refuse focus ourselves TheWindowManager->winSetFocus( parent ); @@ -104,19 +104,19 @@ static GameWindow *gogoExMessageBox(Int x, Int y, Int width, Int height, Unsigne Int buttonX[3], buttonY[3]; //In the layout, buttonOk will be in the first button position - NameKeyType buttonOkID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonOk" ) ); + NameKeyType buttonOkID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonOk" ); GameWindow *buttonOk = TheWindowManager->winGetWindowFromId(parent, buttonOkID); buttonOk->winGetPosition(&buttonX[0], &buttonY[0]); - NameKeyType buttonYesID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonYes" ) ); + NameKeyType buttonYesID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonYes" ); GameWindow *buttonYes = TheWindowManager->winGetWindowFromId(parent, buttonYesID); //buttonNo in the second position - NameKeyType buttonNoID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonNo" ) ); + NameKeyType buttonNoID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonNo" ); GameWindow *buttonNo = TheWindowManager->winGetWindowFromId(parent, buttonNoID); buttonNo->winGetPosition(&buttonX[1], &buttonY[1]); //and buttonCancel in the third - NameKeyType buttonCancelID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonCancel" ) ); + NameKeyType buttonCancelID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonCancel" ); GameWindow *buttonCancel = TheWindowManager->winGetWindowFromId(parent, buttonCancelID); buttonCancel->winGetPosition(&buttonX[2], &buttonY[2]); @@ -161,11 +161,11 @@ static GameWindow *gogoExMessageBox(Int x, Int y, Int width, Int height, Unsigne } // Fill the text into the text boxes - NameKeyType staticTextTitleID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:StaticTextTitle" ) ); + NameKeyType staticTextTitleID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:StaticTextTitle" ); GameWindow *staticTextTitle = TheWindowManager->winGetWindowFromId(parent, staticTextTitleID); GadgetStaticTextSetText(staticTextTitle,titleString); - NameKeyType staticTextMessageID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:StaticTextMessage" ) ); + NameKeyType staticTextMessageID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:StaticTextMessage" ); GameWindow *staticTextMessage = TheWindowManager->winGetWindowFromId(parent, staticTextMessageID); GadgetStaticTextSetText(staticTextMessage,bodyString); @@ -261,10 +261,10 @@ WindowMsgHandledType ExtendedMessageBoxSystem( GameWindow *window, UnsignedInt m { GameWindow *control = (GameWindow *)mData1; Int controlID = control->winGetWindowId(); - static NameKeyType buttonOkID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonOk" ) ); - static NameKeyType buttonYesID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonYes" ) ); - static NameKeyType buttonNoID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonNo" ) ); - static NameKeyType buttonCancelID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonCancel" ) ); + static NameKeyType buttonOkID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonOk" ); + static NameKeyType buttonYesID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonYes" ); + static NameKeyType buttonNoID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonNo" ); + static NameKeyType buttonCancelID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonCancel" ); WindowExMessageBoxData *MsgBoxCallbacks = (WindowExMessageBoxData *)window->winGetUserData(); MessageBoxReturnType ret = MB_RETURN_CLOSE; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/InGameChat.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/InGameChat.cpp index f462512cdf..09336b1417 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/InGameChat.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/InGameChat.cpp @@ -76,7 +76,7 @@ void ShowInGameChat( Bool immediate ) } else { - chatWindow = TheWindowManager->winCreateFromScript( AsciiString("InGameChat.wnd") ); + chatWindow = TheWindowManager->winCreateFromScript( "InGameChat.wnd" ); static NameKeyType textEntryChatID = TheNameKeyGenerator->nameToKey( "InGameChat.wnd:TextEntryChat" ); chatTextEntry = TheWindowManager->winGetWindowFromId( NULL, textEntryChatID ); @@ -338,7 +338,7 @@ WindowMsgHandledType InGameChatSystem( GameWindow *window, UnsignedInt msg, case GBM_SELECTED: { GameWindow *control = (GameWindow *)mData1; - static NameKeyType buttonClearID = TheNameKeyGenerator->nameToKey( AsciiString( "InGameChat.wnd:ButtonClear" ) ); + static NameKeyType buttonClearID = TheNameKeyGenerator->nameToKey( "InGameChat.wnd:ButtonClear" ); if (control && control->winGetWindowId() == buttonClearID) { if (chatTextEntry) diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/InGamePopupMessage.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/InGamePopupMessage.cpp index 83f4d87aac..25726ad39c 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/InGamePopupMessage.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/InGamePopupMessage.cpp @@ -89,12 +89,12 @@ static Bool pause = FALSE; void InGamePopupMessageInit( WindowLayout *layout, void *userData ) { - parentID = TheNameKeyGenerator->nameToKey(AsciiString("InGamePopupMessage.wnd:InGamePopupMessageParent")); + parentID = TheNameKeyGenerator->nameToKey("InGamePopupMessage.wnd:InGamePopupMessageParent"); parent = TheWindowManager->winGetWindowFromId(NULL, parentID); - staticTextMessageID = TheNameKeyGenerator->nameToKey(AsciiString("InGamePopupMessage.wnd:StaticTextMessage")); + staticTextMessageID = TheNameKeyGenerator->nameToKey("InGamePopupMessage.wnd:StaticTextMessage"); staticTextMessage = TheWindowManager->winGetWindowFromId(parent, staticTextMessageID); - buttonOkID = TheNameKeyGenerator->nameToKey(AsciiString("InGamePopupMessage.wnd:ButtonOk")); + buttonOkID = TheNameKeyGenerator->nameToKey("InGamePopupMessage.wnd:ButtonOk"); buttonOk = TheWindowManager->winGetWindowFromId(parent, buttonOkID); PopupMessageData *pMData = TheInGameUI->getPopupMessageData(); 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 1824892e77..8a7ca7b216 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ChallengeMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ChallengeMenu.cpp @@ -338,25 +338,25 @@ void ChallengeMenuInit( WindowLayout *layout, void *userData ) TheShell->showShellMap(TRUE); // init window ids and pointers - parentID = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeMenu.wnd:ParentChallengeMenu") ); + parentID = TheNameKeyGenerator->nameToKey( "ChallengeMenu.wnd:ParentChallengeMenu" ); parentMenu = TheWindowManager->winGetWindowFromId( NULL, parentID ); - buttonPlayID = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeMenu.wnd:ButtonPlay") ); + buttonPlayID = TheNameKeyGenerator->nameToKey( "ChallengeMenu.wnd:ButtonPlay" ); buttonPlay = TheWindowManager->winGetWindowFromId( parentMenu, buttonPlayID ); - buttonBackID = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeMenu.wnd:ButtonBack") ); + buttonBackID = TheNameKeyGenerator->nameToKey( "ChallengeMenu.wnd:ButtonBack" ); buttonBack = TheWindowManager->winGetWindowFromId( parentMenu, buttonBackID ); - bioPortraitID = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeMenu.wnd:BioPortrait") ); + bioPortraitID = TheNameKeyGenerator->nameToKey( "ChallengeMenu.wnd:BioPortrait" ); bioPortrait = TheWindowManager->winGetWindowFromId( parentMenu, bioPortraitID ); - bioNameEntryID = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeMenu.wnd:BioNameEntry") ); + bioNameEntryID = TheNameKeyGenerator->nameToKey( "ChallengeMenu.wnd:BioNameEntry" ); bioLine1Entry = TheWindowManager->winGetWindowFromId( parentMenu, bioNameEntryID ); // this window has been repurposed - bioDOBEntryID = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeMenu.wnd:BioDOBEntry") ); + bioDOBEntryID = TheNameKeyGenerator->nameToKey( "ChallengeMenu.wnd:BioDOBEntry" ); bioLine2Entry = TheWindowManager->winGetWindowFromId( parentMenu, bioDOBEntryID ); // this window has been repurposed - bioBirthplaceEntryID = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeMenu.wnd:BioBirthplaceEntry") ); + bioBirthplaceEntryID = TheNameKeyGenerator->nameToKey( "ChallengeMenu.wnd:BioBirthplaceEntry" ); bioLine3Entry = TheWindowManager->winGetWindowFromId( parentMenu, bioBirthplaceEntryID ); // this window has been repurposed - bioStrategyEntryID = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeMenu.wnd:BioStrategyEntry") ); + bioStrategyEntryID = TheNameKeyGenerator->nameToKey( "ChallengeMenu.wnd:BioStrategyEntry" ); bioLine4Entry = TheWindowManager->winGetWindowFromId( parentMenu, bioStrategyEntryID ); // this window has been repurposed - backdropID = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeMenu.wnd:MainBackdrop") ); + backdropID = TheNameKeyGenerator->nameToKey( "ChallengeMenu.wnd:MainBackdrop" ); backdrop = TheWindowManager->winGetWindowFromId( parentMenu, backdropID); - bioParentID = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeMenu.wnd:GeneralsBioParent") ); + bioParentID = TheNameKeyGenerator->nameToKey( "ChallengeMenu.wnd:GeneralsBioParent" ); bioParent = TheWindowManager->winGetWindowFromId( parentMenu, bioParentID); AsciiString strButtonName; 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 f4b4fa23e6..3a0087ded9 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/CreditsMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/CreditsMenu.cpp @@ -86,7 +86,7 @@ void CreditsMenuInit( WindowLayout *layout, void *userData ) TheCredits->load(); TheCredits->init(); - parentMainMenuID = TheNameKeyGenerator->nameToKey( AsciiString("CreditsMenu.wnd:ParentCreditsWindow") ); + parentMainMenuID = TheNameKeyGenerator->nameToKey( "CreditsMenu.wnd:ParentCreditsWindow" ); parentMainMenu = TheWindowManager->winGetWindowFromId( NULL, parentMainMenuID ); @@ -99,7 +99,7 @@ void CreditsMenuInit( WindowLayout *layout, void *userData ) TheAudio->removeAudioEvent( AHSV_StopTheMusicFade ); - AudioEventRTS event( AsciiString( "Credits" ) ); + AudioEventRTS event( "Credits" ); event.setShouldFade( TRUE ); TheAudio->addAudioEvent( &event ); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DifficultySelect.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DifficultySelect.cpp index ea9a364109..ae20452c8e 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DifficultySelect.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DifficultySelect.cpp @@ -133,11 +133,11 @@ void DifficultySelectInit( WindowLayout *layout, void *userData ) buttonOk = TheWindowManager->winGetWindowFromId( parent, buttonOkID ); buttonCancelID = TheNameKeyGenerator->nameToKey( "DifficultySelect.wnd:ButtonCancel" ); buttonCancel = TheWindowManager->winGetWindowFromId( parent, buttonCancelID ); - radioButtonEasyAIID = TheNameKeyGenerator->nameToKey( AsciiString("DifficultySelect.wnd:RadioButtonEasy") ); + radioButtonEasyAIID = TheNameKeyGenerator->nameToKey( "DifficultySelect.wnd:RadioButtonEasy" ); radioButtonEasyAI = TheWindowManager->winGetWindowFromId( parent, radioButtonEasyAIID ); - radioButtonMediumAIID = TheNameKeyGenerator->nameToKey( AsciiString("DifficultySelect.wnd:RadioButtonMedium") ); + radioButtonMediumAIID = TheNameKeyGenerator->nameToKey( "DifficultySelect.wnd:RadioButtonMedium" ); radioButtonMediumAI = TheWindowManager->winGetWindowFromId( parent, radioButtonMediumAIID ); - radioButtonHardAIID = TheNameKeyGenerator->nameToKey( AsciiString("DifficultySelect.wnd:RadioButtonHard") ); + radioButtonHardAIID = TheNameKeyGenerator->nameToKey( "DifficultySelect.wnd:RadioButtonHard" ); radioButtonHardAI = TheWindowManager->winGetWindowFromId( parent, radioButtonHardAIID ); s_AIDiff = DIFFICULTY_NORMAL; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DisconnectWindow.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DisconnectWindow.cpp index 15b3aa1c45..c0b7f7097c 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DisconnectWindow.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DisconnectWindow.cpp @@ -69,8 +69,8 @@ static GameWindow *buttonVotePlayer6Window = NULL; static GameWindow *buttonVotePlayer7Window = NULL; static void InitDisconnectWindow( void ) { - textEntryID = TheNameKeyGenerator->nameToKey( AsciiString("DisconnectScreen.wnd:TextEntry")); - textDisplayID = TheNameKeyGenerator->nameToKey( AsciiString("DisconnectScreen.wnd:ListboxTextDisplay")); + textEntryID = TheNameKeyGenerator->nameToKey( "DisconnectScreen.wnd:TextEntry"); + textDisplayID = TheNameKeyGenerator->nameToKey( "DisconnectScreen.wnd:ListboxTextDisplay"); textEntryWindow = TheWindowManager->winGetWindowFromId(NULL, textEntryID); textDisplayWindow = TheWindowManager->winGetWindowFromId(NULL, textDisplayID); @@ -80,16 +80,16 @@ static void InitDisconnectWindow( void ) { TheWindowManager->winSetFocus(textEntryWindow); } - buttonQuitID = TheNameKeyGenerator->nameToKey( AsciiString("DisconnectScreen.wnd:ButtonQuitGame")); + buttonQuitID = TheNameKeyGenerator->nameToKey( "DisconnectScreen.wnd:ButtonQuitGame"); buttonQuitWindow = TheWindowManager->winGetWindowFromId(NULL, buttonQuitID); - buttonVotePlayer1ID = TheNameKeyGenerator->nameToKey( AsciiString("DisconnectScreen.wnd:ButtonKickPlayer1")); - buttonVotePlayer2ID = TheNameKeyGenerator->nameToKey( AsciiString("DisconnectScreen.wnd:ButtonKickPlayer2")); - buttonVotePlayer3ID = TheNameKeyGenerator->nameToKey( AsciiString("DisconnectScreen.wnd:ButtonKickPlayer3")); - buttonVotePlayer4ID = TheNameKeyGenerator->nameToKey( AsciiString("DisconnectScreen.wnd:ButtonKickPlayer4")); - buttonVotePlayer5ID = TheNameKeyGenerator->nameToKey( AsciiString("DisconnectScreen.wnd:ButtonKickPlayer5")); - buttonVotePlayer6ID = TheNameKeyGenerator->nameToKey( AsciiString("DisconnectScreen.wnd:ButtonKickPlayer6")); - buttonVotePlayer7ID = TheNameKeyGenerator->nameToKey( AsciiString("DisconnectScreen.wnd:ButtonKickPlayer7")); + buttonVotePlayer1ID = TheNameKeyGenerator->nameToKey( "DisconnectScreen.wnd:ButtonKickPlayer1"); + buttonVotePlayer2ID = TheNameKeyGenerator->nameToKey( "DisconnectScreen.wnd:ButtonKickPlayer2"); + buttonVotePlayer3ID = TheNameKeyGenerator->nameToKey( "DisconnectScreen.wnd:ButtonKickPlayer3"); + buttonVotePlayer4ID = TheNameKeyGenerator->nameToKey( "DisconnectScreen.wnd:ButtonKickPlayer4"); + buttonVotePlayer5ID = TheNameKeyGenerator->nameToKey( "DisconnectScreen.wnd:ButtonKickPlayer5"); + buttonVotePlayer6ID = TheNameKeyGenerator->nameToKey( "DisconnectScreen.wnd:ButtonKickPlayer6"); + buttonVotePlayer7ID = TheNameKeyGenerator->nameToKey( "DisconnectScreen.wnd:ButtonKickPlayer7"); buttonVotePlayer1Window = TheWindowManager->winGetWindowFromId(NULL, buttonVotePlayer1ID); buttonVotePlayer2Window = TheWindowManager->winGetWindowFromId(NULL, buttonVotePlayer2ID); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/EstablishConnectionsWindow.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/EstablishConnectionsWindow.cpp index ab8214c2ca..c3c10fa3f6 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/EstablishConnectionsWindow.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/EstablishConnectionsWindow.cpp @@ -126,7 +126,7 @@ static void showGameSpyQMUnderlyingGUIElements( Bool show ) } static void InitEstablishConnectionsDialog( void ) { - buttonQuitID = TheNameKeyGenerator->nameToKey( AsciiString("EstablishConnectionsScreen.wnd:ButtonQuit") ); + buttonQuitID = TheNameKeyGenerator->nameToKey( "EstablishConnectionsScreen.wnd:ButtonQuit" ); buttonQuitWindow = TheWindowManager->winGetWindowFromId(NULL, buttonQuitID); } 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 5f904f5ed9..3286091c8e 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/GameInfoWindow.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/GameInfoWindow.cpp @@ -67,7 +67,7 @@ static WindowLayout *gameInfoWindowLayout = NULL; void CreateLANGameInfoWindow( GameWindow *sizeAndPosWin ) { if( !gameInfoWindowLayout ) - gameInfoWindowLayout = TheWindowManager->winCreateLayout( AsciiString( "Menus/GameInfoWindow.wnd" ) ); + gameInfoWindowLayout = TheWindowManager->winCreateLayout( "Menus/GameInfoWindow.wnd" ); gameInfoWindowLayout->runInit(); gameInfoWindowLayout->bringForward(); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/KeyboardOptionsMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/KeyboardOptionsMenu.cpp index 4d03d0836f..9468c4500f 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/KeyboardOptionsMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/KeyboardOptionsMenu.cpp @@ -395,7 +395,7 @@ void KeyboardOptionsMenuInit( WindowLayout *layout, void *userData ) parentKeyboardOptionsMenu = TheWindowManager->winGetWindowFromId( NULL, parentKeyboardOptionsMenuID ); // get ids for our children controls - buttonBackID = TheNameKeyGenerator->nameToKey( AsciiString("KeyboardOptionsMenu.wnd:ButtonBack") ); + buttonBackID = TheNameKeyGenerator->nameToKey( "KeyboardOptionsMenu.wnd:ButtonBack" ); buttonBack = TheWindowManager->winGetWindowFromId( parentKeyboardOptionsMenu, buttonBackID ); comboBoxCategoryListID = TheNameKeyGenerator->nameToKey( "KeyboardOptionsMenu.wnd:ComboBoxCategoryList" ); 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 62050e0c39..45f5039eae 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp @@ -678,17 +678,17 @@ void lanUpdateSlotList( void ) void InitLanGameGadgets( void ) { //Initialize the gadget IDs - parentLanGameOptionsID = TheNameKeyGenerator->nameToKey( AsciiString( "LanGameOptionsMenu.wnd:LanGameOptionsMenuParent" ) ); - buttonBackID = TheNameKeyGenerator->nameToKey( AsciiString( "LanGameOptionsMenu.wnd:ButtonBack" ) ); - buttonStartID = TheNameKeyGenerator->nameToKey( AsciiString( "LanGameOptionsMenu.wnd:ButtonStart" ) ); - textEntryChatID = TheNameKeyGenerator->nameToKey( AsciiString( "LanGameOptionsMenu.wnd:TextEntryChat" ) ); - textEntryMapDisplayID = TheNameKeyGenerator->nameToKey( AsciiString( "LanGameOptionsMenu.wnd:TextEntryMapDisplay" ) ); - listboxChatWindowLanGameID = TheNameKeyGenerator->nameToKey( AsciiString( "LanGameOptionsMenu.wnd:ListboxChatWindowLanGame" ) ); - buttonEmoteID = TheNameKeyGenerator->nameToKey( AsciiString( "LanGameOptionsMenu.wnd:ButtonEmote" ) ); - buttonSelectMapID = TheNameKeyGenerator->nameToKey( AsciiString( "LanGameOptionsMenu.wnd:ButtonSelectMap" ) ); - checkboxLimitSuperweaponsID = TheNameKeyGenerator->nameToKey( AsciiString( "LanGameOptionsMenu.wnd:CheckboxLimitSuperweapons" ) ); - comboBoxStartingCashID = TheNameKeyGenerator->nameToKey( AsciiString( "LanGameOptionsMenu.wnd:ComboBoxStartingCash" ) ); - windowMapID = TheNameKeyGenerator->nameToKey( AsciiString( "LanGameOptionsMenu.wnd:MapWindow" ) ); + parentLanGameOptionsID = TheNameKeyGenerator->nameToKey( "LanGameOptionsMenu.wnd:LanGameOptionsMenuParent" ); + buttonBackID = TheNameKeyGenerator->nameToKey( "LanGameOptionsMenu.wnd:ButtonBack" ); + buttonStartID = TheNameKeyGenerator->nameToKey( "LanGameOptionsMenu.wnd:ButtonStart" ); + textEntryChatID = TheNameKeyGenerator->nameToKey( "LanGameOptionsMenu.wnd:TextEntryChat" ); + textEntryMapDisplayID = TheNameKeyGenerator->nameToKey( "LanGameOptionsMenu.wnd:TextEntryMapDisplay" ); + listboxChatWindowLanGameID = TheNameKeyGenerator->nameToKey( "LanGameOptionsMenu.wnd:ListboxChatWindowLanGame" ); + buttonEmoteID = TheNameKeyGenerator->nameToKey( "LanGameOptionsMenu.wnd:ButtonEmote" ); + buttonSelectMapID = TheNameKeyGenerator->nameToKey( "LanGameOptionsMenu.wnd:ButtonSelectMap" ); + checkboxLimitSuperweaponsID = TheNameKeyGenerator->nameToKey( "LanGameOptionsMenu.wnd:CheckboxLimitSuperweapons" ); + comboBoxStartingCashID = TheNameKeyGenerator->nameToKey( "LanGameOptionsMenu.wnd:ComboBoxStartingCash" ); + windowMapID = TheNameKeyGenerator->nameToKey( "LanGameOptionsMenu.wnd:MapWindow" ); // Initialize the pointers to our gadgets parentLanGameOptions = TheWindowManager->winGetWindowFromId( NULL, parentLanGameOptionsID ); @@ -1262,7 +1262,7 @@ WindowMsgHandledType LanGameOptionsMenuSystem( GameWindow *window, UnsignedInt m { //buttonBack->winEnable( false ); - mapSelectLayout = TheWindowManager->winCreateLayout( AsciiString( "Menus/LanMapSelectMenu.wnd" ) ); + mapSelectLayout = TheWindowManager->winCreateLayout( "Menus/LanMapSelectMenu.wnd" ); mapSelectLayout->runInit(); mapSelectLayout->hide( FALSE ); mapSelectLayout->bringForward(); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp index 17d5fcd1ef..e1bd2a9e42 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp @@ -367,20 +367,20 @@ void LanLobbyMenuInit( WindowLayout *layout, void *userData ) LANisShuttingDown = false; // get the ids for our controls - parentLanLobbyID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:LanLobbyMenuParent" ) ); - buttonBackID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:ButtonBack" ) ); - buttonClearID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:ButtonClear" ) ); - buttonHostID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:ButtonHost" ) ); - buttonJoinID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:ButtonJoin" ) ); - buttonDirectConnectID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:ButtonDirectConnect" ) ); - buttonEmoteID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:ButtonEmote" ) ); - staticToolTipID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:StaticToolTip" ) ); - textEntryPlayerNameID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:TextEntryPlayerName" ) ); - textEntryChatID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:TextEntryChat" ) ); - listboxPlayersID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:ListboxPlayers" ) ); - listboxChatWindowID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:ListboxChatWindowLanLobby" ) ); - listboxGamesID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:ListboxGames" ) ); - staticTextGameInfoID = TheNameKeyGenerator->nameToKey( AsciiString( "LanLobbyMenu.wnd:StaticTextGameInfo" ) ); + parentLanLobbyID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:LanLobbyMenuParent" ); + buttonBackID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:ButtonBack" ); + buttonClearID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:ButtonClear" ); + buttonHostID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:ButtonHost" ); + buttonJoinID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:ButtonJoin" ); + buttonDirectConnectID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:ButtonDirectConnect" ); + buttonEmoteID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:ButtonEmote" ); + staticToolTipID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:StaticToolTip" ); + textEntryPlayerNameID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:TextEntryPlayerName" ); + textEntryChatID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:TextEntryChat" ); + listboxPlayersID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:ListboxPlayers" ); + listboxChatWindowID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:ListboxChatWindowLanLobby" ); + listboxGamesID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:ListboxGames" ); + staticTextGameInfoID = TheNameKeyGenerator->nameToKey( "LanLobbyMenu.wnd:StaticTextGameInfo" ); // Get pointers to the window buttons @@ -786,7 +786,7 @@ WindowMsgHandledType LanLobbyMenuSystem( GameWindow *window, UnsignedInt msg, else if ( controlID == buttonJoinID ) { - //TheShell->push( AsciiString("Menus/LanGameOptionsMenu.wnd") ); + //TheShell->push( "Menus/LanGameOptionsMenu.wnd" ); int rowSelected = -1; GadgetListBoxGetSelected( listboxGames, &rowSelected ); @@ -822,7 +822,7 @@ WindowMsgHandledType LanLobbyMenuSystem( GameWindow *window, UnsignedInt msg, else if (controlID == buttonDirectConnectID) { TheLAN->RequestLobbyLeave( false ); - TheShell->push(AsciiString("Menus/NetworkDirectConnect.wnd")); + TheShell->push("Menus/NetworkDirectConnect.wnd"); } break; 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 fe7af25507..537352824c 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanMapSelectMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanMapSelectMenu.cpp @@ -138,10 +138,10 @@ void LanMapSelectMenuInit( WindowLayout *layout, void *userData ) } - buttonBack = TheNameKeyGenerator->nameToKey( AsciiString("LanMapSelectMenu.wnd:ButtonBack") ); - buttonOK = TheNameKeyGenerator->nameToKey( AsciiString("LanMapSelectMenu.wnd:ButtonOK") ); - listboxMap = TheNameKeyGenerator->nameToKey( AsciiString("LanMapSelectMenu.wnd:ListboxMap") ); - winMapPreviewID = TheNameKeyGenerator->nameToKey( AsciiString("LanMapSelectMenu.wnd:WinMapPreview") ); + buttonBack = TheNameKeyGenerator->nameToKey( "LanMapSelectMenu.wnd:ButtonBack" ); + buttonOK = TheNameKeyGenerator->nameToKey( "LanMapSelectMenu.wnd:ButtonOK" ); + listboxMap = TheNameKeyGenerator->nameToKey( "LanMapSelectMenu.wnd:ListboxMap" ); + winMapPreviewID = TheNameKeyGenerator->nameToKey( "LanMapSelectMenu.wnd:WinMapPreview" ); radioButtonSystemMapsID = TheNameKeyGenerator->nameToKey( "LanMapSelectMenu.wnd:RadioButtonSystemMaps" ); radioButtonUserMapsID = TheNameKeyGenerator->nameToKey( "LanMapSelectMenu.wnd:RadioButtonUserMaps" ); 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 da3359cc1c..b52054d4e5 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp @@ -279,7 +279,7 @@ void setupGameStart(AsciiString mapName, GameDifficulty diff) TheChallengeGenerals->setCurrentDifficulty(diff); campaignSelected = TRUE; - TheShell->push( AsciiString("Menus/ChallengeMenu.wnd") ); + TheShell->push( "Menus/ChallengeMenu.wnd" ); TheTransitionHandler->reverse("MainMenuDifficultyMenuTraining"); } else @@ -447,7 +447,7 @@ GameWindow *win = NULL; // Originally this label does not exist in the Main Menu. It can be copied from the Options Menu. static void initLabelVersion() { - NameKeyType versionID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:LabelVersion") ); + NameKeyType versionID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:LabelVersion" ); GameWindow *labelVersion = TheWindowManager->winGetWindowFromId( NULL, versionID ); if (labelVersion) @@ -484,41 +484,41 @@ void MainMenuInit( WindowLayout *layout, void *userData ) dropDownWindows[i] = NULL; // get ids for our windows - mainMenuID = TheNameKeyGenerator->nameToKey( AsciiString( "MainMenu.wnd:MainMenuParent" ) ); -// campaignID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonCampaign") ); - skirmishID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonSkirmish") ); - onlineID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonOnline") ); - networkID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonNetwork") ); - optionsID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonOptions") ); - exitID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonExit") ); - motdID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonMOTD") ); - worldBuilderID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonWorldBuilder") ); - getUpdateID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonGetUpdate") ); -// buttonTRAININGID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonTRAINING") ); - buttonChallengeID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonChallenge") ); - buttonUSAID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonUSA") ); - buttonGLAID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonGLA") ); - buttonChinaID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonChina") ); - buttonUSARecentSaveID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonUSARecentSave") ); - buttonUSALoadGameID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonUSALoadGame") ); - buttonGLARecentSaveID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonGLARecentSave") ); - buttonGLALoadGameID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonGLALoadGame") ); - buttonChinaRecentSaveID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonChinaRecentSave") ); - buttonChinaLoadGameID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonChinaLoadGame") ); - buttonSinglePlayerID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonSinglePlayer") ); - buttonMultiPlayerID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonMultiplayer") ); - buttonMultiBackID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonMultiBack") ); - buttonSingleBackID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonSingleBack") ); - buttonLoadReplayBackID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonLoadReplayBack") ); - buttonReplayID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonReplay") ); - buttonLoadReplayID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonLoadReplay") ); - buttonLoadID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonLoadGame") ); - buttonCreditsID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonCredits") ); - - buttonEasyID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonEasy") ); - buttonMediumID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonMedium") ); - buttonHardID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonHard") ); - buttonDiffBackID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonDiffBack") ); + mainMenuID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:MainMenuParent" ); +// campaignID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonCampaign" ); + skirmishID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonSkirmish" ); + onlineID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonOnline" ); + networkID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonNetwork" ); + optionsID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonOptions" ); + exitID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonExit" ); + motdID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonMOTD" ); + worldBuilderID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonWorldBuilder" ); + getUpdateID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonGetUpdate" ); +// buttonTRAININGID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonTRAINING" ); + buttonChallengeID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonChallenge" ); + buttonUSAID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonUSA" ); + buttonGLAID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonGLA" ); + buttonChinaID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonChina" ); + buttonUSARecentSaveID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonUSARecentSave" ); + buttonUSALoadGameID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonUSALoadGame" ); + buttonGLARecentSaveID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonGLARecentSave" ); + buttonGLALoadGameID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonGLALoadGame" ); + buttonChinaRecentSaveID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonChinaRecentSave" ); + buttonChinaLoadGameID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonChinaLoadGame" ); + buttonSinglePlayerID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonSinglePlayer" ); + buttonMultiPlayerID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonMultiplayer" ); + buttonMultiBackID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonMultiBack" ); + buttonSingleBackID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonSingleBack" ); + buttonLoadReplayBackID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonLoadReplayBack" ); + buttonReplayID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonReplay" ); + buttonLoadReplayID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonLoadReplay" ); + buttonLoadID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonLoadGame" ); + buttonCreditsID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonCredits" ); + + buttonEasyID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonEasy" ); + buttonMediumID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonMedium" ); + buttonHardID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonHard" ); + buttonDiffBackID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonDiffBack" ); // get pointers to the window buttons parentMainMenu = TheWindowManager->winGetWindowFromId( NULL, mainMenuID ); @@ -555,11 +555,11 @@ void MainMenuInit( WindowLayout *layout, void *userData ) buttonChinaRecentSave = TheWindowManager->winGetWindowFromId( parentMainMenu, buttonChinaRecentSaveID ); buttonChinaLoadGame = TheWindowManager->winGetWindowFromId( parentMainMenu, buttonChinaLoadGameID ); - dropDownWindows[DROPDOWN_SINGLE] = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:MapBorder") )); - dropDownWindows[DROPDOWN_MULTIPLAYER] = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:MapBorder1") ) ); - dropDownWindows[DROPDOWN_MAIN] = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:MapBorder2") ) ); - dropDownWindows[DROPDOWN_LOADREPLAY] = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:MapBorder3") ) ); - dropDownWindows[DROPDOWN_DIFFICULTY] = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:MapBorder4") ) ); + dropDownWindows[DROPDOWN_SINGLE] = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( "MainMenu.wnd:MapBorder" )); + dropDownWindows[DROPDOWN_MULTIPLAYER] = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( "MainMenu.wnd:MapBorder1" ) ); + dropDownWindows[DROPDOWN_MAIN] = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( "MainMenu.wnd:MapBorder2" ) ); + dropDownWindows[DROPDOWN_LOADREPLAY] = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( "MainMenu.wnd:MapBorder3" ) ); + dropDownWindows[DROPDOWN_DIFFICULTY] = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( "MainMenu.wnd:MapBorder4" ) ); for(i = 1; i < DROPDOWN_COUNT; ++i) dropDownWindows[i]->winHide(TRUE); @@ -650,7 +650,7 @@ void MainMenuInit( WindowLayout *layout, void *userData ) //pendingDropDown =DROPDOWN_MAIN; - GameWindow *rule = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:MainMenuRuler") ) ); + GameWindow *rule = TheWindowManager->winGetWindowFromId( parentMainMenu, TheNameKeyGenerator->nameToKey( "MainMenu.wnd:MainMenuRuler" ) ); if(rule) rule->winHide(TRUE); campaignSelected = FALSE; @@ -1307,7 +1307,7 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, if( control == buttonCampaign ) { buttonPushed = TRUE; - TheShell->push(AsciiString( "Menus/MapSelectMenu.wnd" )); + TheShell->push("Menus/MapSelectMenu.wnd"); // As soon as we have a campaign, add it in here!; } #ifdef TEST_COMPRESSION @@ -1423,7 +1423,7 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, buttonPushed = TRUE; dropDownWindows[DROPDOWN_LOADREPLAY]->winHide(FALSE); TheTransitionHandler->reverse("MainMenuLoadReplayMenuBackTransition"); - TheShell->push(AsciiString("Menus/SaveLoad.wnd")); + TheShell->push("Menus/SaveLoad.wnd"); } else if( controlID == buttonReplayID ) @@ -1434,7 +1434,7 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, buttonPushed = TRUE; dropDownWindows[DROPDOWN_LOADREPLAY]->winHide(FALSE); TheTransitionHandler->reverse("MainMenuLoadReplayMenuBackTransition"); - TheShell->push(AsciiString("Menus/ReplayMenu.wnd")); + TheShell->push("Menus/ReplayMenu.wnd"); } else if( controlID == skirmishID ) { @@ -1457,7 +1457,7 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, checkCDBeforeCampaign(DIFFICULTY_NORMAL); break; #endif - TheShell->push( AsciiString("Menus/SkirmishGameOptionsMenu.wnd") ); + TheShell->push( "Menus/SkirmishGameOptionsMenu.wnd" ); TheScriptEngine->signalUIInteract(TheShellHookNames[SHELL_SCRIPT_HOOK_MAIN_MENU_SKIRMISH_SELECTED]); } else if( controlID == onlineID ) @@ -1482,7 +1482,7 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, buttonPushed = TRUE; dropDownWindows[DROPDOWN_MULTIPLAYER]->winHide(FALSE); TheTransitionHandler->reverse("MainMenuMultiPlayerMenuTransitionToNext"); - TheShell->push( AsciiString("Menus/LanLobbyMenu.wnd") ); + TheShell->push( "Menus/LanLobbyMenu.wnd" ); TheScriptEngine->signalUIInteract(TheShellHookNames[SHELL_SCRIPT_HOOK_MAIN_MENU_NETWORK_SELECTED]); } @@ -1594,7 +1594,7 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, showSide = SHOW_USA; // launchChallengeMenu = FALSE; // WindowLayout *layout = NULL; -// layout = TheWindowManager->winCreateLayout( AsciiString( "Menus/DifficultySelect.wnd" ) ); +// layout = TheWindowManager->winCreateLayout( "Menus/DifficultySelect.wnd" ); // layout->runInit(); // layout->hide( FALSE ); // layout->bringForward(); @@ -1622,7 +1622,7 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, showSide = SHOW_GLA; // launchChallengeMenu = FALSE; // WindowLayout *layout = NULL; -// layout = TheWindowManager->winCreateLayout( AsciiString( "Menus/DifficultySelect.wnd" ) ); +// layout = TheWindowManager->winCreateLayout( "Menus/DifficultySelect.wnd" ); // layout->runInit(); // layout->hide( FALSE ); // layout->bringForward(); @@ -1650,7 +1650,7 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, showSide = SHOW_CHINA; // launchChallengeMenu = FALSE; // WindowLayout *layout = NULL; -// layout = TheWindowManager->winCreateLayout( AsciiString( "Menus/DifficultySelect.wnd" ) ); +// layout = TheWindowManager->winCreateLayout( "Menus/DifficultySelect.wnd" ); // layout->runInit(); // layout->hide( FALSE ); // layout->bringForward(); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MapSelectMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MapSelectMenu.cpp index b5884867b1..ca0cf4fe1f 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MapSelectMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MapSelectMenu.cpp @@ -122,7 +122,7 @@ void SetDifficultyRadioButton( void ) { case DIFFICULTY_EASY: { - NameKeyType radioButtonEasyAIID = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:RadioButtonEasyAI") ); + NameKeyType radioButtonEasyAIID = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:RadioButtonEasyAI" ); GameWindow *radioButtonEasyAI = TheWindowManager->winGetWindowFromId( parent, radioButtonEasyAIID ); GadgetRadioSetSelection(radioButtonEasyAI, FALSE); s_AIDiff = DIFFICULTY_EASY; @@ -130,7 +130,7 @@ void SetDifficultyRadioButton( void ) } case DIFFICULTY_NORMAL: { - NameKeyType radioButtonMediumAIID = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:RadioButtonMediumAI") ); + NameKeyType radioButtonMediumAIID = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:RadioButtonMediumAI" ); GameWindow *radioButtonMediumAI = TheWindowManager->winGetWindowFromId( parent, radioButtonMediumAIID ); GadgetRadioSetSelection(radioButtonMediumAI, FALSE); s_AIDiff = DIFFICULTY_NORMAL; @@ -138,7 +138,7 @@ void SetDifficultyRadioButton( void ) } case DIFFICULTY_HARD: { - NameKeyType radioButtonHardAIID = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:RadioButtonHardAI") ); + NameKeyType radioButtonHardAIID = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:RadioButtonHardAI" ); GameWindow *radioButtonHardAI = TheWindowManager->winGetWindowFromId( parent, radioButtonHardAIID ); GadgetRadioSetSelection(radioButtonHardAI, FALSE); s_AIDiff = DIFFICULTY_HARD; @@ -188,10 +188,10 @@ void MapSelectMenuInit( WindowLayout *layout, void *userData ) GameWindow *parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); TheWindowManager->winSetFocus( parent ); - NameKeyType buttonBackID = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:ButtonBack") ); + NameKeyType buttonBackID = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:ButtonBack" ); GameWindow *buttonBack = TheWindowManager->winGetWindowFromId( NULL, buttonBackID ); - NameKeyType buttonOKID = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:ButtonOK") ); + NameKeyType buttonOKID = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:ButtonOK" ); GameWindow *buttonOK = TheWindowManager->winGetWindowFromId( NULL, buttonOKID ); @@ -324,12 +324,12 @@ WindowMsgHandledType MapSelectMenuSystem( GameWindow *window, UnsignedInt msg, { // get ids for our children controls - buttonBack = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:ButtonBack") ); - buttonOK = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:ButtonOK") ); - listboxMap = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:ListboxMap") ); - radioButtonEasyAI = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:RadioButtonEasyAI") ); - radioButtonMediumAI = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:RadioButtonMediumAI") ); - radioButtonHardAI = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:RadioButtonHardAI") ); + buttonBack = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:ButtonBack" ); + buttonOK = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:ButtonOK" ); + listboxMap = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:ListboxMap" ); + radioButtonEasyAI = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:RadioButtonEasyAI" ); + radioButtonMediumAI = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:RadioButtonMediumAI" ); + radioButtonHardAI = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:RadioButtonHardAI" ); break; } @@ -418,7 +418,7 @@ WindowMsgHandledType MapSelectMenuSystem( GameWindow *window, UnsignedInt msg, buttonPushed = true; // reset the campaign manager to empty if( TheCampaignManager ) - TheCampaignManager->setCampaign( AsciiString( "" ) ); + TheCampaignManager->setCampaign( "" ); // get text of the map to load const char *mapFname = (const char *)GadgetListBoxGetItemData( mapWindow, selected ); DEBUG_ASSERTCRASH(mapFname, ("No map item data")); @@ -457,7 +457,7 @@ WindowMsgHandledType MapSelectMenuSystem( GameWindow *window, UnsignedInt msg, { //buttonPushed = true; GadgetListBoxSetSelected( control, rowSelected ); - NameKeyType buttonOKID = TheNameKeyGenerator->nameToKey( AsciiString("MapSelectMenu.wnd:ButtonOK") ); + NameKeyType buttonOKID = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:ButtonOK" ); GameWindow *buttonOK = TheWindowManager->winGetWindowFromId( NULL, buttonOKID ); TheWindowManager->winSendSystemMsg( window, GBM_SELECTED, 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 1976e21aae..5124c90b45 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp @@ -262,12 +262,12 @@ void NetworkDirectConnectInit( WindowLayout *layout, void *userData ) buttonPushed = false; isShuttingDown = false; TheShell->showShellMap(TRUE); - buttonBackID = TheNameKeyGenerator->nameToKey( AsciiString( "NetworkDirectConnect.wnd:ButtonBack" ) ); - buttonHostID = TheNameKeyGenerator->nameToKey( AsciiString( "NetworkDirectConnect.wnd:ButtonHost" ) ); - buttonJoinID = TheNameKeyGenerator->nameToKey( AsciiString( "NetworkDirectConnect.wnd:ButtonJoin" ) ); - editPlayerNameID = TheNameKeyGenerator->nameToKey( AsciiString( "NetworkDirectConnect.wnd:EditPlayerName" ) ); - comboboxRemoteIPID = TheNameKeyGenerator->nameToKey( AsciiString( "NetworkDirectConnect.wnd:ComboboxRemoteIP" ) ); - staticLocalIPID = TheNameKeyGenerator->nameToKey( AsciiString( "NetworkDirectConnect.wnd:StaticLocalIP" ) ); + buttonBackID = TheNameKeyGenerator->nameToKey( "NetworkDirectConnect.wnd:ButtonBack" ); + buttonHostID = TheNameKeyGenerator->nameToKey( "NetworkDirectConnect.wnd:ButtonHost" ); + buttonJoinID = TheNameKeyGenerator->nameToKey( "NetworkDirectConnect.wnd:ButtonJoin" ); + editPlayerNameID = TheNameKeyGenerator->nameToKey( "NetworkDirectConnect.wnd:EditPlayerName" ); + comboboxRemoteIPID = TheNameKeyGenerator->nameToKey( "NetworkDirectConnect.wnd:ComboboxRemoteIP" ); + staticLocalIPID = TheNameKeyGenerator->nameToKey( "NetworkDirectConnect.wnd:StaticLocalIP" ); buttonBack = TheWindowManager->winGetWindowFromId( NULL, buttonBackID); buttonHost = TheWindowManager->winGetWindowFromId( NULL, buttonHostID); 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 180dad5cfb..660911e951 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp @@ -1195,9 +1195,9 @@ static void saveOptions( void ) { TheWritableGlobalData->m_firewallSendDelay = GadgetCheckBoxIsChecked(checkSendDelay); if (TheGlobalData->m_firewallSendDelay) { - (*pref)["SendDelay"] = AsciiString("yes"); + (*pref)["SendDelay"] = "yes"; } else { - (*pref)["SendDelay"] = AsciiString("no"); + (*pref)["SendDelay"] = "no"; } } @@ -1220,39 +1220,39 @@ static void saveOptions( void ) } TheWritableGlobalData->m_useShadowVolumes = GadgetCheckBoxIsChecked( check3DShadows ); - (*pref)["UseShadowVolumes"] = TheWritableGlobalData->m_useShadowVolumes ? AsciiString("yes") : AsciiString("no"); + (*pref)["UseShadowVolumes"] = TheWritableGlobalData->m_useShadowVolumes ? "yes" : "no"; TheWritableGlobalData->m_useShadowDecals = GadgetCheckBoxIsChecked( check2DShadows ); - (*pref)["UseShadowDecals"] = TheWritableGlobalData->m_useShadowDecals ? AsciiString("yes") : AsciiString("no"); + (*pref)["UseShadowDecals"] = TheWritableGlobalData->m_useShadowDecals ? "yes" : "no"; TheWritableGlobalData->m_useCloudMap = GadgetCheckBoxIsChecked( checkCloudShadows ); - (*pref)["UseCloudMap"] = TheGlobalData->m_useCloudMap ? AsciiString("yes") : AsciiString("no"); + (*pref)["UseCloudMap"] = TheGlobalData->m_useCloudMap ? "yes" : "no"; TheWritableGlobalData->m_useLightMap = GadgetCheckBoxIsChecked( checkGroundLighting ); - (*pref)["UseLightMap"] = TheGlobalData->m_useLightMap ? AsciiString("yes") : AsciiString("no"); + (*pref)["UseLightMap"] = TheGlobalData->m_useLightMap ? "yes" : "no"; TheWritableGlobalData->m_showSoftWaterEdge = GadgetCheckBoxIsChecked( checkSmoothWater ); - (*pref)["ShowSoftWaterEdge"] = TheGlobalData->m_showSoftWaterEdge ? AsciiString("yes") : AsciiString("no"); + (*pref)["ShowSoftWaterEdge"] = TheGlobalData->m_showSoftWaterEdge ? "yes" : "no"; TheWritableGlobalData->m_useDrawModuleLOD = !GadgetCheckBoxIsChecked( checkExtraAnimations ); TheWritableGlobalData->m_useTreeSway = !TheWritableGlobalData->m_useDrawModuleLOD; //borrow same setting. - (*pref)["ExtraAnimations"] = TheGlobalData->m_useDrawModuleLOD ? AsciiString("no") : AsciiString("yes"); + (*pref)["ExtraAnimations"] = TheGlobalData->m_useDrawModuleLOD ? "no" : "yes"; TheWritableGlobalData->m_enableDynamicLOD = !GadgetCheckBoxIsChecked( checkNoDynamicLod ); - (*pref)["DynamicLOD"] = TheGlobalData->m_enableDynamicLOD ? AsciiString("yes") : AsciiString("no"); + (*pref)["DynamicLOD"] = TheGlobalData->m_enableDynamicLOD ? "yes" : "no"; TheWritableGlobalData->m_useHeatEffects = GadgetCheckBoxIsChecked( checkHeatEffects ); - (*pref)["HeatEffects"] = TheGlobalData->m_useHeatEffects ? AsciiString("yes") : AsciiString("no"); + (*pref)["HeatEffects"] = TheGlobalData->m_useHeatEffects ? "yes" : "no"; // Never write this out //TheWritableGlobalData->m_useFpsLimit = !GadgetCheckBoxIsChecked( checkUnlockFps ); - //(*pref)["FPSLimit"] = TheGlobalData->m_useFpsLimit ? AsciiString("yes") : AsciiString("no"); + //(*pref)["FPSLimit"] = TheGlobalData->m_useFpsLimit ? "yes" : "no"; TheWritableGlobalData->m_enableBehindBuildingMarkers = GadgetCheckBoxIsChecked( checkBuildingOcclusion ); - (*pref)["BuildingOcclusion"] = TheWritableGlobalData->m_enableBehindBuildingMarkers ? AsciiString("yes") : AsciiString("no"); + (*pref)["BuildingOcclusion"] = TheWritableGlobalData->m_enableBehindBuildingMarkers ? "yes" : "no"; TheWritableGlobalData->m_useTrees = GadgetCheckBoxIsChecked( checkProps); - (*pref)["ShowTrees"] = TheWritableGlobalData->m_useTrees ? AsciiString("yes") : AsciiString("no"); + (*pref)["ShowTrees"] = TheWritableGlobalData->m_useTrees ? "yes" : "no"; //------------------------------------------------------------------------------------------------- // Particle Cap slider @@ -1349,13 +1349,13 @@ static void saveOptions( void ) //------------------------------------------------------------------------------------------------- // mouse mode TheWritableGlobalData->m_useAlternateMouse = GadgetCheckBoxIsChecked(checkAlternateMouse); - (*pref)["UseAlternateMouse"] = TheWritableGlobalData->m_useAlternateMouse ? AsciiString("yes") : AsciiString("no"); + (*pref)["UseAlternateMouse"] = TheWritableGlobalData->m_useAlternateMouse ? "yes" : "no"; TheWritableGlobalData->m_clientRetaliationModeEnabled = GadgetCheckBoxIsChecked(checkRetaliation); - (*pref)["Retaliation"] = TheWritableGlobalData->m_clientRetaliationModeEnabled? AsciiString("yes") : AsciiString("no"); + (*pref)["Retaliation"] = TheWritableGlobalData->m_clientRetaliationModeEnabled? "yes" : "no"; TheWritableGlobalData->m_doubleClickAttackMove = GadgetCheckBoxIsChecked( checkDoubleClickAttackMove ); - (*pref)["UseDoubleClickAttackMove"] = TheWritableGlobalData->m_doubleClickAttackMove ? AsciiString("yes") : AsciiString("no"); + (*pref)["UseDoubleClickAttackMove"] = TheWritableGlobalData->m_doubleClickAttackMove ? "yes" : "no"; // TheSuperHackers @todo Add combo box ? { @@ -1658,7 +1658,7 @@ static void cancelAdvancedOptions() // TheSuperHackers @tweak Now prints additional version information in the version label. static void initLabelVersion() { - NameKeyType versionID = TheNameKeyGenerator->nameToKey( AsciiString("OptionsMenu.wnd:LabelVersion") ); + NameKeyType versionID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:LabelVersion" ); GameWindow *labelVersion = TheWindowManager->winGetWindowFromId( NULL, versionID ); if (labelVersion) @@ -1691,107 +1691,107 @@ void OptionsMenuInit( WindowLayout *layout, void *userData ) SignalUIInteraction(SHELL_SCRIPT_HOOK_OPTIONS_OPENED); - comboBoxLANIPID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ComboBoxIP" ) ); + comboBoxLANIPID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ComboBoxIP" ); comboBoxLANIP = TheWindowManager->winGetWindowFromId( NULL, comboBoxLANIPID); - comboBoxOnlineIPID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ComboBoxOnlineIP" ) ); + comboBoxOnlineIPID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ComboBoxOnlineIP" ); comboBoxOnlineIP = TheWindowManager->winGetWindowFromId( NULL, comboBoxOnlineIPID); - checkAlternateMouseID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckAlternateMouse" ) ); + checkAlternateMouseID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckAlternateMouse" ); checkAlternateMouse = TheWindowManager->winGetWindowFromId( NULL, checkAlternateMouseID); - checkRetaliationID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:Retaliation" ) ); + checkRetaliationID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:Retaliation" ); checkRetaliation = TheWindowManager->winGetWindowFromId( NULL, checkRetaliationID); - checkDoubleClickAttackMoveID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckDoubleClickAttackMove" ) ); + checkDoubleClickAttackMoveID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckDoubleClickAttackMove" ); checkDoubleClickAttackMove = TheWindowManager->winGetWindowFromId( NULL, checkDoubleClickAttackMoveID ); - sliderScrollSpeedID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:SliderScrollSpeed" ) ); + sliderScrollSpeedID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:SliderScrollSpeed" ); sliderScrollSpeed = TheWindowManager->winGetWindowFromId( NULL, sliderScrollSpeedID); - comboBoxAntiAliasingID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ComboBoxAntiAliasing" ) ); + comboBoxAntiAliasingID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ComboBoxAntiAliasing" ); comboBoxAntiAliasing = TheWindowManager->winGetWindowFromId( NULL, comboBoxAntiAliasingID ); - comboBoxResolutionID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ComboBoxResolution" ) ); + comboBoxResolutionID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ComboBoxResolution" ); comboBoxResolution = TheWindowManager->winGetWindowFromId( NULL, comboBoxResolutionID ); - comboBoxDetailID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ComboBoxDetail" ) ); + comboBoxDetailID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ComboBoxDetail" ); comboBoxDetail = TheWindowManager->winGetWindowFromId( NULL, comboBoxDetailID ); - checkLanguageFilterID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckLanguageFilter" ) ); + checkLanguageFilterID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckLanguageFilter" ); checkLanguageFilter = TheWindowManager->winGetWindowFromId( NULL, checkLanguageFilterID ); - checkSendDelayID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckSendDelay" ) ); + checkSendDelayID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckSendDelay" ); checkSendDelay = TheWindowManager->winGetWindowFromId( NULL, checkSendDelayID); - buttonFirewallRefreshID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ButtonFirewallRefresh" ) ); + buttonFirewallRefreshID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ButtonFirewallRefresh" ); buttonFirewallRefresh = TheWindowManager->winGetWindowFromId( NULL, buttonFirewallRefreshID); - checkDrawAnchorID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckBoxDrawAnchor" ) ); + checkDrawAnchorID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckBoxDrawAnchor" ); checkDrawAnchor = TheWindowManager->winGetWindowFromId( NULL, checkDrawAnchorID); - checkMoveAnchorID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckBoxMoveAnchor" ) ); + checkMoveAnchorID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckBoxMoveAnchor" ); checkMoveAnchor = TheWindowManager->winGetWindowFromId( NULL, checkMoveAnchorID); // Replay camera - checkSaveCameraID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckBoxSaveCamera" ) ); + checkSaveCameraID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckBoxSaveCamera" ); checkSaveCamera = TheWindowManager->winGetWindowFromId( NULL, checkSaveCameraID ); - checkUseCameraID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckBoxUseCamera" ) ); + checkUseCameraID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckBoxUseCamera" ); checkUseCamera = TheWindowManager->winGetWindowFromId( NULL, checkUseCameraID ); // // Speakers and 3-D Audio -// checkAudioSurroundID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckAudioSurround" ) ); +// checkAudioSurroundID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckAudioSurround" ); // checkAudioSurround = TheWindowManager->winGetWindowFromId( NULL, checkAudioSurroundID ); -// checkAudioHardwareID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckAudioHardware" ) ); +// checkAudioHardwareID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckAudioHardware" ); // checkAudioHardware = TheWindowManager->winGetWindowFromId( NULL, checkAudioHardwareID ); // // Volume Controls - sliderMusicVolumeID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:SliderMusicVolume" ) ); + sliderMusicVolumeID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:SliderMusicVolume" ); sliderMusicVolume = TheWindowManager->winGetWindowFromId( NULL, sliderMusicVolumeID ); - sliderSFXVolumeID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:SliderSFXVolume" ) ); + sliderSFXVolumeID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:SliderSFXVolume" ); sliderSFXVolume = TheWindowManager->winGetWindowFromId( NULL, sliderSFXVolumeID ); - sliderVoiceVolumeID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:SliderVoiceVolume" ) ); + sliderVoiceVolumeID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:SliderVoiceVolume" ); sliderVoiceVolume = TheWindowManager->winGetWindowFromId( NULL, sliderVoiceVolumeID ); - sliderGammaID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:SliderGamma" ) ); + sliderGammaID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:SliderGamma" ); sliderGamma = TheWindowManager->winGetWindowFromId( NULL, sliderGammaID ); -// checkBoxLowTextureDetailID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckLowTextureDetail" ) ); +// checkBoxLowTextureDetailID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckLowTextureDetail" ); // checkBoxLowTextureDetail = TheWindowManager->winGetWindowFromId( NULL, checkBoxLowTextureDetailID ); - WinAdvancedDisplayID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:WinAdvancedDisplayOptions" ) ); + WinAdvancedDisplayID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:WinAdvancedDisplayOptions" ); WinAdvancedDisplay = TheWindowManager->winGetWindowFromId( NULL, WinAdvancedDisplayID ); - ButtonAdvancedAcceptID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ButtonAdvanceAccept" ) ); + ButtonAdvancedAcceptID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ButtonAdvanceAccept" ); ButtonAdvancedAccept = TheWindowManager->winGetWindowFromId( NULL, ButtonAdvancedAcceptID ); - ButtonAdvancedCancelID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ButtonAdvanceBack" ) ); + ButtonAdvancedCancelID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ButtonAdvanceBack" ); ButtonAdvancedCancel = TheWindowManager->winGetWindowFromId( NULL, ButtonAdvancedCancelID ); - sliderTextureResolutionID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:LowResSlider" ) ); + sliderTextureResolutionID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:LowResSlider" ); sliderTextureResolution = TheWindowManager->winGetWindowFromId( NULL, sliderTextureResolutionID ); - check3DShadowsID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:Check3DShadows" ) ); + check3DShadowsID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:Check3DShadows" ); check3DShadows = TheWindowManager->winGetWindowFromId( NULL, check3DShadowsID); - check2DShadowsID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:Check2DShadows" ) ); + check2DShadowsID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:Check2DShadows" ); check2DShadows = TheWindowManager->winGetWindowFromId( NULL, check2DShadowsID); - checkCloudShadowsID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckCloudShadows" ) ); + checkCloudShadowsID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckCloudShadows" ); checkCloudShadows = TheWindowManager->winGetWindowFromId( NULL, checkCloudShadowsID); - checkGroundLightingID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckGroundLighting" ) ); + checkGroundLightingID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckGroundLighting" ); checkGroundLighting = TheWindowManager->winGetWindowFromId( NULL, checkGroundLightingID); - checkSmoothWaterID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckSmoothWater" ) ); + checkSmoothWaterID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckSmoothWater" ); checkSmoothWater = TheWindowManager->winGetWindowFromId( NULL, checkSmoothWaterID); - checkExtraAnimationsID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckExtraAnimations" ) ); + checkExtraAnimationsID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckExtraAnimations" ); checkExtraAnimations = TheWindowManager->winGetWindowFromId( NULL, checkExtraAnimationsID); - checkNoDynamicLodID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckNoDynamicLOD" ) ); + checkNoDynamicLodID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckNoDynamicLOD" ); checkNoDynamicLod = TheWindowManager->winGetWindowFromId( NULL, checkNoDynamicLodID); - checkHeatEffectsID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckHeatEffects" ) ); + checkHeatEffectsID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckHeatEffects" ); checkHeatEffects = TheWindowManager->winGetWindowFromId( NULL, checkHeatEffectsID); - checkUnlockFpsID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckUnlockFPS" ) ); + checkUnlockFpsID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckUnlockFPS" ); checkUnlockFps = TheWindowManager->winGetWindowFromId( NULL, checkUnlockFpsID); - checkBuildingOcclusionID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckBehindBuilding" ) ); + checkBuildingOcclusionID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckBehindBuilding" ); checkBuildingOcclusion = TheWindowManager->winGetWindowFromId( NULL, checkBuildingOcclusionID); - checkPropsID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:CheckShowProps" ) ); + checkPropsID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:CheckShowProps" ); checkProps = TheWindowManager->winGetWindowFromId( NULL, checkPropsID); - sliderParticleCapID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ParticleCapSlider" ) ); + sliderParticleCapID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ParticleCapSlider" ); sliderParticleCap = TheWindowManager->winGetWindowFromId( NULL, sliderParticleCapID ); WinAdvancedDisplay->winHide(TRUE); @@ -2268,10 +2268,10 @@ WindowMsgHandledType OptionsMenuSystem( GameWindow *window, UnsignedInt msg, { // get ids for our children controls - buttonBack = TheNameKeyGenerator->nameToKey( AsciiString("OptionsMenu.wnd:ButtonBack") ); - buttonDefaults = TheNameKeyGenerator->nameToKey( AsciiString("OptionsMenu.wnd:ButtonDefaults") ); - buttonAccept = TheNameKeyGenerator->nameToKey( AsciiString("OptionsMenu.wnd:ButtonAccept") ); - buttonKeyboardOptionsMenu = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ButtonKeyboardOptions" ) ); + buttonBack = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ButtonBack" ); + buttonDefaults = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ButtonDefaults" ); + buttonAccept = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ButtonAccept" ); + buttonKeyboardOptionsMenu = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ButtonKeyboardOptions" ); break; @@ -2389,7 +2389,7 @@ WindowMsgHandledType OptionsMenuSystem( GameWindow *window, UnsignedInt msg, } else if ( controlID == buttonKeyboardOptionsMenu ) { - TheShell->push( AsciiString( "Menus/KeyboardOptionsMenu.wnd" ) ); + TheShell->push( "Menus/KeyboardOptionsMenu.wnd" ); } else if(controlID == checkDrawAnchorID ) { diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupCommunicator.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupCommunicator.cpp index 83bf875234..d3b9be11bc 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupCommunicator.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupCommunicator.cpp @@ -69,7 +69,7 @@ void PopupCommunicatorInit( WindowLayout *layout, void *userData ) TheWindowManager->winSetModal( parent ); // get ids for our children controls - buttonOkID = TheNameKeyGenerator->nameToKey( AsciiString("PopupCommunicator.wnd:ButtonOk") ); + buttonOkID = TheNameKeyGenerator->nameToKey( "PopupCommunicator.wnd:ButtonOk" ); buttonOk = TheWindowManager->winGetWindowFromId( parent, buttonOkID ); } 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 ab790df909..76a55a69e9 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupHostGame.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupHostGame.cpp @@ -310,51 +310,51 @@ void PopulateCustomLadderComboBox( void ) //------------------------------------------------------------------------------------------------- void PopupHostGameInit( WindowLayout *layout, void *userData ) { - parentPopupID = TheNameKeyGenerator->nameToKey(AsciiString("PopupHostGame.wnd:ParentHostPopUp")); + parentPopupID = TheNameKeyGenerator->nameToKey("PopupHostGame.wnd:ParentHostPopUp"); parentPopup = TheWindowManager->winGetWindowFromId(NULL, parentPopupID); - textEntryGameNameID = TheNameKeyGenerator->nameToKey(AsciiString("PopupHostGame.wnd:TextEntryGameName")); + textEntryGameNameID = TheNameKeyGenerator->nameToKey("PopupHostGame.wnd:TextEntryGameName"); textEntryGameName = TheWindowManager->winGetWindowFromId(parentPopup, textEntryGameNameID); UnicodeString name; name.translate(TheGameSpyInfo->getLocalName()); GadgetTextEntrySetText(textEntryGameName, name); - textEntryGameDescriptionID = TheNameKeyGenerator->nameToKey(AsciiString("PopupHostGame.wnd:TextEntryGameDescription")); + textEntryGameDescriptionID = TheNameKeyGenerator->nameToKey("PopupHostGame.wnd:TextEntryGameDescription"); textEntryGameDescription = TheWindowManager->winGetWindowFromId(parentPopup, textEntryGameDescriptionID); GadgetTextEntrySetText(textEntryGameDescription, UnicodeString::TheEmptyString); - textEntryLadderPasswordID = TheNameKeyGenerator->nameToKey(AsciiString("PopupHostGame.wnd:TextEntryLadderPassword")); + textEntryLadderPasswordID = TheNameKeyGenerator->nameToKey("PopupHostGame.wnd:TextEntryLadderPassword"); textEntryLadderPassword = TheWindowManager->winGetWindowFromId(parentPopup, textEntryLadderPasswordID); GadgetTextEntrySetText(textEntryLadderPassword, UnicodeString::TheEmptyString); - textEntryGamePasswordID = TheNameKeyGenerator->nameToKey(AsciiString("PopupHostGame.wnd:TextEntryGamePassword")); + textEntryGamePasswordID = TheNameKeyGenerator->nameToKey("PopupHostGame.wnd:TextEntryGamePassword"); textEntryGamePassword = TheWindowManager->winGetWindowFromId(parentPopup, textEntryGamePasswordID); GadgetTextEntrySetText(textEntryGamePassword, UnicodeString::TheEmptyString); - buttonCreateGameID = TheNameKeyGenerator->nameToKey(AsciiString("PopupHostGame.wnd:ButtonCreateGame")); + buttonCreateGameID = TheNameKeyGenerator->nameToKey("PopupHostGame.wnd:ButtonCreateGame"); buttonCreateGame = TheWindowManager->winGetWindowFromId(parentPopup, buttonCreateGameID); - buttonCancelID = TheNameKeyGenerator->nameToKey(AsciiString("PopupHostGame.wnd:ButtonCancel")); + buttonCancelID = TheNameKeyGenerator->nameToKey("PopupHostGame.wnd:ButtonCancel"); buttonCancel = TheWindowManager->winGetWindowFromId(parentPopup, buttonCancelID); - checkBoxAllowObserversID = TheNameKeyGenerator->nameToKey(AsciiString("PopupHostGame.wnd:CheckBoxAllowObservers")); + checkBoxAllowObserversID = TheNameKeyGenerator->nameToKey("PopupHostGame.wnd:CheckBoxAllowObservers"); checkBoxAllowObservers = TheWindowManager->winGetWindowFromId(parentPopup, checkBoxAllowObserversID); CustomMatchPreferences customPref; GadgetCheckBoxSetChecked(checkBoxAllowObservers, customPref.allowsObservers()); - comboBoxLadderNameID = TheNameKeyGenerator->nameToKey(AsciiString("PopupHostGame.wnd:ComboBoxLadderName")); + comboBoxLadderNameID = TheNameKeyGenerator->nameToKey("PopupHostGame.wnd:ComboBoxLadderName"); comboBoxLadderName = TheWindowManager->winGetWindowFromId(parentPopup, comboBoxLadderNameID); if (comboBoxLadderName) GadgetComboBoxReset(comboBoxLadderName); PopulateCustomLadderComboBox(); - checkBoxUseStatsID = TheNameKeyGenerator->nameToKey(AsciiString("PopupHostGame.wnd:CheckBoxUseStats")); + checkBoxUseStatsID = TheNameKeyGenerator->nameToKey("PopupHostGame.wnd:CheckBoxUseStats"); checkBoxUseStats = TheWindowManager->winGetWindowFromId(parentPopup, checkBoxUseStatsID); Bool usingStats = customPref.getUseStats(); GadgetCheckBoxSetChecked( checkBoxUseStats, usingStats ); // limit armies is disallowed in "use stats" games - checkBoxLimitArmiesID = TheNameKeyGenerator->nameToKey(AsciiString("PopupHostGame.wnd:CheckBoxLimitArmies")); + checkBoxLimitArmiesID = TheNameKeyGenerator->nameToKey("PopupHostGame.wnd:CheckBoxLimitArmies"); checkBoxLimitArmies = TheWindowManager->winGetWindowFromId(parentPopup, checkBoxLimitArmiesID); checkBoxLimitArmies->winEnable(! usingStats ); GadgetCheckBoxSetChecked( checkBoxLimitArmies, usingStats? FALSE : customPref.getFactionsLimited() ); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupJoinGame.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupJoinGame.cpp index ca4da664df..efbba30770 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupJoinGame.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupJoinGame.cpp @@ -86,14 +86,14 @@ static void joinGame( AsciiString password ); //------------------------------------------------------------------------------------------------- void PopupJoinGameInit( WindowLayout *layout, void *userData ) { - parentPopupID = TheNameKeyGenerator->nameToKey(AsciiString("PopupJoinGame.wnd:ParentJoinPopUp")); + parentPopupID = TheNameKeyGenerator->nameToKey("PopupJoinGame.wnd:ParentJoinPopUp"); parentPopup = TheWindowManager->winGetWindowFromId(NULL, parentPopupID); - textEntryGamePasswordID = TheNameKeyGenerator->nameToKey(AsciiString("PopupJoinGame.wnd:TextEntryGamePassword")); + textEntryGamePasswordID = TheNameKeyGenerator->nameToKey("PopupJoinGame.wnd:TextEntryGamePassword"); textEntryGamePassword = TheWindowManager->winGetWindowFromId(parentPopup, textEntryGamePasswordID); GadgetTextEntrySetText(textEntryGamePassword, UnicodeString::TheEmptyString); - NameKeyType staticTextGameNameID = TheNameKeyGenerator->nameToKey(AsciiString("PopupJoinGame.wnd:StaticTextGameName")); + NameKeyType staticTextGameNameID = TheNameKeyGenerator->nameToKey("PopupJoinGame.wnd:StaticTextGameName"); GameWindow *staticTextGameName = TheWindowManager->winGetWindowFromId(parentPopup, staticTextGameNameID); GadgetStaticTextSetText(staticTextGameName, UnicodeString::TheEmptyString); 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 ba85bf7c21..72389c9f9f 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupLadderSelect.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupLadderSelect.cpp @@ -648,7 +648,7 @@ WindowMsgHandledType RCGameDetailsMenuSystem( GameWindow *window, UnsignedInt ms const LadderInfo *linfo = TheLadderList->findLadder(theRoom->getLadderIP(), theRoom->getLadderPort()); if (linfo) { - WindowLayout *rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/PopupLadderDetails.wnd")); + WindowLayout *rcLayout = TheWindowManager->winCreateLayout("Menus/PopupLadderDetails.wnd"); if (!rcLayout) break; 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 2458fd2dfe..2bf37bbfa1 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/QuitMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/QuitMenu.cpp @@ -81,11 +81,11 @@ static NameKeyType buttonSaveLoad = NAMEKEY_INVALID; static void initGadgetsFullQuit( void ) { - buttonExit = TheNameKeyGenerator->nameToKey( AsciiString( "QuitMenu.wnd:ButtonExit" ) ); - buttonRestart = TheNameKeyGenerator->nameToKey( AsciiString( "QuitMenu.wnd:ButtonRestart" ) ); - buttonReturn = TheNameKeyGenerator->nameToKey( AsciiString( "QuitMenu.wnd:ButtonReturn" ) ); - buttonOptions = TheNameKeyGenerator->nameToKey( AsciiString( "QuitMenu.wnd:ButtonOptions" ) ); - buttonSaveLoad = TheNameKeyGenerator->nameToKey( AsciiString( "QuitMenu.wnd:ButtonSaveLoad" ) ); + buttonExit = TheNameKeyGenerator->nameToKey( "QuitMenu.wnd:ButtonExit" ); + buttonRestart = TheNameKeyGenerator->nameToKey( "QuitMenu.wnd:ButtonRestart" ); + buttonReturn = TheNameKeyGenerator->nameToKey( "QuitMenu.wnd:ButtonReturn" ); + buttonOptions = TheNameKeyGenerator->nameToKey( "QuitMenu.wnd:ButtonOptions" ); + buttonSaveLoad = TheNameKeyGenerator->nameToKey( "QuitMenu.wnd:ButtonSaveLoad" ); buttonRestartWin = TheWindowManager->winGetWindowFromId( NULL, buttonRestart ); buttonSaveLoadWin = TheWindowManager->winGetWindowFromId( NULL, buttonSaveLoad ); @@ -95,10 +95,10 @@ static void initGadgetsFullQuit( void ) static void initGadgetsNoSaveQuit( void ) { - buttonExit = TheNameKeyGenerator->nameToKey( AsciiString( "QuitNoSave.wnd:ButtonExit" ) ); - buttonRestart = TheNameKeyGenerator->nameToKey( AsciiString( "QuitNoSave.wnd:ButtonRestart" ) ); - buttonReturn = TheNameKeyGenerator->nameToKey( AsciiString( "QuitNoSave.wnd:ButtonReturn" ) ); - buttonOptions = TheNameKeyGenerator->nameToKey( AsciiString( "QuitNoSave.wnd:ButtonOptions" ) ); + buttonExit = TheNameKeyGenerator->nameToKey( "QuitNoSave.wnd:ButtonExit" ); + buttonRestart = TheNameKeyGenerator->nameToKey( "QuitNoSave.wnd:ButtonRestart" ); + buttonReturn = TheNameKeyGenerator->nameToKey( "QuitNoSave.wnd:ButtonReturn" ); + buttonOptions = TheNameKeyGenerator->nameToKey( "QuitNoSave.wnd:ButtonOptions" ); buttonSaveLoad = NAMEKEY_INVALID; buttonRestartWin = TheWindowManager->winGetWindowFromId( NULL, buttonRestart ); @@ -301,7 +301,7 @@ void ToggleQuitMenu() WindowLayout *optLayout = TheShell->getOptionsLayout(FALSE); GameWindow *optionsParent = optLayout->getFirstWindow(); DEBUG_ASSERTCRASH(optionsParent != NULL, ("Not able to get the options layout parent window")); - GameWindow *optionsBack = TheWindowManager->winGetWindowFromId(optionsParent, TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ButtonBack" ) )); + GameWindow *optionsBack = TheWindowManager->winGetWindowFromId(optionsParent, TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ButtonBack" )); DEBUG_ASSERTCRASH(optionsBack != NULL, ("Not able to get the back button window from the options menu")); TheWindowManager->winSendSystemMsg(optLayout->getFirstWindow(), GBM_SELECTED, (WindowMsgData)optionsBack, NULL); return; @@ -310,7 +310,7 @@ void ToggleQuitMenu() { GameWindow *saveLoadParent = saveLoadMenuLayout->getFirstWindow(); DEBUG_ASSERTCRASH(saveLoadParent != NULL, ("Not able to get the save/load layout parent window")); - GameWindow *saveLoadBack = TheWindowManager->winGetWindowFromId(saveLoadParent, TheNameKeyGenerator->nameToKey( AsciiString( "PopupSaveLoad.wnd:ButtonBack" ) )); + GameWindow *saveLoadBack = TheWindowManager->winGetWindowFromId(saveLoadParent, TheNameKeyGenerator->nameToKey( "PopupSaveLoad.wnd:ButtonBack" )); DEBUG_ASSERTCRASH(saveLoadBack != NULL, ("Not able to get the back button window from the save/load menu")); TheWindowManager->winSendSystemMsg(saveLoadMenuLayout->getFirstWindow(), GBM_SELECTED, (WindowMsgData)saveLoadBack, NULL); saveLoadMenuLayout = NULL; @@ -362,7 +362,7 @@ void ToggleQuitMenu() { // we don't want to show the save load button. if(!noSaveLoadQuitMenuLayout) - noSaveLoadQuitMenuLayout = TheWindowManager->winCreateLayout( AsciiString( "Menus/QuitNoSave.wnd" ) ); + noSaveLoadQuitMenuLayout = TheWindowManager->winCreateLayout( "Menus/QuitNoSave.wnd" ); quitMenuLayout = noSaveLoadQuitMenuLayout; initGadgetsNoSaveQuit(); TheTransitionHandler->remove("QuitNoSave"); @@ -371,7 +371,7 @@ void ToggleQuitMenu() else { if(!fullQuitMenuLayout) - fullQuitMenuLayout= TheWindowManager->winCreateLayout( AsciiString( "Menus/QuitMenu.wnd" ) ); + fullQuitMenuLayout= TheWindowManager->winCreateLayout( "Menus/QuitMenu.wnd" ); quitMenuLayout = fullQuitMenuLayout; initGadgetsFullQuit(); TheTransitionHandler->remove("QuitFull"); 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 9a0d3751c2..c73221d487 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ReplayMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ReplayMenu.cpp @@ -373,12 +373,12 @@ void ReplayMenuInit( WindowLayout *layout, void *userData ) TheShell->showShellMap(TRUE); // get ids for our children controls - parentReplayMenuID = TheNameKeyGenerator->nameToKey( AsciiString("ReplayMenu.wnd:ParentReplayMenu") ); - buttonLoadID = TheNameKeyGenerator->nameToKey( AsciiString("ReplayMenu.wnd:ButtonLoadReplay") ); - buttonBackID = TheNameKeyGenerator->nameToKey( AsciiString("ReplayMenu.wnd:ButtonBack") ); - listboxReplayFilesID = TheNameKeyGenerator->nameToKey( AsciiString("ReplayMenu.wnd:ListboxReplayFiles") ); - buttonDeleteID = TheNameKeyGenerator->nameToKey( AsciiString("ReplayMenu.wnd:ButtonDeleteReplay") ); - buttonCopyID = TheNameKeyGenerator->nameToKey( AsciiString("ReplayMenu.wnd:ButtonCopyReplay") ); + parentReplayMenuID = TheNameKeyGenerator->nameToKey( "ReplayMenu.wnd:ParentReplayMenu" ); + buttonLoadID = TheNameKeyGenerator->nameToKey( "ReplayMenu.wnd:ButtonLoadReplay" ); + buttonBackID = TheNameKeyGenerator->nameToKey( "ReplayMenu.wnd:ButtonBack" ); + listboxReplayFilesID = TheNameKeyGenerator->nameToKey( "ReplayMenu.wnd:ListboxReplayFiles" ); + buttonDeleteID = TheNameKeyGenerator->nameToKey( "ReplayMenu.wnd:ButtonDeleteReplay" ); + buttonCopyID = TheNameKeyGenerator->nameToKey( "ReplayMenu.wnd:ButtonCopyReplay" ); parentReplayMenu = TheWindowManager->winGetWindowFromId( NULL, parentReplayMenuID ); buttonLoad = TheWindowManager->winGetWindowFromId( parentReplayMenu, buttonLoadID ); 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 0387b8fcbb..ae00310f84 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp @@ -267,19 +267,19 @@ void ScoreScreenInit( WindowLayout *layout, void *userData ) buttonIsFinishCampaign = FALSE; //Store the keys so we have them later - parentID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:ParentScoreScreen" ) ); - buttonOkID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:ButtonOk" ) ); - textEntryChatID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:TextEntryChat" ) ); - buttonEmoteID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:ButtonEmote" ) ); - listboxChatWindowScoreScreenID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:ListboxChatWindowScoreScreen" ) ); - listboxAcademyWindowScoreScreenID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:ListboxWarschoolAdvice" ) ); - staticTextAcademyTitleID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:StaticTextWarSchool" ) ); -// buttonRehostID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:ButtonRehost" ) ); - chatBoxBorderID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:ChatBoxBorder" ) ); - buttonBuddiesID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:ButtonBuddy" ) ); - buttonContinueID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:ButtonContinue" ) ); - buttonSaveReplayID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:ButtonSaveReplay" ) ); - backdropID = TheNameKeyGenerator->nameToKey( AsciiString( "ScoreScreen.wnd:MainBackdrop" ) ); + parentID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:ParentScoreScreen" ); + buttonOkID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:ButtonOk" ); + textEntryChatID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:TextEntryChat" ); + buttonEmoteID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:ButtonEmote" ); + listboxChatWindowScoreScreenID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:ListboxChatWindowScoreScreen" ); + listboxAcademyWindowScoreScreenID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:ListboxWarschoolAdvice" ); + staticTextAcademyTitleID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:StaticTextWarSchool" ); +// buttonRehostID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:ButtonRehost" ); + chatBoxBorderID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:ChatBoxBorder" ); + buttonBuddiesID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:ButtonBuddy" ); + buttonContinueID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:ButtonContinue" ); + buttonSaveReplayID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:ButtonSaveReplay" ); + backdropID = TheNameKeyGenerator->nameToKey( "ScoreScreen.wnd:MainBackdrop" ); parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); buttonOk = TheWindowManager->winGetWindowFromId( parent, buttonOkID ); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SinglePlayerMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SinglePlayerMenu.cpp index 4c07b8cad8..e30311d80d 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SinglePlayerMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SinglePlayerMenu.cpp @@ -74,15 +74,15 @@ void SinglePlayerMenuInit( WindowLayout *layout, void *userData ) GameWindow *parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); TheWindowManager->winSetFocus( parent ); - NameKeyType buttonNewID = TheNameKeyGenerator->nameToKey( AsciiString("SinglePlayerMenu.wnd:ButtonNew") ); + NameKeyType buttonNewID = TheNameKeyGenerator->nameToKey( "SinglePlayerMenu.wnd:ButtonNew" ); GameWindow *buttonNew = TheWindowManager->winGetWindowFromId( NULL, buttonNewID ); TheShell->registerWithAnimateManager(buttonNew, WIN_ANIMATION_SLIDE_LEFT, TRUE,1); - NameKeyType buttonLoadID = TheNameKeyGenerator->nameToKey( AsciiString("SinglePlayerMenu.wnd:ButtonLoad") ); + NameKeyType buttonLoadID = TheNameKeyGenerator->nameToKey( "SinglePlayerMenu.wnd:ButtonLoad" ); GameWindow *buttonLoad = TheWindowManager->winGetWindowFromId( NULL, buttonLoadID ); TheShell->registerWithAnimateManager(buttonLoad, WIN_ANIMATION_SLIDE_LEFT, TRUE,200); - NameKeyType buttonBackID = TheNameKeyGenerator->nameToKey( AsciiString("SinglePlayerMenu.wnd:ButtonBack") ); + NameKeyType buttonBackID = TheNameKeyGenerator->nameToKey( "SinglePlayerMenu.wnd:ButtonBack" ); GameWindow *buttonBack = TheWindowManager->winGetWindowFromId( NULL, buttonBackID ); TheShell->registerWithAnimateManager(buttonBack, WIN_ANIMATION_SLIDE_RIGHT, TRUE,1); @@ -197,9 +197,9 @@ WindowMsgHandledType SinglePlayerMenuSystem( GameWindow *window, UnsignedInt msg { // get ids for our children controls - buttonNew = TheNameKeyGenerator->nameToKey( AsciiString("SinglePlayerMenu.wnd:ButtonNew") ); - buttonLoad = TheNameKeyGenerator->nameToKey( AsciiString("SinglePlayerMenu.wnd:ButtonLoad") ); - buttonBack = TheNameKeyGenerator->nameToKey( AsciiString("SinglePlayerMenu.wnd:ButtonBack") ); + buttonNew = TheNameKeyGenerator->nameToKey( "SinglePlayerMenu.wnd:ButtonNew" ); + buttonLoad = TheNameKeyGenerator->nameToKey( "SinglePlayerMenu.wnd:ButtonLoad" ); + buttonBack = TheNameKeyGenerator->nameToKey( "SinglePlayerMenu.wnd:ButtonBack" ); break; @@ -237,7 +237,7 @@ WindowMsgHandledType SinglePlayerMenuSystem( GameWindow *window, UnsignedInt msg { // open up the map select menu - TheShell->push( AsciiString( "Menus/MapSelectMenu.wnd" ) ); + TheShell->push( "Menus/MapSelectMenu.wnd" ); buttonPushed = true; } 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 7c658c1766..6c114b7bc6 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp @@ -368,7 +368,7 @@ Bool SkirmishPreferences::write(void) setSlotList(); -// NameKeyType sliderGameSpeedID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:SliderGameSpeed" ) ); +// NameKeyType sliderGameSpeedID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:SliderGameSpeed" ); GameWindow *sliderGameSpeed = TheWindowManager->winGetWindowFromId( parentSkirmishGameOptions, sliderGameSpeedID ); Int maxFPS = GadgetSliderGetPosition( sliderGameSpeed ); setInt("FPS", maxFPS); @@ -427,7 +427,7 @@ void reallyDoStart( void ) if (TheGameLogic->isInGame()) TheGameLogic->clearGameData(FALSE); - //NameKeyType sliderGameSpeedID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:SliderGameSpeed" ) ); + //NameKeyType sliderGameSpeedID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:SliderGameSpeed" ); GameWindow *sliderGameSpeed = TheWindowManager->winGetWindowFromId( parentSkirmishGameOptions, sliderGameSpeedID ); Int maxFPS = GadgetSliderGetPosition( sliderGameSpeed ); DEBUG_LOG(("GameSpeedSlider was at %d", maxFPS)); @@ -1075,16 +1075,16 @@ static void handleLimitSuperweaponsClick() void InitSkirmishGameGadgets( void ) { //Initialize the gadget IDs - parentSkirmishGameOptionsID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:SkirmishGameOptionsMenuParent" ) ); - buttonExitID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:ButtonBack" ) ); - buttonStartID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:ButtonStart" ) ); - textEntryMapDisplayID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:TextEntryMapDisplay" ) ); - buttonSelectMapID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:ButtonSelectMap" ) ); - buttonResetID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:ButtonReset" ) ); - windowMapID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:MapWindow" ) ); - staticTextGameSpeedID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:StaticTextGameSpeed" ) ); - checkBoxLimitSuperweaponsID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:CheckboxLimitSuperweapons" ) ); - comboBoxStartingCashID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:ComboBoxStartingCash" ) ); + parentSkirmishGameOptionsID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:SkirmishGameOptionsMenuParent" ); + buttonExitID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:ButtonBack" ); + buttonStartID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:ButtonStart" ); + textEntryMapDisplayID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:TextEntryMapDisplay" ); + buttonSelectMapID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:ButtonSelectMap" ); + buttonResetID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:ButtonReset" ); + windowMapID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:MapWindow" ); + staticTextGameSpeedID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:StaticTextGameSpeed" ); + checkBoxLimitSuperweaponsID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:CheckboxLimitSuperweapons" ); + comboBoxStartingCashID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:ComboBoxStartingCash" ); // Initialize the pointers to our gadgets parentSkirmishGameOptions = TheWindowManager->winGetWindowFromId( NULL, parentSkirmishGameOptionsID ); @@ -1107,7 +1107,7 @@ void InitSkirmishGameGadgets( void ) DEBUG_ASSERTCRASH(comboBoxStartingCash, ("Could not find the comboBoxStartingCash")); PopulateStartingCashComboBox(comboBoxStartingCash, TheSkirmishGameInfo ); - textEntryPlayerNameID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:TextEntryPlayerName" ) ); + textEntryPlayerNameID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:TextEntryPlayerName" ); textEntryPlayerName = TheWindowManager->winGetWindowFromId( NULL, textEntryPlayerNameID ); DEBUG_ASSERTCRASH(textEntryPlayerName, ("Could not find the textEntryPlayerName" )); @@ -1311,7 +1311,7 @@ void SkirmishGameOptionsMenuInit( WindowLayout *layout, void *userData ) stillNeedsToSetOptions = FALSE; - sliderGameSpeedID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:SliderGameSpeed" ) ); + sliderGameSpeedID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:SliderGameSpeed" ); sandboxOk = FALSE; doUpdateSlotList = FALSE; @@ -1397,7 +1397,7 @@ void SkirmishGameOptionsMenuInit( WindowLayout *layout, void *userData ) //initSkirmishGameOptions(); // set up the game speed slider -// NameKeyType sliderGameSpeedID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:SliderGameSpeed" ) ); +// NameKeyType sliderGameSpeedID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:SliderGameSpeed" ); GameWindow *sliderGameSpeed = TheWindowManager->winGetWindowFromId( parentSkirmishGameOptions, sliderGameSpeedID ); Int sliderPos = max(15,min(61,prefs.getInt("FPS", TheGlobalData->m_framesPerSecondLimit))); GadgetSliderSetPosition( sliderGameSpeed, sliderPos ); @@ -1647,7 +1647,7 @@ WindowMsgHandledType SkirmishGameOptionsMenuSystem( GameWindow *window, Unsigned GameWindow *control = (GameWindow *)mData1; Int controlID = control->winGetWindowId(); -/// static NameKeyType buttonResetFPSID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:ButtonResetFPS" ) ); +/// static NameKeyType buttonResetFPSID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:ButtonResetFPS" ); if(buttonPushed) break; if ( controlID == buttonExitID ) @@ -1668,7 +1668,7 @@ WindowMsgHandledType SkirmishGameOptionsMenuSystem( GameWindow *window, Unsigned } // else if ( controlID == buttonResetFPSID ) // { -// static NameKeyType sliderGameSpeedID = TheNameKeyGenerator->nameToKey( AsciiString( "SkirmishGameOptionsMenu.wnd:SliderGameSpeed" ) ); +// static NameKeyType sliderGameSpeedID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:SliderGameSpeed" ); // GameWindow *sliderGameSpeed = TheWindowManager->winGetWindowFromId( parentSkirmishGameOptions, sliderGameSpeedID ); // GadgetSliderSetPosition( sliderGameSpeed, TheGlobalData->m_framesPerSecondLimit ); // } @@ -1676,7 +1676,7 @@ WindowMsgHandledType SkirmishGameOptionsMenuSystem( GameWindow *window, Unsigned { sandboxOk = FALSE; //buttonBack->winEnable( false ); - skirmishMapSelectLayout = TheWindowManager->winCreateLayout( AsciiString( "Menus/SkirmishMapSelectMenu.wnd" ) ); + skirmishMapSelectLayout = TheWindowManager->winCreateLayout( "Menus/SkirmishMapSelectMenu.wnd" ); skirmishMapSelectLayout->runInit(); skirmishMapSelectLayout->hide( FALSE ); skirmishMapSelectLayout->bringForward(); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp index e6e428ba6e..8d66cac120 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp @@ -267,13 +267,13 @@ void SkirmishMapSelectMenuInit( WindowLayout *layout, void *userData ) usesSystemMapDir = mmd->m_isOfficial; } - winMapPreviewID = TheNameKeyGenerator->nameToKey( AsciiString("SkirmishMapSelectMenu.wnd:WinMapPreview") ); + winMapPreviewID = TheNameKeyGenerator->nameToKey( "SkirmishMapSelectMenu.wnd:WinMapPreview" ); winMapPreview = TheWindowManager->winGetWindowFromId(parent, winMapPreviewID); - buttonBack = TheNameKeyGenerator->nameToKey( AsciiString("SkirmishMapSelectMenu.wnd:ButtonBack") ); - buttonOK = TheNameKeyGenerator->nameToKey( AsciiString("SkirmishMapSelectMenu.wnd:ButtonOK") ); - listboxMap = TheNameKeyGenerator->nameToKey( AsciiString("SkirmishMapSelectMenu.wnd:ListboxMap") ); + buttonBack = TheNameKeyGenerator->nameToKey( "SkirmishMapSelectMenu.wnd:ButtonBack" ); + buttonOK = TheNameKeyGenerator->nameToKey( "SkirmishMapSelectMenu.wnd:ButtonOK" ); + listboxMap = TheNameKeyGenerator->nameToKey( "SkirmishMapSelectMenu.wnd:ListboxMap" ); radioButtonSystemMapsID = TheNameKeyGenerator->nameToKey( "SkirmishMapSelectMenu.wnd:RadioButtonSystemMaps" ); radioButtonUserMapsID = TheNameKeyGenerator->nameToKey( "SkirmishMapSelectMenu.wnd:RadioButtonUserMaps" ); 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 6e7b453954..166659a950 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLBuddyOverlay.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLBuddyOverlay.cpp @@ -166,20 +166,20 @@ void InitBuddyControls(Int type) buddyControls.isInit = FALSE; break; case BUDDY_WINDOW_BUDDIES: - buddyControls.textEntryEditID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:TextEntryChat" ) ); + buddyControls.textEntryEditID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:TextEntryChat" ); buddyControls.textEntryEdit = TheWindowManager->winGetWindowFromId(NULL, buddyControls.textEntryEditID); - buddyControls.listboxBuddiesID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:ListboxBuddies" ) ); - buddyControls.listboxChatID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:ListboxBuddyChat" ) ); + buddyControls.listboxBuddiesID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:ListboxBuddies" ); + buddyControls.listboxChatID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:ListboxBuddyChat" ); buddyControls.listboxBuddies = TheWindowManager->winGetWindowFromId( NULL, buddyControls.listboxBuddiesID ); buddyControls.listboxChat = TheWindowManager->winGetWindowFromId( NULL, buddyControls.listboxChatID); GadgetTextEntrySetText(buddyControls.textEntryEdit, UnicodeString::TheEmptyString); buddyControls.isInit = TRUE; break; case BUDDY_WINDOW_DIPLOMACY: - buddyControls.textEntryEditID = TheNameKeyGenerator->nameToKey( AsciiString( "Diplomacy.wnd:TextEntryChat" ) ); + buddyControls.textEntryEditID = TheNameKeyGenerator->nameToKey( "Diplomacy.wnd:TextEntryChat" ); buddyControls.textEntryEdit = TheWindowManager->winGetWindowFromId(NULL, buddyControls.textEntryEditID); - buddyControls.listboxBuddiesID = TheNameKeyGenerator->nameToKey( AsciiString( "Diplomacy.wnd:ListboxBuddies" ) ); - buddyControls.listboxChatID = TheNameKeyGenerator->nameToKey( AsciiString( "Diplomacy.wnd:ListboxBuddyChat" ) ); + buddyControls.listboxBuddiesID = TheNameKeyGenerator->nameToKey( "Diplomacy.wnd:ListboxBuddies" ); + buddyControls.listboxChatID = TheNameKeyGenerator->nameToKey( "Diplomacy.wnd:ListboxBuddyChat" ); buddyControls.listboxBuddies = TheWindowManager->winGetWindowFromId( NULL, buddyControls.listboxBuddiesID ); buddyControls.listboxChat = TheWindowManager->winGetWindowFromId( NULL, buddyControls.listboxChatID); GadgetTextEntrySetText(buddyControls.textEntryEdit, UnicodeString::TheEmptyString); @@ -221,11 +221,11 @@ WindowMsgHandledType BuddyControlSystem( GameWindow *window, UnsignedInt msg, GadgetListBoxSetSelected(control, rc->pos); if (itemType == ITEM_BUDDY) - rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/RCBuddiesMenu.wnd")); + rcLayout = TheWindowManager->winCreateLayout("Menus/RCBuddiesMenu.wnd"); else if (itemType == ITEM_REQUEST) - rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/RCBuddyRequestMenu.wnd")); + rcLayout = TheWindowManager->winCreateLayout("Menus/RCBuddyRequestMenu.wnd"); else - rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/RCNonBuddiesMenu.wnd")); + rcLayout = TheWindowManager->winCreateLayout("Menus/RCNonBuddiesMenu.wnd"); rcMenu = rcLayout->getFirstWindow(); rcMenu->winGetLayout()->runInit(); rcMenu->winBringToTop(); @@ -709,20 +709,20 @@ void PopulateOldBuddyMessages(void) //------------------------------------------------------------------------------------------------- void WOLBuddyOverlayInit( WindowLayout *layout, void *userData ) { - parentID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:BuddyMenuParent" ) ); - buttonHideID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:ButtonHide" ) ); - buttonAddBuddyID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:ButtonAdd" ) ); - buttonDeleteBuddyID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:ButtonDelete" ) ); - //textEntryID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:TextEntryChat" ) ); - //listboxBuddyID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:ListboxBuddies" ) ); - //listboxChatID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:ListboxBuddyChat" ) ); - buttonAcceptBuddyID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:ButtonYes" ) ); - buttonDenyBuddyID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:ButtonNo" ) ); - radioButtonBuddiesID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:RadioButtonBuddies" ) ); - radioButtonIgnoreID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:RadioButtonIgnore" ) ); - parentBuddiesID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:BuddiesParent" ) ); - parentIgnoreID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:IgnoreParent" ) ); - listboxIgnoreID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLBuddyOverlay.wnd:ListboxIgnore" ) ); + parentID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:BuddyMenuParent" ); + buttonHideID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:ButtonHide" ); + buttonAddBuddyID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:ButtonAdd" ); + buttonDeleteBuddyID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:ButtonDelete" ); + //textEntryID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:TextEntryChat" ); + //listboxBuddyID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:ListboxBuddies" ); + //listboxChatID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:ListboxBuddyChat" ); + buttonAcceptBuddyID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:ButtonYes" ); + buttonDenyBuddyID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:ButtonNo" ); + radioButtonBuddiesID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:RadioButtonBuddies" ); + radioButtonIgnoreID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:RadioButtonIgnore" ); + parentBuddiesID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:BuddiesParent" ); + parentIgnoreID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:IgnoreParent" ); + listboxIgnoreID = TheNameKeyGenerator->nameToKey( "WOLBuddyOverlay.wnd:ListboxIgnore" ); parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); @@ -910,11 +910,11 @@ WindowMsgHandledType WOLBuddyOverlaySystem( GameWindow *window, UnsignedInt msg, GadgetListBoxSetSelected(control, rc->pos); if (isBuddy) - rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/RCBuddiesMenu.wnd")); + rcLayout = TheWindowManager->winCreateLayout("Menus/RCBuddiesMenu.wnd"); else if (isRequest) - rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/RCBuddyRequestMenu.wnd")); + rcLayout = TheWindowManager->winCreateLayout("Menus/RCBuddyRequestMenu.wnd"); else - rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/RCNonBuddiesMenu.wnd")); + rcLayout = TheWindowManager->winCreateLayout("Menus/RCNonBuddiesMenu.wnd"); rcMenu = rcLayout->getFirstWindow(); rcMenu->winGetLayout()->runInit(); rcMenu->winBringToTop(); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLCustomScoreScreen.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLCustomScoreScreen.cpp index e35781f238..359cac5d11 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLCustomScoreScreen.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLCustomScoreScreen.cpp @@ -63,9 +63,9 @@ static GameWindow *buttonLobby = NULL; //------------------------------------------------------------------------------------------------- void WOLCustomScoreScreenInit( WindowLayout *layout, void *userData ) { - parentWOLCustomScoreID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLCustomScoreScreen.wnd:WOLCustomScoreScreenParent" ) ); - buttonDisconnectID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLCustomScoreScreen.wnd:ButtonDisconnect" ) ); - buttonLobbyID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLCustomScoreScreen.wnd:ButtonLobby" ) ); + parentWOLCustomScoreID = TheNameKeyGenerator->nameToKey( "WOLCustomScoreScreen.wnd:WOLCustomScoreScreenParent" ); + buttonDisconnectID = TheNameKeyGenerator->nameToKey( "WOLCustomScoreScreen.wnd:ButtonDisconnect" ); + buttonLobbyID = TheNameKeyGenerator->nameToKey( "WOLCustomScoreScreen.wnd:ButtonLobby" ); parentWOLCustomScore = TheWindowManager->winGetWindowFromId( NULL, parentWOLCustomScoreID ); buttonDisconnect = TheWindowManager->winGetWindowFromId( NULL, buttonDisconnectID); buttonLobby = TheWindowManager->winGetWindowFromId( NULL, buttonLobbyID); 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 f8ded6ae93..d0de9eb542 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp @@ -272,7 +272,7 @@ void WOLPositionStartSpots( void ) win = TheWindowManager->winGetWindowFromId(NULL, windowMapSelectMapID); // get the controls. - NameKeyType listboxMapID = TheNameKeyGenerator->nameToKey( AsciiString("WOLMapSelectMenu.wnd:ListboxMap") ); + NameKeyType listboxMapID = TheNameKeyGenerator->nameToKey( "WOLMapSelectMenu.wnd:ListboxMap" ); GameWindow *listboxMap = TheWindowManager->winGetWindowFromId( NULL, listboxMapID ); if (listboxMap != NULL) { @@ -1108,20 +1108,20 @@ void InitWOLGameGadgets( void ) DEBUG_ASSERTCRASH(pingImages[2], ("Can't find ping image!")); //Initialize the gadget IDs - parentWOLGameSetupID = TheNameKeyGenerator->nameToKey( AsciiString( "GameSpyGameOptionsMenu.wnd:GameSpyGameOptionsMenuParent" ) ); - buttonBackID = TheNameKeyGenerator->nameToKey( AsciiString( "GameSpyGameOptionsMenu.wnd:ButtonBack" ) ); - buttonStartID = TheNameKeyGenerator->nameToKey( AsciiString( "GameSpyGameOptionsMenu.wnd:ButtonStart" ) ); - textEntryChatID = TheNameKeyGenerator->nameToKey( AsciiString( "GameSpyGameOptionsMenu.wnd:TextEntryChat" ) ); - textEntryMapDisplayID = TheNameKeyGenerator->nameToKey( AsciiString( "GameSpyGameOptionsMenu.wnd:TextEntryMapDisplay" ) ); - listboxGameSetupChatID = TheNameKeyGenerator->nameToKey( AsciiString( "GameSpyGameOptionsMenu.wnd:ListboxChatWindowGameSpyGameSetup" ) ); - buttonEmoteID = TheNameKeyGenerator->nameToKey( AsciiString( "GameSpyGameOptionsMenu.wnd:ButtonEmote" ) ); - buttonSelectMapID = TheNameKeyGenerator->nameToKey( AsciiString( "GameSpyGameOptionsMenu.wnd:ButtonSelectMap" ) ); - checkBoxUseStatsID = TheNameKeyGenerator->nameToKey( AsciiString( "GameSpyGameOptionsMenu.wnd:CheckBoxUseStats" ) ); - windowMapID = TheNameKeyGenerator->nameToKey( AsciiString( "GameSpyGameOptionsMenu.wnd:MapWindow" ) ); - checkBoxLimitSuperweaponsID = TheNameKeyGenerator->nameToKey(AsciiString("GameSpyGameOptionsMenu.wnd:CheckboxLimitSuperweapons")); - comboBoxStartingCashID = TheNameKeyGenerator->nameToKey(AsciiString("GameSpyGameOptionsMenu.wnd:ComboBoxStartingCash")); - checkBoxLimitArmiesID = TheNameKeyGenerator->nameToKey(AsciiString("GameSpyGameOptionsMenu.wnd:CheckBoxLimitArmies")); - windowMapSelectMapID = TheNameKeyGenerator->nameToKey(AsciiString("WOLMapSelectMenu.wnd:WinMapPreview")); + parentWOLGameSetupID = TheNameKeyGenerator->nameToKey( "GameSpyGameOptionsMenu.wnd:GameSpyGameOptionsMenuParent" ); + buttonBackID = TheNameKeyGenerator->nameToKey( "GameSpyGameOptionsMenu.wnd:ButtonBack" ); + buttonStartID = TheNameKeyGenerator->nameToKey( "GameSpyGameOptionsMenu.wnd:ButtonStart" ); + textEntryChatID = TheNameKeyGenerator->nameToKey( "GameSpyGameOptionsMenu.wnd:TextEntryChat" ); + textEntryMapDisplayID = TheNameKeyGenerator->nameToKey( "GameSpyGameOptionsMenu.wnd:TextEntryMapDisplay" ); + listboxGameSetupChatID = TheNameKeyGenerator->nameToKey( "GameSpyGameOptionsMenu.wnd:ListboxChatWindowGameSpyGameSetup" ); + buttonEmoteID = TheNameKeyGenerator->nameToKey( "GameSpyGameOptionsMenu.wnd:ButtonEmote" ); + buttonSelectMapID = TheNameKeyGenerator->nameToKey( "GameSpyGameOptionsMenu.wnd:ButtonSelectMap" ); + checkBoxUseStatsID = TheNameKeyGenerator->nameToKey( "GameSpyGameOptionsMenu.wnd:CheckBoxUseStats" ); + windowMapID = TheNameKeyGenerator->nameToKey( "GameSpyGameOptionsMenu.wnd:MapWindow" ); + checkBoxLimitSuperweaponsID = TheNameKeyGenerator->nameToKey("GameSpyGameOptionsMenu.wnd:CheckboxLimitSuperweapons"); + comboBoxStartingCashID = TheNameKeyGenerator->nameToKey("GameSpyGameOptionsMenu.wnd:ComboBoxStartingCash"); + checkBoxLimitArmiesID = TheNameKeyGenerator->nameToKey("GameSpyGameOptionsMenu.wnd:CheckBoxLimitArmies"); + windowMapSelectMapID = TheNameKeyGenerator->nameToKey("WOLMapSelectMenu.wnd:WinMapPreview"); NameKeyType staticTextTitleID = NAMEKEY("GameSpyGameOptionsMenu.wnd:StaticTextGameName"); @@ -1158,7 +1158,7 @@ void InitWOLGameGadgets( void ) { checkBoxLimitSuperweapons->winEnable( false ); comboBoxStartingCash->winEnable( false ); - NameKeyType labelID = TheNameKeyGenerator->nameToKey(AsciiString("GameSpyGameOptionsMenu.wnd:StartingCashLabel")); + NameKeyType labelID = TheNameKeyGenerator->nameToKey("GameSpyGameOptionsMenu.wnd:StartingCashLabel"); TheWindowManager->winGetWindowFromId(parentWOLGameSetup, labelID)->winEnable( FALSE ); } @@ -1169,7 +1169,7 @@ void InitWOLGameGadgets( void ) checkBoxLimitSuperweapons->winEnable( FALSE ); comboBoxStartingCash->winEnable( FALSE ); checkBoxLimitArmies->winEnable( FALSE ); - NameKeyType labelID = TheNameKeyGenerator->nameToKey(AsciiString("GameSpyGameOptionsMenu.wnd:StartingCashLabel")); + NameKeyType labelID = TheNameKeyGenerator->nameToKey("GameSpyGameOptionsMenu.wnd:StartingCashLabel"); TheWindowManager->winGetWindowFromId(parentWOLGameSetup, labelID)->winEnable( FALSE ); } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLadderScreen.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLadderScreen.cpp index f8e9d3f195..2e02bd2960 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLadderScreen.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLadderScreen.cpp @@ -58,9 +58,9 @@ void WOLLadderScreenInit( WindowLayout *layout, void *userData ) TheShell->showShellMap(TRUE); // get ids for our children controls - parentWindowID = TheNameKeyGenerator->nameToKey( AsciiString("WOLLadderScreen.wnd:LadderParent") ); - buttonBackID = TheNameKeyGenerator->nameToKey( AsciiString("WOLLadderScreen.wnd:ButtonBack") ); - windowLadderID = TheNameKeyGenerator->nameToKey( AsciiString("WOLLadderScreen.wnd:WindowLadder") ); + parentWindowID = TheNameKeyGenerator->nameToKey( "WOLLadderScreen.wnd:LadderParent" ); + buttonBackID = TheNameKeyGenerator->nameToKey( "WOLLadderScreen.wnd:ButtonBack" ); + windowLadderID = TheNameKeyGenerator->nameToKey( "WOLLadderScreen.wnd:WindowLadder" ); parentWindow = TheWindowManager->winGetWindowFromId( NULL, parentWindowID ); buttonBack = TheWindowManager->winGetWindowFromId( parentWindow, buttonBackID ); 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 597f79d5b2..35dde88d59 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp @@ -622,40 +622,40 @@ void WOLLobbyMenuInit( WindowLayout *layout, void *userData ) gameListRefreshTime = 0; playerListRefreshTime = 0; - parentWOLLobbyID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLCustomLobby.wnd:WOLLobbyMenuParent" ) ); + parentWOLLobbyID = TheNameKeyGenerator->nameToKey( "WOLCustomLobby.wnd:WOLLobbyMenuParent" ); parent = TheWindowManager->winGetWindowFromId(NULL, parentWOLLobbyID); - buttonBackID = TheNameKeyGenerator->nameToKey(AsciiString("WOLCustomLobby.wnd:ButtonBack")); + buttonBackID = TheNameKeyGenerator->nameToKey("WOLCustomLobby.wnd:ButtonBack"); buttonBack = TheWindowManager->winGetWindowFromId(parent, buttonBackID); - buttonHostID = TheNameKeyGenerator->nameToKey(AsciiString("WOLCustomLobby.wnd:ButtonHost")); + buttonHostID = TheNameKeyGenerator->nameToKey("WOLCustomLobby.wnd:ButtonHost"); buttonHost = TheWindowManager->winGetWindowFromId(parent, buttonHostID); - buttonRefreshID = TheNameKeyGenerator->nameToKey(AsciiString("WOLCustomLobby.wnd:ButtonRefresh")); + buttonRefreshID = TheNameKeyGenerator->nameToKey("WOLCustomLobby.wnd:ButtonRefresh"); buttonRefresh = TheWindowManager->winGetWindowFromId(parent, buttonRefreshID); - buttonJoinID = TheNameKeyGenerator->nameToKey(AsciiString("WOLCustomLobby.wnd:ButtonJoin")); + buttonJoinID = TheNameKeyGenerator->nameToKey("WOLCustomLobby.wnd:ButtonJoin"); buttonJoin = TheWindowManager->winGetWindowFromId(parent, buttonJoinID); buttonJoin->winEnable(FALSE); - buttonBuddyID = TheNameKeyGenerator->nameToKey(AsciiString("WOLCustomLobby.wnd:ButtonBuddy")); + buttonBuddyID = TheNameKeyGenerator->nameToKey("WOLCustomLobby.wnd:ButtonBuddy"); buttonBuddy = TheWindowManager->winGetWindowFromId(parent, buttonBuddyID); - buttonEmoteID = TheNameKeyGenerator->nameToKey(AsciiString("WOLCustomLobby.wnd:ButtonEmote")); + buttonEmoteID = TheNameKeyGenerator->nameToKey("WOLCustomLobby.wnd:ButtonEmote"); buttonEmote = TheWindowManager->winGetWindowFromId(parent, buttonEmoteID); - textEntryChatID = TheNameKeyGenerator->nameToKey(AsciiString("WOLCustomLobby.wnd:TextEntryChat")); + textEntryChatID = TheNameKeyGenerator->nameToKey("WOLCustomLobby.wnd:TextEntryChat"); textEntryChat = TheWindowManager->winGetWindowFromId(parent, textEntryChatID); - listboxLobbyPlayersID = TheNameKeyGenerator->nameToKey(AsciiString("WOLCustomLobby.wnd:ListboxPlayers")); + listboxLobbyPlayersID = TheNameKeyGenerator->nameToKey("WOLCustomLobby.wnd:ListboxPlayers"); listboxLobbyPlayers = TheWindowManager->winGetWindowFromId(parent, listboxLobbyPlayersID); listboxLobbyPlayers->winSetTooltipFunc(playerTooltip); - listboxLobbyChatID = TheNameKeyGenerator->nameToKey(AsciiString("WOLCustomLobby.wnd:ListboxChat")); + listboxLobbyChatID = TheNameKeyGenerator->nameToKey("WOLCustomLobby.wnd:ListboxChat"); listboxLobbyChat = TheWindowManager->winGetWindowFromId(parent, listboxLobbyChatID); TheGameSpyInfo->registerTextWindow(listboxLobbyChat); - comboLobbyGroupRoomsID = TheNameKeyGenerator->nameToKey(AsciiString("WOLCustomLobby.wnd:ComboBoxGroupRooms")); + comboLobbyGroupRoomsID = TheNameKeyGenerator->nameToKey("WOLCustomLobby.wnd:ComboBoxGroupRooms"); comboLobbyGroupRooms = TheWindowManager->winGetWindowFromId(parent, comboLobbyGroupRoomsID); GadgetTextEntrySetText(textEntryChat, UnicodeString::TheEmptyString); @@ -1744,20 +1744,20 @@ WindowMsgHandledType WOLLobbyMenuSystem( GameWindow *window, UnsignedInt msg, Bool isBuddy = FALSE; if (profileID <= 0) - rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/RCNoProfileMenu.wnd")); + rcLayout = TheWindowManager->winCreateLayout("Menus/RCNoProfileMenu.wnd"); else { if (profileID == TheGameSpyInfo->getLocalProfileID()) { - rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/RCLocalPlayerMenu.wnd")); + rcLayout = TheWindowManager->winCreateLayout("Menus/RCLocalPlayerMenu.wnd"); } else if(TheGameSpyInfo->isBuddy(profileID)) { - rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/RCBuddiesMenu.wnd")); + rcLayout = TheWindowManager->winCreateLayout("Menus/RCBuddiesMenu.wnd"); isBuddy = TRUE; } else - rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/RCNonBuddiesMenu.wnd")); + rcLayout = TheWindowManager->winCreateLayout("Menus/RCNonBuddiesMenu.wnd"); } if(!rcLayout) break; @@ -1810,7 +1810,7 @@ WindowMsgHandledType WOLLobbyMenuSystem( GameWindow *window, UnsignedInt msg, const LadderInfo *linfo = TheLadderList->findLadder(theRoom->getLadderIP(), theRoom->getLadderPort()); if (linfo) { - rcLayout = TheWindowManager->winCreateLayout(AsciiString("Menus/RCGameDetailsMenu.wnd")); + rcLayout = TheWindowManager->winCreateLayout("Menus/RCGameDetailsMenu.wnd"); if (!rcLayout) break; 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 1f5f34898b..9c8aa8db08 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLocaleSelectPopup.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLocaleSelectPopup.cpp @@ -65,9 +65,9 @@ static GameWindow *listboxLocale = NULL; //------------------------------------------------------------------------------------------------- void WOLLocaleSelectInit( WindowLayout *layout, void *userData ) { - parentLocaleSelectID = TheNameKeyGenerator->nameToKey( AsciiString( "PopupLocaleSelect.wnd:ParentLocaleSelect" ) ); - buttonOkID = TheNameKeyGenerator->nameToKey( AsciiString( "PopupLocaleSelect.wnd:ButtonOk" ) ); - listboxLocaleID = TheNameKeyGenerator->nameToKey( AsciiString( "PopupLocaleSelect.wnd:ListBoxLocaleSelect" ) ); + parentLocaleSelectID = TheNameKeyGenerator->nameToKey( "PopupLocaleSelect.wnd:ParentLocaleSelect" ); + buttonOkID = TheNameKeyGenerator->nameToKey( "PopupLocaleSelect.wnd:ButtonOk" ); + listboxLocaleID = TheNameKeyGenerator->nameToKey( "PopupLocaleSelect.wnd:ListBoxLocaleSelect" ); parentLocaleSelect = TheWindowManager->winGetWindowFromId( NULL, parentLocaleSelectID ); buttonOk = TheWindowManager->winGetWindowFromId( NULL, buttonOkID); listboxLocale = TheWindowManager->winGetWindowFromId( NULL, listboxLocaleID); 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 ab0dc39c6e..fffd934564 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMapSelectMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMapSelectMenu.cpp @@ -135,7 +135,7 @@ void WOLMapSelectMenuInit( WindowLayout *layout, void *userData ) CustomMatchPreferences pref; Bool usesSystemMapDir = pref.usesSystemMapDir(); - winMapPreviewID = TheNameKeyGenerator->nameToKey( AsciiString("WOLMapSelectMenu.wnd:WinMapPreview") ); + winMapPreviewID = TheNameKeyGenerator->nameToKey( "WOLMapSelectMenu.wnd:WinMapPreview" ); winMapPreview = TheWindowManager->winGetWindowFromId(parent, winMapPreviewID); const MapMetaData *mmd = TheMapCache->findMap(TheGameSpyGame->getMap()); @@ -148,9 +148,9 @@ void WOLMapSelectMenuInit( WindowLayout *layout, void *userData ) if( TheGameSpyInfo->getCurrentStagingRoom()->getUseStats() ) usesSystemMapDir = true; - buttonBack = TheNameKeyGenerator->nameToKey( AsciiString("WOLMapSelectMenu.wnd:ButtonBack") ); - buttonOK = TheNameKeyGenerator->nameToKey( AsciiString("WOLMapSelectMenu.wnd:ButtonOK") ); - listboxMap = TheNameKeyGenerator->nameToKey( AsciiString("WOLMapSelectMenu.wnd:ListboxMap") ); + buttonBack = TheNameKeyGenerator->nameToKey( "WOLMapSelectMenu.wnd:ButtonBack" ); + buttonOK = TheNameKeyGenerator->nameToKey( "WOLMapSelectMenu.wnd:ButtonOK" ); + listboxMap = TheNameKeyGenerator->nameToKey( "WOLMapSelectMenu.wnd:ListboxMap" ); radioButtonSystemMapsID = TheNameKeyGenerator->nameToKey( "WOLMapSelectMenu.wnd:RadioButtonSystemMaps" ); radioButtonUserMapsID = TheNameKeyGenerator->nameToKey( "WOLMapSelectMenu.wnd:RadioButtonUserMaps" ); winMapWindow = TheWindowManager->winGetWindowFromId( parent, listboxMap ); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMessageWindow.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMessageWindow.cpp index 4975dfa1a0..7eb372eb8c 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMessageWindow.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMessageWindow.cpp @@ -59,8 +59,8 @@ static GameWindow *buttonCancel = NULL; //------------------------------------------------------------------------------------------------- void WOLMessageWindowInit( WindowLayout *layout, void *userData ) { - parentWOLMessageWindowID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLMessageWindow.wnd:WOLMessageWindowParent" ) ); - buttonCancelID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLMessageWindow.wnd:ButtonCancel" ) ); + parentWOLMessageWindowID = TheNameKeyGenerator->nameToKey( "WOLMessageWindow.wnd:WOLMessageWindowParent" ); + buttonCancelID = TheNameKeyGenerator->nameToKey( "WOLMessageWindow.wnd:ButtonCancel" ); parentWOLMessageWindow = TheWindowManager->winGetWindowFromId( NULL, parentWOLMessageWindowID ); buttonCancel = TheWindowManager->winGetWindowFromId( NULL, buttonCancelID); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQMScoreScreen.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQMScoreScreen.cpp index 75113baa66..94b1113afa 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQMScoreScreen.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQMScoreScreen.cpp @@ -60,9 +60,9 @@ static GameWindow *buttonQuickmatch = NULL; //------------------------------------------------------------------------------------------------- void WOLQMScoreScreenInit( WindowLayout *layout, void *userData ) { - parentWOLQMScoreID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLQMScoreScreen.wnd:WOLQMScoreScreenParent" ) ); - buttonDisconnectID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLQMScoreScreen.wnd:ButtonDisconnect" ) ); - buttonQuickmatchID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLQMScoreScreen.wnd:ButtonQuickMatch" ) ); + parentWOLQMScoreID = TheNameKeyGenerator->nameToKey( "WOLQMScoreScreen.wnd:WOLQMScoreScreenParent" ); + buttonDisconnectID = TheNameKeyGenerator->nameToKey( "WOLQMScoreScreen.wnd:ButtonDisconnect" ); + buttonQuickmatchID = TheNameKeyGenerator->nameToKey( "WOLQMScoreScreen.wnd:ButtonQuickMatch" ); parentWOLQMScore = TheWindowManager->winGetWindowFromId( NULL, parentWOLQMScoreID ); buttonDisconnect = TheWindowManager->winGetWindowFromId( NULL, buttonDisconnectID); buttonQuickmatch = TheWindowManager->winGetWindowFromId( NULL, buttonQuickmatchID); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLStatusMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLStatusMenu.cpp index ff0c5c6779..e186969e79 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLStatusMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLStatusMenu.cpp @@ -59,13 +59,13 @@ GameWindow *progressTextWindow = NULL; //------------------------------------------------------------------------------------------------- void WOLStatusMenuInit( WindowLayout *layout, void *userData ) { - parentWOLStatusID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLStatusMenu.wnd:WOLStatusMenuParent" ) ); - buttonDisconnectID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLStatusMenu.wnd:ButtonDisconnect" ) ); + parentWOLStatusID = TheNameKeyGenerator->nameToKey( "WOLStatusMenu.wnd:WOLStatusMenuParent" ); + buttonDisconnectID = TheNameKeyGenerator->nameToKey( "WOLStatusMenu.wnd:ButtonDisconnect" ); parentWOLStatus = TheWindowManager->winGetWindowFromId( NULL, parentWOLStatusID ); buttonDisconnect = TheWindowManager->winGetWindowFromId( NULL, buttonDisconnectID); progressTextWindow = TheWindowManager->winGetWindowFromId( NULL, - TheNameKeyGenerator->nameToKey( AsciiString( "WOLStatusMenu.wnd:ListboxStatus" ) ) ); + TheNameKeyGenerator->nameToKey( "WOLStatusMenu.wnd:ListboxStatus" ) ); // Show Menu layout->hide( FALSE ); 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 2846e2b156..4729001bf3 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp @@ -425,13 +425,13 @@ void WOLWelcomeMenuInit( WindowLayout *layout, void *userData ) //TheWOL->reset(); - parentWOLWelcomeID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLWelcomeMenu.wnd:WOLWelcomeMenuParent" ) ); - buttonBackID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLWelcomeMenu.wnd:ButtonBack" ) ); + parentWOLWelcomeID = TheNameKeyGenerator->nameToKey( "WOLWelcomeMenu.wnd:WOLWelcomeMenuParent" ); + buttonBackID = TheNameKeyGenerator->nameToKey( "WOLWelcomeMenu.wnd:ButtonBack" ); parentWOLWelcome = TheWindowManager->winGetWindowFromId( NULL, parentWOLWelcomeID ); buttonBack = TheWindowManager->winGetWindowFromId( NULL, buttonBackID); buttonOptionsID = TheNameKeyGenerator->nameToKey( "WOLWelcomeMenu.wnd:ButtonOptions" ); buttonbuttonOptions = TheWindowManager->winGetWindowFromId( NULL, buttonOptionsID); - listboxInfoID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLWelcomeMenu.wnd:InfoListbox" ) ); + listboxInfoID = TheNameKeyGenerator->nameToKey( "WOLWelcomeMenu.wnd:InfoListbox" ); listboxInfo = TheWindowManager->winGetWindowFromId( NULL, listboxInfoID); @@ -490,19 +490,19 @@ void WOLWelcomeMenuInit( WindowLayout *layout, void *userData ) //DEBUG_ASSERTCRASH(listboxInfo, ("No control found!")); - buttonQuickMatchID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLWelcomeMenu.wnd:ButtonQuickMatch" ) ); + buttonQuickMatchID = TheNameKeyGenerator->nameToKey( "WOLWelcomeMenu.wnd:ButtonQuickMatch" ); buttonQuickMatch = TheWindowManager->winGetWindowFromId( parentWOLWelcome, buttonQuickMatchID ); - buttonLobbyID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLWelcomeMenu.wnd:ButtonCustomMatch" ) ); + buttonLobbyID = TheNameKeyGenerator->nameToKey( "WOLWelcomeMenu.wnd:ButtonCustomMatch" ); buttonLobby = TheWindowManager->winGetWindowFromId( parentWOLWelcome, buttonLobbyID ); - buttonBuddiesID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLWelcomeMenu.wnd:ButtonBuddies" ) ); + buttonBuddiesID = TheNameKeyGenerator->nameToKey( "WOLWelcomeMenu.wnd:ButtonBuddies" ); buttonBuddies = TheWindowManager->winGetWindowFromId( parentWOLWelcome, buttonBuddiesID ); - buttonMyInfoID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLWelcomeMenu.wnd:ButtonMyInfo" ) ); + buttonMyInfoID = TheNameKeyGenerator->nameToKey( "WOLWelcomeMenu.wnd:ButtonMyInfo" ); buttonMyInfo = TheWindowManager->winGetWindowFromId( parentWOLWelcome, buttonMyInfoID ); - buttonLadderID = TheNameKeyGenerator->nameToKey( AsciiString( "WOLWelcomeMenu.wnd:ButtonLadder" ) ); + buttonLadderID = TheNameKeyGenerator->nameToKey( "WOLWelcomeMenu.wnd:ButtonLadder" ); buttonLadder = TheWindowManager->winGetWindowFromId( parentWOLWelcome, buttonLadderID ); if (TheFirewallHelper == NULL) { @@ -880,7 +880,7 @@ WindowMsgHandledType WOLWelcomeMenuSystem( GameWindow *window, UnsignedInt msg, } else if (controlID == buttonLadderID) { - TheShell->push(AsciiString("Menus/WOLLadderScreen.wnd")); + TheShell->push("Menus/WOLLadderScreen.wnd"); } break; } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/MessageBox.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/MessageBox.cpp index 44e0af8d12..998f9daee5 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/MessageBox.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/MessageBox.cpp @@ -132,10 +132,10 @@ WindowMsgHandledType MessageBoxSystem( GameWindow *window, UnsignedInt msg, { GameWindow *control = (GameWindow *)mData1; Int controlID = control->winGetWindowId(); - static NameKeyType buttonOkID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonOk" ) ); - static NameKeyType buttonYesID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonYes" ) ); - static NameKeyType buttonNoID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonNo" ) ); - static NameKeyType buttonCancelID = TheNameKeyGenerator->nameToKey( AsciiString( "MessageBox.wnd:ButtonCancel" ) ); + static NameKeyType buttonOkID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonOk" ); + static NameKeyType buttonYesID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonYes" ); + static NameKeyType buttonNoID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonNo" ); + static NameKeyType buttonCancelID = TheNameKeyGenerator->nameToKey( "MessageBox.wnd:ButtonCancel" ); WindowMessageBoxData *MsgBoxCallbacks = (WindowMessageBoxData *)window->winGetUserData(); if( controlID == buttonOkID ) @@ -216,10 +216,10 @@ WindowMsgHandledType QuitMessageBoxSystem( GameWindow *window, UnsignedInt msg, { GameWindow *control = (GameWindow *)mData1; Int controlID = control->winGetWindowId(); - static NameKeyType buttonOkID = TheNameKeyGenerator->nameToKey( AsciiString( "QuitMessageBox.wnd:ButtonOk" ) ); - static NameKeyType buttonYesID = TheNameKeyGenerator->nameToKey( AsciiString( "QuitMessageBox.wnd:ButtonYes" ) ); - static NameKeyType buttonNoID = TheNameKeyGenerator->nameToKey( AsciiString( "QuitMessageBox.wnd:ButtonNo" ) ); - static NameKeyType buttonCancelID = TheNameKeyGenerator->nameToKey( AsciiString( "QuitMessageBox.wnd:ButtonCancel" ) ); + static NameKeyType buttonOkID = TheNameKeyGenerator->nameToKey( "QuitMessageBox.wnd:ButtonOk" ); + static NameKeyType buttonYesID = TheNameKeyGenerator->nameToKey( "QuitMessageBox.wnd:ButtonYes" ); + static NameKeyType buttonNoID = TheNameKeyGenerator->nameToKey( "QuitMessageBox.wnd:ButtonNo" ); + static NameKeyType buttonCancelID = TheNameKeyGenerator->nameToKey( "QuitMessageBox.wnd:ButtonCancel" ); WindowMessageBoxData *MsgBoxCallbacks = (WindowMessageBoxData *)window->winGetUserData(); if( controlID == buttonOkID ) diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp index 523fc4de96..5596456e06 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp @@ -1386,7 +1386,7 @@ GameWindow *GameWindowManager::winCreate( GameWindow *parent, TheGlobalLanguageData->m_defaultWindowFont.bold) ); } else - window->winSetFont( winFindFont( AsciiString("Times New Roman"), 14, FALSE ) ); + window->winSetFont( winFindFont( "Times New Roman", 14, FALSE ) ); return window; @@ -1618,9 +1618,9 @@ GameWindow *GameWindowManager::gogoMessageBox(Int x, Int y, Int width, Int heigh GameWindow *trueParent = NULL; //Changed by Chris if(useLogo) - trueParent = winCreateFromScript( AsciiString("Menus/QuitMessageBox.wnd") ); + trueParent = winCreateFromScript( "Menus/QuitMessageBox.wnd" ); else - trueParent = winCreateFromScript( AsciiString("Menus/MessageBox.wnd") ); + trueParent = winCreateFromScript( "Menus/MessageBox.wnd" ); //Added By Chris AsciiString menuName; if(useLogo) @@ -2854,7 +2854,7 @@ void GameWindowManager::assignDefaultGadgetLook( GameWindow *gadget, TheGlobalLanguageData->m_defaultWindowFont.bold) ); } else - gadget->winSetFont( TheWindowManager->winFindFont( AsciiString("Times New Roman"), 14, FALSE ) ); + gadget->winSetFont( TheWindowManager->winFindFont( "Times New Roman", 14, FALSE ) ); } // if we don't want to assign default colors/images get out of here @@ -3802,7 +3802,7 @@ Bool GameWindowManager::initTestGUI( void ) TheWindowManager->winMakeColor( 235, 105, 255, 255 ), -1, 0 ); GadgetListBoxAddEntryText( window, UnicodeString(L"Natural"), TheWindowManager->winMakeColor( 105, 205, 45, 255 ), -1, 0 ); - window->winSetFont( TheFontLibrary->getFont( AsciiString("Times New Roman"), 12, FALSE ) ); + window->winSetFont( TheFontLibrary->getFont( "Times New Roman", 12, FALSE ) ); // make a listbox memset( &listData, 0, sizeof( ListboxData ) ); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitions.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitions.cpp index 9f67add4db..684b10dff8 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitions.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitions.cpp @@ -394,7 +394,7 @@ void GameWindowTransitionsHandler::load(void ) { INI ini; // Read from INI all the ControlBarSchemes - ini.loadFileDirectory( AsciiString( "Data\\INI\\WindowTransitions" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\WindowTransitions", INI_LOAD_OVERWRITE, NULL ); } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp index 748f1aa41c..8ca208be05 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp @@ -566,7 +566,7 @@ void IMEManager::init( void ) m_context = ImmCreateContext(); m_oldContext = ImmGetContext( ApplicationHWnd ); m_disabled = 0; - m_candidateWindow = TheWindowManager->winCreateFromScript( AsciiString("IMECandidateWindow.wnd")); + m_candidateWindow = TheWindowManager->winCreateFromScript( "IMECandidateWindow.wnd"); m_candidateWindow->winSetStatus(WIN_STATUS_ABOVE); if ( m_candidateWindow ) @@ -574,14 +574,14 @@ void IMEManager::init( void ) m_candidateWindow->winHide( TRUE ); // find text area window - NameKeyType id = TheNameKeyGenerator->nameToKey( AsciiString( "IMECandidateWindow.wnd:TextArea" ) ); + NameKeyType id = TheNameKeyGenerator->nameToKey( "IMECandidateWindow.wnd:TextArea" ); m_candidateTextArea = TheWindowManager->winGetWindowFromId(m_candidateWindow, id); // find arrows - id = TheNameKeyGenerator->nameToKey( AsciiString( "IMECandidateWindow.wnd:UpArrow" ) ); + id = TheNameKeyGenerator->nameToKey( "IMECandidateWindow.wnd:UpArrow" ); m_candidateUpArrow = TheWindowManager->winGetWindowFromId(m_candidateWindow, id); - id = TheNameKeyGenerator->nameToKey( AsciiString( "IMECandidateWindow.wnd:DownArrow" ) ); + id = TheNameKeyGenerator->nameToKey( "IMECandidateWindow.wnd:DownArrow" ); m_candidateDownArrow = TheWindowManager->winGetWindowFromId(m_candidateWindow, id); @@ -593,7 +593,7 @@ void IMEManager::init( void ) } } - m_statusWindow = TheWindowManager->winCreateFromScript( AsciiString("IMEStatusWindow.wnd")); + m_statusWindow = TheWindowManager->winCreateFromScript( "IMEStatusWindow.wnd"); if ( m_statusWindow ) { diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp index 2613bcf697..c05cace94a 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp @@ -391,22 +391,22 @@ void SinglePlayerLoadScreen::init( GameInfo *game ) //No music in SinglePlayerLoadScreen // create the layout of the load screen - m_loadScreen = TheWindowManager->winCreateFromScript( AsciiString( "Menus/SinglePlayerLoadScreen.wnd" ) ); + m_loadScreen = TheWindowManager->winCreateFromScript( "Menus/SinglePlayerLoadScreen.wnd" ); DEBUG_ASSERTCRASH(m_loadScreen, ("Can't initialize the single player loadscreen")); m_loadScreen->winHide(FALSE); m_loadScreen->winBringToTop(); // Mission *mission = TheCampaignManager->getCurrentMission(); // Store the pointer to the progress bar on the loadscreen - m_progressBar = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "SinglePlayerLoadScreen.wnd:ProgressLoad" ) )); + m_progressBar = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:ProgressLoad" )); DEBUG_ASSERTCRASH(m_progressBar, ("Can't initialize the progressbar for the single player loadscreen")); GadgetProgressBarSetProgress(m_progressBar, 0 ); - m_percent = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "SinglePlayerLoadScreen.wnd:Percent" ) )); + m_percent = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:Percent" )); DEBUG_ASSERTCRASH(m_percent, ("Can't initialize the m_percent for the single player loadscreen")); GadgetStaticTextSetText(m_percent,UnicodeString(L"0%")); m_percent->winHide(TRUE); - m_objectiveWin = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "SinglePlayerLoadScreen.wnd:ObjectivesWin" ) )); + m_objectiveWin = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:ObjectivesWin" )); DEBUG_ASSERTCRASH(m_objectiveWin, ("Can't initialize the m_objectiveWin for the single player loadscreen")); m_objectiveWin->winHide(TRUE); @@ -434,7 +434,7 @@ void SinglePlayerLoadScreen::init( GameInfo *game ) GadgetStaticTextSetText(m_unitDesc[i],TheGameText->fetch(mission->m_unitNames[i])); m_unitDesc[i]->winHide(TRUE); } - m_location = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "SinglePlayerLoadScreen.wnd:StaticTextCameoText3" ) )); + m_location = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:StaticTextCameoText3" )); DEBUG_ASSERTCRASH(m_location, ("Can't initialize the m_objectiveWin for the single player loadscreen")); m_location->winHide(TRUE); GadgetStaticTextSetText(m_location, TheGameText->fetch(mission->m_locationNameLabel)); @@ -446,34 +446,34 @@ void SinglePlayerLoadScreen::init( GameInfo *game ) m_currentObjectiveLineCharacter = 0; m_finishedObjectiveText = FALSE; /* - m_cameoWindow1 = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "SinglePlayerLoadScreen.wnd:WindowCameo1" ) )); + m_cameoWindow1 = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:WindowCameo1" )); DEBUG_ASSERTCRASH(m_cameoWindow1, ("Can't initialize the m_cameoWindow1 for the single player loadscreen")); m_cameoWindow1->winHide(TRUE); m_cameoWindow1->winEnable(FALSE); m_cameoWindow1->winSetEnabledImage(0, mission->m_cameoImage[0]); m_cameoWindow1->winSetDisabledImage(0, mission->m_cameoDisabledImage[0]); - m_cameoWindow2 = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "SinglePlayerLoadScreen.wnd:WindowCameo2" ) )); + m_cameoWindow2 = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:WindowCameo2" )); DEBUG_ASSERTCRASH(m_cameoWindow2, ("Can't initialize the m_cameoWindow2 for the single player loadscreen")); m_cameoWindow2->winHide(TRUE); m_cameoWindow2->winEnable(FALSE); m_cameoWindow2->winSetEnabledImage(0, mission->m_cameoImage[1]); m_cameoWindow2->winSetDisabledImage(0, mission->m_cameoDisabledImage[1]); - m_cameoWindow3 = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "SinglePlayerLoadScreen.wnd:WindowCameo3" ) )); + m_cameoWindow3 = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:WindowCameo3" )); DEBUG_ASSERTCRASH(m_cameoWindow3, ("Can't initialize the m_cameoWindow3 for the single player loadscreen")); m_cameoWindow3->winHide(TRUE); m_cameoWindow3->winEnable(FALSE); m_cameoWindow3->winSetEnabledImage(0, mission->m_cameoImage[2]); m_cameoWindow3->winSetDisabledImage(0, mission->m_cameoDisabledImage[2]); - m_headMovie = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "SinglePlayerLoadScreen.wnd:WindowHead" ) )); + m_headMovie = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:WindowHead" )); DEBUG_ASSERTCRASH(m_headMovie, ("Can't initialize the m_headMovie for the single player loadscreen")); m_headMovie->winHide(TRUE); - m_cameoFrame = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "SinglePlayerLoadScreen.wnd:WindowHiliteCameo" ) )); + m_cameoFrame = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:WindowHiliteCameo" )); DEBUG_ASSERTCRASH(m_cameoFrame, ("Can't initialize the m_cameoFrame for the single player loadscreen")); m_cameoFrame->winHide(TRUE); - m_cameoText = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "SinglePlayerLoadScreen.wnd:StaticTextCameoText" ) )); + m_cameoText = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:StaticTextCameoText" )); DEBUG_ASSERTCRASH(m_cameoText, ("Can't initialize the m_cameoText for the single player loadscreen")); */ @@ -508,7 +508,7 @@ void SinglePlayerLoadScreen::init( GameInfo *game ) // format the progress bar: USA to blue, GLA to green, China to red // and set the background image AsciiString campaignName = TheCampaignManager->getCurrentCampaign()->m_name; - GameWindow *backgroundWin = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "SinglePlayerLoadScreen.wnd:ParentSinglePlayerLoadScreen" ) )); + GameWindow *backgroundWin = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:ParentSinglePlayerLoadScreen" )); if (campaignName.compareNoCase("USA") == 0) { backgroundWin->winSetEnabledImage( 0, TheMappedImageCollection->findImageByName("MissionLoad_USA") ); @@ -854,7 +854,7 @@ void ChallengeLoadScreen::activatePieces( Int frame, const GeneralPersona *gener // m_overlayVsBackdrop->winSetEnabledImage( 0, TheMappedImageCollection->findImageByFilename(")) m_overlayVsBackdrop->winHide(FALSE); m_overlayVs->winHide(FALSE); - m_wndVideoManager->playMovie( m_overlayVs, AsciiString("VSSmall"), WINDOW_PLAY_MOVIE_SHOW_LAST_FRAME); + m_wndVideoManager->playMovie( m_overlayVs, "VSSmall", WINDOW_PLAY_MOVIE_SHOW_LAST_FRAME); // "Verses" TheAudio->addAudioEvent( &eventVS ); @@ -922,7 +922,7 @@ void ChallengeLoadScreen::activatePiecesMinSpec(const GeneralPersona *generalPla m_overlayVsBackdrop->winHide(FALSE); m_overlayVsBackdrop->winHide(FALSE); m_overlayVs->winHide(FALSE); - m_wndVideoManager->playMovie( m_overlayVs, AsciiString("VSSmall"), WINDOW_PLAY_MOVIE_SHOW_LAST_FRAME); + m_wndVideoManager->playMovie( m_overlayVs, "VSSmall", WINDOW_PLAY_MOVIE_SHOW_LAST_FRAME); } @@ -939,13 +939,13 @@ void ChallengeLoadScreen::init( GameInfo *game ) const GeneralPersona* generalOpponent = TheChallengeGenerals->getGeneralByGeneralName( mission->m_generalName ); // create the layout of the load screen - m_loadScreen = TheWindowManager->winCreateFromScript( AsciiString( "Menus/ChallengeLoadScreen.wnd" ) ); + m_loadScreen = TheWindowManager->winCreateFromScript( "Menus/ChallengeLoadScreen.wnd" ); DEBUG_ASSERTCRASH(m_loadScreen, ("Can't initialize the single player loadscreen")); m_loadScreen->winHide(FALSE); m_loadScreen->winBringToTop(); // Store the pointer to the progress bar on the loadscreen - m_progressBar = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "ChallengeLoadScreen.wnd:ProgressLoad" ) )); + m_progressBar = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:ProgressLoad" )); DEBUG_ASSERTCRASH(m_progressBar, ("Can't initialize the progressbar for the single player loadscreen")); GadgetProgressBarSetProgress(m_progressBar, 0 ); @@ -971,68 +971,68 @@ void ChallengeLoadScreen::init( GameInfo *game ) } // init overlays - NameKeyType namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:PortraitLeft")); + NameKeyType namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:PortraitLeft"); m_portraitLeft = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:PortraitRight")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:PortraitRight"); m_portraitRight = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:PortraitMovieLeft")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:PortraitMovieLeft"); m_portraitMovieLeft = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:PortraitMovieRight")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:PortraitMovieRight"); m_portraitMovieRight = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); -// namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:ReticleCrosshairs")); +// namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:ReticleCrosshairs"); // m_overlayReticleCrosshairs = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); /* - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:OuterCircleLine")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:OuterCircleLine"); m_overlayReticleCircleLineOuter = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:InnerCircleLine")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:InnerCircleLine"); m_overlayReticleCircleLineInner = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); */ - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:CircleAlphaOuter")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:CircleAlphaOuter"); m_overlayReticleCircleAlphaOuter = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:CircleAlphaInner")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:CircleAlphaInner"); m_overlayReticleCircleAlphaInner = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:VersusBackdrop")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:VersusBackdrop"); m_overlayVsBackdrop = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:OverlayVs")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:OverlayVs"); m_overlayVs = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:BioNameLeft")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:BioNameLeft"); m_bioNameLeft = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); -// namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:BioDOBLeft")); +// namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:BioDOBLeft"); // m_bioAgeLeft = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:BioBirthplaceLeft")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:BioBirthplaceLeft"); m_bioBirthplaceLeft = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:BioStrategyLeft")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:BioStrategyLeft"); m_bioStrategyLeft = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:BigNameEntryLeft")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:BigNameEntryLeft"); m_bioBigNameEntryLeft = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:BioNameEntryLeft")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:BioNameEntryLeft"); m_bioNameEntryLeft = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); -// namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:BioDOBEntryLeft")); +// namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:BioDOBEntryLeft"); // m_bioAgeEntryLeft = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:BioBirthplaceEntryLeft")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:BioBirthplaceEntryLeft"); m_bioBirthplaceEntryLeft = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:BioStrategyEntryLeft")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:BioStrategyEntryLeft"); m_bioStrategyEntryLeft = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:BioNameRight")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:BioNameRight"); m_bioNameRight = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); -// namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:BioDOBRight")); +// namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:BioDOBRight"); // m_bioAgeRight = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:BioBirthplaceRight")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:BioBirthplaceRight"); m_bioBirthplaceRight = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:BioStrategyRight")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:BioStrategyRight"); m_bioStrategyRight = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:BigNameEntryRight")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:BigNameEntryRight"); m_bioBigNameEntryRight = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:BioNameEntryRight")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:BioNameEntryRight"); m_bioNameEntryRight = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); -// namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:BioDOBEntryRight")); +// namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:BioDOBEntryRight"); // m_bioAgeEntryRight = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:BioBirthplaceEntryRight")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:BioBirthplaceEntryRight"); m_bioBirthplaceEntryRight = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); - namekey = TheNameKeyGenerator->nameToKey( AsciiString("ChallengeLoadScreen.wnd:BioStrategyEntryRight")); + namekey = TheNameKeyGenerator->nameToKey( "ChallengeLoadScreen.wnd:BioStrategyEntryRight"); m_bioStrategyEntryRight = TheWindowManager->winGetWindowFromId( m_loadScreen, namekey ); @@ -1182,13 +1182,13 @@ void ShellGameLoadScreen::init( GameInfo *game ) // create the layout of the load screen - m_loadScreen = TheWindowManager->winCreateFromScript( AsciiString( "Menus/ShellGameLoadScreen.wnd" ) ); + m_loadScreen = TheWindowManager->winCreateFromScript( "Menus/ShellGameLoadScreen.wnd" ); DEBUG_ASSERTCRASH(m_loadScreen, ("Can't initialize the ShellGame loadscreen")); m_loadScreen->winHide(FALSE); m_loadScreen->winBringToTop(); // Store the pointer to the progress bar on the loadscreen - m_progressBar = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "ShellGameLoadScreen.wnd:ProgressLoad" ) )); + m_progressBar = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "ShellGameLoadScreen.wnd:ProgressLoad" )); DEBUG_ASSERTCRASH(m_progressBar, ("Can't initialize the progressbar for the single player loadscreen")); GadgetProgressBarSetProgress(m_progressBar, 0 ); m_progressBar->winHide(TRUE); @@ -1198,7 +1198,7 @@ void ShellGameLoadScreen::init( GameInfo *game ) m_loadScreen->winSetEnabledImage(0, TheMappedImageCollection->findImageByName("TitleScreen")); TheWritableGlobalData->m_breakTheMovie = FALSE; - GameWindow *win = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( AsciiString( "ShellGameLoadScreen.wnd:StaticTextLegal" ) )); + GameWindow *win = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "ShellGameLoadScreen.wnd:StaticTextLegal" )); if(win) win->winHide(FALSE); firstLoad = FALSE; @@ -1269,7 +1269,7 @@ MultiPlayerLoadScreen::~MultiPlayerLoadScreen( void ) void MultiPlayerLoadScreen::init( GameInfo *game ) { // create the layout of the load screen - m_loadScreen = TheWindowManager->winCreateFromScript( AsciiString( "Menus/MultiplayerLoadScreen.wnd" ) ); + m_loadScreen = TheWindowManager->winCreateFromScript( "Menus/MultiplayerLoadScreen.wnd" ); DEBUG_ASSERTCRASH(m_loadScreen, ("Can't initialize the Multiplayer loadscreen")); m_loadScreen->winHide(FALSE); m_loadScreen->winBringToTop(); @@ -1310,7 +1310,7 @@ void MultiPlayerLoadScreen::init( GameInfo *game ) m_portraitLocalGeneral->winSetEnabledImage( 0, portrait); m_featuresLocalGeneral = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "MultiplayerLoadScreen.wnd:LocalGeneralFeatures")); AsciiString features = pt->getGeneralFeatures(); - GadgetStaticTextSetText( m_featuresLocalGeneral, TheGameText->fetch( features.isEmpty() ? AsciiString( "GUI:PlayerObserver" ) : pt->getGeneralFeatures() ) ); + GadgetStaticTextSetText( m_featuresLocalGeneral, TheGameText->fetch( features.isEmpty() ? "GUI:PlayerObserver" : pt->getGeneralFeatures() ) ); m_nameLocalGeneral = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "MultiplayerLoadScreen.wnd:LocalGeneralName")); GadgetStaticTextSetText( m_nameLocalGeneral, localName ); @@ -1542,7 +1542,7 @@ extern Int GetAdditionalDisconnectsFromUserFile(Int playerID); void GameSpyLoadScreen::init( GameInfo *game ) { // create the layout of the load screen - m_loadScreen = TheWindowManager->winCreateFromScript( AsciiString( "Menus/GameSpyLoadScreen.wnd" ) ); + m_loadScreen = TheWindowManager->winCreateFromScript( "Menus/GameSpyLoadScreen.wnd" ); DEBUG_ASSERTCRASH(m_loadScreen, ("Can't initialize the Multiplayer loadscreen")); m_loadScreen->winHide(FALSE); m_loadScreen->winBringToTop(); @@ -1587,7 +1587,7 @@ GameSlot *lSlot = game->getSlot(game->getLocalSlotNum()); m_portraitLocalGeneral->winSetEnabledImage( 0, portrait); m_featuresLocalGeneral = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "GameSpyLoadScreen.wnd:LocalGeneralFeatures")); AsciiString features = pt->getGeneralFeatures(); - GadgetStaticTextSetText( m_featuresLocalGeneral, TheGameText->fetch( features.isEmpty() ? AsciiString( "GUI:PlayerObserver" ) : pt->getGeneralFeatures() ) ); + GadgetStaticTextSetText( m_featuresLocalGeneral, TheGameText->fetch( features.isEmpty() ? "GUI:PlayerObserver" : pt->getGeneralFeatures() ) ); m_nameLocalGeneral = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "GameSpyLoadScreen.wnd:LocalGeneralName")); GadgetStaticTextSetText( m_nameLocalGeneral, localName ); @@ -1891,7 +1891,7 @@ MapTransferLoadScreen::~MapTransferLoadScreen( void ) void MapTransferLoadScreen::init( GameInfo *game ) { // create the layout of the load screen - m_loadScreen = TheWindowManager->winCreateFromScript( AsciiString( "Menus/MapTransferScreen.wnd" ) ); + m_loadScreen = TheWindowManager->winCreateFromScript( "Menus/MapTransferScreen.wnd" ); DEBUG_ASSERTCRASH(m_loadScreen, ("Can't initialize the map transfer loadscreen")); if (!m_loadScreen) return; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp index b12a9eb363..20299ecdd8 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp @@ -150,8 +150,8 @@ void Shell::init( void ) { INI ini; // Read from INI all the ShellMenuScheme - ini.loadFileDirectory( AsciiString( "Data\\INI\\Default\\ShellMenuScheme" ), INI_LOAD_OVERWRITE, NULL ); - ini.loadFileDirectory( AsciiString( "Data\\INI\\ShellMenuScheme" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Default\\ShellMenuScheme", INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\ShellMenuScheme", INI_LOAD_OVERWRITE, NULL ); if( m_schemeManager ) m_schemeManager->init(); @@ -525,7 +525,7 @@ void Shell::showShell( Bool runInit ) Profile::StopRange("init"); #endif //else - push( AsciiString("Menus/MainMenu.wnd") ); + push( "Menus/MainMenu.wnd" ); } m_isShellActive = TRUE; } @@ -849,7 +849,7 @@ WindowLayout *Shell::getSaveLoadMenuLayout( void ) // if layout has not been created, create it now if( m_saveLoadMenuLayout == NULL ) - m_saveLoadMenuLayout = TheWindowManager->winCreateLayout( AsciiString( "Menus/PopupSaveLoad.wnd" ) ); + m_saveLoadMenuLayout = TheWindowManager->winCreateLayout( "Menus/PopupSaveLoad.wnd" ); // sanity DEBUG_ASSERTCRASH( m_saveLoadMenuLayout, ("Unable to create save/load menu layout") ); @@ -866,7 +866,7 @@ WindowLayout *Shell::getPopupReplayLayout( void ) // if layout has not been created, create it now if( m_popupReplayLayout == NULL ) - m_popupReplayLayout = TheWindowManager->winCreateLayout( AsciiString( "Menus/PopupReplay.wnd" ) ); + m_popupReplayLayout = TheWindowManager->winCreateLayout( "Menus/PopupReplay.wnd" ); // sanity DEBUG_ASSERTCRASH( m_popupReplayLayout, ("Unable to create replay save menu layout") ); @@ -883,7 +883,7 @@ WindowLayout *Shell::getOptionsLayout( Bool create ) // if layout has not been created, create it now if ((m_optionsLayout == NULL) && (create == TRUE)) { - m_optionsLayout = TheWindowManager->winCreateLayout( AsciiString( "Menus/OptionsMenu.wnd" ) ); + m_optionsLayout = TheWindowManager->winCreateLayout( "Menus/OptionsMenu.wnd" ); // sanity DEBUG_ASSERTCRASH( m_optionsLayout, ("Unable to create options menu layout") ); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Shell/ShellMenuScheme.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Shell/ShellMenuScheme.cpp index 795082bbba..276f0f5e0d 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Shell/ShellMenuScheme.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Shell/ShellMenuScheme.cpp @@ -279,8 +279,8 @@ void ShellMenuSchemeManager::init( void ) { INI ini; // Read from INI all the ControlBarSchemes - ini.loadFileDirectory( AsciiString( "Data\\INI\\Default\\ShellMenuScheme" ), INI_LOAD_OVERWRITE, NULL ); - ini.loadFileDirectory( AsciiString( "Data\\INI\\ShellMenuScheme" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Default\\ShellMenuScheme", INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\ShellMenuScheme", INI_LOAD_OVERWRITE, NULL ); } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp index c616deed95..ac7277eda4 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp @@ -1213,7 +1213,7 @@ InGameUI::~InGameUI() void InGameUI::init( void ) { INI ini; - ini.loadFileDirectory( AsciiString( "Data\\INI\\InGameUI" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\InGameUI", INI_LOAD_OVERWRITE, NULL ); //override INI values with language localized values: if (TheGlobalLanguageData) @@ -4103,7 +4103,7 @@ void InGameUI::expireHint( HintType type, UnsignedInt hintIndex ) void InGameUI::createControlBar( void ) { - TheWindowManager->winCreateFromScript( AsciiString("ControlBar.wnd") ); + TheWindowManager->winCreateFromScript( "ControlBar.wnd" ); HideControlBar(); /* // hide all windows created from this layout @@ -4120,7 +4120,7 @@ void InGameUI::createControlBar( void ) void InGameUI::createReplayControl( void ) { - m_replayWindow = TheWindowManager->winCreateFromScript( AsciiString("ReplayControl.wnd") ); + m_replayWindow = TheWindowManager->winCreateFromScript( "ReplayControl.wnd" ); /* // hide all windows created from this layout @@ -4211,7 +4211,7 @@ void InGameUI::playCameoMovie( const AsciiString& movieName ) stopCameoMovie(); return; } - GameWindow *window = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( AsciiString("ControlBar.wnd:RightHUD") )); + GameWindow *window = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( "ControlBar.wnd:RightHUD" )); WinInstanceData *winData = window->winGetInstanceData(); winData->setVideoBuffer(m_cameoVideoBuffer); // window->winHide(FALSE); @@ -4222,8 +4222,8 @@ void InGameUI::playCameoMovie( const AsciiString& movieName ) void InGameUI::stopCameoMovie( void ) { //RightHUD - //GameWindow *window = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( AsciiString("ControlBar.wnd:CameoMovieWindow") )); - GameWindow *window = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( AsciiString("ControlBar.wnd:RightHUD") )); + //GameWindow *window = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( "ControlBar.wnd:CameoMovieWindow" )); + GameWindow *window = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( "ControlBar.wnd:RightHUD" )); // window->winHide(FALSE); WinInstanceData *winData = window->winGetInstanceData(); winData->setVideoBuffer(NULL); @@ -5274,7 +5274,7 @@ void InGameUI::DEBUG_addFloatingText(const AsciiString& text, const Coord3D * po translate.translate(text); newFTD->m_text = translate; newFTD->m_dString->setText(translate); - newFTD->m_dString->setFont(TheWindowManager->winFindFont( AsciiString("Arial"), POINTSIZE, FALSE )); + newFTD->m_dString->setFont(TheWindowManager->winFindFont( "Arial", POINTSIZE, FALSE )); if(m_floatingTextTimeOut <= 0) newFTD->m_frameTimeOut = TheGameLogic->getFrame() + DEFAULT_FLOATING_TEXT_TIMEOUT; @@ -5439,7 +5439,7 @@ void InGameUI::popupMessage( const AsciiString& identifier, Int x, Int y, Int wi if( pause ) TheGameLogic->setGamePaused(TRUE, pauseMusic); - m_popupMessageData->layout = TheWindowManager->winCreateLayout(AsciiString("InGamePopupMessage.wnd")); + m_popupMessageData->layout = TheWindowManager->winCreateLayout("InGamePopupMessage.wnd"); m_popupMessageData->layout->runInit(); } @@ -5892,7 +5892,7 @@ void InGameUI::resetIdleWorker( void ) void InGameUI::recreateControlBar( void ) { - GameWindow *win = TheWindowManager->winGetWindowFromId(NULL, TheNameKeyGenerator->nameToKey(AsciiString("ControlBar.wnd"))); + GameWindow *win = TheWindowManager->winGetWindowFromId(NULL, TheNameKeyGenerator->nameToKey("ControlBar.wnd")); deleteInstance(win); m_idleWorkerWin = NULL; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp index 8321ab2469..27fa57927b 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp @@ -567,7 +567,7 @@ the Win32 version of the mouse (by preloading resources before D3D device is cre void Mouse::parseIni(void) { INI ini; - ini.loadFileDirectory( AsciiString( "Data\\INI\\Mouse" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Mouse", INI_LOAD_OVERWRITE, NULL ); } //------------------------------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MapUtil.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MapUtil.cpp index 2d8c9dd65a..a99f1cdc36 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/MapUtil.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MapUtil.cpp @@ -158,7 +158,7 @@ static Bool ParseObjectDataChunk(DataChunkInput &file, DataChunkInfo *info, void static Bool ParseObjectsDataChunk(DataChunkInput &file, DataChunkInfo *info, void *userData) { file.m_currentObject = NULL; - file.registerParser( AsciiString("Object"), info->label, ParseObjectDataChunk ); + file.registerParser( "Object", info->label, ParseObjectDataChunk ); return (file.parse(userData)); } @@ -230,9 +230,9 @@ static Bool loadMap( AsciiString filename ) m_waypoints = NEW WaypointMap; - file.registerParser( AsciiString("HeightMapData"), AsciiString::TheEmptyString, ParseSizeOnlyInChunk ); - file.registerParser( AsciiString("WorldInfo"), AsciiString::TheEmptyString, ParseWorldDictDataChunk ); - file.registerParser( AsciiString("ObjectsList"), AsciiString::TheEmptyString, ParseObjectsDataChunk ); + file.registerParser( "HeightMapData", AsciiString::TheEmptyString, ParseSizeOnlyInChunk ); + file.registerParser( "WorldInfo", AsciiString::TheEmptyString, ParseWorldDictDataChunk ); + file.registerParser( "ObjectsList", AsciiString::TheEmptyString, ParseObjectsDataChunk ); if (!file.parse(NULL)) { throw(ERROR_CORRUPT_FILE_FORMAT); } @@ -314,7 +314,7 @@ const char *const MapCache::m_mapCacheName = "MapCache.ini"; AsciiString MapCache::getMapDir() const { - return AsciiString("Maps"); + return "Maps"; } AsciiString MapCache::getUserMapDir() const @@ -326,7 +326,7 @@ AsciiString MapCache::getUserMapDir() const AsciiString MapCache::getMapExtension() const { - return AsciiString("map"); + return "map"; } void MapCache::writeCacheINI( const AsciiString &mapDir ) @@ -1254,7 +1254,7 @@ Image *getMapPreviewImage( AsciiString mapName ) DataChunkInput file( pStrm ); if (file.isValidFileType()) { // Backwards compatible files aren't valid data chunk files. // Read the waypoints. - file.registerParser( AsciiString("MapPreview"), AsciiString::TheEmptyString, parseMapPreviewChunk ); + file.registerParser( "MapPreview", AsciiString::TheEmptyString, parseMapPreviewChunk ); if (!file.parse(NULL)) { DEBUG_ASSERTCRASH(false,("Unable to read MapPreview info.")); deleteInstance(mapPreviewImage); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp index a4b56d395b..c4056a6c92 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp @@ -3368,7 +3368,7 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage Bool hide = false; if (TheWindowManager) { - Int id = (Int)TheNameKeyGenerator->nameToKey(AsciiString("ControlBar.wnd:ControlBarParent")); + Int id = (Int)TheNameKeyGenerator->nameToKey("ControlBar.wnd:ControlBarParent"); GameWindow *window = TheWindowManager->winGetWindowFromId(NULL, id); if (window) @@ -4210,7 +4210,7 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage /* if (TheWindowManager && TheNameKeyGenerator) { - GameWindow *motd = TheWindowManager->winGetWindowFromId(NULL, (Int)TheNameKeyGenerator->nameToKey(AsciiString("MOTD.wnd:MOTD"))); + GameWindow *motd = TheWindowManager->winGetWindowFromId(NULL, (Int)TheNameKeyGenerator->nameToKey("MOTD.wnd:MOTD")); if (motd) motd->winHide(!motd->winIsHidden()); }*/ @@ -4259,7 +4259,7 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage Bool hide = false; if (TheWindowManager) { - Int id = (Int)TheNameKeyGenerator->nameToKey(AsciiString("ControlBar.wnd:ControlBarParent")); + Int id = (Int)TheNameKeyGenerator->nameToKey("ControlBar.wnd:ControlBarParent"); GameWindow *window = TheWindowManager->winGetWindowFromId(NULL, id); if (window) diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/CampaignManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/CampaignManager.cpp index d6b3a3ded8..c04aadbe0e 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/CampaignManager.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/CampaignManager.cpp @@ -244,7 +244,7 @@ void CampaignManager::init( void ) { INI ini; // Read from INI all the CampaignManager - ini.loadFileDirectory( AsciiString( "Data\\INI\\Campaign" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Campaign", INI_LOAD_OVERWRITE, NULL ); } //----------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp index e3686a05a9..4d413443d1 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp @@ -2865,7 +2865,7 @@ void ParticleSystemManager::init( void ) { /// Read INI data and build templates INI ini; - ini.loadFileDirectory( AsciiString( "Data\\INI\\ParticleSystem" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\ParticleSystem", INI_LOAD_OVERWRITE, NULL ); // sanity, our lists must be empty!! for( Int i = 0; i < NUM_PARTICLE_PRIORITIES; ++i ) diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Terrain/TerrainRoads.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Terrain/TerrainRoads.cpp index 3d05caf6b2..ceae1abd30 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Terrain/TerrainRoads.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Terrain/TerrainRoads.cpp @@ -353,7 +353,7 @@ TerrainRoadType *TerrainRoadCollection::newRoad( AsciiString name ) road->friend_setBridge( FALSE ); // set defaults from the default road - TerrainRoadType *defaultRoad = findRoad( AsciiString( "DefaultRoad" ) ); + TerrainRoadType *defaultRoad = findRoad( "DefaultRoad" ); if( defaultRoad ) { @@ -389,7 +389,7 @@ TerrainRoadType *TerrainRoadCollection::newBridge( AsciiString name ) bridge->friend_setBridge( TRUE ); // set defaults from the default bridge - TerrainRoadType *defaultBridge = findBridge( AsciiString( "DefaultBridge" ) ); + TerrainRoadType *defaultBridge = findBridge( "DefaultBridge" ); if( defaultBridge ) { diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/SidesList.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/SidesList.cpp index 99be0c2193..b3ffc1c6ca 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/SidesList.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/SidesList.cpp @@ -296,7 +296,7 @@ Bool SidesList::ParseSidesDataChunk(DataChunkInput &file, DataChunkInfo *info, v } } - file.registerParser( AsciiString("PlayerScriptsList"), info->label, ScriptList::ParseScriptsDataChunk ); + file.registerParser( "PlayerScriptsList", info->label, ScriptList::ParseScriptsDataChunk ); if (!file.parse(NULL)) { throw(ERROR_CORRUPT_FILE_FORMAT); } @@ -524,9 +524,9 @@ void SidesList::prepareForMP_or_Skirmish(void) if (theInputStream.open(path)) { ChunkInputStream *pStrm = &theInputStream; DataChunkInput file( pStrm ); - file.registerParser( AsciiString("PlayerScriptsList"), AsciiString::TheEmptyString, ScriptList::ParseScriptsDataChunk ); - file.registerParser( AsciiString("ScriptsPlayers"), AsciiString::TheEmptyString, ParsePlayersDataChunk ); - file.registerParser( AsciiString("ScriptTeams"), AsciiString::TheEmptyString, ParseTeamsDataChunk ); + file.registerParser( "PlayerScriptsList", AsciiString::TheEmptyString, ScriptList::ParseScriptsDataChunk ); + file.registerParser( "ScriptsPlayers", AsciiString::TheEmptyString, ParsePlayersDataChunk ); + file.registerParser( "ScriptTeams", AsciiString::TheEmptyString, ParseTeamsDataChunk ); if (!file.parse(this)) { DEBUG_LOG(("ERROR - Unable to read in skirmish scripts.")); return; @@ -826,10 +826,10 @@ Bool SidesList::validateSides() tdict->setAsciiString(TheKey_teamOwner, AsciiString::TheEmptyString); modified = true; } -// if (tdict->getType(NAMEKEY(AsciiString("teamAllies"))) != Dict::DICT_NONE) -// tdict->remove(NAMEKEY(AsciiString("teamAllies"))); -// if (tdict->getType(NAMEKEY(AsciiString("teamEnemies"))) != Dict::DICT_NONE) -// tdict->remove(NAMEKEY(AsciiString("teamEnemies"))); +// if (tdict->getType(NAMEKEY("teamAllies")) != Dict::DICT_NONE) +// tdict->remove(NAMEKEY("teamAllies")); +// if (tdict->getType(NAMEKEY("teamEnemies")) != Dict::DICT_NONE) +// tdict->remove(NAMEKEY("teamEnemies")); } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp index 0d4cff7dc1..5f4fba3f77 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp @@ -1272,7 +1272,7 @@ Bool TerrainLogic::loadMap( AsciiString filename, Bool query ) DataChunkInput file( pStrm ); if (file.isValidFileType()) { // Backwards compatible files aren't valid data chunk files. // Read the waypoints. - file.registerParser( AsciiString("WaypointsList"), AsciiString::TheEmptyString, parseWaypointDataChunk ); + file.registerParser( "WaypointsList", AsciiString::TheEmptyString, parseWaypointDataChunk ); if (!file.parse(this)) { DEBUG_CRASH(("Unable to read waypoint info.")); return false; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp index b768794a4b..d9fd016690 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp @@ -525,7 +525,7 @@ void ScriptList::deleteGroup(ScriptGroup *pGrp) Bool ScriptList::ParseScriptsDataChunk(DataChunkInput &file, DataChunkInfo *info, void *userData) { Int i; - file.registerParser( AsciiString("ScriptList"), info->label, ScriptList::ParseScriptListDataChunk ); + file.registerParser( "ScriptList", info->label, ScriptList::ParseScriptListDataChunk ); DEBUG_ASSERTCRASH(s_numInReadList==0, ("Leftover scripts floating aroung.")); for (i=0; ireadLists[pInfo->numLists] = newInstance(ScriptList); Int cur = pInfo->numLists; pInfo->numLists++; - file.registerParser( AsciiString("Script"), info->label, Script::ParseScriptFromListDataChunk ); - file.registerParser( AsciiString("ScriptGroup"), info->label, ScriptGroup::ParseGroupDataChunk ); + file.registerParser( "Script", info->label, Script::ParseScriptFromListDataChunk ); + file.registerParser( "ScriptGroup", info->label, ScriptGroup::ParseGroupDataChunk ); return file.parse(pInfo->readLists[cur]); } @@ -888,7 +888,7 @@ Bool ScriptGroup::ParseGroupDataChunk(DataChunkInput &file, DataChunkInfo *info, pGroup->m_isGroupSubroutine= file.readByte(); } pList->addGroup(pGroup, AT_END); - file.registerParser( AsciiString("Script"), info->label, Script::ParseScriptFromGroupDataChunk ); + file.registerParser( "Script", info->label, Script::ParseScriptFromGroupDataChunk ); return file.parse(pGroup); } @@ -1253,9 +1253,9 @@ Script *Script::ParseScript(DataChunkInput &file, unsigned short version) if (version>=K_SCRIPT_DATA_VERSION_2) { pScript->m_delayEvaluationSeconds = file.readInt(); } - file.registerParser( AsciiString("OrCondition"), AsciiString("Script"), OrCondition::ParseOrConditionDataChunk ); - file.registerParser( AsciiString("ScriptAction"), AsciiString("Script"), ScriptAction::ParseActionDataChunk ); - file.registerParser( AsciiString("ScriptActionFalse"), AsciiString("Script"), ScriptAction::ParseActionFalseDataChunk ); + file.registerParser( "OrCondition", "Script", OrCondition::ParseOrConditionDataChunk ); + file.registerParser( "ScriptAction", "Script", ScriptAction::ParseActionDataChunk ); + file.registerParser( "ScriptActionFalse", "Script", ScriptAction::ParseActionFalseDataChunk ); if (! file.parse(pScript) ) { return NULL; @@ -1449,7 +1449,7 @@ Bool OrCondition::ParseOrConditionDataChunk(DataChunkInput &file, DataChunkInfo } else { pScript->setOrCondition(pOrCondition); } - file.registerParser( AsciiString("Condition"), info->label, Condition::ParseConditionDataChunk ); + file.registerParser( "Condition", info->label, Condition::ParseConditionDataChunk ); return file.parse(pOrCondition); } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/CrateSystem.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/CrateSystem.cpp index e04166f564..baf563ea46 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/CrateSystem.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/CrateSystem.cpp @@ -119,7 +119,7 @@ CrateTemplate *CrateSystem::newCrateTemplate( AsciiString name ) CrateTemplate *ct = newInstance(CrateTemplate); // if the default template is present, get it and copy over any data to the new template - const CrateTemplate *defaultCT = findCrateTemplate(AsciiString("DefaultCrate")); + const CrateTemplate *defaultCT = findCrateTemplate("DefaultCrate"); if(defaultCT) { *ct = *defaultCT; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp index 1275f07557..a1d704c3be 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp @@ -1583,7 +1583,7 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) { ChunkInputStream *pStrm = &theInputStream; DataChunkInput file( pStrm ); - file.registerParser( AsciiString("PlayerScriptsList"), AsciiString::TheEmptyString, ScriptList::ParseScriptsDataChunk ); + file.registerParser( "PlayerScriptsList", AsciiString::TheEmptyString, ScriptList::ParseScriptsDataChunk ); if (!file.parse(NULL)) { DEBUG_LOG(("ERROR - Unable to read in multiplayer scripts.")); return; @@ -2270,7 +2270,7 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) if (!TheGlobalData->m_headless) { if(TheShell->getScreenCount() == 0) - TheShell->push( AsciiString("Menus/MainMenu.wnd") ); + TheShell->push( "Menus/MainMenu.wnd" ); else if (TheShell->top()) { TheShell->top()->hide(FALSE); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp index 8b18e615d1..814fd70de7 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp @@ -1470,7 +1470,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // place the sound for putting a building down - static AudioEventRTS placeBuilding(AsciiString("PlaceBuilding")); + static AudioEventRTS placeBuilding("PlaceBuilding"); placeBuilding.setObjectID(constructorObject->getID()); TheAudio->addAudioEvent( &placeBuilding ); diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DControlBar.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DControlBar.cpp index 2992a4c9e0..5cf8d3c4f6 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DControlBar.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DControlBar.cpp @@ -624,13 +624,13 @@ void W3DCommandBarBackgroundDraw( GameWindow *window, WinInstanceData *instData ControlBarSchemeManager *man = TheControlBar->getControlBarSchemeManager(); if(!man) return; - static NameKeyType winNamekey = TheNameKeyGenerator->nameToKey( AsciiString( "ControlBar.wnd:BackgroundMarker" ) ); + static NameKeyType winNamekey = TheNameKeyGenerator->nameToKey( "ControlBar.wnd:BackgroundMarker" ); GameWindow *win = TheWindowManager->winGetWindowFromId(NULL,winNamekey); static ICoord2D basePos; if(!win) { return; - //win = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( AsciiString( "ControlBar.wnd:BackgroundMarker" ) )); + //win = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( "ControlBar.wnd:BackgroundMarker" )); } TheControlBar->getBackgroundMarkerPos(&basePos.x, &basePos.y); ICoord2D pos, offset; @@ -649,13 +649,13 @@ void W3DCommandBarForegroundDraw( GameWindow *window, WinInstanceData *instData if(!man) return; - static NameKeyType winNamekey = TheNameKeyGenerator->nameToKey( AsciiString( "ControlBar.wnd:BackgroundMarker" ) ); + static NameKeyType winNamekey = TheNameKeyGenerator->nameToKey( "ControlBar.wnd:BackgroundMarker" ); GameWindow *win = TheWindowManager->winGetWindowFromId(NULL,winNamekey); static ICoord2D basePos; if(!win) { return; - //win = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( AsciiString( "ControlBar.wnd:BackgroundMarker" ) )); + //win = TheWindowManager->winGetWindowFromId(NULL,TheNameKeyGenerator->nameToKey( "ControlBar.wnd:BackgroundMarker" )); } TheControlBar->getForegroundMarkerPos(&basePos.x, &basePos.y); ICoord2D pos, offset; diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DMainMenu.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DMainMenu.cpp index 15f0672510..a81ccef2ac 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DMainMenu.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DMainMenu.cpp @@ -916,9 +916,9 @@ void W3DMainMenuInit( WindowLayout *layout, void *userData ) NameKeyType buttonUSAID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonUSA" ); NameKeyType buttonGLAID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonGLA" ); NameKeyType buttonChinaID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonChina" ); - NameKeyType skirmishID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonSkirmish") ); - NameKeyType onlineID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonOnline") ); - NameKeyType networkID = TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:ButtonNetwork") ); + NameKeyType skirmishID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonSkirmish" ); + NameKeyType onlineID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonOnline" ); + NameKeyType networkID = TheNameKeyGenerator->nameToKey( "MainMenu.wnd:ButtonNetwork" ); GameWindow *button = TheWindowManager->winGetWindowFromId( parent, skirmishID ); if (button) @@ -984,7 +984,7 @@ void W3DMainMenuInit( WindowLayout *layout, void *userData ) if(win) win->winSetDrawFunc(W3DMainMenuButtonDropShadowDraw); - GameWindow *clipRegionWin = TheWindowManager->winGetWindowFromId( parent, TheNameKeyGenerator->nameToKey( AsciiString("MainMenu.wnd:MapBorder") )); + GameWindow *clipRegionWin = TheWindowManager->winGetWindowFromId( parent, TheNameKeyGenerator->nameToKey( "MainMenu.wnd:MapBorder" )); Int x,y,width,height; clipRegionWin->winGetScreenPosition(&x, &y); clipRegionWin->winGetSize(&width, &height); diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/W3DGameWindow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/W3DGameWindow.cpp index 385ef02813..dbabe8bfe5 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/W3DGameWindow.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/W3DGameWindow.cpp @@ -82,40 +82,40 @@ static void initBorders( void ) { borderPieces[ BORDER_CORNER_UL ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderCornerUL" ) ); + TheMappedImageCollection->findImageByName( "BorderCornerUL" ); borderPieces[ BORDER_CORNER_UR ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderCornerUR" ) ); + TheMappedImageCollection->findImageByName( "BorderCornerUR" ); borderPieces[ BORDER_CORNER_LL ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderCornerLL" ) ); + TheMappedImageCollection->findImageByName( "BorderCornerLL" ); borderPieces[ BORDER_CORNER_LR ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderCornerLR" ) ); + TheMappedImageCollection->findImageByName( "BorderCornerLR" ); borderPieces[ BORDER_VERTICAL_LEFT ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderLeft" ) ); + TheMappedImageCollection->findImageByName( "BorderLeft" ); borderPieces[ BORDER_VERTICAL_LEFT_SHORT ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderLeftShort" ) ); + TheMappedImageCollection->findImageByName( "BorderLeftShort" ); borderPieces[ BORDER_HORIZONTAL_TOP ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderTop" ) ); + TheMappedImageCollection->findImageByName( "BorderTop" ); borderPieces[ BORDER_HORIZONTAL_TOP_SHORT ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderTopShort" ) ); + TheMappedImageCollection->findImageByName( "BorderTopShort" ); borderPieces[ BORDER_VERTICAL_RIGHT ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderRight" ) ); + TheMappedImageCollection->findImageByName( "BorderRight" ); borderPieces[ BORDER_VERTICAL_RIGHT_SHORT ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderRightShort" ) ); + TheMappedImageCollection->findImageByName( "BorderRightShort" ); borderPieces[ BORDER_HORIZONTAL_BOTTOM ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderBottom" ) ); + TheMappedImageCollection->findImageByName( "BorderBottom" ); borderPieces[ BORDER_HORIZONTAL_BOTTOM_SHORT ] = - TheMappedImageCollection->findImageByName( AsciiString( "BorderBottomShort" ) ); + TheMappedImageCollection->findImageByName( "BorderBottomShort" ); bordersInit = TRUE; diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp index 9ed1b12fd9..08ea00f639 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp @@ -822,7 +822,7 @@ void W3DDisplay::init( void ) TheGlobalLanguageData->m_nativeDebugDisplay.bold); } else - font=TheFontLibrary->getFont( AsciiString("FixedSys"), 8, FALSE ); + font=TheFontLibrary->getFont( "FixedSys", 8, FALSE ); m_nativeDebugDisplay->setFont( font ); m_nativeDebugDisplay->setFontHeight( 13 ); @@ -941,7 +941,7 @@ void W3DDisplay::gatherDebugStats( void ) TheGlobalLanguageData->m_nativeDebugDisplay.bold); } else - font = TheFontLibrary->getFont( AsciiString("FixedSys"), 8, FALSE ); + font = TheFontLibrary->getFont( "FixedSys", 8, FALSE ); for (int i = 0; i < DisplayStringCount; i++) { @@ -957,7 +957,7 @@ void W3DDisplay::gatherDebugStats( void ) if (m_benchmarkDisplayString == NULL) { - GameFont *thisFont = TheFontLibrary->getFont( AsciiString("FixedSys"), 8, FALSE ); + GameFont *thisFont = TheFontLibrary->getFont( "FixedSys", 8, FALSE ); m_benchmarkDisplayString = TheDisplayStringManager->newDisplayString(); DEBUG_ASSERTCRASH( m_benchmarkDisplayString, ("Failed to create DisplayString") ); m_benchmarkDisplayString->setFont( thisFont ); diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayStringManager.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayStringManager.cpp index dc945b22e7..fe6294679b 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayStringManager.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayStringManager.cpp @@ -131,7 +131,7 @@ DisplayString *W3DDisplayStringManager::newDisplayString( void ) TheGlobalLanguageData->m_defaultDisplayStringFont.bold) ); } else - newString->setFont( TheFontLibrary->getFont( AsciiString("Times New Roman"), 12, FALSE ) ); + newString->setFont( TheFontLibrary->getFont( "Times New Roman", 12, FALSE ) ); // link string to list link( newString ); diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp index 7fc6c62f5f..e221ed511a 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp @@ -344,7 +344,7 @@ void W3DInGameUI::init( void ) // comment because we'll probably want to add this back in. /* // create the MOTD - GameWindow *motd = TheWindowManager->winCreateFromScript( AsciiString("MOTD.wnd") ); + GameWindow *motd = TheWindowManager->winCreateFromScript( "MOTD.wnd" ); if( motd ) { NameKeyType listboxTextID = TheNameKeyGenerator->nameToKey( "MOTD.wnd:ListboxMOTD" ); diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp index c5b6bddffd..6fe0998491 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp @@ -495,21 +495,21 @@ WorldHeightMap::WorldHeightMap(ChunkInputStream *pStrm, Bool logicalDataOnly): DataChunkInput file( pStrm ); if (logicalDataOnly) { - file.registerParser( AsciiString("HeightMapData"), AsciiString::TheEmptyString, ParseSizeOnlyInChunk ); - file.registerParser( AsciiString("WorldInfo"), AsciiString::TheEmptyString, ParseWorldDictDataChunk ); - file.registerParser( AsciiString("ObjectsList"), AsciiString::TheEmptyString, ParseObjectsDataChunk ); + file.registerParser( "HeightMapData", AsciiString::TheEmptyString, ParseSizeOnlyInChunk ); + file.registerParser( "WorldInfo", AsciiString::TheEmptyString, ParseWorldDictDataChunk ); + file.registerParser( "ObjectsList", AsciiString::TheEmptyString, ParseObjectsDataChunk ); freeListOfMapObjects(); // just in case. - file.registerParser( AsciiString("PolygonTriggers"), AsciiString::TheEmptyString, PolygonTrigger::ParsePolygonTriggersDataChunk ); + file.registerParser( "PolygonTriggers", AsciiString::TheEmptyString, PolygonTrigger::ParsePolygonTriggersDataChunk ); PolygonTrigger::deleteTriggers(); // just in case. TheSidesList->emptySides(); - file.registerParser(AsciiString("SidesList"), AsciiString::TheEmptyString, SidesList::ParseSidesDataChunk ); + file.registerParser("SidesList", AsciiString::TheEmptyString, SidesList::ParseSidesDataChunk ); } else { - file.registerParser( AsciiString("HeightMapData"), AsciiString::TheEmptyString, ParseHeightMapDataChunk ); - file.registerParser( AsciiString("BlendTileData"), AsciiString::TheEmptyString, ParseBlendTileDataChunk ); + file.registerParser( "HeightMapData", AsciiString::TheEmptyString, ParseHeightMapDataChunk ); + file.registerParser( "BlendTileData", AsciiString::TheEmptyString, ParseBlendTileDataChunk ); #ifdef EVAL_TILING_MODES - file.registerParser( AsciiString("FUNKY_TILING"), AsciiString::TheEmptyString, ParseFunkyTilingDataChunk ); + file.registerParser( "FUNKY_TILING", AsciiString::TheEmptyString, ParseFunkyTilingDataChunk ); #endif - file.registerParser( AsciiString("GlobalLighting"), AsciiString::TheEmptyString, ParseLightingDataChunk ); + file.registerParser( "GlobalLighting", AsciiString::TheEmptyString, ParseLightingDataChunk ); } if (!file.parse(this)) { @@ -848,7 +848,7 @@ Bool WorldHeightMap::ParseLightingDataChunk(DataChunkInput &file, DataChunkInfo Bool WorldHeightMap::ParseObjectsDataChunk(DataChunkInput &file, DataChunkInfo *info, void *userData) { file.m_currentObject = NULL; - file.registerParser( AsciiString("Object"), info->label, ParseObjectDataChunk ); + file.registerParser( "Object", info->label, ParseObjectDataChunk ); return (file.parse(userData)); } diff --git a/GeneralsMD/Code/Tools/GUIEdit/Source/LayoutScheme.cpp b/GeneralsMD/Code/Tools/GUIEdit/Source/LayoutScheme.cpp index dcd163c461..5e828d1837 100644 --- a/GeneralsMD/Code/Tools/GUIEdit/Source/LayoutScheme.cpp +++ b/GeneralsMD/Code/Tools/GUIEdit/Source/LayoutScheme.cpp @@ -1570,563 +1570,563 @@ void LayoutScheme::init( void ) const Image *image; // push button - image = TheMappedImageCollection->findImageByName( AsciiString( "PushButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "PushButtonEnabled" ); storeImageAndColor( BUTTON_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "PushButtonEnabledSelected" ) ); + image = TheMappedImageCollection->findImageByName( "PushButtonEnabledSelected" ); storeImageAndColor( BUTTON_ENABLED_PUSHED, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "PushButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "PushButtonDisabled" ); storeImageAndColor( BUTTON_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "PushButtonDisabledSelected" ) ); + image = TheMappedImageCollection->findImageByName( "PushButtonDisabledSelected" ); storeImageAndColor( BUTTON_DISABLED_PUSHED, image, lightGray, gray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "PushButtonHilite" ) ); + image = TheMappedImageCollection->findImageByName( "PushButtonHilite" ); storeImageAndColor( BUTTON_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "PushButtonHiliteSelected" ) ); + image = TheMappedImageCollection->findImageByName( "PushButtonHiliteSelected" ); storeImageAndColor( BUTTON_HILITE_PUSHED, image, yellow, white ); // radio button - image = TheMappedImageCollection->findImageByName( AsciiString( "RadioButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "RadioButtonEnabled" ); storeImageAndColor( RADIO_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "RadioButtonEnabledBoxUnselected" ) ); + image = TheMappedImageCollection->findImageByName( "RadioButtonEnabledBoxUnselected" ); storeImageAndColor( RADIO_ENABLED_UNCHECKED_BOX, image, darkRed, black ); - image = TheMappedImageCollection->findImageByName( AsciiString( "RadioButtonEnabledBoxSelected" ) ); + image = TheMappedImageCollection->findImageByName( "RadioButtonEnabledBoxSelected" ); storeImageAndColor( RADIO_ENABLED_CHECKED_BOX, image, blue, lightBlue ); - image = TheMappedImageCollection->findImageByName( AsciiString( "RadioButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "RadioButtonDisabled" ); storeImageAndColor( RADIO_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "RadioButtonDisabledBoxUnselected" ) ); + image = TheMappedImageCollection->findImageByName( "RadioButtonDisabledBoxUnselected" ); storeImageAndColor( RADIO_DISABLED_UNCHECKED_BOX, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "RadioButtonDisabledBoxSelected" ) ); + image = TheMappedImageCollection->findImageByName( "RadioButtonDisabledBoxSelected" ); storeImageAndColor( RADIO_DISABLED_CHECKED_BOX, image, darkGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "RadioButtonHilite" ) ); + image = TheMappedImageCollection->findImageByName( "RadioButtonHilite" ); storeImageAndColor( RADIO_HILITE, image, green, lightGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "RadioButtonHiliteBoxUnselected" ) ); + image = TheMappedImageCollection->findImageByName( "RadioButtonHiliteBoxUnselected" ); storeImageAndColor( RADIO_HILITE_UNCHECKED_BOX, image, darkGreen, lightGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "RadioButtonHiliteBoxSelected" ) ); + image = TheMappedImageCollection->findImageByName( "RadioButtonHiliteBoxSelected" ); storeImageAndColor( RADIO_HILITE_CHECKED_BOX, image, yellow, white ); // check box - image = TheMappedImageCollection->findImageByName( AsciiString( "CheckBoxEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "CheckBoxEnabled" ); storeImageAndColor( CHECK_BOX_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "CheckBoxEnabledBoxUnselected" ) ); + image = TheMappedImageCollection->findImageByName( "CheckBoxEnabledBoxUnselected" ); storeImageAndColor( CHECK_BOX_ENABLED_UNCHECKED_BOX, image, WIN_COLOR_UNDEFINED, lightBlue ); - image = TheMappedImageCollection->findImageByName( AsciiString( "CheckBoxEnabledBoxSelected" ) ); + image = TheMappedImageCollection->findImageByName( "CheckBoxEnabledBoxSelected" ); storeImageAndColor( CHECK_BOX_ENABLED_CHECKED_BOX, image, blue, lightBlue ); - image = TheMappedImageCollection->findImageByName( AsciiString( "CheckBoxDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "CheckBoxDisabled" ); storeImageAndColor( CHECK_BOX_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "CheckBoxDisabledBoxUnselected" ) ); + image = TheMappedImageCollection->findImageByName( "CheckBoxDisabledBoxUnselected" ); storeImageAndColor( CHECK_BOX_DISABLED_UNCHECKED_BOX, image, WIN_COLOR_UNDEFINED, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "CheckBoxDisabledBoxSelected" ) ); + image = TheMappedImageCollection->findImageByName( "CheckBoxDisabledBoxSelected" ); storeImageAndColor( CHECK_BOX_DISABLED_CHECKED_BOX, image, darkGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "CheckBoxHilite" ) ); + image = TheMappedImageCollection->findImageByName( "CheckBoxHilite" ); storeImageAndColor( CHECK_BOX_HILITE, image, green, lightGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "CheckBoxHiliteBoxUnselected" ) ); + image = TheMappedImageCollection->findImageByName( "CheckBoxHiliteBoxUnselected" ); storeImageAndColor( CHECK_BOX_HILITE_UNCHECKED_BOX, image, WIN_COLOR_UNDEFINED, lightBlue ); - image = TheMappedImageCollection->findImageByName( AsciiString( "CheckBoxHiliteBoxSelected" ) ); + image = TheMappedImageCollection->findImageByName( "CheckBoxHiliteBoxSelected" ); storeImageAndColor( CHECK_BOX_HILITE_CHECKED_BOX, image, yellow, white ); // horz slider - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderEnabledLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderEnabledLeftEnd" ); storeImageAndColor( HSLIDER_ENABLED_LEFT, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderEnabledRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderEnabledRightEnd" ); storeImageAndColor( HSLIDER_ENABLED_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderEnabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderEnabledRepeatingCenter" ); storeImageAndColor( HSLIDER_ENABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderEnabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderEnabledSmallRepeatingCenter" ); storeImageAndColor( HSLIDER_ENABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderDisabledLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderDisabledLeftEnd" ); storeImageAndColor( HSLIDER_DISABLED_LEFT, image, gray, darkGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderDisabledRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderDisabledRightEnd" ); storeImageAndColor( HSLIDER_DISABLED_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderDisabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderDisabledRepeatingCenter" ); storeImageAndColor( HSLIDER_DISABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderDisabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderDisabledSmallRepeatingCenter" ); storeImageAndColor( HSLIDER_DISABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderHiliteLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderHiliteLeftEnd" ); storeImageAndColor( HSLIDER_HILITE_LEFT, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderHiliteRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderHiliteRightEnd" ); storeImageAndColor( HSLIDER_HILITE_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderHiliteRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderHiliteRepeatingCenter" ); storeImageAndColor( HSLIDER_HILITE_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderHiliteSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderHiliteSmallRepeatingCenter" ); storeImageAndColor( HSLIDER_HILITE_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderThumbEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderThumbEnabled" ); storeImageAndColor( HSLIDER_THUMB_ENABLED, image, lightRed, red ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderThumbEnabledSelected" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderThumbEnabledSelected" ); storeImageAndColor( HSLIDER_THUMB_ENABLED_PUSHED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderThumbDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderThumbDisabled" ); storeImageAndColor( HSLIDER_THUMB_DISABLED, image, darkGray, gray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderThumbDisabledSelected" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderThumbDisabledSelected" ); storeImageAndColor( HSLIDER_THUMB_DISABLED_PUSHED, image, black, darkGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderThumbHilite" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderThumbHilite" ); storeImageAndColor( HSLIDER_THUMB_HILITE, image, green, lightGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "HSliderThumbHiliteSelected" ) ); + image = TheMappedImageCollection->findImageByName( "HSliderThumbHiliteSelected" ); storeImageAndColor( HSLIDER_THUMB_HILITE_PUSHED, image, blue, lightBlue ); // vert slider - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderEnabledTopEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderEnabledTopEnd" ); storeImageAndColor( VSLIDER_ENABLED_TOP, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderEnabledBottomEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderEnabledBottomEnd" ); storeImageAndColor( VSLIDER_ENABLED_BOTTOM, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderEnabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderEnabledRepeatingCenter" ); storeImageAndColor( VSLIDER_ENABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderEnabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderEnabledSmallRepeatingCenter" ); storeImageAndColor( VSLIDER_ENABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderDisabledTopEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderDisabledTopEnd" ); storeImageAndColor( VSLIDER_DISABLED_TOP, image, gray, darkGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderDisabledBottomEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderDisabledBottomEnd" ); storeImageAndColor( VSLIDER_DISABLED_BOTTOM, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderDisabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderDisabledRepeatingCenter" ); storeImageAndColor( VSLIDER_DISABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderDisabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderDisabledSmallRepeatingCenter" ); storeImageAndColor( VSLIDER_DISABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderHiliteTopEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderHiliteTopEnd" ); storeImageAndColor( VSLIDER_HILITE_TOP, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderHiliteBottomEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderHiliteBottomEnd" ); storeImageAndColor( VSLIDER_HILITE_BOTTOM, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderHiliteRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderHiliteRepeatingCenter" ); storeImageAndColor( VSLIDER_HILITE_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderHiliteSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderHiliteSmallRepeatingCenter" ); storeImageAndColor( VSLIDER_HILITE_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderThumbEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderThumbEnabled" ); storeImageAndColor( VSLIDER_THUMB_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderThumbEnabledSelected" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderThumbEnabledSelected" ); storeImageAndColor( VSLIDER_THUMB_ENABLED_PUSHED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderThumbDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderThumbDisabled" ); storeImageAndColor( VSLIDER_THUMB_DISABLED, image, darkGray, gray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderThumbDisabledSelected" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderThumbDisabledSelected" ); storeImageAndColor( VSLIDER_THUMB_DISABLED_PUSHED, image, black, darkGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderThumbHilite" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderThumbHilite" ); storeImageAndColor( VSLIDER_THUMB_HILITE, image, green, lightGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderThumbHiliteSelected" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderThumbHiliteSelected" ); storeImageAndColor( VSLIDER_THUMB_HILITE_PUSHED, image, blue, lightBlue ); // listbox - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabled" ); storeImageAndColor( LISTBOX_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemLeftEnd" ); storeImageAndColor( LISTBOX_ENABLED_SELECTED_ITEM_LEFT, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemRightEnd" ); storeImageAndColor( LISTBOX_ENABLED_SELECTED_ITEM_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemRepeatingCenter" ); storeImageAndColor( LISTBOX_ENABLED_SELECTED_ITEM_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemSmallRepeatingCenter" ); storeImageAndColor( LISTBOX_ENABLED_SELECTED_ITEM_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabled" ); storeImageAndColor( LISTBOX_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemLeftEnd" ); storeImageAndColor( LISTBOX_DISABLED_SELECTED_ITEM_LEFT, image, lightGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemRightEnd" ); storeImageAndColor( LISTBOX_DISABLED_SELECTED_ITEM_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemRepeatingCenter" ); storeImageAndColor( LISTBOX_DISABLED_SELECTED_ITEM_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemSmallRepeatingCenter" ); storeImageAndColor( LISTBOX_DISABLED_SELECTED_ITEM_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHilite" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHilite" ); storeImageAndColor( LISTBOX_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemLeftEnd" ); storeImageAndColor( LISTBOX_HILITE_SELECTED_ITEM_LEFT, image, white, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemRightEnd" ); storeImageAndColor( LISTBOX_HILITE_SELECTED_ITEM_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemRepeatingCenter" ); storeImageAndColor( LISTBOX_HILITE_SELECTED_ITEM_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemSmallRepeatingCenter" ); storeImageAndColor( LISTBOX_HILITE_SELECTED_ITEM_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonEnabled" ); storeImageAndColor( LISTBOX_UP_BUTTON_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonEnabled" ); storeImageAndColor( LISTBOX_UP_BUTTON_ENABLED_PUSHED, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonDisabled" ); storeImageAndColor( LISTBOX_UP_BUTTON_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonDisabled" ); storeImageAndColor( LISTBOX_UP_BUTTON_DISABLED_PUSHED, image, lightGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonHilite" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonHilite" ); storeImageAndColor( LISTBOX_UP_BUTTON_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonHiliteSelected" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonHiliteSelected" ); storeImageAndColor( LISTBOX_UP_BUTTON_HILITE_PUSHED, image, white, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonEnabled" ); storeImageAndColor( LISTBOX_DOWN_BUTTON_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonEnabled" ); storeImageAndColor( LISTBOX_DOWN_BUTTON_ENABLED_PUSHED, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonDisabled" ); storeImageAndColor( LISTBOX_DOWN_BUTTON_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonDisabled" ); storeImageAndColor( LISTBOX_DOWN_BUTTON_DISABLED_PUSHED, image, lightGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonHilite" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonHilite" ); storeImageAndColor( LISTBOX_DOWN_BUTTON_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonHiliteSelected" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonHiliteSelected" ); storeImageAndColor( LISTBOX_DOWN_BUTTON_HILITE_PUSHED, image, white, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeEnabledTopEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeEnabledTopEnd" ); storeImageAndColor( LISTBOX_SLIDER_ENABLED_TOP, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeEnabledBottomEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeEnabledBottomEnd" ); storeImageAndColor( LISTBOX_SLIDER_ENABLED_BOTTOM, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeEnabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeEnabledRepeatingCenter" ); storeImageAndColor( LISTBOX_SLIDER_ENABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeEnabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeEnabledSmallRepeatingCenter" ); storeImageAndColor( LISTBOX_SLIDER_ENABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDisabledTopEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDisabledTopEnd" ); storeImageAndColor( LISTBOX_SLIDER_DISABLED_TOP, image, gray, darkGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDisabledBottomEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDisabledBottomEnd" ); storeImageAndColor( LISTBOX_SLIDER_DISABLED_BOTTOM, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDisabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDisabledRepeatingCenter" ); storeImageAndColor( LISTBOX_SLIDER_DISABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDisabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDisabledSmallRepeatingCenter" ); storeImageAndColor( LISTBOX_SLIDER_DISABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeHiliteTopEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeHiliteTopEnd" ); storeImageAndColor( LISTBOX_SLIDER_HILITE_TOP, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeHiliteBottomEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeHiliteBottomEnd" ); storeImageAndColor( LISTBOX_SLIDER_HILITE_BOTTOM, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeHiliteRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeHiliteRepeatingCenter" ); storeImageAndColor( LISTBOX_SLIDER_HILITE_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeHiliteSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeHiliteSmallRepeatingCenter" ); storeImageAndColor( LISTBOX_SLIDER_HILITE_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbEnabled" ); storeImageAndColor( LISTBOX_SLIDER_THUMB_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbEnabled" ); storeImageAndColor( LISTBOX_SLIDER_THUMB_ENABLED_PUSHED, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbDisabled" ); storeImageAndColor( LISTBOX_SLIDER_THUMB_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbDisabled" ); storeImageAndColor( LISTBOX_SLIDER_THUMB_DISABLED_PUSHED, image, lightGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbHilite" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbHilite" ); storeImageAndColor( LISTBOX_SLIDER_THUMB_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbHiliteSelected" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbHiliteSelected" ); storeImageAndColor( LISTBOX_SLIDER_THUMB_HILITE_PUSHED, image, white, darkGreen ); // Combo Box //--------------------------------------------------------------------------- - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabled" ); storeImageAndColor( COMBOBOX_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemLeftEnd" ); storeImageAndColor( COMBOBOX_ENABLED_SELECTED_ITEM_LEFT, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemRightEnd" ); storeImageAndColor( COMBOBOX_ENABLED_SELECTED_ITEM_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemRepeatingCenter" ); storeImageAndColor( COMBOBOX_ENABLED_SELECTED_ITEM_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_ENABLED_SELECTED_ITEM_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabled" ); storeImageAndColor( COMBOBOX_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemLeftEnd" ); storeImageAndColor( COMBOBOX_DISABLED_SELECTED_ITEM_LEFT, image, lightGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemRightEnd" ); storeImageAndColor( COMBOBOX_DISABLED_SELECTED_ITEM_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemRepeatingCenter" ); storeImageAndColor( COMBOBOX_DISABLED_SELECTED_ITEM_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_DISABLED_SELECTED_ITEM_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHilite" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHilite" ); storeImageAndColor( COMBOBOX_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemLeftEnd" ); storeImageAndColor( COMBOBOX_HILITE_SELECTED_ITEM_LEFT, image, white, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemRightEnd" ); storeImageAndColor( COMBOBOX_HILITE_SELECTED_ITEM_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemRepeatingCenter" ); storeImageAndColor( COMBOBOX_HILITE_SELECTED_ITEM_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_HILITE_SELECTED_ITEM_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonEnabled" ); storeImageAndColor( COMBOBOX_DROP_DOWN_BUTTON_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonEnabled" ); storeImageAndColor( COMBOBOX_DROP_DOWN_BUTTON_ENABLED_PUSHED, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonDisabled" ); storeImageAndColor( COMBOBOX_DROP_DOWN_BUTTON_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonDisabled" ); storeImageAndColor( COMBOBOX_DROP_DOWN_BUTTON_DISABLED_PUSHED, image, lightGray, gray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonHilite" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonHilite" ); storeImageAndColor( COMBOBOX_DROP_DOWN_BUTTON_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonHilite" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonHilite" ); storeImageAndColor( COMBOBOX_DROP_DOWN_BUTTON_HILITE_PUSHED, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryEnabledLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryEnabledLeftEnd" ); storeImageAndColor( COMBOBOX_EDIT_BOX_ENABLED_LEFT, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryEnabledRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryEnabledRightEnd" ); storeImageAndColor( COMBOBOX_EDIT_BOX_ENABLED_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryEnabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryEnabledRepeatingCenter" ); storeImageAndColor( COMBOBOX_EDIT_BOX_ENABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryEnabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryEnabledSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_EDIT_BOX_ENABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryDisabledLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryDisabledLeftEnd" ); storeImageAndColor( COMBOBOX_EDIT_BOX_DISABLED_LEFT, image, gray, black ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryDisabledRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryDisabledRightEnd" ); storeImageAndColor( COMBOBOX_EDIT_BOX_DISABLED_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryDisabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryDisabledRepeatingCenter" ); storeImageAndColor( COMBOBOX_EDIT_BOX_DISABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryDisabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryDisabledSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_EDIT_BOX_DISABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryHiliteLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryHiliteLeftEnd" ); storeImageAndColor( COMBOBOX_EDIT_BOX_HILITE_LEFT, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryHiliteRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryHiliteRightEnd" ); storeImageAndColor( COMBOBOX_EDIT_BOX_HILITE_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryHiliteRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryHiliteRepeatingCenter" ); storeImageAndColor( COMBOBOX_EDIT_BOX_HILITE_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryHiliteSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryHiliteSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_EDIT_BOX_HILITE_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabled" ); storeImageAndColor( COMBOBOX_LISTBOX_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemLeftEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_ENABLED_SELECTED_ITEM_LEFT, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemRightEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_ENABLED_SELECTED_ITEM_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_ENABLED_SELECTED_ITEM_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxEnabledSelectedItemSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxEnabledSelectedItemSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_ENABLED_SELECTED_ITEM_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabled" ); storeImageAndColor( COMBOBOX_LISTBOX_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemLeftEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_DISABLED_SELECTED_ITEM_LEFT, image, lightGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemRightEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_DISABLED_SELECTED_ITEM_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_DISABLED_SELECTED_ITEM_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxDisabledSelectedItemSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxDisabledSelectedItemSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_DISABLED_SELECTED_ITEM_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHilite" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHilite" ); storeImageAndColor( COMBOBOX_LISTBOX_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemLeftEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_HILITE_SELECTED_ITEM_LEFT, image, white, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemRightEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_HILITE_SELECTED_ITEM_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_HILITE_SELECTED_ITEM_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ListBoxHiliteSelectedItemSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ListBoxHiliteSelectedItemSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_HILITE_SELECTED_ITEM_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonEnabled" ); storeImageAndColor( COMBOBOX_LISTBOX_UP_BUTTON_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonEnabled" ); storeImageAndColor( COMBOBOX_LISTBOX_UP_BUTTON_ENABLED_PUSHED, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonDisabled" ); storeImageAndColor( COMBOBOX_LISTBOX_UP_BUTTON_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonDisabled" ); storeImageAndColor( COMBOBOX_LISTBOX_UP_BUTTON_DISABLED_PUSHED, image, lightGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonHilite" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonHilite" ); storeImageAndColor( COMBOBOX_LISTBOX_UP_BUTTON_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeUpButtonHiliteSelected" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeUpButtonHiliteSelected" ); storeImageAndColor( COMBOBOX_LISTBOX_UP_BUTTON_HILITE_PUSHED, image, white, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonEnabled" ); storeImageAndColor( COMBOBOX_LISTBOX_DOWN_BUTTON_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonEnabled" ); storeImageAndColor( COMBOBOX_LISTBOX_DOWN_BUTTON_ENABLED_PUSHED, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonDisabled" ); storeImageAndColor( COMBOBOX_LISTBOX_DOWN_BUTTON_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonDisabled" ); storeImageAndColor( COMBOBOX_LISTBOX_DOWN_BUTTON_DISABLED_PUSHED, image, lightGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonHilite" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonHilite" ); storeImageAndColor( COMBOBOX_LISTBOX_DOWN_BUTTON_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDownButtonHiliteSelected" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDownButtonHiliteSelected" ); storeImageAndColor( COMBOBOX_LISTBOX_DOWN_BUTTON_HILITE_PUSHED, image, white, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeEnabledTopEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeEnabledTopEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_ENABLED_TOP, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeEnabledBottomEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeEnabledBottomEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_ENABLED_BOTTOM, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeEnabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeEnabledRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_ENABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeEnabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeEnabledSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_ENABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDisabledTopEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDisabledTopEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_DISABLED_TOP, image, gray, darkGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDisabledBottomEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDisabledBottomEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_DISABLED_BOTTOM, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDisabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDisabledRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_DISABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeDisabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeDisabledSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_DISABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeHiliteTopEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeHiliteTopEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_HILITE_TOP, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeHiliteBottomEnd" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeHiliteBottomEnd" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_HILITE_BOTTOM, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeHiliteRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeHiliteRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_HILITE_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeHiliteSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeHiliteSmallRepeatingCenter" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_HILITE_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbEnabled" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_THUMB_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbEnabled" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_THUMB_ENABLED_PUSHED, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbDisabled" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_THUMB_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbDisabled" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_THUMB_DISABLED_PUSHED, image, lightGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbHilite" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbHilite" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_THUMB_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "VSliderLargeThumbHiliteSelected" ) ); + image = TheMappedImageCollection->findImageByName( "VSliderLargeThumbHiliteSelected" ); storeImageAndColor( COMBOBOX_LISTBOX_SLIDER_THUMB_HILITE_PUSHED, image, white, darkGreen ); // progress bar //--------------------------------------------------------------------------- - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarEnabledLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarEnabledLeftEnd" ); storeImageAndColor( PROGRESS_BAR_ENABLED_LEFT, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarEnabledRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarEnabledRightEnd" ); storeImageAndColor( PROGRESS_BAR_ENABLED_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarEnabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarEnabledRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_ENABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarEnabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarEnabledSmallRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_ENABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarEnabledBarLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarEnabledBarLeftEnd" ); storeImageAndColor( PROGRESS_BAR_ENABLED_BAR_LEFT, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarEnabledBarRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarEnabledBarRightEnd" ); storeImageAndColor( PROGRESS_BAR_ENABLED_BAR_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarEnabledBarRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarEnabledBarRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_ENABLED_BAR_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarEnabledBarSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarEnabledBarSmallRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_ENABLED_BAR_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); //--------------------------------------------------------------------------- - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarDisabledLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarDisabledLeftEnd" ); storeImageAndColor( PROGRESS_BAR_DISABLED_LEFT, image, darkGray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarDisabledRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarDisabledRightEnd" ); storeImageAndColor( PROGRESS_BAR_DISABLED_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarDisabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarDisabledRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_DISABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarDisabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarDisabledSmallRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_DISABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarDisabledBarLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarDisabledBarLeftEnd" ); storeImageAndColor( PROGRESS_BAR_DISABLED_BAR_LEFT, image, lightGray, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarDisabledBarRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarDisabledBarRightEnd" ); storeImageAndColor( PROGRESS_BAR_DISABLED_BAR_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarDisabledBarRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarDisabledBarRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_DISABLED_BAR_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarDisabledBarSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarDisabledBarSmallRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_DISABLED_BAR_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); //--------------------------------------------------------------------------- - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarHiliteLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarHiliteLeftEnd" ); storeImageAndColor( PROGRESS_BAR_HILITE_LEFT, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarHiliteRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarHiliteRightEnd" ); storeImageAndColor( PROGRESS_BAR_HILITE_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarHiliteRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarHiliteRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_HILITE_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarHiliteSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarHiliteSmallRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_HILITE_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarHiliteBarLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarHiliteBarLeftEnd" ); storeImageAndColor( PROGRESS_BAR_HILITE_BAR_LEFT, image, yellow, white ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarHiliteBarRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarHiliteBarRightEnd" ); storeImageAndColor( PROGRESS_BAR_HILITE_BAR_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarHiliteBarRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarHiliteBarRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_HILITE_BAR_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "ProgressBarHiliteBarSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "ProgressBarHiliteBarSmallRepeatingCenter" ); storeImageAndColor( PROGRESS_BAR_HILITE_BAR_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); // static text //--------------------------------------------------------------------------- - image = TheMappedImageCollection->findImageByName( AsciiString( "StaticTextEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "StaticTextEnabled" ); storeImageAndColor( STATIC_TEXT_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "StaticTextDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "StaticTextDisabled" ); storeImageAndColor( STATIC_TEXT_DISABLED, image, darkGray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "StaticTextHilite" ) ); + image = TheMappedImageCollection->findImageByName( "StaticTextHilite" ); storeImageAndColor( STATIC_TEXT_HILITE, image, darkGreen, lightGreen ); // text entry - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryEnabledLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryEnabledLeftEnd" ); storeImageAndColor( TEXT_ENTRY_ENABLED_LEFT, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryEnabledRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryEnabledRightEnd" ); storeImageAndColor( TEXT_ENTRY_ENABLED_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryEnabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryEnabledRepeatingCenter" ); storeImageAndColor( TEXT_ENTRY_ENABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryEnabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryEnabledSmallRepeatingCenter" ); storeImageAndColor( TEXT_ENTRY_ENABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryDisabledLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryDisabledLeftEnd" ); storeImageAndColor( TEXT_ENTRY_DISABLED_LEFT, image, gray, black ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryDisabledRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryDisabledRightEnd" ); storeImageAndColor( TEXT_ENTRY_DISABLED_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryDisabledRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryDisabledRepeatingCenter" ); storeImageAndColor( TEXT_ENTRY_DISABLED_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryDisabledSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryDisabledSmallRepeatingCenter" ); storeImageAndColor( TEXT_ENTRY_DISABLED_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryHiliteLeftEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryHiliteLeftEnd" ); storeImageAndColor( TEXT_ENTRY_HILITE_LEFT, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryHiliteRightEnd" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryHiliteRightEnd" ); storeImageAndColor( TEXT_ENTRY_HILITE_RIGHT, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryHiliteRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryHiliteRepeatingCenter" ); storeImageAndColor( TEXT_ENTRY_HILITE_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TextEntryHiliteSmallRepeatingCenter" ) ); + image = TheMappedImageCollection->findImageByName( "TextEntryHiliteSmallRepeatingCenter" ); storeImageAndColor( TEXT_ENTRY_HILITE_SMALL_CENTER, image, WIN_COLOR_UNDEFINED, WIN_COLOR_UNDEFINED ); // Tab Control - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlZeroEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlZeroEnabled" ); storeImageAndColor( TC_TAB_0_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlZeroDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlZeroDisabled" ); storeImageAndColor( TC_TAB_0_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlZeroHilite" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlZeroHilite" ); storeImageAndColor( TC_TAB_0_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlOneEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlOneEnabled" ); storeImageAndColor( TC_TAB_1_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlOneDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlOneDisabled" ); storeImageAndColor( TC_TAB_1_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlOneHilite" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlOneHilite" ); storeImageAndColor( TC_TAB_1_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlTwoEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlTwoEnabled" ); storeImageAndColor( TC_TAB_2_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlTwoDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlTwoDisabled" ); storeImageAndColor( TC_TAB_2_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlTwoHilite" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlTwoHilite" ); storeImageAndColor( TC_TAB_2_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlThreeEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlThreeEnabled" ); storeImageAndColor( TC_TAB_3_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlThreeDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlThreeDisabled" ); storeImageAndColor( TC_TAB_3_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlThreeHilite" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlThreeHilite" ); storeImageAndColor( TC_TAB_3_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlFourEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlFourEnabled" ); storeImageAndColor( TC_TAB_4_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlFourDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlFourDisabled" ); storeImageAndColor( TC_TAB_4_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlFourHilite" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlFourHilite" ); storeImageAndColor( TC_TAB_4_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlFiveEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlFiveEnabled" ); storeImageAndColor( TC_TAB_5_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlFiveDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlFiveDisabled" ); storeImageAndColor( TC_TAB_5_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlFiveHilite" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlFiveHilite" ); storeImageAndColor( TC_TAB_5_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlSixEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlSixEnabled" ); storeImageAndColor( TC_TAB_6_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlSixDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlSixDisabled" ); storeImageAndColor( TC_TAB_6_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlSixHilite" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlSixHilite" ); storeImageAndColor( TC_TAB_6_HILITE, image, green, darkGreen ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlSevenEnabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlSevenEnabled" ); storeImageAndColor( TC_TAB_7_ENABLED, image, red, lightRed ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlSevenDisabled" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlSevenDisabled" ); storeImageAndColor( TC_TAB_7_DISABLED, image, gray, lightGray ); - image = TheMappedImageCollection->findImageByName( AsciiString( "TabControlSevenHilite" ) ); + image = TheMappedImageCollection->findImageByName( "TabControlSevenHilite" ); storeImageAndColor( TC_TAB_7_HILITE, image, green, darkGreen ); storeImageAndColor( TAB_CONTROL_ENABLED, NULL, black, white ); @@ -2147,7 +2147,7 @@ void LayoutScheme::init( void ) m_hiliteText.borderColor = darkBlue; // default font - m_font = TheWindowManager->winFindFont( AsciiString("Times New Roman"), 14, FALSE ); + m_font = TheWindowManager->winFindFont( "Times New Roman", 14, FALSE ); } // LayoutScheme::openDialog =================================================== diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/CameraOptions.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/CameraOptions.cpp index 58f3fc97ab..9a5e47225c 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/CameraOptions.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/CameraOptions.cpp @@ -94,8 +94,8 @@ void CameraOptions::OnDropWaypointButton() // // MBL CNC3 INCURSION 10.29.2002 - Fix compile error w/ 10-15-2002 Drop // - // MapObject *pNew = new MapObject(docPt, AsciiString("*Waypoints/Waypoint"), 0, 0, NULL, NULL ); - MapObject *pNew = newInstance(MapObject)(docPt, AsciiString("*Waypoints/Waypoint"), 0, 0, NULL, NULL ); + // MapObject *pNew = new MapObject(docPt, "*Waypoints/Waypoint", 0, 0, NULL, NULL ); + MapObject *pNew = newInstance(MapObject)(docPt, "*Waypoints/Waypoint", 0, 0, NULL, NULL ); Int id = pDoc->getNextWaypointID(); AsciiString name = WaypointOptions::GenerateUniqueName(id); @@ -103,7 +103,7 @@ void CameraOptions::OnDropWaypointButton() pNew->setIsWaypoint(); pNew->setWaypointID(id); pNew->setWaypointName(name); - pNew->getProperties()->setAsciiString(TheKey_originalOwner, AsciiString("team")); + pNew->getProperties()->setAsciiString(TheKey_originalOwner, "team"); AddObjectUndoable *pUndo = new AddObjectUndoable(pDoc, pNew); pDoc->AddAndDoUndoable(pUndo); REF_PTR_RELEASE(pUndo); // belongs to pDoc now. diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/GroveTool.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/GroveTool.cpp index 6c989d09fd..753714f457 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/GroveTool.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/GroveTool.cpp @@ -108,7 +108,7 @@ void GroveTool::activate() void GroveTool::plantShrub( Coord3D *pos ) { // TODO: Determine when we can tell something is a shurubbery, and plant it here - jkmcd -// addObj(pos, AsciiString("Shrub")); +// addObj(pos, "Shrub"); } void GroveTool::_plantGroveInBox(CPoint tl, CPoint br, WbView* pView) diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/ScorchTool.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/ScorchTool.cpp index 318a8c6e53..311897b00f 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/ScorchTool.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/ScorchTool.cpp @@ -111,7 +111,7 @@ void ScorchTool::mouseDown(TTrackingMode m, CPoint viewPt, WbView* pView, CWorld ScorchOptions::update(); } else { pView->snapPoint(&docPt); - MapObject *pNew = newInstance(MapObject)(docPt, AsciiString("Scorch"), 0, 0, NULL, NULL ); + MapObject *pNew = newInstance(MapObject)(docPt, "Scorch", 0, 0, NULL, NULL ); pNew->getProperties()->setAsciiString(TheKey_originalOwner, NEUTRAL_TEAM_INTERNAL_STR); pNew->setSelected(true); pNew->setIsScorch(); diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/ScriptDialog.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/ScriptDialog.cpp index 001fd9c439..c45f8ef396 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/ScriptDialog.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/ScriptDialog.cpp @@ -1534,12 +1534,12 @@ void ScriptDialog::OnLoad() m_firstTrigger = NULL; m_waypointBase = pDoc->getNextWaypointID(); m_maxWaypoint = m_waypointBase; - file.registerParser( AsciiString("PlayerScriptsList"), AsciiString::TheEmptyString, ScriptList::ParseScriptsDataChunk ); - file.registerParser( AsciiString("ObjectsList"), AsciiString::TheEmptyString, ParseObjectsDataChunk ); - file.registerParser( AsciiString("PolygonTriggers"), AsciiString::TheEmptyString, ParsePolygonTriggersDataChunk ); - file.registerParser( AsciiString("WaypointsList"), AsciiString::TheEmptyString, ParseWaypointDataChunk ); - file.registerParser( AsciiString("ScriptTeams"), AsciiString::TheEmptyString, ParseTeamsDataChunk ); - file.registerParser( AsciiString("ScriptsPlayers"), AsciiString::TheEmptyString, ParsePlayersDataChunk ); + file.registerParser( "PlayerScriptsList", AsciiString::TheEmptyString, ScriptList::ParseScriptsDataChunk ); + file.registerParser( "ObjectsList", AsciiString::TheEmptyString, ParseObjectsDataChunk ); + file.registerParser( "PolygonTriggers", AsciiString::TheEmptyString, ParsePolygonTriggersDataChunk ); + file.registerParser( "WaypointsList", AsciiString::TheEmptyString, ParseWaypointDataChunk ); + file.registerParser( "ScriptTeams", AsciiString::TheEmptyString, ParseTeamsDataChunk ); + file.registerParser( "ScriptsPlayers", AsciiString::TheEmptyString, ParsePlayersDataChunk ); if (!file.parse(this)) { throw(ERROR_CORRUPT_FILE_FORMAT); } @@ -1646,7 +1646,7 @@ void ScriptDialog::OnLoad() Bool ScriptDialog::ParseObjectsDataChunk(DataChunkInput &file, DataChunkInfo *info, void *userData) { file.m_currentObject = NULL; - file.registerParser( AsciiString("Object"), info->label, ParseObjectDataChunk ); + file.registerParser( "Object", info->label, ParseObjectDataChunk ); return (file.parse(userData)); } diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/SelectMacrotexture.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/SelectMacrotexture.cpp index cf5c6d77a8..47eef54dcb 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/SelectMacrotexture.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/SelectMacrotexture.cpp @@ -131,7 +131,7 @@ BOOL SelectMacrotexture::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult item.cchTextMax = sizeof(buffer)-2; m_textureTreeView.GetItem(&item); if (0==strcmp(buffer, DEFAULT)) { - TheTerrainRenderObject->updateMacroTexture(AsciiString("")); + TheTerrainRenderObject->updateMacroTexture(""); } else { TheTerrainRenderObject->updateMacroTexture(AsciiString(buffer)); } diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp index d326723eb4..c1b902172c 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp @@ -426,7 +426,7 @@ void WorldHeightMapEdit::loadDirectoryOfImages(const char *pFilePath) } FilenameList filenameList; - TheFileSystem->getFileListInDirectory(AsciiString(dirBuf), AsciiString("*.*"), filenameList, TRUE); + TheFileSystem->getFileListInDirectory(AsciiString(dirBuf), "*.*", filenameList, TRUE); if (filenameList.size() == 0) { return; diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/WaypointTool.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/WaypointTool.cpp index c4fbb40316..72a2506c65 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/WaypointTool.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/WaypointTool.cpp @@ -119,14 +119,14 @@ void WaypointTool::mouseDown(TTrackingMode m, CPoint viewPt, WbView* pView, CWor WaypointOptions::update(); } else { pView->snapPoint(&docPt); - MapObject *pNew = newInstance( MapObject)(docPt, AsciiString("*Waypoints/Waypoint"), 0, 0, NULL, NULL ); + MapObject *pNew = newInstance( MapObject)(docPt, "*Waypoints/Waypoint", 0, 0, NULL, NULL ); Int id = pDoc->getNextWaypointID(); AsciiString name = WaypointOptions::GenerateUniqueName(id); pNew->setSelected(true); pNew->setIsWaypoint(); pNew->setWaypointID(id); pNew->setWaypointName(name); - pNew->getProperties()->setAsciiString(TheKey_originalOwner, AsciiString("team")); + pNew->getProperties()->setAsciiString(TheKey_originalOwner, "team"); AddObjectUndoable *pUndo = new AddObjectUndoable(pDoc, pNew); pDoc->AddAndDoUndoable(pUndo); REF_PTR_RELEASE(pUndo); // belongs to pDoc now. @@ -166,7 +166,7 @@ void WaypointTool::mouseUp(TTrackingMode m, CPoint viewPt, WbView* pView, CWorld pObj = pickWaypoint(docPt); if (pObj == NULL) { pView->snapPoint(&docPt); - MapObject *pNew = newInstance( MapObject)(docPt, AsciiString("*Waypoints/Waypoint"), 0, 0, NULL, NULL ); + MapObject *pNew = newInstance( MapObject)(docPt, "*Waypoints/Waypoint", 0, 0, NULL, NULL ); Int id = pDoc->getNextWaypointID(); AsciiString name; name.format("Waypoint %d", id); @@ -174,7 +174,7 @@ void WaypointTool::mouseUp(TTrackingMode m, CPoint viewPt, WbView* pView, CWorld pNew->setIsWaypoint(); pNew->setWaypointID(id); pNew->setWaypointName(name); - pNew->getProperties()->setAsciiString(TheKey_originalOwner, AsciiString("team")); + pNew->getProperties()->setAsciiString(TheKey_originalOwner, "team"); AddObjectUndoable *pUndo = new AddObjectUndoable(pDoc, pNew); pDoc->AddAndDoUndoable(pUndo); REF_PTR_RELEASE(pUndo); // belongs to pDoc now. diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilder.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilder.cpp index d4459af550..8b01c80c83 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilder.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilder.cpp @@ -349,7 +349,7 @@ BOOL CWorldBuilderApp::InitInstance() TheFramePacer = new FramePacer(); #if defined(RTS_DEBUG) - ini.loadFileDirectory( AsciiString( "Data\\INI\\GameDataDebug" ), INI_LOAD_MULTIFILE, NULL ); + ini.loadFileDirectory( "Data\\INI\\GameDataDebug", INI_LOAD_MULTIFILE, NULL ); #endif #ifdef DEBUG_CRASHING @@ -375,8 +375,8 @@ BOOL CWorldBuilderApp::InitInstance() CreateDirectory(buf, NULL); // read the water settings from INI (must do prior to initing GameClient, apparently) - ini.loadFileDirectory( AsciiString( "Data\\INI\\Default\\Water" ), INI_LOAD_OVERWRITE, NULL ); - ini.loadFileDirectory( AsciiString( "Data\\INI\\Water" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Default\\Water", INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\INI\\Water", INI_LOAD_OVERWRITE, NULL ); initSubsystem(TheGameText, CreateGameTextInterface()); initSubsystem(TheScienceStore, new ScienceStore(), "Data\\INI\\Default\\Science", "Data\\INI\\Science"); @@ -391,7 +391,7 @@ BOOL CWorldBuilderApp::InitInstance() TheScriptEngine->turnBreezeOff(); // stop the tree sway. // [2/11/2003] - ini.loadFileDirectory( AsciiString( "Data\\Scripts\\Scripts" ), INI_LOAD_OVERWRITE, NULL ); + ini.loadFileDirectory( "Data\\Scripts\\Scripts", INI_LOAD_OVERWRITE, NULL ); // need this before TheAudio in case we're running off of CD - TheAudio can try to open Music.big on the CD... initSubsystem(TheCDManager, CreateCDManager(), NULL); @@ -703,7 +703,7 @@ void CWorldBuilderApp::OnFileOpen() #endif CFileStatus status; - if (m_currentDirectory != AsciiString("")) try { + if (m_currentDirectory != "") try { if (CFile::GetStatus(m_currentDirectory.str(), status)) { if (status.m_attribute & CFile::directory) { ::SetCurrentDirectory(m_currentDirectory.str()); diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp index 4db400158f..a2c5d7836c 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp @@ -334,7 +334,7 @@ void CWorldBuilderDoc::Serialize(CArchive& ar) DataChunkInput file( pStrm ); if (file.isValidFileType()) { // Backwards compatible files aren't valid data chunk files. // Read the waypoints. - file.registerParser( AsciiString("WaypointsList"), AsciiString::TheEmptyString, ParseWaypointDataChunk ); + file.registerParser( "WaypointsList", AsciiString::TheEmptyString, ParseWaypointDataChunk ); if (!file.parse(this)) { throw(ERROR_CORRUPT_FILE_FORMAT); } @@ -1291,7 +1291,7 @@ BOOL CWorldBuilderDoc::OnNewDocument() PolygonTrigger *pTrig = newInstance(PolygonTrigger)(4); ICoord3D loc; pTrig->setWaterArea(true); - pTrig->setTriggerName(AsciiString("Default Water")); + pTrig->setTriggerName("Default Water"); loc.x = -hi.borderWidth*MAP_XY_FACTOR; loc.y = -hi.borderWidth*MAP_XY_FACTOR; loc.z = TheGlobalData->m_waterPositionZ; diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/playerlistdlg.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/playerlistdlg.cpp index d9125debeb..a7e33d0ab9 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/playerlistdlg.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/playerlistdlg.cpp @@ -305,8 +305,8 @@ void PlayerListDlg::OnNewplayer() newPlayerDict.setBool(TheKey_playerIsHuman, true); newPlayerDict.setUnicodeString(TheKey_playerDisplayName, pnameu); newPlayerDict.setAsciiString(TheKey_playerFaction, addedPTName); - newPlayerDict.setAsciiString(TheKey_playerEnemies, AsciiString("")); - newPlayerDict.setAsciiString(TheKey_playerAllies, AsciiString("")); + newPlayerDict.setAsciiString(TheKey_playerEnemies, ""); + newPlayerDict.setAsciiString(TheKey_playerAllies, ""); #ifdef NOT_IN_USE // auto-open the advanced prop editor @@ -856,8 +856,8 @@ static void addSide(SidesList *sides, AsciiString faction, newPlayerDict.setBool(TheKey_playerIsHuman, false); newPlayerDict.setUnicodeString(TheKey_playerDisplayName, playerUStr); newPlayerDict.setAsciiString(TheKey_playerFaction, faction); - newPlayerDict.setAsciiString(TheKey_playerEnemies, AsciiString("")); - newPlayerDict.setAsciiString(TheKey_playerAllies, AsciiString("")); + newPlayerDict.setAsciiString(TheKey_playerEnemies, ""); + newPlayerDict.setAsciiString(TheKey_playerAllies, ""); ensureValidPlayerName(&newPlayerDict); sides->addSide(&newPlayerDict); diff --git a/scripts/cpp/refactor_asciistring_unicodestring_instantiation.py b/scripts/cpp/refactor_asciistring_unicodestring_instantiation.py new file mode 100644 index 0000000000..b65ab95d2e --- /dev/null +++ b/scripts/cpp/refactor_asciistring_unicodestring_instantiation.py @@ -0,0 +1,50 @@ +# Created with python 3.11.4 + +# This script applies basic formatting and cleanups to the various CPP files. +# Just run it. + +import glob +import os +import re + + +def fix_string(line: str, typename: str) -> str: + # Build a regex that allows arbitrary whitespace + pattern = rf"""{typename}\s*\(\s*"([^"]*)"\s*\)""" + # Replace typename( "value" ) -> "value" + return re.sub(pattern, r'"\1"', line) + + +def main(): + current_dir = os.path.dirname(os.path.abspath(__file__)) + root_dir = os.path.join(current_dir, "..", "..") + root_dir = os.path.normpath(root_dir) + core_dir = os.path.join(root_dir, "Core") + generals_dir = os.path.join(root_dir, "Generals") + generalsmd_dir = os.path.join(root_dir, "GeneralsMD") + utility_dir = os.path.join(root_dir, "Dependencies", "Utility") + fileNames = [] + for ext in ["*.cpp", "*.h", "*.inl"]: + fileNames.extend(glob.glob(os.path.join(core_dir, '**', ext), recursive=True)) + fileNames.extend(glob.glob(os.path.join(generals_dir, '**', ext), recursive=True)) + fileNames.extend(glob.glob(os.path.join(generalsmd_dir, '**', ext), recursive=True)) + fileNames.extend(glob.glob(os.path.join(utility_dir, '**', ext), recursive=True)) + + for fileName in fileNames: + with open(fileName, 'r', encoding="cp1252") as file: + try: + lines = file.readlines() + except UnicodeDecodeError: + continue # Not good. + + with open(fileName, 'w', encoding="cp1252") as file: + for line in lines: + line = fix_string(line, 'AsciiString') + #line = fix_string(line, 'UnicodeString') + file.write(line) + + return + + +if __name__ == "__main__": + main() From 963d7f757b1e61ebf994b4735fa326d8b7c3554f Mon Sep 17 00:00:00 2001 From: Bobby Battista Date: Sun, 30 Nov 2025 13:46:59 -0500 Subject: [PATCH 05/70] refactor: Remove superfluous variable init comments (#1876) --- Core/GameEngine/Include/GameClient/View.h | 3 --- .../Source/Common/Audio/GameAudio.cpp | 3 --- .../Source/Common/System/RAMFile.cpp | 3 --- .../Source/Common/System/XferCRC.cpp | 3 --- Core/GameEngine/Source/GameClient/View.cpp | 3 --- .../Source/GameNetwork/Connection.cpp | 3 --- .../Source/GameNetwork/DisconnectManager.cpp | 2 -- .../Source/GameNetwork/DownloadManager.cpp | 7 ------- .../Source/GameNetwork/FirewallHelper.cpp | 4 ---- .../Source/GameNetwork/FrameData.cpp | 3 --- .../Source/GameNetwork/FrameMetrics.cpp | 3 --- .../GameEngine/Source/GameNetwork/GameInfo.cpp | 4 ---- .../Source/GameNetwork/GameSpy/PeerDefs.cpp | 8 -------- .../GameSpy/StagingRoomGameInfo.cpp | 2 -- .../GameNetwork/GameSpy/Thread/PeerThread.cpp | 10 +--------- .../GameSpy/Thread/PersistentStorageThread.cpp | 3 --- .../Source/GameNetwork/LANGameInfo.cpp | 3 --- Core/GameEngine/Source/GameNetwork/NAT.cpp | 4 ---- .../Source/GameNetwork/NetCommandMsg.cpp | 11 ----------- .../GameNetwork/NetCommandWrapperList.cpp | 5 ----- Core/GameEngine/Source/GameNetwork/Network.cpp | 4 ---- .../Source/WWVegas/WW3D2/render2dsentence.cpp | 3 --- Core/Tools/Autorun/GameText.cpp | 2 +- .../Code/GameEngine/Include/Common/Geometry.h | 4 ---- Generals/Code/GameEngine/Include/Common/INI.h | 4 ---- .../GameEngine/Include/GameClient/ControlBar.h | 3 --- .../GameEngine/Include/GameClient/Display.h | 2 -- .../Include/GameClient/SelectionXlat.h | 2 -- .../GameEngine/Include/GameLogic/AIGuard.h | 2 -- .../GameEngine/Include/GameLogic/AIPlayer.h | 3 --- .../GameEngine/Include/GameLogic/GameLogic.h | 3 --- .../Include/GameLogic/Module/CreateCrateDie.h | 2 -- .../GameLogic/Module/DeliverPayloadAIUpdate.h | 9 --------- .../GameLogic/Module/DeployStyleAIUpdate.h | 3 --- .../GameLogic/Module/HackInternetAIUpdate.h | 6 ------ .../GameLogic/Module/ObjectDefectionHelper.h | 3 --- .../Include/GameLogic/Module/SpawnBehavior.h | 3 --- .../Include/GameLogic/Module/StealthUpdate.h | 3 --- .../GameLogic/Module/StructureCollapseUpdate.h | 3 --- .../Include/GameLogic/PartitionManager.h | 3 --- .../Source/Common/Bezier/BezFwdIterator.cpp | 4 ---- .../GameEngine/Source/Common/GlobalData.cpp | 12 +++--------- .../Source/Common/MultiplayerSettings.cpp | 7 ------- .../Source/Common/PartitionSolver.cpp | 3 --- .../GameEngine/Source/Common/PerfTimer.cpp | 5 ----- .../GameEngine/Source/Common/RTS/Player.cpp | 3 --- .../Common/RTS/ProductionPrerequisite.cpp | 4 ---- .../Source/Common/RTS/ScoreKeeper.cpp | 3 --- .../Code/GameEngine/Source/Common/RTS/Team.cpp | 5 ----- .../Code/GameEngine/Source/Common/Recorder.cpp | 4 ---- .../Source/Common/StatsCollector.cpp | 6 ------ .../Source/Common/System/DataChunk.cpp | 4 ---- .../Source/Common/System/Upgrade.cpp | 3 --- .../GameEngine/Source/GameClient/Display.cpp | 3 --- .../GameEngine/Source/GameClient/Drawable.cpp | 8 -------- .../GameClient/GUI/ControlBar/ControlBar.cpp | 16 ++-------------- .../GUI/ControlBar/ControlBarScheme.cpp | 10 ---------- .../GUICallbacks/Menus/LanGameOptionsMenu.cpp | 4 ---- .../GUI/GUICallbacks/Menus/MainMenu.cpp | 13 ------------- .../GUI/GUICallbacks/Menus/OptionsMenu.cpp | 5 ----- .../GUI/GUICallbacks/Menus/PopupSaveLoad.cpp | 12 ++---------- .../GUI/GUICallbacks/Menus/QuitMenu.cpp | 10 ---------- .../GUI/GUICallbacks/Menus/ScoreScreen.cpp | 5 ----- .../Menus/SkirmishGameOptionsMenu.cpp | 4 ---- .../GUICallbacks/Menus/WOLGameSetupMenu.cpp | 3 --- .../Source/GameClient/GUI/GameWindow.cpp | 2 -- .../Source/GameClient/GUI/HeaderTemplate.cpp | 2 -- .../Source/GameClient/GUI/IMEManager.cpp | 3 --- .../Source/GameClient/GUI/LoadScreen.cpp | 18 ------------------ .../Source/GameClient/GUI/Shell/Shell.cpp | 3 --- .../Source/GameClient/GameClient.cpp | 3 --- .../GameEngine/Source/GameClient/GameText.cpp | 6 +----- .../Source/GameClient/GlobalLanguage.cpp | 3 --- .../GameEngine/Source/GameClient/InGameUI.cpp | 5 ----- .../Source/GameClient/Input/Mouse.cpp | 7 ------- .../Source/GameClient/LanguageFilter.cpp | 3 --- .../Source/GameClient/MessageStream/HotKey.cpp | 3 --- .../GameClient/MessageStream/LookAtXlat.cpp | 3 --- .../GameClient/MessageStream/SelectionXlat.cpp | 5 ----- .../Source/GameClient/RadiusDecal.cpp | 2 +- .../Source/GameClient/SelectionInfo.cpp | 3 --- .../Source/GameClient/System/Anim2D.cpp | 11 ----------- .../Source/GameClient/System/ParticleSys.cpp | 18 ------------------ .../Code/GameEngine/Source/GameLogic/AI/AI.cpp | 3 --- .../Source/GameLogic/AI/AIPathfind.cpp | 4 ---- .../Source/GameLogic/AI/TurretAI.cpp | 6 ------ .../Source/GameLogic/Map/PolygonTrigger.cpp | 3 --- .../Source/GameLogic/Map/SidesList.cpp | 2 -- .../Source/GameLogic/Map/TerrainLogic.cpp | 3 --- .../Object/Behavior/ParkingPlaceBehavior.cpp | 7 ------- .../Behavior/PropagandaTowerBehavior.cpp | 3 --- .../Object/Behavior/SpawnBehavior.cpp | 3 --- .../Collide/CrateCollide/CrateCollide.cpp | 6 ------ .../GameLogic/Object/Contain/OpenContain.cpp | 3 --- .../Object/Contain/ParachuteContain.cpp | 3 --- .../GameLogic/Object/ExperienceTracker.cpp | 2 +- .../Source/GameLogic/Object/GhostObject.cpp | 2 -- .../Source/GameLogic/Object/Locomotor.cpp | 5 ----- .../Source/GameLogic/Object/Object.cpp | 3 --- .../GameLogic/Object/ObjectCreationList.cpp | 16 ++++------------ .../GameLogic/Object/PartitionManager.cpp | 3 --- .../Update/AIUpdate/DeliverPayloadAIUpdate.cpp | 8 -------- .../Object/Update/AIUpdate/DozerAIUpdate.cpp | 2 -- .../Object/Update/AIUpdate/JetAIUpdate.cpp | 3 --- .../Object/Update/AIUpdate/WorkerAIUpdate.cpp | 5 ----- .../Object/Update/BattlePlanUpdate.cpp | 5 ----- .../GameLogic/Object/Update/BoneFXUpdate.cpp | 1 - .../Object/Update/FlammableUpdate.cpp | 3 --- .../Update/HelicopterSlowDeathUpdate.cpp | 3 --- .../GameLogic/Object/Update/HordeUpdate.cpp | 3 --- .../GameLogic/Object/Update/LaserUpdate.cpp | 3 --- .../GameLogic/Object/Update/LifetimeUpdate.cpp | 3 --- .../Update/ParticleUplinkCannonUpdate.cpp | 3 --- .../DefaultProductionExitUpdate.cpp | 6 ------ .../QueueProductionExitUpdate.cpp | 4 ---- .../Object/Update/ProductionUpdate.cpp | 3 --- .../Object/Update/SpecialAbilityUpdate.cpp | 3 --- .../GameLogic/Object/Update/StealthUpdate.cpp | 3 --- .../Object/Update/StickyBombUpdate.cpp | 3 --- .../Object/Update/StructureCollapseUpdate.cpp | 3 --- .../Object/Update/StructureToppleUpdate.cpp | 4 ---- .../GameLogic/Object/Update/ToppleUpdate.cpp | 3 --- .../Object/Update/WaveGuideUpdate.cpp | 3 --- .../GameLogic/ScriptEngine/ScriptEngine.cpp | 3 --- .../Source/GameLogic/ScriptEngine/Scripts.cpp | 9 --------- .../Source/GameLogic/System/GameLogic.cpp | 6 ------ .../GameLogic/System/GameLogicDispatch.cpp | 3 --- .../GameClient/GUI/Gadget/W3DProgressBar.cpp | 1 - .../Code/GameEngine/Include/Common/Geometry.h | 4 ---- .../Code/GameEngine/Include/Common/INI.h | 4 ---- .../GameEngine/Include/GameClient/ControlBar.h | 3 --- .../GameEngine/Include/GameClient/Display.h | 2 -- .../Include/GameClient/SelectionXlat.h | 2 -- .../GameEngine/Include/GameLogic/AIGuard.h | 2 -- .../Include/GameLogic/AIGuardRetaliate.h | 2 -- .../GameEngine/Include/GameLogic/AIPlayer.h | 3 --- .../GameEngine/Include/GameLogic/GameLogic.h | 3 --- .../Include/GameLogic/Module/CreateCrateDie.h | 2 -- .../GameLogic/Module/DeliverPayloadAIUpdate.h | 9 --------- .../GameLogic/Module/DeployStyleAIUpdate.h | 3 --- .../GameLogic/Module/HackInternetAIUpdate.h | 6 ------ .../GameLogic/Module/ObjectDefectionHelper.h | 3 --- .../Include/GameLogic/Module/SpawnBehavior.h | 3 --- .../GameLogic/Module/StructureCollapseUpdate.h | 3 --- .../Include/GameLogic/PartitionManager.h | 3 --- .../Source/Common/Bezier/BezFwdIterator.cpp | 4 ---- .../GameEngine/Source/Common/GlobalData.cpp | 12 +++--------- .../Source/Common/MultiplayerSettings.cpp | 1 - .../Source/Common/PartitionSolver.cpp | 3 --- .../GameEngine/Source/Common/PerfTimer.cpp | 5 ----- .../GameEngine/Source/Common/RTS/Player.cpp | 3 --- .../Common/RTS/ProductionPrerequisite.cpp | 4 ---- .../Source/Common/RTS/ScoreKeeper.cpp | 3 --- .../Code/GameEngine/Source/Common/RTS/Team.cpp | 4 ---- .../Code/GameEngine/Source/Common/Recorder.cpp | 4 ---- .../Source/Common/StatsCollector.cpp | 6 ------ .../Source/Common/System/DataChunk.cpp | 4 ---- .../Source/Common/System/Upgrade.cpp | 3 --- .../GameEngine/Source/GameClient/Display.cpp | 3 --- .../GameEngine/Source/GameClient/Drawable.cpp | 8 -------- .../GameClient/GUI/ControlBar/ControlBar.cpp | 14 ++------------ .../GUI/ControlBar/ControlBarScheme.cpp | 10 ---------- .../GUICallbacks/Menus/LanGameOptionsMenu.cpp | 4 ---- .../GUI/GUICallbacks/Menus/MainMenu.cpp | 13 ------------- .../GUI/GUICallbacks/Menus/OptionsMenu.cpp | 5 ----- .../GUI/GUICallbacks/Menus/PopupSaveLoad.cpp | 12 ++---------- .../GUI/GUICallbacks/Menus/QuitMenu.cpp | 10 ---------- .../GUI/GUICallbacks/Menus/ScoreScreen.cpp | 4 ---- .../Menus/SkirmishGameOptionsMenu.cpp | 4 ---- .../GUICallbacks/Menus/WOLGameSetupMenu.cpp | 3 --- .../Source/GameClient/GUI/GameWindow.cpp | 2 -- .../Source/GameClient/GUI/HeaderTemplate.cpp | 2 -- .../Source/GameClient/GUI/IMEManager.cpp | 3 --- .../Source/GameClient/GUI/LoadScreen.cpp | 18 ------------------ .../Source/GameClient/GUI/Shell/Shell.cpp | 3 --- .../Source/GameClient/GameClient.cpp | 3 --- .../GameEngine/Source/GameClient/GameText.cpp | 5 +---- .../Source/GameClient/GlobalLanguage.cpp | 3 --- .../GameEngine/Source/GameClient/InGameUI.cpp | 5 ----- .../Source/GameClient/Input/Mouse.cpp | 7 ------- .../Source/GameClient/LanguageFilter.cpp | 3 --- .../Source/GameClient/MessageStream/HotKey.cpp | 3 --- .../GameClient/MessageStream/LookAtXlat.cpp | 3 --- .../GameClient/MessageStream/SelectionXlat.cpp | 5 ----- .../Source/GameClient/RadiusDecal.cpp | 2 +- .../Source/GameClient/System/Anim2D.cpp | 10 ---------- .../Source/GameClient/System/ParticleSys.cpp | 18 ------------------ .../Code/GameEngine/Source/GameLogic/AI/AI.cpp | 3 --- .../Source/GameLogic/AI/AIPathfind.cpp | 4 ---- .../Source/GameLogic/AI/TurretAI.cpp | 6 ------ .../Source/GameLogic/Map/PolygonTrigger.cpp | 3 --- .../Source/GameLogic/Map/SidesList.cpp | 2 -- .../Source/GameLogic/Map/TerrainLogic.cpp | 3 --- .../Object/Behavior/ParkingPlaceBehavior.cpp | 7 ------- .../Behavior/PropagandaTowerBehavior.cpp | 3 --- .../Object/Behavior/SpawnBehavior.cpp | 3 --- .../Collide/CrateCollide/CrateCollide.cpp | 6 ------ .../GameLogic/Object/Contain/OpenContain.cpp | 3 --- .../Object/Contain/ParachuteContain.cpp | 3 --- .../GameLogic/Object/ExperienceTracker.cpp | 2 +- .../Source/GameLogic/Object/GhostObject.cpp | 2 -- .../Source/GameLogic/Object/Locomotor.cpp | 5 ----- .../Source/GameLogic/Object/Object.cpp | 3 --- .../GameLogic/Object/ObjectCreationList.cpp | 16 ++++------------ .../GameLogic/Object/PartitionManager.cpp | 3 --- .../GameLogic/Object/Update/AIUpdate.cpp | 4 ---- .../Update/AIUpdate/DeliverPayloadAIUpdate.cpp | 8 -------- .../Object/Update/AIUpdate/DozerAIUpdate.cpp | 2 -- .../Object/Update/AIUpdate/JetAIUpdate.cpp | 3 --- .../Object/Update/AIUpdate/WorkerAIUpdate.cpp | 5 ----- .../Object/Update/BattlePlanUpdate.cpp | 5 ----- .../GameLogic/Object/Update/BoneFXUpdate.cpp | 1 - .../Object/Update/FlammableUpdate.cpp | 3 --- .../Update/HelicopterSlowDeathUpdate.cpp | 3 --- .../GameLogic/Object/Update/HordeUpdate.cpp | 3 --- .../GameLogic/Object/Update/LaserUpdate.cpp | 3 --- .../GameLogic/Object/Update/LifetimeUpdate.cpp | 3 --- .../Update/ParticleUplinkCannonUpdate.cpp | 3 --- .../DefaultProductionExitUpdate.cpp | 6 ------ .../QueueProductionExitUpdate.cpp | 4 ---- .../Object/Update/ProductionUpdate.cpp | 3 --- .../Object/Update/SpecialAbilityUpdate.cpp | 3 --- .../GameLogic/Object/Update/StealthUpdate.cpp | 6 ------ .../Object/Update/StickyBombUpdate.cpp | 3 --- .../Object/Update/StructureCollapseUpdate.cpp | 3 --- .../Object/Update/StructureToppleUpdate.cpp | 4 ---- .../GameLogic/Object/Update/ToppleUpdate.cpp | 3 --- .../Object/Update/WaveGuideUpdate.cpp | 3 --- .../GameLogic/ScriptEngine/ScriptEngine.cpp | 3 --- .../Source/GameLogic/ScriptEngine/Scripts.cpp | 9 --------- .../Source/GameLogic/System/GameLogic.cpp | 6 ------ .../GameLogic/System/GameLogicDispatch.cpp | 3 --- .../GameClient/GUI/Gadget/W3DProgressBar.cpp | 1 - 233 files changed, 30 insertions(+), 1037 deletions(-) diff --git a/Core/GameEngine/Include/GameClient/View.h b/Core/GameEngine/Include/GameClient/View.h index f61a1db60d..9d26976deb 100644 --- a/Core/GameEngine/Include/GameClient/View.h +++ b/Core/GameEngine/Include/GameClient/View.h @@ -311,11 +311,8 @@ class ViewLocation ViewLocation() { m_valid = FALSE; - //Added By Sadullah Nader - //Initialization(s) inserted m_pos.zero(); m_angle = m_pitch = m_zoom = 0.0; - // } const Coord3D& getPosition() const { return m_pos; } diff --git a/Core/GameEngine/Source/Common/Audio/GameAudio.cpp b/Core/GameEngine/Source/Common/Audio/GameAudio.cpp index a5844c063b..9917266a64 100644 --- a/Core/GameEngine/Source/Common/Audio/GameAudio.cpp +++ b/Core/GameEngine/Source/Common/Audio/GameAudio.cpp @@ -152,7 +152,6 @@ AudioManager::AudioManager() : m_hardwareAccel(FALSE), m_musicPlayingFromCD(FALSE) { - // Added by Sadullah Nader m_adjustedVolumes.clear(); m_audioRequests.clear(); m_listenerPosition.zero(); @@ -166,8 +165,6 @@ AudioManager::AudioManager() : m_systemSoundVolume = 0.0f; m_systemSpeechVolume = 0.0f; m_volumeHasChanged = FALSE; - // - m_listenerOrientation.set(0.0, 1.0, 0.0); theAudioHandlePool = AHSV_FirstHandle; m_audioSettings = NEW AudioSettings; diff --git a/Core/GameEngine/Source/Common/System/RAMFile.cpp b/Core/GameEngine/Source/Common/System/RAMFile.cpp index a10b63f5e7..93d5994b45 100644 --- a/Core/GameEngine/Source/Common/System/RAMFile.cpp +++ b/Core/GameEngine/Source/Common/System/RAMFile.cpp @@ -104,10 +104,7 @@ RAMFile::RAMFile() : m_size(0), m_data(NULL), -//Added By Sadullah Nader -//Initializtion(s) inserted m_pos(0) -// { } diff --git a/Core/GameEngine/Source/Common/System/XferCRC.cpp b/Core/GameEngine/Source/Common/System/XferCRC.cpp index 087d0cb95a..520cd2cc4f 100644 --- a/Core/GameEngine/Source/Common/System/XferCRC.cpp +++ b/Core/GameEngine/Source/Common/System/XferCRC.cpp @@ -42,10 +42,7 @@ XferCRC::XferCRC( void ) { m_xferMode = XFER_CRC; - //Added By Sadullah Nader - //Initialization(s) inserted m_crc = 0; - // } //------------------------------------------------------------------------------------------------- diff --git a/Core/GameEngine/Source/GameClient/View.cpp b/Core/GameEngine/Source/GameClient/View.cpp index 6e760b2dd3..9794560208 100644 --- a/Core/GameEngine/Source/GameClient/View.cpp +++ b/Core/GameEngine/Source/GameClient/View.cpp @@ -41,8 +41,6 @@ View *TheTacticalView = NULL; View::View( void ) { - //Added By Sadullah Nader - //Initialization(s) inserted m_viewLockedUntilFrame = 0u; m_currentHeightAboveGround = 0.0f; m_defaultAngle = 0.0f; @@ -58,7 +56,6 @@ View::View( void ) m_snapImmediate = FALSE; m_terrainHeightUnderCamera = 0.0f; m_zoom = 0.0f; - // m_pos.x = 0; m_pos.y = 0; m_width = 0; diff --git a/Core/GameEngine/Source/GameNetwork/Connection.cpp b/Core/GameEngine/Source/GameNetwork/Connection.cpp index 0e2419ded5..fe804e5ae8 100644 --- a/Core/GameEngine/Source/GameNetwork/Connection.cpp +++ b/Core/GameEngine/Source/GameNetwork/Connection.cpp @@ -43,15 +43,12 @@ Connection::Connection() { m_frameGrouping = 1; m_isQuitting = false; m_quitTime = 0; - // Added By Sadullah Nader - // clearing out the latency tracker m_averageLatency = 0.0f; Int i; for(i = 0; i < CONNECTION_LATENCY_HISTORY_LENGTH; i++) { m_latencies[i] = 0.0f; } - // End Add } /** diff --git a/Core/GameEngine/Source/GameNetwork/DisconnectManager.cpp b/Core/GameEngine/Source/GameNetwork/DisconnectManager.cpp index cd00da753c..94beda05da 100644 --- a/Core/GameEngine/Source/GameNetwork/DisconnectManager.cpp +++ b/Core/GameEngine/Source/GameNetwork/DisconnectManager.cpp @@ -38,8 +38,6 @@ DisconnectManager::DisconnectManager() { - // Added By Sadullah Nader - // Initializations missing and needed Int i; m_currentPacketRouterIndex = 0; m_lastFrame = 0; diff --git a/Core/GameEngine/Source/GameNetwork/DownloadManager.cpp b/Core/GameEngine/Source/GameNetwork/DownloadManager.cpp index 6bfe74911e..b84abac918 100644 --- a/Core/GameEngine/Source/GameNetwork/DownloadManager.cpp +++ b/Core/GameEngine/Source/GameNetwork/DownloadManager.cpp @@ -37,14 +37,7 @@ DownloadManager::DownloadManager() { m_download = NEW CDownload(this); m_wasError = m_sawEnd = false; - - //Added By Sadullah Nader - //Initializations missing and needed - m_queuedDownloads.clear(); - - // - m_statusString = TheGameText->fetch("FTP:StatusIdle"); // ----- Initialize Winsock ----- diff --git a/Core/GameEngine/Source/GameNetwork/FirewallHelper.cpp b/Core/GameEngine/Source/GameNetwork/FirewallHelper.cpp index e650c3c272..320b672ee9 100644 --- a/Core/GameEngine/Source/GameNetwork/FirewallHelper.cpp +++ b/Core/GameEngine/Source/GameNetwork/FirewallHelper.cpp @@ -83,16 +83,12 @@ FirewallHelperClass * createFirewallHelper() FirewallHelperClass::FirewallHelperClass(void) { - //Added Sadullah Nader - //Initializations missing and needed m_currentTry = 0; m_numManglers = 0; m_numResponses = 0; m_packetID = 0; m_timeoutLength = 0; m_timeoutStart = 0; - // - m_behavior = FIREWALL_TYPE_UNKNOWN; m_lastBehavior = FIREWALL_TYPE_UNKNOWN; m_sourcePortAllocationDelta = 0; diff --git a/Core/GameEngine/Source/GameNetwork/FrameData.cpp b/Core/GameEngine/Source/GameNetwork/FrameData.cpp index 78a96cd622..da5fef6e76 100644 --- a/Core/GameEngine/Source/GameNetwork/FrameData.cpp +++ b/Core/GameEngine/Source/GameNetwork/FrameData.cpp @@ -37,11 +37,8 @@ FrameData::FrameData() m_commandList = NULL; m_commandCount = 0; m_frameCommandCount = -1; - //Added By Sadullah Nader - //Initializations missing and needed m_lastFailedCC = 0; m_lastFailedFrameCC = 0; - // } /** diff --git a/Core/GameEngine/Source/GameNetwork/FrameMetrics.cpp b/Core/GameEngine/Source/GameNetwork/FrameMetrics.cpp index a524a7e216..a9a9aca66e 100644 --- a/Core/GameEngine/Source/GameNetwork/FrameMetrics.cpp +++ b/Core/GameEngine/Source/GameNetwork/FrameMetrics.cpp @@ -32,8 +32,6 @@ FrameMetrics::FrameMetrics() { - //Added By Sadullah Nader - //Initializations missing and needed m_averageFps = 0.0f; m_averageLatency = 0.0f; m_cushionIndex = 0; @@ -44,7 +42,6 @@ FrameMetrics::FrameMetrics() m_pendingLatencies = NEW time_t[MAX_FRAMES_AHEAD]; for(Int i = 0; i < MAX_FRAMES_AHEAD; i++) m_pendingLatencies[i] = 0; - // m_fpsList = NEW Real[TheGlobalData->m_networkFPSHistoryLength]; m_latencyList = NEW Real[TheGlobalData->m_networkLatencyHistoryLength]; } diff --git a/Core/GameEngine/Source/GameNetwork/GameInfo.cpp b/Core/GameEngine/Source/GameNetwork/GameInfo.cpp index 20bc7e334b..8551069dae 100644 --- a/Core/GameEngine/Source/GameNetwork/GameInfo.cpp +++ b/Core/GameEngine/Source/GameNetwork/GameInfo.cpp @@ -307,8 +307,6 @@ void GameInfo::reset( void ) m_useStats = TRUE; m_surrendered = FALSE; m_oldFactionsOnly = FALSE; - // Added By Sadullah Nader - // Initializations missing and needed // m_localIP = 0; // BGC - actually we don't want this to be reset since the m_localIP is // set properly in the constructor of LANGameInfo which uses this as a base class. m_mapCRC = 0; @@ -316,8 +314,6 @@ void GameInfo::reset( void ) m_superweaponRestriction = 0; m_startingCash = TheGlobalData->m_defaultStartingCash; - // - for (Int i=0; igetNumChunks(); m_chunksPresent = NEW Bool[m_numChunks]; // pool[]ify m_numChunksPresent = 0; diff --git a/Core/GameEngine/Source/GameNetwork/Network.cpp b/Core/GameEngine/Source/GameNetwork/Network.cpp index 160e41bd39..de436e7b58 100644 --- a/Core/GameEngine/Source/GameNetwork/Network.cpp +++ b/Core/GameEngine/Source/GameNetwork/Network.cpp @@ -265,15 +265,11 @@ NetworkInterface *NetworkInterface::createNetwork() */ Network::Network() { - //Added By Sadullah Nader - //Initializations inserted m_checkCRCsThisFrame = FALSE; m_didSelfSlug = FALSE; m_frameDataReady = FALSE; m_isStalling = FALSE; m_sawCRCMismatch = FALSE; - // - m_conMgr = NULL; m_messageWindow = NULL; diff --git a/Core/Libraries/Source/WWVegas/WW3D2/render2dsentence.cpp b/Core/Libraries/Source/WWVegas/WW3D2/render2dsentence.cpp index 34a347c50b..e307f2e41f 100644 --- a/Core/Libraries/Source/WWVegas/WW3D2/render2dsentence.cpp +++ b/Core/Libraries/Source/WWVegas/WW3D2/render2dsentence.cpp @@ -785,7 +785,6 @@ void Render2DSentenceClass::Build_Sentence_Centered (const WCHAR *text, int *hkX 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; @@ -796,7 +795,6 @@ void Render2DSentenceClass::Build_Sentence_Centered (const WCHAR *text, int *hkX offset =-1; } } - // *word++; calcHotKeyX = true; } @@ -853,7 +851,6 @@ void Render2DSentenceClass::Build_Sentence_Centered (const WCHAR *text, int *hkX // word_width = Font->Get_Char_Spacing (*word++); wordCount = 0; - //Added By Saad line_width += word_width; } // diff --git a/Core/Tools/Autorun/GameText.cpp b/Core/Tools/Autorun/GameText.cpp index edde74bdfa..f961646d97 100644 --- a/Core/Tools/Autorun/GameText.cpp +++ b/Core/Tools/Autorun/GameText.cpp @@ -227,7 +227,7 @@ GameTextManager::GameTextManager() m_munkee(FALSE), m_noStringList(NULL), m_useStringFile(TRUE), - m_failed(L"***FATAL*** String Manager failed to initilaized properly") + m_failed(L"***FATAL*** String Manager failed to initialized properly") { } diff --git a/Generals/Code/GameEngine/Include/Common/Geometry.h b/Generals/Code/GameEngine/Include/Common/Geometry.h index 9501c2c9d4..029c854ca0 100644 --- a/Generals/Code/GameEngine/Include/Common/Geometry.h +++ b/Generals/Code/GameEngine/Include/Common/Geometry.h @@ -111,12 +111,8 @@ class GeometryInfo : public Snapshot GeometryInfo(GeometryType type, Bool isSmall, Real height, Real majorRadius, Real minorRadius) { - // Added by Sadullah Nader - // Initializations missing and needed m_boundingCircleRadius = 0.0f; m_boundingSphereRadius = 0.0f; - // - set(type, isSmall, height, majorRadius, minorRadius); } diff --git a/Generals/Code/GameEngine/Include/Common/INI.h b/Generals/Code/GameEngine/Include/Common/INI.h index 861f61f7e4..0e5c0e4f8e 100644 --- a/Generals/Code/GameEngine/Include/Common/INI.h +++ b/Generals/Code/GameEngine/Include/Common/INI.h @@ -138,12 +138,8 @@ class MultiIniFieldParse public: MultiIniFieldParse() : m_count(0) { - //Added By Sadullah Nader - //Initializations missing and needed for(Int i = 0; i < MAX_MULTI_FIELDS; i++) m_extraOffset[i] = 0; - // - } void add(const FieldParse* f, UnsignedInt e = 0); diff --git a/Generals/Code/GameEngine/Include/GameClient/ControlBar.h b/Generals/Code/GameEngine/Include/GameClient/ControlBar.h index 2a0cf0823d..19e6580aae 100644 --- a/Generals/Code/GameEngine/Include/GameClient/ControlBar.h +++ b/Generals/Code/GameEngine/Include/GameClient/ControlBar.h @@ -434,8 +434,6 @@ class SideSelectWindowData public: SideSelectWindowData(void) { - //Added By Sadullah Nader - //Initializations generalSpeak = NULL; m_currColor = 0; m_gereralsNameWin = NULL; @@ -459,7 +457,6 @@ class SideSelectWindowData m_upgradeLabel3Win = NULL; m_upgradeLabel4Win = NULL; sideWindow = NULL; - // } ~SideSelectWindowData(void); diff --git a/Generals/Code/GameEngine/Include/GameClient/Display.h b/Generals/Code/GameEngine/Include/GameClient/Display.h index 5823e8aef6..3d6a9d857c 100644 --- a/Generals/Code/GameEngine/Include/GameClient/Display.h +++ b/Generals/Code/GameEngine/Include/GameClient/Display.h @@ -218,10 +218,8 @@ extern Display *TheDisplay; extern void StatDebugDisplay( DebugDisplayInterface *dd, void *, FILE *fp = NULL ); -//Added By Saad //Necessary for display resolution confirmation dialog box //Holds the previous and current display settings - typedef struct _DisplaySettings { Int xRes; //Resolution width diff --git a/Generals/Code/GameEngine/Include/GameClient/SelectionXlat.h b/Generals/Code/GameEngine/Include/GameClient/SelectionXlat.h index c6df1833a8..978ccfb1b6 100644 --- a/Generals/Code/GameEngine/Include/GameClient/SelectionXlat.h +++ b/Generals/Code/GameEngine/Include/GameClient/SelectionXlat.h @@ -62,8 +62,6 @@ class SelectionTranslator : public GameMessageTranslator SelectionTranslator(); ~SelectionTranslator(); virtual GameMessageDisposition translateGameMessage(const GameMessage *msg); - - //Added By Sadullah Nader //added for fix to the drag selection when entering control bar //changes the mode of drag selecting to it's opposite void setDragSelecting(Bool dragSelect); diff --git a/Generals/Code/GameEngine/Include/GameLogic/AIGuard.h b/Generals/Code/GameEngine/Include/GameLogic/AIGuard.h index 45d6863d69..9672c5668f 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/AIGuard.h +++ b/Generals/Code/GameEngine/Include/GameLogic/AIGuard.h @@ -78,8 +78,6 @@ class ExitConditions : public AttackExitConditionsInterface ExitConditions() : m_attackGiveUpFrame(0), m_conditionsToConsider(0), m_radiusSqr(0.0f) { - //Added By Sadullah Nader - // Initializations missing and needed m_center.zero(); } diff --git a/Generals/Code/GameEngine/Include/GameLogic/AIPlayer.h b/Generals/Code/GameEngine/Include/GameLogic/AIPlayer.h index e4a8ab352b..1e42be0603 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/AIPlayer.h +++ b/Generals/Code/GameEngine/Include/GameLogic/AIPlayer.h @@ -113,11 +113,8 @@ class TeamInQueue : public MemoryPoolObject, m_reinforcement(false), m_stopQueueing(false), m_reinforcementID(INVALID_ID), - //Added By Sadullah Nader - //Initialization(s) inserted m_frameStarted(0), m_priorityBuild(FALSE) - // { } diff --git a/Generals/Code/GameEngine/Include/GameLogic/GameLogic.h b/Generals/Code/GameEngine/Include/GameLogic/GameLogic.h index abfc552b96..0993841d0a 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/GameLogic.h +++ b/Generals/Code/GameEngine/Include/GameLogic/GameLogic.h @@ -292,9 +292,6 @@ class GameLogic : public SubsystemInterface, public Snapshot std::map m_cachedCRCs; ///< CRCs we've seen this frame Bool m_shouldValidateCRCs; ///< Should we validate CRCs this frame? //----------------------------------------------------------------------------------------------- - - //Added By Sadullah Nader - //Used to for load scene Bool m_loadingScene; Bool m_isInUpdate; diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/CreateCrateDie.h b/Generals/Code/GameEngine/Include/GameLogic/Module/CreateCrateDie.h index 90dccafc31..4cbc1f77b1 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/CreateCrateDie.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/CreateCrateDie.h @@ -46,8 +46,6 @@ class CreateCrateDieModuleData : public DieModuleData CreateCrateDieModuleData() { - // Added By Sadullah Nader - // Initializations missing and needed m_crateNameList.clear(); } ~CreateCrateDieModuleData() diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/DeliverPayloadAIUpdate.h b/Generals/Code/GameEngine/Include/GameLogic/Module/DeliverPayloadAIUpdate.h index f82fd57a74..17b8925305 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/DeliverPayloadAIUpdate.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/DeliverPayloadAIUpdate.h @@ -202,11 +202,7 @@ class DeliverPayloadAIUpdateModuleData : public AIUpdateModuleData m_dropOffset.zero(); m_dropVariance.zero(); m_deliveryDecalRadius = 0; - // Added By Sadullah Nader - // Initialization missing and needed - m_putInContainerName.clear(); - // End Add } static void buildFieldParse(MultiIniFieldParse& p) @@ -293,14 +289,9 @@ class DeliverPayloadData m_visiblePayloadWeaponTemplate = NULL; m_selfDestructObject = FALSE; m_deliveryDecalRadius = 0; - // Added By Sadullah Nader - // Initialization missing and needed - m_visibleDropBoneName.clear(); m_visiblePayloadTemplateName.clear(); m_visibleSubObjectName.clear(); - - // End Add } static const FieldParse* getFieldParse(); diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/DeployStyleAIUpdate.h b/Generals/Code/GameEngine/Include/GameLogic/Module/DeployStyleAIUpdate.h index 19223d5057..74a90c299a 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/DeployStyleAIUpdate.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/DeployStyleAIUpdate.h @@ -58,10 +58,7 @@ class DeployStyleAIUpdateModuleData : public AIUpdateModuleData m_packTime = 0; m_resetTurretBeforePacking = false; m_turretsFunctionOnlyWhenDeployed = false; - // Added By Sadullah Nader - // Initialization necessary m_turretsMustCenterBeforePacking = FALSE; - // End Add } static void buildFieldParse(MultiIniFieldParse& p) diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/HackInternetAIUpdate.h b/Generals/Code/GameEngine/Include/GameLogic/Module/HackInternetAIUpdate.h index 7c161b47fa..8599b393c5 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/HackInternetAIUpdate.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/HackInternetAIUpdate.h @@ -46,10 +46,7 @@ class HackInternetState : public State public: HackInternetState( StateMachine *machine ) :State( machine, "HackInternetState" ) { - //Added By Sadullah Nader - //Initializations missing and needed m_framesRemaining = 0; - // } virtual StateReturnType update(); virtual StateReturnType onEnter(); @@ -73,10 +70,7 @@ class PackingState : public State public: PackingState( StateMachine *machine ) : State( machine, "PackingState" ) { - //Added By Sadullah Nader - //Initializations inserted m_framesRemaining = 0; - // } virtual StateReturnType update(); virtual StateReturnType onEnter(); diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/ObjectDefectionHelper.h b/Generals/Code/GameEngine/Include/GameLogic/Module/ObjectDefectionHelper.h index 1037db0bf2..27a8ea53fe 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/ObjectDefectionHelper.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/ObjectDefectionHelper.h @@ -61,13 +61,10 @@ class ObjectDefectionHelper : public ObjectHelper ObjectDefectionHelper( Thing *thing, const ModuleData *modData ) : ObjectHelper( thing, modData ) { - //Added By Sadullah Nader - //Initializations inserted m_defectionDetectionEnd = 0; m_defectionDetectionFlashPhase = FALSE; m_defectionDetectionStart = 0; m_doDefectorFX = FALSE; - // } // virtual destructor prototype provided by memory pool object diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/SpawnBehavior.h b/Generals/Code/GameEngine/Include/GameLogic/Module/SpawnBehavior.h index 3f602420f0..debea0cc3e 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/SpawnBehavior.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/SpawnBehavior.h @@ -64,10 +64,7 @@ class SpawnBehaviorModuleData : public BehaviorModuleData { m_spawnNumberData = 0; m_spawnReplaceDelayData = 0; - //Added By Sadullah Nader - //Initialization(s) inserted m_spawnStartNumberData = 0; - // m_initialBurst = 0; m_isOneShotData = FALSE; m_canReclaimOrphans = FALSE; diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/StealthUpdate.h b/Generals/Code/GameEngine/Include/GameLogic/Module/StealthUpdate.h index 87cf4908b3..649e36d359 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/StealthUpdate.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/StealthUpdate.h @@ -85,11 +85,8 @@ class StealthUpdateModuleData : public UpdateModuleData StealthUpdateModuleData() { - //Added By Sadullah Nader - //Initialization(s) inserted m_disguiseFX = NULL; m_disguiseRevealFX = NULL; - // m_stealthDelay = UINT_MAX; m_stealthLevel = 0; m_stealthSpeed = 0.0f; diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/StructureCollapseUpdate.h b/Generals/Code/GameEngine/Include/GameLogic/Module/StructureCollapseUpdate.h index 3c21400835..13c1919e7f 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/StructureCollapseUpdate.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/StructureCollapseUpdate.h @@ -75,9 +75,6 @@ class StructureCollapseUpdateModuleData : public UpdateModuleData m_minCollapseDelay = 0; m_maxCollapseDelay = 0; m_minBurstDelay = 9999; - //Removed by Sadullah Nader - //Redundancy from above - //m_minBurstDelay = 9999; m_maxShudder = 0; m_collapseDamping = 0.0; m_bigBurstFrequency = 0; diff --git a/Generals/Code/GameEngine/Include/GameLogic/PartitionManager.h b/Generals/Code/GameEngine/Include/GameLogic/PartitionManager.h index f924fa3a0a..4b26a65620 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/PartitionManager.h +++ b/Generals/Code/GameEngine/Include/GameLogic/PartitionManager.h @@ -1109,10 +1109,7 @@ class PartitionFilterGarrisonable : public PartitionFilter public: PartitionFilterGarrisonable( Bool match ) : m_match(match) { - //Added By Sadullah Nader - //Initializations m_player = NULL; - // } protected: virtual Bool allow( Object *other ); diff --git a/Generals/Code/GameEngine/Source/Common/Bezier/BezFwdIterator.cpp b/Generals/Code/GameEngine/Source/Common/Bezier/BezFwdIterator.cpp index b7fdb96ab6..13c26feb03 100644 --- a/Generals/Code/GameEngine/Source/Common/Bezier/BezFwdIterator.cpp +++ b/Generals/Code/GameEngine/Source/Common/Bezier/BezFwdIterator.cpp @@ -28,7 +28,6 @@ //------------------------------------------------------------------------------------------------- BezFwdIterator::BezFwdIterator(): mStep(0), mStepsDesired(0) { - // Added by Sadullah Nader mCurrPoint.zero(); mDDDq.zero(); mDDq.zero(); @@ -38,13 +37,10 @@ BezFwdIterator::BezFwdIterator(): mStep(0), mStepsDesired(0) //------------------------------------------------------------------------------------------------- BezFwdIterator::BezFwdIterator(Int stepsDesired, const BezierSegment *bezSeg) { - // Added by Sadullah Nader mCurrPoint.zero(); mDDDq.zero(); mDDq.zero(); mDq.zero(); - // - mStepsDesired = stepsDesired; mBezSeg = (*bezSeg); } diff --git a/Generals/Code/GameEngine/Source/Common/GlobalData.cpp b/Generals/Code/GameEngine/Source/Common/GlobalData.cpp index 9e573ad77b..9bb81b3165 100644 --- a/Generals/Code/GameEngine/Source/Common/GlobalData.cpp +++ b/Generals/Code/GameEngine/Source/Common/GlobalData.cpp @@ -579,13 +579,13 @@ GlobalData::GlobalData() m_debugVisibilityTileDuration = LOGICFRAMES_PER_SECOND; m_debugProjectilePath = FALSE; m_debugProjectileTileWidth = 10; - m_debugProjectileTileDuration = LOGICFRAMES_PER_SECOND; // Changed By Sadullah Nader + m_debugProjectileTileDuration = LOGICFRAMES_PER_SECOND; m_debugThreatMap = FALSE; m_maxDebugThreat = 5000; - m_debugThreatMapTileDuration = LOGICFRAMES_PER_SECOND; // Changed By Sadullah Nader + m_debugThreatMapTileDuration = LOGICFRAMES_PER_SECOND; m_debugCashValueMap = FALSE; m_maxDebugValue = 10000; - m_debugCashValueMapTileDuration = LOGICFRAMES_PER_SECOND; // Changed By Sadullah Nader + m_debugCashValueMapTileDuration = LOGICFRAMES_PER_SECOND; m_vTune = false; m_checkForLeaks = TRUE; m_benchmarkTimer = -1; @@ -689,8 +689,6 @@ GlobalData::GlobalData() m_vertexWaterAttenuationB[ i ] = 0.0f; m_vertexWaterAttenuationC[ i ] = 0.0f; m_vertexWaterAttenuationRange[ i ] = 0.0f; - //Added By Sadullah Nader - //Initializations missing and needed m_vertexWaterAvailableMaps[i].clear(); } @@ -802,8 +800,6 @@ GlobalData::GlobalData() m_autoSmokeParticleLargeMax = 0; m_autoAflameParticleMax = 0; - // Added By Sadullah Nader - // Initializations missing and needed m_autoFireParticleSmallPrefix.clear(); m_autoFireParticleMediumPrefix.clear(); m_autoFireParticleLargePrefix.clear(); @@ -827,8 +823,6 @@ GlobalData::GlobalData() m_maxParticleCount = 0; m_maxFieldParticleCount = 30; - // End Add - m_debugAI = AI_DEBUG_NONE; m_debugSupplyCenterPlacement = FALSE; m_debugAIObstacles = FALSE; diff --git a/Generals/Code/GameEngine/Source/Common/MultiplayerSettings.cpp b/Generals/Code/GameEngine/Source/Common/MultiplayerSettings.cpp index 9b410ab632..f9ec094415 100644 --- a/Generals/Code/GameEngine/Source/Common/MultiplayerSettings.cpp +++ b/Generals/Code/GameEngine/Source/Common/MultiplayerSettings.cpp @@ -74,21 +74,14 @@ const FieldParse MultiplayerSettings::m_multiplayerSettingsFieldParseTable[] = MultiplayerSettings::MultiplayerSettings() { m_initialCreditsMin = 5000; - - //Fixed And Added Code By Sadullah Nader - //DID U MEAN m_initialCreditsMax = 10000;? - //Initializations inserted m_initialCreditsMax = 10000; m_maxBeaconsPerPlayer = 3; - // - m_startCountdownTimerSeconds = 0; m_numColors = 0; m_isShroudInMultiplayer = TRUE; m_showRandomPlayerTemplate = TRUE; m_showRandomStartPos = TRUE; m_showRandomColor = TRUE; - m_observerColor; m_randomColor; } diff --git a/Generals/Code/GameEngine/Source/Common/PartitionSolver.cpp b/Generals/Code/GameEngine/Source/Common/PartitionSolver.cpp index 27de4d19df..f33969a3b7 100644 --- a/Generals/Code/GameEngine/Source/Common/PartitionSolver.cpp +++ b/Generals/Code/GameEngine/Source/Common/PartitionSolver.cpp @@ -63,10 +63,7 @@ PartitionSolver::PartitionSolver(const EntriesVec& elements, const SpacesVec& sp m_data = elements; m_spacesForData = spaces; m_howToSolve = solveHow; - //Added By Sadullah Nader - //Initializations inserted m_currentSolutionLeftovers = 0; - // } void PartitionSolver::solve(void) diff --git a/Generals/Code/GameEngine/Source/Common/PerfTimer.cpp b/Generals/Code/GameEngine/Source/Common/PerfTimer.cpp index f65abb69af..1505f84619 100644 --- a/Generals/Code/GameEngine/Source/Common/PerfTimer.cpp +++ b/Generals/Code/GameEngine/Source/Common/PerfTimer.cpp @@ -232,10 +232,7 @@ PerfGather::PerfGather(const char *identifier) : m_next(0), m_prev(0) { - //Added By Sadullah Nader - //Initializations inserted m_ignore = FALSE; - // DEBUG_ASSERTCRASH(strchr(m_identifier, ',') == NULL, ("PerfGather names must not contain commas")); addToList(); } @@ -481,8 +478,6 @@ PerfTimer::PerfTimer( const char *identifier, Bool crashWithInfo, Int startFrame m_callCount(0), m_runningTime(0), m_outputInfo(true), - //Added By Sadullah Nader - //Intializations inserted m_lastFrame(-1) { } diff --git a/Generals/Code/GameEngine/Source/Common/RTS/Player.cpp b/Generals/Code/GameEngine/Source/Common/RTS/Player.cpp index 217474b898..90b9fc6008 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/Player.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/Player.cpp @@ -321,8 +321,6 @@ Player::Player( Int playerIndex ) m_visionSpiedMask = PLAYERMASK_NONE; m_battlePlanBonuses = NULL; m_skillPointsModifier = 1.0f; - //Added By Sadullah - //Initializations inserted m_canBuildUnits = TRUE; m_canBuildBase = TRUE; m_cashBountyPercent = 0.0f; @@ -338,7 +336,6 @@ Player::Player( Int playerIndex ) { m_squads[i] = NULL; } - // for (i = 0; i < MAX_PLAYER_COUNT; ++i) { m_attackedBy[i] = false; diff --git a/Generals/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp b/Generals/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp index 63a6b33e6c..bc70cbb12b 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp @@ -234,14 +234,10 @@ UnicodeString ProductionPrerequisite::getRequiresList(const Player *player) cons Int i; Bool orRequirements[MAX_PREREQ]; - //Added for fix below in getRequiresList - //By Sadullah Nader - //Initializes the OR_WITH_PREV structures for (i = 0; i < MAX_PREREQ; i++) { orRequirements[i] = FALSE; } - // // account for the "or" unit cases, start for loop at 1 for (i = 1; i < cnt; i++) { diff --git a/Generals/Code/GameEngine/Source/Common/RTS/ScoreKeeper.cpp b/Generals/Code/GameEngine/Source/Common/RTS/ScoreKeeper.cpp index 8810dcfbd2..0056c1f7e0 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/ScoreKeeper.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/ScoreKeeper.cpp @@ -102,10 +102,7 @@ void ScoreKeeper::reset( Int playerIdx ) m_totalMoneyEarned = m_totalMoneySpent = 0; m_totalUnitsLost = m_totalUnitsBuilt = 0; m_totalBuildingsLost = m_totalBuildingsBuilt = 0; - //Added By Sadullah Nader - //Initializtion(s) inserted m_totalFactionBuildingsCaptured = m_totalTechBuildingsCaptured = 0; - // m_currentScore = 0; m_objectsBuilt.clear(); m_objectsCaptured.clear(); diff --git a/Generals/Code/GameEngine/Source/Common/RTS/Team.cpp b/Generals/Code/GameEngine/Source/Common/RTS/Team.cpp index 2d75320064..f81283fdae 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/Team.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/Team.cpp @@ -1316,13 +1316,8 @@ Team::Team(TeamPrototype *proto, TeamID id ) : m_curUnits(0), m_wasIdle(false) { - //Added By Sadullah Nader - //Initialization(s) inserted m_created = FALSE; - - // m_commonAttackTarget = INVALID_ID; - // allocate new relation map pools m_playerRelations = newInstance(PlayerRelationMap); m_teamRelations = newInstance(TeamRelationMap); diff --git a/Generals/Code/GameEngine/Source/Common/Recorder.cpp b/Generals/Code/GameEngine/Source/Common/Recorder.cpp index 75d8a31ec0..4e0c7aa5ce 100644 --- a/Generals/Code/GameEngine/Source/Common/Recorder.cpp +++ b/Generals/Code/GameEngine/Source/Common/Recorder.cpp @@ -368,14 +368,10 @@ RecorderClass::RecorderClass() m_file = NULL; m_fileName.clear(); m_currentFilePosition = 0; - //Added By Sadullah Nader - //Initializtion(s) inserted m_doingAnalysis = FALSE; m_archiveReplays = FALSE; m_nextFrame = 0; m_wasDesync = FALSE; - // - init(); // just for the heck of it. } diff --git a/Generals/Code/GameEngine/Source/Common/StatsCollector.cpp b/Generals/Code/GameEngine/Source/Common/StatsCollector.cpp index cc05f9c297..9f05592a70 100644 --- a/Generals/Code/GameEngine/Source/Common/StatsCollector.cpp +++ b/Generals/Code/GameEngine/Source/Common/StatsCollector.cpp @@ -76,13 +76,9 @@ static char statsDir[255] = "Stats\\"; //============================================================================= StatsCollector::StatsCollector( void ) { - //Added By Sadullah Nader - //Initialization(s) inserted m_isScrolling = FALSE; m_scrollBeginTime = 0; m_scrollTime = 0; - - // m_timeCount = 0; m_buildCommands = 0; m_moveCommands = 0; @@ -90,10 +86,8 @@ StatsCollector::StatsCollector( void ) m_scrollMapCommands = 0; m_AIUnits = 0; m_playerUnits = 0; - m_lastUpdate = 0; m_startFrame = TheGameLogic->getFrame(); - } //Destructor //============================================================================= diff --git a/Generals/Code/GameEngine/Source/Common/System/DataChunk.cpp b/Generals/Code/GameEngine/Source/Common/System/DataChunk.cpp index c1cd2400a6..63f980cb58 100644 --- a/Generals/Code/GameEngine/Source/Common/System/DataChunk.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/DataChunk.cpp @@ -237,11 +237,7 @@ m_pOut(pOut) AsciiString tmpFileName = TheGlobalData->getPath_UserData(); tmpFileName.concat(TEMP_FILENAME); m_tmp_file = ::fopen( tmpFileName.str(), "wb" ); - // Added Sadullah Nader - // Initializations missing and needed m_chunkStack = NULL; - - // End Add } DataChunkOutput::~DataChunkOutput() diff --git a/Generals/Code/GameEngine/Source/Common/System/Upgrade.cpp b/Generals/Code/GameEngine/Source/Common/System/Upgrade.cpp index 50064fc556..f3cbb377fe 100644 --- a/Generals/Code/GameEngine/Source/Common/System/Upgrade.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/Upgrade.cpp @@ -131,10 +131,7 @@ const FieldParse UpgradeTemplate::m_upgradeFieldParseTable[] = //------------------------------------------------------------------------------------------------- UpgradeTemplate::UpgradeTemplate( void ) { - //Added By Sadullah Nader - //Initialization(s) inserted m_cost = 0; - // m_type = UPGRADE_TYPE_PLAYER; m_nameKey = NAMEKEY_INVALID; m_buildTime = 0.0f; diff --git a/Generals/Code/GameEngine/Source/GameClient/Display.cpp b/Generals/Code/GameEngine/Source/GameClient/Display.cpp index 9d80db8ca1..e9acb876df 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Display.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Display.cpp @@ -64,11 +64,8 @@ Display::Display() m_elapsedCopywriteTime = 0; m_copyrightDisplayString = NULL; - // Added by Sadullah Nader - // Initializations missing and needed m_currentlyPlayingMovie.clear(); m_letterBoxFadeStartTime = 0; - // End Add } /** diff --git a/Generals/Code/GameEngine/Source/GameClient/Drawable.cpp b/Generals/Code/GameEngine/Source/GameClient/Drawable.cpp index cba6fb5adb..10e680001b 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Drawable.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Drawable.cpp @@ -316,11 +316,8 @@ Drawable::Drawable( const ThingTemplate *thingTemplate, DrawableStatusBits statu // assign status bits before anything else can be done m_status = statusBits; - // Added By Sadullah Nader - // Initialization missing and needed m_nextDrawable = NULL; m_prevDrawable = NULL; - // // register drawable with the GameClient ... do this first before we start doing anything // complex that uses any of the drawable data so that we have and ID!! It's ok to initialize @@ -330,17 +327,12 @@ Drawable::Drawable( const ThingTemplate *thingTemplate, DrawableStatusBits statu Int i; - // Added By Sadullah Nader - // Initialization missing and needed m_flashColor = 0; m_selected = '\0'; - // m_expirationDate = 0; // 0 == never expires m_lastConstructDisplayed = -1.0f; - - //Added By Sadullah Nader //Fix for the building percent m_constructDisplayString = TheDisplayStringManager->newDisplayString(); m_constructDisplayString->setFont(TheFontLibrary->getFont(TheInGameUI->getDrawableCaptionFontName(), diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp index c08c490fc9..ecabff9b8e 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp @@ -561,10 +561,6 @@ CommandButton::CommandButton( void ) //m_pushedImage = NULL; m_flashCount = 0; - - // Added by Sadullah Nader - // The purpose is to initialize these variable to values that are zero or empty - m_conflictingLabel.clear(); m_cursorName.clear(); m_descriptionLabel.clear(); @@ -573,9 +569,6 @@ CommandButton::CommandButton( void ) m_options = 0; m_purchasedLabel.clear(); m_textLabel.clear(); - - // End Add - m_window = NULL; m_commandButtonBorder = COMMAND_BUTTON_BORDER_NONE; //m_prev = NULL; @@ -860,14 +853,10 @@ ControlBar::ControlBar( void ) m_observedPlayer = NULL; m_buildToolTipLayout = NULL; m_showBuildToolTipLayout = FALSE; - - // Added By Sadullah Nader - // initializing vars to zero m_animateDownWin1Pos.x = m_animateDownWin1Pos.y = 0; m_animateDownWin1Size.x = m_animateDownWin1Size.y = 0; m_animateDownWin2Pos.x = m_animateDownWin2Pos.y = 0; m_animateDownWin2Size.x = m_animateDownWin2Size.y = 0; - m_animateDownWindow = NULL; m_animTime = 0; @@ -879,11 +868,10 @@ ControlBar::ControlBar( void ) m_currContext = CB_CONTEXT_NONE; m_defaultControlBarPosition.x = m_defaultControlBarPosition.y = 0; m_genStarFlash = FALSE; - m_genStarOff = NULL; + m_genStarOff = NULL; m_genStarOn = NULL; m_UIDirty = FALSE; - // -// m_controlBarResizer = NULL; + // m_controlBarResizer = NULL; m_buildUpClockColor = GameMakeColor(0,0,0,100); m_commandBarBorderColor = GameMakeColor(0,0,0,100); for( i = 0; i < NUM_CONTEXT_PARENTS; i++ ) diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp index 6554aa8746..f5ec055e12 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp @@ -188,13 +188,8 @@ ControlBarSchemeImage::~ControlBarSchemeImage( void ) ControlBarSchemeAnimation::ControlBarSchemeAnimation( void ) { - // Added by Sadullah Nader - // Initializations missing and needed - m_animDuration = 0; m_finalPos.x = m_finalPos.y = 0; - - // End Add m_name.clear(); m_animType = 0; m_animImage = NULL; @@ -302,12 +297,8 @@ ControlBarScheme::ControlBarScheme(void) m_optionsButtonPushed = NULL; m_optionsButtonDisabled = NULL; - // Added By Sadullah Nader - // Initializations needed - m_commandBarBorderColor = 0; - // m_idleWorkerButtonEnable = NULL; m_idleWorkerButtonHightlited = NULL; m_idleWorkerButtonPushed = NULL; @@ -351,7 +342,6 @@ ControlBarScheme::ControlBarScheme(void) m_minMaxButtonHightlited = NULL; m_minMaxButtonPushed = NULL; - m_minMaxUL.x = 0; m_minMaxLR.x = 0; 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 b884e58bdf..05d8a1d354 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp @@ -649,11 +649,8 @@ void InitLanGameGadgets( void ) Int localSlotNum = TheLAN->GetMyGame()->getLocalSlotNum(); DEBUG_ASSERTCRASH(localSlotNum >= 0, ("Bad slot number!")); - //Added By Sadullah Nader //Tooltip function is being set for techBuildings, and supplyDocks - windowMap->winSetTooltipFunc(MapSelectorTooltip); - //End Add for (Int i = 0; i < MAX_SLOTS; i++) { @@ -704,7 +701,6 @@ void InitLanGameGadgets( void ) buttonAcceptID[i] = TheNameKeyGenerator->nameToKey( tmpString ); buttonAccept[i] = TheWindowManager->winGetWindowFromId( parentLanGameOptions, buttonAcceptID[i] ); DEBUG_ASSERTCRASH(buttonAccept[i], ("Could not find the buttonAccept[%d]",i )); - //Added by Saad for the tooltips on the MultiPlayer icons buttonAccept[i]->winSetTooltipFunc(gameAcceptTooltip); // // tmpString.format("LanGameOptionsMenu.wnd:ButtonStartPosition%d", i); 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 11d3090148..eb20eee788 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp @@ -71,12 +71,9 @@ #include "GameNetwork/GameSpy/MainMenuUtils.h" #include "GameClient/CDCheck.h" -//Added By Saad -//for accessing the InGameUI #include "GameClient/InGameUI.h" - // PRIVATE DATA /////////////////////////////////////////////////////////////////////////////////// enum @@ -200,7 +197,6 @@ static Bool justEntered = FALSE; static Bool dontAllowTransitions = FALSE; -//Added by Saad const Int /*TIME_OUT = 15,*/ CORNER = 10; void AcceptResolution(); void DeclineResolution(); @@ -208,7 +204,6 @@ GameWindow *resAcceptMenu = NULL; extern DisplaySettings oldDispSettings, newDispSettings; extern Bool dispChanged; //static time_t timeStarted = 0, currentTime = 0; -// void diffReverseSide( void ); void HandleCanceledDownload( Bool resetDropDown ) @@ -681,8 +676,6 @@ void MainMenuShutdown( WindowLayout *layout, void *userData ) extern Bool DontShowMainMenu; //////////////////////////////////////////////////////////////////////////// -//Added By Sadullah Nader -//Added as a fix to the resolution change //Allows the user to confirm the change, goes back to the previous mode //if the time to change expires. //////////////////////////////////////////////////////////////////////////// @@ -801,8 +794,6 @@ void MainMenuUpdate( WindowLayout *layout, void *userData ) DownloadMenuUpdate(layout, userData); } - // Added by Saad to the confirmation or decline of the resoluotion change - // dialog box. /* This is also commented for the same reason as the top if (dispChanged) { @@ -1435,9 +1426,6 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, { // 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(RTS_DEBUG) - - //Added By Sadullah Nader - //Changed the preprocessing code to normal code if (TheGlobalData->m_windowed) { quitCallback(); @@ -1447,7 +1435,6 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, { QuitMessageBoxYesNo(TheGameText->fetch("GUI:QuitPopupTitle"), TheGameText->fetch("GUI:QuitPopupMessage"),quitCallback,NULL); } - // //#endif } 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 8cffa3c435..32bb9002f3 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp @@ -72,8 +72,6 @@ #include "GameLogic/GameLogic.h" #include "GameLogic/ScriptEngine.h" #include "WWDownload/Registry.h" -//added by saad -//used to access a messagebox that does "ok" and "cancel" #include "GameClient/MessageBox.h" #include "ww3d.h" @@ -201,13 +199,10 @@ static GameWindow * radioLow = NULL; */ -//Added By Saad for the resolution confirmation dialog box DisplaySettings oldDispSettings, newDispSettings; Bool dispChanged = FALSE; extern Int timer; extern void DoResolutionDialog(); -// - static Bool ignoreSelected = FALSE; WindowLayout *OptionsLayout = NULL; diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupSaveLoad.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupSaveLoad.cpp index 9668f2f69d..6d7c3e661e 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupSaveLoad.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupSaveLoad.cpp @@ -753,9 +753,7 @@ WindowMsgHandledType SaveLoadMenuSystem( GameWindow *window, UnsignedInt msg, buttonFrame->winEnable( TRUE ); updateMenuActions(); - //Added By Sadullah Nader - //Fix for bug - // close save menuu + // close save menu closeSaveMenu( window ); // @@ -815,7 +813,7 @@ WindowMsgHandledType SaveLoadMenuSystem( GameWindow *window, UnsignedInt msg, buttonFrame->winEnable( TRUE ); updateMenuActions(); - // close save menuu + // close save menu closeSaveMenu( window ); // get save filename @@ -873,15 +871,9 @@ WindowMsgHandledType SaveLoadMenuSystem( GameWindow *window, UnsignedInt msg, buttonFrame->winEnable( TRUE ); updateMenuActions(); - - - // do the load game if( controlID == buttonLoadConfirm ) { - //Moved by Sadullah Nader - //moved to fix the - // close save/load layout menu closeSaveMenu( window ); doLoadGame(); } 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 8ea39e4230..3d75636428 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/QuitMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/QuitMenu.cpp @@ -279,14 +279,9 @@ void HideQuitMenu( void ) //------------------------------------------------------------------------------------------------- void ToggleQuitMenu() { - - //Added By Sadullah Nader - //Added a check to see if we're not in game yet if (TheGameLogic->isIntroMoviePlaying() || TheGameLogic->isLoadingGame() ||TheScriptEngine->isGameEnding()) return; - //End Add - // BGC- If we are currently in the disconnect screen, don't let the quit menu come up. if (TheDisconnectMenu != NULL) { if (TheDisconnectMenu->isScreenVisible() == TRUE) { @@ -323,12 +318,9 @@ void ToggleQuitMenu() isVisible = FALSE; - //Added By Sadullah Nader - //Bug: When Toggling the quit menu off, the quit confirmation should also go away if (quitConfirmationWindow) TheWindowManager->winDestroy(quitConfirmationWindow); quitConfirmationWindow = NULL; - // if ( !TheGameLogic->isInMultiplayerGame() ) TheGameLogic->setGamePaused(FALSE); @@ -352,8 +344,6 @@ void ToggleQuitMenu() } else { - //Added By Sadullah Nader - //Added to compensate for the quit confirmation window pop-up TheMouse->setCursor( Mouse::ARROW ); 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 18d33cfaba..8ff4cd41b5 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp @@ -95,7 +95,6 @@ #include "GameNetwork/GameSpyOverlay.h" #include "GameNetwork/GameSpy/BuddyThread.h" #include "GameNetwork/GameSpy/PersistentStorageThread.h" -//Added By Saad #include "GameClient/InGameUI.h" @@ -767,12 +766,8 @@ void finishSinglePlayerInit( void ) } - //Added By Sadullah Nader - //Fix for the black screen text that appears after loading sequence - TheInGameUI->freeMessageResources(); - // if (s_blankLayout) { s_blankLayout->destroyWindows(); 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 2cfd273c55..4386c5fd91 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp @@ -542,8 +542,6 @@ static void startPressed(void) ///////////////////////////////////////////////////// // MapSelectorTooltip - shows tooltips for the tech buildings // and supply depots -// Added By : Sadullah Nader -///////////////////////////////////////////////////// void MapSelectorTooltip(GameWindow *window, WinInstanceData *instData, UnsignedInt mouse) @@ -873,8 +871,6 @@ void updateMapStartSpots( GameInfo *myGame, GameWindow *buttonMapStartPositions[ AsciiString displayNumber; displayNumber.format("NUMBER:%d",i + 1); GadgetButtonSetText(buttonMapStartPositions[gs->getStartPos()], TheGameText->fetch(displayNumber)); - //Added By Sadullah Nader - //Fix for no tooltips at start positions //added start position tooltip //Fixed again to show the right number , ie "i + 1" UnicodeString temp; 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 e0d0f03cc4..ddafdd13d4 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp @@ -1024,10 +1024,7 @@ void InitWOLGameGadgets( void ) windowMap = TheWindowManager->winGetWindowFromId( parentWOLGameSetup,windowMapID ); DEBUG_ASSERTCRASH(windowMap, ("Could not find the parentWOLGameSetup.wnd:MapWindow" )); - //Added By Sadullah Nader - //Tooltip Function set windowMap->winSetTooltipFunc(MapSelectorTooltip); - // GameWindow *staticTextTitle = TheWindowManager->winGetWindowFromId( parentWOLGameSetup, staticTextTitleID ); if (staticTextTitle) diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindow.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindow.cpp index e371f8ec70..3710e5d5be 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindow.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindow.cpp @@ -1544,8 +1544,6 @@ WindowMsgHandledType GameWinBlockInput( GameWindow *window, UnsignedInt msg, if (msg == GWM_CHAR || msg == GWM_MOUSE_POS) return MSG_IGNORED; - //Added By Sadullah Nader - //Fix for drag selecting in the control bar if (msg == GWM_LEFT_UP )//|| msg == GWM_LEFT_DRAG) { //stop drag selecting diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp index c974cbb59c..2f07686158 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp @@ -107,8 +107,6 @@ m_font(NULL), m_point(0), m_bold(FALSE) { - //Added By Sadullah Nader - //Initializations missing and needed m_fontName.clear(); m_name.clear(); } diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp index 0857283fed..96783bb42f 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp @@ -506,8 +506,6 @@ IMEManager::IMEManager() m_result(0), m_indexBase(1), - //Added By Sadullah Nader - //Initializations missing and needed m_compositionCharsDisplayed(0), m_candidateDownArrow(NULL), m_candidateTextArea(NULL), @@ -517,7 +515,6 @@ IMEManager::IMEManager() m_pageStart(0), m_selectedIndex(0), m_unicodeIME(FALSE) - // { } diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp index 755395afce..937b86f899 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp @@ -154,13 +154,10 @@ void LoadScreen::update( Int percent ) //----------------------------------------------------------------------------- SinglePlayerLoadScreen::SinglePlayerLoadScreen( void ) { - //Added By Sadullah Nader - //Initialization(s) inserted m_currentObjectiveLine = 0; m_currentObjectiveLineCharacter = 0; m_finishedObjectiveText = NULL; m_currentObjectiveWidthOffset = 0; - // m_progressBar = NULL; m_percent = NULL; m_videoStream = NULL; @@ -669,17 +666,11 @@ void ShellGameLoadScreen::update( Int percent ) //----------------------------------------------------------------------------- MultiPlayerLoadScreen::MultiPlayerLoadScreen( void ) { - //Added By Sadullah Nader - //Initializations missing and needed m_mapPreview = NULL; - // for(Int i = 0; i < MAX_SLOTS; ++i) { - //Added By Sadullah Nader - //Initializations missing and needed m_buttonMapStartPosition[i] = NULL; - // m_progressBars[i] = NULL; m_playerNames[i] = NULL; m_playerSide[i]= NULL; @@ -892,19 +883,13 @@ void MultiPlayerLoadScreen::processProgress(Int playerId, Int percentage) GameSpyLoadScreen::GameSpyLoadScreen( void ) { - // Added By Sadullah Nader - // Initializations missing and needed m_mapPreview = NULL; - // for(Int i = 0; i < MAX_SLOTS; ++i) { - // Added By Sadullah Nader - // Initializations missing and needed m_buttonMapStartPosition[i] = NULL; m_playerRank[i] = NULL; - // m_playerOfficerMedal[i] = NULL; m_progressBars[i] = NULL; @@ -1219,10 +1204,7 @@ void GameSpyLoadScreen::processProgress(Int playerId, Int percentage) //----------------------------------------------------------------------------- MapTransferLoadScreen::MapTransferLoadScreen( void ) { - //Added By Sadullah Nader - //Initializations missing and needed m_oldTimeout = 0; - // for(Int i = 0; i < MAX_SLOTS; ++i) { m_progressBars[i] = NULL; diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp index d5fe8efa31..9644062444 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp @@ -83,11 +83,8 @@ void Shell::construct( void ) m_schemeManager = NEW ShellMenuSchemeManager; m_saveLoadMenuLayout = NULL; m_popupReplayLayout = NULL; - //Added By Sadullah Nader - //Initializations m_optionsLayout = NULL; m_screenCount = 0; - // } //------------------------------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Source/GameClient/GameClient.cpp b/Generals/Code/GameEngine/Source/GameClient/GameClient.cpp index aa6b7c0bc9..8f3a55c29c 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GameClient.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GameClient.cpp @@ -98,10 +98,7 @@ GameClient::GameClient() m_numTranslators = 0; m_commandTranslator = NULL; - // Added By Sadullah Nader - // Initializations missing and needed m_drawableTOC.clear(); - // m_textBearingDrawableList.clear(); m_frame = 0; diff --git a/Generals/Code/GameEngine/Source/GameClient/GameText.cpp b/Generals/Code/GameEngine/Source/GameClient/GameText.cpp index a2437adf52..8bbc840f2b 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GameText.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GameText.cpp @@ -258,18 +258,14 @@ GameTextManager::GameTextManager() #endif m_mapStringInfo(NULL), m_mapStringLUT(NULL), - m_failed(L"***FATAL*** String Manager failed to initilaize properly") + m_failed(L"***FATAL*** String Manager failed to initialize properly") { - // Added By Sadullah Nader - // Initializations missing and needed - for(Int i=0; i < MAX_UITEXT_LENGTH; i++) { m_buffer[i] = 0; m_buffer2[i] = 0; m_buffer3[i] = 0; } - // } //============================================================================ diff --git a/Generals/Code/GameEngine/Source/GameClient/GlobalLanguage.cpp b/Generals/Code/GameEngine/Source/GameClient/GlobalLanguage.cpp index d41cae4064..887381c444 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GlobalLanguage.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GlobalLanguage.cpp @@ -122,15 +122,12 @@ void INI::parseLanguageDefinition( INI *ini ) GlobalLanguage::GlobalLanguage() { m_unicodeFontName.clear(); - //Added By Sadullah Nader - //Initializations missing and needed m_unicodeFontFileName.clear(); m_unicodeFontName.clear(); m_militaryCaptionSpeed = 0; m_useHardWrap = FALSE; m_resolutionFontSizeAdjustment = 0.7f; m_resolutionFontSizeMethod = ResolutionFontSizeMethod_Default; - //End Add m_userResolutionFontSizeAdjustment = -1.0f; } diff --git a/Generals/Code/GameEngine/Source/GameClient/InGameUI.cpp b/Generals/Code/GameEngine/Source/GameClient/InGameUI.cpp index d4bf6b296a..773aed31c2 100644 --- a/Generals/Code/GameEngine/Source/GameClient/InGameUI.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/InGameUI.cpp @@ -946,8 +946,6 @@ InGameUI::InGameUI() m_mouseModeCursor = Mouse::ARROW; m_mousedOverDrawableID = INVALID_DRAWABLE_ID; - //Added By Sadullah Nader - //Initializations missing and needed m_currentlyPlayingMovie.clear(); m_militarySubtitle = NULL; m_popupMessageData = NULL; @@ -5300,14 +5298,11 @@ void InGameUI::clearPopupMessageData( void ) //------------------------------------------------------------------------------------------------- FloatingTextData::FloatingTextData(void) { - // Added By Sadullah Nader - // Initializations missing and needed m_color = 0; m_frameCount = 0; m_frameTimeOut = 0; m_pos3D.zero(); m_text.clear(); - // m_dString = TheDisplayStringManager->newDisplayString(); } diff --git a/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp b/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp index 2ae572300f..99180dbce7 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp @@ -423,15 +423,12 @@ Bool Mouse::isClick(const ICoord2D *anchor, const ICoord2D *dest, UnsignedInt pr //------------------------------------------------------------------------------------------------- CursorInfo::CursorInfo( void ) { - // Added Sadullah Nader - // Initializations missing and needed cursorName.clear(); cursorText.clear(); cursorTextColor.red = cursorTextColor.green = cursorTextColor.blue = 0; cursorTextDropColor.red = cursorTextDropColor.blue = cursorTextDropColor.green = 0; - // textureName.clear(); imageName.clear(); W3DModelName.clear(); @@ -458,13 +455,9 @@ Mouse::Mouse( void ) m_numAxes = 0; m_forceFeedback = FALSE; - //Added By Sadullah Nader - //Initializations missing and needed m_dragTolerance = 0; m_dragTolerance3D = 0; m_dragToleranceMS = 0; - // - //m_tooltipString.clear(); // redundant m_displayTooltip = FALSE; m_tooltipDisplayString = NULL; diff --git a/Generals/Code/GameEngine/Source/GameClient/LanguageFilter.cpp b/Generals/Code/GameEngine/Source/GameClient/LanguageFilter.cpp index 3b6d485e6b..0aa3abf688 100644 --- a/Generals/Code/GameEngine/Source/GameClient/LanguageFilter.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/LanguageFilter.cpp @@ -35,9 +35,6 @@ LanguageFilter *TheLanguageFilter = NULL; LanguageFilter::LanguageFilter() { - //Modified by Saad - //Unnecessary - //m_wordList.clear(); } LanguageFilter::~LanguageFilter() { diff --git a/Generals/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp b/Generals/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp index 707574dc17..355c037b5a 100644 --- a/Generals/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp @@ -113,10 +113,7 @@ GameMessageDisposition HotKeyTranslator::translateGameMessage(const GameMessage HotKey::HotKey() { m_win = NULL; - //Added By Sadullah Nader - //Initializations missing and needed m_key.clear(); - // } //----------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp b/Generals/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp index c77e045a11..1f0d4e7cc7 100644 --- a/Generals/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp @@ -142,12 +142,9 @@ LookAtTranslator::LookAtTranslator() : m_lastMouseMoveFrame(0), m_scrollType(SCROLL_NONE) { - //Added By Sadullah Nader - //Initializations missing and needed m_anchor.x = m_anchor.y = 0; m_currentPos.x = m_currentPos.y = 0; m_originalAnchor.x = m_originalAnchor.y = 0; - // OptionPreferences prefs; m_screenEdgeScrollMode = prefs.getScreenEdgeScrollMode(); diff --git a/Generals/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp b/Generals/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp index a8acd90d38..daf5d4bd42 100644 --- a/Generals/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp @@ -265,11 +265,8 @@ SelectionTranslator::SelectionTranslator() m_deselectFeedbackAnchor.x = 0; m_deselectFeedbackAnchor.y = 0; m_lastClick = 0; - //Added By Sadullah Nader - //Initializtion(s) inserted m_deselectDownCameraPosition.zero(); m_displayedMaxWarning = FALSE; - // m_selectCountMap.clear(); TheSelectionTranslator = this; @@ -1242,8 +1239,6 @@ GameMessageDisposition SelectionTranslator::translateGameMessage(const GameMessa } -//Added By Sadullah Nader - //setDragSelecting(Bool dragSelect) //Added to fix the drag selection problem in control bar //////////////////////////////////////////////////////////////////////// diff --git a/Generals/Code/GameEngine/Source/GameClient/RadiusDecal.cpp b/Generals/Code/GameEngine/Source/GameClient/RadiusDecal.cpp index 350e981e19..28b20813bb 100644 --- a/Generals/Code/GameEngine/Source/GameClient/RadiusDecal.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/RadiusDecal.cpp @@ -45,7 +45,7 @@ RadiusDecalTemplate::RadiusDecalTemplate() : m_opacityThrobTime(LOGICFRAMES_PER_SECOND), m_color(0), m_onlyVisibleToOwningPlayer(true), - m_name(AsciiString::TheEmptyString) // Added By Sadullah Nader for Init purposes + m_name(AsciiString::TheEmptyString) { } diff --git a/Generals/Code/GameEngine/Source/GameClient/SelectionInfo.cpp b/Generals/Code/GameEngine/Source/GameClient/SelectionInfo.cpp index 203c37c22c..4cc29191ca 100644 --- a/Generals/Code/GameEngine/Source/GameClient/SelectionInfo.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/SelectionInfo.cpp @@ -63,10 +63,7 @@ SelectionInfo::SelectionInfo() : //------------------------------------------------------------------------------------------------- PickDrawableStruct::PickDrawableStruct() : drawableListToFill(NULL) { - //Added By Sadullah Nader - //Initializations inserted drawableListToFill = FALSE; - // forceAttackMode = TheInGameUI->isInForceAttackMode(); UnsignedInt pickType = getPickTypesForContext(forceAttackMode); translatePickTypesToKindof(pickType, kindofsToMatch); diff --git a/Generals/Code/GameEngine/Source/GameClient/System/Anim2D.cpp b/Generals/Code/GameEngine/Source/GameClient/System/Anim2D.cpp index 66d3b6c1bb..dc3cf08312 100644 --- a/Generals/Code/GameEngine/Source/GameClient/System/Anim2D.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/System/Anim2D.cpp @@ -295,17 +295,10 @@ const Image* Anim2DTemplate::getFrame( UnsignedShort frameNumber ) const // ------------------------------------------------------------------------------------------------ Anim2D::Anim2D( Anim2DTemplate *animTemplate, Anim2DCollection *collectionSystem ) { - // sanity DEBUG_ASSERTCRASH( animTemplate != NULL, ("Anim2D::Anim2D - NULL template") ); - - //Added By Sadullah Nader - //Initialization - m_currentFrame = 0; - // - // set the template m_template = animTemplate; @@ -323,8 +316,6 @@ Anim2D::Anim2D( Anim2DTemplate *animTemplate, Anim2DCollection *collectionSystem m_maxFrame = m_template->getNumFrames() - 1; m_framesBetweenUpdates = m_template->getNumFramesBetweenUpdates(); - //added by Sadullah Nader - // initializing pointers to NULL, and clearing Frame counters before // we register ourselves to the System m_collectionSystemNext = NULL; m_collectionSystemPrev = NULL; @@ -335,8 +326,6 @@ Anim2D::Anim2D( Anim2DTemplate *animTemplate, Anim2DCollection *collectionSystem m_collectionSystem = collectionSystem; if( m_collectionSystem ) m_collectionSystem->registerAnimation( this ); - - } // ------------------------------------------------------------------------------------------------ diff --git a/Generals/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp b/Generals/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp index 1ec4a0ca72..12104ec64b 100644 --- a/Generals/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp @@ -68,8 +68,6 @@ ParticleSystemManager *TheParticleSystemManager = NULL; // ------------------------------------------------------------------------------------------------ ParticleInfo::ParticleInfo( void ) { - //Added By Sadullah Nader - //Initializations inserted m_angleX = m_angleY = m_angleZ = 0.0f; m_angularDamping = 0.0f; m_angularRateX = m_angularRateY = m_angularRateZ = 0.0f; @@ -87,7 +85,6 @@ ParticleInfo::ParticleInfo( void ) m_lifetime = 0; m_particleUpTowardsEmitter = FALSE; - // } // ------------------------------------------------------------------------------------------------ @@ -288,10 +285,7 @@ Particle::Particle( ParticleSystem *system, const ParticleInfo *info ) m_angleY = info->m_angleY; m_angleZ = info->m_angleZ; - //Added By Sadullah Nader - //Initializations inserted m_lastPos.zero(); - // m_windRandomness = info->m_windRandomness; m_particleUpTowardsEmitter = info->m_particleUpTowardsEmitter; m_emitterPos = info->m_emitterPos; @@ -826,8 +820,6 @@ ParticleSystemInfo::ParticleSystemInfo() m_isEmitAboveGroundOnly = false; m_isParticleUpTowardsEmitter = false; - //Added By Sadullah Nader - //Initializations inserted m_driftVelocity.zero(); m_gravity = 0.0f; m_isEmissionVolumeHollow = FALSE; @@ -835,7 +827,6 @@ ParticleSystemInfo::ParticleSystemInfo() m_slavePosOffset.zero(); m_systemLifetime = 0; - // // some default values for the wind motion values m_windMotion = WIND_MOTION_NOT_USED; m_windAngle = 0.0f; @@ -1135,12 +1126,9 @@ ParticleSystem::ParticleSystem( const ParticleSystemTemplate *sysTemplate, m_template = sysTemplate; m_systemID = id; - //Added By Sadullah Nader - //Initializations inserted m_lastPos.zero(); m_pos.zero(); m_velCoeff.zero(); - // m_attachedToDrawableID = INVALID_DRAWABLE_ID; m_attachedToObjectID = INVALID_ID; @@ -2881,10 +2869,7 @@ void ParticleSystemTemplate::parseRandomRGBColor( INI* ini, void *instance, ParticleSystemTemplate::ParticleSystemTemplate( const AsciiString &name ) : m_name(name) { - //Added By Sadullah Nader - //Initializations inserted m_slaveTemplate = NULL; - // } // ------------------------------------------------------------------------------------------------ @@ -2925,13 +2910,10 @@ ParticleSystemManager::ParticleSystemManager( void ) m_onScreenParticleCount = 0; m_localPlayerIndex = 0; - //Added By Sadullah Nader - //Initializations inserted m_lastLogicFrameUpdate = 0; m_particleCount = 0; m_fieldParticleCount = 0; m_particleSystemCount = 0; - // for( Int i = 0; i < NUM_PARTICLE_PRIORITIES; ++i ) { diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/AI.cpp index 5cfffbb6a3..72ba53e678 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/AI.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/AI.cpp @@ -937,15 +937,12 @@ m_infantryPathfindDiameter(6), m_vehiclePathfindDiameter(6), m_supplyCenterSafeRadius(250), m_rebuildDelaySeconds(10), -//Added By Sadullah Nader -//Initialization(s) inserted m_distanceRequiresGroup(0.0f), m_sideBuildLists(NULL), m_structuresPoorMod(0.0f), m_teamWealthyMod(0.0f), m_aiDozerBoredRadiusModifier(2.0), m_aiCrushesInfantry(true) -// { } diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp index 7b344d538c..2b693ac950 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp @@ -2810,15 +2810,12 @@ zoneStorageType PathfindZoneManager::getEffectiveZone( LocomotorSurfaceTypeMask } //-------------------- PathfindLayer ---------------------------------------- PathfindLayer::PathfindLayer() : m_blockOfMapCells(NULL), m_layerCells(NULL), m_bridge(NULL), -// Added By Sadullah Nader -// Initializations inserted m_destroyed(FALSE), m_height(0), m_width(0), m_xOrigin(0), m_yOrigin(0), m_zone(0) -// { m_startCell.x = -1; m_startCell.y = -1; @@ -4984,7 +4981,6 @@ Bool Pathfinder::adjustToPossibleDestination(Object *obj, const LocomotorSet& lo return false; } - // Int zone1, zone2; Bool isCrusher = obj ? obj->getCrusherLevel() > 0 : false; zone1 = m_zoneManager.getEffectiveZone(locomotorSet.getValidSurfaces(), isCrusher, parentCell->getZone()); diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/TurretAI.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/TurretAI.cpp index 8b55c09218..c9270e8904 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/TurretAI.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/TurretAI.cpp @@ -280,15 +280,9 @@ TurretAI::TurretAI(Object* owner, const TurretAIData* data, WhichTurretType tur) m_enabled(!data->m_initiallyDisabled), m_firesWhileTurning(data->m_firesWhileTurning), m_isForceAttacking(false), - //Added By Sadullah Nader - //Initialization(s) inserted m_victimInitialTeam(NULL) - // { - //Added By Sadullah Nader - //Initialization(s) inserted m_continuousFireExpirationFrame = -1; - // if (!m_data) { DEBUG_CRASH(("TurretAI MUST have ModuleData")); diff --git a/Generals/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cpp b/Generals/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cpp index 50acb849db..4026e72869 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cpp @@ -48,11 +48,8 @@ m_numPoints(0), m_sizePoints(0), m_exportWithScripts(false), m_isWaterArea(false), -//Added By Sadullah Nader -//Initializations inserted m_isRiver(FALSE), m_riverStart(0) -// { if (initialAllocation < 2) initialAllocation = 2; m_points = NEW ICoord3D[initialAllocation]; // pool[]ify diff --git a/Generals/Code/GameEngine/Source/GameLogic/Map/SidesList.cpp b/Generals/Code/GameEngine/Source/GameLogic/Map/SidesList.cpp index 3c8e496b29..c660fdf121 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Map/SidesList.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Map/SidesList.cpp @@ -917,8 +917,6 @@ m_automaticallyBuild(true), m_priorityBuild(false), m_buildingName(AsciiString::TheEmptyString) { - // Added by Sadullah Nader - // these initialized values are necessary!!! m_location.zero(); m_rallyPointOffset.x = 0.0f; m_rallyPointOffset.y = 0.0f; diff --git a/Generals/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp b/Generals/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp index 88baf0b0ae..685cd22558 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp @@ -959,11 +959,8 @@ TerrainLogic::TerrainLogic() { Int i; - //Added By Sadullah Nader - //Initialization(s) inserted m_activeBoundary = 0; m_waterGridEnabled = FALSE; - // for( i = 0; i < MAX_DYNAMIC_WATER; ++i ) { diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cpp index 0c2ce6954d..4105cf9600 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cpp @@ -51,14 +51,7 @@ ParkingPlaceBehavior::ParkingPlaceBehavior( Thing *thing, const ModuleData* moduleData ) : UpdateModule( thing, moduleData ) { m_gotInfo = false; - - //Added By Sadullah Nader - //Initializations - m_heliRallyPoint.zero(); - - // - m_heliRallyPointExists = FALSE; m_nextHealFrame = FOREVER; setWakeFrame(getObject(), UPDATE_SLEEP_NONE); diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/PropagandaTowerBehavior.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/PropagandaTowerBehavior.cpp index 8b940b7d2a..3d0ee6d9b2 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/PropagandaTowerBehavior.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/PropagandaTowerBehavior.cpp @@ -119,10 +119,7 @@ PropagandaTowerBehaviorModuleData::PropagandaTowerBehaviorModuleData( void ) PropagandaTowerBehavior::PropagandaTowerBehavior( Thing *thing, const ModuleData *modData ) : UpdateModule( thing, modData ) { - //Added By Sadullah Nader - //Initializations inserted m_lastScanFrame = 0; - // m_insideList = NULL; setWakeFrame( getObject(), UPDATE_SLEEP_NONE ); diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp index e7409a19b7..350e7f7866 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp @@ -67,10 +67,7 @@ SpawnBehavior::SpawnBehavior( Thing *thing, const ModuleData* moduleData ) //looping back to the beginning m_framesToWait = 0; - //Added By Sadullah Nader - //Initialization(s) inserted m_firstBatchCount = 0; - // if( md->m_isOneShotData ) m_oneShotCountdown = md->m_spawnNumberData; else 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 cac8cd3c5a..8d8e7d5081 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cpp @@ -52,13 +52,7 @@ CrateCollideModuleData::CrateCollideModuleData() m_isHumanOnlyPickup = FALSE; m_executeFX = NULL; m_pickupScience = SCIENCE_INVALID; - - // Added By Sadullah Nader - // Initializations missing and needed - m_executionAnimationTemplate = AsciiString::TheEmptyString; - - // End Add } //------------------------------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp index 4e32ce205e..48a73f62f8 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp @@ -127,11 +127,8 @@ OpenContain::OpenContain( Thing *thing, const ModuleData* moduleData ) : UpdateM m_stealthUnitsContained = 0; m_doorCloseCountdown = 0; - //Added By Sadullah Nader - //Initializations inserted m_rallyPoint.zero(); m_rallyPointExists = FALSE; - // m_conditionState.clear(); m_firePointStart = -1; m_firePointNext = 0; diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/ParachuteContain.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/ParachuteContain.cpp index fa2e511341..2cb5300b4a 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/ParachuteContain.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/ParachuteContain.cpp @@ -99,8 +99,6 @@ ParachuteContain::ParachuteContain( Thing *thing, const ModuleData *moduleData ) m_isLandingOverrideSet = FALSE; m_startZ = NO_START_Z; - //Added By Sadullah Nader - //Initializations m_landingOverride.zero(); m_paraAttachBone.zero(); m_paraAttachOffset.zero(); @@ -111,7 +109,6 @@ ParachuteContain::ParachuteContain( Thing *thing, const ModuleData *moduleData ) m_riderSwayBone.zero(); m_riderSwayOffset.zero(); - // const ParachuteContainModuleData* d = getParachuteContainModuleData(); if (d) { diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp index ca1facc47b..f6a1b05032 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp @@ -43,7 +43,7 @@ ExperienceTracker::ExperienceTracker(Object *parent) : m_currentLevel(LEVEL_REGULAR), m_experienceSink(INVALID_ID), m_experienceScalar( 1.0f ), - m_currentExperience(0) // Added By Sadullah Nader + m_currentExperience(0) { } diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/GhostObject.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/GhostObject.cpp index 2b48f3396f..2c7af51476 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/GhostObject.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/GhostObject.cpp @@ -39,8 +39,6 @@ GhostObjectManager *TheGhostObjectManager = NULL; //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- GhostObject::GhostObject(void): -//Added By Sadullah Nader -//Initializations missing and needed m_parentAngle(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. diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Locomotor.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Locomotor.cpp index 6f010be3b9..06d42d780c 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Locomotor.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Locomotor.cpp @@ -660,13 +660,8 @@ Locomotor::Locomotor(const LocomotorTemplate* tmpl) //------------------------------------------------------------------------------------------------- Locomotor::Locomotor(const Locomotor& that) { - //Added By Sadullah Nader - //Initializations m_angleOffset = 0.0f; m_maintainPos.zero(); - - // - m_template = that.m_template; m_brakingFactor = that.m_brakingFactor; m_maxLift = that.m_maxLift; diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp index fbda3ce5b8..d0f4b52301 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp @@ -213,11 +213,8 @@ Object::Object( const ThingTemplate *tt, const ObjectStatusMaskType &objectStatu Int i, modIdx; AsciiString modName; - //Added By Sadullah Nader - //Initializations inserted m_formationOffset.x = m_formationOffset.y = 0.0f; m_iPos.zero(); - // for( i = 0; i < DISABLED_COUNT; i++ ) { m_disabledTillFrame[ i ] = NEVER; diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp index f935cc2685..93e792bb46 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp @@ -247,15 +247,9 @@ class DeliverPayloadNugget : public ObjectCreationNugget m_convergenceFactor( 0.0f ) { //Note: m_data is constructed with default values. - - // Added by Sadullah Nader - // Initialization missing and needed - m_payload.clear(); m_putInContainerName.clear(); m_transportName.clear(); - - // End Add } virtual Object* create(const Object *primaryObj, const Coord3D *primary, const Coord3D *secondary, UnsignedInt lifetimeFrames = 0 ) const @@ -754,9 +748,9 @@ class GenericObjectCreationNugget : public ObjectCreationNugget m_fadeIn(false), m_fadeOut(false), m_fadeFrames(0), - m_fadeSoundName(AsciiString::TheEmptyString), // Added By Sadullah Nader - m_particleSysName(AsciiString::TheEmptyString), // Added By Sadullah Nader - m_putInContainer(AsciiString::TheEmptyString), // Added By Sadullah Nader + m_fadeSoundName(AsciiString::TheEmptyString), + m_particleSysName(AsciiString::TheEmptyString), + m_putInContainer(AsciiString::TheEmptyString), m_minMag(0.0f), m_maxMag(0.0f), m_minPitch(0.0f), @@ -766,10 +760,8 @@ class GenericObjectCreationNugget : public ObjectCreationNugget m_shadowType(SHADOW_NONE), m_fxFinal(NULL), m_preserveLayer(true), - m_objectCount(0) // Added By Sadullah Nader + m_objectCount(0) { - // Change Made by Sadullah Nader - // for init purposes, easier to read m_offset.zero(); } diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp index f12d71bf52..ce28b73cbe 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp @@ -1221,10 +1221,7 @@ void CellAndObjectIntersection::removeAllCoverage() //----------------------------------------------------------------------------- PartitionCell::PartitionCell() { - //Added By Sadullah Nader - //Initializations inserted m_cellX = m_cellY = 0; - // m_firstCoiInCell = NULL; m_coiCount = 0; #ifdef PM_CACHE_TERRAIN_HEIGHT 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 8f6331f8c4..51d2a7813e 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeliverPayloadAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeliverPayloadAIUpdate.cpp @@ -115,23 +115,15 @@ DeliverPayloadAIUpdate::DeliverPayloadAIUpdate( Thing *thing, const ModuleData* m_visibleItemsDelivered = 0; m_deliveryDecal.clear(); m_previousDistanceSqr = 0; - m_freeToExit = FALSE; m_acceptingCommands = TRUE; - - // Added By Sadullah Nader - // Initialization missing and needed - m_diveState = DIVESTATE_PREDIVE; - - // End Add } //------------------------------------------------------------------------------------------------- DeliverPayloadAIUpdate::~DeliverPayloadAIUpdate( void ) { m_deliveryDecal.clear(); - deleteInstance(m_deliverPayloadStateMachine); } 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 c509c0baf6..32aa3ece0f 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp @@ -384,8 +384,6 @@ class DozerActionDoActionState : public State DozerActionDoActionState( StateMachine *machine, DozerTask task ) : State( machine, "DozerActionDoActionState" ) { m_task = task; - //Added By Sadullah Nader - // Initializations missing and needed m_enterFrame = 0; } virtual StateReturnType update( void ); 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 29034934a4..f264228618 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp @@ -1665,10 +1665,7 @@ JetAIUpdate::JetAIUpdate( Thing *thing, const ModuleData* moduleData ) : AIUpdat m_lockonDrawable = NULL; m_landingPosForHelipadStuff.zero(); - //Added By Sadullah Nader - //Initializations missing and needed m_producerLocation.zero(); - // m_enginesOn = TRUE; } 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 7b2dfd9eec..4721df43da 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp @@ -87,12 +87,7 @@ WorkerAIUpdate::WorkerAIUpdate( Thing *thing, const ModuleData* moduleData ) : // // initialize the dozer machine to NULL, we want to do this and create it during the update // implementation because at this point we don't have the object all setup - // - - //Added By Sadullah Nader - //Initialization(s) inserted m_isRebuild = FALSE; - // m_dozerMachine = NULL; for( Int i = 0; i < DOZER_NUM_TASKS; i++ ) { diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/BattlePlanUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/BattlePlanUpdate.cpp index 5b50aa12c3..8647e01008 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/BattlePlanUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/BattlePlanUpdate.cpp @@ -155,12 +155,7 @@ BattlePlanUpdate::BattlePlanUpdate( Thing *thing, const ModuleData* moduleData ) m_visionObjectID = INVALID_ID; - //------------------------// - // Added by Sadullah Nader// - //------------------------// - m_specialPowerModule = NULL; - // } //------------------------------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/BoneFXUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/BoneFXUpdate.cpp index 6e25783247..92dc1c839d 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/BoneFXUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/BoneFXUpdate.cpp @@ -88,7 +88,6 @@ BoneFXUpdate::BoneFXUpdate( Thing *thing, const ModuleData* moduleData ) : Updat m_particleSystemIDs.clear(); m_active = FALSE; - //Added By Sadullah Nader m_curBodyState = BODY_PRISTINE; } diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/FlammableUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/FlammableUpdate.cpp index 1598557952..e8e8f750e7 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/FlammableUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/FlammableUpdate.cpp @@ -47,10 +47,7 @@ FlammableUpdateModuleData::FlammableUpdateModuleData() m_aflameDuration = 0; m_aflameDamageDelay = 0; m_aflameDamageAmount = 0; - // Enabled By Sadullah Nader - // Initialization needed m_burningSoundName.clear(); - // m_flameDamageLimitData = 20.0f; m_flameDamageExpirationDelay = LOGICFRAMES_PER_SECOND * 2; } diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp index 0bd22873dd..57057173a9 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp @@ -61,13 +61,10 @@ //------------------------------------------------------------------------------------------------- HelicopterSlowDeathBehaviorModuleData::HelicopterSlowDeathBehaviorModuleData( void ) { - //Added By Sadullah Nader - //Initializations missing and needed m_attachParticleBone.clear(); m_bladeBone.clear(); m_bladeObjectName.clear(); m_finalRubbleObject.clear(); - // m_spiralOrbitTurnRate = 0.0f; m_spiralOrbitForwardSpeed = 0.0f; diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cpp index 73505c6863..9d1be6984d 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cpp @@ -157,10 +157,7 @@ HordeUpdate::HordeUpdate( Thing *thing, const ModuleData* moduleData ) : UpdateM m_inHorde = FALSE; m_hasFlag = FALSE; m_lastHordeRefreshFrame = TheGameLogic->getFrame(); - // Added By Sadullah Nader - // Initializations missing and needed m_trueHordeMember = FALSE; - // UnsignedInt delay = getHordeUpdateModuleData()->m_updateRate; setWakeFrame(getObject(), UPDATE_SLEEP(GameLogicRandomValue(1, delay))); diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/LaserUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/LaserUpdate.cpp index 3cebb0af7a..8b4a9b4ed7 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/LaserUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/LaserUpdate.cpp @@ -82,12 +82,9 @@ LaserRadiusUpdate::LaserRadiusUpdate() //------------------------------------------------------------------------------------------------- LaserUpdate::LaserUpdate( Thing *thing, const ModuleData* moduleData ) : ClientUpdateModule( thing, moduleData ) { - //Added By Sadullah Nader - //Initialization missing and needed m_dirty = FALSE; m_endPos.zero(); m_startPos.zero(); - // m_particleSystemID = INVALID_PARTICLE_SYSTEM_ID; m_targetParticleSystemID = INVALID_PARTICLE_SYSTEM_ID; } diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/LifetimeUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/LifetimeUpdate.cpp index f1147b5036..c56333c961 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/LifetimeUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/LifetimeUpdate.cpp @@ -42,10 +42,7 @@ LifetimeUpdate::LifetimeUpdate( Thing *thing, const ModuleData* moduleData ) : UpdateModule( thing, moduleData ) { const LifetimeUpdateModuleData* d = getLifetimeUpdateModuleData(); - // Added By Sadullah Nader - // Initializations needed m_dieFrame = 0; - // UnsignedInt delay; if( getObject()->isKindOf( KINDOF_HULK ) && TheGameLogic->getHulkMaxLifetimeOverride() != -1 ) { diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cpp index 3ebe93f320..ad7614d1f1 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cpp @@ -87,11 +87,8 @@ ParticleUplinkCannonUpdateModuleData::ParticleUplinkCannonUpdateModuleData() m_manualDrivingSpeed = 0.0f; m_manualFastDrivingSpeed = 0.0f; m_doubleClickToFastDriveDelay = 500; - //Added by Sadullah Nader - //Initializations inserted m_swathOfDeathAmplitude = 0.0f; m_swathOfDeathDistance = 0.0f; - // } //------------------------------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ProductionExitUpdate/DefaultProductionExitUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ProductionExitUpdate/DefaultProductionExitUpdate.cpp index bd137d1630..9d559b0250 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ProductionExitUpdate/DefaultProductionExitUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ProductionExitUpdate/DefaultProductionExitUpdate.cpp @@ -46,13 +46,7 @@ DefaultProductionExitUpdate::DefaultProductionExitUpdate( Thing *thing, const Mo { // no rally point has been set m_rallyPointExists = false; - // Added By Sadullah Nader - // Initialization missing and needed - m_rallyPoint.zero(); - - // - setWakeFrame(getObject(), UPDATE_SLEEP_FOREVER); } diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ProductionExitUpdate/QueueProductionExitUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ProductionExitUpdate/QueueProductionExitUpdate.cpp index 6e7124a877..bfcab8950b 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ProductionExitUpdate/QueueProductionExitUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ProductionExitUpdate/QueueProductionExitUpdate.cpp @@ -46,12 +46,8 @@ QueueProductionExitUpdate::QueueProductionExitUpdate( Thing *thing, const Module { m_currentDelay = 0; - //Added By Sadullah Nader - //Initializations inserted m_creationClearDistance = 0; m_rallyPoint.zero(); - // - // no rally point has been set m_rallyPointExists = false; m_currentBurstCount = 0; diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cpp index 909be605fb..179b61d139 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cpp @@ -158,11 +158,8 @@ ProductionEntry::ProductionEntry( void ) m_framesUnderConstruction = 0; m_next = NULL; m_prev = NULL; - //Added By Sadullah Nader - //Initializations inserted m_productionQuantityProduced = 0; m_productionQuantityTotal = 0; - // } //------------------------------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp index 4dda51c050..7a1e167cbc 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp @@ -68,10 +68,7 @@ //------------------------------------------------------------------------------------------------- SpecialAbilityUpdate::SpecialAbilityUpdate( Thing *thing, const ModuleData* moduleData ) : UpdateModule( thing, moduleData ) { - //Added By Sadullah Nader - //Initialization(s) inserted m_captureFlashPhase = 0.0f; - // m_active = false; m_prepFrames = 0; m_animFrames = 0; diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp index a1f767a712..1411a1b830 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp @@ -99,10 +99,7 @@ StealthUpdate::StealthUpdate( Thing *thing, const ModuleData* moduleData ) : Upd //Must be enabled manually if using disguise system (bomb truck uses) m_enabled = !data->m_teamDisguised; - //Added By Sadullah Nader - //Initialization(s) inserted m_detectionExpiresFrame = 0; - // m_pulsePhaseRate = 0.2f; m_pulsePhase = GameClientRandomValueReal(0, PI); diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StickyBombUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StickyBombUpdate.cpp index 2e71aa28f4..0b7ca86706 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StickyBombUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StickyBombUpdate.cpp @@ -50,10 +50,7 @@ StickyBombUpdate::StickyBombUpdate( Thing *thing, const ModuleData *moduleData ) { m_targetID = INVALID_ID; m_dieFrame = 0; - //Added By Sadullah Nader - //Initialization(s) inserted m_nextPingFrame = 0; - // setWakeFrame(getObject(), UPDATE_SLEEP_FOREVER); } diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StructureCollapseUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StructureCollapseUpdate.cpp index 62a4942333..7789f245f4 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StructureCollapseUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StructureCollapseUpdate.cpp @@ -68,11 +68,8 @@ StructureCollapseUpdate::StructureCollapseUpdate( Thing *thing, const ModuleData m_collapseFrame = 0; m_collapseState = COLLAPSESTATE_STANDING; m_collapseVelocity = 0.0f; - //Added By Sadullah Nader - //Initialization(s) inserted m_burstFrame = 0; m_currentHeight = 0.0f; - // setWakeFrame(getObject(), UPDATE_SLEEP_FOREVER); } diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StructureToppleUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StructureToppleUpdate.cpp index 61470e9a32..ec95774da6 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StructureToppleUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StructureToppleUpdate.cpp @@ -55,13 +55,9 @@ const Int MAX_IDX = 32; //------------------------------------------------------------------------------------------------- StructureToppleUpdate::StructureToppleUpdate( Thing *thing, const ModuleData* moduleData ) : UpdateModule( thing, moduleData ) { - - //Added By Sadullah Nader - //Initialization(s) inserted m_delayBurstLocation.zero(); m_structuralIntegrity = 0.0f; m_toppleDirection.x = m_toppleDirection.y = 0; - // m_toppleFrame = 0; m_toppleState = TOPPLESTATE_STANDING; m_toppleVelocity = 0.0f; diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ToppleUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ToppleUpdate.cpp index 497a4e0680..8eb909b880 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ToppleUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ToppleUpdate.cpp @@ -104,12 +104,9 @@ void ToppleUpdateModuleData::buildFieldParse(MultiIniFieldParse& p) //------------------------------------------------------------------------------------------------- ToppleUpdate::ToppleUpdate( Thing *thing, const ModuleData* moduleData ) : UpdateModule( thing, moduleData ) { - //Added By Sadullah Nader - //Initialization(s) inserted m_angleDeltaX = 0.0f; m_doBounceFX = FALSE; m_numAngleDeltaX = 0; - // m_angularVelocity = 0; m_angularAccumulation = 0; m_angularAcceleration = 0; diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/WaveGuideUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/WaveGuideUpdate.cpp index 0783293471..33737623cb 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/WaveGuideUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/WaveGuideUpdate.cpp @@ -58,12 +58,9 @@ // ------------------------------------------------------------------------------------------------ WaveGuideUpdateModuleData::WaveGuideUpdateModuleData( void ) { - //Added By Sadullah Nader - //Initialization(s) inserted m_bridgeParticleAngleFudge = 0.0f; m_randomSplashSoundFrequency = 0; m_waveDelay = 0.0f; - // m_ySize = 0.0f; m_linearWaveSpacing = 0.0f; m_waveBendMagnitude = 0.0f; diff --git a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp index 8573b7b181..95b6957d5b 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp @@ -362,8 +362,6 @@ m_skirmishHumanPlayer(NULL), m_fade(FADE_NONE), m_freezeByScript(FALSE), m_frameObjectCountChanged(0), -//Added By Sadullah Nader -//Initializations inserted m_closeWindowTimer(0), m_curFadeFrame(0), m_curFadeValue(0.0f), @@ -378,7 +376,6 @@ m_numAttackInfo(0), m_shownMPLocalDefeatWindow(FALSE), m_objectsShouldReceiveDifficultyBonus(TRUE), m_ChooseVictimAlwaysUsesNormal(false) -// { st_CanAppCont = true; st_LastCurrentFrame = st_CurrentFrame = 0; diff --git a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp index b8b13754c6..e81045e9a9 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp @@ -632,10 +632,7 @@ m_firstScript(NULL), m_hasWarnings(false), m_isGroupActive(true), m_isGroupSubroutine(false), -//Added By Sadullah Nader -//Initializations inserted m_nextGroup(NULL) -// { m_groupName.format("Script Group %d", ScriptList::getNextID()); } @@ -906,11 +903,8 @@ m_hasWarnings(false), m_nextScript(NULL), m_condition(NULL), m_action(NULL), -//Added By Sadullah Nader -//Initializations inserted m_actionFalse(NULL), m_curTime(0.0f) -// { } @@ -2172,10 +2166,7 @@ ScriptAction::ScriptAction(): m_actionType(NO_OP), m_hasWarnings(false), m_numParms(0), -//Added By Sadullah Nader -//Initializations inserted m_nextAction(NULL) -// { } diff --git a/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp index 03321c2be2..0e93742b9d 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp @@ -207,8 +207,6 @@ void setFPMode( void ) // ------------------------------------------------------------------------------------------------ GameLogic::GameLogic( void ) { - //Added By Sadullah Nader - //Initializations missing and necessary m_background = NULL; m_CRC = 0; m_isInUpdate = FALSE; @@ -224,7 +222,6 @@ GameLogic::GameLogic( void ) m_shouldValidateCRCs = FALSE; m_startNewGame = FALSE; - // m_frame = 0; m_hasUpdated = FALSE; @@ -1157,7 +1154,6 @@ void GameLogic::startNewGame( Bool saveGame ) TheMouse->setVisibility(FALSE); m_loadScreen->init(game); - // updateLoadProgress( LOAD_PROGRESS_START ); } } @@ -2094,8 +2090,6 @@ void GameLogic::startNewGame( Bool saveGame ) TheGameSpyBuddyMessageQueue->addRequest(req); } - //Added By Sadullah Nader - //Added to fix the quit menu //ReAllows quit menu to work during loading scene setGameLoading(FALSE); diff --git a/Generals/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp b/Generals/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp index 2e67453c02..e556457319 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp @@ -299,10 +299,7 @@ void GameLogic::clearGameData( Bool showScoreScreen ) // ------------------------------------------------------------------------------------------------ void GameLogic::prepareNewGame( GameMode gameMode, GameDifficulty diff, Int rankPoints ) { - //Added By Sadullah Nader - //Fix for loading game scene setGameLoading(TRUE); - // TheScriptEngine->setGlobalDifficulty(diff); diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DProgressBar.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DProgressBar.cpp index f6e4f252fb..e8a97d8105 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DProgressBar.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DProgressBar.cpp @@ -401,7 +401,6 @@ void W3DGadgetProgressBarImageDraw( GameWindow *window, WinInstanceData *instDat } start.x = origin.x + 10 + barCenter->getImageWidth() * pieces; //pieces = (size.x - barWindowSize.x -20) / barRight->getImageWidth(); - //Changed By Saad for flashing grey piece pieces = ((size.x - 20) / barCenter->getImageWidth()) - pieces; for( i = 0; i < pieces; i++ ) { diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Geometry.h b/GeneralsMD/Code/GameEngine/Include/Common/Geometry.h index 1efebfb6a8..c5ce3cbff1 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/Geometry.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/Geometry.h @@ -111,12 +111,8 @@ class GeometryInfo : public Snapshot GeometryInfo(GeometryType type, Bool isSmall, Real height, Real majorRadius, Real minorRadius) { - // Added by Sadullah Nader - // Initializations missing and needed m_boundingCircleRadius = 0.0f; m_boundingSphereRadius = 0.0f; - // - set(type, isSmall, height, majorRadius, minorRadius); } diff --git a/GeneralsMD/Code/GameEngine/Include/Common/INI.h b/GeneralsMD/Code/GameEngine/Include/Common/INI.h index 182df0ad3f..3268152780 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/INI.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/INI.h @@ -138,12 +138,8 @@ class MultiIniFieldParse public: MultiIniFieldParse() : m_count(0) { - //Added By Sadullah Nader - //Initializations missing and needed for(Int i = 0; i < MAX_MULTI_FIELDS; i++) m_extraOffset[i] = 0; - // - } void add(const FieldParse* f, UnsignedInt e = 0); diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h index 3c4b388500..1d37eb6ee3 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h @@ -448,8 +448,6 @@ class SideSelectWindowData public: SideSelectWindowData(void) { - //Added By Sadullah Nader - //Initializations generalSpeak = NULL; m_currColor = 0; m_gereralsNameWin = NULL; @@ -473,7 +471,6 @@ class SideSelectWindowData m_upgradeLabel3Win = NULL; m_upgradeLabel4Win = NULL; sideWindow = NULL; - // } ~SideSelectWindowData(void); diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Display.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Display.h index 7a100795c1..799633ed04 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/Display.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Display.h @@ -218,10 +218,8 @@ extern Display *TheDisplay; extern void StatDebugDisplay( DebugDisplayInterface *dd, void *, FILE *fp = NULL ); -//Added By Saad //Necessary for display resolution confirmation dialog box //Holds the previous and current display settings - typedef struct _DisplaySettings { Int xRes; //Resolution width diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/SelectionXlat.h b/GeneralsMD/Code/GameEngine/Include/GameClient/SelectionXlat.h index f3bd0827b7..a102bae2c8 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/SelectionXlat.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/SelectionXlat.h @@ -64,8 +64,6 @@ class SelectionTranslator : public GameMessageTranslator SelectionTranslator(); ~SelectionTranslator(); virtual GameMessageDisposition translateGameMessage(const GameMessage *msg); - - //Added By Sadullah Nader //added for fix to the drag selection when entering control bar //changes the mode of drag selecting to it's opposite void setDragSelecting(Bool dragSelect); diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIGuard.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIGuard.h index a9f6a68501..c8b0597bff 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIGuard.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIGuard.h @@ -78,8 +78,6 @@ class ExitConditions : public AttackExitConditionsInterface ExitConditions() : m_attackGiveUpFrame(0), m_conditionsToConsider(0), m_radiusSqr(0.0f) { - //Added By Sadullah Nader - // Initializations missing and needed m_center.zero(); } diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIGuardRetaliate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIGuardRetaliate.h index ba9eb252ea..cc889280cd 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIGuardRetaliate.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIGuardRetaliate.h @@ -76,8 +76,6 @@ class GuardRetaliateExitConditions : public AttackExitConditionsInterface GuardRetaliateExitConditions() : m_attackGiveUpFrame(0), m_conditionsToConsider(0), m_radiusSqr(0.0f) { - //Added By Sadullah Nader - // Initializations missing and needed m_center.zero(); } diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h index 84aedef91d..c623b5aba3 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h @@ -113,11 +113,8 @@ class TeamInQueue : public MemoryPoolObject, m_reinforcement(false), m_stopQueueing(false), m_reinforcementID(INVALID_ID), - //Added By Sadullah Nader - //Initialization(s) inserted m_frameStarted(0), m_priorityBuild(FALSE) - // { } diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h index 49bbfffc9a..420142129b 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h @@ -312,9 +312,6 @@ class GameLogic : public SubsystemInterface, public Snapshot std::map m_cachedCRCs; ///< CRCs we've seen this frame Bool m_shouldValidateCRCs; ///< Should we validate CRCs this frame? //----------------------------------------------------------------------------------------------- - - //Added By Sadullah Nader - //Used to for load scene //Bool m_loadingScene; Bool m_loadingMap; Bool m_loadingSave; diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CreateCrateDie.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CreateCrateDie.h index 2139b995cb..a5c9f2e21d 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CreateCrateDie.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CreateCrateDie.h @@ -46,8 +46,6 @@ class CreateCrateDieModuleData : public DieModuleData CreateCrateDieModuleData() { - // Added By Sadullah Nader - // Initializations missing and needed m_crateNameList.clear(); } ~CreateCrateDieModuleData() diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/DeliverPayloadAIUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/DeliverPayloadAIUpdate.h index e92b964b6e..84e64d9f04 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/DeliverPayloadAIUpdate.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/DeliverPayloadAIUpdate.h @@ -204,11 +204,7 @@ class DeliverPayloadAIUpdateModuleData : public AIUpdateModuleData m_dropOffset.zero(); m_dropVariance.zero(); m_deliveryDecalRadius = 0; - // Added By Sadullah Nader - // Initialization missing and needed - m_putInContainerName.clear(); - // End Add } static void buildFieldParse(MultiIniFieldParse& p) @@ -295,14 +291,9 @@ class DeliverPayloadData m_visiblePayloadWeaponTemplate = NULL; m_selfDestructObject = FALSE; m_deliveryDecalRadius = 0; - // Added By Sadullah Nader - // Initialization missing and needed - m_visibleDropBoneName.clear(); m_visiblePayloadTemplateName.clear(); m_visibleSubObjectName.clear(); - - // End Add } static const FieldParse* getFieldParse(); diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/DeployStyleAIUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/DeployStyleAIUpdate.h index d79bccd2f7..d50fc085f1 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/DeployStyleAIUpdate.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/DeployStyleAIUpdate.h @@ -59,10 +59,7 @@ class DeployStyleAIUpdateModuleData : public AIUpdateModuleData m_packTime = 0; m_resetTurretBeforePacking = false; m_turretsFunctionOnlyWhenDeployed = false; - // Added By Sadullah Nader - // Initialization necessary m_turretsMustCenterBeforePacking = FALSE; - // End Add m_manualDeployAnimations = FALSE; } diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/HackInternetAIUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/HackInternetAIUpdate.h index 6b049d7372..48c3f44b91 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/HackInternetAIUpdate.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/HackInternetAIUpdate.h @@ -46,10 +46,7 @@ class HackInternetState : public State public: HackInternetState( StateMachine *machine ) :State( machine, "HackInternetState" ) { - //Added By Sadullah Nader - //Initializations missing and needed m_framesRemaining = 0; - // } virtual StateReturnType update(); virtual StateReturnType onEnter(); @@ -73,10 +70,7 @@ class PackingState : public State public: PackingState( StateMachine *machine ) : State( machine, "PackingState" ) { - //Added By Sadullah Nader - //Initializations inserted m_framesRemaining = 0; - // } virtual StateReturnType update(); virtual StateReturnType onEnter(); diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ObjectDefectionHelper.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ObjectDefectionHelper.h index baa2c45508..8a3985e59a 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ObjectDefectionHelper.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ObjectDefectionHelper.h @@ -61,13 +61,10 @@ class ObjectDefectionHelper : public ObjectHelper ObjectDefectionHelper( Thing *thing, const ModuleData *modData ) : ObjectHelper( thing, modData ) { - //Added By Sadullah Nader - //Initializations inserted m_defectionDetectionEnd = 0; m_defectionDetectionFlashPhase = FALSE; m_defectionDetectionStart = 0; m_doDefectorFX = FALSE; - // } // virtual destructor prototype provided by memory pool object diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SpawnBehavior.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SpawnBehavior.h index 131105a662..748355ff15 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SpawnBehavior.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SpawnBehavior.h @@ -65,10 +65,7 @@ class SpawnBehaviorModuleData : public BehaviorModuleData { m_spawnNumberData = 0; m_spawnReplaceDelayData = 0; - //Added By Sadullah Nader - //Initialization(s) inserted m_spawnStartNumberData = 0; - // m_initialBurst = 0; m_isOneShotData = FALSE; m_canReclaimOrphans = FALSE; diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/StructureCollapseUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/StructureCollapseUpdate.h index ca645c3004..aecbb73b41 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/StructureCollapseUpdate.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/StructureCollapseUpdate.h @@ -75,9 +75,6 @@ class StructureCollapseUpdateModuleData : public UpdateModuleData m_minCollapseDelay = 0; m_maxCollapseDelay = 0; m_minBurstDelay = 9999; - //Removed by Sadullah Nader - //Redundancy from above - //m_minBurstDelay = 9999; m_maxShudder = 0; m_collapseDamping = 0.0; m_bigBurstFrequency = 0; diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h index 978b04950f..00bf6486bd 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h @@ -1146,10 +1146,7 @@ class PartitionFilterGarrisonable : public PartitionFilter public: PartitionFilterGarrisonable( Bool match ) : m_match(match) { - //Added By Sadullah Nader - //Initializations m_player = NULL; - // } protected: virtual Bool allow( Object *other ); diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Bezier/BezFwdIterator.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Bezier/BezFwdIterator.cpp index 71d0401bce..976b119fc7 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/Bezier/BezFwdIterator.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/Bezier/BezFwdIterator.cpp @@ -28,7 +28,6 @@ //------------------------------------------------------------------------------------------------- BezFwdIterator::BezFwdIterator(): mStep(0), mStepsDesired(0) { - // Added by Sadullah Nader mCurrPoint.zero(); mDDDq.zero(); mDDq.zero(); @@ -38,13 +37,10 @@ BezFwdIterator::BezFwdIterator(): mStep(0), mStepsDesired(0) //------------------------------------------------------------------------------------------------- BezFwdIterator::BezFwdIterator(Int stepsDesired, const BezierSegment *bezSeg) { - // Added by Sadullah Nader mCurrPoint.zero(); mDDDq.zero(); mDDq.zero(); mDq.zero(); - // - mStepsDesired = stepsDesired; mBezSeg = (*bezSeg); } diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp index 42f2775f74..8da2880226 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp @@ -581,13 +581,13 @@ GlobalData::GlobalData() m_debugVisibilityTileDuration = LOGICFRAMES_PER_SECOND; m_debugProjectilePath = FALSE; m_debugProjectileTileWidth = 10; - m_debugProjectileTileDuration = LOGICFRAMES_PER_SECOND; // Changed By Sadullah Nader + m_debugProjectileTileDuration = LOGICFRAMES_PER_SECOND; m_debugThreatMap = FALSE; m_maxDebugThreat = 5000; - m_debugThreatMapTileDuration = LOGICFRAMES_PER_SECOND; // Changed By Sadullah Nader + m_debugThreatMapTileDuration = LOGICFRAMES_PER_SECOND; m_debugCashValueMap = FALSE; m_maxDebugValue = 10000; - m_debugCashValueMapTileDuration = LOGICFRAMES_PER_SECOND; // Changed By Sadullah Nader + m_debugCashValueMapTileDuration = LOGICFRAMES_PER_SECOND; m_vTune = false; m_checkForLeaks = TRUE; m_benchmarkTimer = -1; @@ -695,8 +695,6 @@ GlobalData::GlobalData() m_vertexWaterAttenuationB[ i ] = 0.0f; m_vertexWaterAttenuationC[ i ] = 0.0f; m_vertexWaterAttenuationRange[ i ] = 0.0f; - //Added By Sadullah Nader - //Initializations missing and needed m_vertexWaterAvailableMaps[i].clear(); } @@ -808,8 +806,6 @@ GlobalData::GlobalData() m_autoSmokeParticleLargeMax = 0; m_autoAflameParticleMax = 0; - // Added By Sadullah Nader - // Initializations missing and needed m_autoFireParticleSmallPrefix.clear(); m_autoFireParticleMediumPrefix.clear(); m_autoFireParticleLargePrefix.clear(); @@ -833,8 +829,6 @@ GlobalData::GlobalData() m_maxParticleCount = 0; m_maxFieldParticleCount = 30; - // End Add - m_debugAI = AI_DEBUG_NONE; m_debugSupplyCenterPlacement = FALSE; m_debugAIObstacles = FALSE; diff --git a/GeneralsMD/Code/GameEngine/Source/Common/MultiplayerSettings.cpp b/GeneralsMD/Code/GameEngine/Source/Common/MultiplayerSettings.cpp index a0a36dc499..d23ec32b56 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/MultiplayerSettings.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/MultiplayerSettings.cpp @@ -80,7 +80,6 @@ MultiplayerSettings::MultiplayerSettings() m_showRandomPlayerTemplate = TRUE; m_showRandomStartPos = TRUE; m_showRandomColor = TRUE; - m_observerColor; m_randomColor; diff --git a/GeneralsMD/Code/GameEngine/Source/Common/PartitionSolver.cpp b/GeneralsMD/Code/GameEngine/Source/Common/PartitionSolver.cpp index 3b98cb556e..e51add0e21 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/PartitionSolver.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/PartitionSolver.cpp @@ -63,10 +63,7 @@ PartitionSolver::PartitionSolver(const EntriesVec& elements, const SpacesVec& sp m_data = elements; m_spacesForData = spaces; m_howToSolve = solveHow; - //Added By Sadullah Nader - //Initializations inserted m_currentSolutionLeftovers = 0; - // } void PartitionSolver::solve(void) diff --git a/GeneralsMD/Code/GameEngine/Source/Common/PerfTimer.cpp b/GeneralsMD/Code/GameEngine/Source/Common/PerfTimer.cpp index 2bec94d959..336cffbc83 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/PerfTimer.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/PerfTimer.cpp @@ -312,10 +312,7 @@ PerfGather::PerfGather(const char *identifier) : m_next(0), m_prev(0) { - //Added By Sadullah Nader - //Initializations inserted m_ignore = FALSE; - // DEBUG_ASSERTCRASH(strchr(m_identifier, ',') == NULL, ("PerfGather names must not contain commas")); addToList(); } @@ -561,8 +558,6 @@ PerfTimer::PerfTimer( const char *identifier, Bool crashWithInfo, Int startFrame m_callCount(0), m_runningTime(0), m_outputInfo(true), - //Added By Sadullah Nader - //Intializations inserted m_lastFrame(-1) { } diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp index 48296af878..9088ec4bd1 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp @@ -321,8 +321,6 @@ Player::Player( Int playerIndex ) m_playerTemplate = NULL; m_battlePlanBonuses = NULL; m_skillPointsModifier = 1.0f; - //Added By Sadullah - //Initializations inserted m_canBuildUnits = TRUE; m_canBuildBase = TRUE; m_cashBountyPercent = 0.0f; @@ -339,7 +337,6 @@ Player::Player( Int playerIndex ) { m_squads[i] = NULL; } - // for (i = 0; i < MAX_PLAYER_COUNT; ++i) { m_attackedBy[i] = false; diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp index 3e87bdb391..61770bd035 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp @@ -237,14 +237,10 @@ UnicodeString ProductionPrerequisite::getRequiresList(const Player *player) cons Int i; Bool orRequirements[MAX_PREREQ]; - //Added for fix below in getRequiresList - //By Sadullah Nader - //Initializes the OR_WITH_PREV structures for (i = 0; i < MAX_PREREQ; i++) { orRequirements[i] = FALSE; } - // // account for the "or" unit cases, start for loop at 1 for (i = 1; i < cnt; i++) { diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ScoreKeeper.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ScoreKeeper.cpp index da01c71b0a..41e6d5ceaa 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ScoreKeeper.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ScoreKeeper.cpp @@ -102,10 +102,7 @@ void ScoreKeeper::reset( Int playerIdx ) m_totalMoneyEarned = m_totalMoneySpent = 0; m_totalUnitsLost = m_totalUnitsBuilt = 0; m_totalBuildingsLost = m_totalBuildingsBuilt = 0; - //Added By Sadullah Nader - //Initializtion(s) inserted m_totalFactionBuildingsCaptured = m_totalTechBuildingsCaptured = 0; - // m_currentScore = 0; m_objectsBuilt.clear(); m_objectsCaptured.clear(); diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp index a1bb7375a1..701debf163 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp @@ -1316,11 +1316,7 @@ Team::Team(TeamPrototype *proto, TeamID id ) : m_curUnits(0), m_wasIdle(false) { - //Added By Sadullah Nader - //Initialization(s) inserted m_created = FALSE; - - // m_commonAttackTarget = INVALID_ID; // allocate new relation map pools diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp index a02e47e3c0..a90b4903f7 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp @@ -368,14 +368,10 @@ RecorderClass::RecorderClass() m_file = NULL; m_fileName.clear(); m_currentFilePosition = 0; - //Added By Sadullah Nader - //Initializtion(s) inserted m_doingAnalysis = FALSE; m_archiveReplays = FALSE; m_nextFrame = 0; m_wasDesync = FALSE; - // - init(); // just for the heck of it. } diff --git a/GeneralsMD/Code/GameEngine/Source/Common/StatsCollector.cpp b/GeneralsMD/Code/GameEngine/Source/Common/StatsCollector.cpp index a3395260a7..4289f2b201 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/StatsCollector.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/StatsCollector.cpp @@ -76,13 +76,9 @@ static char statsDir[255] = "Stats\\"; //============================================================================= StatsCollector::StatsCollector( void ) { - //Added By Sadullah Nader - //Initialization(s) inserted m_isScrolling = FALSE; m_scrollBeginTime = 0; m_scrollTime = 0; - - // m_timeCount = 0; m_buildCommands = 0; m_moveCommands = 0; @@ -90,10 +86,8 @@ StatsCollector::StatsCollector( void ) m_scrollMapCommands = 0; m_AIUnits = 0; m_playerUnits = 0; - m_lastUpdate = 0; m_startFrame = TheGameLogic->getFrame(); - } //Destructor //============================================================================= diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/DataChunk.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/DataChunk.cpp index 01bc174f2f..6f04f71e8d 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/DataChunk.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/DataChunk.cpp @@ -237,11 +237,7 @@ m_pOut(pOut) AsciiString tmpFileName = TheGlobalData->getPath_UserData(); tmpFileName.concat(TEMP_FILENAME); m_tmp_file = ::fopen( tmpFileName.str(), "wb" ); - // Added Sadullah Nader - // Initializations missing and needed m_chunkStack = NULL; - - // End Add } DataChunkOutput::~DataChunkOutput() diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/Upgrade.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/Upgrade.cpp index 38a4566e30..b93fb4de03 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/Upgrade.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/Upgrade.cpp @@ -131,10 +131,7 @@ const FieldParse UpgradeTemplate::m_upgradeFieldParseTable[] = //------------------------------------------------------------------------------------------------- UpgradeTemplate::UpgradeTemplate( void ) { - //Added By Sadullah Nader - //Initialization(s) inserted m_cost = 0; - // m_type = UPGRADE_TYPE_PLAYER; m_nameKey = NAMEKEY_INVALID; m_buildTime = 0.0f; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Display.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Display.cpp index d8a70c0be9..1b75c62468 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Display.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Display.cpp @@ -64,11 +64,8 @@ Display::Display() m_elapsedCopywriteTime = 0; m_copyrightDisplayString = NULL; - // Added by Sadullah Nader - // Initializations missing and needed m_currentlyPlayingMovie.clear(); m_letterBoxFadeStartTime = 0; - // End Add } /** diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp index e96a787c51..9f1f5f7eaf 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp @@ -349,11 +349,8 @@ Drawable::Drawable( const ThingTemplate *thingTemplate, DrawableStatusBits statu // assign status bits before anything else can be done m_status = statusBits; - // Added By Sadullah Nader - // Initialization missing and needed m_nextDrawable = NULL; m_prevDrawable = NULL; - // m_customSoundAmbientInfo = NULL; @@ -365,17 +362,12 @@ Drawable::Drawable( const ThingTemplate *thingTemplate, DrawableStatusBits statu Int i; - // Added By Sadullah Nader - // Initialization missing and needed m_flashColor = 0; m_selected = '\0'; - // m_expirationDate = 0; // 0 == never expires m_lastConstructDisplayed = -1.0f; - - //Added By Sadullah Nader //Fix for the building percent m_constructDisplayString = TheDisplayStringManager->newDisplayString(); m_constructDisplayString->setFont(TheFontLibrary->getFont(TheInGameUI->getDrawableCaptionFontName(), diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp index a526844127..7ad72afa73 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp @@ -565,10 +565,6 @@ CommandButton::CommandButton( void ) //m_pushedImage = NULL; m_flashCount = 0; - - // Added by Sadullah Nader - // The purpose is to initialize these variable to values that are zero or empty - m_conflictingLabel.clear(); m_cursorName.clear(); m_descriptionLabel.clear(); @@ -577,9 +573,6 @@ CommandButton::CommandButton( void ) m_options = 0; m_purchasedLabel.clear(); m_textLabel.clear(); - - // End Add - m_window = NULL; m_commandButtonBorder = COMMAND_BUTTON_BORDER_NONE; //m_prev = NULL; @@ -884,8 +877,6 @@ ControlBar::ControlBar( void ) m_buildToolTipLayout = NULL; m_showBuildToolTipLayout = FALSE; - // Added By Sadullah Nader - // initializing vars to zero m_animateDownWin1Pos.x = m_animateDownWin1Pos.y = 0; m_animateDownWin1Size.x = m_animateDownWin1Size.y = 0; m_animateDownWin2Pos.x = m_animateDownWin2Pos.y = 0; @@ -902,11 +893,10 @@ ControlBar::ControlBar( void ) m_currContext = CB_CONTEXT_NONE; m_defaultControlBarPosition.x = m_defaultControlBarPosition.y = 0; m_genStarFlash = FALSE; - m_genStarOff = NULL; + m_genStarOff = NULL; m_genStarOn = NULL; m_UIDirty = FALSE; - // -// m_controlBarResizer = NULL; + // m_controlBarResizer = NULL; m_buildUpClockColor = GameMakeColor(0,0,0,100); m_commandBarBorderColor = GameMakeColor(0,0,0,100); for( i = 0; i < NUM_CONTEXT_PARENTS; i++ ) diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp index c6be2fa7fa..dd3ff335ae 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp @@ -189,13 +189,8 @@ ControlBarSchemeImage::~ControlBarSchemeImage( void ) ControlBarSchemeAnimation::ControlBarSchemeAnimation( void ) { - // Added by Sadullah Nader - // Initializations missing and needed - m_animDuration = 0; m_finalPos.x = m_finalPos.y = 0; - - // End Add m_name.clear(); m_animType = 0; m_animImage = NULL; @@ -304,12 +299,8 @@ ControlBarScheme::ControlBarScheme(void) m_optionsButtonPushed = NULL; m_optionsButtonDisabled = NULL; - // Added By Sadullah Nader - // Initializations needed - m_commandBarBorderColor = 0; - // m_idleWorkerButtonEnable = NULL; m_idleWorkerButtonHightlited = NULL; m_idleWorkerButtonPushed = NULL; @@ -354,7 +345,6 @@ ControlBarScheme::ControlBarScheme(void) m_minMaxButtonEnable = NULL; m_minMaxButtonHightlited = NULL; m_minMaxButtonPushed = NULL; - m_minMaxUL.x = 0; m_minMaxLR.x = 0; 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 45f5039eae..9454e3c4b2 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp @@ -719,11 +719,8 @@ void InitLanGameGadgets( void ) Int localSlotNum = TheLAN->GetMyGame()->getLocalSlotNum(); DEBUG_ASSERTCRASH(localSlotNum >= 0, ("Bad slot number!")); - //Added By Sadullah Nader //Tooltip function is being set for techBuildings, and supplyDocks - windowMap->winSetTooltipFunc(MapSelectorTooltip); - //End Add for (Int i = 0; i < MAX_SLOTS; i++) { @@ -778,7 +775,6 @@ void InitLanGameGadgets( void ) buttonAcceptID[i] = TheNameKeyGenerator->nameToKey( tmpString ); buttonAccept[i] = TheWindowManager->winGetWindowFromId( parentLanGameOptions, buttonAcceptID[i] ); DEBUG_ASSERTCRASH(buttonAccept[i], ("Could not find the buttonAccept[%d]",i )); - //Added by Saad for the tooltips on the MultiPlayer icons buttonAccept[i]->winSetTooltipFunc(gameAcceptTooltip); // // tmpString.format("LanGameOptionsMenu.wnd:ButtonStartPosition%d", i); 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 b52054d4e5..db90f5ab0a 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp @@ -74,12 +74,9 @@ #include "GameNetwork/GameSpy/MainMenuUtils.h" #include "GameClient/CDCheck.h" -//Added By Saad -//for accessing the InGameUI #include "GameClient/InGameUI.h" - // PRIVATE DATA /////////////////////////////////////////////////////////////////////////////////// enum @@ -208,7 +205,6 @@ static Bool launchChallengeMenu = FALSE; static Bool dontAllowTransitions = FALSE; -//Added by Saad const Int /*TIME_OUT = 15,*/ CORNER = 10; void AcceptResolution(); void DeclineResolution(); @@ -216,7 +212,6 @@ GameWindow *resAcceptMenu = NULL; extern DisplaySettings oldDispSettings, newDispSettings; extern Bool dispChanged; //static time_t timeStarted = 0, currentTime = 0; -// void diffReverseSide( void ); void HandleCanceledDownload( Bool resetDropDown ) @@ -718,8 +713,6 @@ void MainMenuShutdown( WindowLayout *layout, void *userData ) extern Bool DontShowMainMenu; //////////////////////////////////////////////////////////////////////////// -//Added By Sadullah Nader -//Added as a fix to the resolution change //Allows the user to confirm the change, goes back to the previous mode //if the time to change expires. //////////////////////////////////////////////////////////////////////////// @@ -838,8 +831,6 @@ void MainMenuUpdate( WindowLayout *layout, void *userData ) DownloadMenuUpdate(layout, userData); } - // Added by Saad to the confirmation or decline of the resoluotion change - // dialog box. /* This is also commented for the same reason as the top if (dispChanged) { @@ -1519,9 +1510,6 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, { // 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(RTS_DEBUG) - - //Added By Sadullah Nader - //Changed the preprocessing code to normal code if (TheGlobalData->m_windowed) { quitCallback(); @@ -1531,7 +1519,6 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, { QuitMessageBoxYesNo(TheGameText->fetch("GUI:QuitPopupTitle"), TheGameText->fetch("GUI:QuitPopupMessage"),quitCallback,NULL); } - // //#endif } 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 660911e951..14d6063f8e 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp @@ -72,8 +72,6 @@ #include "GameLogic/GameLogic.h" #include "GameLogic/ScriptEngine.h" #include "WWDownload/Registry.h" -//added by saad -//used to access a messagebox that does "ok" and "cancel" #include "GameClient/MessageBox.h" #include "ww3d.h" @@ -210,13 +208,10 @@ static GameWindow * radioLow = NULL; */ -//Added By Saad for the resolution confirmation dialog box DisplaySettings oldDispSettings, newDispSettings; Bool dispChanged = FALSE; extern Int timer; extern void DoResolutionDialog(); -// - static Bool ignoreSelected = FALSE; WindowLayout *OptionsLayout = NULL; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupSaveLoad.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupSaveLoad.cpp index 0ed1e4174e..7f4d4b990a 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupSaveLoad.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupSaveLoad.cpp @@ -769,9 +769,7 @@ WindowMsgHandledType SaveLoadMenuSystem( GameWindow *window, UnsignedInt msg, buttonFrame->winEnable( TRUE ); updateMenuActions(); - //Added By Sadullah Nader - //Fix for bug - // close save menuu + // close save menu closeSaveMenu( window ); // @@ -831,7 +829,7 @@ WindowMsgHandledType SaveLoadMenuSystem( GameWindow *window, UnsignedInt msg, buttonFrame->winEnable( TRUE ); updateMenuActions(); - // close save menuu + // close save menu closeSaveMenu( window ); // get save filename @@ -889,15 +887,9 @@ WindowMsgHandledType SaveLoadMenuSystem( GameWindow *window, UnsignedInt msg, buttonFrame->winEnable( TRUE ); updateMenuActions(); - - - // do the load game if( controlID == buttonLoadConfirm ) { - //Moved by Sadullah Nader - //moved to fix the - // close save/load layout menu closeSaveMenu( window ); doLoadGame(); } 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 2bf37bbfa1..0d387b201c 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/QuitMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/QuitMenu.cpp @@ -279,14 +279,9 @@ void HideQuitMenu( void ) //------------------------------------------------------------------------------------------------- void ToggleQuitMenu() { - - //Added By Sadullah Nader - //Added a check to see if we're not in game yet if (TheGameLogic->isIntroMoviePlaying() || TheGameLogic->isLoadingMap() ||TheScriptEngine->isGameEnding()) return; - //End Add - // BGC- If we are currently in the disconnect screen, don't let the quit menu come up. if (TheDisconnectMenu != NULL) { if (TheDisconnectMenu->isScreenVisible() == TRUE) { @@ -323,12 +318,9 @@ void ToggleQuitMenu() isVisible = FALSE; - //Added By Sadullah Nader - //Bug: When Toggling the quit menu off, the quit confirmation should also go away if (quitConfirmationWindow) TheWindowManager->winDestroy(quitConfirmationWindow); quitConfirmationWindow = NULL; - // if ( !TheGameLogic->isInMultiplayerGame() ) TheGameLogic->setGamePaused(FALSE); @@ -352,8 +344,6 @@ void ToggleQuitMenu() } else { - //Added By Sadullah Nader - //Added to compensate for the quit confirmation window pop-up TheMouse->setCursor( Mouse::ARROW ); 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 ae00310f84..1ab780e3ac 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp @@ -944,12 +944,8 @@ void finishSinglePlayerInit( void ) } - //Added By Sadullah Nader - //Fix for the black screen text that appears after loading sequence - TheInGameUI->freeMessageResources(); - // if (s_blankLayout) { s_blankLayout->destroyWindows(); 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 6c114b7bc6..d99f370cc3 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp @@ -553,8 +553,6 @@ static void startPressed(void) ///////////////////////////////////////////////////// // MapSelectorTooltip - shows tooltips for the tech buildings // and supply depots -// Added By : Sadullah Nader -///////////////////////////////////////////////////// void MapSelectorTooltip(GameWindow *window, WinInstanceData *instData, UnsignedInt mouse) @@ -885,8 +883,6 @@ void updateMapStartSpots( GameInfo *myGame, GameWindow *buttonMapStartPositions[ AsciiString displayNumber; displayNumber.format("NUMBER:%d",i + 1); GadgetButtonSetText(buttonMapStartPositions[gs->getStartPos()], TheGameText->fetch(displayNumber)); - //Added By Sadullah Nader - //Fix for no tooltips at start positions //added start position tooltip //Fixed again to show the right number , ie "i + 1" UnicodeString temp; 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 d0de9eb542..3ad3b46956 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp @@ -1173,10 +1173,7 @@ void InitWOLGameGadgets( void ) TheWindowManager->winGetWindowFromId(parentWOLGameSetup, labelID)->winEnable( FALSE ); } - //Added By Sadullah Nader - //Tooltip Function set windowMap->winSetTooltipFunc(MapSelectorTooltip); - // GameWindow *staticTextTitle = TheWindowManager->winGetWindowFromId( parentWOLGameSetup, staticTextTitleID ); if (staticTextTitle) diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindow.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindow.cpp index cb3f1a831d..49d7e6ee54 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindow.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindow.cpp @@ -1544,8 +1544,6 @@ WindowMsgHandledType GameWinBlockInput( GameWindow *window, UnsignedInt msg, if (msg == GWM_CHAR || msg == GWM_MOUSE_POS) return MSG_IGNORED; - //Added By Sadullah Nader - //Fix for drag selecting in the control bar if (msg == GWM_LEFT_UP )//|| msg == GWM_LEFT_DRAG) { //stop drag selecting diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp index f813d3048d..dfbd9e9c49 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp @@ -107,8 +107,6 @@ m_font(NULL), m_point(0), m_bold(FALSE) { - //Added By Sadullah Nader - //Initializations missing and needed m_fontName.clear(); m_name.clear(); } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp index 8ca208be05..708802b0b3 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp @@ -506,8 +506,6 @@ IMEManager::IMEManager() m_result(0), m_indexBase(1), - //Added By Sadullah Nader - //Initializations missing and needed m_compositionCharsDisplayed(0), m_candidateDownArrow(NULL), m_candidateTextArea(NULL), @@ -517,7 +515,6 @@ IMEManager::IMEManager() m_pageStart(0), m_selectedIndex(0), m_unicodeIME(FALSE) - // { } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp index c05cace94a..7a43a6b923 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp @@ -175,13 +175,10 @@ void LoadScreen::update( Int percent ) //----------------------------------------------------------------------------- SinglePlayerLoadScreen::SinglePlayerLoadScreen( void ) { - //Added By Sadullah Nader - //Initialization(s) inserted m_currentObjectiveLine = 0; m_currentObjectiveLineCharacter = 0; m_finishedObjectiveText = NULL; m_currentObjectiveWidthOffset = 0; - // m_progressBar = NULL; m_percent = NULL; m_videoStream = NULL; @@ -1225,17 +1222,11 @@ void ShellGameLoadScreen::update( Int percent ) //----------------------------------------------------------------------------- MultiPlayerLoadScreen::MultiPlayerLoadScreen( void ) { - //Added By Sadullah Nader - //Initializations missing and needed m_mapPreview = NULL; - // for(Int i = 0; i < MAX_SLOTS; ++i) { - //Added By Sadullah Nader - //Initializations missing and needed m_buttonMapStartPosition[i] = NULL; - // m_progressBars[i] = NULL; m_playerNames[i] = NULL; m_playerSide[i]= NULL; @@ -1491,19 +1482,13 @@ void MultiPlayerLoadScreen::processProgress(Int playerId, Int percentage) GameSpyLoadScreen::GameSpyLoadScreen( void ) { - // Added By Sadullah Nader - // Initializations missing and needed m_mapPreview = NULL; - // for(Int i = 0; i < MAX_SLOTS; ++i) { - // Added By Sadullah Nader - // Initializations missing and needed m_buttonMapStartPosition[i] = NULL; m_playerRank[i] = NULL; - // m_playerOfficerMedal[i] = NULL; m_progressBars[i] = NULL; @@ -1858,10 +1843,7 @@ void GameSpyLoadScreen::processProgress(Int playerId, Int percentage) //----------------------------------------------------------------------------- MapTransferLoadScreen::MapTransferLoadScreen( void ) { - //Added By Sadullah Nader - //Initializations missing and needed m_oldTimeout = 0; - // for(Int i = 0; i < MAX_SLOTS; ++i) { m_progressBars[i] = NULL; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp index 20299ecdd8..319c5cc475 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp @@ -85,11 +85,8 @@ void Shell::construct( void ) m_schemeManager = NEW ShellMenuSchemeManager; m_saveLoadMenuLayout = NULL; m_popupReplayLayout = NULL; - //Added By Sadullah Nader - //Initializations m_optionsLayout = NULL; m_screenCount = 0; - // } //------------------------------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp index a0de88a9ae..0c49c2a141 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp @@ -100,10 +100,7 @@ GameClient::GameClient() m_numTranslators = 0; m_commandTranslator = NULL; - // Added By Sadullah Nader - // Initializations missing and needed m_drawableTOC.clear(); - // m_textBearingDrawableList.clear(); m_frame = 0; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GameText.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GameText.cpp index 8df77e4708..7492768036 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GameText.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GameText.cpp @@ -258,11 +258,8 @@ GameTextManager::GameTextManager() #endif m_mapStringInfo(NULL), m_mapStringLUT(NULL), - m_failed(L"***FATAL*** String Manager failed to initilaize properly") + m_failed(L"***FATAL*** String Manager failed to initialize properly") { - // Added By Sadullah Nader - // Initializations missing and needed - for(Int i=0; i < MAX_UITEXT_LENGTH; i++) { m_buffer[i] = 0; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GlobalLanguage.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GlobalLanguage.cpp index 2b279e0c56..17c88e9480 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GlobalLanguage.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GlobalLanguage.cpp @@ -123,8 +123,6 @@ void INI::parseLanguageDefinition( INI *ini ) GlobalLanguage::GlobalLanguage() { m_unicodeFontName.clear(); - //Added By Sadullah Nader - //Initializations missing and needed m_unicodeFontFileName.clear(); m_unicodeFontName.clear(); m_militaryCaptionSpeed = 0; @@ -132,7 +130,6 @@ GlobalLanguage::GlobalLanguage() m_resolutionFontSizeAdjustment = 0.7f; m_resolutionFontSizeMethod = ResolutionFontSizeMethod_Default; m_militaryCaptionDelayMS = 750; - //End Add m_userResolutionFontSizeAdjustment = -1.0f; } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp index ac7277eda4..8bbebf42c0 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp @@ -977,8 +977,6 @@ InGameUI::InGameUI() m_mouseModeCursor = Mouse::ARROW; m_mousedOverDrawableID = INVALID_DRAWABLE_ID; - //Added By Sadullah Nader - //Initializations missing and needed m_currentlyPlayingMovie.clear(); m_militarySubtitle = NULL; m_popupMessageData = NULL; @@ -5473,14 +5471,11 @@ void InGameUI::clearPopupMessageData( void ) //------------------------------------------------------------------------------------------------- FloatingTextData::FloatingTextData(void) { - // Added By Sadullah Nader - // Initializations missing and needed m_color = 0; m_frameCount = 0; m_frameTimeOut = 0; m_pos3D.zero(); m_text.clear(); - // m_dString = TheDisplayStringManager->newDisplayString(); } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp index 27fa57927b..d7f8816f57 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp @@ -423,15 +423,12 @@ Bool Mouse::isClick(const ICoord2D *anchor, const ICoord2D *dest, UnsignedInt pr //------------------------------------------------------------------------------------------------- CursorInfo::CursorInfo( void ) { - // Added Sadullah Nader - // Initializations missing and needed cursorName.clear(); cursorText.clear(); cursorTextColor.red = cursorTextColor.green = cursorTextColor.blue = 0; cursorTextDropColor.red = cursorTextDropColor.blue = cursorTextDropColor.green = 0; - // textureName.clear(); imageName.clear(); W3DModelName.clear(); @@ -458,13 +455,9 @@ Mouse::Mouse( void ) m_numAxes = 0; m_forceFeedback = FALSE; - //Added By Sadullah Nader - //Initializations missing and needed m_dragTolerance = 0; m_dragTolerance3D = 0; m_dragToleranceMS = 0; - // - //m_tooltipString.clear(); // redundant m_displayTooltip = FALSE; m_tooltipDisplayString = NULL; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/LanguageFilter.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/LanguageFilter.cpp index 656bf74490..1631d522fe 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/LanguageFilter.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/LanguageFilter.cpp @@ -35,9 +35,6 @@ LanguageFilter *TheLanguageFilter = NULL; LanguageFilter::LanguageFilter() { - //Modified by Saad - //Unnecessary - //m_wordList.clear(); } LanguageFilter::~LanguageFilter() { diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp index 35ede1fdbf..e71399c7e8 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp @@ -113,10 +113,7 @@ GameMessageDisposition HotKeyTranslator::translateGameMessage(const GameMessage HotKey::HotKey() { m_win = NULL; - //Added By Sadullah Nader - //Initializations missing and needed m_key.clear(); - // } //----------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp index b9990857de..8d900a3636 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp @@ -142,12 +142,9 @@ LookAtTranslator::LookAtTranslator() : m_lastMouseMoveFrame(0), m_scrollType(SCROLL_NONE) { - //Added By Sadullah Nader - //Initializations missing and needed m_anchor.x = m_anchor.y = 0; m_currentPos.x = m_currentPos.y = 0; m_originalAnchor.x = m_originalAnchor.y = 0; - // OptionPreferences prefs; m_screenEdgeScrollMode = prefs.getScreenEdgeScrollMode(); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp index 2dcfe187fe..501f23d244 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp @@ -270,11 +270,8 @@ SelectionTranslator::SelectionTranslator() m_deselectFeedbackAnchor.x = 0; m_deselectFeedbackAnchor.y = 0; m_lastClick = 0; - //Added By Sadullah Nader - //Initializtion(s) inserted m_deselectDownCameraPosition.zero(); m_displayedMaxWarning = FALSE; - // m_selectCountMap.clear(); TheSelectionTranslator = this; @@ -1338,8 +1335,6 @@ GameMessageDisposition SelectionTranslator::translateGameMessage(const GameMessa } -//Added By Sadullah Nader - //setDragSelecting(Bool dragSelect) //Added to fix the drag selection problem in control bar //////////////////////////////////////////////////////////////////////// diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/RadiusDecal.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/RadiusDecal.cpp index e6558f637b..0bc882eae4 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/RadiusDecal.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/RadiusDecal.cpp @@ -45,7 +45,7 @@ RadiusDecalTemplate::RadiusDecalTemplate() : m_opacityThrobTime(LOGICFRAMES_PER_SECOND), m_color(0), m_onlyVisibleToOwningPlayer(true), - m_name(AsciiString::TheEmptyString) // Added By Sadullah Nader for Init purposes + m_name(AsciiString::TheEmptyString) { } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/Anim2D.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/Anim2D.cpp index 9ec84290db..cabff15a15 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/Anim2D.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/Anim2D.cpp @@ -295,17 +295,11 @@ const Image* Anim2DTemplate::getFrame( UnsignedShort frameNumber ) const // ------------------------------------------------------------------------------------------------ Anim2D::Anim2D( Anim2DTemplate *animTemplate, Anim2DCollection *collectionSystem ) { - // sanity DEBUG_ASSERTCRASH( animTemplate != NULL, ("Anim2D::Anim2D - NULL template") ); - //Added By Sadullah Nader - //Initialization - m_currentFrame = 0; - // - // set the template m_template = animTemplate; @@ -323,8 +317,6 @@ Anim2D::Anim2D( Anim2DTemplate *animTemplate, Anim2DCollection *collectionSystem m_maxFrame = m_template->getNumFrames() - 1; m_framesBetweenUpdates = m_template->getNumFramesBetweenUpdates(); - //added by Sadullah Nader - // initializing pointers to NULL, and clearing Frame counters before // we register ourselves to the System m_collectionSystemNext = NULL; m_collectionSystemPrev = NULL; @@ -335,8 +327,6 @@ Anim2D::Anim2D( Anim2DTemplate *animTemplate, Anim2DCollection *collectionSystem m_collectionSystem = collectionSystem; if( m_collectionSystem ) m_collectionSystem->registerAnimation( this ); - - } // ------------------------------------------------------------------------------------------------ diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp index 4d413443d1..03d7c5448a 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp @@ -68,8 +68,6 @@ ParticleSystemManager *TheParticleSystemManager = NULL; // ------------------------------------------------------------------------------------------------ ParticleInfo::ParticleInfo( void ) { - //Added By Sadullah Nader - //Initializations inserted m_angleZ = 0.0f; m_angularDamping = 0.0f; m_angularRateZ = 0.0f; @@ -87,7 +85,6 @@ ParticleInfo::ParticleInfo( void ) m_lifetime = 0; m_particleUpTowardsEmitter = FALSE; - // } // ------------------------------------------------------------------------------------------------ @@ -262,10 +259,7 @@ Particle::Particle( ParticleSystem *system, const ParticleInfo *info ) m_angleZ = info->m_angleZ; - //Added By Sadullah Nader - //Initializations inserted m_lastPos.zero(); - // m_windRandomness = info->m_windRandomness; m_particleUpTowardsEmitter = info->m_particleUpTowardsEmitter; m_emitterPos = info->m_emitterPos; @@ -728,8 +722,6 @@ ParticleSystemInfo::ParticleSystemInfo() m_isEmitAboveGroundOnly = false; m_isParticleUpTowardsEmitter = false; - //Added By Sadullah Nader - //Initializations inserted m_driftVelocity.zero(); m_gravity = 0.0f; m_isEmissionVolumeHollow = FALSE; @@ -737,7 +729,6 @@ ParticleSystemInfo::ParticleSystemInfo() m_slavePosOffset.zero(); m_systemLifetime = 0; - // // some default values for the wind motion values m_windMotion = WIND_MOTION_NOT_USED; m_windAngle = 0.0f; @@ -1038,12 +1029,9 @@ ParticleSystem::ParticleSystem( const ParticleSystemTemplate *sysTemplate, m_template = sysTemplate; m_systemID = id; - //Added By Sadullah Nader - //Initializations inserted m_lastPos.zero(); m_pos.zero(); m_velCoeff.zero(); - // m_attachedToDrawableID = INVALID_DRAWABLE_ID; m_attachedToObjectID = INVALID_ID; @@ -2783,10 +2771,7 @@ void ParticleSystemTemplate::parseRandomRGBColor( INI* ini, void *instance, ParticleSystemTemplate::ParticleSystemTemplate( const AsciiString &name ) : m_name(name) { - //Added By Sadullah Nader - //Initializations inserted m_slaveTemplate = NULL; - // } // ------------------------------------------------------------------------------------------------ @@ -2827,13 +2812,10 @@ ParticleSystemManager::ParticleSystemManager( void ) m_onScreenParticleCount = 0; m_localPlayerIndex = 0; - //Added By Sadullah Nader - //Initializations inserted m_lastLogicFrameUpdate = 0; m_particleCount = 0; m_fieldParticleCount = 0; m_particleSystemCount = 0; - // for( Int i = 0; i < NUM_PARTICLE_PRIORITIES; ++i ) { diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp index cd079dc035..fa9ad40747 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp @@ -941,8 +941,6 @@ m_infantryPathfindDiameter(6), m_vehiclePathfindDiameter(6), m_supplyCenterSafeRadius(250), m_rebuildDelaySeconds(10), -//Added By Sadullah Nader -//Initialization(s) inserted m_distanceRequiresGroup(0.0f), m_sideBuildLists(NULL), m_structuresPoorMod(0.0f), @@ -951,7 +949,6 @@ m_aiDozerBoredRadiusModifier(2.0), m_aiCrushesInfantry(true), m_maxRetaliateDistance(210.0f), m_retaliateFriendsRadius(120.0f) -// { } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp index 6d1aef8e23..e1b50033c2 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp @@ -3029,15 +3029,12 @@ zoneStorageType PathfindZoneManager::getEffectiveZone( LocomotorSurfaceTypeMask } //-------------------- PathfindLayer ---------------------------------------- PathfindLayer::PathfindLayer() : m_blockOfMapCells(NULL), m_layerCells(NULL), m_bridge(NULL), -// Added By Sadullah Nader -// Initializations inserted m_destroyed(FALSE), m_height(0), m_width(0), m_xOrigin(0), m_yOrigin(0), m_zone(0) -// { m_startCell.x = -1; m_startCell.y = -1; @@ -5267,7 +5264,6 @@ Bool Pathfinder::adjustToPossibleDestination(Object *obj, const LocomotorSet& lo return false; } - // Int zone1, zone2; Bool isCrusher = obj ? obj->getCrusherLevel() > 0 : false; zone1 = m_zoneManager.getEffectiveZone(locomotorSet.getValidSurfaces(), isCrusher, parentCell->getZone()); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/TurretAI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/TurretAI.cpp index 645b4edb7b..073f5b4fd0 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/TurretAI.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/TurretAI.cpp @@ -280,15 +280,9 @@ TurretAI::TurretAI(Object* owner, const TurretAIData* data, WhichTurretType tur) m_enabled(!data->m_initiallyDisabled), m_firesWhileTurning(data->m_firesWhileTurning), m_isForceAttacking(false), - //Added By Sadullah Nader - //Initialization(s) inserted m_victimInitialTeam(NULL) - // { - //Added By Sadullah Nader - //Initialization(s) inserted m_continuousFireExpirationFrame = -1; - // if (!m_data) { DEBUG_CRASH(("TurretAI MUST have ModuleData")); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cpp index 6fbc415e91..6059e774ea 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cpp @@ -50,11 +50,8 @@ m_exportWithScripts(false), m_isWaterArea(false), m_shouldRender(true), m_selected(false), -//Added By Sadullah Nader -//Initializations inserted m_isRiver(FALSE), m_riverStart(0) -// { if (initialAllocation < 2) initialAllocation = 2; m_points = NEW ICoord3D[initialAllocation]; // pool[]ify diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/SidesList.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/SidesList.cpp index b3ffc1c6ca..4824fa87b9 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/SidesList.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/SidesList.cpp @@ -927,8 +927,6 @@ m_automaticallyBuild(true), m_priorityBuild(false), m_buildingName(AsciiString::TheEmptyString) { - // Added by Sadullah Nader - // these initialized values are necessary!!! m_location.zero(); m_rallyPointOffset.x = 0.0f; m_rallyPointOffset.y = 0.0f; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp index 5f4fba3f77..6af3e05b1b 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp @@ -959,11 +959,8 @@ TerrainLogic::TerrainLogic() { Int i; - //Added By Sadullah Nader - //Initialization(s) inserted m_activeBoundary = 0; m_waterGridEnabled = FALSE; - // for( i = 0; i < MAX_DYNAMIC_WATER; ++i ) { diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cpp index bf626b9f38..ed1cfc4137 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cpp @@ -51,14 +51,7 @@ ParkingPlaceBehavior::ParkingPlaceBehavior( Thing *thing, const ModuleData* moduleData ) : UpdateModule( thing, moduleData ) { m_gotInfo = false; - - //Added By Sadullah Nader - //Initializations - m_heliRallyPoint.zero(); - - // - m_heliRallyPointExists = FALSE; m_nextHealFrame = FOREVER; setWakeFrame(getObject(), UPDATE_SLEEP_NONE); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/PropagandaTowerBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/PropagandaTowerBehavior.cpp index 67281f1612..0283d17197 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/PropagandaTowerBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/PropagandaTowerBehavior.cpp @@ -121,10 +121,7 @@ PropagandaTowerBehaviorModuleData::PropagandaTowerBehaviorModuleData( void ) PropagandaTowerBehavior::PropagandaTowerBehavior( Thing *thing, const ModuleData *modData ) : UpdateModule( thing, modData ) { - //Added By Sadullah Nader - //Initializations inserted m_lastScanFrame = 0; - // m_insideList = NULL; setWakeFrame( getObject(), UPDATE_SLEEP_NONE ); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp index b343f4c053..b645f454b1 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp @@ -68,10 +68,7 @@ SpawnBehavior::SpawnBehavior( Thing *thing, const ModuleData* moduleData ) //looping back to the beginning m_framesToWait = 0; - //Added By Sadullah Nader - //Initialization(s) inserted m_firstBatchCount = 0; - // if( md->m_isOneShotData ) m_oneShotCountdown = md->m_spawnNumberData; else 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 7b05a6d1ec..6e4cbf8d39 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cpp @@ -55,13 +55,7 @@ CrateCollideModuleData::CrateCollideModuleData() m_isHumanOnlyPickup = FALSE; m_executeFX = NULL; m_pickupScience = SCIENCE_INVALID; - - // Added By Sadullah Nader - // Initializations missing and needed - m_executionAnimationTemplate = AsciiString::TheEmptyString; - - // End Add } //------------------------------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp index 8e42cbc9f7..44c7af5f3c 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp @@ -131,11 +131,8 @@ OpenContain::OpenContain( Thing *thing, const ModuleData* moduleData ) : UpdateM m_stealthUnitsContained = 0; m_doorCloseCountdown = 0; - //Added By Sadullah Nader - //Initializations inserted m_rallyPoint.zero(); m_rallyPointExists = FALSE; - // m_conditionState.clear(); m_firePointStart = -1; m_firePointNext = 0; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/ParachuteContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/ParachuteContain.cpp index cb826a3be9..f7dbe00973 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/ParachuteContain.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/ParachuteContain.cpp @@ -100,8 +100,6 @@ ParachuteContain::ParachuteContain( Thing *thing, const ModuleData *moduleData ) m_isLandingOverrideSet = FALSE; m_startZ = NO_START_Z; - //Added By Sadullah Nader - //Initializations m_landingOverride.zero(); m_paraAttachBone.zero(); m_paraAttachOffset.zero(); @@ -112,7 +110,6 @@ ParachuteContain::ParachuteContain( Thing *thing, const ModuleData *moduleData ) m_riderSwayBone.zero(); m_riderSwayOffset.zero(); - // const ParachuteContainModuleData* d = getParachuteContainModuleData(); if (d) { diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp index 776a5b0e50..d589e30d33 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp @@ -43,7 +43,7 @@ ExperienceTracker::ExperienceTracker(Object *parent) : m_currentLevel(LEVEL_REGULAR), m_experienceSink(INVALID_ID), m_experienceScalar( 1.0f ), - m_currentExperience(0) // Added By Sadullah Nader + m_currentExperience(0) { } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/GhostObject.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/GhostObject.cpp index b5e8f177f3..7c8dd524d6 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/GhostObject.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/GhostObject.cpp @@ -39,8 +39,6 @@ GhostObjectManager *TheGhostObjectManager = NULL; //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- GhostObject::GhostObject(void): -//Added By Sadullah Nader -//Initializations missing and needed m_parentAngle(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. diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Locomotor.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Locomotor.cpp index ab92ee7307..9b2a9bba46 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Locomotor.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Locomotor.cpp @@ -672,13 +672,8 @@ Locomotor::Locomotor(const LocomotorTemplate* tmpl) //------------------------------------------------------------------------------------------------- Locomotor::Locomotor(const Locomotor& that) { - //Added By Sadullah Nader - //Initializations m_angleOffset = 0.0f; m_maintainPos.zero(); - - // - m_template = that.m_template; m_brakingFactor = that.m_brakingFactor; m_maxLift = that.m_maxLift; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp index 45a31a7f43..598e266bea 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp @@ -232,11 +232,8 @@ Object::Object( const ThingTemplate *tt, const ObjectStatusMaskType &objectStatu Int i, modIdx; AsciiString modName; - //Added By Sadullah Nader - //Initializations inserted m_formationOffset.x = m_formationOffset.y = 0.0f; m_iPos.zero(); - // for (i = 0; i < MAX_PLAYER_COUNT; ++i) { m_visionSpiedBy[i] = 0; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp index 3e6d515983..78847445fc 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp @@ -256,15 +256,9 @@ class DeliverPayloadNugget : public ObjectCreationNugget m_convergenceFactor( 0.0f ) { //Note: m_data is constructed with default values. - - // Added by Sadullah Nader - // Initialization missing and needed - m_payload.clear(); m_putInContainerName.clear(); m_transportName.clear(); - - // End Add } virtual Object* create(const Object *primaryObj, const Coord3D *primary, const Coord3D *secondary, Real angle, UnsignedInt lifetimeFrames = 0 ) const @@ -764,9 +758,9 @@ class GenericObjectCreationNugget : public ObjectCreationNugget m_fadeIn(false), m_fadeOut(false), m_fadeFrames(0), - m_fadeSoundName(AsciiString::TheEmptyString), // Added By Sadullah Nader - m_particleSysName(AsciiString::TheEmptyString), // Added By Sadullah Nader - m_putInContainer(AsciiString::TheEmptyString), // Added By Sadullah Nader + m_fadeSoundName(AsciiString::TheEmptyString), + m_particleSysName(AsciiString::TheEmptyString), + m_putInContainer(AsciiString::TheEmptyString), m_minMag(0.0f), m_maxMag(0.0f), m_minPitch(0.0f), @@ -776,10 +770,8 @@ class GenericObjectCreationNugget : public ObjectCreationNugget m_shadowType(SHADOW_NONE), m_fxFinal(NULL), m_preserveLayer(true), - m_objectCount(0) // Added By Sadullah Nader + m_objectCount(0) { - // Change Made by Sadullah Nader - // for init purposes, easier to read m_offset.zero(); } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp index 4c7ace116a..4eb90530ce 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp @@ -1225,10 +1225,7 @@ void CellAndObjectIntersection::removeAllCoverage() //----------------------------------------------------------------------------- PartitionCell::PartitionCell() { - //Added By Sadullah Nader - //Initializations inserted m_cellX = m_cellY = 0; - // m_firstCoiInCell = NULL; m_coiCount = 0; #ifdef PM_CACHE_TERRAIN_HEIGHT diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp index 2200bfd823..797879498b 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp @@ -2774,7 +2774,6 @@ void AIUpdateInterface::aiDoCommand(const AICommandParms* parms) { state->clear(); } - //end privateGuardPosition(&parms->m_pos, (GuardMode)parms->m_intValue, parms->m_cmdSource); break; @@ -2790,7 +2789,6 @@ void AIUpdateInterface::aiDoCommand(const AICommandParms* parms) { state->clear(); } - //end privateGuardObject(parms->m_obj, (GuardMode)parms->m_intValue, parms->m_cmdSource); break; @@ -2806,7 +2804,6 @@ void AIUpdateInterface::aiDoCommand(const AICommandParms* parms) { state->clear(); } - //end privateGuardTunnelNetwork((GuardMode)parms->m_intValue, parms->m_cmdSource); break; @@ -2822,7 +2819,6 @@ void AIUpdateInterface::aiDoCommand(const AICommandParms* parms) { state->clear(); } - //end privateGuardArea(parms->m_polygon, (GuardMode)parms->m_intValue, parms->m_cmdSource); break; 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 ed8a8937a7..63cf5c78cb 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeliverPayloadAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeliverPayloadAIUpdate.cpp @@ -116,23 +116,15 @@ DeliverPayloadAIUpdate::DeliverPayloadAIUpdate( Thing *thing, const ModuleData* m_visibleItemsDelivered = 0; m_deliveryDecal.clear(); m_previousDistanceSqr = 0; - m_freeToExit = FALSE; m_acceptingCommands = TRUE; - - // Added By Sadullah Nader - // Initialization missing and needed - m_diveState = DIVESTATE_PREDIVE; - - // End Add } //------------------------------------------------------------------------------------------------- DeliverPayloadAIUpdate::~DeliverPayloadAIUpdate( void ) { m_deliveryDecal.clear(); - deleteInstance(m_deliverPayloadStateMachine); } 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 1bebdbe441..e901fd9df8 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp @@ -384,8 +384,6 @@ class DozerActionDoActionState : public State DozerActionDoActionState( StateMachine *machine, DozerTask task ) : State( machine, "DozerActionDoActionState" ) { m_task = task; - //Added By Sadullah Nader - // Initializations missing and needed m_enterFrame = 0; } virtual StateReturnType update( void ); 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 cac797bc77..4e3b24a426 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp @@ -1857,10 +1857,7 @@ JetAIUpdate::JetAIUpdate( Thing *thing, const ModuleData* moduleData ) : AIUpdat m_lockonDrawable = NULL; m_landingPosForHelipadStuff.zero(); - //Added By Sadullah Nader - //Initializations missing and needed m_producerLocation.zero(); - // m_enginesOn = TRUE; } 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 a3bdd0628a..f36a83f720 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp @@ -87,12 +87,7 @@ WorkerAIUpdate::WorkerAIUpdate( Thing *thing, const ModuleData* moduleData ) : // // initialize the dozer machine to NULL, we want to do this and create it during the update // implementation because at this point we don't have the object all setup - // - - //Added By Sadullah Nader - //Initialization(s) inserted m_isRebuild = FALSE; - // m_dozerMachine = NULL; for( Int i = 0; i < DOZER_NUM_TASKS; i++ ) { diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/BattlePlanUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/BattlePlanUpdate.cpp index d97f23d63d..2cf23405c6 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/BattlePlanUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/BattlePlanUpdate.cpp @@ -155,12 +155,7 @@ BattlePlanUpdate::BattlePlanUpdate( Thing *thing, const ModuleData* moduleData ) m_visionObjectID = INVALID_ID; - //------------------------// - // Added by Sadullah Nader// - //------------------------// - m_specialPowerModule = NULL; - // } //------------------------------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/BoneFXUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/BoneFXUpdate.cpp index e6c315e6e2..d2bd3ef3d1 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/BoneFXUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/BoneFXUpdate.cpp @@ -91,7 +91,6 @@ BoneFXUpdate::BoneFXUpdate( Thing *thing, const ModuleData* moduleData ) : Updat m_particleSystemIDs.clear(); m_active = FALSE; - //Added By Sadullah Nader m_curBodyState = BODY_PRISTINE; } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FlammableUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FlammableUpdate.cpp index 06387187ef..a665abaaa4 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FlammableUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FlammableUpdate.cpp @@ -47,10 +47,7 @@ FlammableUpdateModuleData::FlammableUpdateModuleData() m_aflameDuration = 0; m_aflameDamageDelay = 0; m_aflameDamageAmount = 0; - // Enabled By Sadullah Nader - // Initialization needed m_burningSoundName.clear(); - // m_flameDamageLimitData = 20.0f; m_flameDamageExpirationDelay = LOGICFRAMES_PER_SECOND * 2; } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp index f7bdf06e20..03b7d9ed59 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp @@ -61,13 +61,10 @@ //------------------------------------------------------------------------------------------------- HelicopterSlowDeathBehaviorModuleData::HelicopterSlowDeathBehaviorModuleData( void ) { - //Added By Sadullah Nader - //Initializations missing and needed m_attachParticleBone.clear(); m_bladeBone.clear(); m_bladeObjectName.clear(); m_finalRubbleObject.clear(); - // m_spiralOrbitTurnRate = 0.0f; m_spiralOrbitForwardSpeed = 0.0f; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cpp index 8198bf0039..aac30b83c4 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cpp @@ -157,10 +157,7 @@ HordeUpdate::HordeUpdate( Thing *thing, const ModuleData* moduleData ) : UpdateM m_inHorde = FALSE; m_hasFlag = FALSE; m_lastHordeRefreshFrame = TheGameLogic->getFrame(); - // Added By Sadullah Nader - // Initializations missing and needed m_trueHordeMember = FALSE; - // UnsignedInt delay = getHordeUpdateModuleData()->m_updateRate; setWakeFrame(getObject(), UPDATE_SLEEP(GameLogicRandomValue(1, delay))); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/LaserUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/LaserUpdate.cpp index a4e85305f7..60d0baf30e 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/LaserUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/LaserUpdate.cpp @@ -85,12 +85,9 @@ LaserRadiusUpdate::LaserRadiusUpdate() //------------------------------------------------------------------------------------------------- LaserUpdate::LaserUpdate( Thing *thing, const ModuleData* moduleData ) : ClientUpdateModule( thing, moduleData ) { - //Added By Sadullah Nader - //Initialization missing and needed m_dirty = FALSE; m_endPos.zero(); m_startPos.zero(); - // m_particleSystemID = INVALID_PARTICLE_SYSTEM_ID; m_targetParticleSystemID = INVALID_PARTICLE_SYSTEM_ID; m_parentID = INVALID_DRAWABLE_ID; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/LifetimeUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/LifetimeUpdate.cpp index 976dbaab38..974d94bc21 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/LifetimeUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/LifetimeUpdate.cpp @@ -42,10 +42,7 @@ LifetimeUpdate::LifetimeUpdate( Thing *thing, const ModuleData* moduleData ) : UpdateModule( thing, moduleData ) { const LifetimeUpdateModuleData* d = getLifetimeUpdateModuleData(); - // Added By Sadullah Nader - // Initializations needed m_dieFrame = 0; - // UnsignedInt delay; if( getObject()->isKindOf( KINDOF_HULK ) && TheGameLogic->getHulkMaxLifetimeOverride() != -1 ) { diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cpp index 514f6b1691..d2d1d07928 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cpp @@ -86,11 +86,8 @@ ParticleUplinkCannonUpdateModuleData::ParticleUplinkCannonUpdateModuleData() m_manualDrivingSpeed = 0.0f; m_manualFastDrivingSpeed = 0.0f; m_doubleClickToFastDriveDelay = 500; - //Added by Sadullah Nader - //Initializations inserted m_swathOfDeathAmplitude = 0.0f; m_swathOfDeathDistance = 0.0f; - // } //------------------------------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionExitUpdate/DefaultProductionExitUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionExitUpdate/DefaultProductionExitUpdate.cpp index 8166c4b44d..b6b360bae8 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionExitUpdate/DefaultProductionExitUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionExitUpdate/DefaultProductionExitUpdate.cpp @@ -46,13 +46,7 @@ DefaultProductionExitUpdate::DefaultProductionExitUpdate( Thing *thing, const Mo { // no rally point has been set m_rallyPointExists = false; - // Added By Sadullah Nader - // Initialization missing and needed - m_rallyPoint.zero(); - - // - setWakeFrame(getObject(), UPDATE_SLEEP_FOREVER); } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionExitUpdate/QueueProductionExitUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionExitUpdate/QueueProductionExitUpdate.cpp index 68ef05211f..f7748360ca 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionExitUpdate/QueueProductionExitUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionExitUpdate/QueueProductionExitUpdate.cpp @@ -46,12 +46,8 @@ QueueProductionExitUpdate::QueueProductionExitUpdate( Thing *thing, const Module { m_currentDelay = 0; - //Added By Sadullah Nader - //Initializations inserted m_creationClearDistance = 0; m_rallyPoint.zero(); - // - // no rally point has been set m_rallyPointExists = false; m_currentBurstCount = 0; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cpp index 1f701859da..9eb841a70b 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cpp @@ -158,11 +158,8 @@ ProductionEntry::ProductionEntry( void ) m_framesUnderConstruction = 0; m_next = NULL; m_prev = NULL; - //Added By Sadullah Nader - //Initializations inserted m_productionQuantityProduced = 0; m_productionQuantityTotal = 0; - // } //------------------------------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp index d4b872f2fe..0d87c22f89 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp @@ -69,10 +69,7 @@ //------------------------------------------------------------------------------------------------- SpecialAbilityUpdate::SpecialAbilityUpdate( Thing *thing, const ModuleData* moduleData ) : SpecialPowerUpdateModule( thing, moduleData ) { - //Added By Sadullah Nader - //Initialization(s) inserted m_captureFlashPhase = 0.0f; - // m_active = false; m_prepFrames = 0; m_animFrames = 0; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp index 5c20cbfadc..a390bc943f 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp @@ -64,11 +64,8 @@ StealthUpdateModuleData::StealthUpdateModuleData() { - //Added By Sadullah Nader - //Initialization(s) inserted m_disguiseFX = NULL; m_disguiseRevealFX = NULL; - // m_stealthDelay = UINT_MAX; m_stealthLevel = 0; m_stealthSpeed = 0.0f; @@ -133,10 +130,7 @@ StealthUpdate::StealthUpdate( Thing *thing, const ModuleData* moduleData ) : Upd //Must be enabled manually if using disguise system (bomb truck uses) m_enabled = !data->m_teamDisguised; - //Added By Sadullah Nader - //Initialization(s) inserted m_detectionExpiresFrame = 0; - // m_pulsePhaseRate = 0.2f; m_pulsePhase = GameClientRandomValueReal(0, PI); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StickyBombUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StickyBombUpdate.cpp index 25e3803878..a94c348d04 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StickyBombUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StickyBombUpdate.cpp @@ -56,10 +56,7 @@ StickyBombUpdate::StickyBombUpdate( Thing *thing, const ModuleData *moduleData ) { m_targetID = INVALID_ID; m_dieFrame = 0; - //Added By Sadullah Nader - //Initialization(s) inserted m_nextPingFrame = 0; - // setWakeFrame(getObject(), UPDATE_SLEEP_FOREVER); } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StructureCollapseUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StructureCollapseUpdate.cpp index 7ac2a0dab1..11128be257 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StructureCollapseUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StructureCollapseUpdate.cpp @@ -68,11 +68,8 @@ StructureCollapseUpdate::StructureCollapseUpdate( Thing *thing, const ModuleData m_collapseFrame = 0; m_collapseState = COLLAPSESTATE_STANDING; m_collapseVelocity = 0.0f; - //Added By Sadullah Nader - //Initialization(s) inserted m_burstFrame = 0; m_currentHeight = 0.0f; - // setWakeFrame(getObject(), UPDATE_SLEEP_FOREVER); } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StructureToppleUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StructureToppleUpdate.cpp index dd25b7ecee..005fa4a8af 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StructureToppleUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StructureToppleUpdate.cpp @@ -55,13 +55,9 @@ const Int MAX_IDX = 32; //------------------------------------------------------------------------------------------------- StructureToppleUpdate::StructureToppleUpdate( Thing *thing, const ModuleData* moduleData ) : UpdateModule( thing, moduleData ) { - - //Added By Sadullah Nader - //Initialization(s) inserted m_delayBurstLocation.zero(); m_structuralIntegrity = 0.0f; m_toppleDirection.x = m_toppleDirection.y = 0; - // m_toppleFrame = 0; m_toppleState = TOPPLESTATE_STANDING; m_toppleVelocity = 0.0f; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ToppleUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ToppleUpdate.cpp index 950734fc4b..7af9b83cfc 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ToppleUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ToppleUpdate.cpp @@ -104,12 +104,9 @@ void ToppleUpdateModuleData::buildFieldParse(MultiIniFieldParse& p) //------------------------------------------------------------------------------------------------- ToppleUpdate::ToppleUpdate( Thing *thing, const ModuleData* moduleData ) : UpdateModule( thing, moduleData ) { - //Added By Sadullah Nader - //Initialization(s) inserted m_angleDeltaX = 0.0f; m_doBounceFX = FALSE; m_numAngleDeltaX = 0; - // m_angularVelocity = 0; m_angularAccumulation = 0; m_angularAcceleration = 0; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/WaveGuideUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/WaveGuideUpdate.cpp index 4a83ab7504..a628657312 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/WaveGuideUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/WaveGuideUpdate.cpp @@ -58,12 +58,9 @@ // ------------------------------------------------------------------------------------------------ WaveGuideUpdateModuleData::WaveGuideUpdateModuleData( void ) { - //Added By Sadullah Nader - //Initialization(s) inserted m_bridgeParticleAngleFudge = 0.0f; m_randomSplashSoundFrequency = 0; m_waveDelay = 0.0f; - // m_ySize = 0.0f; m_linearWaveSpacing = 0.0f; m_waveBendMagnitude = 0.0f; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp index 0f18c6f7b6..41b35abe0b 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp @@ -445,8 +445,6 @@ m_skirmishHumanPlayer(NULL), m_fade(FADE_NONE), m_freezeByScript(FALSE), m_frameObjectCountChanged(0), -//Added By Sadullah Nader -//Initializations inserted m_closeWindowTimer(0), m_curFadeFrame(0), m_curFadeValue(0.0f), @@ -461,7 +459,6 @@ m_numAttackInfo(0), m_shownMPLocalDefeatWindow(FALSE), m_objectsShouldReceiveDifficultyBonus(TRUE), m_ChooseVictimAlwaysUsesNormal(false) -// { st_CanAppCont = true; st_LastCurrentFrame = st_CurrentFrame = 0; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp index d9fd016690..31b589c905 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp @@ -635,10 +635,7 @@ m_firstScript(NULL), m_hasWarnings(false), m_isGroupActive(true), m_isGroupSubroutine(false), -//Added By Sadullah Nader -//Initializations inserted m_nextGroup(NULL) -// { m_groupName.format("Script Group %d", ScriptList::getNextID()); } @@ -914,11 +911,8 @@ m_hasWarnings(false), m_nextScript(NULL), m_condition(NULL), m_action(NULL), -//Added By Sadullah Nader -//Initializations inserted m_actionFalse(NULL), m_curTime(0.0f) -// { } @@ -2247,10 +2241,7 @@ ScriptAction::ScriptAction(): m_actionType(NO_OP), m_hasWarnings(false), m_numParms(0), -//Added By Sadullah Nader -//Initializations inserted m_nextAction(NULL) -// { } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp index a1d704c3be..b72cec84e1 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp @@ -218,8 +218,6 @@ void setFPMode( void ) // ------------------------------------------------------------------------------------------------ GameLogic::GameLogic( void ) { - //Added By Sadullah Nader - //Initializations missing and necessary m_background = NULL; m_CRC = 0; m_isInUpdate = FALSE; @@ -235,7 +233,6 @@ GameLogic::GameLogic( void ) m_shouldValidateCRCs = FALSE; m_startNewGame = FALSE; - // m_frame = 0; m_hasUpdated = FALSE; @@ -1319,7 +1316,6 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) TheMouse->setVisibility(FALSE); m_loadScreen->init(game); - // updateLoadProgress( LOAD_PROGRESS_START ); } } @@ -2396,8 +2392,6 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) } } - //Added By Sadullah Nader - //Added to fix the quit menu //ReAllows quit menu to work during loading scene //setGameLoading(FALSE); setLoadingMap( FALSE ); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp index 814fd70de7..23d726911a 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp @@ -306,9 +306,6 @@ void GameLogic::clearGameData( Bool showScoreScreen ) // ------------------------------------------------------------------------------------------------ void GameLogic::prepareNewGame( GameMode gameMode, GameDifficulty diff, Int rankPoints ) { - //Added By Sadullah Nader - //Fix for loading game scene - //Kris: Commented this out, but leaving it around incase it bites us later. I cleaned up the // nomenclature. Look for setLoadingMap() and setLoadingSave() //setGameLoading(TRUE); diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DProgressBar.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DProgressBar.cpp index 22ed2957ee..23099a7226 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DProgressBar.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DProgressBar.cpp @@ -401,7 +401,6 @@ void W3DGadgetProgressBarImageDraw( GameWindow *window, WinInstanceData *instDat } start.x = origin.x + 10 + barCenter->getImageWidth() * pieces; //pieces = (size.x - barWindowSize.x -20) / barRight->getImageWidth(); - //Changed By Saad for flashing grey piece pieces = ((size.x - 20) / barCenter->getImageWidth()) - pieces; for( i = 0; i < pieces; i++ ) { From 2a1f9630b178cc0f5666c865ee9d05de312a19b1 Mon Sep 17 00:00:00 2001 From: Bobby Battista Date: Sun, 30 Nov 2025 14:29:06 -0500 Subject: [PATCH 06/70] bugfix(filesystem): Prevent loading wrong INIZH.big from Data/INI directory to prevent INI CRC mismatch (#1879) --- .../Source/StdDevice/Common/StdBIGFileSystem.cpp | 10 ++++++++++ .../Source/Win32Device/Common/Win32BIGFileSystem.cpp | 10 ++++++++++ .../Code/GameEngine/Source/Common/GameEngine.cpp | 6 ------ 3 files changed, 20 insertions(+), 6 deletions(-) diff --git a/Core/GameEngineDevice/Source/StdDevice/Common/StdBIGFileSystem.cpp b/Core/GameEngineDevice/Source/StdDevice/Common/StdBIGFileSystem.cpp index bfd2bd094d..079f00a307 100644 --- a/Core/GameEngineDevice/Source/StdDevice/Common/StdBIGFileSystem.cpp +++ b/Core/GameEngineDevice/Source/StdDevice/Common/StdBIGFileSystem.cpp @@ -215,6 +215,16 @@ Bool StdBIGFileSystem::loadBigFilesFromDirectory(AsciiString dir, AsciiString fi Bool actuallyAdded = FALSE; FilenameListIter it = filenameList.begin(); while (it != filenameList.end()) { +#if RTS_ZEROHOUR + // TheSuperHackers @bugfix bobtista 18/11/2025 Skip duplicate INIZH.big in Data\INI to prevent CRC mismatches. + // English, Chinese, and Korean SKUs shipped with two INIZH.big files (one in Run directory, one in Run\Data\INI). + // The DeleteFile cleanup doesn't work on EA App/Origin installs because the folder is not writable, so we skip loading it instead. + if (it->endsWithNoCase("Data\\INI\\INIZH.big") || it->endsWithNoCase("Data/INI/INIZH.big")) { + it++; + continue; + } +#endif + ArchiveFile *archiveFile = openArchiveFile((*it).str()); if (archiveFile != NULL) { diff --git a/Core/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp b/Core/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp index 27491ab758..8ced8a7b36 100644 --- a/Core/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp +++ b/Core/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp @@ -216,6 +216,16 @@ Bool Win32BIGFileSystem::loadBigFilesFromDirectory(AsciiString dir, AsciiString Bool actuallyAdded = FALSE; FilenameListIter it = filenameList.begin(); while (it != filenameList.end()) { +#if RTS_ZEROHOUR + // TheSuperHackers @bugfix bobtista 18/11/2025 Skip duplicate INIZH.big in Data\INI to prevent CRC mismatches. + // English, Chinese, and Korean SKUs shipped with two INIZH.big files (one in Run directory, one in Run\Data\INI). + // The DeleteFile cleanup doesn't work on EA App/Origin installs because the folder is not writable, so we skip loading it instead. + if (it->endsWithNoCase("Data\\INI\\INIZH.big") || it->endsWithNoCase("Data/INI/INIZH.big")) { + it++; + continue; + } +#endif + ArchiveFile *archiveFile = openArchiveFile((*it).str()); if (archiveFile != NULL) { diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp index 186b54ac33..3c183794f8 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp @@ -395,12 +395,6 @@ void GameEngine::init() // Create the low-level file system interface TheFileSystem = createFileSystem(); - //Kris: Patch 1.01 - November 17, 2003 - //I was unable to resolve the RTPatch method of deleting a shipped file. English, Chinese, and Korean - //SKU's shipped with two INIZH.big files. One properly in the Run directory and the other in Run\INI\Data. - //We need to toast the latter in order for the game to patch properly. - DeleteFile( "Data\\INI\\INIZH.big" ); - // not part of the subsystem list, because it should normally never be reset! TheNameKeyGenerator = MSGNEW("GameEngineSubsystem") NameKeyGenerator; TheNameKeyGenerator->init(); From 0410990457c9629481f793b8be053a9620eed035 Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Sun, 30 Nov 2025 20:30:17 +0100 Subject: [PATCH 07/70] refactor: Remove all explicit UnicodeString instantiations from C strings (#1928) --- Core/GameEngine/Source/Common/CRCDebug.cpp | 2 +- .../Source/Common/System/UnicodeString.cpp | 2 +- .../Source/GameNetwork/ConnectionManager.cpp | 8 ++--- .../Source/GameNetwork/GameSpy/LobbyUtils.cpp | 8 ++--- Core/GameEngine/Source/GameNetwork/LANAPI.cpp | 6 ++-- .../Source/GameNetwork/LANAPICallbacks.cpp | 6 ++-- .../Code/GameEngine/Source/Common/version.cpp | 2 +- .../GameClient/GUI/ControlBar/ControlBar.cpp | 4 +-- .../GUI/ControlBar/ControlBarCommand.cpp | 2 +- .../GUI/DisconnectMenu/DisconnectMenu.cpp | 4 +-- .../GUI/GUICallbacks/IMECandidate.cpp | 2 +- .../GUICallbacks/Menus/LanGameOptionsMenu.cpp | 10 +++---- .../GUI/GUICallbacks/Menus/LanLobbyMenu.cpp | 2 +- .../GUI/GUICallbacks/Menus/MainMenu.cpp | 4 +-- .../Menus/NetworkDirectConnect.cpp | 4 +-- .../GUICallbacks/Menus/PopupPlayerInfo.cpp | 4 +-- .../GUI/GUICallbacks/Menus/ReplayMenu.cpp | 4 +-- .../GUICallbacks/Menus/WOLGameSetupMenu.cpp | 2 +- .../GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp | 16 +++++----- .../GUI/GUICallbacks/Menus/WOLLoginMenu.cpp | 2 +- .../GUICallbacks/Menus/WOLQuickMatchMenu.cpp | 2 +- .../GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp | 12 ++++---- .../GameClient/GUI/Gadget/GadgetListBox.cpp | 2 +- .../GameClient/GUI/GameWindowManager.cpp | 24 +++++++-------- .../Source/GameClient/GUI/LoadScreen.cpp | 2 +- .../Source/GameClient/Input/Mouse.cpp | 2 +- .../Source/GameClient/LanguageFilter.cpp | 2 +- .../MessageStream/SelectionXlat.cpp | 6 ++-- .../GameLogic/Object/Contain/OpenContain.cpp | 2 +- .../Source/GameLogic/System/GameLogic.cpp | 2 +- .../GameEngine/Source/GameNetwork/GameSpy.cpp | 30 +++++++++---------- .../W3DDevice/GameClient/W3DInGameUI.cpp | 2 +- .../Source/Common/RTS/AcademyStats.cpp | 2 +- .../Code/GameEngine/Source/Common/version.cpp | 2 +- .../GameClient/GUI/ControlBar/ControlBar.cpp | 4 +-- .../GUI/ControlBar/ControlBarCommand.cpp | 2 +- .../GUI/DisconnectMenu/DisconnectMenu.cpp | 4 +-- .../GUI/GUICallbacks/IMECandidate.cpp | 2 +- .../GUICallbacks/Menus/LanGameOptionsMenu.cpp | 10 +++---- .../GUI/GUICallbacks/Menus/LanLobbyMenu.cpp | 2 +- .../GUI/GUICallbacks/Menus/MainMenu.cpp | 4 +-- .../Menus/NetworkDirectConnect.cpp | 4 +-- .../GUICallbacks/Menus/PopupPlayerInfo.cpp | 4 +-- .../GUI/GUICallbacks/Menus/ReplayMenu.cpp | 4 +-- .../GUICallbacks/Menus/WOLGameSetupMenu.cpp | 2 +- .../GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp | 16 +++++----- .../GUI/GUICallbacks/Menus/WOLLoginMenu.cpp | 2 +- .../GUICallbacks/Menus/WOLQuickMatchMenu.cpp | 6 ++-- .../GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp | 12 ++++---- .../GameClient/GUI/Gadget/GadgetListBox.cpp | 2 +- .../GameClient/GUI/GameWindowManager.cpp | 24 +++++++-------- .../Source/GameClient/GUI/LoadScreen.cpp | 2 +- .../Source/GameClient/Input/Mouse.cpp | 2 +- .../Source/GameClient/LanguageFilter.cpp | 2 +- .../MessageStream/SelectionXlat.cpp | 8 ++--- .../GameLogic/Object/Contain/OpenContain.cpp | 2 +- .../Source/GameLogic/System/GameLogic.cpp | 2 +- .../W3DDevice/GameClient/W3DDisplay.cpp | 2 +- .../W3DDevice/GameClient/W3DInGameUI.cpp | 2 +- ...asciistring_unicodestring_instantiation.py | 6 ++-- 60 files changed, 159 insertions(+), 159 deletions(-) diff --git a/Core/GameEngine/Source/Common/CRCDebug.cpp b/Core/GameEngine/Source/Common/CRCDebug.cpp index db8dbee0a2..6b46e248bb 100644 --- a/Core/GameEngine/Source/Common/CRCDebug.cpp +++ b/Core/GameEngine/Source/Common/CRCDebug.cpp @@ -80,7 +80,7 @@ CRCVerification::~CRCVerification() { if (TheInGameUI) { - TheInGameUI->message(UnicodeString(L"GameLogic changed outside of GameLogic::update() - call Matt (x36804)!")); + TheInGameUI->message(L"GameLogic changed outside of GameLogic::update() - call Matt (x36804)!"); } CRCDEBUG_LOG(("GameLogic changed outside of GameLogic::update()!!!")); } diff --git a/Core/GameEngine/Source/Common/System/UnicodeString.cpp b/Core/GameEngine/Source/Common/System/UnicodeString.cpp index 3f0fe47b04..31bf39d373 100644 --- a/Core/GameEngine/Source/Common/System/UnicodeString.cpp +++ b/Core/GameEngine/Source/Common/System/UnicodeString.cpp @@ -437,7 +437,7 @@ Bool UnicodeString::nextToken(UnicodeString* tok, UnicodeString delimiters) return false; if (delimiters.isEmpty()) - delimiters = UnicodeString(L" \t\n\r"); + delimiters = L" \t\n\r"; Int offset; diff --git a/Core/GameEngine/Source/GameNetwork/ConnectionManager.cpp b/Core/GameEngine/Source/GameNetwork/ConnectionManager.cpp index 6bd869f1bf..7b3450a960 100644 --- a/Core/GameEngine/Source/GameNetwork/ConnectionManager.cpp +++ b/Core/GameEngine/Source/GameNetwork/ConnectionManager.cpp @@ -651,7 +651,7 @@ void ConnectionManager::processChat(NetChatCommandMsg *msg) const Player *player = ThePlayerList->findPlayerWithNameKey( TheNameKeyGenerator->nameToKey( playerName ) ); if (!player) { - TheInGameUI->message(UnicodeString(L"%ls"), unitext.str()); + TheInGameUI->message(L"%ls", unitext.str()); return; } @@ -663,7 +663,7 @@ void ConnectionManager::processChat(NetChatCommandMsg *msg) { RGBColor rgb; rgb.setFromInt(player->getPlayerColor()); - TheInGameUI->messageColor(&rgb, UnicodeString(L"%ls"), unitext.str()); + TheInGameUI->messageColor(&rgb, L"%ls", unitext.str()); // feedback for received chat messages in-game AudioEventRTS audioEvent("GUICommunicatorIncoming"); @@ -2120,7 +2120,7 @@ UnsignedShort ConnectionManager::sendFileAnnounce(AsciiString path, UnsignedByte log.format(L"Not sending file '%hs' to %X", path.str(), playerMask); DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("%ls", log.str())); if (TheLAN) - TheLAN->OnChat(UnicodeString(L"sendFile"), 0, log, LANAPI::LANCHAT_SYSTEM); + TheLAN->OnChat(L"sendFile", 0, log, LANAPI::LANCHAT_SYSTEM); return 0; } @@ -2158,7 +2158,7 @@ void ConnectionManager::sendFile(AsciiString path, UnsignedByte playerMask, Unsi log.format(L"Not sending file '%hs' to %X", path.str(), playerMask); DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("%ls", log.str())); if (TheLAN) - TheLAN->OnChat(UnicodeString(L"sendFile"), 0, log, LANAPI::LANCHAT_SYSTEM); + TheLAN->OnChat(L"sendFile", 0, log, LANAPI::LANCHAT_SYSTEM); return; } diff --git a/Core/GameEngine/Source/GameNetwork/GameSpy/LobbyUtils.cpp b/Core/GameEngine/Source/GameNetwork/GameSpy/LobbyUtils.cpp index a14969bd88..7ac0d39b85 100644 --- a/Core/GameEngine/Source/GameNetwork/GameSpy/LobbyUtils.cpp +++ b/Core/GameEngine/Source/GameNetwork/GameSpy/LobbyUtils.cpp @@ -613,8 +613,8 @@ static Int insertGame( GameWindow *win, GameSpyStagingRoom *game, Bool showMap ) } else { - GadgetListBoxAddEntryText(win, UnicodeString(L" "), gameColor, index, COLUMN_MAP); - GadgetListBoxAddEntryText(win, UnicodeString(L" "), gameColor, index, COLUMN_LADDER); + GadgetListBoxAddEntryText(win, L" ", gameColor, index, COLUMN_MAP); + GadgetListBoxAddEntryText(win, L" ", gameColor, index, COLUMN_LADDER); } s.format(L"%d/%d", game->getReportedNumPlayers(), game->getReportedMaxPlayers()); @@ -633,7 +633,7 @@ static Int insertGame( GameWindow *win, GameSpyStagingRoom *game, Bool showMap ) } else { - GadgetListBoxAddEntryText(win, UnicodeString(L" "), gameColor, index, COLUMN_PASSWORD); + GadgetListBoxAddEntryText(win, L" ", gameColor, index, COLUMN_PASSWORD); } if (game->getAllowObservers()) @@ -643,7 +643,7 @@ static Int insertGame( GameWindow *win, GameSpyStagingRoom *game, Bool showMap ) } else { - GadgetListBoxAddEntryText(win, UnicodeString(L" "), gameColor, index, COLUMN_OBSERVER); + GadgetListBoxAddEntryText(win, L" ", gameColor, index, COLUMN_OBSERVER); } #if !RTS_GENERALS diff --git a/Core/GameEngine/Source/GameNetwork/LANAPI.cpp b/Core/GameEngine/Source/GameNetwork/LANAPI.cpp index 87963c5bef..9549e58c78 100644 --- a/Core/GameEngine/Source/GameNetwork/LANAPI.cpp +++ b/Core/GameEngine/Source/GameNetwork/LANAPI.cpp @@ -308,7 +308,7 @@ void LANAPI::checkMOTD( void ) UnicodeString uniLine; uniLine.translate(line); - OnChat( UnicodeString(L"MOTD"), 0, uniLine, LANCHAT_SYSTEM ); + OnChat( L"MOTD", 0, uniLine, LANCHAT_SYSTEM ); } } } @@ -773,7 +773,7 @@ void LANAPI::RequestHasMap( void ) text.format(TheGameText->fetch("GUI:LocalPlayerNoMapWillTransfer"), mapDisplayName.str()); else text.format(TheGameText->fetch("GUI:LocalPlayerNoMap"), mapDisplayName.str()); - OnChat(UnicodeString(L"SYSTEM"), m_localIP, text, LANCHAT_SYSTEM); + OnChat(L"SYSTEM", m_localIP, text, LANCHAT_SYSTEM); } } @@ -921,7 +921,7 @@ void LANAPI::RequestGameCreate( UnicodeString gameName, Bool isDirectConnect ) /// @todo: Need to initialize the players elsewere. /* for (int player = 1; player < MAX_SLOTS; ++player) { - myGame->setPlayerName(player, UnicodeString(L"")); + myGame->setPlayerName(player, L""); myGame->setIP(player, 0); myGame->setAccepted(player, false); }*/ diff --git a/Core/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp b/Core/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp index 8c17920205..9c9fd2a0a0 100644 --- a/Core/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp +++ b/Core/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp @@ -124,7 +124,7 @@ void LANAPI::OnAccept( UnsignedInt playerIP, Bool status ) { UnicodeString text; text = TheGameText->fetch("GUI:HostWantsToStart"); - OnChat(UnicodeString(L"SYSTEM"), m_localIP, text, LANCHAT_SYSTEM); + OnChat(L"SYSTEM", m_localIP, text, LANCHAT_SYSTEM); } } } @@ -165,7 +165,7 @@ void LANAPI::OnHasMap( UnsignedInt playerIP, Bool status ) text.format(TheGameText->fetch("GUI:PlayerNoMapWillTransfer"), m_currentGame->getLANSlot(i)->getName().str(), mapDisplayName.str()); else text.format(TheGameText->fetch("GUI:PlayerNoMap"), m_currentGame->getLANSlot(i)->getName().str(), mapDisplayName.str()); - OnChat(UnicodeString(L"SYSTEM"), m_localIP, text, LANCHAT_SYSTEM); + OnChat(L"SYSTEM", m_localIP, text, LANCHAT_SYSTEM); } lanUpdateSlotList(); } @@ -179,7 +179,7 @@ void LANAPI::OnGameStartTimer( Int seconds ) text.format(TheGameText->fetch("LAN:GameStartTimerSingular"), seconds); else text.format(TheGameText->fetch("LAN:GameStartTimerPlural"), seconds); - OnChat(UnicodeString(L"SYSTEM"), m_localIP, text, LANCHAT_SYSTEM); + OnChat(L"SYSTEM", m_localIP, text, LANCHAT_SYSTEM); } void LANAPI::OnGameStart( void ) diff --git a/Generals/Code/GameEngine/Source/Common/version.cpp b/Generals/Code/GameEngine/Source/Common/version.cpp index a5eca5b66f..0c6375cfaf 100644 --- a/Generals/Code/GameEngine/Source/Common/version.cpp +++ b/Generals/Code/GameEngine/Source/Common/version.cpp @@ -309,7 +309,7 @@ UnicodeString Version::getUnicodeBuildUserOrGitCommitAuthorName() const UnicodeString Version::getUnicodeProductTitle() const { // @todo Make configurable - return UnicodeString(L"Community Patch"); + return L"Community Patch"; } UnicodeString Version::getUnicodeProductVersion() const diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp index ecabff9b8e..dfc5f077e1 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp @@ -455,7 +455,7 @@ void ControlBar::populatePurchaseScience( Player* player ) u.translate(foo); GadgetListBoxAddEntryText(win, u, color, -1, -1); } - GadgetListBoxAddEntryText(win, UnicodeString(L"Cancel"), color, -1, -1);*/ + GadgetListBoxAddEntryText(win, L"Cancel", color, -1, -1);*/ } @@ -2469,7 +2469,7 @@ void ControlBar::setControlCommand( GameWindow *button, const CommandButton *com button->winSetTooltipFunc(commandButtonTooltip); } else - GadgetButtonSetText( button, UnicodeString( L"" ) ); + GadgetButtonSetText( button, L"" ); // save the command in the user data of the window GadgetButtonSetData(button, (void*)commandButton); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp index 530304c492..f70dcc6612 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp @@ -519,7 +519,7 @@ void ControlBar::populateBuildQueue( Object *producer ) m_queueData[ i ].control->winClearStatus( WIN_STATUS_USE_OVERLAY_STATES ); // set the text of the window to nothing by default - GadgetButtonSetText( m_queueData[ i ].control, UnicodeString( L"" ) ); + GadgetButtonSetText( m_queueData[ i ].control, L"" ); //Clear any potential veterancy rank, or else we'll see it when it's empty! GadgetButtonDrawOverlayImage( m_queueData[ i ].control, NULL ); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/DisconnectMenu/DisconnectMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/DisconnectMenu/DisconnectMenu.cpp index ebaacbb63f..e249a7fe96 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/DisconnectMenu/DisconnectMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/DisconnectMenu/DisconnectMenu.cpp @@ -133,7 +133,7 @@ void DisconnectMenu::setPlayerName(Int playerNum, UnicodeString name) { if (control != NULL) { if (name.getLength() > 0) { - GadgetStaticTextSetText(control, UnicodeString(L"")); + GadgetStaticTextSetText(control, L""); } } @@ -241,7 +241,7 @@ void DisconnectMenu::showPacketRouterTimeout() { control = TheWindowManager->winGetWindowFromId(NULL, id); if (control != NULL) { - GadgetStaticTextSetText(control, UnicodeString(L"")); // start it off with a blank string. + GadgetStaticTextSetText(control, L""); // start it off with a blank string. control->winHide(FALSE); } } diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/IMECandidate.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/IMECandidate.cpp index c55a5c984f..9a03af81ba 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/IMECandidate.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/IMECandidate.cpp @@ -193,7 +193,7 @@ void IMECandidateTextAreaDraw( GameWindow *window, WinInstanceData *instData ) // calulate the widest number text Int width; - Dstring->setText(UnicodeString(L"00:")); + Dstring->setText(L"00:"); width = Dstring->getWidth(); // calc y start pos 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 05d8a1d354..0fdce08eaa 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp @@ -254,7 +254,7 @@ void StartPressed(void) { UnicodeString text; text.format(TheGameText->fetch("LAN:TooManyPlayers"), (md)?md->m_numPlayers:0); - TheLAN->OnChat(UnicodeString(L"SYSTEM"), TheLAN->GetLocalIP(), text, LANAPI::LANCHAT_SYSTEM); + TheLAN->OnChat(L"SYSTEM", TheLAN->GetLocalIP(), text, LANAPI::LANCHAT_SYSTEM); } return; } @@ -265,7 +265,7 @@ void StartPressed(void) if (TheLAN->AmIHost()) { UnicodeString text = TheGameText->fetch("GUI:NeedHumanPlayers"); - TheLAN->OnChat(UnicodeString(L"SYSTEM"), TheLAN->GetLocalIP(), text, LANAPI::LANCHAT_SYSTEM); + TheLAN->OnChat(L"SYSTEM", TheLAN->GetLocalIP(), text, LANAPI::LANCHAT_SYSTEM); } return; } @@ -277,7 +277,7 @@ void StartPressed(void) { UnicodeString text; text.format(TheGameText->fetch("LAN:NeedMorePlayers"),numUsers); - TheLAN->OnChat(UnicodeString(L"SYSTEM"), TheLAN->GetLocalIP(), text, LANAPI::LANCHAT_SYSTEM); + TheLAN->OnChat(L"SYSTEM", TheLAN->GetLocalIP(), text, LANAPI::LANCHAT_SYSTEM); } return; } @@ -306,7 +306,7 @@ void StartPressed(void) { UnicodeString text; text.format(TheGameText->fetch("LAN:NeedMoreTeams")); - TheLAN->OnChat(UnicodeString(L"SYSTEM"), TheLAN->GetLocalIP(), text, LANAPI::LANCHAT_SYSTEM); + TheLAN->OnChat(L"SYSTEM", TheLAN->GetLocalIP(), text, LANAPI::LANCHAT_SYSTEM); } return; } @@ -315,7 +315,7 @@ void StartPressed(void) { UnicodeString text; text.format(TheGameText->fetch("GUI:SandboxMode")); - TheLAN->OnChat(UnicodeString(L"SYSTEM"), TheLAN->GetLocalIP(), text, LANAPI::LANCHAT_SYSTEM); + TheLAN->OnChat(L"SYSTEM", TheLAN->GetLocalIP(), text, LANAPI::LANCHAT_SYSTEM); } // see if everyone's accepted and count the number of players in the game diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp index 9f65481880..89e8efd685 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp @@ -771,7 +771,7 @@ WindowMsgHandledType LanLobbyMenuSystem( GameWindow *window, UnsignedInt msg, } else if ( controlID == buttonHostID ) { - TheLAN->RequestGameCreate( UnicodeString(L""), FALSE); + TheLAN->RequestGameCreate( L"", FALSE); } else if ( controlID == buttonClearID ) 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 eb20eee788..699352fe08 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp @@ -531,7 +531,7 @@ void MainMenuInit( WindowLayout *layout, void *userData ) instData.init(); BitSet( instData.m_style, GWS_PUSH_BUTTON | GWS_MOUSE_TRACK ); instData.m_textLabelString = "Debug: Compress/Decompress Maps"; - instData.setTooltipText(UnicodeString(L"Only Used in Debug and Internal!")); + instData.setTooltipText(L"Only Used in Debug and Internal!"); buttonCompressTest = TheWindowManager->gogoGadgetPushButton( parentMainMenu, WIN_STATUS_ENABLED | WIN_STATUS_IMAGE, 25, 175, @@ -543,7 +543,7 @@ void MainMenuInit( WindowLayout *layout, void *userData ) BitSet( instData.m_style, GWS_PUSH_BUTTON | GWS_MOUSE_TRACK ); instData.m_textLabelString = "Debug: Load Map"; - instData.setTooltipText(UnicodeString(L"Only Used in Debug and Internal!")); + instData.setTooltipText(L"Only Used in Debug and Internal!"); buttonCampaign = TheWindowManager->gogoGadgetPushButton( parentMainMenu, WIN_STATUS_ENABLED, 25, 54, 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 32cd126db5..f9e7349779 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp @@ -113,7 +113,7 @@ void UpdateRemoteIPList() // UnicodeString newEntry = prefs.getRemoteIPEntry(0); UnicodeString newEntry = unisel; UnicodeString newIP; - newEntry.nextToken(&newIP, UnicodeString(L":")); + newEntry.nextToken(&newIP, L":"); Int numFields = swscanf(newIP.str(), L"%d.%d.%d.%d", &(n1[0]), &(n1[1]), &(n1[2]), &(n1[3])); if (numFields != 4) { @@ -140,7 +140,7 @@ void UpdateRemoteIPList() { UnicodeString oldEntry = uni; UnicodeString oldIP; - oldEntry.nextToken(&oldIP, UnicodeString(L":")); + oldEntry.nextToken(&oldIP, L":"); swscanf(oldIP.str(), L"%d.%d.%d.%d", &(n2[0]), &(n2[1]), &(n2[2]), &(n2[3])); 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 b783f77f34..2b08e31bf4 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupPlayerInfo.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupPlayerInfo.cpp @@ -1105,7 +1105,7 @@ void HandlePersistentStorageResponses( void ) } DEBUG_LOG(("PopulatePlayerInfoWindows() - lookAtPlayerID is %d, got %d", lookAtPlayerID, resp.player.id)); PopulatePlayerInfoWindows("PopupPlayerInfo.wnd"); - //GadgetListBoxAddEntryText(listboxInfo, UnicodeString(L"Got info!"), GameSpyColor[GSCOLOR_DEFAULT], -1); + //GadgetListBoxAddEntryText(listboxInfo, L"Got info!", GameSpyColor[GSCOLOR_DEFAULT], -1); // also update info for player list in lobby PlayerInfoMap::iterator it = TheGameSpyInfo->getPlayerInfoMap()->begin(); @@ -1202,7 +1202,7 @@ void GameSpyPlayerInfoOverlayInit( WindowLayout *layout, void *userData ) isOverlayActive = true; - //GadgetListBoxAddEntryText(listboxInfo, UnicodeString(L"Working"), GameSpyColor[GSCOLOR_DEFAULT], -1); + //GadgetListBoxAddEntryText(listboxInfo, L"Working", GameSpyColor[GSCOLOR_DEFAULT], -1); GameSpyCloseOverlay(GSOVERLAY_BUDDY); raiseMessageBox = true; 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 3571ff025d..bbad3784ad 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ReplayMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ReplayMenu.cpp @@ -397,7 +397,7 @@ void ReplayMenuInit( WindowLayout *layout, void *userData ) instData.init(); BitSet( instData.m_style, GWS_PUSH_BUTTON | GWS_MOUSE_TRACK ); instData.m_textLabelString = "Debug: Analyze Replay"; - instData.setTooltipText(UnicodeString(L"Only Used in Debug and Internal!")); + instData.setTooltipText(L"Only Used in Debug and Internal!"); buttonAnalyzeReplay = TheWindowManager->gogoGadgetPushButton( parentReplayMenu, WIN_STATUS_ENABLED | WIN_STATUS_IMAGE, 4, 4, @@ -657,7 +657,7 @@ WindowMsgHandledType ReplayMenuSystem( GameWindow *window, UnsignedInt msg, GadgetListBoxGetSelected( listboxReplayFiles, &selected ); if(selected < 0) { - MessageBoxOk(UnicodeString(L"Blah Blah"),UnicodeString(L"Please select something munkee boy"), NULL); + MessageBoxOk(L"Blah Blah",L"Please select something munkee boy", NULL); break; } 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 ddafdd13d4..db5ffbd2a2 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp @@ -2330,7 +2330,7 @@ Bool handleGameSetupSlashCommands(UnicodeString uText) else if (token == "slots") { g_debugSlots = !g_debugSlots; - TheGameSpyInfo->addText(UnicodeString(L"Toggled SlotList debug"), GameSpyColor[GSCOLOR_DEFAULT], NULL); + TheGameSpyInfo->addText(L"Toggled SlotList debug", GameSpyColor[GSCOLOR_DEFAULT], NULL); return TRUE; // was a slash command } else if (token == "discon") 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 a86b514f67..e719999f2f 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp @@ -201,13 +201,13 @@ Bool handleLobbySlashCommands(UnicodeString uText) else if (token == "fakecrc") { g_fakeCRC = !g_fakeCRC; - TheGameSpyInfo->addText(UnicodeString(L"Toggled CRC fakery"), GameSpyColor[GSCOLOR_DEFAULT], NULL); + TheGameSpyInfo->addText(L"Toggled CRC fakery", GameSpyColor[GSCOLOR_DEFAULT], NULL); return TRUE; // was a slash command } else if (token == "slots") { g_debugSlots = !g_debugSlots; - TheGameSpyInfo->addText(UnicodeString(L"Toggled SlotList debug"), GameSpyColor[GSCOLOR_DEFAULT], NULL); + TheGameSpyInfo->addText(L"Toggled SlotList debug", GameSpyColor[GSCOLOR_DEFAULT], NULL); return TRUE; // was a slash command } #endif @@ -1135,7 +1135,7 @@ void WOLLobbyMenuUpdate( WindowLayout * layout, void *userData) { case PEER_CLEAR: TheGameSpyInfo->clearStagingRoomList(); - //TheGameSpyInfo->addText( UnicodeString(L"gameList: PEER_CLEAR"), GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); + //TheGameSpyInfo->addText( L"gameList: PEER_CLEAR", GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); break; case PEER_ADD: case PEER_UPDATE: @@ -1238,29 +1238,29 @@ void WOLLobbyMenuUpdate( WindowLayout * layout, void *userData) if (resp.stagingRoom.action == PEER_ADD) { TheGameSpyInfo->addStagingRoom(room); - //TheGameSpyInfo->addText( UnicodeString(L"gameList: PEER_ADD"), GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); + //TheGameSpyInfo->addText( L"gameList: PEER_ADD", GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); } else { TheGameSpyInfo->updateStagingRoom(room); - //TheGameSpyInfo->addText( UnicodeString(L"gameList: PEER_UPDATE"), GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); + //TheGameSpyInfo->addText( L"gameList: PEER_UPDATE", GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); } } else { room.setID(resp.stagingRoom.id); TheGameSpyInfo->removeStagingRoom(room); - //TheGameSpyInfo->addText( UnicodeString(L"gameList: PEER_UPDATE FAILED"), GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); + //TheGameSpyInfo->addText( L"gameList: PEER_UPDATE FAILED", GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); } break; } case PEER_REMOVE: room.setID(resp.stagingRoom.id); TheGameSpyInfo->removeStagingRoom(room); - //TheGameSpyInfo->addText( UnicodeString(L"gameList: PEER_REMOVE"), GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); + //TheGameSpyInfo->addText( L"gameList: PEER_REMOVE", GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); break; default: - //TheGameSpyInfo->addText( UnicodeString(L"gameList: Unknown"), GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); + //TheGameSpyInfo->addText( L"gameList: Unknown", GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); break; } } 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 e3d7e353f6..74f8f49bbd 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLoginMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLoginMenu.cpp @@ -830,7 +830,7 @@ void WOLLoginMenuUpdate( WindowLayout * layout, void *userData) room.m_groupID = resp.groupRoom.id; room.m_maxWaiting = resp.groupRoom.maxWaiting; room.m_name = resp.groupRoomName.c_str(); - room.m_translatedName = UnicodeString(L"TEST"); + room.m_translatedName = L"TEST"; room.m_numGames = resp.groupRoom.numGames; room.m_numPlaying = resp.groupRoom.numPlaying; room.m_numWaiting = resp.groupRoom.numWaiting; 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 a50d2f6a93..35d8a0bf6e 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp @@ -1207,7 +1207,7 @@ void WOLQuickMatchMenuUpdate( WindowLayout * layout, void *userData) switch( resp.qmStatus.status ) { case QM_IDLE: - //TheGameSpyInfo->addText(UnicodeString(L"Status: QM_IDLE"), GameSpyColor[GSCOLOR_DEFAULT], quickmatchTextWindow); + //TheGameSpyInfo->addText(L"Status: QM_IDLE", GameSpyColor[GSCOLOR_DEFAULT], quickmatchTextWindow); break; case QM_JOININGQMCHANNEL: TheGameSpyInfo->addText(TheGameText->fetch("QM:JOININGQMCHANNEL"), GameSpyColor[GSCOLOR_DEFAULT], quickmatchTextWindow); 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 0a011d40c6..894a3f0e70 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp @@ -238,7 +238,7 @@ static void updateNumPlayersOnline(void) UnicodeString headingStr; headingStr.format(TheGameText->fetch("MOTD:NumPlayersHeading"), lastNumPlayersOnline); - while (headingStr.nextToken(&line, UnicodeString(L"\n"))) + while (headingStr.nextToken(&line, L"\n")) { if (line.getCharAt(line.getLength()-1) == '\r') line.removeLastChar(); // there is a trailing '\r' @@ -247,12 +247,12 @@ static void updateNumPlayersOnline(void) if (line.isEmpty()) { - line = UnicodeString(L" "); + line = L" "; } GadgetListBoxAddEntryText(listboxInfo, line, GameSpyColor[GSCOLOR_MOTD_HEADING], -1, -1); } - GadgetListBoxAddEntryText(listboxInfo, UnicodeString(L" "), GameSpyColor[GSCOLOR_MOTD_HEADING], -1, -1); + GadgetListBoxAddEntryText(listboxInfo, L" ", GameSpyColor[GSCOLOR_MOTD_HEADING], -1, -1); while (aMotd.nextToken(&aLine, "\n")) { @@ -458,7 +458,7 @@ void WOLWelcomeMenuInit( WindowLayout *layout, void *userData ) // Clear some defaults /* - UnicodeString questionMark = UnicodeString(L"?"); + UnicodeString questionMark = L"?"; GadgetStaticTextSetText(staticTextLastUpdated, questionMark); GadgetStaticTextSetText(staticTextLadderWins, questionMark); GadgetStaticTextSetText(staticTextLadderLosses, questionMark); @@ -624,7 +624,7 @@ void WOLWelcomeMenuUpdate( WindowLayout * layout, void *userData) room.m_groupID = resp.groupRoom.id; room.m_maxWaiting = resp.groupRoom.maxWaiting; room.m_name = resp.groupRoomName.c_str(); - room.m_translatedName = UnicodeString(L"TEST"); + room.m_translatedName = L"TEST"; room.m_numGames = resp.groupRoom.numGames; room.m_numPlaying = resp.groupRoom.numPlaying; room.m_numWaiting = resp.groupRoom.numWaiting; @@ -857,7 +857,7 @@ WindowMsgHandledType WOLWelcomeMenuSystem( GameWindow *window, UnsignedInt msg, else { GameSpyCurrentGroupRoomID = 0; - GSMessageBoxOk(UnicodeString(L"Oops"), UnicodeString(L"Unable to join title room"), NULL); + GSMessageBoxOk(L"Oops", L"Unable to join title room", NULL); } */ } diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp index 1101a2ceab..d35381fe44 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp @@ -2205,7 +2205,7 @@ Int GadgetListBoxAddEntryText( GameWindow *listbox, if (!listbox) return -1; if (text.isEmpty()) - text = UnicodeString(L" "); + text = L" "; Int index; AddMessageStruct addInfo; addInfo.row = row; diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp index 9a52580044..ddddb59367 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp @@ -3790,17 +3790,17 @@ Bool GameWindowManager::initTestGUI( void ) 100, 100, &instData, &listData, NULL, TRUE ); - GadgetListBoxAddEntryText( window, UnicodeString(L"Listbox text"), + GadgetListBoxAddEntryText( window, L"Listbox text", TheWindowManager->winMakeColor( 255, 255, 255, 255 ), -1, 0 ); - GadgetListBoxAddEntryText( window, UnicodeString(L"More text"), + GadgetListBoxAddEntryText( window, L"More text", TheWindowManager->winMakeColor( 105, 105, 255, 255 ), -1, 0 ); - GadgetListBoxAddEntryText( window, UnicodeString(L"Nothing"), + GadgetListBoxAddEntryText( window, L"Nothing", TheWindowManager->winMakeColor( 105, 105, 255, 255 ), -1, 0 ); - GadgetListBoxAddEntryText( window, UnicodeString(L"Seasons"), + GadgetListBoxAddEntryText( window, L"Seasons", TheWindowManager->winMakeColor( 105, 205, 255, 255 ), -1, 0 ); - GadgetListBoxAddEntryText( window, UnicodeString(L"Misery"), + GadgetListBoxAddEntryText( window, L"Misery", TheWindowManager->winMakeColor( 235, 105, 255, 255 ), -1, 0 ); - GadgetListBoxAddEntryText( window, UnicodeString(L"Natural"), + GadgetListBoxAddEntryText( window, L"Natural", TheWindowManager->winMakeColor( 105, 205, 45, 255 ), -1, 0 ); window->winSetFont( TheFontLibrary->getFont( "Times New Roman", 12, FALSE ) ); @@ -3823,17 +3823,17 @@ Bool GameWindowManager::initTestGUI( void ) 100, 100, &instData, &listData, NULL, TRUE ); - GadgetListBoxAddEntryText( window, UnicodeString(L"Listbox text"), + GadgetListBoxAddEntryText( window, L"Listbox text", TheWindowManager->winMakeColor( 255, 255, 255, 255 ), -1, -1 ); - GadgetListBoxAddEntryText( window, UnicodeString(L"More text"), + GadgetListBoxAddEntryText( window, L"More text", TheWindowManager->winMakeColor( 105, 105, 255, 255 ), -1, -1 ); - GadgetListBoxAddEntryText( window, UnicodeString(L"Nothing"), + GadgetListBoxAddEntryText( window, L"Nothing", TheWindowManager->winMakeColor( 105, 105, 255, 255 ), -1, -1 ); - GadgetListBoxAddEntryText( window, UnicodeString(L"Seasons"), + GadgetListBoxAddEntryText( window, L"Seasons", TheWindowManager->winMakeColor( 105, 205, 255, 255 ), -1, -1 ); - GadgetListBoxAddEntryText( window, UnicodeString(L"Misery"), + GadgetListBoxAddEntryText( window, L"Misery", TheWindowManager->winMakeColor( 235, 105, 255, 255 ), -1, -1 ); - GadgetListBoxAddEntryText( window, UnicodeString(L"Natural"), + GadgetListBoxAddEntryText( window, L"Natural", TheWindowManager->winMakeColor( 105, 205, 45, 255 ), -1, -1 ); // make a vert slider diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp index 937b86f899..a1011520c0 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp @@ -379,7 +379,7 @@ void SinglePlayerLoadScreen::init( GameInfo *game ) m_percent = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:Percent" )); DEBUG_ASSERTCRASH(m_percent, ("Can't initialize the m_percent for the single player loadscreen")); - GadgetStaticTextSetText(m_percent,UnicodeString(L"0%")); + GadgetStaticTextSetText(m_percent,L"0%"); m_percent->winHide(TRUE); m_objectiveWin = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:ObjectivesWin" )); diff --git a/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp b/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp index 99180dbce7..7331faec6b 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp @@ -1337,7 +1337,7 @@ void Mouse::setCursor( MouseCursor cursor ) &(cursorInfo->cursorTextColor), &(cursorInfo->cursorTextDropColor) ); else - setMouseText( UnicodeString( L"" ), NULL, NULL ); + setMouseText( L"", NULL, NULL ); } diff --git a/Generals/Code/GameEngine/Source/GameClient/LanguageFilter.cpp b/Generals/Code/GameEngine/Source/GameClient/LanguageFilter.cpp index 0aa3abf688..15ef18db3b 100644 --- a/Generals/Code/GameEngine/Source/GameClient/LanguageFilter.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/LanguageFilter.cpp @@ -86,7 +86,7 @@ void LanguageFilter::filterLine(UnicodeString &line) UnicodeString newLine(line); UnicodeString token(L""); - while (newLine.nextToken(&token, UnicodeString(L" ;,.!?:=\\/><`~()&^%#\n\t"))) { + while (newLine.nextToken(&token, L" ;,.!?:=\\/><`~()&^%#\n\t")) { wchar_t *pos = wcsstr(buf, token.str()); if (pos == NULL) { DEBUG_CRASH(("Couldn't find the token in its own string.")); diff --git a/Generals/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp b/Generals/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp index daf5d4bd42..627da82562 100644 --- a/Generals/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp @@ -1203,7 +1203,7 @@ GameMessageDisposition SelectionTranslator::translateGameMessage(const GameMessa case GameMessage::MSG_META_DEMO_TOGGLE_HAND_OF_GOD_MODE: { TheHandOfGodSelectionMode = !TheHandOfGodSelectionMode; - TheInGameUI->message( UnicodeString( L"Hand-Of-God Mode is %s" ), TheHandOfGodSelectionMode ? L"ON" : L"OFF" ); + TheInGameUI->message( L"Hand-Of-God Mode is %s", TheHandOfGodSelectionMode ? L"ON" : L"OFF" ); disp = DESTROY_MESSAGE; break; } @@ -1214,7 +1214,7 @@ GameMessageDisposition SelectionTranslator::translateGameMessage(const GameMessa case GameMessage::MSG_META_DEMO_TOGGLE_HURT_ME_MODE: { TheHurtSelectionMode = !TheHurtSelectionMode; - TheInGameUI->message( UnicodeString( L"Hurt-Me Mode is %s" ), TheHurtSelectionMode ? L"ON" : L"OFF" ); + TheInGameUI->message( L"Hurt-Me Mode is %s", TheHurtSelectionMode ? L"ON" : L"OFF" ); disp = DESTROY_MESSAGE; break; } @@ -1225,7 +1225,7 @@ GameMessageDisposition SelectionTranslator::translateGameMessage(const GameMessa case GameMessage::MSG_META_DEMO_DEBUG_SELECTION: { TheDebugSelectionMode = !TheDebugSelectionMode; - TheInGameUI->message( UnicodeString( L"Debug-Selected-Item Mode is %s" ), TheDebugSelectionMode ? L"ON" : L"OFF" ); + TheInGameUI->message( L"Debug-Selected-Item Mode is %s", TheDebugSelectionMode ? L"ON" : L"OFF" ); #ifdef DEBUG_OBJECT_ID_EXISTS TheObjectIDToDebug = INVALID_ID; #endif diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp index 48a73f62f8..9cff8d09cd 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp @@ -518,7 +518,7 @@ void OpenContain::removeFromContainViaIterator( ContainedItemsList::iterator it, /* #ifdef RTS_DEBUG - TheInGameUI->message( UnicodeString( L"'%S(%d)' no longer contains '%S(%d)'" ), + TheInGameUI->message( L"'%S(%d)' no longer contains '%S(%d)'", getObject()->getTemplate()->getName().str(), getObject()->getID(), itemToRemove->m_object->getTemplate()->getName().str(), diff --git a/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp index 0e93742b9d..03b6cfda0f 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp @@ -1348,7 +1348,7 @@ void GameLogic::startNewGame( Bool saveGame ) Dict d; d.setAsciiString(TheKey_playerName, "ReplayObserver"); d.setBool(TheKey_playerIsHuman, TRUE); - d.setUnicodeString(TheKey_playerDisplayName, UnicodeString(L"Observer")); + d.setUnicodeString(TheKey_playerDisplayName, L"Observer"); const PlayerTemplate* pt; pt = ThePlayerTemplateStore->findPlayerTemplate( TheNameKeyGenerator->nameToKey("FactionObserver") ); if (pt) diff --git a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy.cpp b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy.cpp index 6939d74029..79a79303d6 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy.cpp @@ -305,7 +305,7 @@ void GameSpyChat::update( void ) { // login timed out m_loginTimeout = 0; - GSMessageBoxOk(UnicodeString(L"Error connecting"), UnicodeString(L"Timed out connecting"), NULL); + GSMessageBoxOk(L"Error connecting", L"Timed out connecting", NULL); // Enable controls again //EnableLoginControls(TRUE); @@ -440,12 +440,12 @@ void GameSpyChat::joinBestGroupRoom( void ) } else { - GSMessageBoxOk(UnicodeString(L"Oops"), UnicodeString(L"No empty group rooms"), NULL); + GSMessageBoxOk(L"Oops", L"No empty group rooms", NULL); } } else { - GSMessageBoxOk(UnicodeString(L"Oops"), UnicodeString(L"No group rooms"), NULL); + GSMessageBoxOk(L"Oops", L"No group rooms", NULL); } } @@ -920,7 +920,7 @@ void JoinRoomCallback(PEER peer, PEERBool success, PEERJoinResult result, RoomTy TheShell->pop(); TheShell->push("Menus/WOLWelcomeMenu.wnd"); } - GSMessageBoxOk(UnicodeString(L"Oops"), UnicodeString(L"Unable to join group room"), NULL); + GSMessageBoxOk(L"Oops", L"Unable to join group room", NULL); } // Update buddy location @@ -978,7 +978,7 @@ void JoinRoomCallback(PEER peer, PEERBool success, PEERJoinResult result, RoomTy else { // let the user know - GSMessageBoxOk(UnicodeString(L"Oops"), UnicodeString(L"Unable to join game"), NULL); + GSMessageBoxOk(L"Oops", L"Unable to join game", NULL); DEBUG_LOG(("JoinRoomCallback - Failed to join staging room.")); } @@ -1065,7 +1065,7 @@ void createRoomCallback(PEER peer, PEERBool success, PEERJoinResult result, Room { // join the lobby again TheGameSpyChat->joinGroupRoom(oldGroupID); - GSMessageBoxOk(UnicodeString(L"Oops"), UnicodeString(L"Unable to create game"), NULL); + GSMessageBoxOk(L"Oops", L"Unable to create game", NULL); } // Update buddy location @@ -1141,7 +1141,7 @@ void GameSpyChat::_connectCallback(PEER peer, PEERBool success, void * param) m_loginTimeout = 0; if (!success) { - GSMessageBoxOk(UnicodeString(L"Error connecting"), UnicodeString(L"Failed to connect"), NULL); + GSMessageBoxOk(L"Error connecting", L"Failed to connect", NULL); DEBUG_LOG(("GameSpyChat::_connectCallback - failed to connect.")); } @@ -1207,7 +1207,7 @@ void GameSpyChat::_nickErrorCallback(PEER peer, int type, const char * nick, voi } else { - GSMessageBoxOk(UnicodeString(L"Error connecting"), UnicodeString(L"That nickname is already taken; please choose another one."), NULL); + GSMessageBoxOk(L"Error connecting", L"That nickname is already taken; please choose another one.", NULL); // Cancel the connect. peerRetryWithNick(peer, NULL); @@ -1218,7 +1218,7 @@ void GameSpyChat::_nickErrorCallback(PEER peer, int type, const char * nick, voi } else { - GSMessageBoxOk(UnicodeString(L"Error connecting"), UnicodeString(L"That nickname contains at least 1 invalid character, please choose another one."), NULL); + GSMessageBoxOk(L"Error connecting", L"That nickname contains at least 1 invalid character, please choose another one.", NULL); // Cancel the connect. peerRetryWithNick(peer, NULL); @@ -1239,7 +1239,7 @@ void GameSpyChat::_GPConnectCallback(GPConnection * pconnection, GPConnectRespon if (*res != GP_NO_ERROR) { // couldn't connect. bummer. - GSMessageBoxOk(UnicodeString(L"Error connecting"), UnicodeString(L"Error connecting to buddy server"), NULL); + GSMessageBoxOk(L"Error connecting", L"Error connecting to buddy server", NULL); gpDisconnect(TheGPConnection); gpDestroy(TheGPConnection); m_loginTimeout = 0; @@ -1262,7 +1262,7 @@ void GameSpyChat::_GPReconnectCallback(GPConnection * pconnection, GPConnectResp if (arg->result != GP_NO_ERROR) { // couldn't connect. bummer. - GSMessageBoxOk(UnicodeString(L"Error connecting"), UnicodeString(L"Error connecting to buddy server"), NULL); + GSMessageBoxOk(L"Error connecting", L"Error connecting to buddy server", NULL); gpDisconnect(TheGPConnection); gpDestroy(TheGPConnection); return; @@ -1270,7 +1270,7 @@ void GameSpyChat::_GPReconnectCallback(GPConnection * pconnection, GPConnectResp else { // yay! we're back in! - GSMessageBoxOk(UnicodeString(L"Connected!"), UnicodeString(L"Reonnected to buddy server"), NULL); + GSMessageBoxOk(L"Connected!", L"Reonnected to buddy server", NULL); } } @@ -1295,7 +1295,7 @@ void GameSpyChat::loginProfile(AsciiString loginName, AsciiString password, Asci if (res != GP_NO_ERROR) { // couldn't connect. bummer. - GSMessageBoxOk(UnicodeString(L"Error connecting"), UnicodeString(L"Error connecting to buddy server"), NULL); + GSMessageBoxOk(L"Error connecting", L"Error connecting to buddy server", NULL); gpDisconnect(TheGPConnection); gpDestroy(TheGPConnection); loginTimeout = 0; @@ -1373,7 +1373,7 @@ void GameSpyChat::login(AsciiString loginName, AsciiString password, AsciiString m_peer = peerInitialize(&callbacks); if(!m_peer) { - GSMessageBoxOk(UnicodeString(L"No Peer"), UnicodeString(L"No Peer"), NULL); + GSMessageBoxOk(L"No Peer", L"No Peer", NULL); return; } @@ -1392,7 +1392,7 @@ void GameSpyChat::login(AsciiString loginName, AsciiString password, AsciiString ///////////////// if(!peerSetTitle(m_peer, "gmtest", "HA6zkS", "gmtest", "HA6zkS", 15, pingRooms, crossPingRooms)) { - GSMessageBoxOk(UnicodeString(L"Error setting title"), UnicodeString(L"Error setting title"), NULL); + GSMessageBoxOk(L"Error setting title", L"Error setting title", NULL); peerShutdown(m_peer); m_peer = NULL; return; diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp index b88d231996..816d96ec8c 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp @@ -324,7 +324,7 @@ static void loadText( char *filename, GameWindow *listboxText ) line.translate(buffer); line.trim(); if (line.isEmpty()) - line = UnicodeString(L" "); + line = L" "; GadgetListBoxAddEntryText(listboxText, line, color, -1, -1); } diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/AcademyStats.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/AcademyStats.cpp index eea2bf3dd0..9041f653bd 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/AcademyStats.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/AcademyStats.cpp @@ -1079,7 +1079,7 @@ Bool AcademyStats::calculateAcademyAdvice( AcademyAdviceInfo *info ) //Build the header for each string. for( UnsignedInt i = 0; i < maxAdviceTips; i++ ) { - info->advice[ i ].format( UnicodeString( L"\n\n" ) ); + info->advice[ i ].format( L"\n\n" ); } //First look at tier 1 basic advice and pick any advice we could benefit from. diff --git a/GeneralsMD/Code/GameEngine/Source/Common/version.cpp b/GeneralsMD/Code/GameEngine/Source/Common/version.cpp index abbf0991ed..39876290cc 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/version.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/version.cpp @@ -309,7 +309,7 @@ UnicodeString Version::getUnicodeBuildUserOrGitCommitAuthorName() const UnicodeString Version::getUnicodeProductTitle() const { // @todo Make configurable - return UnicodeString(L"Community Patch"); + return L"Community Patch"; } UnicodeString Version::getUnicodeProductVersion() const diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp index 7ad72afa73..c6f3972b40 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp @@ -459,7 +459,7 @@ void ControlBar::populatePurchaseScience( Player* player ) u.translate(foo); GadgetListBoxAddEntryText(win, u, color, -1, -1); } - GadgetListBoxAddEntryText(win, UnicodeString(L"Cancel"), color, -1, -1);*/ + GadgetListBoxAddEntryText(win, L"Cancel", color, -1, -1);*/ } @@ -2494,7 +2494,7 @@ void ControlBar::setControlCommand( GameWindow *button, const CommandButton *com button->winSetTooltipFunc(commandButtonTooltip); } else - GadgetButtonSetText( button, UnicodeString( L"" ) ); + GadgetButtonSetText( button, L"" ); // save the command in the user data of the window GadgetButtonSetData(button, (void*)commandButton); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp index 8319505314..d76112978d 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp @@ -589,7 +589,7 @@ void ControlBar::populateBuildQueue( Object *producer ) m_queueData[ i ].control->winClearStatus( WIN_STATUS_USE_OVERLAY_STATES ); // set the text of the window to nothing by default - GadgetButtonSetText( m_queueData[ i ].control, UnicodeString( L"" ) ); + GadgetButtonSetText( m_queueData[ i ].control, L"" ); //Clear any potential veterancy rank, or else we'll see it when it's empty! GadgetButtonDrawOverlayImage( m_queueData[ i ].control, NULL ); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/DisconnectMenu/DisconnectMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/DisconnectMenu/DisconnectMenu.cpp index 7b0a738dbb..13c80807ea 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/DisconnectMenu/DisconnectMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/DisconnectMenu/DisconnectMenu.cpp @@ -132,7 +132,7 @@ void DisconnectMenu::setPlayerName(Int playerNum, UnicodeString name) { if (control != NULL) { if (name.getLength() > 0) { - GadgetStaticTextSetText(control, UnicodeString(L"")); + GadgetStaticTextSetText(control, L""); } } @@ -224,7 +224,7 @@ void DisconnectMenu::showPacketRouterTimeout() { control = TheWindowManager->winGetWindowFromId(NULL, id); if (control != NULL) { - GadgetStaticTextSetText(control, UnicodeString(L"")); // start it off with a blank string. + GadgetStaticTextSetText(control, L""); // start it off with a blank string. control->winHide(FALSE); } } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/IMECandidate.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/IMECandidate.cpp index 3cfbe4722c..1765157c19 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/IMECandidate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/IMECandidate.cpp @@ -193,7 +193,7 @@ void IMECandidateTextAreaDraw( GameWindow *window, WinInstanceData *instData ) // calulate the widest number text Int width; - Dstring->setText(UnicodeString(L"00:")); + Dstring->setText(L"00:"); width = Dstring->getWidth(); // calc y start pos 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 9454e3c4b2..2541ecafb9 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp @@ -261,7 +261,7 @@ void StartPressed(void) { UnicodeString text; text.format(TheGameText->fetch("LAN:TooManyPlayers"), (md)?md->m_numPlayers:0); - TheLAN->OnChat(UnicodeString(L"SYSTEM"), TheLAN->GetLocalIP(), text, LANAPI::LANCHAT_SYSTEM); + TheLAN->OnChat(L"SYSTEM", TheLAN->GetLocalIP(), text, LANAPI::LANCHAT_SYSTEM); } return; } @@ -272,7 +272,7 @@ void StartPressed(void) if (TheLAN->AmIHost()) { UnicodeString text = TheGameText->fetch("GUI:NeedHumanPlayers"); - TheLAN->OnChat(UnicodeString(L"SYSTEM"), TheLAN->GetLocalIP(), text, LANAPI::LANCHAT_SYSTEM); + TheLAN->OnChat(L"SYSTEM", TheLAN->GetLocalIP(), text, LANAPI::LANCHAT_SYSTEM); } return; } @@ -284,7 +284,7 @@ void StartPressed(void) { UnicodeString text; text.format(TheGameText->fetch("LAN:NeedMorePlayers"),numUsers); - TheLAN->OnChat(UnicodeString(L"SYSTEM"), TheLAN->GetLocalIP(), text, LANAPI::LANCHAT_SYSTEM); + TheLAN->OnChat(L"SYSTEM", TheLAN->GetLocalIP(), text, LANAPI::LANCHAT_SYSTEM); } return; } @@ -313,7 +313,7 @@ void StartPressed(void) { UnicodeString text; text.format(TheGameText->fetch("LAN:NeedMoreTeams")); - TheLAN->OnChat(UnicodeString(L"SYSTEM"), TheLAN->GetLocalIP(), text, LANAPI::LANCHAT_SYSTEM); + TheLAN->OnChat(L"SYSTEM", TheLAN->GetLocalIP(), text, LANAPI::LANCHAT_SYSTEM); } return; } @@ -322,7 +322,7 @@ void StartPressed(void) { UnicodeString text; text.format(TheGameText->fetch("GUI:SandboxMode")); - TheLAN->OnChat(UnicodeString(L"SYSTEM"), TheLAN->GetLocalIP(), text, LANAPI::LANCHAT_SYSTEM); + TheLAN->OnChat(L"SYSTEM", TheLAN->GetLocalIP(), text, LANAPI::LANCHAT_SYSTEM); } // see if everyone's accepted and count the number of players in the game diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp index e1bd2a9e42..359d9da101 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp @@ -771,7 +771,7 @@ WindowMsgHandledType LanLobbyMenuSystem( GameWindow *window, UnsignedInt msg, } else if ( controlID == buttonHostID ) { - TheLAN->RequestGameCreate( UnicodeString(L""), FALSE); + TheLAN->RequestGameCreate( L"", FALSE); } else if ( controlID == buttonClearID ) 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 db90f5ab0a..e2cb0193c1 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp @@ -568,7 +568,7 @@ void MainMenuInit( WindowLayout *layout, void *userData ) instData.init(); BitSet( instData.m_style, GWS_PUSH_BUTTON | GWS_MOUSE_TRACK ); instData.m_textLabelString = "Debug: Compress/Decompress Maps"; - instData.setTooltipText(UnicodeString(L"Only Used in Debug and Internal!")); + instData.setTooltipText(L"Only Used in Debug and Internal!"); buttonCompressTest = TheWindowManager->gogoGadgetPushButton( parentMainMenu, WIN_STATUS_ENABLED | WIN_STATUS_IMAGE, 25, 175, @@ -580,7 +580,7 @@ void MainMenuInit( WindowLayout *layout, void *userData ) BitSet( instData.m_style, GWS_PUSH_BUTTON | GWS_MOUSE_TRACK ); instData.m_textLabelString = "Debug: Load Map"; - instData.setTooltipText(UnicodeString(L"Only Used in Debug and Internal!")); + instData.setTooltipText(L"Only Used in Debug and Internal!"); buttonCampaign = TheWindowManager->gogoGadgetPushButton( parentMainMenu, WIN_STATUS_ENABLED, 25, 54, 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 5124c90b45..bd85e8826f 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp @@ -113,7 +113,7 @@ void UpdateRemoteIPList() // UnicodeString newEntry = prefs.getRemoteIPEntry(0); UnicodeString newEntry = unisel; UnicodeString newIP; - newEntry.nextToken(&newIP, UnicodeString(L":")); + newEntry.nextToken(&newIP, L":"); Int numFields = swscanf(newIP.str(), L"%d.%d.%d.%d", &(n1[0]), &(n1[1]), &(n1[2]), &(n1[3])); if (numFields != 4) { @@ -140,7 +140,7 @@ void UpdateRemoteIPList() { UnicodeString oldEntry = uni; UnicodeString oldIP; - oldEntry.nextToken(&oldIP, UnicodeString(L":")); + oldEntry.nextToken(&oldIP, L":"); swscanf(oldIP.str(), L"%d.%d.%d.%d", &(n2[0]), &(n2[1]), &(n2[2]), &(n2[3])); 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 b2f488b1f5..3dd610bcfd 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupPlayerInfo.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupPlayerInfo.cpp @@ -1195,7 +1195,7 @@ void HandlePersistentStorageResponses( void ) } DEBUG_LOG(("PopulatePlayerInfoWindows() - lookAtPlayerID is %d, got %d", lookAtPlayerID, resp.player.id)); PopulatePlayerInfoWindows("PopupPlayerInfo.wnd"); - //GadgetListBoxAddEntryText(listboxInfo, UnicodeString(L"Got info!"), GameSpyColor[GSCOLOR_DEFAULT], -1); + //GadgetListBoxAddEntryText(listboxInfo, L"Got info!", GameSpyColor[GSCOLOR_DEFAULT], -1); // also update info for player list in lobby PlayerInfoMap::iterator it = TheGameSpyInfo->getPlayerInfoMap()->begin(); @@ -1292,7 +1292,7 @@ void GameSpyPlayerInfoOverlayInit( WindowLayout *layout, void *userData ) isOverlayActive = true; - //GadgetListBoxAddEntryText(listboxInfo, UnicodeString(L"Working"), GameSpyColor[GSCOLOR_DEFAULT], -1); + //GadgetListBoxAddEntryText(listboxInfo, L"Working", GameSpyColor[GSCOLOR_DEFAULT], -1); GameSpyCloseOverlay(GSOVERLAY_BUDDY); raiseMessageBox = true; 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 c73221d487..058841715c 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ReplayMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ReplayMenu.cpp @@ -397,7 +397,7 @@ void ReplayMenuInit( WindowLayout *layout, void *userData ) instData.init(); BitSet( instData.m_style, GWS_PUSH_BUTTON | GWS_MOUSE_TRACK ); instData.m_textLabelString = "Debug: Analyze Replay"; - instData.setTooltipText(UnicodeString(L"Only Used in Debug and Internal!")); + instData.setTooltipText(L"Only Used in Debug and Internal!"); buttonAnalyzeReplay = TheWindowManager->gogoGadgetPushButton( parentReplayMenu, WIN_STATUS_ENABLED | WIN_STATUS_IMAGE, 4, 4, @@ -657,7 +657,7 @@ WindowMsgHandledType ReplayMenuSystem( GameWindow *window, UnsignedInt msg, GadgetListBoxGetSelected( listboxReplayFiles, &selected ); if(selected < 0) { - MessageBoxOk(UnicodeString(L"Blah Blah"),UnicodeString(L"Please select something munkee boy"), NULL); + MessageBoxOk(L"Blah Blah",L"Please select something munkee boy", NULL); break; } 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 3ad3b46956..bb36b3501f 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp @@ -2518,7 +2518,7 @@ Bool handleGameSetupSlashCommands(UnicodeString uText) else if (token == "slots") { g_debugSlots = !g_debugSlots; - TheGameSpyInfo->addText(UnicodeString(L"Toggled SlotList debug"), GameSpyColor[GSCOLOR_DEFAULT], NULL); + TheGameSpyInfo->addText(L"Toggled SlotList debug", GameSpyColor[GSCOLOR_DEFAULT], NULL); return TRUE; // was a slash command } else if (token == "discon") 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 35dde88d59..da15a065ab 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp @@ -201,13 +201,13 @@ Bool handleLobbySlashCommands(UnicodeString uText) else if (token == "fakecrc") { g_fakeCRC = !g_fakeCRC; - TheGameSpyInfo->addText(UnicodeString(L"Toggled CRC fakery"), GameSpyColor[GSCOLOR_DEFAULT], NULL); + TheGameSpyInfo->addText(L"Toggled CRC fakery", GameSpyColor[GSCOLOR_DEFAULT], NULL); return TRUE; // was a slash command } else if (token == "slots") { g_debugSlots = !g_debugSlots; - TheGameSpyInfo->addText(UnicodeString(L"Toggled SlotList debug"), GameSpyColor[GSCOLOR_DEFAULT], NULL); + TheGameSpyInfo->addText(L"Toggled SlotList debug", GameSpyColor[GSCOLOR_DEFAULT], NULL); return TRUE; // was a slash command } #endif @@ -1153,7 +1153,7 @@ void WOLLobbyMenuUpdate( WindowLayout * layout, void *userData) { case PEER_CLEAR: TheGameSpyInfo->clearStagingRoomList(); - //TheGameSpyInfo->addText( UnicodeString(L"gameList: PEER_CLEAR"), GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); + //TheGameSpyInfo->addText( L"gameList: PEER_CLEAR", GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); break; case PEER_ADD: case PEER_UPDATE: @@ -1256,29 +1256,29 @@ void WOLLobbyMenuUpdate( WindowLayout * layout, void *userData) if (resp.stagingRoom.action == PEER_ADD) { TheGameSpyInfo->addStagingRoom(room); - //TheGameSpyInfo->addText( UnicodeString(L"gameList: PEER_ADD"), GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); + //TheGameSpyInfo->addText( L"gameList: PEER_ADD", GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); } else { TheGameSpyInfo->updateStagingRoom(room); - //TheGameSpyInfo->addText( UnicodeString(L"gameList: PEER_UPDATE"), GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); + //TheGameSpyInfo->addText( L"gameList: PEER_UPDATE", GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); } } else { room.setID(resp.stagingRoom.id); TheGameSpyInfo->removeStagingRoom(room); - //TheGameSpyInfo->addText( UnicodeString(L"gameList: PEER_UPDATE FAILED"), GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); + //TheGameSpyInfo->addText( L"gameList: PEER_UPDATE FAILED", GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); } break; } case PEER_REMOVE: room.setID(resp.stagingRoom.id); TheGameSpyInfo->removeStagingRoom(room); - //TheGameSpyInfo->addText( UnicodeString(L"gameList: PEER_REMOVE"), GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); + //TheGameSpyInfo->addText( L"gameList: PEER_REMOVE", GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); break; default: - //TheGameSpyInfo->addText( UnicodeString(L"gameList: Unknown"), GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); + //TheGameSpyInfo->addText( L"gameList: Unknown", GameSpyColor[GSCOLOR_DEFAULT], listboxLobbyChat ); break; } } 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 0795b273aa..52955e817d 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLoginMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLoginMenu.cpp @@ -830,7 +830,7 @@ void WOLLoginMenuUpdate( WindowLayout * layout, void *userData) room.m_groupID = resp.groupRoom.id; room.m_maxWaiting = resp.groupRoom.maxWaiting; room.m_name = resp.groupRoomName.c_str(); - room.m_translatedName = UnicodeString(L"TEST"); + room.m_translatedName = L"TEST"; room.m_numGames = resp.groupRoom.numGames; room.m_numPlaying = resp.groupRoom.numPlaying; room.m_numWaiting = resp.groupRoom.numWaiting; 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 b1f89019e8..d793702957 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp @@ -1187,11 +1187,11 @@ void WOLQuickMatchMenuUpdate( WindowLayout * layout, void *userData) /* if (resp.joinGroupRoom.ok) { - TheGameSpyInfo->addText(UnicodeString(L"Joined group room"), GameSpyColor[GSCOLOR_DEFAULT], quickmatchTextWindow); + TheGameSpyInfo->addText(L"Joined group room", GameSpyColor[GSCOLOR_DEFAULT], quickmatchTextWindow); } else { - TheGameSpyInfo->addText(UnicodeString(L"Didn't join group room"), GameSpyColor[GSCOLOR_DEFAULT], quickmatchTextWindow); + TheGameSpyInfo->addText(L"Didn't join group room", GameSpyColor[GSCOLOR_DEFAULT], quickmatchTextWindow); } */ break; @@ -1284,7 +1284,7 @@ void WOLQuickMatchMenuUpdate( WindowLayout * layout, void *userData) switch( resp.qmStatus.status ) { case QM_IDLE: - //TheGameSpyInfo->addText(UnicodeString(L"Status: QM_IDLE"), GameSpyColor[GSCOLOR_DEFAULT], quickmatchTextWindow); + //TheGameSpyInfo->addText(L"Status: QM_IDLE", GameSpyColor[GSCOLOR_DEFAULT], quickmatchTextWindow); break; case QM_JOININGQMCHANNEL: TheGameSpyInfo->addText(TheGameText->fetch("QM:JOININGQMCHANNEL"), GameSpyColor[GSCOLOR_DEFAULT], quickmatchTextWindow); 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 4729001bf3..f098089806 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp @@ -243,7 +243,7 @@ static void updateNumPlayersOnline(void) //This was a Harvard initiated fix. headingStr.format(TheGameText->fetch("MOTD:NumPlayersHeading")); - while (headingStr.nextToken(&line, UnicodeString(L"\n"))) + while (headingStr.nextToken(&line, L"\n")) { if (line.getCharAt(line.getLength()-1) == '\r') line.removeLastChar(); // there is a trailing '\r' @@ -252,12 +252,12 @@ static void updateNumPlayersOnline(void) if (line.isEmpty()) { - line = UnicodeString(L" "); + line = L" "; } GadgetListBoxAddEntryText(listboxInfo, line, GameSpyColor[GSCOLOR_MOTD_HEADING], -1, -1); } - GadgetListBoxAddEntryText(listboxInfo, UnicodeString(L" "), GameSpyColor[GSCOLOR_MOTD_HEADING], -1, -1); + GadgetListBoxAddEntryText(listboxInfo, L" ", GameSpyColor[GSCOLOR_MOTD_HEADING], -1, -1); while (aMotd.nextToken(&aLine, "\n")) { @@ -475,7 +475,7 @@ void WOLWelcomeMenuInit( WindowLayout *layout, void *userData ) // Clear some defaults /* - UnicodeString questionMark = UnicodeString(L"?"); + UnicodeString questionMark = L"?"; GadgetStaticTextSetText(staticTextLastUpdated, questionMark); GadgetStaticTextSetText(staticTextLadderWins, questionMark); GadgetStaticTextSetText(staticTextLadderLosses, questionMark); @@ -641,7 +641,7 @@ void WOLWelcomeMenuUpdate( WindowLayout * layout, void *userData) room.m_groupID = resp.groupRoom.id; room.m_maxWaiting = resp.groupRoom.maxWaiting; room.m_name = resp.groupRoomName.c_str(); - room.m_translatedName = UnicodeString(L"TEST"); + room.m_translatedName = L"TEST"; room.m_numGames = resp.groupRoom.numGames; room.m_numPlaying = resp.groupRoom.numPlaying; room.m_numWaiting = resp.groupRoom.numWaiting; @@ -874,7 +874,7 @@ WindowMsgHandledType WOLWelcomeMenuSystem( GameWindow *window, UnsignedInt msg, else { GameSpyCurrentGroupRoomID = 0; - GSMessageBoxOk(UnicodeString(L"Oops"), UnicodeString(L"Unable to join title room"), NULL); + GSMessageBoxOk(L"Oops", L"Unable to join title room", NULL); } */ } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp index 4064c0f6ff..147c7368ba 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp @@ -2205,7 +2205,7 @@ Int GadgetListBoxAddEntryText( GameWindow *listbox, if (!listbox) return -1; if (text.isEmpty()) - text = UnicodeString(L" "); + text = L" "; Int index; AddMessageStruct addInfo; addInfo.row = row; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp index 5596456e06..a0d01be715 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp @@ -3790,17 +3790,17 @@ Bool GameWindowManager::initTestGUI( void ) 100, 100, &instData, &listData, NULL, TRUE ); - GadgetListBoxAddEntryText( window, UnicodeString(L"Listbox text"), + GadgetListBoxAddEntryText( window, L"Listbox text", TheWindowManager->winMakeColor( 255, 255, 255, 255 ), -1, 0 ); - GadgetListBoxAddEntryText( window, UnicodeString(L"More text"), + GadgetListBoxAddEntryText( window, L"More text", TheWindowManager->winMakeColor( 105, 105, 255, 255 ), -1, 0 ); - GadgetListBoxAddEntryText( window, UnicodeString(L"Nothing"), + GadgetListBoxAddEntryText( window, L"Nothing", TheWindowManager->winMakeColor( 105, 105, 255, 255 ), -1, 0 ); - GadgetListBoxAddEntryText( window, UnicodeString(L"Seasons"), + GadgetListBoxAddEntryText( window, L"Seasons", TheWindowManager->winMakeColor( 105, 205, 255, 255 ), -1, 0 ); - GadgetListBoxAddEntryText( window, UnicodeString(L"Misery"), + GadgetListBoxAddEntryText( window, L"Misery", TheWindowManager->winMakeColor( 235, 105, 255, 255 ), -1, 0 ); - GadgetListBoxAddEntryText( window, UnicodeString(L"Natural"), + GadgetListBoxAddEntryText( window, L"Natural", TheWindowManager->winMakeColor( 105, 205, 45, 255 ), -1, 0 ); window->winSetFont( TheFontLibrary->getFont( "Times New Roman", 12, FALSE ) ); @@ -3823,17 +3823,17 @@ Bool GameWindowManager::initTestGUI( void ) 100, 100, &instData, &listData, NULL, TRUE ); - GadgetListBoxAddEntryText( window, UnicodeString(L"Listbox text"), + GadgetListBoxAddEntryText( window, L"Listbox text", TheWindowManager->winMakeColor( 255, 255, 255, 255 ), -1, -1 ); - GadgetListBoxAddEntryText( window, UnicodeString(L"More text"), + GadgetListBoxAddEntryText( window, L"More text", TheWindowManager->winMakeColor( 105, 105, 255, 255 ), -1, -1 ); - GadgetListBoxAddEntryText( window, UnicodeString(L"Nothing"), + GadgetListBoxAddEntryText( window, L"Nothing", TheWindowManager->winMakeColor( 105, 105, 255, 255 ), -1, -1 ); - GadgetListBoxAddEntryText( window, UnicodeString(L"Seasons"), + GadgetListBoxAddEntryText( window, L"Seasons", TheWindowManager->winMakeColor( 105, 205, 255, 255 ), -1, -1 ); - GadgetListBoxAddEntryText( window, UnicodeString(L"Misery"), + GadgetListBoxAddEntryText( window, L"Misery", TheWindowManager->winMakeColor( 235, 105, 255, 255 ), -1, -1 ); - GadgetListBoxAddEntryText( window, UnicodeString(L"Natural"), + GadgetListBoxAddEntryText( window, L"Natural", TheWindowManager->winMakeColor( 105, 205, 45, 255 ), -1, -1 ); // make a vert slider diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp index 7a43a6b923..8c50f92f60 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp @@ -400,7 +400,7 @@ void SinglePlayerLoadScreen::init( GameInfo *game ) m_percent = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:Percent" )); DEBUG_ASSERTCRASH(m_percent, ("Can't initialize the m_percent for the single player loadscreen")); - GadgetStaticTextSetText(m_percent,UnicodeString(L"0%")); + GadgetStaticTextSetText(m_percent,L"0%"); m_percent->winHide(TRUE); m_objectiveWin = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "SinglePlayerLoadScreen.wnd:ObjectivesWin" )); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp index d7f8816f57..b663e8d3b4 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp @@ -1337,7 +1337,7 @@ void Mouse::setCursor( MouseCursor cursor ) &(cursorInfo->cursorTextColor), &(cursorInfo->cursorTextDropColor) ); else - setMouseText( UnicodeString( L"" ), NULL, NULL ); + setMouseText( L"", NULL, NULL ); } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/LanguageFilter.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/LanguageFilter.cpp index 1631d522fe..46b2f116c9 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/LanguageFilter.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/LanguageFilter.cpp @@ -86,7 +86,7 @@ void LanguageFilter::filterLine(UnicodeString &line) UnicodeString newLine(line); UnicodeString token(L""); - while (newLine.nextToken(&token, UnicodeString(L" ;,.!?:=\\/><`~()&^%#\n\t"))) { + while (newLine.nextToken(&token, L" ;,.!?:=\\/><`~()&^%#\n\t")) { wchar_t *pos = wcsstr(buf, token.str()); if (pos == NULL) { DEBUG_CRASH(("Couldn't find the token in its own string.")); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp index 501f23d244..d4eb297771 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp @@ -1281,7 +1281,7 @@ GameMessageDisposition SelectionTranslator::translateGameMessage(const GameMessa if ( !TheGameLogic->isInMultiplayerGame() ) { m_HandOfGodSelectionMode = !m_HandOfGodSelectionMode; - TheInGameUI->message( UnicodeString( L"Meta Hand-Of-God Mode is %s" ), m_HandOfGodSelectionMode ? L"ON" : L"OFF" ); + TheInGameUI->message( L"Meta Hand-Of-God Mode is %s", m_HandOfGodSelectionMode ? L"ON" : L"OFF" ); disp = DESTROY_MESSAGE; } break; @@ -1295,7 +1295,7 @@ GameMessageDisposition SelectionTranslator::translateGameMessage(const GameMessa if ( !TheGameLogic->isInMultiplayerGame() ) { m_HandOfGodSelectionMode = !m_HandOfGodSelectionMode; - TheInGameUI->message( UnicodeString( L"Hand-Of-God Mode is %s" ), m_HandOfGodSelectionMode ? L"ON" : L"OFF" ); + TheInGameUI->message( L"Hand-Of-God Mode is %s", m_HandOfGodSelectionMode ? L"ON" : L"OFF" ); disp = DESTROY_MESSAGE; } break; @@ -1309,7 +1309,7 @@ GameMessageDisposition SelectionTranslator::translateGameMessage(const GameMessa if ( !TheGameLogic->isInMultiplayerGame() ) { TheHurtSelectionMode = !TheHurtSelectionMode; - TheInGameUI->message( UnicodeString( L"Hurt-Me Mode is %s" ), TheHurtSelectionMode ? L"ON" : L"OFF" ); + TheInGameUI->message( L"Hurt-Me Mode is %s", TheHurtSelectionMode ? L"ON" : L"OFF" ); disp = DESTROY_MESSAGE; } break; @@ -1321,7 +1321,7 @@ GameMessageDisposition SelectionTranslator::translateGameMessage(const GameMessa case GameMessage::MSG_META_DEMO_DEBUG_SELECTION: { TheDebugSelectionMode = !TheDebugSelectionMode; - TheInGameUI->message( UnicodeString( L"Debug-Selected-Item Mode is %s" ), TheDebugSelectionMode ? L"ON" : L"OFF" ); + TheInGameUI->message( L"Debug-Selected-Item Mode is %s", TheDebugSelectionMode ? L"ON" : L"OFF" ); #ifdef DEBUG_OBJECT_ID_EXISTS TheObjectIDToDebug = INVALID_ID; #endif diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp index 44c7af5f3c..2f2bbea878 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp @@ -636,7 +636,7 @@ void OpenContain::removeFromContainViaIterator( ContainedItemsList::iterator it, /* #ifdef RTS_DEBUG - TheInGameUI->message( UnicodeString( L"'%S(%d)' no longer contains '%S(%d)'" ), + TheInGameUI->message( L"'%S(%d)' no longer contains '%S(%d)'", getObject()->getTemplate()->getName().str(), getObject()->getID(), itemToRemove->m_object->getTemplate()->getName().str(), diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp index b72cec84e1..df8b122663 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp @@ -1510,7 +1510,7 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) Dict d; d.setAsciiString(TheKey_playerName, "ReplayObserver"); d.setBool(TheKey_playerIsHuman, TRUE); - d.setUnicodeString(TheKey_playerDisplayName, UnicodeString(L"Observer")); + d.setUnicodeString(TheKey_playerDisplayName, L"Observer"); const PlayerTemplate* pt; pt = ThePlayerTemplateStore->findPlayerTemplate( TheNameKeyGenerator->nameToKey("FactionObserver") ); if (pt) diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp index 08ea00f639..bcf853c1ad 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp @@ -1704,7 +1704,7 @@ void W3DDisplay::draw( void ) if ( TheGameLogic->getFrame() > 0 && (TheGameLogic->getFrame() % interval) == 0 ) { TheStatDump.dumpStats( TRUE, TRUE ); - TheInGameUI->message( UnicodeString( L"-stats is running, at interval: %d." ), TheGlobalData->m_statsInterval ); + TheInGameUI->message( L"-stats is running, at interval: %d.", TheGlobalData->m_statsInterval ); } } #endif diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp index e221ed511a..0c72dbf244 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp @@ -324,7 +324,7 @@ static void loadText( char *filename, GameWindow *listboxText ) line.translate(buffer); line.trim(); if (line.isEmpty()) - line = UnicodeString(L" "); + line = L" "; GadgetListBoxAddEntryText(listboxText, line, color, -1, -1); } diff --git a/scripts/cpp/refactor_asciistring_unicodestring_instantiation.py b/scripts/cpp/refactor_asciistring_unicodestring_instantiation.py index b65ab95d2e..9d72bc150b 100644 --- a/scripts/cpp/refactor_asciistring_unicodestring_instantiation.py +++ b/scripts/cpp/refactor_asciistring_unicodestring_instantiation.py @@ -10,9 +10,9 @@ def fix_string(line: str, typename: str) -> str: # Build a regex that allows arbitrary whitespace - pattern = rf"""{typename}\s*\(\s*"([^"]*)"\s*\)""" + pattern = rf"""{typename}\s*\(\s*(L?)\s*"([^"]*)"\s*\)""" # Replace typename( "value" ) -> "value" - return re.sub(pattern, r'"\1"', line) + return re.sub(pattern, r'\1"\2"', line) def main(): @@ -40,7 +40,7 @@ def main(): with open(fileName, 'w', encoding="cp1252") as file: for line in lines: line = fix_string(line, 'AsciiString') - #line = fix_string(line, 'UnicodeString') + line = fix_string(line, 'UnicodeString') file.write(line) return From 94354fdf503fee7c6934d9f723dbf1c1f5cd1181 Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Mon, 1 Dec 2025 20:35:04 +0100 Subject: [PATCH 08/70] refactor(string): Fix constness of TheEmptyString (#1930) --- Core/GameEngine/Include/Common/AsciiString.h | 2 +- Core/GameEngine/Include/Common/UnicodeString.h | 2 +- Core/GameEngine/Source/Common/System/AsciiString.cpp | 2 +- Core/GameEngine/Source/Common/System/UnicodeString.cpp | 2 +- Generals/Code/GameEngine/Include/GameClient/IMEManager.h | 2 +- .../Source/GameClient/GUI/GUICallbacks/IMECandidate.cpp | 2 +- Generals/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp | 4 ++-- GeneralsMD/Code/GameEngine/Include/GameClient/IMEManager.h | 2 +- .../Source/GameClient/GUI/GUICallbacks/IMECandidate.cpp | 2 +- .../Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp | 4 ++-- 10 files changed, 12 insertions(+), 12 deletions(-) diff --git a/Core/GameEngine/Include/Common/AsciiString.h b/Core/GameEngine/Include/Common/AsciiString.h index 2b04b813d4..53c1e83fc6 100644 --- a/Core/GameEngine/Include/Common/AsciiString.h +++ b/Core/GameEngine/Include/Common/AsciiString.h @@ -125,7 +125,7 @@ class AsciiString string, so we don't need to construct temporaries for such a common thing. */ - static AsciiString TheEmptyString; + static const AsciiString TheEmptyString; /** Default constructor -- construct a new, empty AsciiString. diff --git a/Core/GameEngine/Include/Common/UnicodeString.h b/Core/GameEngine/Include/Common/UnicodeString.h index 78e0b3e180..ee362284f9 100644 --- a/Core/GameEngine/Include/Common/UnicodeString.h +++ b/Core/GameEngine/Include/Common/UnicodeString.h @@ -125,7 +125,7 @@ class UnicodeString string, so we don't need to construct temporaries for such a common thing. */ - static UnicodeString TheEmptyString; + static const UnicodeString TheEmptyString; /** Default constructor -- construct a new, empty UnicodeString. diff --git a/Core/GameEngine/Source/Common/System/AsciiString.cpp b/Core/GameEngine/Source/Common/System/AsciiString.cpp index 1be7898993..9828f7f1e2 100644 --- a/Core/GameEngine/Source/Common/System/AsciiString.cpp +++ b/Core/GameEngine/Source/Common/System/AsciiString.cpp @@ -49,7 +49,7 @@ // ----------------------------------------------------- -/*static*/ AsciiString AsciiString::TheEmptyString; +/*static*/ const AsciiString AsciiString::TheEmptyString; //----------------------------------------------------------------------------- inline char* skipSeps(char* p, const char* seps) diff --git a/Core/GameEngine/Source/Common/System/UnicodeString.cpp b/Core/GameEngine/Source/Common/System/UnicodeString.cpp index 31bf39d373..cb8669da34 100644 --- a/Core/GameEngine/Source/Common/System/UnicodeString.cpp +++ b/Core/GameEngine/Source/Common/System/UnicodeString.cpp @@ -49,7 +49,7 @@ // ----------------------------------------------------- -/*static*/ UnicodeString UnicodeString::TheEmptyString; +/*static*/ const UnicodeString UnicodeString::TheEmptyString; // ----------------------------------------------------- #ifdef RTS_DEBUG diff --git a/Generals/Code/GameEngine/Include/GameClient/IMEManager.h b/Generals/Code/GameEngine/Include/GameClient/IMEManager.h index be703e1bb4..7b245c5e84 100644 --- a/Generals/Code/GameEngine/Include/GameClient/IMEManager.h +++ b/Generals/Code/GameEngine/Include/GameClient/IMEManager.h @@ -88,7 +88,7 @@ class IMEManagerInterface : public SubsystemInterface virtual Int getCandidateCount() = 0; ///< Returns the total number of candidates - virtual UnicodeString*getCandidate( Int index ) = 0; ///< Returns the candidate string + virtual const UnicodeString* getCandidate( Int index ) = 0; ///< Returns the candidate string virtual Int getSelectedCandidateIndex() = 0; ///< Returns the indexed of the currently selected candidate virtual Int getCandidatePageSize() = 0; ///< Returns the page size for the candidates list virtual Int getCandidatePageStart() = 0; ///< Returns the index of the first visibel candidate diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/IMECandidate.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/IMECandidate.cpp index 9a03af81ba..3db793e6e7 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/IMECandidate.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/IMECandidate.cpp @@ -202,7 +202,7 @@ void IMECandidateTextAreaDraw( GameWindow *window, WinInstanceData *instData ) for ( Int i = 0; i < count; i++, y+= height ) { - UnicodeString *candidate = ime->getCandidate( first + i ); + const UnicodeString *candidate = ime->getCandidate( first + i ); Int tcolor, bcolor; if ( i == selected ) diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp index 96783bb42f..368f7bb33a 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp @@ -109,7 +109,7 @@ class IMEManager : public IMEManagerInterface virtual Int getIndexBase( void ); ///< Get index base for candidate list virtual Int getCandidateCount(); ///< Returns the total number of candidates - virtual UnicodeString*getCandidate( Int index ); ///< Returns the candidate string + virtual const UnicodeString* getCandidate( Int index ); ///< Returns the candidate string virtual Int getSelectedCandidateIndex(); ///< Returns the indexed of the currently selected candidate virtual Int getCandidatePageSize(); ///< Returns the page size for the candidates list virtual Int getCandidatePageStart(); ///< Returns the index of the first visibel candidate @@ -1525,7 +1525,7 @@ Int IMEManager::getCandidateCount() // IMEManager::getCandidate //============================================================================ -UnicodeString* IMEManager::getCandidate( Int index ) +const UnicodeString* IMEManager::getCandidate( Int index ) { if ( m_candidateString != NULL && index >=0 && index < m_candidateCount ) { diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/IMEManager.h b/GeneralsMD/Code/GameEngine/Include/GameClient/IMEManager.h index dace4e4092..5d91667527 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/IMEManager.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/IMEManager.h @@ -88,7 +88,7 @@ class IMEManagerInterface : public SubsystemInterface virtual Int getCandidateCount() = 0; ///< Returns the total number of candidates - virtual UnicodeString*getCandidate( Int index ) = 0; ///< Returns the candidate string + virtual const UnicodeString* getCandidate( Int index ) = 0; ///< Returns the candidate string virtual Int getSelectedCandidateIndex() = 0; ///< Returns the indexed of the currently selected candidate virtual Int getCandidatePageSize() = 0; ///< Returns the page size for the candidates list virtual Int getCandidatePageStart() = 0; ///< Returns the index of the first visibel candidate diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/IMECandidate.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/IMECandidate.cpp index 1765157c19..fee4cf69ae 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/IMECandidate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/IMECandidate.cpp @@ -202,7 +202,7 @@ void IMECandidateTextAreaDraw( GameWindow *window, WinInstanceData *instData ) for ( Int i = 0; i < count; i++, y+= height ) { - UnicodeString *candidate = ime->getCandidate( first + i ); + const UnicodeString *candidate = ime->getCandidate( first + i ); Int tcolor, bcolor; if ( i == selected ) diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp index 708802b0b3..ccc22ea9f7 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp @@ -109,7 +109,7 @@ class IMEManager : public IMEManagerInterface virtual Int getIndexBase( void ); ///< Get index base for candidate list virtual Int getCandidateCount(); ///< Returns the total number of candidates - virtual UnicodeString*getCandidate( Int index ); ///< Returns the candidate string + virtual const UnicodeString* getCandidate( Int index ); ///< Returns the candidate string virtual Int getSelectedCandidateIndex(); ///< Returns the indexed of the currently selected candidate virtual Int getCandidatePageSize(); ///< Returns the page size for the candidates list virtual Int getCandidatePageStart(); ///< Returns the index of the first visibel candidate @@ -1525,7 +1525,7 @@ Int IMEManager::getCandidateCount() // IMEManager::getCandidate //============================================================================ -UnicodeString* IMEManager::getCandidate( Int index ) +const UnicodeString* IMEManager::getCandidate( Int index ) { if ( m_candidateString != NULL && index >=0 && index < m_candidateCount ) { From cc9d649b7e37732059c31bdcc114fe0ba1a5495f Mon Sep 17 00:00:00 2001 From: Bobby Battista Date: Tue, 2 Dec 2025 13:10:39 -0500 Subject: [PATCH 09/70] build: Add WOW6432Node to registry path lookups for EA App install path detection (#1903) --- Generals/CMakeLists.txt | 5 +++++ GeneralsMD/CMakeLists.txt | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/Generals/CMakeLists.txt b/Generals/CMakeLists.txt index 964cb375bf..837065acba 100644 --- a/Generals/CMakeLists.txt +++ b/Generals/CMakeLists.txt @@ -20,6 +20,11 @@ if("${CMAKE_HOST_SYSTEM}" MATCHES "Windows" AND "${CMAKE_SYSTEM}" MATCHES "Windo get_filename_component(RTS_INSTALL_PREFIX_GENERALS "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Electronic Arts\\EA Games\\Generals;InstallPath]" ABSOLUTE CACHE) endif() + # Check the WOW6432Node registry path (for EA App on 64-bit Windows) + if(NOT RTS_INSTALL_PREFIX_GENERALS OR "${RTS_INSTALL_PREFIX_GENERALS}" STREQUAL "/registry") + get_filename_component(RTS_INSTALL_PREFIX_GENERALS "[HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Electronic Arts\\EA Games\\Generals;InstallPath]" ABSOLUTE CACHE) + endif() + # Check the "First Decade" registry path if(NOT RTS_INSTALL_PREFIX_GENERALS OR "${RTS_INSTALL_PREFIX_GENERALS}" STREQUAL "/registry") get_filename_component(RTS_INSTALL_PREFIX_GENERALS "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Electronic Arts\\EA Games\\Command and Conquer The First Decade;gr_folder]" ABSOLUTE CACHE) diff --git a/GeneralsMD/CMakeLists.txt b/GeneralsMD/CMakeLists.txt index 9c21d48887..830d0df785 100644 --- a/GeneralsMD/CMakeLists.txt +++ b/GeneralsMD/CMakeLists.txt @@ -19,6 +19,11 @@ if("${CMAKE_HOST_SYSTEM}" MATCHES "Windows" AND "${CMAKE_SYSTEM}" MATCHES "Windo get_filename_component(RTS_INSTALL_PREFIX_ZEROHOUR "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Electronic Arts\\EA Games\\Command and Conquer Generals Zero Hour;InstallPath]" ABSOLUTE CACHE) endif() + # Check the WOW6432Node registry path (for EA App on 64-bit Windows) + if(NOT RTS_INSTALL_PREFIX_ZEROHOUR OR "${RTS_INSTALL_PREFIX_ZEROHOUR}" STREQUAL "/registry") + get_filename_component(RTS_INSTALL_PREFIX_ZEROHOUR "[HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Electronic Arts\\EA Games\\Command and Conquer Generals Zero Hour;InstallPath]" ABSOLUTE CACHE) + endif() + # Check the "First Decade" registry path if(NOT RTS_INSTALL_PREFIX_ZEROHOUR OR "${RTS_INSTALL_PREFIX_ZEROHOUR}" STREQUAL "/registry") get_filename_component(RTS_INSTALL_PREFIX_ZEROHOUR "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Electronic Arts\\EA Games\\Command and Conquer The First Decade;zh_folder]" ABSOLUTE CACHE) From 29bf57a5ae276fd537f2dfe5910319f12f095e00 Mon Sep 17 00:00:00 2001 From: Caball009 <82909616+Caball009@users.noreply.github.com> Date: Tue, 2 Dec 2025 19:11:56 +0100 Subject: [PATCH 10/70] refactor(network): Replace implicit conversion from NULL to AsciiString in IPEnumeration::getMachineName (#1934) --- Core/GameEngine/Source/GameNetwork/IPEnumeration.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Core/GameEngine/Source/GameNetwork/IPEnumeration.cpp b/Core/GameEngine/Source/GameNetwork/IPEnumeration.cpp index 6d7256070c..9336b82064 100644 --- a/Core/GameEngine/Source/GameNetwork/IPEnumeration.cpp +++ b/Core/GameEngine/Source/GameNetwork/IPEnumeration.cpp @@ -172,12 +172,12 @@ AsciiString IPEnumeration::getMachineName( void ) int err = WSAStartup(verReq, &wsadata); if (err != 0) { - return NULL; + return ""; } if ((LOBYTE(wsadata.wVersion) != 2) || (HIBYTE(wsadata.wVersion) !=2)) { WSACleanup(); - return NULL; + return ""; } m_isWinsockInitialized = true; } @@ -187,7 +187,7 @@ AsciiString IPEnumeration::getMachineName( void ) if (gethostname(hostname, sizeof(hostname))) { DEBUG_LOG(("Failed call to gethostname; WSAGetLastError returned %d", WSAGetLastError())); - return NULL; + return ""; } return AsciiString(hostname); From 1ee44db7b04438f15fead6cb0913b9b0a683a6f2 Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Tue, 2 Dec 2025 19:23:43 +0100 Subject: [PATCH 11/70] refactor: Remove or replace some superfluous empty C strings (#1929) --- .../Source/GameNetwork/GameSpy/PeerDefs.cpp | 4 ++-- .../Source/GameNetwork/GameSpy/Thread/PeerThread.cpp | 12 ++++++------ .../GameSpy/Thread/PersistentStorageThread.cpp | 2 +- Core/GameEngine/Source/GameNetwork/LANAPI.cpp | 2 +- .../Source/GameNetwork/LANAPICallbacks.cpp | 4 +--- Core/GameEngine/Source/GameNetwork/LANGameInfo.cpp | 1 - .../Source/StdDevice/Common/StdBIGFileSystem.cpp | 4 ++-- .../Source/Win32Device/Common/Win32BIGFileSystem.cpp | 4 ++-- Core/Tools/CRCDiff/KVPair.cpp | 4 ++-- Core/Tools/CRCDiff/expander.cpp | 2 +- Core/Tools/Compress/Compress.cpp | 4 ++-- Core/Tools/PATCHGET/CHATAPI.cpp | 6 +++--- .../Include/GameLogic/Module/StructureToppleUpdate.h | 1 - .../Include/GameLogic/Module/UnitCrateCollide.h | 1 - .../GameEngine/Source/Common/INI/INIAnimation.cpp | 2 +- .../GameEngine/Source/GameClient/LanguageFilter.cpp | 4 ++-- .../Source/GameClient/System/ParticleSys.cpp | 2 +- .../GameLogic/Object/Behavior/SpawnBehavior.cpp | 2 +- .../GameLogic/Object/Create/GrantUpgradeCreate.cpp | 1 - .../Source/GameLogic/Object/Die/CreateCrateDie.cpp | 2 +- .../GameLogic/Object/Update/AutoDepositUpdate.cpp | 1 - .../Source/GameLogic/ScriptEngine/ScriptEngine.cpp | 2 +- .../Source/GameLogic/System/CrateSystem.cpp | 2 -- .../Source/W3DDevice/GameClient/W3DDisplay.cpp | 2 +- .../Libraries/Source/WWVegas/WW3D2/textureloader.cpp | 2 +- .../Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp | 2 +- .../Code/Tools/WorldBuilder/src/WorldBuilder.cpp | 2 +- .../Code/Tools/WorldBuilder/src/mapobjectprops.cpp | 2 +- .../Include/GameLogic/Module/StructureToppleUpdate.h | 1 - .../Include/GameLogic/Module/UnitCrateCollide.h | 1 - .../GameEngine/Source/Common/INI/INIAnimation.cpp | 2 +- .../GameEngine/Source/GameClient/LanguageFilter.cpp | 4 ++-- .../Source/GameClient/System/ParticleSys.cpp | 2 +- .../GameLogic/Object/Behavior/SpawnBehavior.cpp | 2 +- .../GameLogic/Object/Create/GrantUpgradeCreate.cpp | 1 - .../Source/GameLogic/Object/Die/CreateCrateDie.cpp | 2 +- .../GameLogic/Object/Update/AutoDepositUpdate.cpp | 1 - .../Source/GameLogic/Object/Update/OCLUpdate.cpp | 5 ++--- .../Source/GameLogic/ScriptEngine/ScriptEngine.cpp | 2 +- .../Source/GameLogic/System/CrateSystem.cpp | 2 -- .../GameEngine/Source/GameLogic/System/GameLogic.cpp | 2 +- .../Source/W3DDevice/GameClient/W3DDisplay.cpp | 2 +- .../Libraries/Source/WWVegas/WW3D2/textureloader.cpp | 6 +++--- .../Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp | 2 +- .../Code/Tools/WorldBuilder/src/WorldBuilder.cpp | 2 +- .../Code/Tools/WorldBuilder/src/mapobjectprops.cpp | 2 +- 46 files changed, 52 insertions(+), 68 deletions(-) diff --git a/Core/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp b/Core/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp index 5c9e661b59..047ddd1bb1 100644 --- a/Core/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp +++ b/Core/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp @@ -85,7 +85,7 @@ void GameSpyInfo::reset( void ) m_localStagingRoomID = 0; m_localStagingRoom.reset(); m_gotGroupRoomList = false; - m_localName = ""; + m_localName.clear(); m_localProfileID = 0; m_maxMessagesPerUpdate = 100; m_disallowAsainText = FALSE; @@ -186,7 +186,7 @@ void GameSpyInfo::setGameOptions( void ) req.gameOptions.numPlayers = 0; req.gameOptions.numObservers = 0; Int numOpenSlots = 0; - AsciiString playerInfo = ""; + AsciiString playerInfo; for (i=0; istopHostingAlready(peer); #ifdef DEBUG_LOGGING - AsciiString val = ""; + AsciiString val; #define ADD(x) { qr2_buffer_add(buffer, x); val = x; } #define ADDINT(x) { qr2_buffer_add_int(buffer, x); val.format("%d",x); } #else @@ -852,7 +852,7 @@ static void QRPlayerKeyCallback #undef ADD #undef ADDINT #ifdef DEBUG_LOGGING - AsciiString val = ""; + AsciiString val; #define ADD(x) { qr2_buffer_add(buffer, x); val = x; } #define ADDINT(x) { qr2_buffer_add_int(buffer, x); val.format("%d",x); } #else @@ -1095,7 +1095,7 @@ static SerialAuthResult doCDKeyAuthentication( PEER peer ) if (!peer) return retval; - AsciiString s = ""; + AsciiString s; if (GetStringFromRegistry("\\ergc", "", s) && s.isNotEmpty()) { #ifdef SERVER_DEBUGGING diff --git a/Core/GameEngine/Source/GameNetwork/GameSpy/Thread/PersistentStorageThread.cpp b/Core/GameEngine/Source/GameNetwork/GameSpy/Thread/PersistentStorageThread.cpp index 1f2da6acf8..d21dc20533 100644 --- a/Core/GameEngine/Source/GameNetwork/GameSpy/Thread/PersistentStorageThread.cpp +++ b/Core/GameEngine/Source/GameNetwork/GameSpy/Thread/PersistentStorageThread.cpp @@ -1315,7 +1315,7 @@ PSPlayerStats GameSpyPSMessageQueueInterface::parsePlayerKVPairs( std::string kv std::string GameSpyPSMessageQueueInterface::formatPlayerKVPairs( PSPlayerStats stats ) { char kvbuf[256]; - std::string s = ""; + std::string s; PerGeneralMap::iterator it; ITERATE_OVER(wins); diff --git a/Core/GameEngine/Source/GameNetwork/LANAPI.cpp b/Core/GameEngine/Source/GameNetwork/LANAPI.cpp index 9549e58c78..86db49cbc7 100644 --- a/Core/GameEngine/Source/GameNetwork/LANAPI.cpp +++ b/Core/GameEngine/Source/GameNetwork/LANAPI.cpp @@ -638,7 +638,7 @@ void LANAPI::RequestGameJoin( LANGameInfo *game, UnsignedInt ip /* = 0 */ ) msg.GameToJoin.exeCRC = TheGlobalData->m_exeCRC; msg.GameToJoin.iniCRC = TheGlobalData->m_iniCRC; - AsciiString s = ""; + AsciiString s; GetStringFromRegistry("\\ergc", "", s); strlcpy(msg.GameToJoin.serial, s.str(), ARRAY_SIZE(msg.GameToJoin.serial)); diff --git a/Core/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp b/Core/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp index 9c9fd2a0a0..ee3c87e3bf 100644 --- a/Core/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp +++ b/Core/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp @@ -686,9 +686,7 @@ void LANAPI::OnChat( UnicodeString player, UnsignedInt ip, UnicodeString message switch (format) { case LANAPIInterface::LANCHAT_SYSTEM: - unicodeChat = L""; - unicodeChat.concat(message); - unicodeChat.concat(L""); + unicodeChat = message; index =GadgetListBoxAddEntryText(chatWindow, unicodeChat, chatSystemColor, -1, -1); break; case LANAPIInterface::LANCHAT_EMOTE: diff --git a/Core/GameEngine/Source/GameNetwork/LANGameInfo.cpp b/Core/GameEngine/Source/GameNetwork/LANGameInfo.cpp index 2c5a74ec79..c86a8d844a 100644 --- a/Core/GameEngine/Source/GameNetwork/LANGameInfo.cpp +++ b/Core/GameEngine/Source/GameNetwork/LANGameInfo.cpp @@ -213,7 +213,6 @@ void LANDisplayGameList( GameWindow *gameListbox, LANGameInfo *gameList ) while (gameList) { UnicodeString txtGName; - txtGName = L""; if( gameList->isGameInProgress() ) { txtGName.concat(L"["); diff --git a/Core/GameEngineDevice/Source/StdDevice/Common/StdBIGFileSystem.cpp b/Core/GameEngineDevice/Source/StdDevice/Common/StdBIGFileSystem.cpp index 079f00a307..13f7045bb8 100644 --- a/Core/GameEngineDevice/Source/StdDevice/Common/StdBIGFileSystem.cpp +++ b/Core/GameEngineDevice/Source/StdDevice/Common/StdBIGFileSystem.cpp @@ -63,8 +63,8 @@ void StdBIGFileSystem::init() { AsciiString installPath; GetStringFromGeneralsRegistry("", "InstallPath", installPath ); //@todo this will need to be ramped up to a crash for release - DEBUG_ASSERTCRASH(installPath != "", ("Be 1337! Go install Generals!")); - if (installPath!="") + DEBUG_ASSERTCRASH(!installPath.isEmpty(), ("Be 1337! Go install Generals!")); + if (!installPath.isEmpty()) loadBigFilesFromDirectory(installPath, "*.big"); #endif } diff --git a/Core/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp b/Core/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp index 8ced8a7b36..5aaedc2f1b 100644 --- a/Core/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp +++ b/Core/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp @@ -64,8 +64,8 @@ void Win32BIGFileSystem::init() { AsciiString installPath; GetStringFromGeneralsRegistry("", "InstallPath", installPath ); //@todo this will need to be ramped up to a crash for release - DEBUG_ASSERTCRASH(installPath != "", ("Be 1337! Go install Generals!")); - if (installPath!="") + DEBUG_ASSERTCRASH(!installPath.isEmpty(), ("Be 1337! Go install Generals!")); + if (!installPath.isEmpty()) loadBigFilesFromDirectory(installPath, "*.big"); #endif } diff --git a/Core/Tools/CRCDiff/KVPair.cpp b/Core/Tools/CRCDiff/KVPair.cpp index 4aa7c4a968..bd7b396195 100644 --- a/Core/Tools/CRCDiff/KVPair.cpp +++ b/Core/Tools/CRCDiff/KVPair.cpp @@ -31,7 +31,7 @@ std::string intToString(int val) { - std::string s = ""; + std::string s; bool neg = (val < 0); if (val < 0) { @@ -134,7 +134,7 @@ void KVPairClass::readFromFile( const std::string& in, const std::string& delim FILE *fp = fopen(in.c_str(), "rb"); if (fp) { - std::string s = ""; + std::string s; fseek(fp, 0, SEEK_END); int len = ftell(fp); fseek(fp, 0, SEEK_SET); diff --git a/Core/Tools/CRCDiff/expander.cpp b/Core/Tools/CRCDiff/expander.cpp index 9e7961d5d0..f1d4d07c78 100644 --- a/Core/Tools/CRCDiff/expander.cpp +++ b/Core/Tools/CRCDiff/expander.cpp @@ -99,7 +99,7 @@ void Expander::expand( const std::string& input, else { std::string toExpand = it->second; - std::string expanded = ""; + std::string expanded; //DEBUG_LOG(("###### expanding '%s'", toExpand.c_str())); expand(toExpand, expanded, stripUnknown); //DEBUG_LOG(("###### expanded '%s'", expanded.c_str())); diff --git a/Core/Tools/Compress/Compress.cpp b/Core/Tools/Compress/Compress.cpp index a9119e7b25..323d557d42 100644 --- a/Core/Tools/Compress/Compress.cpp +++ b/Core/Tools/Compress/Compress.cpp @@ -52,8 +52,8 @@ void dumpHelp(const char *exe) int main(int argc, char **argv) { - std::string inFile = ""; - std::string outFile = ""; + std::string inFile; + std::string outFile; CompressionType compressType = CompressionManager::getPreferredCompression(); for (int i=1; inewTemplate( name ); - DEBUG_ASSERTCRASH( animTemplate, ("INI""parseAnim2DDefinition - unable to allocate animation template for '%s'", + DEBUG_ASSERTCRASH( animTemplate, ("INI::parseAnim2DDefinition - unable to allocate animation template for '%s'", name.str()) ); } diff --git a/Generals/Code/GameEngine/Source/GameClient/LanguageFilter.cpp b/Generals/Code/GameEngine/Source/GameClient/LanguageFilter.cpp index 15ef18db3b..9a1a4e6605 100644 --- a/Generals/Code/GameEngine/Source/GameClient/LanguageFilter.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/LanguageFilter.cpp @@ -84,7 +84,7 @@ void LanguageFilter::filterLine(UnicodeString &line) wcscpy(buf, line.str()); UnicodeString newLine(line); - UnicodeString token(L""); + UnicodeString token; while (newLine.nextToken(&token, L" ;,.!?:=\\/><`~()&^%#\n\t")) { wchar_t *pos = wcsstr(buf, token.str()); @@ -112,7 +112,7 @@ void LanguageFilter::filterLine(UnicodeString &line) void LanguageFilter::unHaxor(UnicodeString &word) { Int len = word.getLength(); - UnicodeString newWord(L""); + UnicodeString newWord; for (Int i = 0; i < len; ++i) { wchar_t c = word.getCharAt(i); if ((c == L'p') || (c == L'P')) { diff --git a/Generals/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp b/Generals/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp index 12104ec64b..5e4c0e8b4d 100644 --- a/Generals/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp @@ -3354,7 +3354,7 @@ void ParticleSystemManager::xfer( Xfer *xfer ) // ignore destroyed systems and non-saveable systems if( system->isDestroyed() == TRUE || system->isSaveable() == FALSE ) { - AsciiString mtString = ""; + AsciiString mtString; xfer->xferAsciiString(&mtString); // write null string as key for destroyed system. continue; } diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp index 350e7f7866..294fad763d 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp @@ -530,7 +530,7 @@ Object *SpawnBehavior::reclaimOrphanSpawn( void ) // OrphanData orphanData; - AsciiString prevName = ""; + AsciiString prevName; for (std::vector::const_iterator tempName = md->m_spawnTemplateNameData.begin(); tempName != md->m_spawnTemplateNameData.end(); ++tempName) diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Create/GrantUpgradeCreate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Create/GrantUpgradeCreate.cpp index fc806b6058..c8bcb5ded2 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Create/GrantUpgradeCreate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Create/GrantUpgradeCreate.cpp @@ -41,7 +41,6 @@ // ------------------------------------------------------------------------------------------------ GrantUpgradeCreateModuleData::GrantUpgradeCreateModuleData() { - m_upgradeName = ""; } // ------------------------------------------------------------------------------------------------ diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Die/CreateCrateDie.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Die/CreateCrateDie.cpp index 6f4c88aab9..ee05f5bd9f 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Die/CreateCrateDie.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Die/CreateCrateDie.cpp @@ -179,7 +179,7 @@ Object *CreateCrateDie::createCrate( CrateTemplate const *currentCrateData ) // CreationChance is used for the success of this block, but this block can have any number of potential actual crates Real multipleCratePick = GameLogicRandomValueReal( 0, 1 ); Real multipleCrateRunningTotal = 0; - AsciiString crateName = ""; + AsciiString crateName; for( crateCreationEntryConstIterator iter = currentCrateData->m_possibleCrates.begin(); iter != currentCrateData->m_possibleCrates.end(); diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AutoDepositUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AutoDepositUpdate.cpp index 02e50f9d79..3daca28f94 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AutoDepositUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AutoDepositUpdate.cpp @@ -71,7 +71,6 @@ 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() ); diff --git a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp index 95b6957d5b..6ff9d7e76e 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp @@ -9080,7 +9080,7 @@ void _writeSingleParticleSystem( File *out, ParticleSystemTemplate *templ ) // these were all originally << (feed-operator for streams) // I might come back and re-write this later, if there are enough complaints. ;-) jkmcd // in the meantime, move along... - std::string thisEntry = ""; + std::string thisEntry; thisEntry.append(HEADER).append(SEP_SPACE).append(templ->getName().str()).append(SEP_EOL); thisEntry.append(SEP_HEAD).append(F_PRIORITY).append(EQ_WITH_SPACES).append(ParticlePriorityNames[templ->m_priority]).append(SEP_EOL); thisEntry.append(SEP_HEAD).append(F_ISONESHOT).append(EQ_WITH_SPACES).append((templ->m_isOneShot ? STR_TRUE : STR_FALSE)).append(SEP_EOL); diff --git a/Generals/Code/GameEngine/Source/GameLogic/System/CrateSystem.cpp b/Generals/Code/GameEngine/Source/GameLogic/System/CrateSystem.cpp index 8865ffbf9e..810e5d07b4 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/System/CrateSystem.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/System/CrateSystem.cpp @@ -190,8 +190,6 @@ const FieldParse CrateTemplate::TheCrateTemplateFieldParseTable[] = CrateTemplate::CrateTemplate() { - m_name = ""; - m_creationChance = 0; CLEAR_KINDOFMASK(m_killedByTypeKindof); m_veterancyLevel = LEVEL_INVALID; diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp index 42dcd033db..b8ce435c76 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp @@ -1326,7 +1326,7 @@ void W3DDisplay::gatherDebugStats( void ) // Network outgoing bandwidth stats // unibuffer.format(L"OUT: 0.0 bytes/sec, 0.0 packets/sec"); // m_displayStrings[NetOutgoing]->setText( unibuffer ); - unibuffer.format(L""); + unibuffer.clear(); // unibuffer.format(L"Network not present"); m_displayStrings[NetOutgoing]->setText(unibuffer); m_displayStrings[NetIncoming]->setText(unibuffer); diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/textureloader.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/textureloader.cpp index 0a8101085d..ced18c40aa 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/textureloader.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/textureloader.cpp @@ -992,7 +992,7 @@ void TextureLoadTaskClass::Init(TextureBaseClass* tc,bool high_priority) { // Make sure texture has a filename. REF_PTR_SET(Texture,tc); - //WWASSERT(Texture->Get_Full_Path() != NULL); + //WWASSERT(!Texture->Get_Full_Path().Is_Empty()); Reduction=Texture->Get_Reduction(); HighPriorityRequested=high_priority; diff --git a/Generals/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp b/Generals/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp index 78fd55aeec..9a8ed55116 100644 --- a/Generals/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp @@ -2183,7 +2183,7 @@ Bool WorldHeightMapEdit::selectInvalidTeam(void) } } - AsciiString report = ""; + AsciiString report; AsciiString line; #if 0 diff --git a/Generals/Code/Tools/WorldBuilder/src/WorldBuilder.cpp b/Generals/Code/Tools/WorldBuilder/src/WorldBuilder.cpp index 577eedc7d4..0759139665 100644 --- a/Generals/Code/Tools/WorldBuilder/src/WorldBuilder.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/WorldBuilder.cpp @@ -681,7 +681,7 @@ void CWorldBuilderApp::OnFileOpen() #endif CFileStatus status; - if (m_currentDirectory != "") try { + if (!m_currentDirectory.isEmpty()) try { if (CFile::GetStatus(m_currentDirectory.str(), status)) { if (status.m_attribute & CFile::directory) { ::SetCurrentDirectory(m_currentDirectory.str()); diff --git a/Generals/Code/Tools/WorldBuilder/src/mapobjectprops.cpp b/Generals/Code/Tools/WorldBuilder/src/mapobjectprops.cpp index cad7018834..fe8c46bd54 100644 --- a/Generals/Code/Tools/WorldBuilder/src/mapobjectprops.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/mapobjectprops.cpp @@ -376,7 +376,7 @@ void MapObjectProps::_DictToTeam(void) void MapObjectProps::_DictToName(void) { - AsciiString name = ""; + AsciiString name; Bool exists; if (m_dictToEdit) { name = m_dictToEdit->getAsciiString(TheKey_objectName, &exists); diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/StructureToppleUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/StructureToppleUpdate.h index 916b28ac4e..9e8931794d 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/StructureToppleUpdate.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/StructureToppleUpdate.h @@ -119,7 +119,6 @@ class StructureToppleUpdateModuleData : public UpdateModuleData m_toppleDoneFXList = NULL; m_toppleFXList = NULL; m_crushingFXList = NULL; - m_crushingWeaponName.set(""); for (int i = 0; i < ST_PHASE_COUNT; ++i) { diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/UnitCrateCollide.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/UnitCrateCollide.h index e4595a174a..d0f90a7051 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/UnitCrateCollide.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/UnitCrateCollide.h @@ -46,7 +46,6 @@ class UnitCrateCollideModuleData : public CrateCollideModuleData UnitCrateCollideModuleData() { m_unitCount = 0; - m_unitType = ""; } static void buildFieldParse(MultiIniFieldParse& p) diff --git a/GeneralsMD/Code/GameEngine/Source/Common/INI/INIAnimation.cpp b/GeneralsMD/Code/GameEngine/Source/Common/INI/INIAnimation.cpp index 78bc98c20d..7300b1ebc7 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/INI/INIAnimation.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/INI/INIAnimation.cpp @@ -65,7 +65,7 @@ void INI::parseAnim2DDefinition( INI* ini ) // item not found, create a new one animTemplate = TheAnim2DCollection->newTemplate( name ); - DEBUG_ASSERTCRASH( animTemplate, ("INI""parseAnim2DDefinition - unable to allocate animation template for '%s'", + DEBUG_ASSERTCRASH( animTemplate, ("INI::parseAnim2DDefinition - unable to allocate animation template for '%s'", name.str()) ); } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/LanguageFilter.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/LanguageFilter.cpp index 46b2f116c9..6185748421 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/LanguageFilter.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/LanguageFilter.cpp @@ -84,7 +84,7 @@ void LanguageFilter::filterLine(UnicodeString &line) wcscpy(buf, line.str()); UnicodeString newLine(line); - UnicodeString token(L""); + UnicodeString token; while (newLine.nextToken(&token, L" ;,.!?:=\\/><`~()&^%#\n\t")) { wchar_t *pos = wcsstr(buf, token.str()); @@ -112,7 +112,7 @@ void LanguageFilter::filterLine(UnicodeString &line) void LanguageFilter::unHaxor(UnicodeString &word) { Int len = word.getLength(); - UnicodeString newWord(L""); + UnicodeString newWord; for (Int i = 0; i < len; ++i) { wchar_t c = word.getCharAt(i); if ((c == L'p') || (c == L'P')) { diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp index 03d7c5448a..d847d9df59 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp @@ -3256,7 +3256,7 @@ void ParticleSystemManager::xfer( Xfer *xfer ) // ignore destroyed systems and non-saveable systems if( system->isDestroyed() == TRUE || system->isSaveable() == FALSE ) { - AsciiString mtString = ""; + AsciiString mtString; xfer->xferAsciiString(&mtString); // write null string as key for destroyed system. continue; } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp index b645f454b1..81ca57e86e 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp @@ -574,7 +574,7 @@ Object *SpawnBehavior::reclaimOrphanSpawn( void ) // OrphanData orphanData; - AsciiString prevName = ""; + AsciiString prevName; for (std::vector::const_iterator tempName = md->m_spawnTemplateNameData.begin(); tempName != md->m_spawnTemplateNameData.end(); ++tempName) diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Create/GrantUpgradeCreate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Create/GrantUpgradeCreate.cpp index b8ab4c3dff..2c4e347f27 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Create/GrantUpgradeCreate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Create/GrantUpgradeCreate.cpp @@ -41,7 +41,6 @@ // ------------------------------------------------------------------------------------------------ GrantUpgradeCreateModuleData::GrantUpgradeCreateModuleData() { - m_upgradeName = ""; } // ------------------------------------------------------------------------------------------------ diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Die/CreateCrateDie.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Die/CreateCrateDie.cpp index 7fead542b6..de3a54c8c2 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Die/CreateCrateDie.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Die/CreateCrateDie.cpp @@ -179,7 +179,7 @@ Object *CreateCrateDie::createCrate( CrateTemplate const *currentCrateData ) // CreationChance is used for the success of this block, but this block can have any number of potential actual crates Real multipleCratePick = GameLogicRandomValueReal( 0, 1 ); Real multipleCrateRunningTotal = 0; - AsciiString crateName = ""; + AsciiString crateName; for( crateCreationEntryConstIterator iter = currentCrateData->m_possibleCrates.begin(); iter != currentCrateData->m_possibleCrates.end(); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AutoDepositUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AutoDepositUpdate.cpp index dbda4390ce..6c12c9a553 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AutoDepositUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AutoDepositUpdate.cpp @@ -72,7 +72,6 @@ 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() ); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/OCLUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/OCLUpdate.cpp index e8e5d1346f..a05d9ff2b3 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/OCLUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/OCLUpdate.cpp @@ -46,8 +46,7 @@ void parseFactionObjectCreationList( INI *ini, void *instance, void *store, const void *userData ) { OCLUpdateModuleData::FactionOCLInfo info; - info.m_factionName = ""; - info.m_ocl = 0; + info.m_ocl = NULL; const char *token = ini->getNextToken( ini->getSepsColon() ); @@ -199,7 +198,7 @@ UpdateSleepTime OCLUpdate::update( void ) // If this is faction triggered, search through the faction specific OCLs to find the match if (data->m_isFactionTriggered) { - std::string playerFactionName(""); + std::string playerFactionName; Player *player = getObject()->getControllingPlayer(); if (!player) return UPDATE_SLEEP_NONE; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp index 41b35abe0b..ee2d05bf22 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp @@ -9803,7 +9803,7 @@ void _writeSingleParticleSystem( File *out, ParticleSystemTemplate *templ ) // these were all originally << (feed-operator for streams) // I might come back and re-write this later, if there are enough complaints. ;-) jkmcd // in the meantime, move along... - std::string thisEntry = ""; + std::string thisEntry; thisEntry.append(HEADER).append(SEP_SPACE).append(templ->getName().str()).append(SEP_EOL); thisEntry.append(SEP_HEAD).append(F_PRIORITY).append(EQ_WITH_SPACES).append(ParticlePriorityNames[templ->m_priority]).append(SEP_EOL); thisEntry.append(SEP_HEAD).append(F_ISONESHOT).append(EQ_WITH_SPACES).append((templ->m_isOneShot ? STR_TRUE : STR_FALSE)).append(SEP_EOL); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/CrateSystem.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/CrateSystem.cpp index baf563ea46..33eb9cef8e 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/CrateSystem.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/CrateSystem.cpp @@ -190,8 +190,6 @@ const FieldParse CrateTemplate::TheCrateTemplateFieldParseTable[] = CrateTemplate::CrateTemplate() { - m_name = ""; - m_creationChance = 0; CLEAR_KINDOFMASK(m_killedByTypeKindof); m_veterancyLevel = LEVEL_INVALID; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp index df8b122663..a6001e2206 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp @@ -3449,7 +3449,7 @@ static void unitTimings(void) { if (sides[side] == "*") { - if ( btt->getDefaultOwningSide() == ("") )// wildcard for unspecified side + if ( btt->getDefaultOwningSide().isEmpty() )// wildcard for unspecified side unspecified = TRUE; else continue; diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp index bcf853c1ad..6f3c9ba6eb 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp @@ -1378,7 +1378,7 @@ void W3DDisplay::gatherDebugStats( void ) // Network outgoing bandwidth stats // unibuffer.format(L"OUT: 0.0 bytes/sec, 0.0 packets/sec"); // m_displayStrings[NetOutgoing]->setText( unibuffer ); - unibuffer.format(L""); + unibuffer.clear(); // unibuffer.format(L"Network not present"); m_displayStrings[NetOutgoing]->setText(unibuffer); m_displayStrings[NetIncoming]->setText(unibuffer); diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/textureloader.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/textureloader.cpp index 12326a1f25..3b1fcfa61d 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/textureloader.cpp +++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/textureloader.cpp @@ -1095,7 +1095,7 @@ void TextureLoadTaskClass::Init(TextureBaseClass* tc, TaskType type, PriorityTyp REF_PTR_SET(Texture, tc); // Make sure texture has a filename. - WWASSERT(Texture->Get_Full_Path() != ""); + WWASSERT(!Texture->Get_Full_Path().Is_Empty()); Type = type; Priority = priority; @@ -2065,7 +2065,7 @@ void CubeTextureLoadTaskClass::Init(TextureBaseClass* tc, TaskType type, Priorit REF_PTR_SET(Texture, tc); // Make sure texture has a filename. - WWASSERT(Texture->Get_Full_Path() != ""); + WWASSERT(!Texture->Get_Full_Path().Is_Empty()); Type = type; Priority = priority; @@ -2476,7 +2476,7 @@ void VolumeTextureLoadTaskClass::Init(TextureBaseClass* tc, TaskType type, Prior REF_PTR_SET(Texture, tc); // Make sure texture has a filename. - WWASSERT(Texture->Get_Full_Path() != ""); + WWASSERT(!Texture->Get_Full_Path().Is_Empty()); Type = type; Priority = priority; diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp index c1b902172c..42564af5e6 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp @@ -2155,7 +2155,7 @@ Bool WorldHeightMapEdit::selectInvalidTeam(void) } } - AsciiString report = ""; + AsciiString report; AsciiString line; #if 0 diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilder.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilder.cpp index 8b01c80c83..ba2930f30a 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilder.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilder.cpp @@ -703,7 +703,7 @@ void CWorldBuilderApp::OnFileOpen() #endif CFileStatus status; - if (m_currentDirectory != "") try { + if (!m_currentDirectory.isEmpty()) try { if (CFile::GetStatus(m_currentDirectory.str(), status)) { if (status.m_attribute & CFile::directory) { ::SetCurrentDirectory(m_currentDirectory.str()); diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/mapobjectprops.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/mapobjectprops.cpp index a0d7487fbe..9917fa1ec4 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/mapobjectprops.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/mapobjectprops.cpp @@ -221,7 +221,7 @@ void MapObjectProps::_DictToTeam(void) /// Move data from object to dialog controls void MapObjectProps::_DictToName(void) { - AsciiString name = ""; + AsciiString name; Bool exists; if (m_dictToEdit) { From d81e7435dfc6b695adefca31df87749a6ef3ca5c Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Tue, 2 Dec 2025 19:36:24 +0100 Subject: [PATCH 12/70] bugfix(movie): Fix Campaign, Challenge, Score movie cancellation or decompression artifacts when tabbing out of the game (#1927) --- .../GUI/GUICallbacks/Menus/ScoreScreen.cpp | 10 +++------ .../Source/GameClient/GUI/LoadScreen.cpp | 10 +++------ .../GUI/GUICallbacks/Menus/ScoreScreen.cpp | 10 +++------ .../Source/GameClient/GUI/LoadScreen.cpp | 22 +++++-------------- 4 files changed, 15 insertions(+), 37 deletions(-) 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 8ff4cd41b5..b1f1ec6366 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp @@ -633,6 +633,9 @@ void PlayMovieAndBlock(AsciiString movieTitle) return; } + // TheSuperHackers @bugfix Originally this movie render loop stopped rendering when the game window was inactive. + // This either skipped the movie or caused decompression artifacts. Now the video just keeps playing until it done. + GameWindow *movieWindow = s_blankLayout->getFirstWindow(); TheWritableGlobalData->m_loadScreenRender = TRUE; while (videoStream->frameIndex() < videoStream->frameCount() - 1) @@ -645,13 +648,6 @@ void PlayMovieAndBlock(AsciiString movieTitle) continue; } - if (!TheGameEngine->isActive()) - { //we are alt-tabbed out, so just increment the frame - videoStream->frameNext(); - videoStream->frameDecompress(); - continue; - } - videoStream->frameDecompress(); videoStream->frameRender(videoBuffer); videoStream->frameNext(); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp index a1011520c0..bc158c26a4 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp @@ -483,6 +483,9 @@ void SinglePlayerLoadScreen::init( GameInfo *game ) if(TheGameLODManager && TheGameLODManager->didMemPass()) { + // TheSuperHackers @bugfix Originally this movie render loop stopped rendering when the game window was inactive. + // This either skipped the movie or caused decompression artifacts. Now the video just keeps playing until it done. + Int progressUpdateCount = m_videoStream->frameCount() / FRAME_FUDGE_ADD; Int shiftedPercent = -FRAME_FUDGE_ADD + 1; while (m_videoStream->frameIndex() < m_videoStream->frameCount() - 1 ) @@ -495,13 +498,6 @@ void SinglePlayerLoadScreen::init( GameInfo *game ) continue; } - if (!TheGameEngine->isActive()) - { //we are alt-tabbed out, so just increment the frame - m_videoStream->frameNext(); - m_videoStream->frameDecompress(); - continue; - } - m_videoStream->frameDecompress(); m_videoStream->frameRender(m_videoBuffer); moveWindows( m_videoStream->frameIndex()); 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 1ab780e3ac..f57594d24e 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp @@ -727,6 +727,9 @@ void PlayMovieAndBlock(AsciiString movieTitle) return; } + // TheSuperHackers @bugfix Originally this movie render loop stopped rendering when the game window was inactive. + // This either skipped the movie or caused decompression artifacts. Now the video just keeps playing until it done. + GameWindow *movieWindow = s_blankLayout->getFirstWindow(); TheWritableGlobalData->m_loadScreenRender = TRUE; while (videoStream->frameIndex() < videoStream->frameCount() - 1) @@ -739,13 +742,6 @@ void PlayMovieAndBlock(AsciiString movieTitle) continue; } - if (!TheGameEngine->isActive()) - { //we are alt-tabbed out, so just increment the frame - videoStream->frameNext(); - videoStream->frameDecompress(); - continue; - } - videoStream->frameDecompress(); videoStream->frameRender(videoBuffer); videoStream->frameNext(); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp index 8c50f92f60..5c8bc3430b 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp @@ -526,6 +526,9 @@ void SinglePlayerLoadScreen::init( GameInfo *game ) if(TheGameLODManager && TheGameLODManager->didMemPass()) { + // TheSuperHackers @bugfix Originally this movie render loop stopped rendering when the game window was inactive. + // This either skipped the movie or caused decompression artifacts. Now the video just keeps playing until it done. + Int progressUpdateCount = m_videoStream->frameCount() / FRAME_FUDGE_ADD; Int shiftedPercent = -FRAME_FUDGE_ADD + 1; while (m_videoStream->frameIndex() < m_videoStream->frameCount() - 1 ) @@ -538,15 +541,6 @@ void SinglePlayerLoadScreen::init( GameInfo *game ) continue; } - if (!TheGameEngine->isActive()) - {/* //we are alt-tabbed out, so just increment the frame - m_videoStream->frameNext(); - m_videoStream->frameDecompress();*/ - - //Changing for MissionDisk, just skip to end. - break; - } - m_videoStream->frameDecompress(); m_videoStream->frameRender(m_videoBuffer); @@ -1046,6 +1040,9 @@ void ChallengeLoadScreen::init( GameInfo *game ) if(TheGameLODManager && TheGameLODManager->didMemPass()) { + // TheSuperHackers @bugfix Originally this movie render loop stopped rendering when the game window was inactive. + // This either skipped the movie or caused decompression artifacts. Now the video just keeps playing until it done. + Int progressUpdateCount = m_videoStream->frameCount() / FRAME_FUDGE_ADD; Int shiftedPercent = -FRAME_FUDGE_ADD + 1; while (m_videoStream->frameIndex() < m_videoStream->frameCount() - 1 ) @@ -1058,13 +1055,6 @@ void ChallengeLoadScreen::init( GameInfo *game ) continue; } - if (!TheGameEngine->isActive()) - { //we are alt-tabbed out, so just increment the frame - m_videoStream->frameNext(); - m_videoStream->frameDecompress(); - continue; - } - m_videoStream->frameDecompress(); m_videoStream->frameRender(m_videoBuffer); m_videoStream->frameNext(); From b6c1c54010e00ee0d3f741c048a0730baf908493 Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Sun, 30 Nov 2025 15:15:23 +0100 Subject: [PATCH 13/70] tweak(keyboard): Apply minor improvements to Keyboard class to query pressed keys (#1926) --- .../GameEngine/Include/GameClient/KeyDefs.h | 9 ++++- .../GameEngine/Include/GameClient/Keyboard.h | 30 ++++++++------- .../GameClient/GUI/Gadget/GadgetListBox.cpp | 2 +- .../Source/GameClient/Input/Keyboard.cpp | 37 +++++++++++++------ .../GameClient/MessageStream/HotKey.cpp | 2 +- .../GameEngine/Include/GameClient/KeyDefs.h | 9 ++++- .../GameEngine/Include/GameClient/Keyboard.h | 30 ++++++++------- .../GameClient/GUI/Gadget/GadgetListBox.cpp | 2 +- .../Source/GameClient/Input/Keyboard.cpp | 37 +++++++++++++------ .../GameClient/MessageStream/HotKey.cpp | 2 +- 10 files changed, 100 insertions(+), 60 deletions(-) diff --git a/Generals/Code/GameEngine/Include/GameClient/KeyDefs.h b/Generals/Code/GameEngine/Include/GameClient/KeyDefs.h index a6e19e19bc..3c9f14394d 100644 --- a/Generals/Code/GameEngine/Include/GameClient/KeyDefs.h +++ b/Generals/Code/GameEngine/Include/GameClient/KeyDefs.h @@ -102,7 +102,7 @@ /** The key tables */ //============================================================================= -enum KeyDefType CPP_11(: Int) +enum KeyDefType CPP_11(: UnsignedByte) { // keypad keys ---------------------------------------------------------------- KEY_KP0 = DIK_NUMPAD0, @@ -224,10 +224,15 @@ enum KeyDefType CPP_11(: Int) // specials ------------------------------------------------------------------- KEY_NONE = 0x00, ///< to report end of key stream - KEY_LOST = 0xFF ///< to report lost keyboard focus + KEY_LOST = 0xFF, ///< to report lost keyboard focus }; +enum +{ + KEY_COUNT = 256 +}; + // state for keyboard IO ------------------------------------------------------ enum { diff --git a/Generals/Code/GameEngine/Include/GameClient/Keyboard.h b/Generals/Code/GameEngine/Include/GameClient/Keyboard.h index 638df5a3a3..5e21e33e5f 100644 --- a/Generals/Code/GameEngine/Include/GameClient/Keyboard.h +++ b/Generals/Code/GameEngine/Include/GameClient/Keyboard.h @@ -65,13 +65,15 @@ struct KeyboardIO { - enum StatusType + enum StatusType CPP_11(: UnsignedByte) { STATUS_UNUSED = 0x00, // Key has not been used STATUS_USED = 0x01 // Key has been eaten }; - UnsignedByte key; // key data + void setUsed() { status = STATUS_USED; } + + UnsignedByte key; // KeyDefType, key data UnsignedByte status; // StatusType, above UnsignedShort state; // KEY_STATE_* in KeyDefs.h UnsignedInt sequence; // sequence info from DirectX used for order @@ -91,7 +93,7 @@ class Keyboard : public SubsystemInterface Keyboard( void ); virtual ~Keyboard( void ); - // you may extend the functionanilty of these for your device + // you may extend the functionality of these for your device virtual void init( void ); /**< initialize the keyboard, only extend this functionality, do not replace */ virtual void reset( void ); ///< Reset keyboard system @@ -111,10 +113,11 @@ class Keyboard : public SubsystemInterface // access methods for key data void resetKeys( void ); ///< reset the state of the keys KeyboardIO *getFirstKey( void ); ///< get first key ready for processing - void setKeyStatusData( UnsignedByte key, + KeyboardIO *findKey( KeyDefType key, KeyboardIO::StatusType status ); ///< get key ready for processing, can return NULL + void setKeyStatusData( KeyDefType key, KeyboardIO::StatusType data ); ///< set key status - WideChar translateKey( WideChar keyCode ); ///< translte key code to printable UNICODE char - WideChar getPrintableKey( UnsignedByte key, Int state ); + WideChar translateKey( WideChar keyCode ); ///< translate key code to printable UNICODE char + WideChar getPrintableKey( KeyDefType key, Int state ); enum { MAX_KEY_STATES = 3}; protected: @@ -126,10 +129,10 @@ class Keyboard : public SubsystemInterface void initKeyNames( void ); ///< initialize the key names table void updateKeys( void ); ///< update the state of our key data Bool checkKeyRepeat( void ); ///< check for repeating keys - UnsignedByte getKeyStatusData( UnsignedByte key ); ///< get key status - Bool getKeyStateBit( UnsignedByte key, Int bit ); ///< get key state bit - UnsignedInt getKeySequenceData( UnsignedByte key ); ///< get key sequence - void setKeyStateData( UnsignedByte key, UnsignedByte data ); ///< get key state + UnsignedByte getKeyStatusData( KeyDefType key ); ///< get key status + Bool getKeyStateBit( KeyDefType key, Int bit ); ///< get key state bit + UnsignedInt getKeySequenceData( KeyDefType key ); ///< get key sequence + void setKeyStateData( KeyDefType key, UnsignedByte data ); ///< get key state UnsignedShort m_modifiers; // internal keyboard data members @@ -142,13 +145,12 @@ class Keyboard : public SubsystemInterface //Bool m_rControlState; // 1 if right control is down //Bool m_lAltState; // 1 if left alt is down //Bool m_rAltState; // 1 if right alt is down - UnsignedByte m_shift2Key; // what key is the secondary shift key + KeyDefType m_shift2Key; // what key is the secondary shift key enum { NUM_KEYS = 256 }; KeyboardIO m_keys[ NUM_KEYS ]; ///< the keys - KeyboardIO m_keyStatus[ NUM_KEYS ]; ///< the key status flags + KeyboardIO m_keyStatus[ KEY_COUNT ]; ///< the key status flags - enum { KEY_NAMES_COUNT = 256 }; struct { @@ -156,7 +158,7 @@ class Keyboard : public SubsystemInterface WideChar shifted; WideChar shifted2; - } m_keyNames[ KEY_NAMES_COUNT ]; + } m_keyNames[ KEY_COUNT ]; UnsignedInt m_inputFrame; ///< frame input was gathered on }; diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp index d35381fe44..9b4547a6cf 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp @@ -727,7 +727,7 @@ WindowMsgHandledType GadgetListBoxInput( GameWindow *window, UnsignedInt msg, continue; for(j = 0; j < TheKeyboard->MAX_KEY_STATES; ++j) { - if(dString->getText().getCharAt(0) == TheKeyboard->getPrintableKey(mData1, j)) + if(dString->getText().getCharAt(0) == TheKeyboard->getPrintableKey((KeyDefType)mData1, j)) { list->selectPos = position; Int prevPos = getListboxTopEntry(list); diff --git a/Generals/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp b/Generals/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp index 081242411a..3705c791c2 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp @@ -50,7 +50,7 @@ Keyboard *TheKeyboard = NULL; void Keyboard::createStreamMessages( void ) { - // santiy + // sanity if( TheMessageStream == NULL ) return; @@ -89,6 +89,7 @@ void Keyboard::createStreamMessages( void ) } // next key please + key->setUsed(); key++; } @@ -213,7 +214,7 @@ Bool Keyboard::checkKeyRepeat( void ) // Scan Keyboard status array for first key down // long enough to repeat - for( key = 0; key < 256; key++ ) + for( key = 0; key < ARRAY_SIZE(m_keyStatus); key++ ) { if( BitIsSet( m_keyStatus[ key ].state, KEY_STATE_DOWN ) ) @@ -261,7 +262,7 @@ void Keyboard::initKeyNames( void ) /* * Initialize the keyboard key-names array. */ - for( i = 0; i < KEY_NAMES_COUNT; i++ ) + for( i = 0; i < ARRAY_SIZE(m_keyNames); i++ ) { m_keyNames[ i ].stdKey = L'\0'; @@ -765,10 +766,24 @@ KeyboardIO *Keyboard::getFirstKey( void ) return &m_keys[ 0 ]; } +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +KeyboardIO *Keyboard::findKey( KeyDefType key, KeyboardIO::StatusType status ) +{ + for (KeyboardIO *io = getFirstKey(); io->key != KEY_NONE; ++io) + { + if (io->key == key && io->status == status) + { + return io; + } + } + return NULL; +} + //------------------------------------------------------------------------------------------------- /** return the key status for the specified key */ //------------------------------------------------------------------------------------------------- -UnsignedByte Keyboard::getKeyStatusData( UnsignedByte key ) +UnsignedByte Keyboard::getKeyStatusData( KeyDefType key ) { return m_keyStatus[ key ].status; } @@ -776,7 +791,7 @@ UnsignedByte Keyboard::getKeyStatusData( UnsignedByte key ) //------------------------------------------------------------------------------------------------- /** Get the key state data as a Bool for the specified key */ //------------------------------------------------------------------------------------------------- -Bool Keyboard::getKeyStateBit( UnsignedByte key, Int bit ) +Bool Keyboard::getKeyStateBit( KeyDefType key, Int bit ) { return (m_keyStatus[ key ].state & bit) ? 1 : 0; } @@ -784,7 +799,7 @@ Bool Keyboard::getKeyStateBit( UnsignedByte key, Int bit ) //------------------------------------------------------------------------------------------------- /** return the sequence data for the given key */ //------------------------------------------------------------------------------------------------- -UnsignedInt Keyboard::getKeySequenceData( UnsignedByte key ) +UnsignedInt Keyboard::getKeySequenceData( KeyDefType key ) { return m_keyStatus[ key ].sequence; } @@ -792,7 +807,7 @@ UnsignedInt Keyboard::getKeySequenceData( UnsignedByte key ) //------------------------------------------------------------------------------------------------- /** set the key status data */ //------------------------------------------------------------------------------------------------- -void Keyboard::setKeyStatusData( UnsignedByte key, KeyboardIO::StatusType data ) +void Keyboard::setKeyStatusData( KeyDefType key, KeyboardIO::StatusType data ) { m_keyStatus[ key ].status = data; } @@ -800,7 +815,7 @@ void Keyboard::setKeyStatusData( UnsignedByte key, KeyboardIO::StatusType data ) //------------------------------------------------------------------------------------------------- /** set the key state data */ //------------------------------------------------------------------------------------------------- -void Keyboard::setKeyStateData( UnsignedByte key, UnsignedByte data ) +void Keyboard::setKeyStateData( KeyDefType key, UnsignedByte data ) { m_keyStatus[ key ].state = data; } @@ -973,9 +988,9 @@ Bool Keyboard::isAlt() } -WideChar Keyboard::getPrintableKey( UnsignedByte key, Int state ) +WideChar Keyboard::getPrintableKey( KeyDefType key, Int state ) { - if((key < 0 || key >=KEY_NAMES_COUNT) || ( state < 0 || state >= MAX_KEY_STATES)) + if((key < 0 || key >= ARRAY_SIZE(m_keyNames)) || ( state < 0 || state >= MAX_KEY_STATES)) return L'\0'; if(state == 0) return m_keyNames[key].stdKey; @@ -983,6 +998,4 @@ WideChar Keyboard::getPrintableKey( UnsignedByte key, Int state ) return m_keyNames[key].shifted; else return m_keyNames[key].shifted2; - - } diff --git a/Generals/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp b/Generals/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp index 355c037b5a..637450e48f 100644 --- a/Generals/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp @@ -98,7 +98,7 @@ GameMessageDisposition HotKeyTranslator::translateGameMessage(const GameMessage } if(newModState != 0) return disp; - WideChar key = TheKeyboard->getPrintableKey(msg->getArgument(0)->integer, 0); + WideChar key = TheKeyboard->getPrintableKey((KeyDefType)msg->getArgument(0)->integer, 0); UnicodeString uKey; uKey.concat(key); AsciiString aKey; diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/KeyDefs.h b/GeneralsMD/Code/GameEngine/Include/GameClient/KeyDefs.h index 8d61ed62d3..9f1978d20e 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/KeyDefs.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/KeyDefs.h @@ -102,7 +102,7 @@ /** The key tables */ //============================================================================= -enum KeyDefType CPP_11(: Int) +enum KeyDefType CPP_11(: UnsignedByte) { // keypad keys ---------------------------------------------------------------- KEY_KP0 = DIK_NUMPAD0, @@ -224,10 +224,15 @@ enum KeyDefType CPP_11(: Int) // specials ------------------------------------------------------------------- KEY_NONE = 0x00, ///< to report end of key stream - KEY_LOST = 0xFF ///< to report lost keyboard focus + KEY_LOST = 0xFF, ///< to report lost keyboard focus }; +enum +{ + KEY_COUNT = 256 +}; + // state for keyboard IO ------------------------------------------------------ enum { diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Keyboard.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Keyboard.h index 770a7338fd..99a4cd54ce 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/Keyboard.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Keyboard.h @@ -65,13 +65,15 @@ struct KeyboardIO { - enum StatusType + enum StatusType CPP_11(: UnsignedByte) { STATUS_UNUSED = 0x00, // Key has not been used STATUS_USED = 0x01 // Key has been eaten }; - UnsignedByte key; // key data + void setUsed() { status = STATUS_USED; } + + UnsignedByte key; // KeyDefType, key data UnsignedByte status; // StatusType, above UnsignedShort state; // KEY_STATE_* in KeyDefs.h UnsignedInt sequence; // sequence info from DirectX used for order @@ -91,7 +93,7 @@ class Keyboard : public SubsystemInterface Keyboard( void ); virtual ~Keyboard( void ); - // you may extend the functionanilty of these for your device + // you may extend the functionality of these for your device virtual void init( void ); /**< initialize the keyboard, only extend this functionality, do not replace */ virtual void reset( void ); ///< Reset keyboard system @@ -111,10 +113,11 @@ class Keyboard : public SubsystemInterface // access methods for key data void resetKeys( void ); ///< reset the state of the keys KeyboardIO *getFirstKey( void ); ///< get first key ready for processing - void setKeyStatusData( UnsignedByte key, + KeyboardIO *findKey( KeyDefType key, KeyboardIO::StatusType status ); ///< get key ready for processing, can return NULL + void setKeyStatusData( KeyDefType key, KeyboardIO::StatusType data ); ///< set key status - WideChar translateKey( WideChar keyCode ); ///< translte key code to printable UNICODE char - WideChar getPrintableKey( UnsignedByte key, Int state ); + WideChar translateKey( WideChar keyCode ); ///< translate key code to printable UNICODE char + WideChar getPrintableKey( KeyDefType key, Int state ); enum { MAX_KEY_STATES = 3}; protected: @@ -126,10 +129,10 @@ class Keyboard : public SubsystemInterface void initKeyNames( void ); ///< initialize the key names table void updateKeys( void ); ///< update the state of our key data Bool checkKeyRepeat( void ); ///< check for repeating keys - UnsignedByte getKeyStatusData( UnsignedByte key ); ///< get key status - Bool getKeyStateBit( UnsignedByte key, Int bit ); ///< get key state bit - UnsignedInt getKeySequenceData( UnsignedByte key ); ///< get key sequence - void setKeyStateData( UnsignedByte key, UnsignedByte data ); ///< get key state + UnsignedByte getKeyStatusData( KeyDefType key ); ///< get key status + Bool getKeyStateBit( KeyDefType key, Int bit ); ///< get key state bit + UnsignedInt getKeySequenceData( KeyDefType key ); ///< get key sequence + void setKeyStateData( KeyDefType key, UnsignedByte data ); ///< get key state UnsignedShort m_modifiers; // internal keyboard data members @@ -142,13 +145,12 @@ class Keyboard : public SubsystemInterface //Bool m_rControlState; // 1 if right control is down //Bool m_lAltState; // 1 if left alt is down //Bool m_rAltState; // 1 if right alt is down - UnsignedByte m_shift2Key; // what key is the secondary shift key + KeyDefType m_shift2Key; // what key is the secondary shift key enum { NUM_KEYS = 256 }; KeyboardIO m_keys[ NUM_KEYS ]; ///< the keys - KeyboardIO m_keyStatus[ NUM_KEYS ]; ///< the key status flags + KeyboardIO m_keyStatus[ KEY_COUNT ]; ///< the key status flags - enum { KEY_NAMES_COUNT = 256 }; struct { @@ -156,7 +158,7 @@ class Keyboard : public SubsystemInterface WideChar shifted; WideChar shifted2; - } m_keyNames[ KEY_NAMES_COUNT ]; + } m_keyNames[ KEY_COUNT ]; UnsignedInt m_inputFrame; ///< frame input was gathered on }; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp index 147c7368ba..783f360723 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp @@ -727,7 +727,7 @@ WindowMsgHandledType GadgetListBoxInput( GameWindow *window, UnsignedInt msg, continue; for(j = 0; j < TheKeyboard->MAX_KEY_STATES; ++j) { - if(dString->getText().getCharAt(0) == TheKeyboard->getPrintableKey(mData1, j)) + if(dString->getText().getCharAt(0) == TheKeyboard->getPrintableKey((KeyDefType)mData1, j)) { list->selectPos = position; Int prevPos = getListboxTopEntry(list); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp index a2e67445d1..5a642bdff8 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp @@ -50,7 +50,7 @@ Keyboard *TheKeyboard = NULL; void Keyboard::createStreamMessages( void ) { - // santiy + // sanity if( TheMessageStream == NULL ) return; @@ -89,6 +89,7 @@ void Keyboard::createStreamMessages( void ) } // next key please + key->setUsed(); key++; } @@ -213,7 +214,7 @@ Bool Keyboard::checkKeyRepeat( void ) // Scan Keyboard status array for first key down // long enough to repeat - for( key = 0; key < 256; key++ ) + for( key = 0; key < ARRAY_SIZE(m_keyStatus); key++ ) { if( BitIsSet( m_keyStatus[ key ].state, KEY_STATE_DOWN ) ) @@ -261,7 +262,7 @@ void Keyboard::initKeyNames( void ) /* * Initialize the keyboard key-names array. */ - for( i = 0; i < KEY_NAMES_COUNT; i++ ) + for( i = 0; i < ARRAY_SIZE(m_keyNames); i++ ) { m_keyNames[ i ].stdKey = L'\0'; @@ -765,10 +766,24 @@ KeyboardIO *Keyboard::getFirstKey( void ) return &m_keys[ 0 ]; } +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +KeyboardIO *Keyboard::findKey( KeyDefType key, KeyboardIO::StatusType status ) +{ + for (KeyboardIO *io = getFirstKey(); io->key != KEY_NONE; ++io) + { + if (io->key == key && io->status == status) + { + return io; + } + } + return NULL; +} + //------------------------------------------------------------------------------------------------- /** return the key status for the specified key */ //------------------------------------------------------------------------------------------------- -UnsignedByte Keyboard::getKeyStatusData( UnsignedByte key ) +UnsignedByte Keyboard::getKeyStatusData( KeyDefType key ) { return m_keyStatus[ key ].status; } @@ -776,7 +791,7 @@ UnsignedByte Keyboard::getKeyStatusData( UnsignedByte key ) //------------------------------------------------------------------------------------------------- /** Get the key state data as a Bool for the specified key */ //------------------------------------------------------------------------------------------------- -Bool Keyboard::getKeyStateBit( UnsignedByte key, Int bit ) +Bool Keyboard::getKeyStateBit( KeyDefType key, Int bit ) { return (m_keyStatus[ key ].state & bit) ? 1 : 0; } @@ -784,7 +799,7 @@ Bool Keyboard::getKeyStateBit( UnsignedByte key, Int bit ) //------------------------------------------------------------------------------------------------- /** return the sequence data for the given key */ //------------------------------------------------------------------------------------------------- -UnsignedInt Keyboard::getKeySequenceData( UnsignedByte key ) +UnsignedInt Keyboard::getKeySequenceData( KeyDefType key ) { return m_keyStatus[ key ].sequence; } @@ -792,7 +807,7 @@ UnsignedInt Keyboard::getKeySequenceData( UnsignedByte key ) //------------------------------------------------------------------------------------------------- /** set the key status data */ //------------------------------------------------------------------------------------------------- -void Keyboard::setKeyStatusData( UnsignedByte key, KeyboardIO::StatusType data ) +void Keyboard::setKeyStatusData( KeyDefType key, KeyboardIO::StatusType data ) { m_keyStatus[ key ].status = data; } @@ -800,7 +815,7 @@ void Keyboard::setKeyStatusData( UnsignedByte key, KeyboardIO::StatusType data ) //------------------------------------------------------------------------------------------------- /** set the key state data */ //------------------------------------------------------------------------------------------------- -void Keyboard::setKeyStateData( UnsignedByte key, UnsignedByte data ) +void Keyboard::setKeyStateData( KeyDefType key, UnsignedByte data ) { m_keyStatus[ key ].state = data; } @@ -973,9 +988,9 @@ Bool Keyboard::isAlt() } -WideChar Keyboard::getPrintableKey( UnsignedByte key, Int state ) +WideChar Keyboard::getPrintableKey( KeyDefType key, Int state ) { - if((key < 0 || key >=KEY_NAMES_COUNT) || ( state < 0 || state >= MAX_KEY_STATES)) + if((key < 0 || key >= ARRAY_SIZE(m_keyNames)) || ( state < 0 || state >= MAX_KEY_STATES)) return L'\0'; if(state == 0) return m_keyNames[key].stdKey; @@ -983,6 +998,4 @@ WideChar Keyboard::getPrintableKey( UnsignedByte key, Int state ) return m_keyNames[key].shifted; else return m_keyNames[key].shifted2; - - } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp index e71399c7e8..9e8ffd3a1c 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp @@ -98,7 +98,7 @@ GameMessageDisposition HotKeyTranslator::translateGameMessage(const GameMessage } if(newModState != 0) return disp; - WideChar key = TheKeyboard->getPrintableKey(msg->getArgument(0)->integer, 0); + WideChar key = TheKeyboard->getPrintableKey((KeyDefType)msg->getArgument(0)->integer, 0); UnicodeString uKey; uKey.concat(key); AsciiString aKey; From e6c28a4e2914351920d4a961a0f984fa17f5ac91 Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Sun, 30 Nov 2025 15:15:35 +0100 Subject: [PATCH 14/70] feat(movie): Implement ESC button mapping to skip Campaign, Challenge and Score videos (#1926) --- .../GUI/GUICallbacks/Menus/ScoreScreen.cpp | 13 ++++++++++ .../Source/GameClient/GUI/LoadScreen.cpp | 13 ++++++++++ .../GUI/GUICallbacks/Menus/ScoreScreen.cpp | 13 ++++++++++ .../Source/GameClient/GUI/LoadScreen.cpp | 25 +++++++++++++++++++ 4 files changed, 64 insertions(+) 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 b1f1ec6366..12f22f49c1 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp @@ -79,6 +79,7 @@ #include "GameClient/GameWindowManager.h" #include "GameClient/Gadget.h" #include "GameClient/GameText.h" +#include "GameClient/Keyboard.h" #include "GameClient/MapUtil.h" #include "GameClient/Shell.h" #include "GameClient/KeyDefs.h" @@ -640,6 +641,18 @@ void PlayMovieAndBlock(AsciiString movieTitle) TheWritableGlobalData->m_loadScreenRender = TRUE; while (videoStream->frameIndex() < videoStream->frameCount() - 1) { + // TheSuperHackers @feature User can now skip video by pressing ESC + if (TheKeyboard) + { + TheKeyboard->UPDATE(); + KeyboardIO *io = TheKeyboard->findKey(KEY_ESC, KeyboardIO::STATUS_UNUSED); + if (io && BitIsSet(io->state, KEY_STATE_DOWN)) + { + io->setUsed(); + break; + } + } + TheGameEngine->serviceWindowsOS(); if(!videoStream->isFrameReady()) diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp index bc158c26a4..5515b6cc21 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp @@ -66,6 +66,7 @@ #include "Common/AudioAffect.h" #include "GameClient/LoadScreen.h" +#include "GameClient/Keyboard.h" #include "GameClient/Shell.h" #include "GameClient/GameWindowManager.h" #include "GameClient/GadgetProgressBar.h" @@ -490,6 +491,18 @@ void SinglePlayerLoadScreen::init( GameInfo *game ) Int shiftedPercent = -FRAME_FUDGE_ADD + 1; while (m_videoStream->frameIndex() < m_videoStream->frameCount() - 1 ) { + // TheSuperHackers @feature User can now skip video by pressing ESC + if (TheKeyboard) + { + TheKeyboard->UPDATE(); + KeyboardIO *io = TheKeyboard->findKey(KEY_ESC, KeyboardIO::STATUS_UNUSED); + if (io && BitIsSet(io->state, KEY_STATE_DOWN)) + { + io->setUsed(); + break; + } + } + TheGameEngine->serviceWindowsOS(); if(!m_videoStream->isFrameReady()) 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 f57594d24e..d1edfbd099 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp @@ -82,6 +82,7 @@ #include "GameClient/GameWindowManager.h" #include "GameClient/Gadget.h" #include "GameClient/GameText.h" +#include "GameClient/Keyboard.h" #include "GameClient/MapUtil.h" #include "GameClient/Shell.h" #include "GameClient/KeyDefs.h" @@ -734,6 +735,18 @@ void PlayMovieAndBlock(AsciiString movieTitle) TheWritableGlobalData->m_loadScreenRender = TRUE; while (videoStream->frameIndex() < videoStream->frameCount() - 1) { + // TheSuperHackers @feature User can now skip video by pressing ESC + if (TheKeyboard) + { + TheKeyboard->UPDATE(); + KeyboardIO *io = TheKeyboard->findKey(KEY_ESC, KeyboardIO::STATUS_UNUSED); + if (io && BitIsSet(io->state, KEY_STATE_DOWN)) + { + io->setUsed(); + break; + } + } + TheGameEngine->serviceWindowsOS(); if(!videoStream->isFrameReady()) diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp index 5c8bc3430b..19cb7a2aea 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp @@ -71,6 +71,7 @@ #include "GameClient/GameText.h" #include "GameClient/GameWindowManager.h" #include "GameClient/GameWindowTransitions.h" +#include "GameClient/Keyboard.h" #include "GameClient/LoadScreen.h" #include "GameClient/MapUtil.h" #include "GameClient/Mouse.h" @@ -533,6 +534,18 @@ void SinglePlayerLoadScreen::init( GameInfo *game ) Int shiftedPercent = -FRAME_FUDGE_ADD + 1; while (m_videoStream->frameIndex() < m_videoStream->frameCount() - 1 ) { + // TheSuperHackers @feature User can now skip video by pressing ESC + if (TheKeyboard) + { + TheKeyboard->UPDATE(); + KeyboardIO *io = TheKeyboard->findKey(KEY_ESC, KeyboardIO::STATUS_UNUSED); + if (io && BitIsSet(io->state, KEY_STATE_DOWN)) + { + io->setUsed(); + break; + } + } + TheGameEngine->serviceWindowsOS(); if(!m_videoStream->isFrameReady()) @@ -1047,6 +1060,18 @@ void ChallengeLoadScreen::init( GameInfo *game ) Int shiftedPercent = -FRAME_FUDGE_ADD + 1; while (m_videoStream->frameIndex() < m_videoStream->frameCount() - 1 ) { + // TheSuperHackers @feature User can now skip video by pressing ESC + if (TheKeyboard) + { + TheKeyboard->UPDATE(); + KeyboardIO *io = TheKeyboard->findKey(KEY_ESC, KeyboardIO::STATUS_UNUSED); + if (io && BitIsSet(io->state, KEY_STATE_DOWN)) + { + io->setUsed(); + break; + } + } + TheGameEngine->serviceWindowsOS(); if(!m_videoStream->isFrameReady()) From 6f9785fb2032a7dbb8f2b386e80de5658d4075e6 Mon Sep 17 00:00:00 2001 From: Bobby Battista Date: Sun, 7 Dec 2025 04:19:38 -0500 Subject: [PATCH 15/70] build: Use cmake_host_system_information to make registry queries in cmake (#1943) --- Generals/CMakeLists.txt | 33 ++++++++++++++++++--------------- GeneralsMD/CMakeLists.txt | 32 ++++++++++++++++++-------------- cmake/registry.cmake | 15 +++++++++++++++ 3 files changed, 51 insertions(+), 29 deletions(-) create mode 100644 cmake/registry.cmake diff --git a/Generals/CMakeLists.txt b/Generals/CMakeLists.txt index 837065acba..78f920244e 100644 --- a/Generals/CMakeLists.txt +++ b/Generals/CMakeLists.txt @@ -15,28 +15,31 @@ add_subdirectory(Code) # If we are building on windows for windows, try and get the game install path from the registry. if("${CMAKE_HOST_SYSTEM}" MATCHES "Windows" AND "${CMAKE_SYSTEM}" MATCHES "Windows") - # Check the CD registry path - if(NOT RTS_INSTALL_PREFIX_GENERALS) - get_filename_component(RTS_INSTALL_PREFIX_GENERALS "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Electronic Arts\\EA Games\\Generals;InstallPath]" ABSOLUTE CACHE) - endif() + include(${CMAKE_SOURCE_DIR}/cmake/registry.cmake) - # Check the WOW6432Node registry path (for EA App on 64-bit Windows) - if(NOT RTS_INSTALL_PREFIX_GENERALS OR "${RTS_INSTALL_PREFIX_GENERALS}" STREQUAL "/registry") - get_filename_component(RTS_INSTALL_PREFIX_GENERALS "[HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Electronic Arts\\EA Games\\Generals;InstallPath]" ABSOLUTE CACHE) - endif() + # Check the EA App/CD registry path + fetch_registry_value( + "HKEY_LOCAL_MACHINE/SOFTWARE/Electronic Arts/EA Games/Generals" + "InstallPath" + RTS_INSTALL_PREFIX_GENERALS + "Generals install path from registry") # Check the "First Decade" registry path - if(NOT RTS_INSTALL_PREFIX_GENERALS OR "${RTS_INSTALL_PREFIX_GENERALS}" STREQUAL "/registry") - get_filename_component(RTS_INSTALL_PREFIX_GENERALS "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Electronic Arts\\EA Games\\Command and Conquer The First Decade;gr_folder]" ABSOLUTE CACHE) - endif() + fetch_registry_value( + "HKEY_LOCAL_MACHINE/SOFTWARE/Electronic Arts/EA Games/Command and Conquer The First Decade" + "gr_folder" + RTS_INSTALL_PREFIX_GENERALS + "Generals install path from registry") # Check the Steam registry path - if(NOT RTS_INSTALL_PREFIX_GENERALS OR "${RTS_INSTALL_PREFIX_GENERALS}" STREQUAL "/registry") - get_filename_component(RTS_INSTALL_PREFIX_GENERALS "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Electronic Arts\\EA Games\\Generals;installPath]" ABSOLUTE CACHE) - endif() + fetch_registry_value( + "HKEY_LOCAL_MACHINE/SOFTWARE/Electronic Arts/EA Games/Generals" + "installPath" + RTS_INSTALL_PREFIX_GENERALS + "Generals install path from registry") endif() -if(RTS_INSTALL_PREFIX_GENERALS AND NOT "${RTS_INSTALL_PREFIX_GENERALS}" STREQUAL "/registry") +if(RTS_INSTALL_PREFIX_GENERALS) install(TARGETS g_generals RUNTIME DESTINATION "${RTS_INSTALL_PREFIX_GENERALS}") install(FILES $ DESTINATION "${RTS_INSTALL_PREFIX_GENERALS}" OPTIONAL) diff --git a/GeneralsMD/CMakeLists.txt b/GeneralsMD/CMakeLists.txt index 830d0df785..2a9a65fb78 100644 --- a/GeneralsMD/CMakeLists.txt +++ b/GeneralsMD/CMakeLists.txt @@ -15,27 +15,31 @@ add_subdirectory(Code) # If we are building on windows for windows, try and get the game install path from the registry. if("${CMAKE_HOST_SYSTEM}" MATCHES "Windows" AND "${CMAKE_SYSTEM}" MATCHES "Windows") - if(NOT RTS_INSTALL_PREFIX_ZEROHOUR) - get_filename_component(RTS_INSTALL_PREFIX_ZEROHOUR "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Electronic Arts\\EA Games\\Command and Conquer Generals Zero Hour;InstallPath]" ABSOLUTE CACHE) - endif() + include(${CMAKE_SOURCE_DIR}/cmake/registry.cmake) - # Check the WOW6432Node registry path (for EA App on 64-bit Windows) - if(NOT RTS_INSTALL_PREFIX_ZEROHOUR OR "${RTS_INSTALL_PREFIX_ZEROHOUR}" STREQUAL "/registry") - get_filename_component(RTS_INSTALL_PREFIX_ZEROHOUR "[HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Electronic Arts\\EA Games\\Command and Conquer Generals Zero Hour;InstallPath]" ABSOLUTE CACHE) - endif() + # Check the EA App/CD registry path + fetch_registry_value( + "HKEY_LOCAL_MACHINE/SOFTWARE/Electronic Arts/EA Games/Command and Conquer Generals Zero Hour" + "InstallPath" + RTS_INSTALL_PREFIX_ZEROHOUR + "Zero Hour install path from registry") # Check the "First Decade" registry path - if(NOT RTS_INSTALL_PREFIX_ZEROHOUR OR "${RTS_INSTALL_PREFIX_ZEROHOUR}" STREQUAL "/registry") - get_filename_component(RTS_INSTALL_PREFIX_ZEROHOUR "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Electronic Arts\\EA Games\\Command and Conquer The First Decade;zh_folder]" ABSOLUTE CACHE) - endif() + fetch_registry_value( + "HKEY_LOCAL_MACHINE/SOFTWARE/Electronic Arts/EA Games/Command and Conquer The First Decade" + "zh_folder" + RTS_INSTALL_PREFIX_ZEROHOUR + "Zero Hour install path from registry") # Check the Steam registry path - if(NOT RTS_INSTALL_PREFIX_ZEROHOUR OR "${RTS_INSTALL_PREFIX_ZEROHOUR}" STREQUAL "/registry") - get_filename_component(RTS_INSTALL_PREFIX_ZEROHOUR "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Electronic Arts\\EA Games\\ZeroHour;installPath]" ABSOLUTE CACHE) - endif() + fetch_registry_value( + "HKEY_LOCAL_MACHINE/SOFTWARE/Electronic Arts/EA Games/ZeroHour" + "installPath" + RTS_INSTALL_PREFIX_ZEROHOUR + "Zero Hour install path from registry") endif() -if(RTS_INSTALL_PREFIX_ZEROHOUR AND NOT "${RTS_INSTALL_PREFIX_ZEROHOUR}" STREQUAL "/registry") +if(RTS_INSTALL_PREFIX_ZEROHOUR) install(TARGETS z_generals RUNTIME DESTINATION "${RTS_INSTALL_PREFIX_ZEROHOUR}") install(FILES $ DESTINATION "${RTS_INSTALL_PREFIX_ZEROHOUR}" OPTIONAL) diff --git a/cmake/registry.cmake b/cmake/registry.cmake new file mode 100644 index 0000000000..6f8caae688 --- /dev/null +++ b/cmake/registry.cmake @@ -0,0 +1,15 @@ +# Helper macro for querying Windows registry values +# Queries both 32-bit and 64-bit registry views automatically +macro(fetch_registry_value registry_key registry_value output_var description) + if(NOT ${output_var}) + cmake_host_system_information(RESULT _variable + QUERY WINDOWS_REGISTRY + "${registry_key}" + VALUE "${registry_value}" + VIEW 32_64) + if(_variable) + set(${output_var} "${_variable}" CACHE PATH "${description}") + endif() + endif() +endmacro() + From 2a1593ef70308aa1c81612f4a9982780f6a3e4fa Mon Sep 17 00:00:00 2001 From: Mauller <26652186+Mauller@users.noreply.github.com> Date: Sun, 7 Dec 2025 09:22:53 +0000 Subject: [PATCH 16/70] bugfix(network): Prevent out of bounds memory access in NetCommandWrapperListNode::copyChunkData() (#1946) --- .../GameNetwork/NetCommandWrapperList.h | 2 +- .../GameNetwork/NetCommandWrapperList.cpp | 46 +++++++++++++------ 2 files changed, 34 insertions(+), 14 deletions(-) diff --git a/Core/GameEngine/Include/GameNetwork/NetCommandWrapperList.h b/Core/GameEngine/Include/GameNetwork/NetCommandWrapperList.h index f4ea0bed06..fac7ea7964 100644 --- a/Core/GameEngine/Include/GameNetwork/NetCommandWrapperList.h +++ b/Core/GameEngine/Include/GameNetwork/NetCommandWrapperList.h @@ -49,7 +49,7 @@ class NetCommandWrapperListNode : public MemoryPoolObject protected: UnsignedShort m_commandID; UnsignedByte *m_data; - UnsignedInt m_dataLength; + UnsignedInt m_totalDataLength; Bool *m_chunksPresent; UnsignedInt m_numChunks; UnsignedInt m_numChunksPresent; diff --git a/Core/GameEngine/Source/GameNetwork/NetCommandWrapperList.cpp b/Core/GameEngine/Source/GameNetwork/NetCommandWrapperList.cpp index 698a6b3334..86333e9016 100644 --- a/Core/GameEngine/Source/GameNetwork/NetCommandWrapperList.cpp +++ b/Core/GameEngine/Source/GameNetwork/NetCommandWrapperList.cpp @@ -45,8 +45,8 @@ NetCommandWrapperListNode::NetCommandWrapperListNode(NetWrapperCommandMsg *msg) m_chunksPresent[i] = FALSE; } - m_dataLength = msg->getTotalDataLength(); - m_data = NEW UnsignedByte[m_dataLength]; // pool[]ify + m_totalDataLength = msg->getTotalDataLength(); + m_data = NEW UnsignedByte[m_totalDataLength]; // pool[]ify m_commandID = msg->getWrappedCommandID(); } @@ -75,7 +75,7 @@ UnsignedShort NetCommandWrapperListNode::getCommandID() { } UnsignedInt NetCommandWrapperListNode::getRawDataLength() { - return m_dataLength; + return m_totalDataLength; } void NetCommandWrapperListNode::copyChunkData(NetWrapperCommandMsg *msg) { @@ -84,22 +84,42 @@ void NetCommandWrapperListNode::copyChunkData(NetWrapperCommandMsg *msg) { return; } - DEBUG_ASSERTCRASH(msg->getChunkNumber() < m_numChunks, ("MunkeeChunk %d of %d", - msg->getChunkNumber(), m_numChunks)); - if (msg->getChunkNumber() >= m_numChunks) + UnsignedInt chunkNumber = msg->getChunkNumber(); + + if (chunkNumber >= m_numChunks) { + DEBUG_CRASH(("Data chunk %u exceeds the expected maximum of %u chunks", chunkNumber, m_numChunks)); return; + } - DEBUG_LOG(("NetCommandWrapperListNode::copyChunkData() - copying chunk %d", - msg->getChunkNumber())); + // we already received this chunk, no need to recopy it. + if (m_chunksPresent[chunkNumber] == TRUE) { + return; + } - if (m_chunksPresent[msg->getChunkNumber()] == TRUE) { - // we already received this chunk, no need to recopy it. + UnsignedInt chunkDataOffset = msg->getDataOffset(); + UnsignedInt chunkDataLength = msg->getDataLength(); + + // TheSuperHackers @security Mauller 04/12/2025 Prevent out of bounds memory access + if (chunkDataOffset >= m_totalDataLength) { + DEBUG_CRASH(("Data chunk offset %u exceeds the total data length %u", chunkDataOffset, m_totalDataLength)); return; } - m_chunksPresent[msg->getChunkNumber()] = TRUE; - UnsignedInt offset = msg->getDataOffset(); - memcpy(m_data + offset, msg->getData(), msg->getDataLength()); + if (chunkDataLength > MAX_PACKET_SIZE ) { + DEBUG_CRASH(("Data Chunk size %u greater than max packet size %u", chunkDataLength, MAX_PACKET_SIZE)); + return; + } + + if (chunkDataOffset + chunkDataLength > m_totalDataLength) { + DEBUG_CRASH(("Data chunk exceeds data array size")); + return; + } + + DEBUG_LOG(("NetCommandWrapperListNode::copyChunkData() - copying chunk %u", chunkNumber)); + + memcpy(m_data + chunkDataOffset, msg->getData(), chunkDataLength); + + m_chunksPresent[chunkNumber] = TRUE; ++m_numChunksPresent; } From 2b1bcee088898f4f6c2edcd988b3b69410778688 Mon Sep 17 00:00:00 2001 From: Bobby Battista Date: Sun, 7 Dec 2025 04:56:46 -0500 Subject: [PATCH 17/70] fix: Wrong usage of sizeof(this) in BitFlags::xfer(), W3DMPO::glueEnforcer() (#1947) --- Core/Libraries/Source/WWVegas/WWLib/always.h | 4 ++-- Generals/Code/GameEngine/Include/Common/BitFlagsIO.h | 4 ++++ GeneralsMD/Code/GameEngine/Include/Common/BitFlagsIO.h | 4 ++++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/Core/Libraries/Source/WWVegas/WWLib/always.h b/Core/Libraries/Source/WWVegas/WWLib/always.h index d63eeec2fb..c58e6dd8e4 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/always.h +++ b/Core/Libraries/Source/WWVegas/WWLib/always.h @@ -144,7 +144,7 @@ private: \ return The##ARGCLASS##Pool; \ } \ protected: \ - virtual int glueEnforcer() const { return sizeof(this); } \ + virtual void glueEnforcer() const { } \ public: \ inline void* operator new(size_t s) { return allocateFromW3DMemPool(getClassMemoryPool(), s); } \ inline void operator delete(void *p) { freeFromW3DMemPool(getClassMemoryPool(), p); } \ @@ -162,7 +162,7 @@ class W3DMPO } protected: // we never call this; it is present to cause compile errors in descendent classes - virtual int glueEnforcer() const = 0; + virtual void glueEnforcer() const = 0; public: virtual ~W3DMPO() { /* nothing */ } }; diff --git a/Generals/Code/GameEngine/Include/Common/BitFlagsIO.h b/Generals/Code/GameEngine/Include/Common/BitFlagsIO.h index 2d7be09044..197c79f31f 100644 --- a/Generals/Code/GameEngine/Include/Common/BitFlagsIO.h +++ b/Generals/Code/GameEngine/Include/Common/BitFlagsIO.h @@ -214,7 +214,11 @@ void BitFlags::xfer(Xfer* xfer) { // just call the xfer implementation on the data values +#if RETAIL_COMPATIBLE_CRC xfer->xferUser( this, sizeof( this ) ); +#else + xfer->xferUser( this, sizeof( *this ) ); +#endif } else diff --git a/GeneralsMD/Code/GameEngine/Include/Common/BitFlagsIO.h b/GeneralsMD/Code/GameEngine/Include/Common/BitFlagsIO.h index 2c9d8ba8aa..f579652028 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/BitFlagsIO.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/BitFlagsIO.h @@ -214,7 +214,11 @@ void BitFlags::xfer(Xfer* xfer) { // just call the xfer implementation on the data values +#if RETAIL_COMPATIBLE_CRC xfer->xferUser( this, sizeof( this ) ); +#else + xfer->xferUser( this, sizeof( *this ) ); +#endif } else From aed42f093aa4c4c71a2d28969248989b66fe4ebf Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Tue, 2 Dec 2025 21:29:38 +0100 Subject: [PATCH 18/70] refactor(mouse): Apply minor refactoring and whitespace tweaks in WinMain, Mouse, HeaderTemplate (#1939) --- .../Include/GameClient/HeaderTemplate.h | 2 +- .../GameEngine/Include/GameClient/Mouse.h | 6 +- .../GUI/GUICallbacks/Menus/MainMenu.cpp | 4 +- .../GUI/GUICallbacks/Menus/OptionsMenu.cpp | 4 +- .../Source/GameClient/GUI/HeaderTemplate.cpp | 2 +- .../Source/GameClient/Input/Mouse.cpp | 4 +- Generals/Code/Main/WinMain.cpp | 158 ++++++++-------- .../Include/GameClient/HeaderTemplate.h | 2 +- .../GameEngine/Include/GameClient/Mouse.h | 6 +- .../GUI/GUICallbacks/Menus/MainMenu.cpp | 4 +- .../GUI/GUICallbacks/Menus/OptionsMenu.cpp | 4 +- .../Source/GameClient/GUI/HeaderTemplate.cpp | 2 +- .../Source/GameClient/Input/Mouse.cpp | 4 +- GeneralsMD/Code/Main/WinMain.cpp | 176 ++++++++---------- 14 files changed, 177 insertions(+), 201 deletions(-) diff --git a/Generals/Code/GameEngine/Include/GameClient/HeaderTemplate.h b/Generals/Code/GameEngine/Include/GameClient/HeaderTemplate.h index 15f8816c37..edeec5a3c4 100644 --- a/Generals/Code/GameEngine/Include/GameClient/HeaderTemplate.h +++ b/Generals/Code/GameEngine/Include/GameClient/HeaderTemplate.h @@ -94,7 +94,7 @@ class HeaderTemplateManager HeaderTemplate *getFirstHeader( void ); HeaderTemplate *getNextHeader( HeaderTemplate *ht ); - void headerNotifyResolutionChange(void); + void onResolutionChanged(void); private: void populateGameFonts( void ); diff --git a/Generals/Code/GameEngine/Include/GameClient/Mouse.h b/Generals/Code/GameEngine/Include/GameClient/Mouse.h index 0b4b979c90..dc95a07634 100644 --- a/Generals/Code/GameEngine/Include/GameClient/Mouse.h +++ b/Generals/Code/GameEngine/Include/GameClient/Mouse.h @@ -310,10 +310,10 @@ class Mouse : public SubsystemInterface Int getCursorIndex( const AsciiString& name ); void resetTooltipDelay( void ); - virtual void loseFocus(); - virtual void regainFocus(); + virtual void loseFocus(); ///< called when window has lost focus + virtual void regainFocus(); ///< called when window has regained focus - void mouseNotifyResolutionChange(void); + void onResolutionChanged(void); void onGameModeChanged(GameMode prev, GameMode next); void onGamePaused(Bool paused); 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 699352fe08..926627b084 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp @@ -708,8 +708,8 @@ void DeclineResolution() TheWritableGlobalData->m_xResolution = newDispSettings.xRes; TheWritableGlobalData->m_yResolution = newDispSettings.yRes; - TheHeaderTemplateManager->headerNotifyResolutionChange(); - TheMouse->mouseNotifyResolutionChange(); + TheHeaderTemplateManager->onResolutionChanged(); + TheMouse->onResolutionChanged(); AsciiString prefString; prefString.format("%d %d", newDispSettings.xRes, newDispSettings.yRes); 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 32bb9002f3..1b1d9c9172 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp @@ -1540,8 +1540,8 @@ static void saveOptions( void ) TheWritableGlobalData->m_xResolution = xres; TheWritableGlobalData->m_yResolution = yres; - TheHeaderTemplateManager->headerNotifyResolutionChange(); - TheMouse->mouseNotifyResolutionChange(); + TheHeaderTemplateManager->onResolutionChanged(); + TheMouse->onResolutionChanged(); //Save new settings for a dialog box confirmation after options are accepted newDispSettings.xRes = xres; diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp index 2f07686158..c7288236ae 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp @@ -206,7 +206,7 @@ HeaderTemplate *HeaderTemplateManager::getNextHeader( HeaderTemplate *ht ) } -void HeaderTemplateManager::headerNotifyResolutionChange( void ) +void HeaderTemplateManager::onResolutionChanged( void ) { populateGameFonts(); } diff --git a/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp b/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp index 7331faec6b..f805e7ad3f 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp @@ -575,7 +575,7 @@ void Mouse::init( void ) m_numButtons = 2; // by default just have 2 buttons m_numAxes = 2; // by default a normal mouse moves in a 2d plane m_forceFeedback = FALSE; - mouseNotifyResolutionChange(); + onResolutionChanged(); m_tooltipString.clear(); // redundant m_displayTooltip = FALSE; @@ -607,7 +607,7 @@ void Mouse::init( void ) //------------------------------------------------------------------------------------------------- /** Tell mouse system display resolution changed. */ //------------------------------------------------------------------------------------------------- -void Mouse::mouseNotifyResolutionChange( void ) +void Mouse::onResolutionChanged( void ) { if(m_tooltipDisplayString) TheDisplayStringManager->freeDisplayString(m_tooltipDisplayString); diff --git a/Generals/Code/Main/WinMain.cpp b/Generals/Code/Main/WinMain.cpp index 303d6da1ce..9a3bbbcc2e 100644 --- a/Generals/Code/Main/WinMain.cpp +++ b/Generals/Code/Main/WinMain.cpp @@ -69,7 +69,7 @@ // GLOBALS //////////////////////////////////////////////////////////////////// HINSTANCE ApplicationHInstance = NULL; ///< our application instance HWND ApplicationHWnd = NULL; ///< our application window handle -Win32Mouse *TheWin32Mouse= NULL; ///< for the WndProc() only +Win32Mouse *TheWin32Mouse = NULL; ///< for the WndProc() only DWORD TheMessageTime = 0; ///< For getting the time that a message was posted from Windows. const Char *g_strFile = "data\\Generals.str"; @@ -315,77 +315,59 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, { //------------------------------------------------------------------------- case WM_NCHITTEST: - // Prevent the user from selecting the menu in fullscreen mode - if( !TheGlobalData->m_windowed ) - return HTCLIENT; - break; + // Prevent the user from selecting the menu in fullscreen mode + if( !TheGlobalData->m_windowed ) + return HTCLIENT; + break; //------------------------------------------------------------------------- case WM_POWERBROADCAST: - switch( wParam ) - { - #ifndef PBT_APMQUERYSUSPEND - #define PBT_APMQUERYSUSPEND 0x0000 - #endif - case PBT_APMQUERYSUSPEND: - // At this point, the app should save any data for open - // network connections, files, etc., and prepare to go into - // a suspended mode. - return TRUE; - - #ifndef PBT_APMRESUMESUSPEND - #define PBT_APMRESUMESUSPEND 0x0007 - #endif - case PBT_APMRESUMESUSPEND: - // At this point, the app should recover any data, network - // connections, files, etc., and resume running from when - // the app was suspended. - return TRUE; - } - break; + switch( wParam ) + { + #ifndef PBT_APMQUERYSUSPEND + #define PBT_APMQUERYSUSPEND 0x0000 + #endif + case PBT_APMQUERYSUSPEND: + // At this point, the app should save any data for open + // network connections, files, etc., and prepare to go into + // a suspended mode. + return TRUE; + + #ifndef PBT_APMRESUMESUSPEND + #define PBT_APMRESUMESUSPEND 0x0007 + #endif + case PBT_APMRESUMESUSPEND: + // At this point, the app should recover any data, network + // connections, files, etc., and resume running from when + // the app was suspended. + return TRUE; + } + break; //------------------------------------------------------------------------- case WM_SYSCOMMAND: - // Prevent moving/sizing and power loss in fullscreen mode - switch( wParam ) - { - case SC_KEYMENU: - // TheSuperHackers @bugfix Mauller 10/05/2025 Always handle this command to prevent halting the game when left Alt is pressed. - return 1; - case SC_MOVE: - case SC_SIZE: - case SC_MAXIMIZE: - case SC_MONITORPOWER: - if( !TheGlobalData->m_windowed ) - return 1; - break; - } - break; + // Prevent moving/sizing and power loss in fullscreen mode + switch( wParam ) + { + case SC_KEYMENU: + // TheSuperHackers @bugfix Mauller 10/05/2025 Always handle this command to prevent halting the game when left Alt is pressed. + return 1; + case SC_MOVE: + case SC_SIZE: + case SC_MAXIMIZE: + case SC_MONITORPOWER: + if( !TheGlobalData->m_windowed ) + return 1; + break; + } + break; // ------------------------------------------------------------------------ case WM_CLOSE: - TheGameEngine->checkAbnormalQuitting(); - TheGameEngine->reset(); - TheGameEngine->setQuitting(TRUE); - _exit(EXIT_SUCCESS); - return 0; - - // ------------------------------------------------------------------------ - case WM_SETFOCUS: - { - - // - // reset the state of our keyboard cause we haven't been paying - // attention to the keys while focus was away - // - if( TheKeyboard ) - TheKeyboard->resetKeys(); - - if (TheMouse) - TheMouse->regainFocus(); - - break; - - } + TheGameEngine->checkAbnormalQuitting(); + TheGameEngine->reset(); + TheGameEngine->setQuitting(TRUE); + _exit(EXIT_SUCCESS); + return 0; //------------------------------------------------------------------------- case WM_MOVE: @@ -409,6 +391,22 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, break; } + // ------------------------------------------------------------------------ + case WM_SETFOCUS: + { + // + // reset the state of our keyboard cause we haven't been paying + // attention to the keys while focus was away + // + if( TheKeyboard ) + TheKeyboard->resetKeys(); + + if (TheMouse) + TheMouse->regainFocus(); + + break; + } + //------------------------------------------------------------------------- case WM_KILLFOCUS: { @@ -439,13 +437,15 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, TheGameEngine->setIsActive(isWinMainActive); if (isWinMainActive) - { //restore mouse cursor to our custom version. + { + //restore mouse cursor to our custom version. if (TheWin32Mouse) TheWin32Mouse->setCursor(TheWin32Mouse->getMouseCursor()); } } return 0; } + //------------------------------------------------------------------------- case WM_ACTIVATE: { @@ -466,7 +466,6 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, TheMouse->refreshCursorCapture(); } break; - } //------------------------------------------------------------------------- @@ -476,21 +475,13 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, switch( key ) { - - //--------------------------------------------------------------------- case VK_ESCAPE: { - PostQuitMessage( 0 ); break; - } - - } - return 0; - } //------------------------------------------------------------------------- @@ -506,17 +497,18 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, case WM_RBUTTONUP: case WM_RBUTTONDBLCLK: { - if( TheWin32Mouse ) TheWin32Mouse->addWin32Event( message, wParam, lParam, TheMessageTime ); return 0; - } //------------------------------------------------------------------------- case 0x020A: // WM_MOUSEWHEEL { + if( TheWin32Mouse == NULL ) + return 0; + long x = (long) LOWORD(lParam); long y = (long) HIWORD(lParam); RECT rect; @@ -526,32 +518,28 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, if( x < rect.left || x > rect.right || y < rect.top || y > rect.bottom ) return 0; - if( TheWin32Mouse ) - TheWin32Mouse->addWin32Event( message, wParam, lParam, TheMessageTime ); - + TheWin32Mouse->addWin32Event( message, wParam, lParam, TheMessageTime ); return 0; - } - //------------------------------------------------------------------------- case WM_MOUSEMOVE: { + if( TheWin32Mouse == NULL ) + return 0; + Int x = (Int)LOWORD( lParam ); Int y = (Int)HIWORD( lParam ); RECT rect; -// Int keys = wParam; // ignore when outside of client area GetClientRect( ApplicationHWnd, &rect ); if( x < rect.left || x > rect.right || y < rect.top || y > rect.bottom ) return 0; - if( TheWin32Mouse ) - TheWin32Mouse->addWin32Event( message, wParam, lParam, TheMessageTime ); + TheWin32Mouse->addWin32Event( message, wParam, lParam, TheMessageTime ); return 0; - } //------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/HeaderTemplate.h b/GeneralsMD/Code/GameEngine/Include/GameClient/HeaderTemplate.h index 4ee31cf727..d7683eeb8d 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/HeaderTemplate.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/HeaderTemplate.h @@ -94,7 +94,7 @@ class HeaderTemplateManager HeaderTemplate *getFirstHeader( void ); HeaderTemplate *getNextHeader( HeaderTemplate *ht ); - void headerNotifyResolutionChange(void); + void onResolutionChanged(void); private: void populateGameFonts( void ); diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Mouse.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Mouse.h index d26d97317d..79f4a65158 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/Mouse.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Mouse.h @@ -310,10 +310,10 @@ class Mouse : public SubsystemInterface Int getCursorIndex( const AsciiString& name ); void resetTooltipDelay( void ); - virtual void loseFocus(); - virtual void regainFocus(); + virtual void loseFocus(); ///< called when window has lost focus + virtual void regainFocus(); ///< called when window has regained focus - void mouseNotifyResolutionChange(void); + void onResolutionChanged(void); void onGameModeChanged(GameMode prev, GameMode next); void onGamePaused(Bool paused); 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 e2cb0193c1..23b5e9ea14 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp @@ -745,8 +745,8 @@ void DeclineResolution() TheWritableGlobalData->m_xResolution = newDispSettings.xRes; TheWritableGlobalData->m_yResolution = newDispSettings.yRes; - TheHeaderTemplateManager->headerNotifyResolutionChange(); - TheMouse->mouseNotifyResolutionChange(); + TheHeaderTemplateManager->onResolutionChanged(); + TheMouse->onResolutionChanged(); AsciiString prefString; prefString.format("%d %d", newDispSettings.xRes, newDispSettings.yRes); 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 14d6063f8e..782cc525c8 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp @@ -1600,8 +1600,8 @@ static void saveOptions( void ) TheWritableGlobalData->m_xResolution = xres; TheWritableGlobalData->m_yResolution = yres; - TheHeaderTemplateManager->headerNotifyResolutionChange(); - TheMouse->mouseNotifyResolutionChange(); + TheHeaderTemplateManager->onResolutionChanged(); + TheMouse->onResolutionChanged(); //Save new settings for a dialog box confirmation after options are accepted newDispSettings.xRes = xres; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp index dfbd9e9c49..4b873a3a77 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp @@ -206,7 +206,7 @@ HeaderTemplate *HeaderTemplateManager::getNextHeader( HeaderTemplate *ht ) } -void HeaderTemplateManager::headerNotifyResolutionChange( void ) +void HeaderTemplateManager::onResolutionChanged( void ) { populateGameFonts(); } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp index b663e8d3b4..4aab5c56cf 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp @@ -575,7 +575,7 @@ void Mouse::init( void ) m_numButtons = 2; // by default just have 2 buttons m_numAxes = 2; // by default a normal mouse moves in a 2d plane m_forceFeedback = FALSE; - mouseNotifyResolutionChange(); + onResolutionChanged(); m_tooltipString.clear(); // redundant m_displayTooltip = FALSE; @@ -607,7 +607,7 @@ void Mouse::init( void ) //------------------------------------------------------------------------------------------------- /** Tell mouse system display resolution changed. */ //------------------------------------------------------------------------------------------------- -void Mouse::mouseNotifyResolutionChange( void ) +void Mouse::onResolutionChanged( void ) { if(m_tooltipDisplayString) TheDisplayStringManager->freeDisplayString(m_tooltipDisplayString); diff --git a/GeneralsMD/Code/Main/WinMain.cpp b/GeneralsMD/Code/Main/WinMain.cpp index 6017276941..76a6c2fad2 100644 --- a/GeneralsMD/Code/Main/WinMain.cpp +++ b/GeneralsMD/Code/Main/WinMain.cpp @@ -72,7 +72,7 @@ // GLOBALS //////////////////////////////////////////////////////////////////// HINSTANCE ApplicationHInstance = NULL; ///< our application instance HWND ApplicationHWnd = NULL; ///< our application window handle -Win32Mouse *TheWin32Mouse= NULL; ///< for the WndProc() only +Win32Mouse *TheWin32Mouse = NULL; ///< for the WndProc() only DWORD TheMessageTime = 0; ///< For getting the time that a message was posted from Windows. const Char *g_strFile = "data\\Generals.str"; @@ -318,51 +318,51 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, { //------------------------------------------------------------------------- case WM_NCHITTEST: - // Prevent the user from selecting the menu in fullscreen mode - if( !TheGlobalData->m_windowed ) - return HTCLIENT; - break; + // Prevent the user from selecting the menu in fullscreen mode + if( !TheGlobalData->m_windowed ) + return HTCLIENT; + break; //------------------------------------------------------------------------- case WM_POWERBROADCAST: - switch( wParam ) - { - #ifndef PBT_APMQUERYSUSPEND - #define PBT_APMQUERYSUSPEND 0x0000 - #endif - case PBT_APMQUERYSUSPEND: - // At this point, the app should save any data for open - // network connections, files, etc., and prepare to go into - // a suspended mode. - return TRUE; - - #ifndef PBT_APMRESUMESUSPEND - #define PBT_APMRESUMESUSPEND 0x0007 - #endif - case PBT_APMRESUMESUSPEND: - // At this point, the app should recover any data, network - // connections, files, etc., and resume running from when - // the app was suspended. - return TRUE; - } - break; + switch( wParam ) + { + #ifndef PBT_APMQUERYSUSPEND + #define PBT_APMQUERYSUSPEND 0x0000 + #endif + case PBT_APMQUERYSUSPEND: + // At this point, the app should save any data for open + // network connections, files, etc., and prepare to go into + // a suspended mode. + return TRUE; + + #ifndef PBT_APMRESUMESUSPEND + #define PBT_APMRESUMESUSPEND 0x0007 + #endif + case PBT_APMRESUMESUSPEND: + // At this point, the app should recover any data, network + // connections, files, etc., and resume running from when + // the app was suspended. + return TRUE; + } + break; //------------------------------------------------------------------------- case WM_SYSCOMMAND: - // Prevent moving/sizing and power loss in fullscreen mode - switch( wParam ) - { - case SC_KEYMENU: - // TheSuperHackers @bugfix Mauller 10/05/2025 Always handle this command to prevent halting the game when left Alt is pressed. - return 1; - case SC_MOVE: - case SC_SIZE: - case SC_MAXIMIZE: - case SC_MONITORPOWER: - if( !TheGlobalData->m_windowed ) - return 1; - break; - } - break; + // Prevent moving/sizing and power loss in fullscreen mode + switch( wParam ) + { + case SC_KEYMENU: + // TheSuperHackers @bugfix Mauller 10/05/2025 Always handle this command to prevent halting the game when left Alt is pressed. + return 1; + case SC_MOVE: + case SC_SIZE: + case SC_MAXIMIZE: + case SC_MONITORPOWER: + if( !TheGlobalData->m_windowed ) + return 1; + break; + } + break; case WM_QUERYENDSESSION: { @@ -372,42 +372,24 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, // ------------------------------------------------------------------------ case WM_CLOSE: - if (!TheGameEngine->getQuitting()) - { - //user is exiting without using the menus + if (!TheGameEngine->getQuitting()) + { + //user is exiting without using the menus - //This method didn't work in cinematics because we don't process messages. - //But it's the cleanest way to exit that's similar to using menus. - TheMessageStream->appendMessage(GameMessage::MSG_META_DEMO_INSTANT_QUIT); + //This method didn't work in cinematics because we don't process messages. + //But it's the cleanest way to exit that's similar to using menus. + TheMessageStream->appendMessage(GameMessage::MSG_META_DEMO_INSTANT_QUIT); - //This method used to disable quitting. We just put up the options screen instead. - //TheMessageStream->appendMessage(GameMessage::MSG_META_OPTIONS); + //This method used to disable quitting. We just put up the options screen instead. + //TheMessageStream->appendMessage(GameMessage::MSG_META_OPTIONS); - //This method works everywhere but isn't as clean at shutting down. - //TheGameEngine->checkAbnormalQuitting(); //old way to log disconnections for ALT-F4 - //TheGameEngine->reset(); - //TheGameEngine->setQuitting(TRUE); - //_exit(EXIT_SUCCESS); + //This method works everywhere but isn't as clean at shutting down. + //TheGameEngine->checkAbnormalQuitting(); //old way to log disconnections for ALT-F4 + //TheGameEngine->reset(); + //TheGameEngine->setQuitting(TRUE); + //_exit(EXIT_SUCCESS); + } return 0; - } - - // ------------------------------------------------------------------------ - case WM_SETFOCUS: - { - - // - // reset the state of our keyboard cause we haven't been paying - // attention to the keys while focus was away - // - if( TheKeyboard ) - TheKeyboard->resetKeys(); - - if (TheMouse) - TheMouse->regainFocus(); - - break; - - } //------------------------------------------------------------------------- case WM_MOVE: @@ -431,6 +413,22 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, break; } + // ------------------------------------------------------------------------ + case WM_SETFOCUS: + { + // + // reset the state of our keyboard cause we haven't been paying + // attention to the keys while focus was away + // + if( TheKeyboard ) + TheKeyboard->resetKeys(); + + if (TheMouse) + TheMouse->regainFocus(); + + break; + } + //------------------------------------------------------------------------- case WM_KILLFOCUS: { @@ -461,13 +459,15 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, TheGameEngine->setIsActive(isWinMainActive); if (isWinMainActive) - { //restore mouse cursor to our custom version. + { + //restore mouse cursor to our custom version. if (TheWin32Mouse) TheWin32Mouse->setCursor(TheWin32Mouse->getMouseCursor()); } } return 0; } + //------------------------------------------------------------------------- case WM_ACTIVATE: { @@ -488,7 +488,6 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, TheMouse->refreshCursorCapture(); } break; - } //------------------------------------------------------------------------- @@ -498,21 +497,13 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, switch( key ) { - - //--------------------------------------------------------------------- case VK_ESCAPE: { - PostQuitMessage( 0 ); break; - } - - } - return 0; - } //------------------------------------------------------------------------- @@ -528,17 +519,18 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, case WM_RBUTTONUP: case WM_RBUTTONDBLCLK: { - if( TheWin32Mouse ) TheWin32Mouse->addWin32Event( message, wParam, lParam, TheMessageTime ); return 0; - } //------------------------------------------------------------------------- case 0x020A: // WM_MOUSEWHEEL { + if( TheWin32Mouse == NULL ) + return 0; + long x = (long) LOWORD(lParam); long y = (long) HIWORD(lParam); RECT rect; @@ -548,32 +540,28 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, if( x < rect.left || x > rect.right || y < rect.top || y > rect.bottom ) return 0; - if( TheWin32Mouse ) - TheWin32Mouse->addWin32Event( message, wParam, lParam, TheMessageTime ); - + TheWin32Mouse->addWin32Event( message, wParam, lParam, TheMessageTime ); return 0; - } - //------------------------------------------------------------------------- case WM_MOUSEMOVE: { + if( TheWin32Mouse == NULL ) + return 0; + Int x = (Int)LOWORD( lParam ); Int y = (Int)HIWORD( lParam ); RECT rect; -// Int keys = wParam; // ignore when outside of client area GetClientRect( ApplicationHWnd, &rect ); if( x < rect.left || x > rect.right || y < rect.top || y > rect.bottom ) return 0; - if( TheWin32Mouse ) - TheWin32Mouse->addWin32Event( message, wParam, lParam, TheMessageTime ); + TheWin32Mouse->addWin32Event( message, wParam, lParam, TheMessageTime ); return 0; - } //------------------------------------------------------------------------- From 68d832f2d58018cb949e6f89aec679b45c49734c Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Tue, 2 Dec 2025 21:31:46 +0100 Subject: [PATCH 19/70] bugfix(mouse): Prevent cursor capture when mouse is outside of app window (#1939) --- .../GameEngine/Include/GameClient/Mouse.h | 5 +++++ .../Source/GameClient/Input/Mouse.cpp | 19 +++++++++++++++++ Generals/Code/Main/WinMain.cpp | 21 +++++++++++++++++++ .../GameEngine/Include/GameClient/Mouse.h | 5 +++++ .../Source/GameClient/Input/Mouse.cpp | 19 +++++++++++++++++ GeneralsMD/Code/Main/WinMain.cpp | 21 +++++++++++++++++++ 6 files changed, 90 insertions(+) diff --git a/Generals/Code/GameEngine/Include/GameClient/Mouse.h b/Generals/Code/GameEngine/Include/GameClient/Mouse.h index dc95a07634..bdb94d9578 100644 --- a/Generals/Code/GameEngine/Include/GameClient/Mouse.h +++ b/Generals/Code/GameEngine/Include/GameClient/Mouse.h @@ -170,6 +170,7 @@ class Mouse : public SubsystemInterface CursorCaptureBlockReason_NoInit, CursorCaptureBlockReason_Paused, CursorCaptureBlockReason_Unfocused, + CursorCaptureBlockReadon_CursorIsOutside, CursorCaptureBlockReason_Count }; @@ -313,6 +314,10 @@ class Mouse : public SubsystemInterface virtual void loseFocus(); ///< called when window has lost focus virtual void regainFocus(); ///< called when window has regained focus + void onCursorMovedOutside(); ///< called when cursor has left game window + void onCursorMovedInside(); ///< called when cursor has entered game window + Bool isCursorInside() const; ///< true if the mouse is located inside the game window + void onResolutionChanged(void); void onGameModeChanged(GameMode prev, GameMode next); void onGamePaused(Bool paused); diff --git a/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp b/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp index f805e7ad3f..903a52b8a2 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp @@ -64,6 +64,7 @@ const char *const Mouse::CursorCaptureBlockReasonNames[] = { "CursorCaptureBlockReason_NoInit", "CursorCaptureBlockReason_Paused", "CursorCaptureBlockReason_Unfocused", + "CursorCaptureBlockReason_CursorIsOutside", }; /////////////////////////////////////////////////////////////////////////////////////////////////// @@ -1034,6 +1035,24 @@ void Mouse::regainFocus() unblockCapture(CursorCaptureBlockReason_Unfocused); } +// ------------------------------------------------------------------------------------------------ +void Mouse::onCursorMovedOutside() +{ + blockCapture(CursorCaptureBlockReadon_CursorIsOutside); +} + +// ------------------------------------------------------------------------------------------------ +void Mouse::onCursorMovedInside() +{ + unblockCapture(CursorCaptureBlockReadon_CursorIsOutside); +} + +// ------------------------------------------------------------------------------------------------ +Bool Mouse::isCursorInside() const +{ + return (m_captureBlockReasonBits & (1 << CursorCaptureBlockReadon_CursorIsOutside)) == 0; +} + // ------------------------------------------------------------------------------------------------ void Mouse::initCapture() { diff --git a/Generals/Code/Main/WinMain.cpp b/Generals/Code/Main/WinMain.cpp index 9a3bbbcc2e..9af234e3a5 100644 --- a/Generals/Code/Main/WinMain.cpp +++ b/Generals/Code/Main/WinMain.cpp @@ -414,8 +414,15 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, TheKeyboard->resetKeys(); if (TheMouse) + { TheMouse->loseFocus(); + if (TheMouse->isCursorInside()) + { + TheMouse->onCursorMovedOutside(); + } + } + break; } @@ -528,6 +535,10 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, if( TheWin32Mouse == NULL ) return 0; + // ignore when window is not active + if( !isWinMainActive ) + return 0; + Int x = (Int)LOWORD( lParam ); Int y = (Int)HIWORD( lParam ); RECT rect; @@ -535,8 +546,18 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, // ignore when outside of client area GetClientRect( ApplicationHWnd, &rect ); if( x < rect.left || x > rect.right || y < rect.top || y > rect.bottom ) + { + if ( TheMouse->isCursorInside() ) + { + TheMouse->onCursorMovedOutside(); + } return 0; + } + if( !TheMouse->isCursorInside() ) + { + TheMouse->onCursorMovedInside(); + } TheWin32Mouse->addWin32Event( message, wParam, lParam, TheMessageTime ); return 0; diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Mouse.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Mouse.h index 79f4a65158..8d22891b39 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/Mouse.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Mouse.h @@ -170,6 +170,7 @@ class Mouse : public SubsystemInterface CursorCaptureBlockReason_NoInit, CursorCaptureBlockReason_Paused, CursorCaptureBlockReason_Unfocused, + CursorCaptureBlockReadon_CursorIsOutside, CursorCaptureBlockReason_Count }; @@ -313,6 +314,10 @@ class Mouse : public SubsystemInterface virtual void loseFocus(); ///< called when window has lost focus virtual void regainFocus(); ///< called when window has regained focus + void onCursorMovedOutside(); ///< called when cursor has left game window + void onCursorMovedInside(); ///< called when cursor has entered game window + Bool isCursorInside() const; ///< true if the mouse is located inside the game window + void onResolutionChanged(void); void onGameModeChanged(GameMode prev, GameMode next); void onGamePaused(Bool paused); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp index 4aab5c56cf..db0e9c745f 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp @@ -64,6 +64,7 @@ const char *const Mouse::CursorCaptureBlockReasonNames[] = { "CursorCaptureBlockReason_NoInit", "CursorCaptureBlockReason_Paused", "CursorCaptureBlockReason_Unfocused", + "CursorCaptureBlockReason_CursorIsOutside", }; /////////////////////////////////////////////////////////////////////////////////////////////////// @@ -1034,6 +1035,24 @@ void Mouse::regainFocus() unblockCapture(CursorCaptureBlockReason_Unfocused); } +// ------------------------------------------------------------------------------------------------ +void Mouse::onCursorMovedOutside() +{ + blockCapture(CursorCaptureBlockReadon_CursorIsOutside); +} + +// ------------------------------------------------------------------------------------------------ +void Mouse::onCursorMovedInside() +{ + unblockCapture(CursorCaptureBlockReadon_CursorIsOutside); +} + +// ------------------------------------------------------------------------------------------------ +Bool Mouse::isCursorInside() const +{ + return (m_captureBlockReasonBits & (1 << CursorCaptureBlockReadon_CursorIsOutside)) == 0; +} + // ------------------------------------------------------------------------------------------------ void Mouse::initCapture() { diff --git a/GeneralsMD/Code/Main/WinMain.cpp b/GeneralsMD/Code/Main/WinMain.cpp index 76a6c2fad2..fb91c4fbea 100644 --- a/GeneralsMD/Code/Main/WinMain.cpp +++ b/GeneralsMD/Code/Main/WinMain.cpp @@ -436,8 +436,15 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, TheKeyboard->resetKeys(); if (TheMouse) + { TheMouse->loseFocus(); + if (TheMouse->isCursorInside()) + { + TheMouse->onCursorMovedOutside(); + } + } + break; } @@ -550,6 +557,10 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, if( TheWin32Mouse == NULL ) return 0; + // ignore when window is not active + if( !isWinMainActive ) + return 0; + Int x = (Int)LOWORD( lParam ); Int y = (Int)HIWORD( lParam ); RECT rect; @@ -557,8 +568,18 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, // ignore when outside of client area GetClientRect( ApplicationHWnd, &rect ); if( x < rect.left || x > rect.right || y < rect.top || y > rect.bottom ) + { + if ( TheMouse->isCursorInside() ) + { + TheMouse->onCursorMovedOutside(); + } return 0; + } + if( !TheMouse->isCursorInside() ) + { + TheMouse->onCursorMovedInside(); + } TheWin32Mouse->addWin32Event( message, wParam, lParam, TheMessageTime ); return 0; From f4608dfde9f8f64a3bce7d7cb6ae0a2191cbc72d Mon Sep 17 00:00:00 2001 From: Paul Levlin Date: Sun, 7 Dec 2025 13:31:10 +0100 Subject: [PATCH 20/70] feat(crashdump): Add crash dump functionality for fatal errors (#1594) Crash dumps are stored in %USERPROFILE%\Documents\Command and Conquer Generals Zero Hour Data\CrashDumps --- Core/GameEngine/CMakeLists.txt | 2 + Core/GameEngine/Include/Common/MiniDumper.h | 97 ++++ .../GameEngine/Source/Common/System/Debug.cpp | 23 + .../Source/Common/System/MiniDumper.cpp | 461 ++++++++++++++++++ .../Source/WWVegas/WWLib/CMakeLists.txt | 1 + .../Source/WWVegas/WWLib/DbgHelpLoader.cpp | 28 ++ .../Source/WWVegas/WWLib/DbgHelpLoader.h | 29 +- .../WWVegas/WWLib/DbgHelpLoader_minidump.h | 265 ++++++++++ Generals/Code/Main/WinMain.cpp | 20 + GeneralsMD/Code/Main/WinMain.cpp | 20 + cmake/config-memory.cmake | 12 + 11 files changed, 957 insertions(+), 1 deletion(-) create mode 100644 Core/GameEngine/Include/Common/MiniDumper.h create mode 100644 Core/GameEngine/Source/Common/System/MiniDumper.cpp create mode 100644 Core/Libraries/Source/WWVegas/WWLib/DbgHelpLoader_minidump.h diff --git a/Core/GameEngine/CMakeLists.txt b/Core/GameEngine/CMakeLists.txt index 1c2ca6c6b1..8c720b6238 100644 --- a/Core/GameEngine/CMakeLists.txt +++ b/Core/GameEngine/CMakeLists.txt @@ -72,6 +72,7 @@ set(GAMEENGINE_SRC # Include/Common/MapObject.h # Include/Common/MapReaderWriterInfo.h # Include/Common/MessageStream.h + Include/Common/MiniDumper.h # Include/Common/MiniLog.h Include/Common/MiscAudio.h # Include/Common/MissionStats.h @@ -660,6 +661,7 @@ set(GAMEENGINE_SRC # Source/Common/System/List.cpp Source/Common/System/LocalFile.cpp Source/Common/System/LocalFileSystem.cpp + Source/Common/System/MiniDumper.cpp Source/Common/System/ObjectStatusTypes.cpp # Source/Common/System/QuotedPrintable.cpp Source/Common/System/Radar.cpp diff --git a/Core/GameEngine/Include/Common/MiniDumper.h b/Core/GameEngine/Include/Common/MiniDumper.h new file mode 100644 index 0000000000..44c03e96ef --- /dev/null +++ b/Core/GameEngine/Include/Common/MiniDumper.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 . +*/ + +#pragma once + +#ifdef RTS_ENABLE_CRASHDUMP +#include "DbgHelpLoader.h" + +enum DumpType CPP_11(: Char) +{ + // Smallest dump type with call stacks and some supporting variables + DumpType_Minimal = 'M', + // Largest dump size including complete memory contents of the process + DumpType_Full = 'F', +}; + +class MiniDumper +{ + enum MiniDumperExitCode CPP_11(: Int) + { + MiniDumperExitCode_Success = 0x0, + MiniDumperExitCode_FailureWait = 0x37DA1040, + MiniDumperExitCode_FailureParam = 0x4EA527BB, + MiniDumperExitCode_ForcedTerminate = 0x158B1154, + }; + +public: + MiniDumper(); + Bool IsInitialized() const; + void TriggerMiniDump(DumpType dumpType); + void TriggerMiniDumpForException(_EXCEPTION_POINTERS* e_info, DumpType dumpType); + static void initMiniDumper(const AsciiString& userDirPath); + static void shutdownMiniDumper(); + static LONG WINAPI DumpingExceptionFilter(_EXCEPTION_POINTERS* e_info); + +private: + void Initialize(const AsciiString& userDirPath); + void ShutDown(); + void CreateMiniDump(DumpType dumpType); + void CleanupResources(); + Bool IsDumpThreadStillRunning() const; + void ShutdownDumpThread(); + + // Thread procs + static DWORD WINAPI MiniDumpThreadProc(LPVOID lpParam); + DWORD ThreadProcInternal(); + + // Dump file directory bookkeeping + Bool InitializeDumpDirectory(const AsciiString& userDirPath); + static void KeepNewestFiles(const std::string& directory, const DumpType dumpType, const Int keepCount); + + // Struct to hold file information + struct FileInfo + { + std::string name; + FILETIME lastWriteTime; + }; + + static bool CompareByLastWriteTime(const FileInfo& a, const FileInfo& b); + +private: + Bool m_miniDumpInitialized; + Bool m_loadedDbgHelp; + DumpType m_requestedDumpType; + + // Path buffers + Char m_dumpDir[MAX_PATH]; + Char m_dumpFile[MAX_PATH]; + WideChar m_executablePath[MAX_PATH]; + + // Event handles + HANDLE m_dumpRequested; + HANDLE m_dumpComplete; + HANDLE m_quitting; + + // Thread handles + HANDLE m_dumpThread; + DWORD m_dumpThreadId; +}; + +extern MiniDumper* TheMiniDumper; +#endif diff --git a/Core/GameEngine/Source/Common/System/Debug.cpp b/Core/GameEngine/Source/Common/System/Debug.cpp index 385dd85616..33ddbff460 100644 --- a/Core/GameEngine/Source/Common/System/Debug.cpp +++ b/Core/GameEngine/Source/Common/System/Debug.cpp @@ -70,6 +70,9 @@ #if defined(DEBUG_STACKTRACE) || defined(IG_DEBUG_STACKTRACE) #include "Common/StackDump.h" #endif +#ifdef RTS_ENABLE_CRASHDUMP +#include "Common/MiniDumper.h" +#endif // Horrible reference, but we really, really need to know if we are windowed. extern bool DX8Wrapper_IsWindowed; @@ -727,6 +730,22 @@ double SimpleProfiler::getAverageTime() } } + +static void TriggerMiniDump() +{ +#ifdef RTS_ENABLE_CRASHDUMP + if (TheMiniDumper && TheMiniDumper->IsInitialized()) + { + // Create both minimal and full memory dumps + TheMiniDumper->TriggerMiniDump(DumpType_Minimal); + TheMiniDumper->TriggerMiniDump(DumpType_Full); + } + + MiniDumper::shutdownMiniDumper(); +#endif +} + + void ReleaseCrash(const char *reason) { /// do additional reporting on the crash, if possible @@ -737,6 +756,8 @@ void ReleaseCrash(const char *reason) } } + TriggerMiniDump(); + char prevbuf[ _MAX_PATH ]; char curbuf[ _MAX_PATH ]; @@ -813,6 +834,8 @@ void ReleaseCrashLocalized(const AsciiString& p, const AsciiString& m) return; } + TriggerMiniDump(); + UnicodeString prompt = TheGameText->fetch(p); UnicodeString mesg = TheGameText->fetch(m); diff --git a/Core/GameEngine/Source/Common/System/MiniDumper.cpp b/Core/GameEngine/Source/Common/System/MiniDumper.cpp new file mode 100644 index 0000000000..21ab80e578 --- /dev/null +++ b/Core/GameEngine/Source/Common/System/MiniDumper.cpp @@ -0,0 +1,461 @@ +/* +** 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" // This must go first in EVERY cpp file in the GameEngine + +#ifdef RTS_ENABLE_CRASHDUMP +#include "Common/MiniDumper.h" +#include +#include "gitinfo.h" + +// Globals for storing the pointer to the exception +_EXCEPTION_POINTERS* g_dumpException = NULL; +DWORD g_dumpExceptionThreadId = 0; + +MiniDumper* TheMiniDumper = NULL; + +// Globals containing state about the current exception that's used for context in the mini dump. +// These are populated by MiniDumper::DumpingExceptionFilter to store a copy of the exception in case it goes out of scope +_EXCEPTION_POINTERS g_exceptionPointers = { 0 }; +EXCEPTION_RECORD g_exceptionRecord = { 0 }; +CONTEXT g_exceptionContext = { 0 }; + +constexpr const char* DumpFileNamePrefix = "Crash"; + +void MiniDumper::initMiniDumper(const AsciiString& userDirPath) +{ + DEBUG_ASSERTCRASH(TheMiniDumper == NULL, ("MiniDumper::initMiniDumper called on already created instance")); + + // Use placement new on the process heap so TheMiniDumper is placed outside the MemoryPoolFactory managed area. + // If the crash is due to corrupted MemoryPoolFactory structures, try to mitigate the chances of MiniDumper memory also being corrupted + TheMiniDumper = new (::HeapAlloc(::GetProcessHeap(), HEAP_GENERATE_EXCEPTIONS, sizeof(MiniDumper))) MiniDumper; + TheMiniDumper->Initialize(userDirPath); +} + +void MiniDumper::shutdownMiniDumper() +{ + if (TheMiniDumper) + { + TheMiniDumper->ShutDown(); + TheMiniDumper->~MiniDumper(); + ::HeapFree(::GetProcessHeap(), NULL, TheMiniDumper); + TheMiniDumper = NULL; + } +} + +MiniDumper::MiniDumper() +{ + m_miniDumpInitialized = false; + m_loadedDbgHelp = false; + m_requestedDumpType = DumpType_Minimal; + m_dumpRequested = NULL; + m_dumpComplete = NULL; + m_quitting = NULL; + m_dumpThread = NULL; + m_dumpThreadId = 0; + m_dumpDir[0] = 0; + m_dumpFile[0] = 0; + m_executablePath[0] = 0; +}; + +LONG WINAPI MiniDumper::DumpingExceptionFilter(_EXCEPTION_POINTERS* e_info) +{ + // Store the exception info in the global variables for later use by the dumping thread + g_exceptionRecord = *(e_info->ExceptionRecord); + g_exceptionContext = *(e_info->ContextRecord); + g_exceptionPointers.ContextRecord = &g_exceptionContext; + g_exceptionPointers.ExceptionRecord = &g_exceptionRecord; + g_dumpException = &g_exceptionPointers; + + return EXCEPTION_EXECUTE_HANDLER; +} + +void MiniDumper::TriggerMiniDump(DumpType dumpType) +{ + if (!m_miniDumpInitialized) + { + DEBUG_LOG(("MiniDumper::TriggerMiniDump: Attempted to use an uninitialized instance.")); + return; + } + + __try + { + // Use DebugBreak to raise an exception that can be caught in the __except block + ::DebugBreak(); + } + __except (DumpingExceptionFilter(GetExceptionInformation())) + { + TriggerMiniDumpForException(g_dumpException, dumpType); + } +} + +void MiniDumper::TriggerMiniDumpForException(_EXCEPTION_POINTERS* e_info, DumpType dumpType) +{ + if (!m_miniDumpInitialized) + { + DEBUG_LOG(("MiniDumper::TriggerMiniDumpForException: Attempted to use an uninitialized instance.")); + return; + } + + g_dumpException = e_info; + g_dumpExceptionThreadId = ::GetCurrentThreadId(); + m_requestedDumpType = dumpType; + + DEBUG_ASSERTCRASH(IsDumpThreadStillRunning(), ("MiniDumper::TriggerMiniDumpForException: Dumping thread has exited.")); + ::SetEvent(m_dumpRequested); + DWORD wait = ::WaitForSingleObject(m_dumpComplete, INFINITE); + if (wait != WAIT_OBJECT_0) + { + if (wait == WAIT_FAILED) + { + DEBUG_LOG(("MiniDumper::TriggerMiniDumpForException: Waiting for minidump triggering failed: status=%u, error=%u", wait, ::GetLastError())); + } + else + { + DEBUG_LOG(("MiniDumper::TriggerMiniDumpForException: Waiting for minidump triggering failed: status=%u", wait)); + } + } + + ::ResetEvent(m_dumpComplete); +} + +void MiniDumper::Initialize(const AsciiString& userDirPath) +{ + m_loadedDbgHelp = DbgHelpLoader::load(); + + // We want to only use the dbghelp.dll from the OS installation, as the one bundled with the game does not support MiniDump functionality + if (!(m_loadedDbgHelp && DbgHelpLoader::isLoadedFromSystem())) + { + DEBUG_LOG(("MiniDumper::Initialize: Unable to load system-provided dbghelp.dll, minidump functionality disabled.")); + return; + } + + DWORD executableSize = ::GetModuleFileNameW(NULL, m_executablePath, ARRAY_SIZE(m_executablePath)); + if (executableSize == 0 || executableSize == ARRAY_SIZE(m_executablePath)) + { + DEBUG_LOG(("MiniDumper::Initialize: Could not get executable file name. Returned value=%u", executableSize)); + return; + } + + // Create & store dump folder + if (!InitializeDumpDirectory(userDirPath)) + { + return; + } + + m_dumpRequested = CreateEvent(NULL, TRUE, FALSE, NULL); + m_dumpComplete = CreateEvent(NULL, TRUE, FALSE, NULL); + m_quitting = CreateEvent(NULL, TRUE, FALSE, NULL); + + if (m_dumpRequested == NULL || m_dumpComplete == NULL || m_quitting == NULL) + { + // Something went wrong with the creation of the events.. + DEBUG_LOG(("MiniDumper::Initialize: Unable to create events: error=%u", ::GetLastError())); + return; + } + + m_dumpThread = ::CreateThread(NULL, 0, MiniDumpThreadProc, this, CREATE_SUSPENDED, &m_dumpThreadId); + if (!m_dumpThread) + { + DEBUG_LOG(("MiniDumper::Initialize: Unable to create thread: error=%u", ::GetLastError())); + return; + } + + if (::ResumeThread(m_dumpThread) != 1) + { + DEBUG_LOG(("MiniDumper::Initialize: Unable to resume thread: error=%u", ::GetLastError())); + return; + } + + DEBUG_LOG(("MiniDumper::Initialize: Configured to store crash dumps in '%s'", m_dumpDir)); + m_miniDumpInitialized = true; +} + +Bool MiniDumper::IsInitialized() const +{ + return m_miniDumpInitialized; +} + +Bool MiniDumper::IsDumpThreadStillRunning() const +{ + DWORD exitCode; + if (m_dumpThread != NULL && ::GetExitCodeThread(m_dumpThread, &exitCode) && exitCode == STILL_ACTIVE) + { + return true; + } + + return false; +} + +Bool MiniDumper::InitializeDumpDirectory(const AsciiString& userDirPath) +{ + constexpr const Int MaxFullFileCount = 2; + constexpr const Int MaxMiniFileCount = 10; + + strlcpy(m_dumpDir, userDirPath.str(), ARRAY_SIZE(m_dumpDir)); + strlcat(m_dumpDir, "CrashDumps\\", ARRAY_SIZE(m_dumpDir)); + if (::_access(m_dumpDir, 0) != 0) + { + if (!::CreateDirectory(m_dumpDir, NULL)) + { + DEBUG_LOG(("MiniDumper::Initialize: Unable to create path for crash dumps at '%s': error=%u", m_dumpDir, ::GetLastError())); + return false; + } + } + + // Clean up old files (we keep a maximum of 10 small, 2 full) + KeepNewestFiles(m_dumpDir, DumpType_Full, MaxFullFileCount); + KeepNewestFiles(m_dumpDir, DumpType_Minimal, MaxMiniFileCount); + + return true; +} + +void MiniDumper::ShutdownDumpThread() +{ + if (IsDumpThreadStillRunning()) + { + DEBUG_ASSERTCRASH(m_quitting != NULL, ("MiniDumper::ShutdownDumpThread: Dump thread still running despite m_quitting being NULL")); + ::SetEvent(m_quitting); + + DWORD waitRet = ::WaitForSingleObject(m_dumpThread, 3000); + switch (waitRet) + { + case WAIT_OBJECT_0: + // Wait for thread exit was successful + break; + case WAIT_TIMEOUT: + DEBUG_LOG(("MiniDumper::ShutdownDumpThread: Waiting for dumping thread to exit timed out, killing thread", waitRet)); + ::TerminateThread(m_dumpThread, MiniDumperExitCode_ForcedTerminate); + break; + case WAIT_FAILED: + DEBUG_LOG(("MiniDumper::ShutdownDumpThread: Waiting for minidump triggering failed: status=%u, error=%u", waitRet, ::GetLastError())); + break; + default: + DEBUG_LOG(("MiniDumper::ShutdownDumpThread: Waiting for minidump triggering failed: status=%u", waitRet)); + break; + } + } +} + +void MiniDumper::ShutDown() +{ + ShutdownDumpThread(); + + if (m_dumpThread != NULL) + { + DEBUG_ASSERTCRASH(!IsDumpThreadStillRunning(), ("MiniDumper::ShutDown: ShutdownDumpThread() was unable to stop Dump thread")); + ::CloseHandle(m_dumpThread); + m_dumpThread = NULL; + } + + if (m_quitting != NULL) + { + ::CloseHandle(m_quitting); + m_quitting = NULL; + } + + if (m_dumpComplete != NULL) + { + ::CloseHandle(m_dumpComplete); + m_dumpComplete = NULL; + } + + if (m_dumpRequested != NULL) + { + ::CloseHandle(m_dumpRequested); + m_dumpRequested = NULL; + } + + if (m_loadedDbgHelp) + { + DbgHelpLoader::unload(); + m_loadedDbgHelp = false; + } + + m_miniDumpInitialized = false; +} + +DWORD MiniDumper::ThreadProcInternal() +{ + while (true) + { + HANDLE waitEvents[2] = { m_dumpRequested, m_quitting }; + DWORD event = ::WaitForMultipleObjects(ARRAY_SIZE(waitEvents), waitEvents, FALSE, INFINITE); + switch (event) + { + case WAIT_OBJECT_0 + 0: + // A dump is requested (m_dumpRequested) + ::ResetEvent(m_dumpComplete); + CreateMiniDump(m_requestedDumpType); + ::ResetEvent(m_dumpRequested); + ::SetEvent(m_dumpComplete); + break; + case WAIT_OBJECT_0 + 1: + // Quit (m_quitting) + return MiniDumperExitCode_Success; + case WAIT_FAILED: + DEBUG_LOG(("MiniDumper::ThreadProcInternal: Waiting for events failed: status=%u, error=%u", event, ::GetLastError())); + return MiniDumperExitCode_FailureWait; + default: + DEBUG_LOG(("MiniDumper::ThreadProcInternal: Waiting for events failed: status=%u", event)); + return MiniDumperExitCode_FailureWait; + } + } +} + +DWORD WINAPI MiniDumper::MiniDumpThreadProc(LPVOID lpParam) +{ + if (lpParam == NULL) + { + DEBUG_LOG(("MiniDumper::MiniDumpThreadProc: The provided parameter was NULL, exiting thread.")); + return MiniDumperExitCode_FailureParam; + } + + MiniDumper* dumper = static_cast(lpParam); + return dumper->ThreadProcInternal(); +} + + +void MiniDumper::CreateMiniDump(DumpType dumpType) +{ + // Create a unique dump file name, using the path from m_dumpDir, in m_dumpFile + SYSTEMTIME sysTime; + ::GetLocalTime(&sysTime); +#if RTS_GENERALS + const Char product = 'G'; +#elif RTS_ZEROHOUR + const Char product = 'Z'; +#endif + Char dumpTypeSpecifier = static_cast(dumpType); + DWORD currentProcessId = ::GetCurrentProcessId(); + + // m_dumpDir is stored with trailing backslash in Initialize + snprintf(m_dumpFile, ARRAY_SIZE(m_dumpFile), "%s%s%c%c-%04d%02d%02d-%02d%02d%02d-%s-pid%ld.dmp", + m_dumpDir, DumpFileNamePrefix, dumpTypeSpecifier, product, sysTime.wYear, sysTime.wMonth, + sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond, + GitShortSHA1, currentProcessId); + + HANDLE dumpFile = ::CreateFile(m_dumpFile, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (dumpFile == NULL || dumpFile == INVALID_HANDLE_VALUE) + { + DEBUG_LOG(("MiniDumper::CreateMiniDump: Unable to create dump file '%s': error=%u", m_dumpFile, ::GetLastError())); + return; + } + + PMINIDUMP_EXCEPTION_INFORMATION exceptionInfoPtr = NULL; + MINIDUMP_EXCEPTION_INFORMATION exceptionInfo = { 0 }; + if (g_dumpException != NULL) + { + exceptionInfo.ExceptionPointers = g_dumpException; + exceptionInfo.ThreadId = g_dumpExceptionThreadId; + exceptionInfo.ClientPointers = FALSE; + exceptionInfoPtr = &exceptionInfo; + } + + int dumpTypeFlags = MiniDumpNormal; + switch (dumpType) + { + case DumpType_Full: + dumpTypeFlags |= MiniDumpWithFullMemory | MiniDumpWithDataSegs | MiniDumpWithHandleData | + MiniDumpWithThreadInfo | MiniDumpWithFullMemoryInfo | MiniDumpWithPrivateReadWriteMemory; + FALLTHROUGH; + case DumpType_Minimal: + dumpTypeFlags |= MiniDumpWithIndirectlyReferencedMemory | MiniDumpScanMemory; + break; + } + + MINIDUMP_TYPE miniDumpType = static_cast(dumpTypeFlags); + BOOL success = DbgHelpLoader::miniDumpWriteDump( + ::GetCurrentProcess(), + currentProcessId, + dumpFile, + miniDumpType, + exceptionInfoPtr, + NULL, + NULL); + + if (!success) + { + DEBUG_LOG(("MiniDumper::CreateMiniDump: Unable to write minidump file '%s': error=%u", m_dumpFile, ::GetLastError())); + } + else + { + DEBUG_LOG(("MiniDumper::CreateMiniDump: Successfully wrote minidump file to '%s'", m_dumpFile)); + } + + ::CloseHandle(dumpFile); +} + +// Comparator for sorting files by last modified time (newest first) +bool MiniDumper::CompareByLastWriteTime(const FileInfo& a, const FileInfo& b) +{ + return ::CompareFileTime(&a.lastWriteTime, &b.lastWriteTime) > 0; +} + +void MiniDumper::KeepNewestFiles(const std::string& directory, const DumpType dumpType, const Int keepCount) +{ + // directory already contains trailing backslash + std::string searchPath = directory + DumpFileNamePrefix + static_cast(dumpType) + "*"; + WIN32_FIND_DATA findData; + HANDLE hFind = ::FindFirstFile(searchPath.c_str(), &findData); + + if (hFind == INVALID_HANDLE_VALUE) + { + if (::GetLastError() != ERROR_FILE_NOT_FOUND) + { + DEBUG_LOG(("MiniDumper::KeepNewestFiles: Unable to find files in directory '%s': error=%u", searchPath.c_str(), ::GetLastError())); + } + + return; + } + + std::vector files; + do + { + if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + { + continue; + } + + // Store file info + FileInfo fileInfo; + fileInfo.name = directory + findData.cFileName; + fileInfo.lastWriteTime = findData.ftLastWriteTime; + files.push_back(fileInfo); + + } while (::FindNextFile(hFind, &findData)); + + ::FindClose(hFind); + + // Sort files by last modified time in descending order + std::sort(files.begin(), files.end(), CompareByLastWriteTime); + + // Delete files beyond the newest keepCount + for (size_t i = keepCount; i < files.size(); ++i) + { + if (::DeleteFile(files[i].name.c_str())) + { + DEBUG_LOG(("MiniDumper::KeepNewestFiles: Deleted old dump file '%s'.", files[i].name.c_str())); + } + else + { + DEBUG_LOG(("MiniDumper::KeepNewestFiles: Failed to delete file '%s': error=%u", files[i].name.c_str(), ::GetLastError())); + } + } +} +#endif diff --git a/Core/Libraries/Source/WWVegas/WWLib/CMakeLists.txt b/Core/Libraries/Source/WWVegas/WWLib/CMakeLists.txt index 3eec2f42f8..997a6c0242 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/CMakeLists.txt +++ b/Core/Libraries/Source/WWVegas/WWLib/CMakeLists.txt @@ -36,6 +36,7 @@ set(WWLIB_SRC DbgHelpGuard.h DbgHelpLoader.cpp DbgHelpLoader.h + DbgHelpLoader_minidump.h Except.cpp Except.h FastAllocator.cpp diff --git a/Core/Libraries/Source/WWVegas/WWLib/DbgHelpLoader.cpp b/Core/Libraries/Source/WWVegas/WWLib/DbgHelpLoader.cpp index 96898d5097..368bcd03ca 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/DbgHelpLoader.cpp +++ b/Core/Libraries/Source/WWVegas/WWLib/DbgHelpLoader.cpp @@ -33,6 +33,9 @@ DbgHelpLoader::DbgHelpLoader() , m_symSetOptions(NULL) , m_symFunctionTableAccess(NULL) , m_stackWalk(NULL) +#ifdef RTS_ENABLE_CRASHDUMP + , m_miniDumpWriteDump(NULL) +#endif , m_dllModule(HMODULE(0)) , m_referenceCount(0) , m_failed(false) @@ -118,6 +121,9 @@ bool DbgHelpLoader::load() Inst->m_symSetOptions = reinterpret_cast(::GetProcAddress(Inst->m_dllModule, "SymSetOptions")); Inst->m_symFunctionTableAccess = reinterpret_cast(::GetProcAddress(Inst->m_dllModule, "SymFunctionTableAccess")); Inst->m_stackWalk = reinterpret_cast(::GetProcAddress(Inst->m_dllModule, "StackWalk")); +#ifdef RTS_ENABLE_CRASHDUMP + Inst->m_miniDumpWriteDump = reinterpret_cast(::GetProcAddress(Inst->m_dllModule, "MiniDumpWriteDump")); +#endif if (Inst->m_symInitialize == NULL || Inst->m_symCleanup == NULL) { @@ -171,6 +177,9 @@ void DbgHelpLoader::freeResources() Inst->m_symSetOptions = NULL; Inst->m_symFunctionTableAccess = NULL; Inst->m_stackWalk = NULL; +#ifdef RTS_ENABLE_CRASHDUMP + Inst->m_miniDumpWriteDump = NULL; +#endif Inst->m_loadedFromSystem = false; } @@ -332,3 +341,22 @@ BOOL DbgHelpLoader::stackWalk( return FALSE; } + +#ifdef RTS_ENABLE_CRASHDUMP +BOOL DbgHelpLoader::miniDumpWriteDump( + HANDLE hProcess, + DWORD ProcessId, + HANDLE hFile, + MINIDUMP_TYPE DumpType, + PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, + PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, + PMINIDUMP_CALLBACK_INFORMATION CallbackParam) +{ + CriticalSectionClass::LockClass lock(CriticalSection); + + if (Inst != NULL && Inst->m_miniDumpWriteDump) + return Inst->m_miniDumpWriteDump(hProcess, ProcessId, hFile, DumpType, ExceptionParam, UserStreamParam, CallbackParam); + + return FALSE; +} +#endif diff --git a/Core/Libraries/Source/WWVegas/WWLib/DbgHelpLoader.h b/Core/Libraries/Source/WWVegas/WWLib/DbgHelpLoader.h index c2167db075..3dda58f206 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/DbgHelpLoader.h +++ b/Core/Libraries/Source/WWVegas/WWLib/DbgHelpLoader.h @@ -23,6 +23,9 @@ #include #include // Must be included after Windows.h #include +#ifdef RTS_ENABLE_CRASHDUMP +#include +#endif #include "mutex.h" #include "SystemAllocator.h" @@ -109,6 +112,17 @@ class DbgHelpLoader PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine, PTRANSLATE_ADDRESS_ROUTINE TranslateAddress); +#ifdef RTS_ENABLE_CRASHDUMP + static BOOL WINAPI miniDumpWriteDump( + HANDLE hProcess, + DWORD ProcessId, + HANDLE hFile, + MINIDUMP_TYPE DumpType, + PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, + PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, + PMINIDUMP_CALLBACK_INFORMATION CallbackParam); +#endif + private: static void freeResources(); @@ -167,6 +181,17 @@ class DbgHelpLoader PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine, PTRANSLATE_ADDRESS_ROUTINE TranslateAddress); +#ifdef RTS_ENABLE_CRASHDUMP + typedef BOOL(WINAPI* MiniDumpWriteDump_t)( + HANDLE hProcess, + DWORD ProcessId, + HANDLE hFile, + MINIDUMP_TYPE DumpType, + PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, + PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, + PMINIDUMP_CALLBACK_INFORMATION CallbackParam); +#endif + SymInitialize_t m_symInitialize; SymCleanup_t m_symCleanup; SymLoadModule_t m_symLoadModule; @@ -177,13 +202,15 @@ class DbgHelpLoader SymSetOptions_t m_symSetOptions; SymFunctionTableAccess_t m_symFunctionTableAccess; StackWalk_t m_stackWalk; +#ifdef RTS_ENABLE_CRASHDUMP + MiniDumpWriteDump_t m_miniDumpWriteDump; +#endif typedef std::set, stl::system_allocator > Processes; Processes m_initializedProcesses; HMODULE m_dllModule; int m_referenceCount; - CriticalSectionClass m_criticalSection; bool m_failed; bool m_loadedFromSystem; }; diff --git a/Core/Libraries/Source/WWVegas/WWLib/DbgHelpLoader_minidump.h b/Core/Libraries/Source/WWVegas/WWLib/DbgHelpLoader_minidump.h new file mode 100644 index 0000000000..272fa832f5 --- /dev/null +++ b/Core/Libraries/Source/WWVegas/WWLib/DbgHelpLoader_minidump.h @@ -0,0 +1,265 @@ +#pragma once + +#ifdef RTS_ENABLE_CRASHDUMP + +// Backported defines from minidumpapiset.h for VC6. +// minidumpapiset.h is Copyright (C) Microsoft Corporation. All rights reserved. + +#if defined(_MSC_VER) && _MSC_VER < 1300 +#include + +typedef enum _MINIDUMP_CALLBACK_TYPE { + ModuleCallback, + ThreadCallback, + ThreadExCallback, + IncludeThreadCallback, + IncludeModuleCallback, + MemoryCallback, + CancelCallback, + WriteKernelMinidumpCallback, + KernelMinidumpStatusCallback, + RemoveMemoryCallback, + IncludeVmRegionCallback, + IoStartCallback, + IoWriteAllCallback, + IoFinishCallback, + ReadMemoryFailureCallback, + SecondaryFlagsCallback, + IsProcessSnapshotCallback, + VmStartCallback, + VmQueryCallback, + VmPreReadCallback, + VmPostReadCallback +} MINIDUMP_CALLBACK_TYPE; + +typedef struct _MINIDUMP_THREAD_CALLBACK { + ULONG ThreadId; + HANDLE ThreadHandle; +#if defined(_ARM64_) + ULONG Pad; +#endif + CONTEXT Context; + ULONG SizeOfContext; + ULONG64 StackBase; + ULONG64 StackEnd; +} MINIDUMP_THREAD_CALLBACK, * PMINIDUMP_THREAD_CALLBACK; + +typedef struct _MINIDUMP_THREAD_EX_CALLBACK { + ULONG ThreadId; + HANDLE ThreadHandle; +#if defined(_ARM64_) + ULONG Pad; +#endif + CONTEXT Context; + ULONG SizeOfContext; + ULONG64 StackBase; + ULONG64 StackEnd; + ULONG64 BackingStoreBase; + ULONG64 BackingStoreEnd; +} MINIDUMP_THREAD_EX_CALLBACK, * PMINIDUMP_THREAD_EX_CALLBACK; + +typedef struct _MINIDUMP_MODULE_CALLBACK { + PWCHAR FullPath; + ULONG64 BaseOfImage; + ULONG SizeOfImage; + ULONG CheckSum; + ULONG TimeDateStamp; + VS_FIXEDFILEINFO VersionInfo; + PVOID CvRecord; + ULONG SizeOfCvRecord; + PVOID MiscRecord; + ULONG SizeOfMiscRecord; +} MINIDUMP_MODULE_CALLBACK, * PMINIDUMP_MODULE_CALLBACK; + +typedef struct _MINIDUMP_INCLUDE_THREAD_CALLBACK { + ULONG ThreadId; +} MINIDUMP_INCLUDE_THREAD_CALLBACK, * PMINIDUMP_INCLUDE_THREAD_CALLBACK; + +typedef enum _THREAD_WRITE_FLAGS { + ThreadWriteThread = 0x0001, + ThreadWriteStack = 0x0002, + ThreadWriteContext = 0x0004, + ThreadWriteBackingStore = 0x0008, + ThreadWriteInstructionWindow = 0x0010, + ThreadWriteThreadData = 0x0020, + ThreadWriteThreadInfo = 0x0040, +} THREAD_WRITE_FLAGS; + +typedef struct _MINIDUMP_INCLUDE_MODULE_CALLBACK { + ULONG64 BaseOfImage; +} MINIDUMP_INCLUDE_MODULE_CALLBACK, * PMINIDUMP_INCLUDE_MODULE_CALLBACK; + +typedef struct _MINIDUMP_IO_CALLBACK { + HANDLE Handle; + ULONG64 Offset; + PVOID Buffer; + ULONG BufferBytes; +} MINIDUMP_IO_CALLBACK, * PMINIDUMP_IO_CALLBACK; + +typedef struct _MINIDUMP_READ_MEMORY_FAILURE_CALLBACK +{ + ULONG64 Offset; + ULONG Bytes; + HRESULT FailureStatus; +} MINIDUMP_READ_MEMORY_FAILURE_CALLBACK, +* PMINIDUMP_READ_MEMORY_FAILURE_CALLBACK; + +typedef struct _MINIDUMP_VM_QUERY_CALLBACK +{ + ULONG64 Offset; +} MINIDUMP_VM_QUERY_CALLBACK, * PMINIDUMP_VM_QUERY_CALLBACK; + +typedef struct _MINIDUMP_VM_PRE_READ_CALLBACK +{ + ULONG64 Offset; + PVOID Buffer; + ULONG Size; +} MINIDUMP_VM_PRE_READ_CALLBACK, * PMINIDUMP_VM_PRE_READ_CALLBACK; + +typedef struct _MINIDUMP_VM_POST_READ_CALLBACK +{ + ULONG64 Offset; + PVOID Buffer; + ULONG Size; + ULONG Completed; + HRESULT Status; +} MINIDUMP_VM_POST_READ_CALLBACK, * PMINIDUMP_VM_POST_READ_CALLBACK; + +typedef struct _MINIDUMP_MEMORY_INFO { + ULONG64 BaseAddress; + ULONG64 AllocationBase; + ULONG32 AllocationProtect; + ULONG32 __alignment1; + ULONG64 RegionSize; + ULONG32 State; + ULONG32 Protect; + ULONG32 Type; + ULONG32 __alignment2; +} MINIDUMP_MEMORY_INFO, * PMINIDUMP_MEMORY_INFO; + +typedef struct _MINIDUMP_CALLBACK_INPUT { + ULONG ProcessId; + HANDLE ProcessHandle; + ULONG CallbackType; + union { + HRESULT Status; + MINIDUMP_THREAD_CALLBACK Thread; + MINIDUMP_THREAD_EX_CALLBACK ThreadEx; + MINIDUMP_MODULE_CALLBACK Module; + MINIDUMP_INCLUDE_THREAD_CALLBACK IncludeThread; + MINIDUMP_INCLUDE_MODULE_CALLBACK IncludeModule; + MINIDUMP_IO_CALLBACK Io; + MINIDUMP_READ_MEMORY_FAILURE_CALLBACK ReadMemoryFailure; + ULONG SecondaryFlags; + MINIDUMP_VM_QUERY_CALLBACK VmQuery; + MINIDUMP_VM_PRE_READ_CALLBACK VmPreRead; + MINIDUMP_VM_POST_READ_CALLBACK VmPostRead; + }; +} MINIDUMP_CALLBACK_INPUT, * PMINIDUMP_CALLBACK_INPUT; + +typedef struct _MINIDUMP_CALLBACK_OUTPUT { + union { + ULONG ModuleWriteFlags; + ULONG ThreadWriteFlags; + ULONG SecondaryFlags; + struct { + ULONG64 MemoryBase; + ULONG MemorySize; + }; + struct { + BOOL CheckCancel; + BOOL Cancel; + }; + HANDLE Handle; + struct { + MINIDUMP_MEMORY_INFO VmRegion; + BOOL Continue; + }; + struct { + HRESULT VmQueryStatus; + MINIDUMP_MEMORY_INFO VmQueryResult; + }; + struct { + HRESULT VmReadStatus; + ULONG VmReadBytesCompleted; + }; + HRESULT Status; + }; +} MINIDUMP_CALLBACK_OUTPUT, * PMINIDUMP_CALLBACK_OUTPUT; + +typedef struct _MINIDUMP_EXCEPTION_INFORMATION { + DWORD ThreadId; + PEXCEPTION_POINTERS ExceptionPointers; + BOOL ClientPointers; +} MINIDUMP_EXCEPTION_INFORMATION, * PMINIDUMP_EXCEPTION_INFORMATION; + +typedef struct _MINIDUMP_USER_STREAM { + ULONG32 Type; + ULONG BufferSize; + PVOID Buffer; + +} MINIDUMP_USER_STREAM, * PMINIDUMP_USER_STREAM; + +typedef struct _MINIDUMP_USER_STREAM_INFORMATION { + ULONG UserStreamCount; + PMINIDUMP_USER_STREAM UserStreamArray; +} MINIDUMP_USER_STREAM_INFORMATION, * PMINIDUMP_USER_STREAM_INFORMATION; + +typedef +BOOL +(WINAPI* MINIDUMP_CALLBACK_ROUTINE) ( + PVOID CallbackParam, + PMINIDUMP_CALLBACK_INPUT CallbackInput, + PMINIDUMP_CALLBACK_OUTPUT CallbackOutput + ); + +typedef struct _MINIDUMP_CALLBACK_INFORMATION { + MINIDUMP_CALLBACK_ROUTINE CallbackRoutine; + PVOID CallbackParam; +} MINIDUMP_CALLBACK_INFORMATION, * PMINIDUMP_CALLBACK_INFORMATION; + +typedef enum _MINIDUMP_TYPE { + MiniDumpNormal = 0x00000000, + MiniDumpWithDataSegs = 0x00000001, + MiniDumpWithFullMemory = 0x00000002, + MiniDumpWithHandleData = 0x00000004, + MiniDumpFilterMemory = 0x00000008, + MiniDumpScanMemory = 0x00000010, + MiniDumpWithUnloadedModules = 0x00000020, + MiniDumpWithIndirectlyReferencedMemory = 0x00000040, + MiniDumpFilterModulePaths = 0x00000080, + MiniDumpWithProcessThreadData = 0x00000100, + MiniDumpWithPrivateReadWriteMemory = 0x00000200, + MiniDumpWithoutOptionalData = 0x00000400, + MiniDumpWithFullMemoryInfo = 0x00000800, + MiniDumpWithThreadInfo = 0x00001000, + MiniDumpWithCodeSegs = 0x00002000, + MiniDumpWithoutAuxiliaryState = 0x00004000, + MiniDumpWithFullAuxiliaryState = 0x00008000, + MiniDumpWithPrivateWriteCopyMemory = 0x00010000, + MiniDumpIgnoreInaccessibleMemory = 0x00020000, + MiniDumpWithTokenInformation = 0x00040000, + MiniDumpWithModuleHeaders = 0x00080000, + MiniDumpFilterTriage = 0x00100000, + MiniDumpWithAvxXStateContext = 0x00200000, + MiniDumpWithIptTrace = 0x00400000, + MiniDumpScanInaccessiblePartialPages = 0x00800000, + MiniDumpFilterWriteCombinedMemory = 0x01000000, + MiniDumpValidTypeFlags = 0x01ffffff, + MiniDumpNoIgnoreInaccessibleMemory = 0x02000000, + MiniDumpValidTypeFlagsEx = 0x03ffffff, +} MINIDUMP_TYPE; + +typedef enum _MODULE_WRITE_FLAGS { + ModuleWriteModule = 0x0001, + ModuleWriteDataSeg = 0x0002, + ModuleWriteMiscRecord = 0x0004, + ModuleWriteCvRecord = 0x0008, + ModuleReferencedByMemory = 0x0010, + ModuleWriteTlsData = 0x0020, + ModuleWriteCodeSegs = 0x0040, +} MODULE_WRITE_FLAGS; + +#include +#endif +#endif diff --git a/Generals/Code/Main/WinMain.cpp b/Generals/Code/Main/WinMain.cpp index 9af234e3a5..1bdfe50293 100644 --- a/Generals/Code/Main/WinMain.cpp +++ b/Generals/Code/Main/WinMain.cpp @@ -64,6 +64,9 @@ #include "BuildVersion.h" #include "GeneratedVersion.h" #include "resource.h" +#ifdef RTS_ENABLE_CRASHDUMP +#include "Common/MiniDumper.h" +#endif // GLOBALS //////////////////////////////////////////////////////////////////// @@ -750,6 +753,16 @@ static CriticalSection critSec1, critSec2, critSec3, critSec4, critSec5; static LONG WINAPI UnHandledExceptionFilter( struct _EXCEPTION_POINTERS* e_info ) { DumpExceptionInfo( e_info->ExceptionRecord->ExceptionCode, e_info ); +#ifdef RTS_ENABLE_CRASHDUMP + if (TheMiniDumper && TheMiniDumper->IsInitialized()) + { + // Create both minimal and full memory dumps + TheMiniDumper->TriggerMiniDumpForException(e_info, DumpType_Minimal); + TheMiniDumper->TriggerMiniDumpForException(e_info, DumpType_Full); + } + + MiniDumper::shutdownMiniDumper(); +#endif return EXCEPTION_EXECUTE_HANDLER; } @@ -810,6 +823,10 @@ Int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, CommandLine::parseCommandLineForStartup(); +#ifdef RTS_ENABLE_CRASHDUMP + // Initialize minidump facilities - requires TheGlobalData so performed after parseCommandLineForStartup + MiniDumper::initMiniDumper(TheGlobalData->getPath_UserData()); +#endif // register windows class and create application window if(!TheGlobalData->m_headless && initializeAppWindows(hInstance, nCmdShow, TheGlobalData->m_windowed) == false) return exitcode; @@ -877,6 +894,9 @@ Int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, } +#ifdef RTS_ENABLE_CRASHDUMP + MiniDumper::shutdownMiniDumper(); +#endif TheAsciiStringCriticalSection = NULL; TheUnicodeStringCriticalSection = NULL; TheDmaCriticalSection = NULL; diff --git a/GeneralsMD/Code/Main/WinMain.cpp b/GeneralsMD/Code/Main/WinMain.cpp index fb91c4fbea..8d0dc1aa6c 100644 --- a/GeneralsMD/Code/Main/WinMain.cpp +++ b/GeneralsMD/Code/Main/WinMain.cpp @@ -67,6 +67,9 @@ #include "resource.h" #include +#ifdef RTS_ENABLE_CRASHDUMP +#include "Common/MiniDumper.h" +#endif // GLOBALS //////////////////////////////////////////////////////////////////// @@ -772,6 +775,16 @@ static CriticalSection critSec1, critSec2, critSec3, critSec4, critSec5; static LONG WINAPI UnHandledExceptionFilter( struct _EXCEPTION_POINTERS* e_info ) { DumpExceptionInfo( e_info->ExceptionRecord->ExceptionCode, e_info ); +#ifdef RTS_ENABLE_CRASHDUMP + if (TheMiniDumper && TheMiniDumper->IsInitialized()) + { + // Create both minimal and full memory dumps + TheMiniDumper->TriggerMiniDumpForException(e_info, DumpType_Minimal); + TheMiniDumper->TriggerMiniDumpForException(e_info, DumpType_Full); + } + + MiniDumper::shutdownMiniDumper(); +#endif return EXCEPTION_EXECUTE_HANDLER; } @@ -856,6 +869,10 @@ Int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, #endif CommandLine::parseCommandLineForStartup(); +#ifdef RTS_ENABLE_CRASHDUMP + // Initialize minidump facilities - requires TheGlobalData so performed after parseCommandLineForStartup + MiniDumper::initMiniDumper(TheGlobalData->getPath_UserData()); +#endif // register windows class and create application window if(!TheGlobalData->m_headless && initializeAppWindows(hInstance, nCmdShow, TheGlobalData->m_windowed) == false) @@ -925,6 +942,9 @@ Int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, } +#ifdef RTS_ENABLE_CRASHDUMP + MiniDumper::shutdownMiniDumper(); +#endif TheUnicodeStringCriticalSection = NULL; TheDmaCriticalSection = NULL; TheMemoryPoolCriticalSection = NULL; diff --git a/cmake/config-memory.cmake b/cmake/config-memory.cmake index 72a28d1c94..5daa6f110a 100644 --- a/cmake/config-memory.cmake +++ b/cmake/config-memory.cmake @@ -20,6 +20,9 @@ option(RTS_MEMORYPOOL_DEBUG_INTENSE_VERIFY "Enables intensive verifications afte option(RTS_MEMORYPOOL_DEBUG_CHECK_BLOCK_OWNERSHIP "Enables debug to verify that a block actually belongs to the pool it is called with. This is great for debugging, but can be realllly slow, so is OFF by default." OFF) option(RTS_MEMORYPOOL_DEBUG_INTENSE_DMA_BOOKKEEPING "Prints statistics for memory usage of Memory Pools." OFF) +# Memory dump options +option(RTS_CRASHDUMP_ENABLE "Enables writing crash dumps on unhandled exceptions or release crash failures." ON) + # Game Memory features add_feature_info(GameMemoryEnable RTS_GAMEMEMORY_ENABLE "Build with the original game memory implementation") @@ -37,6 +40,8 @@ add_feature_info(MemoryPoolDebugIntenseVerify RTS_MEMORYPOOL_DEBUG_INTENSE_VERIF add_feature_info(MemoryPoolDebugCheckBlockOwnership RTS_MEMORYPOOL_DEBUG_CHECK_BLOCK_OWNERSHIP "Build with Memory Pool block ownership checks") add_feature_info(MemoryPoolDebugIntenseDmaBookkeeping RTS_MEMORYPOOL_DEBUG_INTENSE_DMA_BOOKKEEPING "Build with Memory Pool intense DMA bookkeeping") +# Memory dump features +add_feature_info(CrashDumpEnable RTS_CRASHDUMP_ENABLE "Build with Crash Dumps") # Game Memory features if(NOT RTS_GAMEMEMORY_ENABLE) @@ -87,3 +92,10 @@ else() target_compile_definitions(core_config INTERFACE INTENSE_DMA_BOOKKEEPING=1) endif() endif() + +if(RTS_CRASHDUMP_ENABLE) + target_compile_definitions(core_config INTERFACE RTS_ENABLE_CRASHDUMP=1) + if (IS_VS6_BUILD AND NOT RTS_BUILD_OPTION_VC6_FULL_DEBUG) + message(STATUS "Crash Dumps will be significantly less useful in VC6 builds without full debug info enabled") + endif() +endif() From 158b046ad7f2c85891049c4f9c6ff68f5a2155ef Mon Sep 17 00:00:00 2001 From: Bobby Battista Date: Wed, 10 Dec 2025 16:24:28 -0500 Subject: [PATCH 21/70] ci(vcpkg): Include preset in binary cache key to avoid ABI mismatches and slow CI builds (#1973) --- .github/workflows/build-toolchain.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build-toolchain.yml b/.github/workflows/build-toolchain.yml index 7caf8ab819..5999ee132b 100644 --- a/.github/workflows/build-toolchain.yml +++ b/.github/workflows/build-toolchain.yml @@ -43,8 +43,9 @@ jobs: uses: actions/cache@v4 with: path: ${{ github.workspace }}\vcpkg-bincache - key: vcpkg-bincache-${{ runner.os }}-${{ hashFiles('vcpkg.json','vcpkg-lock.json') }} + key: vcpkg-bincache-${{ runner.os }}-${{ hashFiles('vcpkg.json','vcpkg-lock.json') }}-${{ inputs.preset }} restore-keys: | + vcpkg-bincache-${{ runner.os }}-${{ hashFiles('vcpkg.json','vcpkg-lock.json') }}- vcpkg-bincache-${{ runner.os }}- - name: Cache VC6 Installation From 42f846b1f98c41c6369c76cf2b483cdbfea88cb0 Mon Sep 17 00:00:00 2001 From: Mauller <26652186+Mauller@users.noreply.github.com> Date: Wed, 10 Dec 2025 21:25:36 +0000 Subject: [PATCH 22/70] bugfix(pathfinder): Prevent infinite loop within PathfindCell::putOnSortedOpenList() (#1965) --- .../Source/GameLogic/AI/AIPathfind.cpp | 38 +++++++++++------- .../Source/GameLogic/AI/AIPathfind.cpp | 39 ++++++++++++------- 2 files changed, 48 insertions(+), 29 deletions(-) diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp index 2b693ac950..f0f4ca98dc 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp @@ -92,6 +92,13 @@ inline Int IABS(Int x) { if (x>=0) return x; return -x;}; //----------------------------------------------------------------------------------- static Int frameToShowObstacles; +constexpr const UnsignedInt MAX_CELL_COUNT = 500; +constexpr const UnsignedInt MAX_ADJUSTMENT_CELL_COUNT = 400; +constexpr const UnsignedInt MAX_SAFE_PATH_CELL_COUNT = 2000; + +constexpr const UnsignedInt PATHFIND_CELLS_PER_FRAME = 5000; // Number of cells we will search pathfinding per frame. +constexpr const UnsignedInt CELL_INFOS_TO_ALLOCATE = 30000; + //----------------------------------------------------------------------------------- PathNode::PathNode() : m_nextOpti(0), @@ -1077,8 +1084,6 @@ Real Path::computeFlightDistToGoal( const Coord3D *pos, Coord3D& goalPos ) } //----------------------------------------------------------------------------------- -enum { PATHFIND_CELLS_PER_FRAME=5000}; // Number of cells we will search pathfinding per frame. -enum {CELL_INFOS_TO_ALLOCATE = 30000}; PathfindCellInfo *PathfindCellInfo::s_infoArray = NULL; PathfindCellInfo *PathfindCellInfo::s_firstFree = NULL; @@ -1547,8 +1552,18 @@ PathfindCell *PathfindCell::putOnSortedOpenList( PathfindCell *list ) { // insertion sort PathfindCell *c, *lastCell = NULL; - for( c = list; c; c = c->getNextOpen() ) +#if RETAIL_COMPATIBLE_PATHFINDING + // TheSuperHackers @bugfix In the retail compatible pathfinding, on rare ocassions, we get stuck in an infinite loop + // External code should pickup on the bad behaviour and cleanup properly, but we need to explicitly break out here + // The fixed pathfinding does not have this issue due to the proper cleanup of pathfindCells and their pathfindCellInfos + UnsignedInt cellCount = 0; + for (c = list; c && cellCount < PATHFIND_CELLS_PER_FRAME; c = c->getNextOpen()) + { + cellCount++; +#else + for (c = list; c; c = c->getNextOpen()) { +#endif if (c->m_info->m_totalCost > m_info->m_totalCost) break; @@ -4715,8 +4730,7 @@ Bool Pathfinder::adjustToLandingDestination(Object *obj, Coord3D *dest) } worldToCell( &adjustDest, &cell ); - enum {MAX_CELLS_TO_TRY=400}; - Int limit = MAX_CELLS_TO_TRY; + Int limit = MAX_ADJUSTMENT_CELL_COUNT; Int i, j; i = cell.x; j = cell.y; @@ -4793,8 +4807,7 @@ Bool Pathfinder::adjustDestination(Object *obj, const LocomotorSet& locomotorSet layer = TheTerrainLogic->getLayerForDestination(groupDest); } - enum {MAX_CELLS_TO_TRY=400}; - Int limit = MAX_CELLS_TO_TRY; + Int limit = MAX_ADJUSTMENT_CELL_COUNT; Int i, j; i = cell.x; j = cell.y; @@ -4877,8 +4890,8 @@ Bool Pathfinder::adjustTargetDestination(const Object *obj, const Object *target if (worldToCell( &adjustDest, &cell )) { return false; // outside of bounds. } - enum {MAX_CELLS_TO_TRY=400}; - Int limit = MAX_CELLS_TO_TRY; + + Int limit = MAX_ADJUSTMENT_CELL_COUNT; Int i, j; i = cell.x; j = cell.y; @@ -5001,8 +5014,7 @@ Bool Pathfinder::adjustToPossibleDestination(Object *obj, const LocomotorSet& lo } } - enum {MAX_CELLS_TO_TRY=400}; - Int limit = MAX_CELLS_TO_TRY; + Int limit = MAX_ADJUSTMENT_CELL_COUNT; Int i, j; i = goalCellNdx.x; j = goalCellNdx.y; @@ -7511,7 +7523,6 @@ Bool Pathfinder::pathDestination( Object *obj, const LocomotorSet& locomotorSet if (!obj) return false; Int cellCount = 0; -#define MAX_CELL_COUNT 500 Coord3D adjustTo = *groupDest; Coord3D *to = &adjustTo; @@ -7806,7 +7817,6 @@ Int Pathfinder::checkPathCost(Object *obj, const LocomotorSet& locomotorSet, con if (!obj) return MAX_COST; Int cellCount = 0; -#define MAX_CELL_COUNT 500 Coord3D adjustTo = *rawTo; Coord3D *to = &adjustTo; @@ -10328,7 +10338,7 @@ Path *Pathfinder::findSafePath( const Object *obj, const LocomotorSet& locomotor // Int startTimeMS = ::GetTickCount(); #endif - const Int MAX_CELLS = 2000; // this is a rather expensive operation, so limit the search. + const Int MAX_CELLS = MAX_SAFE_PATH_CELL_COUNT; // this is a rather expensive operation, so limit the search. Bool centerInCell; Int radius; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp index e1b50033c2..bc2eb2aed1 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp @@ -106,7 +106,13 @@ inline Int IABS(Int x) { if (x>=0) return x; return -x;}; static Int frameToShowObstacles; -static UnsignedInt ZONE_UPDATE_FREQUENCY = 300; +constexpr const UnsignedInt ZONE_UPDATE_FREQUENCY = 300; +constexpr const UnsignedInt MAX_CELL_COUNT = 500; +constexpr const UnsignedInt MAX_ADJUSTMENT_CELL_COUNT = 400; +constexpr const UnsignedInt MAX_SAFE_PATH_CELL_COUNT = 2000; + +constexpr const UnsignedInt PATHFIND_CELLS_PER_FRAME = 5000; // Number of cells we will search pathfinding per frame. +constexpr const UnsignedInt CELL_INFOS_TO_ALLOCATE = 30000; //----------------------------------------------------------------------------------- PathNode::PathNode() : @@ -1093,8 +1099,6 @@ Real Path::computeFlightDistToGoal( const Coord3D *pos, Coord3D& goalPos ) } //----------------------------------------------------------------------------------- -enum { PATHFIND_CELLS_PER_FRAME=5000}; // Number of cells we will search pathfinding per frame. -enum {CELL_INFOS_TO_ALLOCATE = 30000}; PathfindCellInfo *PathfindCellInfo::s_infoArray = NULL; PathfindCellInfo *PathfindCellInfo::s_firstFree = NULL; @@ -1565,8 +1569,18 @@ PathfindCell *PathfindCell::putOnSortedOpenList( PathfindCell *list ) { // insertion sort PathfindCell *c, *lastCell = NULL; - for( c = list; c; c = c->getNextOpen() ) +#if RETAIL_COMPATIBLE_PATHFINDING + // TheSuperHackers @bugfix In the retail compatible pathfinding, on rare ocassions, we get stuck in an infinite loop + // External code should pickup on the bad behaviour and cleanup properly, but we need to explicitly break out here + // The fixed pathfinding does not have this issue due to the proper cleanup of pathfindCells and their pathfindCellInfos + UnsignedInt cellCount = 0; + for (c = list; c && cellCount < PATHFIND_CELLS_PER_FRAME; c = c->getNextOpen()) { + cellCount++; +#else + for (c = list; c; c = c->getNextOpen()) + { +#endif if (c->m_info->m_totalCost > m_info->m_totalCost) break; @@ -4998,8 +5012,7 @@ Bool Pathfinder::adjustToLandingDestination(Object *obj, Coord3D *dest) } worldToCell( &adjustDest, &cell ); - enum {MAX_CELLS_TO_TRY=400}; - Int limit = MAX_CELLS_TO_TRY; + Int limit = MAX_ADJUSTMENT_CELL_COUNT; Int i, j; i = cell.x; j = cell.y; @@ -5076,8 +5089,7 @@ Bool Pathfinder::adjustDestination(Object *obj, const LocomotorSet& locomotorSet layer = TheTerrainLogic->getLayerForDestination(groupDest); } - enum {MAX_CELLS_TO_TRY=400}; - Int limit = MAX_CELLS_TO_TRY; + Int limit = MAX_ADJUSTMENT_CELL_COUNT; Int i, j; i = cell.x; j = cell.y; @@ -5160,8 +5172,8 @@ Bool Pathfinder::adjustTargetDestination(const Object *obj, const Object *target if (worldToCell( &adjustDest, &cell )) { return false; // outside of bounds. } - enum {MAX_CELLS_TO_TRY=400}; - Int limit = MAX_CELLS_TO_TRY; + + Int limit = MAX_ADJUSTMENT_CELL_COUNT; Int i, j; i = cell.x; j = cell.y; @@ -5284,8 +5296,7 @@ Bool Pathfinder::adjustToPossibleDestination(Object *obj, const LocomotorSet& lo } } - enum {MAX_CELLS_TO_TRY=400}; - Int limit = MAX_CELLS_TO_TRY; + Int limit = MAX_ADJUSTMENT_CELL_COUNT; Int i, j; i = goalCellNdx.x; j = goalCellNdx.y; @@ -7910,7 +7921,6 @@ Bool Pathfinder::pathDestination( Object *obj, const LocomotorSet& locomotorSet if (!obj) return false; Int cellCount = 0; -#define MAX_CELL_COUNT 500 Coord3D adjustTo = *groupDest; Coord3D *to = &adjustTo; @@ -8205,7 +8215,6 @@ Int Pathfinder::checkPathCost(Object *obj, const LocomotorSet& locomotorSet, con if (!obj) return MAX_COST; Int cellCount = 0; -#define MAX_CELL_COUNT 500 Coord3D adjustTo = *rawTo; Coord3D *to = &adjustTo; @@ -10805,7 +10814,7 @@ Path *Pathfinder::findSafePath( const Object *obj, const LocomotorSet& locomotor // Int startTimeMS = ::GetTickCount(); #endif - const Int MAX_CELLS = 2000; // this is a rather expensive operation, so limit the search. + const Int MAX_CELLS = MAX_SAFE_PATH_CELL_COUNT; // this is a rather expensive operation, so limit the search. Bool centerInCell; Int radius; From 957325040800f7181cba847a6f1ce8c738473501 Mon Sep 17 00:00:00 2001 From: Bobby Battista Date: Wed, 10 Dec 2025 16:59:03 -0500 Subject: [PATCH 23/70] build: Add clang-tidy checks and script (#1807) --- .clang-tidy | 167 +++++++++++++++ scripts/run-clang-tidy.py | 436 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 603 insertions(+) create mode 100644 .clang-tidy create mode 100755 scripts/run-clang-tidy.py diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000000..69fe82afaf --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,167 @@ +# TheSuperHackers @build JohnsterID 15/09/2025 Add clang-tidy configuration for code quality analysis +--- +# Clang-tidy configuration for GeneralsGameCode project +# This configuration is tailored for a legacy C++98/C++20 hybrid codebase +# with Windows-specific code and COM interfaces + +# Enable specific checks that are appropriate for this codebase +Checks: > + -*, + bugprone-*, + -bugprone-easily-swappable-parameters, + -bugprone-implicit-widening-of-multiplication-result, + -bugprone-narrowing-conversions, + -bugprone-signed-char-misuse, + cert-*, + -cert-dcl21-cpp, + -cert-dcl50-cpp, + -cert-dcl58-cpp, + -cert-env33-c, + -cert-err58-cpp, + clang-analyzer-*, + -clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling, + cppcoreguidelines-*, + -cppcoreguidelines-avoid-c-arrays, + -cppcoreguidelines-avoid-magic-numbers, + -cppcoreguidelines-avoid-non-const-global-variables, + -cppcoreguidelines-init-variables, + -cppcoreguidelines-macro-usage, + -cppcoreguidelines-no-malloc, + -cppcoreguidelines-owning-memory, + -cppcoreguidelines-pro-bounds-array-to-pointer-decay, + -cppcoreguidelines-pro-bounds-constant-array-index, + -cppcoreguidelines-pro-bounds-pointer-arithmetic, + -cppcoreguidelines-pro-type-cstyle-cast, + -cppcoreguidelines-pro-type-reinterpret-cast, + -cppcoreguidelines-pro-type-union-access, + -cppcoreguidelines-pro-type-vararg, + -cppcoreguidelines-special-member-functions, + google-*, + -google-build-using-namespace, + -google-explicit-constructor, + -google-readability-casting, + -google-readability-todo, + -google-runtime-int, + -google-runtime-references, + hicpp-*, + -hicpp-avoid-c-arrays, + -hicpp-explicit-conversions, + -hicpp-no-array-decay, + -hicpp-signed-bitwise, + -hicpp-special-member-functions, + -hicpp-uppercase-literal-suffix, + -hicpp-use-auto, + -hicpp-vararg, + misc-*, + -misc-const-correctness, + -misc-include-cleaner, + -misc-non-private-member-variables-in-classes, + -misc-use-anonymous-namespace, + modernize-*, + -modernize-avoid-c-arrays, + -modernize-concat-nested-namespaces, + -modernize-loop-convert, + -modernize-pass-by-value, + -modernize-raw-string-literal, + -modernize-return-braced-init-list, + -modernize-use-auto, + -modernize-use-default-member-init, + -modernize-use-nodiscard, + -modernize-use-trailing-return-type, + performance-*, + -performance-avoid-endl, + portability-*, + readability-*, + -readability-avoid-const-params-in-decls, + -readability-braces-around-statements, + -readability-convert-member-functions-to-static, + -readability-function-cognitive-complexity, + -readability-identifier-length, + -readability-implicit-bool-conversion, + -readability-isolate-declaration, + -readability-magic-numbers, + -readability-named-parameter, + -readability-redundant-access-specifiers, + -readability-uppercase-literal-suffix + +# Treat warnings as errors for CI/CD +WarningsAsErrors: false + +# Header filter to include project headers +HeaderFilterRegex: '(Core|Generals|GeneralsMD|Dependencies)/.*\.(h|hpp)$' + +# Check options for specific rules +CheckOptions: + # Naming conventions - adapted for the existing codebase style + - key: readability-identifier-naming.ClassCase + value: CamelCase + - key: readability-identifier-naming.StructCase + value: CamelCase + - key: readability-identifier-naming.FunctionCase + value: CamelCase + - key: readability-identifier-naming.MethodCase + value: CamelCase + - key: readability-identifier-naming.VariableCase + value: lower_case + - key: readability-identifier-naming.ParameterCase + value: lower_case + - key: readability-identifier-naming.MemberCase + value: lower_case + - key: readability-identifier-naming.MemberPrefix + value: m_ + - key: readability-identifier-naming.ConstantCase + value: UPPER_CASE + - key: readability-identifier-naming.EnumConstantCase + value: UPPER_CASE + - key: readability-identifier-naming.MacroDefinitionCase + value: UPPER_CASE + + # Performance settings + - key: performance-for-range-copy.WarnOnAllAutoCopies + value: true + - key: performance-unnecessary-value-param.AllowedTypes + value: 'AsciiString;UnicodeString;Utf8String;Utf16String' + + # Modernize settings - be conservative for legacy code + - key: modernize-use-nullptr.NullMacros + value: 'NULL' + - key: modernize-replace-auto-ptr.IncludeStyle + value: llvm + + # Readability settings + - key: readability-function-size.LineThreshold + value: 150 + - key: readability-function-size.StatementThreshold + value: 100 + - key: readability-function-size.BranchThreshold + value: 25 + - key: readability-function-size.ParameterThreshold + value: 8 + - key: readability-function-size.NestingThreshold + value: 6 + + # Bugprone settings + - key: bugprone-argument-comment.StrictMode + value: false + - key: bugprone-suspicious-string-compare.WarnOnImplicitComparison + value: true + - key: bugprone-suspicious-string-compare.WarnOnLogicalNotComparison + value: true + + # Google style settings + - key: google-readability-braces-around-statements.ShortStatementLines + value: 2 + - key: google-readability-function-size.StatementThreshold + value: 100 + + # CERT settings + - key: cert-dcl16-c.NewSuffixes + value: 'L;LL;LU;LLU' + - key: cert-oop54-cpp.WarnOnlyIfThisHasSuspiciousField + value: false + +# Use .clang-format for formatting suggestions +FormatStyle: file + +# Exclude certain directories and files +# Note: This is handled by HeaderFilterRegex above, but can be extended diff --git a/scripts/run-clang-tidy.py b/scripts/run-clang-tidy.py new file mode 100755 index 0000000000..49f06b4563 --- /dev/null +++ b/scripts/run-clang-tidy.py @@ -0,0 +1,436 @@ +#!/usr/bin/env python3 +# TheSuperHackers @build JohnsterID 15/09/2025 Add clang-tidy runner script for code quality analysis +# TheSuperHackers @build bobtista 04/12/2025 Simplify script for PCH-free analysis builds + +""" +Clang-tidy runner script for GeneralsGameCode project. + +This is a convenience wrapper that: +- Auto-detects the clang-tidy analysis build (build/clang-tidy) +- Filters source files by include/exclude patterns +- Processes files in batches to handle Windows command-line limits +- Provides quiet progress reporting (only shows warnings/errors by default) + +For the analysis build to work correctly, it must be built WITHOUT precompiled headers. +Run this first: + cmake -B build/clang-tidy -DCMAKE_DISABLE_PRECOMPILE_HEADERS=ON -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -G Ninja +""" + +import argparse +import json +import multiprocessing +import subprocess +import sys +from collections import defaultdict +from pathlib import Path +from typing import List, Optional, Tuple, Dict + + +def find_clang_tidy() -> str: + """Find clang-tidy executable in PATH.""" + try: + result = subprocess.run( + ['clang-tidy', '--version'], + capture_output=True, + text=True, + timeout=5 + ) + if result.returncode == 0: + return 'clang-tidy' + except (FileNotFoundError, subprocess.TimeoutExpired): + pass + + raise RuntimeError( + "clang-tidy not found in PATH. Please install clang-tidy:\n" + " Windows: Install LLVM from https://llvm.org/builds/" + ) + + +def find_project_root() -> Path: + """Find the project root directory.""" + current = Path(__file__).resolve().parent + while current != current.parent: + if (current / 'CMakeLists.txt').exists(): + return current + current = current.parent + raise RuntimeError("Could not find project root (no CMakeLists.txt found)") + + +def find_compile_commands(build_dir: Optional[Path] = None) -> Path: + """Find compile_commands.json from the clang-tidy analysis build.""" + project_root = find_project_root() + + if build_dir: + if not build_dir.is_absolute(): + build_dir = project_root / build_dir + compile_commands = build_dir / "compile_commands.json" + if compile_commands.exists(): + return compile_commands + raise FileNotFoundError( + f"compile_commands.json not found in {build_dir}" + ) + + clang_tidy_build = project_root / "build" / "clang-tidy" + compile_commands = clang_tidy_build / "compile_commands.json" + + if not compile_commands.exists(): + raise RuntimeError( + "compile_commands.json not found!\n\n" + "Create the analysis build first:\n" + " cmake -B build/clang-tidy -DCMAKE_DISABLE_PRECOMPILE_HEADERS=ON -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -G Ninja\n\n" + "Or specify a different build with --build-dir" + ) + + return compile_commands + + +def load_compile_commands(compile_commands_path: Path) -> List[dict]: + """Load and parse compile_commands.json.""" + try: + with open(compile_commands_path, 'r') as f: + return json.load(f) + except (json.JSONDecodeError, IOError) as e: + raise RuntimeError(f"Failed to load compile_commands.json: {e}") + + +def filter_source_files(compile_commands: List[dict], + include_patterns: List[str], + exclude_patterns: List[str]) -> List[str]: + """Filter source files based on include/exclude patterns.""" + project_root = find_project_root() + source_files = set() + + for entry in compile_commands: + file_path = Path(entry['file']) + + try: + rel_path = file_path.relative_to(project_root) + except ValueError: + continue + + rel_path_str = str(rel_path) + + if include_patterns: + if not any(pattern in rel_path_str for pattern in include_patterns): + continue + + if any(pattern in rel_path_str for pattern in exclude_patterns): + continue + + if file_path.suffix in {'.cpp', '.cxx', '.cc', '.c'}: + source_files.add(str(file_path)) + + return sorted(source_files) + + +def _run_batch(args: Tuple) -> Tuple[int, Dict[str, List[str]]]: + """Helper function to run clang-tidy on a batch of files (for multiprocessing).""" + batch_num, batch, compile_commands_dir, fix, extra_args, project_root, clang_tidy_exe, verbose = args + + cmd = [ + clang_tidy_exe, + f'-p={compile_commands_dir}', + ] + + if fix: + cmd.append('--fix') + + if extra_args: + cmd.extend(extra_args) + + cmd.extend(batch) + + issues_by_file = defaultdict(list) + + try: + result = subprocess.run( + cmd, + cwd=project_root, + capture_output=True, + text=True + ) + + if result.stdout or result.stderr: + output = result.stdout + result.stderr + + for line in output.splitlines(): + line = line.strip() + if not line: + continue + + line_lower = line.lower() + is_warning_or_error = ('warning' in line_lower or 'error' in line_lower) + + if ':' in line and (is_warning_or_error or verbose): + parts = line.split(':', 1) + if parts: + file_path = parts[0].strip() + if any(file_path.endswith(ext) for ext in ['.cpp', '.cxx', '.cc', '.c', '.h', '.hpp', '.hxx']): + try: + rel_path = Path(file_path).relative_to(project_root) + file_key = str(rel_path) + except (ValueError, OSError): + file_key = file_path + + if is_warning_or_error or verbose: + issues_by_file[file_key].append(line) + + return result.returncode, dict(issues_by_file) + except FileNotFoundError: + error_msg = "Error: clang-tidy not found. Please install LLVM/Clang." + if verbose: + print(error_msg, file=sys.stderr) + return 1, {} + + +def run_clang_tidy(source_files: List[str], + compile_commands_path: Path, + extra_args: List[str], + fix: bool = False, + jobs: int = 1, + verbose: bool = False) -> int: + """Run clang-tidy on source files in batches, optionally in parallel.""" + if not source_files: + print("No source files to analyze.") + return 0 + + clang_tidy_exe = find_clang_tidy() + + BATCH_SIZE = 50 + total_files = len(source_files) + batches = [source_files[i:i + BATCH_SIZE] for i in range(0, total_files, BATCH_SIZE)] + + project_root = find_project_root() + compile_commands_dir = compile_commands_path.parent + + all_issues = defaultdict(list) + files_with_issues = set() + total_issues = 0 + + if jobs > 1: + if verbose: + print(f"Running clang-tidy on {total_files} file(s) in {len(batches)} batch(es) with {jobs} workers...\n") + else: + print(f"Analyzing {total_files} file(s) with {jobs} workers...", end='', flush=True) + + try: + with multiprocessing.Pool(processes=jobs) as pool: + batch_results = pool.map( + _run_batch, + [ + (idx + 1, batch, compile_commands_dir, fix, extra_args, project_root, clang_tidy_exe, verbose) + for idx, batch in enumerate(batches) + ] + ) + + overall_returncode = 0 + for returncode, issues in batch_results: + if returncode != 0: + overall_returncode = returncode + for file_path, file_issues in issues.items(): + if file_issues: + all_issues[file_path].extend(file_issues) + files_with_issues.add(file_path) + total_issues += len(file_issues) + + if not verbose: + print(" done.") + except KeyboardInterrupt: + print("\nInterrupted by user.") + return 130 + else: + if verbose: + print(f"Running clang-tidy on {total_files} file(s) in {len(batches)} batch(es)...\n") + else: + print(f"Analyzing {total_files} file(s)...", end='', flush=True) + + overall_returncode = 0 + for batch_num, batch in enumerate(batches, 1): + try: + if verbose: + print(f"Batch {batch_num}/{len(batches)}: {len(batch)} file(s)...") + + returncode, issues = _run_batch((batch_num, batch, compile_commands_dir, fix, extra_args, project_root, clang_tidy_exe, verbose)) + if returncode != 0: + overall_returncode = returncode + + for file_path, file_issues in issues.items(): + if file_issues: + all_issues[file_path].extend(file_issues) + files_with_issues.add(file_path) + total_issues += len(file_issues) + + if not verbose and batch_num < len(batches): + print('.', end='', flush=True) + except KeyboardInterrupt: + print("\nInterrupted by user.") + return 130 + + if not verbose: + print(" done.") + + print(f"\nSummary: {len(files_with_issues)} file(s) with issues, {total_issues} total issue(s)") + + if all_issues: + print("\nIssues found:") + for file_path in sorted(all_issues.keys()): + print(f"\n{file_path}:") + for issue in all_issues[file_path]: + print(f" {issue}") + + return overall_returncode + + +def main(): + parser = argparse.ArgumentParser( + description="Run clang-tidy on GeneralsGameCode project", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +Examples: + # First-time setup: Create PCH-free analysis build + cmake -B build/clang-tidy -DCMAKE_DISABLE_PRECOMPILE_HEADERS=ON -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -G Ninja + + # Analyze all source files + python scripts/run-clang-tidy.py + + # Analyze specific directory + python scripts/run-clang-tidy.py --include Core/Libraries/ + + # Analyze with specific checks + python scripts/run-clang-tidy.py --include GameClient/ -- -checks="-*,modernize-use-nullptr" + + # Apply fixes (use with caution!) + python scripts/run-clang-tidy.py --fix --include Keyboard.cpp -- -checks="-*,modernize-use-nullptr" + + # Use parallel processing (recommended: --jobs 4 for 6-core CPUs) + python scripts/run-clang-tidy.py --jobs 4 -- -checks="-*,modernize-use-nullptr" + + # Show verbose output (default: only warnings/errors) + python scripts/run-clang-tidy.py --verbose --include Core/Libraries/ + + # Use different build directory + python scripts/run-clang-tidy.py --build-dir build/win32-debug + +Note: Requires a PCH-free build. Create with: + cmake -B build/clang-tidy -DCMAKE_DISABLE_PRECOMPILE_HEADERS=ON -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -G Ninja + """ + ) + + parser.add_argument( + '--build-dir', '-b', + type=Path, + help='Build directory with compile_commands.json (auto-detected if omitted)' + ) + + parser.add_argument( + '--include', '-i', + action='append', + default=[], + help='Include files matching this pattern (can be used multiple times)' + ) + + parser.add_argument( + '--exclude', '-e', + action='append', + default=[], + help='Exclude files matching this pattern (can be used multiple times)' + ) + + parser.add_argument( + '--fix', + action='store_true', + help='Apply suggested fixes automatically (use with caution!)' + ) + + parser.add_argument( + '--jobs', '-j', + type=int, + default=multiprocessing.cpu_count(), + help=f'Number of parallel workers (default: {multiprocessing.cpu_count()} - auto-detected). Use 1 for serial processing' + ) + + parser.add_argument( + '--verbose', '-v', + action='store_true', + help='Show detailed output for each file (default: only show warnings/errors)' + ) + + parser.add_argument( + 'clang_tidy_args', + nargs='*', + help='Additional arguments to pass to clang-tidy, or specific files to analyze (if files are provided, --include/--exclude are ignored)' + ) + + args = parser.parse_args() + + try: + compile_commands_path = find_compile_commands(args.build_dir) + print(f"Using compile commands: {compile_commands_path}\n") + + project_root = find_project_root() + specified_files = [] + clang_tidy_args = [] + + for arg in args.clang_tidy_args: + file_path = Path(arg) + if not file_path.is_absolute(): + file_path = project_root / file_path + + if file_path.exists() and file_path.suffix in {'.cpp', '.cxx', '.cc', '.c', '.h', '.hpp'}: + specified_files.append(str(file_path.resolve())) + else: + clang_tidy_args.append(arg) + + if specified_files: + if args.verbose: + print(f"Analyzing {len(specified_files)} specified file(s)\n") + return run_clang_tidy( + specified_files, + compile_commands_path, + clang_tidy_args, + args.fix, + args.jobs, + args.verbose + ) + + compile_commands = load_compile_commands(compile_commands_path) + + default_excludes = [ + 'Dependencies/MaxSDK', # External SDK + '_deps/', # CMake dependencies + 'build/', # Build artifacts + '.git/', # Git directory + ] + + exclude_patterns = default_excludes + args.exclude + + source_files = filter_source_files( + compile_commands, + args.include, + exclude_patterns + ) + + if not source_files: + print("No source files found matching the criteria.") + return 1 + + if args.verbose: + print(f"Found {len(source_files)} source file(s) to analyze\n") + + return run_clang_tidy( + source_files, + compile_commands_path, + clang_tidy_args, + args.fix, + args.jobs, + args.verbose + ) + + except Exception as e: + print(f"Error: {e}", file=sys.stderr) + return 1 + + +if __name__ == '__main__': + sys.exit(main()) + From e6e874e200f8b14ce9e8a83f77064d6fda195e15 Mon Sep 17 00:00:00 2001 From: Caball009 <82909616+Caball009@users.noreply.github.com> Date: Thu, 11 Dec 2025 20:17:47 +0100 Subject: [PATCH 24/70] bugfix(string): Allow startsWith and endsWith to be called on empty strings (#1979) --- Core/GameEngine/Source/Common/System/AsciiString.cpp | 8 ++++---- Core/GameEngine/Source/Common/System/UnicodeString.cpp | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Core/GameEngine/Source/Common/System/AsciiString.cpp b/Core/GameEngine/Source/Common/System/AsciiString.cpp index 9828f7f1e2..31567ec533 100644 --- a/Core/GameEngine/Source/Common/System/AsciiString.cpp +++ b/Core/GameEngine/Source/Common/System/AsciiString.cpp @@ -477,25 +477,25 @@ void AsciiString::format_va(const char* format, va_list args) // ----------------------------------------------------- Bool AsciiString::startsWith(const char* p) const { - return ::startsWith(peek(), p); + return m_data && ::startsWith(peek(), p); } // ----------------------------------------------------- Bool AsciiString::startsWithNoCase(const char* p) const { - return ::startsWithNoCase(peek(), p); + return m_data && ::startsWithNoCase(peek(), p); } // ----------------------------------------------------- Bool AsciiString::endsWith(const char* p) const { - return ::endsWith(peek(), p); + return m_data && ::endsWith(peek(), p); } // ----------------------------------------------------- Bool AsciiString::endsWithNoCase(const char* p) const { - return ::endsWithNoCase(peek(), p); + return m_data && ::endsWithNoCase(peek(), p); } //----------------------------------------------------------------------------- diff --git a/Core/GameEngine/Source/Common/System/UnicodeString.cpp b/Core/GameEngine/Source/Common/System/UnicodeString.cpp index cb8669da34..af1a6317e3 100644 --- a/Core/GameEngine/Source/Common/System/UnicodeString.cpp +++ b/Core/GameEngine/Source/Common/System/UnicodeString.cpp @@ -409,25 +409,25 @@ void UnicodeString::format_va(const WideChar* format, va_list args) // ----------------------------------------------------- Bool UnicodeString::startsWith(const WideChar* p) const { - return ::startsWith(peek(), p); + return m_data && ::startsWith(peek(), p); } // ----------------------------------------------------- Bool UnicodeString::startsWithNoCase(const WideChar* p) const { - return ::startsWithNoCase(peek(), p); + return m_data && ::startsWithNoCase(peek(), p); } // ----------------------------------------------------- Bool UnicodeString::endsWith(const WideChar* p) const { - return ::endsWith(peek(), p); + return m_data && ::endsWith(peek(), p); } // ----------------------------------------------------- Bool UnicodeString::endsWithNoCase(const WideChar* p) const { - return ::endsWithNoCase(peek(), p); + return m_data && ::endsWithNoCase(peek(), p); } //----------------------------------------------------------------------------- From d2625f0f6ad66951ee5a06ebbad3b5aff1463b4c Mon Sep 17 00:00:00 2001 From: Bobby Battista Date: Thu, 11 Dec 2025 16:22:30 -0500 Subject: [PATCH 25/70] refactor: Remove superfluous inline and register keywords with clang-tidy (#1936) --- Core/GameEngine/Include/Common/AsciiString.h | 8 +- Core/GameEngine/Include/Common/GameMemory.h | 4 +- Core/GameEngine/Include/Common/Radar.h | 18 +- .../GameEngine/Include/Common/UnicodeString.h | 8 +- .../Include/GameClient/ClientRandomValue.h | 6 +- Core/GameEngine/Include/GameClient/Smudge.h | 6 +- .../Include/GameLogic/LogicRandomValue.h | 6 +- .../Include/GameNetwork/FirewallHelper.h | 8 +- .../GameEngine/Include/GameNetwork/GameInfo.h | 24 +-- .../GameNetwork/GameSpy/StagingRoomGameInfo.h | 70 ++++---- .../Include/GameNetwork/IPEnumeration.h | 12 +- Core/GameEngine/Include/GameNetwork/LANAPI.h | 6 +- .../Include/GameNetwork/LANGameInfo.h | 44 ++--- .../Include/GameNetwork/LANPlayer.h | 28 +-- .../Include/GameNetwork/NetCommandMsg.h | 20 +-- .../Include/GameNetwork/Transport.h | 2 +- Core/GameEngine/Include/GameNetwork/User.h | 10 +- .../GameEngine/Source/GameNetwork/Network.cpp | 4 +- .../W3DDevice/GameClient/W3DShaderManager.h | 4 +- .../Libraries/Source/WWVegas/WW3D2/bwrender.h | 2 +- .../Source/WWVegas/WW3D2/dx8polygonrenderer.h | 2 +- Core/Libraries/Source/WWVegas/WW3D2/font3d.h | 8 +- .../Libraries/Source/WWVegas/WW3D2/intersec.h | 20 +-- Core/Libraries/Source/WWVegas/WW3D2/proto.h | 4 +- Core/Libraries/Source/WWVegas/WW3D2/rendobj.h | 2 +- .../Source/WWVegas/WW3D2/visrasterizer.cpp | 2 +- .../Source/WWVegas/WWLib/cpudetect.h | 38 ++-- Core/Libraries/Source/WWVegas/WWMath/sphere.h | 6 +- Core/Tools/mangler/wlib/xtime.cpp | 2 +- Core/Tools/matchbot/wlib/xtime.cpp | 2 +- Dependencies/Utility/Utility/endian_compat.h | 40 ++--- .../Code/GameEngine/Include/Common/BitFlags.h | 52 +++--- .../Include/Common/BuildAssistant.h | 2 +- .../Code/GameEngine/Include/Common/Dict.h | 26 +-- .../Code/GameEngine/Include/Common/Geometry.h | 16 +- Generals/Code/GameEngine/Include/Common/INI.h | 24 +-- .../Code/GameEngine/Include/Common/Module.h | 12 +- .../Code/GameEngine/Include/Common/Money.h | 4 +- .../Include/Common/MultiplayerSettings.h | 24 +-- .../Include/Common/NameKeyGenerator.h | 2 +- .../Code/GameEngine/Include/Common/Player.h | 42 ++--- .../Include/Common/PlayerTemplate.h | 38 ++-- .../Include/Common/SparseMatchFinder.h | 4 +- .../GameEngine/Include/Common/StateMachine.h | 10 +- .../Include/Common/SubsystemInterface.h | 4 +- .../Code/GameEngine/Include/Common/Team.h | 8 +- .../GameEngine/Include/Common/TerrainTypes.h | 24 +-- .../GameEngine/Include/Common/ThingTemplate.h | 14 +- .../GameEngine/Include/GameClient/Drawable.h | 30 ++-- .../GameEngine/Include/GameClient/InGameUI.h | 2 +- .../GameEngine/Include/GameClient/Mouse.h | 2 +- .../Include/GameClient/ParticleSys.h | 22 +-- .../GameEngine/Include/GameClient/Shell.h | 2 +- .../Include/GameClient/TerrainRoads.h | 110 ++++++------ .../Code/GameEngine/Include/GameLogic/AI.h | 104 +++++------ .../GameEngine/Include/GameLogic/ArmorSet.h | 12 +- .../Include/GameLogic/CrateSystem.h | 2 +- .../Include/GameLogic/GhostObject.h | 20 +-- .../GameEngine/Include/GameLogic/Locomotor.h | 120 ++++++------- .../Include/GameLogic/LocomotorSet.h | 4 +- .../Include/GameLogic/Module/AIUpdate.h | 40 ++--- .../GameLogic/Module/AutoHealBehavior.h | 2 +- .../Include/GameLogic/Module/DieModule.h | 2 +- .../Module/FireWeaponWhenDamagedBehavior.h | 2 +- .../Module/FireWeaponWhenDeadBehavior.h | 2 +- .../Include/GameLogic/Module/JetAIUpdate.h | 4 +- .../Include/GameLogic/Module/PhysicsUpdate.h | 6 +- .../GameLogic/Module/SlowDeathBehavior.h | 6 +- .../Include/GameLogic/ObjectCreationList.h | 6 +- .../Include/GameLogic/PartitionManager.h | 30 ++-- .../Include/GameLogic/TerrainLogic.h | 10 +- .../Include/GameLogic/VictoryConditions.h | 4 +- .../GameEngine/Include/GameLogic/Weapon.h | 154 ++++++++-------- .../GameEngine/Include/GameLogic/WeaponSet.h | 12 +- .../Include/W3DDevice/GameClient/HeightMap.h | 2 +- .../GameClient/Module/W3DModelDraw.h | 12 +- .../Include/W3DDevice/GameClient/W3DShadow.h | 4 +- .../Include/W3DDevice/GameClient/W3DWater.h | 2 +- .../W3DDevice/GameClient/WorldHeightMap.h | 20 +-- .../Code/Libraries/Include/Lib/BaseType.h | 4 +- .../Libraries/Source/WWVegas/WW3D2/dx8fvf.h | 18 +- .../Source/WWVegas/WW3D2/dx8indexbuffer.h | 8 +- .../Source/WWVegas/WW3D2/dx8renderer.h | 4 +- .../Source/WWVegas/WW3D2/dx8vertexbuffer.h | 8 +- .../Libraries/Source/WWVegas/WW3D2/mesh.h | 2 +- .../Libraries/Source/WWVegas/WW3D2/shader.h | 74 ++++---- .../Source/WWVegas/WW3D2/vertmaterial.h | 2 +- .../Libraries/Source/WWVegas/WW3D2/w3d_file.h | 4 +- .../WorldBuilder/include/WorldBuilderView.h | 2 +- .../Code/GameEngine/Include/Common/BitFlags.h | 52 +++--- .../Include/Common/BuildAssistant.h | 2 +- .../Code/GameEngine/Include/Common/Dict.h | 26 +-- .../Code/GameEngine/Include/Common/Geometry.h | 16 +- .../Code/GameEngine/Include/Common/INI.h | 24 +-- .../Code/GameEngine/Include/Common/Module.h | 12 +- .../Code/GameEngine/Include/Common/Money.h | 4 +- .../Include/Common/MultiplayerSettings.h | 24 +-- .../Include/Common/NameKeyGenerator.h | 2 +- .../Code/GameEngine/Include/Common/Player.h | 44 ++--- .../Include/Common/PlayerTemplate.h | 44 ++--- .../Include/Common/SparseMatchFinder.h | 4 +- .../GameEngine/Include/Common/StateMachine.h | 10 +- .../Include/Common/SubsystemInterface.h | 4 +- .../Code/GameEngine/Include/Common/Team.h | 8 +- .../GameEngine/Include/Common/TerrainTypes.h | 24 +-- .../Code/GameEngine/Include/Common/Thing.h | 12 +- .../GameEngine/Include/Common/ThingTemplate.h | 14 +- .../GameEngine/Include/GameClient/Drawable.h | 30 ++-- .../GameEngine/Include/GameClient/InGameUI.h | 2 +- .../GameEngine/Include/GameClient/Mouse.h | 2 +- .../Include/GameClient/ParticleSys.h | 22 +-- .../GameEngine/Include/GameClient/Shell.h | 2 +- .../Include/GameClient/TerrainRoads.h | 110 ++++++------ .../Code/GameEngine/Include/GameLogic/AI.h | 110 ++++++------ .../GameEngine/Include/GameLogic/ArmorSet.h | 12 +- .../Include/GameLogic/CrateSystem.h | 2 +- .../Include/GameLogic/GhostObject.h | 20 +-- .../GameEngine/Include/GameLogic/Locomotor.h | 138 +++++++------- .../Include/GameLogic/LocomotorSet.h | 4 +- .../Include/GameLogic/Module/AIUpdate.h | 40 ++--- .../GameLogic/Module/AutoHealBehavior.h | 2 +- .../Module/CountermeasuresBehavior.h | 2 +- .../Include/GameLogic/Module/DieModule.h | 2 +- .../Include/GameLogic/Module/FXListDie.h | 2 +- .../Module/FireWeaponWhenDamagedBehavior.h | 2 +- .../Module/FireWeaponWhenDeadBehavior.h | 2 +- .../Include/GameLogic/Module/PhysicsUpdate.h | 6 +- .../GameLogic/Module/SlowDeathBehavior.h | 6 +- .../GameLogic/Module/SpyVisionUpdate.h | 2 +- .../Include/GameLogic/ObjectCreationList.h | 6 +- .../Include/GameLogic/PartitionManager.h | 30 ++-- .../Include/GameLogic/TerrainLogic.h | 10 +- .../Include/GameLogic/VictoryConditions.h | 4 +- .../GameEngine/Include/GameLogic/Weapon.h | 170 +++++++++--------- .../W3DDevice/GameClient/BaseHeightMap.h | 2 +- .../GameClient/Module/W3DModelDraw.h | 12 +- .../Include/W3DDevice/GameClient/W3DShadow.h | 4 +- .../Include/W3DDevice/GameClient/W3DWater.h | 2 +- .../W3DDevice/GameClient/WorldHeightMap.h | 20 +-- .../Code/Libraries/Include/Lib/BaseType.h | 4 +- .../Libraries/Source/WWVegas/WW3D2/dx8fvf.h | 18 +- .../Source/WWVegas/WW3D2/dx8indexbuffer.h | 8 +- .../Source/WWVegas/WW3D2/dx8renderer.h | 8 +- .../Source/WWVegas/WW3D2/dx8vertexbuffer.h | 8 +- .../Source/WWVegas/WW3D2/lightenvironment.h | 2 +- .../Libraries/Source/WWVegas/WW3D2/mesh.h | 2 +- .../Libraries/Source/WWVegas/WW3D2/shader.h | 74 ++++---- .../Source/WWVegas/WW3D2/vertmaterial.h | 2 +- .../Libraries/Source/WWVegas/WW3D2/w3d_file.h | 4 +- .../WorldBuilder/include/WorldBuilderView.h | 2 +- 150 files changed, 1418 insertions(+), 1418 deletions(-) diff --git a/Core/GameEngine/Include/Common/AsciiString.h b/Core/GameEngine/Include/Common/AsciiString.h index 53c1e83fc6..5af9cbe130 100644 --- a/Core/GameEngine/Include/Common/AsciiString.h +++ b/Core/GameEngine/Include/Common/AsciiString.h @@ -91,13 +91,13 @@ class AsciiString unsigned short m_numCharsAllocated; // length of data allocated // char m_stringdata[]; - inline char* peek() { return (char*)(this+1); } + char* peek() { return (char*)(this+1); } }; #ifdef RTS_DEBUG void validate() const; #else - inline void validate() const { } + void validate() const { } #endif protected: @@ -325,13 +325,13 @@ class AsciiString return true iff self starts with the given string. */ Bool startsWith(const char* p) const; - inline Bool startsWith(const AsciiString& stringSrc) const { return startsWith(stringSrc.str()); } + Bool startsWith(const AsciiString& stringSrc) const { return startsWith(stringSrc.str()); } /** return true iff self starts with the given string. (case insensitive) */ Bool startsWithNoCase(const char* p) const; - inline Bool startsWithNoCase(const AsciiString& stringSrc) const { return startsWithNoCase(stringSrc.str()); } + Bool startsWithNoCase(const AsciiString& stringSrc) const { return startsWithNoCase(stringSrc.str()); } /** return true iff self ends with the given string. diff --git a/Core/GameEngine/Include/Common/GameMemory.h b/Core/GameEngine/Include/Common/GameMemory.h index 8d173afec4..1ea96161ce 100644 --- a/Core/GameEngine/Include/Common/GameMemory.h +++ b/Core/GameEngine/Include/Common/GameMemory.h @@ -743,8 +743,8 @@ class MemoryPoolObject virtual ~MemoryPoolObject() { } protected: - inline void *operator new(size_t s) { DEBUG_CRASH(("This should be impossible")); return 0; } - inline void operator delete(void *p) { DEBUG_CRASH(("This should be impossible")); } + void *operator new(size_t s) { DEBUG_CRASH(("This should be impossible")); return 0; } + void operator delete(void *p) { DEBUG_CRASH(("This should be impossible")); } protected: diff --git a/Core/GameEngine/Include/Common/Radar.h b/Core/GameEngine/Include/Common/Radar.h index c3ccbc29e8..431cfbf166 100644 --- a/Core/GameEngine/Include/Common/Radar.h +++ b/Core/GameEngine/Include/Common/Radar.h @@ -95,15 +95,15 @@ class RadarObject : public MemoryPoolObject, // color management void setColor( Color c ) { m_color = c; } - inline Color getColor( void ) const { return m_color; } + Color getColor( void ) const { return m_color; } - inline void friend_setObject( Object *obj ) { m_object = obj; } - inline Object *friend_getObject( void ) { return m_object; } - inline const Object *friend_getObject( void ) const { return m_object; } + void friend_setObject( Object *obj ) { m_object = obj; } + Object *friend_getObject( void ) { return m_object; } + const Object *friend_getObject( void ) const { return m_object; } - inline void friend_setNext( RadarObject *next ) { m_next = next; } - inline RadarObject *friend_getNext( void ) { return m_next; } - inline const RadarObject *friend_getNext( void ) const { return m_next; } + void friend_setNext( RadarObject *next ) { m_next = next; } + RadarObject *friend_getNext( void ) { return m_next; } + const RadarObject *friend_getNext( void ) const { return m_next; } Bool isTemporarilyHidden() const; static Bool isTemporarilyHidden(const Object* obj); @@ -236,8 +236,8 @@ class Radar : public Snapshot, void deleteListResources( void ); ///< delete list radar resources used Bool deleteFromList( Object *obj, RadarObject **list ); ///< try to remove object from specific list - inline Real getTerrainAverageZ() const { return m_terrainAverageZ; } - inline Real getWaterAverageZ() const { return m_waterAverageZ; } + Real getTerrainAverageZ() const { return m_terrainAverageZ; } + Real getWaterAverageZ() const { return m_waterAverageZ; } void clearAllEvents( void ); ///< remove all radar events in progress diff --git a/Core/GameEngine/Include/Common/UnicodeString.h b/Core/GameEngine/Include/Common/UnicodeString.h index ee362284f9..ff66edfe47 100644 --- a/Core/GameEngine/Include/Common/UnicodeString.h +++ b/Core/GameEngine/Include/Common/UnicodeString.h @@ -91,13 +91,13 @@ class UnicodeString unsigned short m_numCharsAllocated; // length of data allocated // WideChar m_stringdata[]; - inline WideChar* peek() { return (WideChar*)(this+1); } + WideChar* peek() { return (WideChar*)(this+1); } }; #ifdef RTS_DEBUG void validate() const; #else - inline void validate() const { } + void validate() const { } #endif protected: @@ -310,13 +310,13 @@ class UnicodeString return true iff self starts with the given string. */ Bool startsWith(const WideChar* p) const; - inline Bool startsWith(const UnicodeString& stringSrc) const { return startsWith(stringSrc.str()); } + Bool startsWith(const UnicodeString& stringSrc) const { return startsWith(stringSrc.str()); } /** return true iff self starts with the given string. (case insensitive) */ Bool startsWithNoCase(const WideChar* p) const; - inline Bool startsWithNoCase(const UnicodeString& stringSrc) const { return startsWithNoCase(stringSrc.str()); } + Bool startsWithNoCase(const UnicodeString& stringSrc) const { return startsWithNoCase(stringSrc.str()); } /** return true iff self ends with the given string. diff --git a/Core/GameEngine/Include/GameClient/ClientRandomValue.h b/Core/GameEngine/Include/GameClient/ClientRandomValue.h index f5488a2666..3222cf4e71 100644 --- a/Core/GameEngine/Include/GameClient/ClientRandomValue.h +++ b/Core/GameEngine/Include/GameClient/ClientRandomValue.h @@ -75,9 +75,9 @@ class GameClientRandomVariable void setRange( Real low, Real high, DistributionType type = UNIFORM ); Real getValue( void ) const; ///< return a value from the random distribution - inline Real getMinimumValue( void ) const { return m_low; } - inline Real getMaximumValue( void ) const { return m_high; } - inline DistributionType getDistributionType( void ) const { return m_type; } + Real getMinimumValue( void ) const { return m_low; } + Real getMaximumValue( void ) const { return m_high; } + DistributionType getDistributionType( void ) const { return m_type; } protected: DistributionType m_type; ///< the kind of random distribution Real m_low, m_high; ///< the range of random values diff --git a/Core/GameEngine/Include/GameClient/Smudge.h b/Core/GameEngine/Include/GameClient/Smudge.h index 2522d5f670..657736d1f2 100644 --- a/Core/GameEngine/Include/GameClient/Smudge.h +++ b/Core/GameEngine/Include/GameClient/Smudge.h @@ -78,9 +78,9 @@ class SmudgeManager SmudgeSet *addSmudgeSet(void); void removeSmudgeSet(SmudgeSet &mySmudge); - inline Int getSmudgeCountLastFrame(void) {return m_smudgeCountLastFrame;} ///name Bool isUser( UnicodeString userName ); ///< Does this slot contain the given user? Bool isLocalPlayer( void ) const; ///< Is this slot me? - inline void setLogin( UnicodeString name ) { m_user.setLogin(name); } - inline void setLogin( AsciiString name ) { m_user.setLogin(name); } - inline void setHost( UnicodeString name ) { m_user.setHost(name); } - inline void setHost( AsciiString name ) { m_user.setHost(name); } - inline void setSerial( AsciiString serial ) { m_serial = serial; } - inline AsciiString getSerial( void ) { return m_serial; } + void setLogin( UnicodeString name ) { m_user.setLogin(name); } + void setLogin( AsciiString name ) { m_user.setLogin(name); } + void setHost( UnicodeString name ) { m_user.setHost(name); } + void setHost( AsciiString name ) { m_user.setHost(name); } + void setSerial( AsciiString serial ) { m_serial = serial; } + AsciiString getSerial( void ) { return m_serial; } - inline void setLastHeard( UnsignedInt t ) { m_lastHeard = t; } - inline UnsignedInt getLastHeard( void ) { return m_lastHeard; } + void setLastHeard( UnsignedInt t ) { m_lastHeard = t; } + UnsignedInt getLastHeard( void ) { return m_lastHeard; } //LANGameSlot& operator=(const LANGameSlot& src); @@ -85,60 +85,60 @@ class LANGameInfo : public GameInfo virtual Int getLocalSlotNum( void ) const; ///< Get the local slot number, or -1 if we're not present Int getSlotNum( UnicodeString userName ); ///< Get the slot number corresponding to a specific user, or -1 if he's not present - inline UnsignedInt getLastHeard( void ) { return m_lastHeard; } - inline void setLastHeard( UnsignedInt lastHeard ) { m_lastHeard = lastHeard; } - inline LANGameInfo *getNext( void ) { return m_next; } - inline void setNext( LANGameInfo *next ) { m_next = next; } + UnsignedInt getLastHeard( void ) { return m_lastHeard; } + void setLastHeard( UnsignedInt lastHeard ) { m_lastHeard = lastHeard; } + LANGameInfo *getNext( void ) { return m_next; } + void setNext( LANGameInfo *next ) { m_next = next; } // Game options void setMap( AsciiString mapName ); ///< Set the map to play on void setSeed( Int seed ); ///< Set the random seed for the game - inline void setName( UnicodeString name ) { m_gameName = name; } ///< Set the Name of the Game - inline UnicodeString getName( void ) { return m_gameName; } ///< Get the Name of the Game + void setName( UnicodeString name ) { m_gameName = name; } ///< Set the Name of the Game + UnicodeString getName( void ) { return m_gameName; } ///< Get the Name of the Game // Convinience functions that interface with the LANPlayer held in the slot list virtual void resetAccepted(void); ///< Reset the accepted flag on all players Bool amIHost( void ); ///< Convenience function - is the local player the game host? /// Get the IP of selected player or return 0 - inline UnsignedInt getIP( int who ) + UnsignedInt getIP( int who ) { return m_LANSlot[who].getIP(); } /// Set the IP of the Selected Player - inline void setIP( int who, UnsignedInt IP ) + void setIP( int who, UnsignedInt IP ) { m_LANSlot[who].setIP(IP); } /// set whether or not this is a direct connect game or not. - inline void setIsDirectConnect(Bool isDirectConnect) + void setIsDirectConnect(Bool isDirectConnect) { m_isDirectConnect = isDirectConnect; } /// returns whether or not this is a direct connect game or not. - inline Bool getIsDirectConnect() + Bool getIsDirectConnect() { return m_isDirectConnect; } /// Set the Player Name - inline void setPlayerName( int who, UnicodeString name ) + void setPlayerName( int who, UnicodeString name ) { m_LANSlot[who].setName(name); } /// Return the Player name or TheEmptyString - inline UnicodeString getPlayerName(int who) + UnicodeString getPlayerName(int who) { return m_LANSlot[who].getName(); } /// Return the time the player was heard from last, or 0 - inline UnsignedInt getPlayerLastHeard( int who ) + UnsignedInt getPlayerLastHeard( int who ) { if (m_LANSlot[who].isHuman()) return m_LANSlot[who].getLastHeard(); @@ -146,7 +146,7 @@ class LANGameInfo : public GameInfo } /// Set the last time we heard from the player - inline void setPlayerLastHeard( int who, UnsignedInt lastHeard ) + void setPlayerLastHeard( int who, UnsignedInt lastHeard ) { DEBUG_LOG(("LANGameInfo::setPlayerLastHeard - changing player %d last heard from %d to %d", who, getPlayerLastHeard(who), lastHeard)); if (m_LANSlot[who].isHuman()) diff --git a/Core/GameEngine/Include/GameNetwork/LANPlayer.h b/Core/GameEngine/Include/GameNetwork/LANPlayer.h index 5c0f146d8a..f71e7b18a7 100644 --- a/Core/GameEngine/Include/GameNetwork/LANPlayer.h +++ b/Core/GameEngine/Include/GameNetwork/LANPlayer.h @@ -38,20 +38,20 @@ class LANPlayer LANPlayer() { m_name = m_login = m_host = L""; m_lastHeard = 0; m_next = NULL; m_IP = 0; } // Access functions - inline UnicodeString getName( void ) { return m_name; } - inline void setName( UnicodeString name ) { m_name = name; } - inline UnicodeString getLogin( void ) { return m_login; } - inline void setLogin( UnicodeString name ) { m_login = name; } - inline void setLogin( AsciiString name ) { m_login.translate(name); } - inline UnicodeString getHost( void ) { return m_host; } - inline void setHost( UnicodeString name ) { m_host = name; } - inline void setHost( AsciiString name ) { m_host.translate(name); } - inline UnsignedInt getLastHeard( void ) { return m_lastHeard; } - inline void setLastHeard( UnsignedInt lastHeard ) { m_lastHeard = lastHeard; } - inline LANPlayer *getNext( void ) { return m_next; } - inline void setNext( LANPlayer *next ) { m_next = next; } - inline UnsignedInt getIP( void ) { return m_IP; } - inline void setIP( UnsignedInt IP ) { m_IP = IP; } + UnicodeString getName( void ) { return m_name; } + void setName( UnicodeString name ) { m_name = name; } + UnicodeString getLogin( void ) { return m_login; } + void setLogin( UnicodeString name ) { m_login = name; } + void setLogin( AsciiString name ) { m_login.translate(name); } + UnicodeString getHost( void ) { return m_host; } + void setHost( UnicodeString name ) { m_host = name; } + void setHost( AsciiString name ) { m_host.translate(name); } + UnsignedInt getLastHeard( void ) { return m_lastHeard; } + void setLastHeard( UnsignedInt lastHeard ) { m_lastHeard = lastHeard; } + LANPlayer *getNext( void ) { return m_next; } + void setNext( LANPlayer *next ) { m_next = next; } + UnsignedInt getIP( void ) { return m_IP; } + void setIP( UnsignedInt IP ) { m_IP = IP; } protected: UnicodeString m_name; ///< Player name diff --git a/Core/GameEngine/Include/GameNetwork/NetCommandMsg.h b/Core/GameEngine/Include/GameNetwork/NetCommandMsg.h index 6f47b794ca..59b05f88e2 100644 --- a/Core/GameEngine/Include/GameNetwork/NetCommandMsg.h +++ b/Core/GameEngine/Include/GameNetwork/NetCommandMsg.h @@ -39,16 +39,16 @@ class NetCommandMsg : public MemoryPoolObject public: NetCommandMsg(); //virtual ~NetCommandMsg(); - inline UnsignedInt GetTimestamp() { return m_timestamp; } - inline void SetTimestamp(UnsignedInt timestamp) { m_timestamp = timestamp; } - inline void setExecutionFrame(UnsignedInt frame) { m_executionFrame = frame; } - inline void setPlayerID(UnsignedInt playerID) { m_playerID = playerID; } - inline void setID(UnsignedShort id) { m_id = id; } - inline UnsignedInt getExecutionFrame() { return m_executionFrame; } - inline UnsignedInt getPlayerID() { return m_playerID; } - inline UnsignedShort getID() { return m_id; } - inline void setNetCommandType(NetCommandType type) { m_commandType = type; } - inline NetCommandType getNetCommandType() { return m_commandType; } + UnsignedInt GetTimestamp() { return m_timestamp; } + void SetTimestamp(UnsignedInt timestamp) { m_timestamp = timestamp; } + void setExecutionFrame(UnsignedInt frame) { m_executionFrame = frame; } + void setPlayerID(UnsignedInt playerID) { m_playerID = playerID; } + void setID(UnsignedShort id) { m_id = id; } + UnsignedInt getExecutionFrame() { return m_executionFrame; } + UnsignedInt getPlayerID() { return m_playerID; } + UnsignedShort getID() { return m_id; } + void setNetCommandType(NetCommandType type) { m_commandType = type; } + NetCommandType getNetCommandType() { return m_commandType; } virtual Int getSortNumber(); void attach(); void detach(); diff --git a/Core/GameEngine/Include/GameNetwork/Transport.h b/Core/GameEngine/Include/GameNetwork/Transport.h index 747f9d475b..bb3caff847 100644 --- a/Core/GameEngine/Include/GameNetwork/Transport.h +++ b/Core/GameEngine/Include/GameNetwork/Transport.h @@ -56,7 +56,7 @@ class Transport //: public MemoryPoolObject Bool queueSend(UnsignedInt addr, UnsignedShort port, const UnsignedByte *buf, Int len /*, NetMessageFlags flags, Int id */); ///< Queue a packet for sending to the specified address and port. This will be sent on the next update() call. - inline Bool allowBroadcasts(Bool val) { if (!m_udpsock) return false; return (m_udpsock->AllowBroadcasts(val))?true:false; } + Bool allowBroadcasts(Bool val) { if (!m_udpsock) return false; return (m_udpsock->AllowBroadcasts(val))?true:false; } // Latency insertion and packet loss void setLatency( Bool val ) { m_useLatency = val; } diff --git a/Core/GameEngine/Include/GameNetwork/User.h b/Core/GameEngine/Include/GameNetwork/User.h index 0f69b8fea9..d37ec9a52e 100644 --- a/Core/GameEngine/Include/GameNetwork/User.h +++ b/Core/GameEngine/Include/GameNetwork/User.h @@ -41,12 +41,12 @@ class User : public MemoryPoolObject Bool operator== (const User *other); Bool operator!= (const User *other); - inline UnicodeString GetName() { return m_name; } + UnicodeString GetName() { return m_name; } void setName(UnicodeString name); - inline UnsignedShort GetPort() { return m_port; } - inline UnsignedInt GetIPAddr() { return m_ipaddr; } - inline void SetPort(UnsignedShort port) { m_port = port; } - inline void SetIPAddr(UnsignedInt ipaddr) { m_ipaddr = ipaddr; } + UnsignedShort GetPort() { return m_port; } + UnsignedInt GetIPAddr() { return m_ipaddr; } + void SetPort(UnsignedShort port) { m_port = port; } + void SetIPAddr(UnsignedInt ipaddr) { m_ipaddr = ipaddr; } private: diff --git a/Core/GameEngine/Source/GameNetwork/Network.cpp b/Core/GameEngine/Source/GameNetwork/Network.cpp index de436e7b58..71d672cfed 100644 --- a/Core/GameEngine/Source/GameNetwork/Network.cpp +++ b/Core/GameEngine/Source/GameNetwork/Network.cpp @@ -112,8 +112,8 @@ class Network : public NetworkInterface Bool deinit( void ); ///< Shutdown connections, release memory void setLocalAddress(UnsignedInt ip, UnsignedInt port); - inline UnsignedInt getRunAhead(void) { return m_runAhead; } - inline UnsignedInt getFrameRate(void) { return m_frameRate; } + UnsignedInt getRunAhead(void) { return m_runAhead; } + UnsignedInt getFrameRate(void) { return m_frameRate; } UnsignedInt getPacketArrivalCushion(void); ///< Returns the smallest packet arrival cushion since this was last called. Bool isFrameDataReady( void ); virtual Bool isStalling(); diff --git a/Core/GameEngineDevice/Include/W3DDevice/GameClient/W3DShaderManager.h b/Core/GameEngineDevice/Include/W3DDevice/GameClient/W3DShaderManager.h index bea0a432d5..90192607a4 100644 --- a/Core/GameEngineDevice/Include/W3DDevice/GameClient/W3DShaderManager.h +++ b/Core/GameEngineDevice/Include/W3DDevice/GameClient/W3DShaderManager.h @@ -90,9 +90,9 @@ class W3DShaderManager ///Specify all textures (up to 8) which can be accessed by the shaders. static void setTexture(Int stage,TextureClass* texture) {m_Textures[stage]=texture;} ///Return current texture available to shaders. - static inline TextureClass *getShaderTexture(Int stage) { return m_Textures[stage];} ///ModelMatrix = Source->ModelMatrix; Destination->ModelLocation = Source->ModelLocation; Copy_Partial_Results(Destination, Source); @@ -176,7 +176,7 @@ class IntersectionClass } - inline void Copy_Results(IntersectionResultClass *Source) { + void Copy_Results(IntersectionResultClass *Source) { Copy_Results(&Result, Source); } @@ -185,7 +185,7 @@ class IntersectionClass // 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) + void Copy_Partial_Results(IntersectionResultClass *Destination, IntersectionResultClass *Source) { Destination->IntersectedPolygon = Source->IntersectedPolygon; Destination->Intersection = Source->Intersection; @@ -198,13 +198,13 @@ class IntersectionClass // used for creating temporary copies - inline IntersectionClass(IntersectionClass *source) + IntersectionClass(IntersectionClass *source) { *this = source; } - inline IntersectionClass *operator =(IntersectionClass *source) + IntersectionClass *operator =(IntersectionClass *source) { Set(source->RayLocation, source->RayDirection, source->IntersectionNormal, source->InterpolateNormal, source->MaxDistance, source->ConvexTest); Copy_Results(&source->Result); @@ -220,7 +220,7 @@ class IntersectionClass // 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) + 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); @@ -238,7 +238,7 @@ class IntersectionClass // this will find the intersection with the sphere and the intersection normal if needed. - inline bool Intersect_Sphere(SphereClass &Sphere, IntersectionResultClass *FinalResult) + bool Intersect_Sphere(SphereClass &Sphere, IntersectionResultClass *FinalResult) { if(!Intersect_Sphere_Quick(Sphere, FinalResult)) return false; diff --git a/Core/Libraries/Source/WWVegas/WW3D2/proto.h b/Core/Libraries/Source/WWVegas/WW3D2/proto.h index e1879f665b..eb375602e2 100644 --- a/Core/Libraries/Source/WWVegas/WW3D2/proto.h +++ b/Core/Libraries/Source/WWVegas/WW3D2/proto.h @@ -88,8 +88,8 @@ class PrototypeClass virtual RenderObjClass * Create(void) = 0; virtual void DeleteSelf() = 0; - inline void friend_setNextHash(PrototypeClass* n) { NextHash = n; } - inline PrototypeClass* friend_getNextHash() { return NextHash; } + void friend_setNextHash(PrototypeClass* n) { NextHash = n; } + PrototypeClass* friend_getNextHash() { return NextHash; } protected: virtual ~PrototypeClass(void) {}; diff --git a/Core/Libraries/Source/WWVegas/WW3D2/rendobj.h b/Core/Libraries/Source/WWVegas/WW3D2/rendobj.h index 95fa52d698..fe1005ff48 100644 --- a/Core/Libraries/Source/WWVegas/WW3D2/rendobj.h +++ b/Core/Libraries/Source/WWVegas/WW3D2/rendobj.h @@ -267,7 +267,7 @@ class RenderObjClass : public RefCountClass , public PersistClass, public MultiL #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; } + RenderObjClass * Get_Container(void) const { return Container; } #else virtual RenderObjClass * Get_Container(void) const; #endif diff --git a/Core/Libraries/Source/WWVegas/WW3D2/visrasterizer.cpp b/Core/Libraries/Source/WWVegas/WW3D2/visrasterizer.cpp index b6021d5087..5c4bf51f9e 100644 --- a/Core/Libraries/Source/WWVegas/WW3D2/visrasterizer.cpp +++ b/Core/Libraries/Source/WWVegas/WW3D2/visrasterizer.cpp @@ -491,7 +491,7 @@ struct EdgeStruct OOZStep = XStep * grad.DOOZ_DX + grad.DOOZ_DY; } - inline int Step(void) + int Step(void) { X+=XStep; Y++; diff --git a/Core/Libraries/Source/WWVegas/WWLib/cpudetect.h b/Core/Libraries/Source/WWVegas/WWLib/cpudetect.h index 76389cd91c..4cba11de11 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/cpudetect.h +++ b/Core/Libraries/Source/WWVegas/WWLib/cpudetect.h @@ -143,30 +143,30 @@ class CPUDetectClass RISE_PROCESSOR_DRAGON2_018 } RiseProcessorType; - inline static ProcessorManufacturerType Get_Processor_Manufacturer() {return ProcessorManufacturer;} + static ProcessorManufacturerType Get_Processor_Manufacturer() {return ProcessorManufacturer;} static const char* Get_Processor_Manufacturer_Name(); - inline static bool Has_CPUID_Instruction() { return HasCPUIDInstruction; } - inline static bool Has_RDTSC_Instruction() { return HasRDTSCInstruction; } - inline static bool Has_CMOV_Instruction() { return HasCMOVSupport; } - inline static bool Has_MMX_Instruction_Set() { return HasMMXSupport; } - inline static bool Has_SSE_Instruction_Set() { return HasSSESupport; } - inline static bool Has_SSE2_Instruction_Set() { return HasSSE2Support; } - inline static bool Has_3DNow_Instruction_Set() { return Has3DNowSupport; } - inline static bool Has_Extended_3DNow_Instruction_Set() { return HasExtended3DNowSupport; } + static bool Has_CPUID_Instruction() { return HasCPUIDInstruction; } + static bool Has_RDTSC_Instruction() { return HasRDTSCInstruction; } + static bool Has_CMOV_Instruction() { return HasCMOVSupport; } + static bool Has_MMX_Instruction_Set() { return HasMMXSupport; } + static bool Has_SSE_Instruction_Set() { return HasSSESupport; } + static bool Has_SSE2_Instruction_Set() { return HasSSE2Support; } + static bool Has_3DNow_Instruction_Set() { return Has3DNowSupport; } + static bool Has_Extended_3DNow_Instruction_Set() { return HasExtended3DNowSupport; } // Call these functions after determining the manufacturer to find out which of the manufacturers processors // the system has. - inline static IntelProcessorType Get_Intel_Processor() { return IntelProcessor; } - inline static AMDProcessorType Get_AMD_Processor() { return AMDProcessor; } - inline static VIAProcessorType Get_VIA_Processor() { return VIAProcessor; } - inline static RiseProcessorType Get_Rise_Processor() { return RiseProcessor; } + static IntelProcessorType Get_Intel_Processor() { return IntelProcessor; } + static AMDProcessorType Get_AMD_Processor() { return AMDProcessor; } + static VIAProcessorType Get_VIA_Processor() { return VIAProcessor; } + static RiseProcessorType Get_Rise_Processor() { return RiseProcessor; } // Note that processor speed is only calculated at start and could change during execution, so // this number is not to be relied on! - inline static int Get_Processor_Speed() { return ProcessorSpeed; } - inline static sint64 Get_Processor_Ticks_Per_Second() { return ProcessorTicksPerSecond; } // Ticks per second - inline static double Get_Inv_Processor_Ticks_Per_Second() { return InvProcessorTicksPerSecond; } // 1.0 / Ticks per second + static int Get_Processor_Speed() { return ProcessorSpeed; } + static sint64 Get_Processor_Ticks_Per_Second() { return ProcessorTicksPerSecond; } // Ticks per second + static double Get_Inv_Processor_Ticks_Per_Second() { return InvProcessorTicksPerSecond; } // 1.0 / Ticks per second static unsigned Get_Feature_Bits() { return FeatureBits; } static unsigned Get_Extended_Feature_Bits() { return ExtendedFeatureBits; } @@ -200,9 +200,9 @@ class CPUDetectClass static unsigned Get_Processor_Type() { return ProcessorType; } - inline static const char* Get_Processor_String() { return ProcessorString; } - inline static const StringClass& Get_Processor_Log() { return ProcessorLog; } - inline static const StringClass& Get_Compact_Log() { return CompactLog; } + static const char* Get_Processor_String() { return ProcessorString; } + static const StringClass& Get_Processor_Log() { return ProcessorLog; } + static const StringClass& Get_Compact_Log() { return CompactLog; } static bool CPUID( unsigned& u_eax_, diff --git a/Core/Libraries/Source/WWVegas/WWMath/sphere.h b/Core/Libraries/Source/WWVegas/WWMath/sphere.h index 1c8fc4ea97..de098d5145 100644 --- a/Core/Libraries/Source/WWVegas/WWMath/sphere.h +++ b/Core/Libraries/Source/WWVegas/WWMath/sphere.h @@ -65,9 +65,9 @@ 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); } + SphereClass(void) { }; + SphereClass(const Vector3 & center,float radius) { Init(center,radius); } + 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); diff --git a/Core/Tools/mangler/wlib/xtime.cpp b/Core/Tools/mangler/wlib/xtime.cpp index 08b05653b2..d36a7ec187 100644 --- a/Core/Tools/mangler/wlib/xtime.cpp +++ b/Core/Tools/mangler/wlib/xtime.cpp @@ -88,7 +88,7 @@ static sint32 Get_Day(int month, int day, int year) static bit8 Get_Date_From_Day(sint32 days, OUT sint32 &year, OUT sint32 &yday) { //register long int rem; - register long int y; + long int y; //register const unsigned short int *ip; if (days <= 365) diff --git a/Core/Tools/matchbot/wlib/xtime.cpp b/Core/Tools/matchbot/wlib/xtime.cpp index 08b05653b2..d36a7ec187 100644 --- a/Core/Tools/matchbot/wlib/xtime.cpp +++ b/Core/Tools/matchbot/wlib/xtime.cpp @@ -88,7 +88,7 @@ static sint32 Get_Day(int month, int day, int year) static bit8 Get_Date_From_Day(sint32 days, OUT sint32 &year, OUT sint32 &yday) { //register long int rem; - register long int y; + long int y; //register const unsigned short int *ip; if (days <= 365) diff --git a/Dependencies/Utility/Utility/endian_compat.h b/Dependencies/Utility/Utility/endian_compat.h index 97e5b31b74..08c6fdb16f 100644 --- a/Dependencies/Utility/Utility/endian_compat.h +++ b/Dependencies/Utility/Utility/endian_compat.h @@ -194,30 +194,30 @@ 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))); } }; +template struct htobeHelper { static Type swap(Type value) { return static_cast(htobe16(static_cast(value))); } }; +template struct htoleHelper { static Type swap(Type value) { return static_cast(htole16(static_cast(value))); } }; +template struct betohHelper { static Type swap(Type value) { return static_cast(be16toh(static_cast(value))); } }; +template struct letohHelper { static 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))); } }; +template struct htobeHelper { static Type swap(Type value) { return static_cast(htobe32(static_cast(value))); } }; +template struct htoleHelper { static Type swap(Type value) { return static_cast(htole32(static_cast(value))); } }; +template struct betohHelper { static Type swap(Type value) { return static_cast(be32toh(static_cast(value))); } }; +template struct letohHelper { static 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))); } }; +template struct htobeHelper { static Type swap(Type value) { return static_cast(htobe64(static_cast(value))); } }; +template struct htoleHelper { static Type swap(Type value) { return static_cast(htole64(static_cast(value))); } }; +template struct betohHelper { static Type swap(Type value) { return static_cast(be64toh(static_cast(value))); } }; +template struct letohHelper { static 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); } }; +template <> struct htobeHelper { static float swap(float value) { SwapType32 v = htobe32(*reinterpret_cast(&value)); return *reinterpret_cast(&v); } }; +template <> struct htoleHelper { static float swap(float value) { SwapType32 v = htole32(*reinterpret_cast(&value)); return *reinterpret_cast(&v); } }; +template <> struct betohHelper { static float swap(float value) { SwapType32 v = be32toh(*reinterpret_cast(&value)); return *reinterpret_cast(&v); } }; +template <> struct letohHelper { static 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); } }; +template <> struct htobeHelper { static double swap(double value) { SwapType64 v = htobe64(*reinterpret_cast(&value)); return *reinterpret_cast(&v); } }; +template <> struct htoleHelper { static double swap(double value) { SwapType64 v = htole64(*reinterpret_cast(&value)); return *reinterpret_cast(&v); } }; +template <> struct betohHelper { static double swap(double value) { SwapType64 v = be64toh(*reinterpret_cast(&value)); return *reinterpret_cast(&v); } }; +template <> struct letohHelper { static 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 diff --git a/Generals/Code/GameEngine/Include/Common/BitFlags.h b/Generals/Code/GameEngine/Include/Common/BitFlags.h index b923379633..2616939a11 100644 --- a/Generals/Code/GameEngine/Include/Common/BitFlags.h +++ b/Generals/Code/GameEngine/Include/Common/BitFlags.h @@ -63,29 +63,29 @@ class BitFlags kInit = 0 }; - inline BitFlags() + BitFlags() { } - inline BitFlags(BogusInitType k, Int idx1) + BitFlags(BogusInitType k, Int idx1) { m_bits.set(idx1); } - inline BitFlags(BogusInitType k, Int idx1, Int idx2) + BitFlags(BogusInitType k, Int idx1, Int idx2) { m_bits.set(idx1); m_bits.set(idx2); } - inline BitFlags(BogusInitType k, Int idx1, Int idx2, Int idx3) + BitFlags(BogusInitType k, Int idx1, Int idx2, Int idx3) { m_bits.set(idx1); m_bits.set(idx2); m_bits.set(idx3); } - inline BitFlags(BogusInitType k, Int idx1, Int idx2, Int idx3, Int idx4) + BitFlags(BogusInitType k, Int idx1, Int idx2, Int idx3, Int idx4) { m_bits.set(idx1); m_bits.set(idx2); @@ -93,7 +93,7 @@ class BitFlags m_bits.set(idx4); } - inline BitFlags(BogusInitType k, Int idx1, Int idx2, Int idx3, Int idx4, Int idx5) + BitFlags(BogusInitType k, Int idx1, Int idx2, Int idx3, Int idx4, Int idx5) { m_bits.set(idx1); m_bits.set(idx2); @@ -102,7 +102,7 @@ class BitFlags m_bits.set(idx5); } - inline BitFlags(BogusInitType k, + BitFlags(BogusInitType k, Int idx1, Int idx2, Int idx3, @@ -131,28 +131,28 @@ class BitFlags m_bits.set(idx12); } - inline Bool operator==(const BitFlags& that) const + Bool operator==(const BitFlags& that) const { return this->m_bits == that.m_bits; } - inline Bool operator!=(const BitFlags& that) const + Bool operator!=(const BitFlags& that) const { return this->m_bits != that.m_bits; } - inline void set(Int i, Int val = 1) + void set(Int i, Int val = 1) { m_bits.set(i, val); } - inline Bool test(Int i) const + Bool test(Int i) const { return m_bits.test(i); } //Tests for any bits that are set in both. - inline Bool testForAny( const BitFlags& that ) const + Bool testForAny( const BitFlags& that ) const { BitFlags tmp = *this; tmp.m_bits &= that.m_bits; @@ -160,7 +160,7 @@ class BitFlags } //All argument bits must be set in our bits too in order to return TRUE - inline Bool testForAll( const BitFlags& that ) const + Bool testForAll( const BitFlags& that ) const { DEBUG_ASSERTCRASH( that.any(), ("BitFlags::testForAll is always true if you ask about zero flags. Did you mean that?") ); @@ -171,46 +171,46 @@ class BitFlags } //None of the argument bits must be set in our bits in order to return TRUE - inline Bool testForNone( const BitFlags& that ) const + Bool testForNone( const BitFlags& that ) const { BitFlags tmp = *this; tmp.m_bits &= that.m_bits; return !tmp.m_bits.any(); } - inline Int size() const + Int size() const { return m_bits.size(); } - inline Int count() const + Int count() const { return m_bits.count(); } - inline Bool any() const + Bool any() const { return m_bits.any(); } - inline void flip() + void flip() { m_bits.flip(); } - inline void clear() + void clear() { m_bits.reset(); } - inline Int countIntersection(const BitFlags& that) const + Int countIntersection(const BitFlags& that) const { BitFlags tmp = *this; tmp.m_bits &= that.m_bits; return tmp.m_bits.count(); } - inline Int countInverseIntersection(const BitFlags& that) const + Int countInverseIntersection(const BitFlags& that) const { BitFlags tmp = *this; tmp.m_bits.flip(); @@ -218,7 +218,7 @@ class BitFlags return tmp.m_bits.count(); } - inline Bool anyIntersectionWith(const BitFlags& that) const + Bool anyIntersectionWith(const BitFlags& that) const { /// @todo srj -- improve me. BitFlags tmp = that; @@ -226,23 +226,23 @@ class BitFlags return tmp.m_bits.any(); } - inline void clear(const BitFlags& clr) + void clear(const BitFlags& clr) { m_bits &= ~clr.m_bits; } - inline void set(const BitFlags& set) + void set(const BitFlags& set) { m_bits |= set.m_bits; } - inline void clearAndSet(const BitFlags& clr, const BitFlags& set) + void clearAndSet(const BitFlags& clr, const BitFlags& set) { m_bits &= ~clr.m_bits; m_bits |= set.m_bits; } - inline Bool testSetAndClear(const BitFlags& mustBeSet, const BitFlags& mustBeClear) const + Bool testSetAndClear(const BitFlags& mustBeSet, const BitFlags& mustBeClear) const { /// @todo srj -- improve me. BitFlags tmp = *this; diff --git a/Generals/Code/GameEngine/Include/Common/BuildAssistant.h b/Generals/Code/GameEngine/Include/Common/BuildAssistant.h index 40573cae97..84a2d20678 100644 --- a/Generals/Code/GameEngine/Include/Common/BuildAssistant.h +++ b/Generals/Code/GameEngine/Include/Common/BuildAssistant.h @@ -171,7 +171,7 @@ class BuildAssistant : public SubsystemInterface Object *builderObject ); /// return the "scratch pad" array that can be used to create a line of build locations - virtual inline Coord3D *getBuildLocations( void ) { return m_buildPositions; } + virtual Coord3D *getBuildLocations( void ) { return m_buildPositions; } /// is the template a line build object, like a wall virtual Bool isLineBuildTemplate( const ThingTemplate *tTemplate ); diff --git a/Generals/Code/GameEngine/Include/Common/Dict.h b/Generals/Code/GameEngine/Include/Common/Dict.h index 80f26dc7b7..424fa3ae6b 100644 --- a/Generals/Code/GameEngine/Include/Common/Dict.h +++ b/Generals/Code/GameEngine/Include/Common/Dict.h @@ -125,7 +125,7 @@ class Dict /** Return there is a pair with the given key and datatype, return true. */ - inline Bool known(NameKeyType key, DataType d) const + Bool known(NameKeyType key, DataType d) const { return getType(key) == d; } @@ -278,17 +278,17 @@ class Dict DictPairKeyType m_key; void* m_value; - inline static DictPairKeyType createKey(NameKeyType keyVal, DataType nt) + static DictPairKeyType createKey(NameKeyType keyVal, DataType nt) { return (DictPairKeyType)((((UnsignedInt)(keyVal)) << 8) | ((UnsignedInt)nt)); } - inline static DataType getTypeFromKey(DictPairKeyType nk) + static DataType getTypeFromKey(DictPairKeyType nk) { return (DataType)(((UnsignedInt)nk) & 0xff); } - inline static NameKeyType getNameFromKey(DictPairKeyType nk) + static NameKeyType getNameFromKey(DictPairKeyType nk) { return (NameKeyType)(((UnsignedInt)nk) >> 8); } @@ -298,13 +298,13 @@ class Dict void clear(); void copyFrom(DictPair* that); void setNameAndType(NameKeyType key, DataType type); - inline DataType getType() const { return getTypeFromKey(m_key); } - inline NameKeyType getName() const { return getNameFromKey(m_key); } - inline Bool* asBool() { return (Bool*)&m_value; } - inline Int* asInt() { return (Int*)&m_value; } - inline Real* asReal() { return (Real*)&m_value; } - inline AsciiString* asAsciiString() { return (AsciiString*)&m_value; } - inline UnicodeString* asUnicodeString() { return (UnicodeString*)&m_value; } + DataType getType() const { return getTypeFromKey(m_key); } + NameKeyType getName() const { return getNameFromKey(m_key); } + Bool* asBool() { return (Bool*)&m_value; } + Int* asInt() { return (Int*)&m_value; } + Real* asReal() { return (Real*)&m_value; } + AsciiString* asAsciiString() { return (AsciiString*)&m_value; } + UnicodeString* asUnicodeString() { return (UnicodeString*)&m_value; } }; struct DictPairData @@ -314,13 +314,13 @@ class Dict unsigned short m_numPairsUsed; // length of data allocated //DictPair m_pairs[]; - inline DictPair* peek() { return (DictPair*)(this+1); } + DictPair* peek() { return (DictPair*)(this+1); } }; #ifdef RTS_DEBUG void validate() const; #else - inline void validate() const { } + void validate() const { } #endif }; diff --git a/Generals/Code/GameEngine/Include/Common/Geometry.h b/Generals/Code/GameEngine/Include/Common/Geometry.h index 029c854ca0..35930f6fa1 100644 --- a/Generals/Code/GameEngine/Include/Common/Geometry.h +++ b/Generals/Code/GameEngine/Include/Common/Geometry.h @@ -119,30 +119,30 @@ class GeometryInfo : public Snapshot void set(GeometryType type, Bool isSmall, Real height, Real majorRadius, Real minorRadius); // bleah, icky but needed for legacy code - inline void setMajorRadius(Real majorRadius) + void setMajorRadius(Real majorRadius) { m_majorRadius = majorRadius; calcBoundingStuff(); } // bleah, icky but needed for legacy code - inline void setMinorRadius(Real minorRadius) + void setMinorRadius(Real minorRadius) { m_minorRadius = minorRadius; calcBoundingStuff(); } - inline GeometryType getGeomType() const { return m_type; } - inline Bool getIsSmall() const { return m_isSmall; } - inline Real getMajorRadius() const { return m_majorRadius; } // x-axis - inline Real getMinorRadius() const { return m_minorRadius; } // y-axis + GeometryType getGeomType() const { return m_type; } + Bool getIsSmall() const { return m_isSmall; } + Real getMajorRadius() const { return m_majorRadius; } // x-axis + Real getMinorRadius() const { return m_minorRadius; } // y-axis // this has been removed and should never need to be called... // you should generally call getMaxHeightAbovePosition() instead. (srj) //inline Real getGeomHeight() const { return m_height; } // z-axis - inline Real getBoundingCircleRadius() const { return m_boundingCircleRadius; } - inline Real getBoundingSphereRadius() const { return m_boundingSphereRadius; } + Real getBoundingCircleRadius() const { return m_boundingCircleRadius; } + Real getBoundingSphereRadius() const { return m_boundingSphereRadius; } Bool isIntersectedByLineSegment(const Coord3D& loc, const Coord3D& from, const Coord3D& to) const; diff --git a/Generals/Code/GameEngine/Include/Common/INI.h b/Generals/Code/GameEngine/Include/Common/INI.h index 0e5c0e4f8e..869b4d1c20 100644 --- a/Generals/Code/GameEngine/Include/Common/INI.h +++ b/Generals/Code/GameEngine/Include/Common/INI.h @@ -116,7 +116,7 @@ struct FieldParse const void* userData; ///< field-specific data Int offset; ///< offset to data field - inline void set(const char* t, INIFieldParseProc p, const void* u, Int o) + void set(const char* t, INIFieldParseProc p, const void* u, Int o) { token = t; parse = p; @@ -144,9 +144,9 @@ class MultiIniFieldParse void add(const FieldParse* f, UnsignedInt e = 0); - inline Int getCount() const { return m_count; } - inline const FieldParse* getNthFieldParse(Int i) const { return m_fieldParse[i]; } - inline UnsignedInt getNthExtraOffset(Int i) const { return m_extraOffset[i]; } + Int getCount() const { return m_count; } + const FieldParse* getNthFieldParse(Int i) const { return m_fieldParse[i]; } + UnsignedInt getNthExtraOffset(Int i) const { return m_extraOffset[i]; } }; //------------------------------------------------------------------------------------------------- @@ -244,14 +244,14 @@ class INI static void parseWindowTransitions( INI* ini ); - inline AsciiString getFilename( void ) const { return m_filename; } - inline INILoadType getLoadType( void ) const { return m_loadType; } - inline UnsignedInt getLineNum( void ) const { return m_lineNum; } - inline const char *getSeps( void ) const { return m_seps; } - inline const char *getSepsPercent( void ) const { return m_sepsPercent; } - inline const char *getSepsColon( void ) const { return m_sepsColon; } - inline const char *getSepsQuote( void ) { return m_sepsQuote; } - inline Bool isEOF( void ) const { return m_endOfFile; } + AsciiString getFilename( void ) const { return m_filename; } + INILoadType getLoadType( void ) const { return m_loadType; } + UnsignedInt getLineNum( void ) const { return m_lineNum; } + const char *getSeps( void ) const { return m_seps; } + const char *getSepsPercent( void ) const { return m_sepsPercent; } + const char *getSepsColon( void ) const { return m_sepsColon; } + const char *getSepsQuote( void ) { return m_sepsQuote; } + Bool isEOF( void ) const { return m_endOfFile; } void initFromINI( void *what, const FieldParse* parseTable ); void initFromINIMulti( void *what, const MultiIniFieldParse& parseTableList ); diff --git a/Generals/Code/GameEngine/Include/Common/Module.h b/Generals/Code/GameEngine/Include/Common/Module.h index 78a26efb02..adc0e98e27 100644 --- a/Generals/Code/GameEngine/Include/Common/Module.h +++ b/Generals/Code/GameEngine/Include/Common/Module.h @@ -189,7 +189,7 @@ class Module : public MemoryPoolObject, virtual NameKeyType getModuleNameKey() const = 0; - inline NameKeyType getModuleTagNameKey() const { return getModuleData()->getModuleTagNameKey(); } + NameKeyType getModuleTagNameKey() const { return getModuleData()->getModuleTagNameKey(); } /** this is called after all the Modules for a given Thing are created; it allows Modules to resolve any inter-Module dependencies. @@ -211,7 +211,7 @@ class Module : public MemoryPoolObject, protected: - inline const ModuleData* getModuleData() const { return m_moduleData; } + const ModuleData* getModuleData() const { return m_moduleData; } virtual void crc( Xfer *xfer ); virtual void xfer( Xfer *xfer ); @@ -248,8 +248,8 @@ class ObjectModule : public Module protected: - inline Object *getObject() { return m_object; } - inline const Object *getObject() const { return m_object; } + Object *getObject() { return m_object; } + const Object *getObject() const { return m_object; } virtual void crc( Xfer *xfer ); virtual void xfer( Xfer *xfer ); @@ -291,8 +291,8 @@ class DrawableModule : public Module protected: - inline Drawable *getDrawable() { return m_drawable; } - inline const Drawable *getDrawable() const { return m_drawable; } + Drawable *getDrawable() { return m_drawable; } + const Drawable *getDrawable() const { return m_drawable; } virtual void crc( Xfer *xfer ); virtual void xfer( Xfer *xfer ); diff --git a/Generals/Code/GameEngine/Include/Common/Money.h b/Generals/Code/GameEngine/Include/Common/Money.h index a93eed08b0..2c4bbe3c6a 100644 --- a/Generals/Code/GameEngine/Include/Common/Money.h +++ b/Generals/Code/GameEngine/Include/Common/Money.h @@ -61,7 +61,7 @@ class Money : public Snapshot public: - inline Money() : m_playerIndex(0) + Money() : m_playerIndex(0) { init(); } @@ -71,7 +71,7 @@ class Money : public Snapshot setStartingCash(0); } - inline UnsignedInt countMoney() const + UnsignedInt countMoney() const { return m_money; } diff --git a/Generals/Code/GameEngine/Include/Common/MultiplayerSettings.h b/Generals/Code/GameEngine/Include/Common/MultiplayerSettings.h index af79c5dca7..4ea47f91b6 100644 --- a/Generals/Code/GameEngine/Include/Common/MultiplayerSettings.h +++ b/Generals/Code/GameEngine/Include/Common/MultiplayerSettings.h @@ -46,11 +46,11 @@ class MultiplayerColorDefinition static const FieldParse m_colorFieldParseTable[]; ///< the parse table for INI definition const FieldParse *getFieldParse( void ) const { return m_colorFieldParseTable; } - inline AsciiString getTooltipName(void) const { return m_tooltipName; }; - inline RGBColor getRGBValue(void) const { return m_rgbValue; }; - inline RGBColor getRGBNightValue(void) const { return m_rgbValueNight; }; - inline Color getColor(void) const { return m_color; } - inline Color getNightColor(void) const { return m_colorNight; } + AsciiString getTooltipName(void) const { return m_tooltipName; }; + RGBColor getRGBValue(void) const { return m_rgbValue; }; + RGBColor getRGBNightValue(void) const { return m_rgbValueNight; }; + Color getColor(void) const { return m_color; } + Color getNightColor(void) const { return m_colorNight; } void setColor( RGBColor rgb ); void setNightColor( RGBColor rgb ); @@ -92,14 +92,14 @@ class MultiplayerSettings : public SubsystemInterface MultiplayerColorDefinition * findMultiplayerColorDefinitionByName(AsciiString name); MultiplayerColorDefinition * newMultiplayerColorDefinition(AsciiString name); - inline Int getStartCountdownTimerSeconds( void ) { return m_startCountdownTimerSeconds; } - inline Int getMaxBeaconsPerPlayer( void ) { return m_maxBeaconsPerPlayer; } - inline Bool isShroudInMultiplayer( void ) { return m_isShroudInMultiplayer; } - inline Bool showRandomPlayerTemplate( void ) { return m_showRandomPlayerTemplate; } - inline Bool showRandomStartPos( void ) { return m_showRandomStartPos; } - inline Bool showRandomColor( void ) { return m_showRandomColor; } + Int getStartCountdownTimerSeconds( void ) { return m_startCountdownTimerSeconds; } + Int getMaxBeaconsPerPlayer( void ) { return m_maxBeaconsPerPlayer; } + Bool isShroudInMultiplayer( void ) { return m_isShroudInMultiplayer; } + Bool showRandomPlayerTemplate( void ) { return m_showRandomPlayerTemplate; } + Bool showRandomStartPos( void ) { return m_showRandomStartPos; } + Bool showRandomColor( void ) { return m_showRandomColor; } - inline Int getNumColors( void ) + Int getNumColors( void ) { if (m_numColors == 0) { m_numColors = m_colorList.size(); diff --git a/Generals/Code/GameEngine/Include/Common/NameKeyGenerator.h b/Generals/Code/GameEngine/Include/Common/NameKeyGenerator.h index 01d237638d..5c15847900 100644 --- a/Generals/Code/GameEngine/Include/Common/NameKeyGenerator.h +++ b/Generals/Code/GameEngine/Include/Common/NameKeyGenerator.h @@ -155,5 +155,5 @@ class StaticNameKey StaticNameKey(const char* p) : m_key(NAMEKEY_INVALID), m_name(p) {} NameKeyType key() const; // ugh, this is a little hokey, but lets us pretend that a StaticNameKey == NameKeyType - inline operator NameKeyType() const { return key(); } + operator NameKeyType() const { return key(); } }; diff --git a/Generals/Code/GameEngine/Include/Common/Player.h b/Generals/Code/GameEngine/Include/Common/Player.h index 86edd8a300..ddf3e3006b 100644 --- a/Generals/Code/GameEngine/Include/Common/Player.h +++ b/Generals/Code/GameEngine/Include/Common/Player.h @@ -219,42 +219,42 @@ class Player : public Snapshot void deletePlayerAI(); - inline UnicodeString getPlayerDisplayName() { return m_playerDisplayName; } - inline NameKeyType getPlayerNameKey() const { return m_playerNameKey; } + UnicodeString getPlayerDisplayName() { return m_playerDisplayName; } + NameKeyType getPlayerNameKey() const { return m_playerNameKey; } - inline AsciiString getSide() const { return m_side; } + AsciiString getSide() const { return m_side; } - inline const PlayerTemplate* getPlayerTemplate() const { return m_playerTemplate; } + const PlayerTemplate* getPlayerTemplate() const { return m_playerTemplate; } /// return the Player's Handicap sub-object - inline const Handicap *getHandicap() const { return &m_handicap; } - inline Handicap *getHandicap() { return &m_handicap; } + const Handicap *getHandicap() const { return &m_handicap; } + Handicap *getHandicap() { return &m_handicap; } /// return the Player's Money sub-object - inline Money *getMoney() { return &m_money; } - inline const Money *getMoney() const { return &m_money; } + Money *getMoney() { return &m_money; } + const Money *getMoney() const { return &m_money; } UnsignedInt getSupplyBoxValue();///< Many things can affect the alue of a crate, but at heart it is a GlobalData ratio. - inline Energy *getEnergy() { return &m_energy; } - inline const Energy *getEnergy() const { return &m_energy; } + Energy *getEnergy() { return &m_energy; } + const Energy *getEnergy() const { return &m_energy; } // adds a power bonus to this player because of energy upgrade at his power plants - inline void addPowerBonus(Object *obj) { m_energy.addPowerBonus(obj); } - inline void removePowerBonus(Object *obj) { m_energy.removePowerBonus(obj); } + void addPowerBonus(Object *obj) { m_energy.addPowerBonus(obj); } + void removePowerBonus(Object *obj) { m_energy.removePowerBonus(obj); } - inline ResourceGatheringManager *getResourceGatheringManager(){ return m_resourceGatheringManager; } - inline TunnelTracker* getTunnelSystem(){ return m_tunnelSystem; } + ResourceGatheringManager *getResourceGatheringManager(){ return m_resourceGatheringManager; } + TunnelTracker* getTunnelSystem(){ return m_tunnelSystem; } - inline Color getPlayerColor() const { return m_color; } - inline Color getPlayerNightColor() const { return m_nightColor;} + Color getPlayerColor() const { return m_color; } + Color getPlayerNightColor() const { return m_nightColor;} /// return the type of controller - inline PlayerType getPlayerType() const { return m_playerType; } + PlayerType getPlayerType() const { return m_playerType; } void setPlayerType(PlayerType t, Bool skirmish); - inline PlayerIndex getPlayerIndex() const { return m_playerIndex; } + PlayerIndex getPlayerIndex() const { return m_playerIndex; } /// return a bitmask that is unique to this player. - inline PlayerMaskType getPlayerMask() const { return 1 << m_playerIndex; } + PlayerMaskType getPlayerMask() const { return 1 << m_playerIndex; } /// a convenience function to test the ThingTemplate against the players canBuild flags /// called by canBuild @@ -528,9 +528,9 @@ class Player : public Snapshot void removeTeamFromList(TeamPrototype* team); typedef std::list PlayerTeamList; - inline const PlayerTeamList* getPlayerTeams() const { return &m_playerTeamPrototypes; } + const PlayerTeamList* getPlayerTeams() const { return &m_playerTeamPrototypes; } - inline Int getMpStartIndex(void) {return m_mpStartIndex;} + Int getMpStartIndex(void) {return m_mpStartIndex;} /// Set that all units should begin hunting. void setUnitsShouldHunt(Bool unitsShouldHunt, CommandSourceType source); diff --git a/Generals/Code/GameEngine/Include/Common/PlayerTemplate.h b/Generals/Code/GameEngine/Include/Common/PlayerTemplate.h index a1bbe03929..1caf422167 100644 --- a/Generals/Code/GameEngine/Include/Common/PlayerTemplate.h +++ b/Generals/Code/GameEngine/Include/Common/PlayerTemplate.h @@ -74,35 +74,35 @@ class PlayerTemplate PlayerTemplate(); - inline void setNameKey(NameKeyType namekey) { m_nameKey = namekey; } + void setNameKey(NameKeyType namekey) { m_nameKey = namekey; } - inline NameKeyType getNameKey() const { DEBUG_ASSERTCRASH(m_nameKey != NAMEKEY_INVALID, ("bad namekey")); return m_nameKey; } - inline AsciiString getName() const { return KEYNAME(m_nameKey); } + NameKeyType getNameKey() const { DEBUG_ASSERTCRASH(m_nameKey != NAMEKEY_INVALID, ("bad namekey")); return m_nameKey; } + AsciiString getName() const { return KEYNAME(m_nameKey); } - inline UnicodeString getDisplayName() const { return m_displayName; } + UnicodeString getDisplayName() const { return m_displayName; } - inline AsciiString getSide() const { return m_side; } + AsciiString getSide() const { return m_side; } /// return the tech tree for the player. - inline const Handicap *getHandicap() const { return &m_handicap; } + const Handicap *getHandicap() const { return &m_handicap; } /// return the money for the player. - inline const Money *getMoney() const { return &m_money; } + const Money *getMoney() const { return &m_money; } - inline const RGBColor* getPreferredColor() const { return &m_preferredColor; } + const RGBColor* getPreferredColor() const { return &m_preferredColor; } - inline AsciiString getStartingBuilding( void ) const { return m_startingBuilding; } + AsciiString getStartingBuilding( void ) const { return m_startingBuilding; } AsciiString getStartingUnit( Int i ) const; - inline const ProductionChangeMap& getProductionCostChanges() const { return m_productionCostChanges; } - inline const ProductionChangeMap& getProductionTimeChanges() const { return m_productionTimeChanges; } - inline const ProductionVeterancyMap& getProductionVeterancyLevels() const { return m_productionVeterancyLevels; } - inline Bool isObserver() const { return m_observer; } - inline Bool isPlayableSide() const { return m_playableSide; } + const ProductionChangeMap& getProductionCostChanges() const { return m_productionCostChanges; } + const ProductionChangeMap& getProductionTimeChanges() const { return m_productionTimeChanges; } + const ProductionVeterancyMap& getProductionVeterancyLevels() const { return m_productionVeterancyLevels; } + Bool isObserver() const { return m_observer; } + Bool isPlayableSide() const { return m_playableSide; } - inline AsciiString getScoreScreen (void ) const { return m_scoreScreenImage; } - inline AsciiString getLoadScreen (void ) const { return m_loadScreenImage; } - inline AsciiString getBeaconTemplate( void ) const { return m_beaconTemplate; } + AsciiString getScoreScreen (void ) const { return m_scoreScreenImage; } + AsciiString getLoadScreen (void ) const { return m_loadScreenImage; } + AsciiString getBeaconTemplate( void ) const { return m_beaconTemplate; } const Image *getHeadWaterMarkImage( void ) const; const Image *getFlagWaterMarkImage( void ) const; @@ -111,7 +111,7 @@ class PlayerTemplate //const Image *getHiliteImage( void ) const; //const Image *getPushedImage( void ) const; const Image *getSideIconImage( void ) const; - inline const AsciiString getTooltip() const { return m_tooltip; } + const AsciiString getTooltip() const { return m_tooltip; } const ScienceVec& getIntrinsicSciences() const { return m_intrinsicSciences; } Int getIntrinsicSciencePurchasePoints() const { return m_intrinsicSPP; } @@ -198,7 +198,7 @@ class PlayerTemplateStore : public SubsystemInterface const PlayerTemplate* getNthPlayerTemplate(Int i) const; const PlayerTemplate* findPlayerTemplate(NameKeyType namekey) const; - inline Int getPlayerTemplateCount() const { return m_playerTemplates.size(); } + Int getPlayerTemplateCount() const { return m_playerTemplates.size(); } // This function will fill outStringList with all the sides found in all the templates diff --git a/Generals/Code/GameEngine/Include/Common/SparseMatchFinder.h b/Generals/Code/GameEngine/Include/Common/SparseMatchFinder.h index 8d983f3a84..38e3bbed4d 100644 --- a/Generals/Code/GameEngine/Include/Common/SparseMatchFinder.h +++ b/Generals/Code/GameEngine/Include/Common/SparseMatchFinder.h @@ -109,13 +109,13 @@ class SparseMatchFinder //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- - inline static Int countConditionIntersection(const BITSET& a, const BITSET& b) + static Int countConditionIntersection(const BITSET& a, const BITSET& b) { return a.countIntersection(b); } //------------------------------------------------------------------------------------------------- - inline static Int countConditionInverseIntersection(const BITSET& a, const BITSET& b) + static Int countConditionInverseIntersection(const BITSET& a, const BITSET& b) { return a.countInverseIntersection(b); } diff --git a/Generals/Code/GameEngine/Include/Common/StateMachine.h b/Generals/Code/GameEngine/Include/Common/StateMachine.h index d60ba6dc02..964612308b 100644 --- a/Generals/Code/GameEngine/Include/Common/StateMachine.h +++ b/Generals/Code/GameEngine/Include/Common/StateMachine.h @@ -152,8 +152,8 @@ class State : public MemoryPoolObject, public Snapshot //Definition of busy -- when explicitly in the busy state. Moving or attacking is not considered busy! virtual Bool isBusy() const { return false; } - inline StateMachine* getMachine() { return m_machine; } ///< return the machine this state is part of - inline StateID getID() const { return m_ID; } ///< get this state's id + StateMachine* getMachine() { return m_machine; } ///< return the machine this state is part of + StateID getID() const { return m_ID; } ///< get this state's id Object* getMachineOwner(); const Object* getMachineOwner() const; @@ -167,7 +167,7 @@ class State : public MemoryPoolObject, public Snapshot #endif // for internal use by the StateMachine class --------------------------------------------------------- - inline void friend_setID( StateID id ) { m_ID = id; } ///< define this state's id (for use only by StateMachine class) + void friend_setID( StateID id ) { m_ID = id; } ///< define this state's id (for use only by StateMachine class) void friend_onSuccess( StateID toStateID ) { m_successStateID = toStateID; } ///< define which state to move to after successful completion void friend_onFailure( StateID toStateID ) { m_failureStateID = toStateID; } ///< define which state to move to after failure void friend_onCondition( StateTransFuncPtr test, StateID toStateID, void* userData, const char* description = NULL ); ///< define when to change state @@ -328,8 +328,8 @@ class StateMachine : public MemoryPoolObject, public Snapshot inline AsciiString getName() const {return m_name;} virtual AsciiString getCurrentStateName() const { return m_currentState ? m_currentState->getName() : AsciiString::TheEmptyString;} #else - inline Bool getWantsDebugOutput() const { return false; } - inline AsciiString getCurrentStateName() const { return AsciiString::TheEmptyString;} + Bool getWantsDebugOutput() const { return false; } + AsciiString getCurrentStateName() const { return AsciiString::TheEmptyString;} #endif protected: diff --git a/Generals/Code/GameEngine/Include/Common/SubsystemInterface.h b/Generals/Code/GameEngine/Include/Common/SubsystemInterface.h index 56b67014a3..740accba46 100644 --- a/Generals/Code/GameEngine/Include/Common/SubsystemInterface.h +++ b/Generals/Code/GameEngine/Include/Common/SubsystemInterface.h @@ -124,8 +124,8 @@ class SubsystemInterface Real m_startDrawTimeConsumed; Real m_curDrawTime; #else - inline void UPDATE(void) {update();} - inline void DRAW(void) {draw();} + void UPDATE(void) {update();} + void DRAW(void) {draw();} #endif protected: AsciiString m_name; diff --git a/Generals/Code/GameEngine/Include/Common/Team.h b/Generals/Code/GameEngine/Include/Common/Team.h index 1f3bd75793..d510d1cc5c 100644 --- a/Generals/Code/GameEngine/Include/Common/Team.h +++ b/Generals/Code/GameEngine/Include/Common/Team.h @@ -525,10 +525,10 @@ class TeamPrototype : public MemoryPoolObject, TeamPrototypeID id ); // virtual destructor prototype provided by memory pool object - inline TeamPrototypeID getID() const { return m_id; } - inline const AsciiString& getName() const { return m_name; } - inline Bool getIsSingleton() const { return (m_flags & TEAM_SINGLETON) != 0; } - inline const TeamTemplateInfo *getTemplateInfo(void) const {return &m_teamTemplate;} + TeamPrototypeID getID() const { return m_id; } + const AsciiString& getName() const { return m_name; } + Bool getIsSingleton() const { return (m_flags & TEAM_SINGLETON) != 0; } + const TeamTemplateInfo *getTemplateInfo(void) const {return &m_teamTemplate;} /** return the team's owner (backtracking up if necessary) */ diff --git a/Generals/Code/GameEngine/Include/Common/TerrainTypes.h b/Generals/Code/GameEngine/Include/Common/TerrainTypes.h index 012393a484..b0b2e2013e 100644 --- a/Generals/Code/GameEngine/Include/Common/TerrainTypes.h +++ b/Generals/Code/GameEngine/Include/Common/TerrainTypes.h @@ -118,40 +118,40 @@ class TerrainType : public MemoryPoolObject // destructor prototype defined by memory pool glue /// get the name for this terrain - inline AsciiString getName( void ) { return m_name; } + AsciiString getName( void ) { return m_name; } /// get whether this terrain is blend edge terrain. - inline Bool isBlendEdge( void ) { return m_blendEdgeTexture; } + Bool isBlendEdge( void ) { return m_blendEdgeTexture; } /// get the type of this terrain - inline TerrainClass getClass( void ) { return m_class; } + TerrainClass getClass( void ) { return m_class; } /// get the construction restrictions - inline Bool getRestrictConstruction( void ) { return m_restrictConstruction; } + Bool getRestrictConstruction( void ) { return m_restrictConstruction; } /// get the texture file for this terrain - inline AsciiString getTexture( void ) { return m_texture; } + AsciiString getTexture( void ) { return m_texture; } /// get next terrain in list, only for use by the terrain collection - inline TerrainType *friend_getNext( void ) { return m_next; } + TerrainType *friend_getNext( void ) { return m_next; } /// set the name for this terrain, for use by terrain collection only - inline void friend_setName( AsciiString name ) { m_name = name; } + void friend_setName( AsciiString name ) { m_name = name; } /// set the next pointer for the terrain list, for use by terrain collection only - inline void friend_setNext( TerrainType *next ) { m_next = next; } + void friend_setNext( TerrainType *next ) { m_next = next; } /// set the texture, for use by terrain collection only - inline void friend_setTexture( AsciiString texture ) { m_texture = texture; } + void friend_setTexture( AsciiString texture ) { m_texture = texture; } /// set the class, for use by terrain collection only - inline void friend_setClass( TerrainClass terrainClass ) { m_class = terrainClass; } + void friend_setClass( TerrainClass terrainClass ) { m_class = terrainClass; } /// set the restrict construction flag, for use by terrain collection only - inline void friend_setRestrictConstruction( Bool restrict ) { m_restrictConstruction = restrict; } + void friend_setRestrictConstruction( Bool restrict ) { m_restrictConstruction = restrict; } /// set whether this terrain is blend edge terrain, for use by terrain collection only - inline void friend_setBlendEdge( Bool isBlend ) { m_blendEdgeTexture = isBlend; } + void friend_setBlendEdge( Bool isBlend ) { m_blendEdgeTexture = isBlend; } /// get the parsing table for INI const FieldParse *getFieldParse( void ) { return m_terrainTypeFieldParseTable; } diff --git a/Generals/Code/GameEngine/Include/Common/ThingTemplate.h b/Generals/Code/GameEngine/Include/Common/ThingTemplate.h index 1e0eb5617d..f01dc7038e 100644 --- a/Generals/Code/GameEngine/Include/Common/ThingTemplate.h +++ b/Generals/Code/GameEngine/Include/Common/ThingTemplate.h @@ -398,18 +398,18 @@ class ThingTemplate : public Overridable EditorSortingType getEditorSorting() const { return (EditorSortingType)m_editorSorting; } /// return true iff the template has the specified kindOf flag set. - inline Bool isKindOf(KindOfType t) const + 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 + Bool isKindOfMulti(const KindOfMaskType& mustBeSet, const KindOfMaskType& mustBeClear) const { return TEST_KINDOFMASK_MULTI(m_kindof, mustBeSet, mustBeClear); } - inline Bool isAnyKindOf( const KindOfMaskType& anyKindOf ) const + Bool isAnyKindOf( const KindOfMaskType& anyKindOf ) const { return TEST_KINDOFMASK_ANY(m_kindof, anyKindOf); } @@ -534,10 +534,10 @@ class ThingTemplate : public Overridable // 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; } + void friend_setTemplateName( const AsciiString& name ) { m_nameString = name; } + ThingTemplate *friend_getNextTemplate() const { return m_nextThingTemplate; } + void friend_setNextTemplate(ThingTemplate *tmplate) { m_nextThingTemplate = tmplate; } + void friend_setTemplateID(UnsignedShort id) { m_templateID = id; } Int getEnergyProduction() const { return m_energyProduction; } Int getEnergyBonus() const { return m_energyBonus; } diff --git a/Generals/Code/GameEngine/Include/GameClient/Drawable.h b/Generals/Code/GameEngine/Include/GameClient/Drawable.h index f189f56c96..8d4c158d7c 100644 --- a/Generals/Code/GameEngine/Include/GameClient/Drawable.h +++ b/Generals/Code/GameEngine/Include/GameClient/Drawable.h @@ -315,17 +315,17 @@ class Drawable : public Thing, void setTerrainDecalSize(Real x, Real y); void setTerrainDecalFadeTarget(Real target, Real rate = 0.1f); - inline Object *getObject( void ) { return m_object; } ///< return object ID bound to this drawble - inline const Object *getObject( void ) const { return m_object; } ///< return object ID bound to this drawble + Object *getObject( void ) { return m_object; } ///< return object ID bound to this drawble + const Object *getObject( void ) const { return m_object; } ///< return object ID bound to this drawble - inline DrawableInfo *getDrawableInfo(void) {return &m_drawableInfo;} + DrawableInfo *getDrawableInfo(void) {return &m_drawableInfo;} void setDrawableHidden( Bool hidden ); ///< hide or unhide drawable // // note that this is not necessarily the 'get' reflection of setDrawableHidden, since drawables // can spontaneously hide via stealth. (srj) // - inline Bool isDrawableEffectivelyHidden() const { return m_hidden || m_hiddenByStealth; } + Bool isDrawableEffectivelyHidden() const { return m_hidden || m_hiddenByStealth; } void setSelectable( Bool selectable ); ///< Changes the drawables selectability Bool isSelectable( void ) const; @@ -364,7 +364,7 @@ class Drawable : public Thing, //--------------------------------------------------------------------------- void setDrawableStatus( DrawableStatus bit ) { BitSet( m_status, bit ); } void clearDrawableStatus( DrawableStatus bit ) { BitClear( m_status, bit ); } - inline Bool testDrawableStatus( DrawableStatus bit ) const { return (m_status & bit) != 0; } + Bool testDrawableStatus( DrawableStatus bit ) const { return (m_status & bit) != 0; } void setShroudClearFrame( UnsignedInt frame ) { m_shroudClearFrame = frame; } UnsignedInt getShroudClearFrame( void ) { return m_shroudClearFrame; } @@ -376,7 +376,7 @@ class Drawable : public Thing, void allocateShadows(void); ///< create shadow resources if not already present. Used by Options screen. void setFullyObscuredByShroud(Bool fullyObscured); - inline Bool getFullyObscuredByShroud(void) {return m_drawableFullyObscuredByShroud;} + Bool getFullyObscuredByShroud(void) {return m_drawableFullyObscuredByShroud;} Bool getDrawsInMirror() const { return BitIsSet(m_status, DRAWABLE_STATUS_DRAWS_IN_MIRROR) || isKindOf(KINDOF_CAN_CAST_REFLECTIONS); } @@ -395,9 +395,9 @@ class Drawable : public Thing, // an "instance" matrix defines the local transform of the Drawable, and is concatenated with the global transform void setInstanceMatrix( const Matrix3D *instance ); ///< set the Drawable's instance transform const Matrix3D *getInstanceMatrix( void ) const { return &m_instance; } ///< get drawable instance transform - inline Bool isInstanceIdentity() const { return m_instanceIsIdentity; } + Bool isInstanceIdentity() const { return m_instanceIsIdentity; } - inline Real getInstanceScale( void ) const { return m_instanceScale; } ///< get scale that will be applied to instance matrix + Real getInstanceScale( void ) const { return m_instanceScale; } ///< get scale that will be applied to instance matrix void setInstanceScale(Real value) { m_instanceScale = value;} ///< set scale that will be applied to instance matrix before rendering. const Matrix3D *getTransformMatrix( void ) const; ///< return the world transform @@ -416,7 +416,7 @@ class Drawable : public Thing, void removeFromList(Drawable **pListHead); void setID( DrawableID id ); ///< set this drawable's unique ID - inline const ModelConditionFlags& getModelConditionFlags( void ) const { return m_conditionState; } + const ModelConditionFlags& getModelConditionFlags( void ) const { return m_conditionState; } // // NOTE: avoid repeated calls to the set and clear for the condition state as they @@ -516,16 +516,16 @@ class Drawable : public Thing, const Vector3 * getTintColor( void ) const; ///< get FX color value to add to ALL LIGHTS when drawing const Vector3 * getSelectionColor( void ) const; ///< get FX color value to add to ALL LIGHTS when drawing - inline TerrainDecalType getTerrainDecalType( void ) const { return m_terrainDecalType; } + TerrainDecalType getTerrainDecalType( void ) const { return m_terrainDecalType; } - inline void setDrawableOpacity( Real value ) { m_explicitOpacity = value; } ///< set alpha/opacity value used to override defaults when drawing. + void setDrawableOpacity( Real value ) { m_explicitOpacity = value; } ///< set alpha/opacity value used to override defaults when drawing. // note that this is not the 'get' inverse of setDrawableOpacity, since stealthing can also affect the effective opacity! - inline Real getEffectiveOpacity() const { return m_explicitOpacity * m_effectiveStealthOpacity; } ///< get alpha/opacity value used to override defaults when drawing. + Real getEffectiveOpacity() const { return m_explicitOpacity * m_effectiveStealthOpacity; } ///< get alpha/opacity value used to override defaults when drawing. void setEffectiveOpacity( Real pulseFactor, Real explicitOpacity = -1.0f ); // this is for the heatvision effect which operates completely independently of the stealth opacity effects. Draw() does the fading every frame. - inline Real getHeatVisionOpacity() const { return m_heatVisionOpacity; } ///< get alpha/opacity value used to render add'l heatvision rendering pass. + Real getHeatVisionOpacity() const { return m_heatVisionOpacity; } ///< get alpha/opacity value used to render add'l heatvision rendering pass. void setHeatVisionOpacity( Real op ) { m_heatVisionOpacity = op; }; ///< set alpha/opacity value used to render add'l heatvision rendering pass. // both of these assume that you are starting at one extreme 100% or 0% opacity and are trying to go to the other!! -- amit @@ -571,13 +571,13 @@ class Drawable : public Thing, Drawable *asDrawableMeth() { return this; } const Drawable *asDrawableMeth() const { return this; } - inline Module** getModuleList(ModuleType i) + Module** getModuleList(ModuleType i) { Module** m = m_modules[i - FIRST_DRAWABLE_MODULE_TYPE]; return m; } - inline Module* const* getModuleList(ModuleType i) const + Module* const* getModuleList(ModuleType i) const { Module** m = m_modules[i - FIRST_DRAWABLE_MODULE_TYPE]; return m; diff --git a/Generals/Code/GameEngine/Include/GameClient/InGameUI.h b/Generals/Code/GameEngine/Include/GameClient/InGameUI.h index b00567e185..710b5efe41 100644 --- a/Generals/Code/GameEngine/Include/GameClient/InGameUI.h +++ b/Generals/Code/GameEngine/Include/GameClient/InGameUI.h @@ -516,7 +516,7 @@ friend class Drawable; // for selection/deselection transactions Bool isDrawableCaptionBold( void ) { return m_drawableCaptionBold; } Color getDrawableCaptionColor( void ) { return m_drawableCaptionColor; } - inline Bool shouldMoveRMBScrollAnchor( void ) { return m_moveRMBScrollAnchor; } + Bool shouldMoveRMBScrollAnchor( void ) { return m_moveRMBScrollAnchor; } Bool isClientQuiet( void ) const { return m_clientQuiet; } Bool isInWaypointMode( void ) const { return m_waypointMode; } diff --git a/Generals/Code/GameEngine/Include/GameClient/Mouse.h b/Generals/Code/GameEngine/Include/GameClient/Mouse.h index bdb94d9578..92fd80497c 100644 --- a/Generals/Code/GameEngine/Include/GameClient/Mouse.h +++ b/Generals/Code/GameEngine/Include/GameClient/Mouse.h @@ -304,7 +304,7 @@ class Mouse : public SubsystemInterface virtual void setRedrawMode(RedrawMode mode) {m_currentRedrawMode=mode;} ///* path, Object *ignoreObject, CommandSourceType cmdSource ) + void aiFollowExitProductionPath( const std::vector* path, Object *ignoreObject, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_FOLLOW_EXITPRODUCTION_PATH, cmdSource); parms.m_coords = *path; @@ -544,7 +544,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiFollowPath( const std::vector* path, Object *ignoreObject, CommandSourceType cmdSource ) + void aiFollowPath( const std::vector* path, Object *ignoreObject, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_FOLLOW_PATH, cmdSource); parms.m_coords = *path; @@ -552,14 +552,14 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiFollowPathAppend( const Coord3D* pos, CommandSourceType cmdSource ) + void aiFollowPathAppend( const Coord3D* pos, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_FOLLOW_PATH_APPEND, cmdSource); parms.m_pos = *pos; aiDoCommand(&parms); } - inline void aiAttackObject( Object *victim, Int maxShotsToFire, CommandSourceType cmdSource ) + void aiAttackObject( Object *victim, Int maxShotsToFire, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_ATTACK_OBJECT, cmdSource); parms.m_obj = victim; @@ -567,7 +567,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiForceAttackObject( Object *victim, Int maxShotsToFire, CommandSourceType cmdSource ) + void aiForceAttackObject( Object *victim, Int maxShotsToFire, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_FORCE_ATTACK_OBJECT, cmdSource); parms.m_obj = victim; @@ -575,7 +575,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiAttackTeam( const Team *team, Int maxShotsToFire, CommandSourceType cmdSource ) + void aiAttackTeam( const Team *team, Int maxShotsToFire, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_ATTACK_TEAM, cmdSource); parms.m_team = team; @@ -583,7 +583,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiAttackPosition( const Coord3D *pos, Int maxShotsToFire, CommandSourceType cmdSource ) + void aiAttackPosition( const Coord3D *pos, Int maxShotsToFire, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_ATTACK_POSITION, cmdSource); parms.m_pos = *pos; @@ -591,7 +591,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiAttackMoveToPosition( const Coord3D *pos, Int maxShotsToFire, CommandSourceType cmdSource ) + void aiAttackMoveToPosition( const Coord3D *pos, Int maxShotsToFire, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_ATTACKMOVE_TO_POSITION, cmdSource); parms.m_pos = *pos; @@ -599,7 +599,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiAttackFollowWaypointPath( const Waypoint *way, Int maxShotsToFire, CommandSourceType cmdSource ) + void aiAttackFollowWaypointPath( const Waypoint *way, Int maxShotsToFire, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_ATTACKFOLLOW_WAYPOINT_PATH, cmdSource); parms.m_waypoint = way; @@ -607,7 +607,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiAttackFollowWaypointPathAsTeam( const Waypoint *way, Int maxShotsToFire, CommandSourceType cmdSource ) + void aiAttackFollowWaypointPathAsTeam( const Waypoint *way, Int maxShotsToFire, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_ATTACKFOLLOW_WAYPOINT_PATH_AS_TEAM, cmdSource); parms.m_waypoint = way; @@ -615,20 +615,20 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiHunt( CommandSourceType cmdSource ) + void aiHunt( CommandSourceType cmdSource ) { AICommandParms parms(AICMD_HUNT, cmdSource); aiDoCommand(&parms); } - inline void aiAttackArea( const PolygonTrigger *areaToGuard, CommandSourceType cmdSource ) + void aiAttackArea( const PolygonTrigger *areaToGuard, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_ATTACK_AREA, cmdSource); parms.m_polygon = areaToGuard; aiDoCommand(&parms); } - inline void aiRepair( Object *obj, CommandSourceType cmdSource ) + void aiRepair( Object *obj, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_REPAIR, cmdSource); parms.m_obj = obj; @@ -653,49 +653,49 @@ class AICommandInterface } #endif - inline void aiResumeConstruction( Object *obj, CommandSourceType cmdSource ) + void aiResumeConstruction( Object *obj, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_RESUME_CONSTRUCTION, cmdSource); parms.m_obj = obj; aiDoCommand(&parms); } - inline void aiGetHealed( Object *healDepot, CommandSourceType cmdSource ) + void aiGetHealed( Object *healDepot, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_GET_HEALED, cmdSource); parms.m_obj = healDepot; aiDoCommand(&parms); } - inline void aiGetRepaired( Object *repairDepot, CommandSourceType cmdSource ) + void aiGetRepaired( Object *repairDepot, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_GET_REPAIRED, cmdSource); parms.m_obj = repairDepot; aiDoCommand(&parms); } - inline void aiEnter( Object *obj, CommandSourceType cmdSource ) + void aiEnter( Object *obj, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_ENTER, cmdSource); parms.m_obj = obj; aiDoCommand(&parms); } - inline void aiDock( Object *obj, CommandSourceType cmdSource ) + void aiDock( Object *obj, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_DOCK, cmdSource); parms.m_obj = obj; aiDoCommand(&parms); } - inline void aiExit( Object *objectToExit, CommandSourceType cmdSource ) + void aiExit( Object *objectToExit, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_EXIT, cmdSource); parms.m_obj = objectToExit; aiDoCommand(&parms); } - inline void aiEvacuate( Bool exposeStealthUnits, CommandSourceType cmdSource ) + void aiEvacuate( Bool exposeStealthUnits, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_EVACUATE, cmdSource); if( exposeStealthUnits ) @@ -705,20 +705,20 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiExecuteRailedTransport( CommandSourceType cmdSource ) + void aiExecuteRailedTransport( CommandSourceType cmdSource ) { AICommandParms parms( AICMD_EXECUTE_RAILED_TRANSPORT, cmdSource ); aiDoCommand( &parms ); } - inline void aiGoProne( const DamageInfo *damageInfo, CommandSourceType cmdSource ) + void aiGoProne( const DamageInfo *damageInfo, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_GO_PRONE, cmdSource); parms.m_damage = *damageInfo; aiDoCommand(&parms); } - inline void aiGuardPosition( const Coord3D *pos, GuardMode guardMode, CommandSourceType cmdSource ) + void aiGuardPosition( const Coord3D *pos, GuardMode guardMode, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_GUARD_POSITION, cmdSource); parms.m_pos = *pos; @@ -726,7 +726,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiGuardObject( Object *objToGuard, GuardMode guardMode, CommandSourceType cmdSource ) + void aiGuardObject( Object *objToGuard, GuardMode guardMode, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_GUARD_OBJECT, cmdSource); parms.m_obj = objToGuard; @@ -734,7 +734,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiGuardArea( const PolygonTrigger *areaToGuard, GuardMode guardMode, CommandSourceType cmdSource ) + void aiGuardArea( const PolygonTrigger *areaToGuard, GuardMode guardMode, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_GUARD_AREA, cmdSource); parms.m_polygon = areaToGuard; @@ -742,34 +742,34 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiGuardTunnelNetwork( GuardMode guardMode, CommandSourceType cmdSource ) + void aiGuardTunnelNetwork( GuardMode guardMode, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_GUARD_TUNNEL_NETWORK, cmdSource); parms.m_intValue = guardMode; aiDoCommand(&parms); } - inline void aiHackInternet( CommandSourceType cmdSource ) + void aiHackInternet( CommandSourceType cmdSource ) { AICommandParms parms(AICMD_HACK_INTERNET, cmdSource); aiDoCommand(&parms); } - inline void aiFaceObject( Object *target, CommandSourceType cmdSource ) + void aiFaceObject( Object *target, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_FACE_OBJECT, cmdSource); parms.m_obj = target; aiDoCommand(&parms); } - inline void aiFacePosition( const Coord3D *pos, CommandSourceType cmdSource ) + void aiFacePosition( const Coord3D *pos, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_FACE_POSITION, cmdSource); parms.m_pos = *pos; aiDoCommand(&parms); } - inline void aiRappelInto( Object *target, const Coord3D& pos, CommandSourceType cmdSource ) + void aiRappelInto( Object *target, const Coord3D& pos, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_RAPPEL_INTO, cmdSource); parms.m_obj = target; @@ -777,7 +777,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiCombatDrop( Object *target, const Coord3D& pos, CommandSourceType cmdSource ) + void aiCombatDrop( Object *target, const Coord3D& pos, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_COMBATDROP, cmdSource); parms.m_obj = target; @@ -785,14 +785,14 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiDoCommandButton( const CommandButton *commandButton, CommandSourceType cmdSource ) + void aiDoCommandButton( const CommandButton *commandButton, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_COMMANDBUTTON, cmdSource); parms.m_commandButton = commandButton; aiDoCommand(&parms); } - inline void aiDoCommandButtonAtPosition( const CommandButton *commandButton, const Coord3D *pos, CommandSourceType cmdSource ) + void aiDoCommandButtonAtPosition( const CommandButton *commandButton, const Coord3D *pos, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_COMMANDBUTTON_POS, cmdSource); parms.m_pos = *pos; @@ -800,7 +800,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiDoCommandButtonAtObject( const CommandButton *commandButton, Object *obj, CommandSourceType cmdSource ) + void aiDoCommandButtonAtObject( const CommandButton *commandButton, Object *obj, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_COMMANDBUTTON_OBJ, cmdSource); parms.m_obj = obj; @@ -808,27 +808,27 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiMoveAwayFromUnit( Object *obj, CommandSourceType cmdSource ) + void aiMoveAwayFromUnit( Object *obj, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_MOVE_AWAY_FROM_UNIT, cmdSource); parms.m_obj = obj; aiDoCommand(&parms); } - inline void aiWander( const Waypoint *way, CommandSourceType cmdSource ) + void aiWander( const Waypoint *way, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_WANDER, cmdSource); parms.m_waypoint = way; aiDoCommand(&parms); } - inline void aiWanderInPlace(CommandSourceType cmdSource) + void aiWanderInPlace(CommandSourceType cmdSource) { AICommandParms parms(AICMD_WANDER_IN_PLACE, cmdSource); aiDoCommand(&parms); } - inline void aiPanic( const Waypoint *way, CommandSourceType cmdSource ) + void aiPanic( const Waypoint *way, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_PANIC, cmdSource); parms.m_waypoint = way; diff --git a/Generals/Code/GameEngine/Include/GameLogic/ArmorSet.h b/Generals/Code/GameEngine/Include/GameLogic/ArmorSet.h index e644defdf6..d684bee367 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/ArmorSet.h +++ b/Generals/Code/GameEngine/Include/GameLogic/ArmorSet.h @@ -63,23 +63,23 @@ class ArmorTemplateSet const DamageFX* m_fx; public: - inline ArmorTemplateSet() + ArmorTemplateSet() { clear(); } - inline void clear() + void clear() { m_types.clear(); m_template = NULL; m_fx = NULL; } - inline const ArmorTemplate* getArmorTemplate() const { return m_template; } - inline const DamageFX* getDamageFX() const { return m_fx; } + const ArmorTemplate* getArmorTemplate() const { return m_template; } + const DamageFX* getDamageFX() const { return m_fx; } - inline Int getConditionsYesCount() const { return 1; } - inline const ArmorSetFlags& getNthConditionsYes(Int i) const { return m_types; } + Int getConditionsYesCount() const { return 1; } + const ArmorSetFlags& getNthConditionsYes(Int i) const { return m_types; } #if defined(RTS_DEBUG) inline AsciiString getDescription() const { return "ArmorTemplateSet"; } #endif diff --git a/Generals/Code/GameEngine/Include/GameLogic/CrateSystem.h b/Generals/Code/GameEngine/Include/GameLogic/CrateSystem.h index 7e4e4da313..c7c4745e31 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/CrateSystem.h +++ b/Generals/Code/GameEngine/Include/GameLogic/CrateSystem.h @@ -60,7 +60,7 @@ class CrateTemplate : public Overridable void setName( AsciiString name ) { m_name = name; } AsciiString getName(){ return m_name; } - inline const FieldParse *getFieldParse() const { return TheCrateTemplateFieldParseTable; } + const FieldParse *getFieldParse() const { return TheCrateTemplateFieldParseTable; } static const FieldParse TheCrateTemplateFieldParseTable[]; ///< the parse table for INI definition static void parseCrateCreationEntry( INI* ini, void *instance, void *store, const void* /*userData*/ ); diff --git a/Generals/Code/GameEngine/Include/GameLogic/GhostObject.h b/Generals/Code/GameEngine/Include/GameLogic/GhostObject.h index 9335f8b0de..17ea737e91 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/GhostObject.h +++ b/Generals/Code/GameEngine/Include/GameLogic/GhostObject.h @@ -47,13 +47,13 @@ class GhostObject : public Snapshot virtual void snapShot(int playerIndex)=0; virtual void updateParentObject(Object *object, PartitionData *mod)=0; virtual void freeSnapShot(int playerIndex)=0; - inline PartitionData *friend_getPartitionData(void) const {return m_partitionData;} - inline GeometryType getGeometryType(void) const {return m_parentGeometryType;} - inline Bool getGeometrySmall(void) const {return m_parentGeometryIsSmall;} - inline Real getGeometryMajorRadius(void) const {return m_parentGeometryMajorRadius;} - inline Real getGeometryMinorRadius(void) const {return m_parentGeometryminorRadius;} - inline Real getParentAngle(void) const {return m_parentAngle;} - inline const Coord3D *getParentPosition(void) const {return &m_parentPosition;} + PartitionData *friend_getPartitionData(void) const {return m_partitionData;} + GeometryType getGeometryType(void) const {return m_parentGeometryType;} + Bool getGeometrySmall(void) const {return m_parentGeometryIsSmall;} + Real getGeometryMajorRadius(void) const {return m_parentGeometryMajorRadius;} + Real getGeometryMinorRadius(void) const {return m_parentGeometryminorRadius;} + Real getParentAngle(void) const {return m_parentAngle;} + const Coord3D *getParentPosition(void) const {return &m_parentPosition;} protected: virtual void crc( Xfer *xfer ); @@ -80,12 +80,12 @@ class GhostObjectManager : public Snapshot virtual GhostObject *addGhostObject(Object *object, PartitionData *pd); virtual void removeGhostObject(GhostObject *mod); virtual void setLocalPlayerIndex(int playerIndex) { m_localPlayer = playerIndex; } - inline int getLocalPlayerIndex(void) { return m_localPlayer; } + int getLocalPlayerIndex(void) { return m_localPlayer; } virtual void updateOrphanedObjects(int *playerIndexList, int playerIndexCount); virtual void releasePartitionData(void); ///m_preferredHeight; }; - inline Real getPreferredHeightDamping() const { return m_preferredHeightDamping;} - inline LocomotorAppearance getAppearance() const { return m_template->m_appearance; } - inline LocomotorPriority getMovePriority() const { return m_template->m_movePriority; } - inline LocomotorSurfaceTypeMask getLegalSurfaces() const { return m_template->m_surfaces; } - - inline AsciiString getTemplateName() const { return m_template->m_name;} - inline Real getMinSpeed() const { return m_template->m_minSpeed;} - inline Real getAccelPitchLimit() const { return m_template->m_accelPitchLimit;} ///< Maximum amount we will pitch up or down under acceleration (including recoil.) - inline Real getBounceKick() const { return m_template->m_bounceKick;} ///< How much simulating rough terrain "bounces" a wheel up. - inline Real getPitchStiffness() const { return m_template->m_pitchStiffness;} ///< How stiff the springs are forward & back. - inline Real getRollStiffness() const { return m_template->m_rollStiffness;} ///< How stiff the springs are side to side. - inline Real getPitchDamping() const { return m_template->m_pitchDamping;} ///< How good the shock absorbers are. - inline Real getRollDamping() const { return m_template->m_rollDamping;} ///< How good the shock absorbers are. - inline Real getPitchByZVelCoef() const { return m_template->m_pitchByZVelCoef;} ///< How much we pitch in response to speed. - inline Real getThrustRoll() const { return m_template->m_thrustRoll; } ///< Thrust roll - inline Real getWobbleRate() const { return m_template->m_wobbleRate; } ///< how fast thrust things "wobble" - inline Real getMaxWobble() const { return m_template->m_maxWobble; } ///< how much thrust things "wobble" - inline Real getMinWobble() const { return m_template->m_minWobble; } ///< how much thrust things "wobble" - - inline Real getForwardVelCoef() const { return m_template->m_forwardVelCoef;} ///< How much we pitch in response to speed. - inline Real getLateralVelCoef() const { return m_template->m_lateralVelCoef;} ///< How much we roll in response to speed. - inline Real getForwardAccelCoef() const { return m_template->m_forwardAccelCoef;} ///< How much we pitch in response to acceleration. - inline Real getLateralAccelCoef() const { return m_template->m_lateralAccelCoef;} ///< How much we roll in response to acceleration. - inline Real getUniformAxialDamping() const { return m_template->m_uniformAxialDamping;} ///< How much we roll in response to acceleration. - inline Real getTurnPivotOffset() const { return m_template->m_turnPivotOffset;} - inline Bool getApply2DFrictionWhenAirborne() const { return m_template->m_apply2DFrictionWhenAirborne; } - inline Bool getIsDownhillOnly() const { return m_template->m_downhillOnly; } - inline Bool getAllowMotiveForceWhileAirborne() const { return m_template->m_allowMotiveForceWhileAirborne; } - inline Int getAirborneTargetingHeight() const { return m_template->m_airborneTargetingHeight; } - inline Bool getLocomotorWorksWhenDead() const { return m_template->m_locomotorWorksWhenDead; } - inline Bool getStickToGround() const { return m_template->m_stickToGround; } - inline Real getCloseEnoughDist() const { return m_closeEnoughDist; } - inline Bool isCloseEnoughDist3D() const { return getFlag(IS_CLOSE_ENOUGH_DIST_3D); } - inline Bool hasSuspension() const {return m_template->m_hasSuspension;} - inline Bool canMoveBackwards() const {return m_template->m_canMoveBackward;} - inline Real getMaxWheelExtension() const {return m_template->m_maximumWheelExtension;} - inline Real getMaxWheelCompression() const {return m_template->m_maximumWheelCompression;} - inline Real getWheelTurnAngle() const {return m_template->m_wheelTurnAngle;} - - inline Real getWanderWidthFactor() const {return m_template->m_wanderWidthFactor;} - inline Real getWanderAboutPointRadius() const {return m_template->m_wanderAboutPointRadius;} + Real getPreferredHeight() const { return m_preferredHeight;} ///< Just return preferredheight, no damage consideration + void restorePreferredHeightFromTemplate() { m_preferredHeight = m_template->m_preferredHeight; }; + Real getPreferredHeightDamping() const { return m_preferredHeightDamping;} + LocomotorAppearance getAppearance() const { return m_template->m_appearance; } + LocomotorPriority getMovePriority() const { return m_template->m_movePriority; } + LocomotorSurfaceTypeMask getLegalSurfaces() const { return m_template->m_surfaces; } + + AsciiString getTemplateName() const { return m_template->m_name;} + Real getMinSpeed() const { return m_template->m_minSpeed;} + Real getAccelPitchLimit() const { return m_template->m_accelPitchLimit;} ///< Maximum amount we will pitch up or down under acceleration (including recoil.) + Real getBounceKick() const { return m_template->m_bounceKick;} ///< How much simulating rough terrain "bounces" a wheel up. + Real getPitchStiffness() const { return m_template->m_pitchStiffness;} ///< How stiff the springs are forward & back. + Real getRollStiffness() const { return m_template->m_rollStiffness;} ///< How stiff the springs are side to side. + Real getPitchDamping() const { return m_template->m_pitchDamping;} ///< How good the shock absorbers are. + Real getRollDamping() const { return m_template->m_rollDamping;} ///< How good the shock absorbers are. + Real getPitchByZVelCoef() const { return m_template->m_pitchByZVelCoef;} ///< How much we pitch in response to speed. + Real getThrustRoll() const { return m_template->m_thrustRoll; } ///< Thrust roll + Real getWobbleRate() const { return m_template->m_wobbleRate; } ///< how fast thrust things "wobble" + Real getMaxWobble() const { return m_template->m_maxWobble; } ///< how much thrust things "wobble" + Real getMinWobble() const { return m_template->m_minWobble; } ///< how much thrust things "wobble" + + Real getForwardVelCoef() const { return m_template->m_forwardVelCoef;} ///< How much we pitch in response to speed. + Real getLateralVelCoef() const { return m_template->m_lateralVelCoef;} ///< How much we roll in response to speed. + Real getForwardAccelCoef() const { return m_template->m_forwardAccelCoef;} ///< How much we pitch in response to acceleration. + Real getLateralAccelCoef() const { return m_template->m_lateralAccelCoef;} ///< How much we roll in response to acceleration. + Real getUniformAxialDamping() const { return m_template->m_uniformAxialDamping;} ///< How much we roll in response to acceleration. + Real getTurnPivotOffset() const { return m_template->m_turnPivotOffset;} + Bool getApply2DFrictionWhenAirborne() const { return m_template->m_apply2DFrictionWhenAirborne; } + Bool getIsDownhillOnly() const { return m_template->m_downhillOnly; } + Bool getAllowMotiveForceWhileAirborne() const { return m_template->m_allowMotiveForceWhileAirborne; } + Int getAirborneTargetingHeight() const { return m_template->m_airborneTargetingHeight; } + Bool getLocomotorWorksWhenDead() const { return m_template->m_locomotorWorksWhenDead; } + Bool getStickToGround() const { return m_template->m_stickToGround; } + Real getCloseEnoughDist() const { return m_closeEnoughDist; } + Bool isCloseEnoughDist3D() const { return getFlag(IS_CLOSE_ENOUGH_DIST_3D); } + Bool hasSuspension() const {return m_template->m_hasSuspension;} + Bool canMoveBackwards() const {return m_template->m_canMoveBackward;} + Real getMaxWheelExtension() const {return m_template->m_maximumWheelExtension;} + Real getMaxWheelCompression() const {return m_template->m_maximumWheelCompression;} + Real getWheelTurnAngle() const {return m_template->m_wheelTurnAngle;} + + Real getWanderWidthFactor() const {return m_template->m_wanderWidthFactor;} + Real getWanderAboutPointRadius() const {return m_template->m_wanderAboutPointRadius;} Real calcMinTurnRadius(BodyDamageType condition, Real* timeToTravelThatDist) const; /// this is handy for doing things like forcing helicopters to crash realistically: cut their lift. - inline void setMaxLift(Real lift) { m_maxLift = lift; } - inline void setMaxSpeed(Real speed) + void setMaxLift(Real lift) { m_maxLift = lift; } + void setMaxSpeed(Real speed) { DEBUG_ASSERTCRASH(!(speed <= 0.0f && m_template->m_appearance == LOCO_THRUST), ("THRUST locos may not have zero speeds!")); m_maxSpeed = speed; } - inline void setMaxAcceleration(Real accel) { m_maxAccel = accel; } - inline void setMaxBraking(Real braking) { m_maxBraking = braking; } - inline void setMaxTurnRate(Real turn) { m_maxTurnRate = turn; } - inline void setAllowInvalidPosition(Bool allow) { setFlag(ALLOW_INVALID_POSITION, allow); } - inline void setCloseEnoughDist( Real dist ) { m_closeEnoughDist = dist; } - inline void setCloseEnoughDist3D( Bool setting ) { setFlag(IS_CLOSE_ENOUGH_DIST_3D, setting); } + void setMaxAcceleration(Real accel) { m_maxAccel = accel; } + void setMaxBraking(Real braking) { m_maxBraking = braking; } + void setMaxTurnRate(Real turn) { m_maxTurnRate = turn; } + void setAllowInvalidPosition(Bool allow) { setFlag(ALLOW_INVALID_POSITION, allow); } + void setCloseEnoughDist( Real dist ) { m_closeEnoughDist = dist; } + void setCloseEnoughDist3D( Bool setting ) { setFlag(IS_CLOSE_ENOUGH_DIST_3D, setting); } - inline void setPreferredHeight( Real height ) { m_preferredHeight = height; } + void setPreferredHeight( Real height ) { m_preferredHeight = height; } #ifdef CIRCLE_FOR_LANDING /** @@ -319,7 +319,7 @@ class Locomotor : public MemoryPoolObject, public Snapshot this is used mainly for force missiles to swoop in on their target, and to force airplane takeoff/landing to go smoothly. */ - inline void setUsePreciseZPos(Bool u) { setFlag(PRECISE_Z_POS, u); } + void setUsePreciseZPos(Bool u) { setFlag(PRECISE_Z_POS, u); } /** when off (the default), units slow down as they approach their target. @@ -328,7 +328,7 @@ class Locomotor : public MemoryPoolObject, public Snapshot this is useful mainly in some weird, temporary situations where we know we are going to follow this move with another one... or for carbombs. */ - inline void setNoSlowDownAsApproachingDest(Bool u) { setFlag(NO_SLOW_DOWN_AS_APPROACHING_DEST, u); } + void setNoSlowDownAsApproachingDest(Bool u) { setFlag(NO_SLOW_DOWN_AS_APPROACHING_DEST, u); } /** when off (the default), units do their normal stuff. @@ -341,10 +341,10 @@ class Locomotor : public MemoryPoolObject, public Snapshot For ground units, it also allows units to have a destination off of a pathfing grid. */ - inline void setUltraAccurate(Bool u) { setFlag(ULTRA_ACCURATE, u); } - inline Bool isUltraAccurate() const { return getFlag(ULTRA_ACCURATE); } + void setUltraAccurate(Bool u) { setFlag(ULTRA_ACCURATE, u); } + Bool isUltraAccurate() const { return getFlag(ULTRA_ACCURATE); } - inline Bool isMovingBackwards(void) const {return getFlag(MOVING_BACKWARDS);} + Bool isMovingBackwards(void) const {return getFlag(MOVING_BACKWARDS);} void startMove(void); ///< Indicates that a move is starting, primarily to reset the donut timer. jba. @@ -419,8 +419,8 @@ class Locomotor : public MemoryPoolObject, public Snapshot OFFSET_INCREASING }; - inline Bool getFlag(LocoFlag f) const { return (m_flags & (1 << f)) != 0; } - inline void setFlag(LocoFlag f, Bool b) { if (b) m_flags |= (1<getCurrentStateID(); } ///< return the id of the current state of the machine + StateID getCurrentStateID() const { return getStateMachine()->getCurrentStateID(); } ///< return the id of the current state of the machine /// @ todo -- srj sez: JBA NUKE THIS CODE, IT IS EVIL - inline void friend_addToWaypointGoalPath( const Coord3D *pathPoint ) { getStateMachine()->addToGoalPath(pathPoint); } + void friend_addToWaypointGoalPath( const Coord3D *pathPoint ) { getStateMachine()->addToGoalPath(pathPoint); } // this is intended for use ONLY by W3dWaypointBuffer and AIFollowPathState. - inline const Coord3D* friend_getGoalPathPosition( Int index ) const { return getStateMachine()->getGoalPathPosition( index ); } + const Coord3D* friend_getGoalPathPosition( Int index ) const { return getStateMachine()->getGoalPathPosition( index ); } // this is intended for use ONLY by W3dWaypointBuffer. Int friend_getWaypointGoalPathSize() const; // this is intended for use ONLY by W3dWaypointBuffer. - inline Int friend_getCurrentGoalPathIndex() const { return m_nextGoalPathIndex; } + Int friend_getCurrentGoalPathIndex() const { return m_nextGoalPathIndex; } // this is intended for use ONLY by AIFollowPathState. - inline void friend_setCurrentGoalPathIndex( Int index ) { m_nextGoalPathIndex = index; } + void friend_setCurrentGoalPathIndex( Int index ) { m_nextGoalPathIndex = index; } #ifdef DEBUG_LOGGING inline const Coord3D *friend_getRequestedDestination() const { return &m_requestedDestination; } inline const Coord3D *friend_getRequestedDestination2() const { return &m_requestedDestination2; } #endif - inline Object* getGoalObject() { return getStateMachine()->getGoalObject(); } ///< return the id of the current state of the machine - inline const Coord3D* getGoalPosition() const { return getStateMachine()->getGoalPosition(); } ///< return the id of the current state of the machine + Object* getGoalObject() { return getStateMachine()->getGoalObject(); } ///< return the id of the current state of the machine + const Coord3D* getGoalPosition() const { return getStateMachine()->getGoalPosition(); } ///< return the id of the current state of the machine - inline WhichTurretType friend_getTurretSync() const { return m_turretSyncFlag; } - inline void friend_setTurretSync(WhichTurretType t) { m_turretSyncFlag = t; } + WhichTurretType friend_getTurretSync() const { return m_turretSyncFlag; } + void friend_setTurretSync(WhichTurretType t) { m_turretSyncFlag = t; } - inline UnsignedInt getPriorWaypointID ( void ) { return m_priorWaypointID; }; - inline UnsignedInt getCurrentWaypointID ( void ) { return m_currentWaypointID; }; + UnsignedInt getPriorWaypointID ( void ) { return m_priorWaypointID; }; + UnsignedInt getCurrentWaypointID ( void ) { return m_currentWaypointID; }; - inline void clearMoveOutOfWay(void) {m_moveOutOfWay1 = INVALID_ID; m_moveOutOfWay2 = INVALID_ID;} + void clearMoveOutOfWay(void) {m_moveOutOfWay1 = INVALID_ID; m_moveOutOfWay2 = INVALID_ID;} - inline void setTmpValue(Int val) {m_tmpInt = val;} - inline Int getTmpValue(void) {return m_tmpInt;} + void setTmpValue(Int val) {m_tmpInt = val;} + Int getTmpValue(void) {return m_tmpInt;} - inline Bool getRetryPath(void) {return m_retryPath;} + Bool getRetryPath(void) {return m_retryPath;} - inline void setAllowedToChase( Bool allow ) { m_allowedToChase = allow; } - inline Bool isAllowedToChase() const { return m_allowedToChase; } + void setAllowedToChase( Bool allow ) { m_allowedToChase = allow; } + Bool isAllowedToChase() const { return m_allowedToChase; } // only for AIStateMachine. virtual void friend_notifyStateMachineChanged(); diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/AutoHealBehavior.h b/Generals/Code/GameEngine/Include/GameLogic/Module/AutoHealBehavior.h index a1cfcafdb0..c1f3a17834 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/AutoHealBehavior.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/AutoHealBehavior.h @@ -154,7 +154,7 @@ class AutoHealBehavior : public UpdateModule, return getAutoHealBehaviorModuleData()->m_upgradeMuxData.m_requiresAllTriggers; } - inline Bool isUpgradeActive() const { return isAlreadyUpgraded(); } + Bool isUpgradeActive() const { return isAlreadyUpgraded(); } virtual Bool isSubObjectsUpgrade() { return false; } diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/DieModule.h b/Generals/Code/GameEngine/Include/GameLogic/Module/DieModule.h index ac770552fe..d16a49ab3d 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/DieModule.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/DieModule.h @@ -76,7 +76,7 @@ class DieModuleData : public BehaviorModuleData p.add(DieMuxData::getFieldParse(), offsetof( DieModuleData, m_dieMuxData )); } - inline Bool isDieApplicable(const Object* obj, const DamageInfo *damageInfo) const { return m_dieMuxData.isDieApplicable(obj, damageInfo); } + Bool isDieApplicable(const Object* obj, const DamageInfo *damageInfo) const { return m_dieMuxData.isDieApplicable(obj, damageInfo); } }; //------------------------------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDamagedBehavior.h b/Generals/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDamagedBehavior.h index 77003163c1..906e7784d9 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDamagedBehavior.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDamagedBehavior.h @@ -149,7 +149,7 @@ class FireWeaponWhenDamagedBehavior : public UpdateModule, return getFireWeaponWhenDamagedBehaviorModuleData()->m_upgradeMuxData.m_requiresAllTriggers; } - inline Bool isUpgradeActive() const { return isAlreadyUpgraded(); } + Bool isUpgradeActive() const { return isAlreadyUpgraded(); } virtual Bool isSubObjectsUpgrade() { return false; } diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDeadBehavior.h b/Generals/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDeadBehavior.h index 60772c23e3..a7d6a9bc7c 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDeadBehavior.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDeadBehavior.h @@ -113,7 +113,7 @@ class FireWeaponWhenDeadBehavior : public BehaviorModule, return getFireWeaponWhenDeadBehaviorModuleData()->m_upgradeMuxData.m_requiresAllTriggers; } - inline Bool isUpgradeActive() const { return isAlreadyUpgraded(); } + Bool isUpgradeActive() const { return isAlreadyUpgraded(); } virtual Bool isSubObjectsUpgrade() { return false; } diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/JetAIUpdate.h b/Generals/Code/GameEngine/Include/GameLogic/Module/JetAIUpdate.h index c1b5facba1..cc6f8c4e72 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/JetAIUpdate.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/JetAIUpdate.h @@ -164,6 +164,6 @@ class JetAIUpdate : public AIUpdateInterface void getProducerLocation(); void buildLockonDrawableIfNecessary(); void doLandingCommand(Object *airfield, CommandSourceType cmdSource); - inline Bool getFlag(FlagType f) const { return (m_flags & (1<createInternal( primaryObj, primary, secondary, createOwner, lifetimeFrames ); @@ -144,7 +144,7 @@ class ObjectCreationList // 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 Object* create(const ObjectCreationList* ocl, const Object* primaryObj, const Coord3D *primary, const Coord3D *secondary, UnsignedInt lifetimeFrames = 0 ) + static Object* create(const ObjectCreationList* ocl, const Object* primaryObj, const Coord3D *primary, const Coord3D *secondary, UnsignedInt lifetimeFrames = 0 ) { if (ocl) return ocl->createInternal( primaryObj, primary, secondary, lifetimeFrames ); @@ -154,7 +154,7 @@ class ObjectCreationList // 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 Object* create( const ObjectCreationList* ocl, const Object* primary, const Object* secondary, UnsignedInt lifetimeFrames = 0 ) + static Object* create( const ObjectCreationList* ocl, const Object* primary, const Object* secondary, UnsignedInt lifetimeFrames = 0 ) { if (ocl) return ocl->createInternal( primary, secondary, lifetimeFrames ); diff --git a/Generals/Code/GameEngine/Include/GameLogic/PartitionManager.h b/Generals/Code/GameEngine/Include/GameLogic/PartitionManager.h index 4b26a65620..20c9146ac3 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/PartitionManager.h +++ b/Generals/Code/GameEngine/Include/GameLogic/PartitionManager.h @@ -213,22 +213,22 @@ class CellAndObjectIntersection // not MPO: we allocate these in arrays /** return the Cell for this COI (null if the COI is not in use) */ - inline PartitionCell *getCell() { return m_cell; } + PartitionCell *getCell() { return m_cell; } /** return the Module for this COI (null if the COI is not in use) */ - inline PartitionData *getModule() { return m_module; } + PartitionData *getModule() { return m_module; } /** return the previous COI in the Cell's list of COIs. */ - inline CellAndObjectIntersection *getPrevCoi() { return m_prevCoi; } + CellAndObjectIntersection *getPrevCoi() { return m_prevCoi; } /** return the next COI in the Cell's list of COIs. */ - inline CellAndObjectIntersection *getNextCoi() { return m_nextCoi; } + CellAndObjectIntersection *getNextCoi() { return m_nextCoi; } // only for use by PartitionCell. void friend_addToCellList(CellAndObjectIntersection **pListHead); @@ -341,13 +341,13 @@ class PartitionCell : public Snapshot // not MPO: allocated in an array void invalidateShroudedStatusForAllCois(Int playerIndex); #ifdef PM_CACHE_TERRAIN_HEIGHT - inline Real getLoTerrain() const { return m_loTerrainZ; } - inline Real getHiTerrain() const { return m_hiTerrainZ; } + Real getLoTerrain() const { return m_loTerrainZ; } + Real getHiTerrain() const { return m_hiTerrainZ; } #endif void getCellCenterPos(Real& x, Real& y); - inline CellAndObjectIntersection *getFirstCoiInCell() { return m_firstCoiInCell; } + CellAndObjectIntersection *getFirstCoiInCell() { return m_firstCoiInCell; } #ifdef RTS_DEBUG void validateCoiList(); @@ -510,7 +510,7 @@ class PartitionData : public MemoryPoolObject ObjectShroudStatus getShroudedStatus(Int playerIndex); - inline Int wasSeenByAnyPlayers() const ///isInListDirtyModules(&m_dirtyModules); } - inline void prependToDirtyModules(PartitionData* o) + void prependToDirtyModules(PartitionData* o) { o->prependToDirtyModules(&m_dirtyModules); } - inline void removeFromDirtyModules(PartitionData* o) + void removeFromDirtyModules(PartitionData* o) { o->removeFromDirtyModules(&m_dirtyModules); } - inline void removeAllDirtyModules() + void removeAllDirtyModules() { while (m_dirtyModules) { diff --git a/Generals/Code/GameEngine/Include/GameLogic/TerrainLogic.h b/Generals/Code/GameEngine/Include/GameLogic/TerrainLogic.h index 30ccb58394..55614c5757 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/TerrainLogic.h +++ b/Generals/Code/GameEngine/Include/GameLogic/TerrainLogic.h @@ -194,16 +194,16 @@ class Bridge : public MemoryPoolObject Bool isPointOnBridge(const Coord3D *pLoc); Drawable *pickBridge(const Vector3 &from, const Vector3 &to, Vector3 *pos); void updateDamageState(void); ///< Updates a bridge's damage info. - inline const BridgeInfo *peekBridgeInfo(void) const {return &m_bridgeInfo;} - inline PathfindLayerEnum getLayer(void) const {return m_layer;} - inline void setLayer(PathfindLayerEnum layer) {m_layer = layer;} + const BridgeInfo *peekBridgeInfo(void) const {return &m_bridgeInfo;} + PathfindLayerEnum getLayer(void) const {return m_layer;} + void setLayer(PathfindLayerEnum layer) {m_layer = layer;} const Region2D *getBounds(void) const {return &m_bounds;} Bool isCellOnEnd(const Region2D *cell); // Is pathfind cell on the sides of the bridge Bool isCellOnSide(const Region2D *cell); // Is pathfind cell on the end of the bridge Bool isCellEntryPoint(const Region2D *cell); // Is pathfind cell an entry point to the bridge - inline void setBridgeObjectID( ObjectID id ) { m_bridgeInfo.bridgeObjectID = id; } - inline void setTowerObjectID( ObjectID id, BridgeTowerType which ) { m_bridgeInfo.towerObjectID[ which ] = id; } + void setBridgeObjectID( ObjectID id ) { m_bridgeInfo.bridgeObjectID = id; } + void setTowerObjectID( ObjectID id, BridgeTowerType which ) { m_bridgeInfo.towerObjectID[ which ] = id; } }; diff --git a/Generals/Code/GameEngine/Include/GameLogic/VictoryConditions.h b/Generals/Code/GameEngine/Include/GameLogic/VictoryConditions.h index 3fca822233..de74d3fa72 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/VictoryConditions.h +++ b/Generals/Code/GameEngine/Include/GameLogic/VictoryConditions.h @@ -55,8 +55,8 @@ class VictoryConditionsInterface : public SubsystemInterface virtual void reset( void ) = 0; virtual void update( void ) = 0; - inline void setVictoryConditions( Int victoryConditions ) { m_victoryConditions = victoryConditions; } - inline Int getVictoryConditions( void ) { return m_victoryConditions; } + void setVictoryConditions( Int victoryConditions ) { m_victoryConditions = victoryConditions; } + Int getVictoryConditions( void ) { return m_victoryConditions; } virtual Bool hasAchievedVictory(Player *player) = 0; ///< has a specific player and his allies won? virtual Bool hasBeenDefeated(Player *player) = 0; ///< has a specific player and his allies lost? diff --git a/Generals/Code/GameEngine/Include/GameLogic/Weapon.h b/Generals/Code/GameEngine/Include/GameLogic/Weapon.h index ca98a412f6..2346a3f8a1 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Weapon.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Weapon.h @@ -276,14 +276,14 @@ class WeaponBonus clear(); } - inline void clear() + void clear() { for (int i = 0; i < FIELD_COUNT; ++i) m_field[i] = 1.0f; } - inline Real getField(Field f) const { return m_field[f]; } - inline void setField(Field f, Real v) { m_field[f] = v; } + Real getField(Field f) const { return m_field[f]; } + void setField(Field f, Real v) { m_field[f] = v; } void appendBonuses(WeaponBonus& bonus) const; @@ -357,7 +357,7 @@ class WeaponTemplate : public MemoryPoolObject Bool isOverride( void ) { return m_nextTemplate != NULL; } /// field table for loading the values from an INI - inline const FieldParse *getFieldParse() const { return TheWeaponTemplateFieldParseTable; } + const FieldParse *getFieldParse() const { return TheWeaponTemplateFieldParseTable; } /** fire the weapon. return the logic-frame in which the damage will be dealt. @@ -406,54 +406,54 @@ class WeaponTemplate : public MemoryPoolObject Int getPreAttackDelay(const WeaponBonus& bonus) const; Bool isContactWeapon() const; - inline Real getRequestAssistRange() const {return m_requestAssistRange;} - inline AsciiString getName() const { return m_name; } - inline AsciiString getProjectileStreamName() const { return m_projectileStreamName; } - inline AsciiString getLaserName() const { return m_laserName; } - inline NameKeyType getNameKey() const { return m_nameKey; } - inline Real getWeaponSpeed() const { return m_weaponSpeed; } - inline Real getMinWeaponSpeed() const { return m_minWeaponSpeed; } - inline Bool isScaleWeaponSpeed() const { return m_isScaleWeaponSpeed; } - inline Real getWeaponRecoilAmount() const { return m_weaponRecoil; } - inline Real getMinTargetPitch() const { return m_minTargetPitch; } - inline Real getMaxTargetPitch() const { return m_maxTargetPitch; } - inline DamageType getDamageType() const { return m_damageType; } - inline DeathType getDeathType() const { return m_deathType; } - inline Real getContinueAttackRange() const { return m_continueAttackRange; } - inline Real getInfantryInaccuracyDist() const { return m_infantryInaccuracyDist; } - inline Real getAimDelta() const { return m_aimDelta; } - inline Real getScatterRadius() const { return m_scatterRadius; } - inline Real getScatterTargetScalar() const { return m_scatterTargetScalar; } - inline const ThingTemplate* getProjectileTemplate() const { return m_projectileTmpl; } - inline Bool getDamageDealtAtSelfPosition() const { return m_damageDealtAtSelfPosition; } - inline Int getAffectsMask() const { return m_affectsMask; } - inline Int getProjectileCollideMask() const { return m_collideMask; } - inline WeaponReloadType getReloadType() const { return m_reloadType; } - inline WeaponPrefireType getPrefireType() const { return m_prefireType; } - inline Bool getAutoReloadsClip() const { return m_reloadType == AUTO_RELOAD; } - inline Int getClipSize() const { return m_clipSize; } - inline Int getContinuousFireOneShotsNeeded() const { return m_continuousFireOneShotsNeeded; } - inline Int getContinuousFireTwoShotsNeeded() const { return m_continuousFireTwoShotsNeeded; } - inline UnsignedInt getContinuousFireCoastFrames() const { return m_continuousFireCoastFrames; } - inline UnsignedInt getAutoReloadWhenIdleFrames() const { return m_autoReloadWhenIdleFrames; } - inline UnsignedInt getSuspendFXDelay() const { return m_suspendFXDelay; } - - inline const FXList* getFireFX(VeterancyLevel v) const { return m_fireFXs[v]; } - inline const FXList* getProjectileDetonateFX(VeterancyLevel v) const { return m_projectileDetonateFXs[v]; } - 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 AudioEventRTS& getFireSound() const { return m_fireSound; } - inline UnsignedInt getFireSoundLoopTime() const { return m_fireSoundLoopTime; } - inline const std::vector& getScatterTargetsVector() const { return m_scatterTargets; } - inline const WeaponBonusSet* getExtraBonus() const { return m_extraBonus; } - inline Int getShotsPerBarrel() const { return m_shotsPerBarrel; } - inline Int getAntiMask() const { return m_antiMask; } - inline Bool isLeechRangeWeapon() const { return m_leechRangeWeapon; } - inline Bool isCapableOfFollowingWaypoint() const { return m_capableOfFollowingWaypoint; } - inline Bool isShowsAmmoPips() const { return m_isShowsAmmoPips; } - inline Bool isPlayFXWhenStealthed() const { return m_playFXWhenStealthed; } + Real getRequestAssistRange() const {return m_requestAssistRange;} + AsciiString getName() const { return m_name; } + AsciiString getProjectileStreamName() const { return m_projectileStreamName; } + AsciiString getLaserName() const { return m_laserName; } + NameKeyType getNameKey() const { return m_nameKey; } + Real getWeaponSpeed() const { return m_weaponSpeed; } + Real getMinWeaponSpeed() const { return m_minWeaponSpeed; } + Bool isScaleWeaponSpeed() const { return m_isScaleWeaponSpeed; } + Real getWeaponRecoilAmount() const { return m_weaponRecoil; } + Real getMinTargetPitch() const { return m_minTargetPitch; } + Real getMaxTargetPitch() const { return m_maxTargetPitch; } + DamageType getDamageType() const { return m_damageType; } + DeathType getDeathType() const { return m_deathType; } + Real getContinueAttackRange() const { return m_continueAttackRange; } + Real getInfantryInaccuracyDist() const { return m_infantryInaccuracyDist; } + Real getAimDelta() const { return m_aimDelta; } + Real getScatterRadius() const { return m_scatterRadius; } + Real getScatterTargetScalar() const { return m_scatterTargetScalar; } + const ThingTemplate* getProjectileTemplate() const { return m_projectileTmpl; } + Bool getDamageDealtAtSelfPosition() const { return m_damageDealtAtSelfPosition; } + Int getAffectsMask() const { return m_affectsMask; } + Int getProjectileCollideMask() const { return m_collideMask; } + WeaponReloadType getReloadType() const { return m_reloadType; } + WeaponPrefireType getPrefireType() const { return m_prefireType; } + Bool getAutoReloadsClip() const { return m_reloadType == AUTO_RELOAD; } + Int getClipSize() const { return m_clipSize; } + Int getContinuousFireOneShotsNeeded() const { return m_continuousFireOneShotsNeeded; } + Int getContinuousFireTwoShotsNeeded() const { return m_continuousFireTwoShotsNeeded; } + UnsignedInt getContinuousFireCoastFrames() const { return m_continuousFireCoastFrames; } + UnsignedInt getAutoReloadWhenIdleFrames() const { return m_autoReloadWhenIdleFrames; } + UnsignedInt getSuspendFXDelay() const { return m_suspendFXDelay; } + + const FXList* getFireFX(VeterancyLevel v) const { return m_fireFXs[v]; } + const FXList* getProjectileDetonateFX(VeterancyLevel v) const { return m_projectileDetonateFXs[v]; } + const ObjectCreationList* getFireOCL(VeterancyLevel v) const { return m_fireOCLs[v]; } + const ObjectCreationList* getProjectileDetonationOCL(VeterancyLevel v) const { return m_projectileDetonationOCLs[v]; } + const ParticleSystemTemplate* getProjectileExhaust(VeterancyLevel v) const { return m_projectileExhausts[v]; } + + const AudioEventRTS& getFireSound() const { return m_fireSound; } + UnsignedInt getFireSoundLoopTime() const { return m_fireSoundLoopTime; } + const std::vector& getScatterTargetsVector() const { return m_scatterTargets; } + const WeaponBonusSet* getExtraBonus() const { return m_extraBonus; } + Int getShotsPerBarrel() const { return m_shotsPerBarrel; } + Int getAntiMask() const { return m_antiMask; } + Bool isLeechRangeWeapon() const { return m_leechRangeWeapon; } + Bool isCapableOfFollowingWaypoint() const { return m_capableOfFollowingWaypoint; } + Bool isShowsAmmoPips() const { return m_isShowsAmmoPips; } + Bool isPlayFXWhenStealthed() const { return m_playFXWhenStealthed; } Bool shouldProjectileCollideWith( const Object* projectileLauncher, @@ -665,32 +665,32 @@ class Weapon : public MemoryPoolObject, Bool isLaser() const { return m_template->getLaserName().isNotEmpty(); } void createLaser( const Object *sourceObj, const Object *victimObj, const Coord3D *victimPos ); - inline const WeaponTemplate* getTemplate() const { return m_template; } - inline WeaponSlotType getWeaponSlot() const { return m_wslot; } - inline AsciiString getName() const { return m_template->getName(); } - inline UnsignedInt getLastShotFrame() const { return m_lastFireFrame; } ///< frame a shot was last fired on + const WeaponTemplate* getTemplate() const { return m_template; } + WeaponSlotType getWeaponSlot() const { return m_wslot; } + AsciiString getName() const { return m_template->getName(); } + UnsignedInt getLastShotFrame() const { return m_lastFireFrame; } ///< frame a shot was last fired on // If we are "reloading", then m_ammoInClip is a lie. It will say full. - inline UnsignedInt getRemainingAmmo() const { return (getStatus() == RELOADING_CLIP) ? 0 : m_ammoInClip; } - inline WeaponReloadType getReloadType() const { return m_template->getReloadType(); } - inline Bool getAutoReloadsClip() const { return m_template->getAutoReloadsClip(); } - inline Real getAimDelta() const { return m_template->getAimDelta(); } - inline Real getScatterRadius() const { return m_template->getScatterRadius(); } - inline Real getScatterTargetScalar() const { return m_template->getScatterTargetScalar(); } - inline Int getAntiMask() const { return m_template->getAntiMask(); } - inline Bool isCapableOfFollowingWaypoint() const { return m_template->isCapableOfFollowingWaypoint(); } - inline Int getContinuousFireOneShotsNeeded() const { return m_template->getContinuousFireOneShotsNeeded(); } - inline Int getContinuousFireTwoShotsNeeded() const { return m_template->getContinuousFireTwoShotsNeeded(); } - inline UnsignedInt getContinuousFireCoastFrames() const { return m_template->getContinuousFireCoastFrames(); } - 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 DamageType getDamageType() const { return m_template->getDamageType(); } - inline DeathType getDeathType() const { return m_template->getDeathType(); } - inline Real getContinueAttackRange() const { return m_template->getContinueAttackRange(); } - inline Bool isShowsAmmoPips() const { return m_template->isShowsAmmoPips(); } - inline Int getClipSize() const { return m_template->getClipSize(); } + UnsignedInt getRemainingAmmo() const { return (getStatus() == RELOADING_CLIP) ? 0 : m_ammoInClip; } + WeaponReloadType getReloadType() const { return m_template->getReloadType(); } + Bool getAutoReloadsClip() const { return m_template->getAutoReloadsClip(); } + Real getAimDelta() const { return m_template->getAimDelta(); } + Real getScatterRadius() const { return m_template->getScatterRadius(); } + Real getScatterTargetScalar() const { return m_template->getScatterTargetScalar(); } + Int getAntiMask() const { return m_template->getAntiMask(); } + Bool isCapableOfFollowingWaypoint() const { return m_template->isCapableOfFollowingWaypoint(); } + Int getContinuousFireOneShotsNeeded() const { return m_template->getContinuousFireOneShotsNeeded(); } + Int getContinuousFireTwoShotsNeeded() const { return m_template->getContinuousFireTwoShotsNeeded(); } + UnsignedInt getContinuousFireCoastFrames() const { return m_template->getContinuousFireCoastFrames(); } + UnsignedInt getAutoReloadWhenIdleFrames() const { return m_template->getAutoReloadWhenIdleFrames(); } + const AudioEventRTS& getFireSound() const { return m_template->getFireSound(); } + UnsignedInt getFireSoundLoopTime() const { return m_template->getFireSoundLoopTime(); } + DamageType getDamageType() const { return m_template->getDamageType(); } + DeathType getDeathType() const { return m_template->getDeathType(); } + Real getContinueAttackRange() const { return m_template->getContinueAttackRange(); } + Bool isShowsAmmoPips() const { return m_template->isShowsAmmoPips(); } + Int getClipSize() const { return m_template->getClipSize(); } // Contact weapons (like car bombs) need to basically collide with their target. - inline Bool isContactWeapon() const { return m_template->isContactWeapon(); } + Bool isContactWeapon() const { return m_template->isContactWeapon(); } UnsignedInt getClipReloadTime(const Object *source) const; @@ -818,7 +818,7 @@ class WeaponStore : public SubsystemInterface const WeaponTemplate *findWeaponTemplateByNameKey( NameKeyType key ) const { return findWeaponTemplatePrivate( key ); } // this dynamically allocates a new Weapon, which is owned (and must be freed!) by the caller. - inline Weapon* allocateNewWeapon(const WeaponTemplate *tmpl, WeaponSlotType wslot) const + Weapon* allocateNewWeapon(const WeaponTemplate *tmpl, WeaponSlotType wslot) const { return newInstance(Weapon)(tmpl, wslot); // my, that was easy } diff --git a/Generals/Code/GameEngine/Include/GameLogic/WeaponSet.h b/Generals/Code/GameEngine/Include/GameLogic/WeaponSet.h index c2e8ecefe6..eecd011a36 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/WeaponSet.h +++ b/Generals/Code/GameEngine/Include/GameLogic/WeaponSet.h @@ -116,7 +116,7 @@ class WeaponTemplateSet static void parsePreferredAgainst(INI* ini, void *instance, void *store, const void* userData); public: - inline WeaponTemplateSet() + WeaponTemplateSet() { clear(); } @@ -131,12 +131,12 @@ class WeaponTemplateSet Bool isWeaponLockSharedAcrossSets() const {return m_isWeaponLockSharedAcrossSets; } Bool hasAnyWeapons() const; - inline const WeaponTemplate* getNth(WeaponSlotType n) const { return m_template[n]; } - inline UnsignedInt getNthCommandSourceMask(WeaponSlotType n) const { return m_autoChooseMask[n]; } - inline const KindOfMaskType& getNthPreferredAgainstMask(WeaponSlotType n) const { return m_preferredAgainst[n]; } + const WeaponTemplate* getNth(WeaponSlotType n) const { return m_template[n]; } + UnsignedInt getNthCommandSourceMask(WeaponSlotType n) const { return m_autoChooseMask[n]; } + const KindOfMaskType& getNthPreferredAgainstMask(WeaponSlotType n) const { return m_preferredAgainst[n]; } - inline Int getConditionsYesCount() const { return 1; } - inline const WeaponSetFlags& getNthConditionsYes(Int i) const { return m_types; } + Int getConditionsYesCount() const { return 1; } + const WeaponSetFlags& getNthConditionsYes(Int i) const { return m_types; } #if defined(RTS_DEBUG) inline AsciiString getDescription() const { return "ArmorTemplateSet"; } #endif diff --git a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h index e94fa96159..4e0829dedd 100644 --- a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h +++ b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h @@ -134,7 +134,7 @@ class HeightMapRenderObjClass : public RenderObjClass, public DX8_CleanupHook ///allocate resources needed to render heightmap int initHeightData(Int width, Int height, WorldHeightMap *pMap, RefRenderObjListIterator *pLightsIterator); Int freeMapResources(void); ///< free resources used to render heightmap - inline UnsignedByte getClipHeight(Int x, Int y) const + UnsignedByte getClipHeight(Int x, Int y) const { Int xextent = m_map->getXExtent() - 1; Int yextent = m_map->getYExtent() - 1; diff --git a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h index 293ca4bc07..3db0b660f3 100644 --- a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h +++ b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h @@ -236,7 +236,7 @@ struct ModelConditionInfo PUBLIC_BONES_VALID = 0x0010 }; - inline ModelConditionInfo() + ModelConditionInfo() { clear(); } @@ -245,8 +245,8 @@ struct ModelConditionInfo void loadAnimations() const; void preloadAssets( TimeOfDay timeOfDay, Real scale ); ///< preload any assets for time of day - 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]; } + Int getConditionsYesCount() const { DEBUG_ASSERTCRASH(m_conditionsYesVec.size() > 0, ("empty m_conditionsYesVec.size(), see srj")); return m_conditionsYesVec.size(); } + const ModelConditionFlags& getNthConditionsYes(Int i) const { return m_conditionsYesVec[i]; } #if defined(RTS_DEBUG) inline AsciiString getDescription() const { return m_description; } #endif @@ -412,7 +412,7 @@ class W3DModelDraw : public DrawModule, public ObjectDrawInterface virtual const ObjectDrawInterface* getObjectDrawInterface() const { return this; } ///@todo: I had to make this public because W3DDevice needs access for casting shadows -MW - inline RenderObjClass *getRenderObject() { return m_renderObject; } + RenderObjClass *getRenderObject() { return m_renderObject; } virtual Bool updateBonesForClientParticleSystems( void );///< this will reposition particle systems on the fly ML virtual void onDrawableBoundToObject(); @@ -423,7 +423,7 @@ class W3DModelDraw : public DrawModule, public ObjectDrawInterface virtual void onRenderObjRecreated(void){}; - inline const ModelConditionInfo* getCurState() const { return m_curState; } + const ModelConditionInfo* getCurState() const { return m_curState; } void setModelState(const ModelConditionInfo* newState); const ModelConditionInfo* findBestInfo(const ModelConditionFlags& c) const; @@ -438,7 +438,7 @@ class W3DModelDraw : public DrawModule, public ObjectDrawInterface Bool setCurAnimDurationInMsec(Real duration); - inline Bool getFullyObscuredByShroud() const { return m_fullyObscuredByShroud; } + Bool getFullyObscuredByShroud() const { return m_fullyObscuredByShroud; } private: diff --git a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DShadow.h b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DShadow.h index 16d8b46667..da0a942acd 100644 --- a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DShadow.h +++ b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DShadow.h @@ -52,8 +52,8 @@ class W3DShadowManager void invalidateCachedLightPositions(void); ///m_width) m_drawWidthX = m_width;} - inline void setDrawHeight(Int height) {m_drawHeightY = height; if (m_drawHeightY>m_height) m_drawHeightY = m_height;} - inline Int getBorderSize(void) {return m_borderSize;} + Int getDrawOrgX(void) {return m_drawOriginX;} + Int getDrawOrgY(void) {return m_drawOriginY;} + + Int getDrawWidth(void) {return m_drawWidthX;} + Int getDrawHeight(void) {return m_drawHeightY;} + void setDrawWidth(Int width) {m_drawWidthX = width; if (m_drawWidthX>m_width) m_drawWidthX = m_width;} + void setDrawHeight(Int height) {m_drawHeightY = height; if (m_drawHeightY>m_height) m_drawHeightY = m_height;} + Int getBorderSize(void) {return m_borderSize;} /// Get height with the offset that HeightMapRenderObjClass uses built in. - inline UnsignedByte getDisplayHeight(Int x, Int y) { return m_data[x+m_drawOriginX+m_width*(y+m_drawOriginY)];} + UnsignedByte getDisplayHeight(Int x, Int y) { return m_data[x+m_drawOriginX+m_width*(y+m_drawOriginY)];} /// Get height in normal coordinates. - inline UnsignedByte getHeight(Int xIndex, Int yIndex) + UnsignedByte getHeight(Int xIndex, Int yIndex) { Int ndx = (yIndex*m_width)+xIndex; if ((ndx>=0) && (ndx> 16) & 0xff) / 255.0f; green = ((c >> 8) & 0xff) / 255.0f; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8fvf.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8fvf.h index a7adf40f71..dc004e925b 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8fvf.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8fvf.h @@ -260,22 +260,22 @@ class FVFInfoClass : public W3DMPO public: FVFInfoClass(unsigned FVF); - inline unsigned Get_Location_Offset() const { return location_offset; } - inline unsigned Get_Normal_Offset() const { return normal_offset; } + unsigned Get_Location_Offset() const { return location_offset; } + unsigned Get_Normal_Offset() const { return normal_offset; } #ifdef WWDEBUG inline unsigned Get_Tex_Offset(unsigned int n) const { WWASSERT(n>SHIFT_DEPTHCOMPARE); } - inline DepthMaskType Get_Depth_Mask(void) const { return (DepthMaskType)((ShaderBits&MASK_DEPTHMASK)>>SHIFT_DEPTHMASK); } - inline ColorMaskType Get_Color_Mask(void) const { return (ColorMaskType)((ShaderBits&MASK_COLORMASK)>>SHIFT_COLORMASK); } - inline DetailAlphaFuncType Get_Post_Detail_Alpha_Func(void) const { return (DetailAlphaFuncType)((ShaderBits&MASK_POSTDETAILALPHAFUNC)>>SHIFT_POSTDETAILALPHAFUNC); } - inline DetailColorFuncType Get_Post_Detail_Color_Func(void) const { return (DetailColorFuncType)((ShaderBits&MASK_POSTDETAILCOLORFUNC)>>SHIFT_POSTDETAILCOLORFUNC); } - inline AlphaTestType Get_Alpha_Test(void) const { return (AlphaTestType)((ShaderBits&MASK_ALPHATEST)>>SHIFT_ALPHATEST); } - inline CullModeType Get_Cull_Mode(void) const { return (CullModeType)((ShaderBits&MASK_CULLMODE)>>SHIFT_CULLMODE); } - inline DstBlendFuncType Get_Dst_Blend_Func(void) const { return (DstBlendFuncType)((ShaderBits&MASK_DSTBLEND)>>SHIFT_DSTBLEND); } - inline FogFuncType Get_Fog_Func(void) const { return (FogFuncType)((ShaderBits&MASK_FOG)>>SHIFT_FOG); } - inline PriGradientType Get_Primary_Gradient(void) const { return (PriGradientType)((ShaderBits&MASK_PRIGRADIENT)>>SHIFT_PRIGRADIENT); } - inline SecGradientType Get_Secondary_Gradient(void) const { return (SecGradientType)((ShaderBits&MASK_SECGRADIENT)>>SHIFT_SECGRADIENT); } - inline SrcBlendFuncType Get_Src_Blend_Func(void) const { return (SrcBlendFuncType)((ShaderBits&MASK_SRCBLEND)>>SHIFT_SRCBLEND); } - inline TexturingType Get_Texturing(void) const { return (TexturingType)((ShaderBits&MASK_TEXTURING)>>SHIFT_TEXTURING); } - inline NPatchEnableType Get_NPatch_Enable(void) const { return (NPatchEnableType)((ShaderBits&MASK_NPATCHENABLE)>>SHIFT_NPATCHENABLE); } - - inline void Set_Depth_Compare(DepthCompareType x) { ShaderBits&=~MASK_DEPTHCOMPARE;ShaderBits|=(x<>SHIFT_DEPTHCOMPARE); } + DepthMaskType Get_Depth_Mask(void) const { return (DepthMaskType)((ShaderBits&MASK_DEPTHMASK)>>SHIFT_DEPTHMASK); } + ColorMaskType Get_Color_Mask(void) const { return (ColorMaskType)((ShaderBits&MASK_COLORMASK)>>SHIFT_COLORMASK); } + DetailAlphaFuncType Get_Post_Detail_Alpha_Func(void) const { return (DetailAlphaFuncType)((ShaderBits&MASK_POSTDETAILALPHAFUNC)>>SHIFT_POSTDETAILALPHAFUNC); } + DetailColorFuncType Get_Post_Detail_Color_Func(void) const { return (DetailColorFuncType)((ShaderBits&MASK_POSTDETAILCOLORFUNC)>>SHIFT_POSTDETAILCOLORFUNC); } + AlphaTestType Get_Alpha_Test(void) const { return (AlphaTestType)((ShaderBits&MASK_ALPHATEST)>>SHIFT_ALPHATEST); } + CullModeType Get_Cull_Mode(void) const { return (CullModeType)((ShaderBits&MASK_CULLMODE)>>SHIFT_CULLMODE); } + DstBlendFuncType Get_Dst_Blend_Func(void) const { return (DstBlendFuncType)((ShaderBits&MASK_DSTBLEND)>>SHIFT_DSTBLEND); } + FogFuncType Get_Fog_Func(void) const { return (FogFuncType)((ShaderBits&MASK_FOG)>>SHIFT_FOG); } + PriGradientType Get_Primary_Gradient(void) const { return (PriGradientType)((ShaderBits&MASK_PRIGRADIENT)>>SHIFT_PRIGRADIENT); } + SecGradientType Get_Secondary_Gradient(void) const { return (SecGradientType)((ShaderBits&MASK_SECGRADIENT)>>SHIFT_SECGRADIENT); } + SrcBlendFuncType Get_Src_Blend_Func(void) const { return (SrcBlendFuncType)((ShaderBits&MASK_SRCBLEND)>>SHIFT_SRCBLEND); } + TexturingType Get_Texturing(void) const { return (TexturingType)((ShaderBits&MASK_TEXTURING)>>SHIFT_TEXTURING); } + NPatchEnableType Get_NPatch_Enable(void) const { return (NPatchEnableType)((ShaderBits&MASK_NPATCHENABLE)>>SHIFT_NPATCHENABLE); } + + void Set_Depth_Compare(DepthCompareType x) { ShaderBits&=~MASK_DEPTHCOMPARE;ShaderBits|=(x<=first && cur<=second) is = true; if (cur<=first && cur>=second) is = true; diff --git a/GeneralsMD/Code/GameEngine/Include/Common/BitFlags.h b/GeneralsMD/Code/GameEngine/Include/Common/BitFlags.h index fccf3c2ed9..84b2ec0b70 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/BitFlags.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/BitFlags.h @@ -63,29 +63,29 @@ class BitFlags kInit = 0 }; - inline BitFlags() + BitFlags() { } - inline BitFlags(BogusInitType k, Int idx1) + BitFlags(BogusInitType k, Int idx1) { m_bits.set(idx1); } - inline BitFlags(BogusInitType k, Int idx1, Int idx2) + BitFlags(BogusInitType k, Int idx1, Int idx2) { m_bits.set(idx1); m_bits.set(idx2); } - inline BitFlags(BogusInitType k, Int idx1, Int idx2, Int idx3) + BitFlags(BogusInitType k, Int idx1, Int idx2, Int idx3) { m_bits.set(idx1); m_bits.set(idx2); m_bits.set(idx3); } - inline BitFlags(BogusInitType k, Int idx1, Int idx2, Int idx3, Int idx4) + BitFlags(BogusInitType k, Int idx1, Int idx2, Int idx3, Int idx4) { m_bits.set(idx1); m_bits.set(idx2); @@ -93,7 +93,7 @@ class BitFlags m_bits.set(idx4); } - inline BitFlags(BogusInitType k, Int idx1, Int idx2, Int idx3, Int idx4, Int idx5) + BitFlags(BogusInitType k, Int idx1, Int idx2, Int idx3, Int idx4, Int idx5) { m_bits.set(idx1); m_bits.set(idx2); @@ -102,7 +102,7 @@ class BitFlags m_bits.set(idx5); } - inline BitFlags(BogusInitType k, + BitFlags(BogusInitType k, Int idx1, Int idx2, Int idx3, @@ -131,28 +131,28 @@ class BitFlags m_bits.set(idx12); } - inline Bool operator==(const BitFlags& that) const + Bool operator==(const BitFlags& that) const { return this->m_bits == that.m_bits; } - inline Bool operator!=(const BitFlags& that) const + Bool operator!=(const BitFlags& that) const { return this->m_bits != that.m_bits; } - inline void set(Int i, Int val = 1) + void set(Int i, Int val = 1) { m_bits.set(i, val); } - inline Bool test(Int i) const + Bool test(Int i) const { return m_bits.test(i); } //Tests for any bits that are set in both. - inline Bool testForAny( const BitFlags& that ) const + Bool testForAny( const BitFlags& that ) const { BitFlags tmp = *this; tmp.m_bits &= that.m_bits; @@ -160,7 +160,7 @@ class BitFlags } //All argument bits must be set in our bits too in order to return TRUE - inline Bool testForAll( const BitFlags& that ) const + Bool testForAll( const BitFlags& that ) const { DEBUG_ASSERTCRASH( that.any(), ("BitFlags::testForAll is always true if you ask about zero flags. Did you mean that?") ); @@ -171,46 +171,46 @@ class BitFlags } //None of the argument bits must be set in our bits in order to return TRUE - inline Bool testForNone( const BitFlags& that ) const + Bool testForNone( const BitFlags& that ) const { BitFlags tmp = *this; tmp.m_bits &= that.m_bits; return !tmp.m_bits.any(); } - inline Int size() const + Int size() const { return m_bits.size(); } - inline Int count() const + Int count() const { return m_bits.count(); } - inline Bool any() const + Bool any() const { return m_bits.any(); } - inline void flip() + void flip() { m_bits.flip(); } - inline void clear() + void clear() { m_bits.reset(); } - inline Int countIntersection(const BitFlags& that) const + Int countIntersection(const BitFlags& that) const { BitFlags tmp = *this; tmp.m_bits &= that.m_bits; return tmp.m_bits.count(); } - inline Int countInverseIntersection(const BitFlags& that) const + Int countInverseIntersection(const BitFlags& that) const { BitFlags tmp = *this; tmp.m_bits.flip(); @@ -218,7 +218,7 @@ class BitFlags return tmp.m_bits.count(); } - inline Bool anyIntersectionWith(const BitFlags& that) const + Bool anyIntersectionWith(const BitFlags& that) const { /// @todo srj -- improve me. BitFlags tmp = that; @@ -226,23 +226,23 @@ class BitFlags return tmp.m_bits.any(); } - inline void clear(const BitFlags& clr) + void clear(const BitFlags& clr) { m_bits &= ~clr.m_bits; } - inline void set(const BitFlags& set) + void set(const BitFlags& set) { m_bits |= set.m_bits; } - inline void clearAndSet(const BitFlags& clr, const BitFlags& set) + void clearAndSet(const BitFlags& clr, const BitFlags& set) { m_bits &= ~clr.m_bits; m_bits |= set.m_bits; } - inline Bool testSetAndClear(const BitFlags& mustBeSet, const BitFlags& mustBeClear) const + Bool testSetAndClear(const BitFlags& mustBeSet, const BitFlags& mustBeClear) const { /// @todo srj -- improve me. BitFlags tmp = *this; diff --git a/GeneralsMD/Code/GameEngine/Include/Common/BuildAssistant.h b/GeneralsMD/Code/GameEngine/Include/Common/BuildAssistant.h index 23dad11fca..f56792d282 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/BuildAssistant.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/BuildAssistant.h @@ -174,7 +174,7 @@ class BuildAssistant : public SubsystemInterface Object *builderObject ); /// return the "scratch pad" array that can be used to create a line of build locations - virtual inline Coord3D *getBuildLocations( void ) { return m_buildPositions; } + virtual Coord3D *getBuildLocations( void ) { return m_buildPositions; } /// is the template a line build object, like a wall virtual Bool isLineBuildTemplate( const ThingTemplate *tTemplate ); diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Dict.h b/GeneralsMD/Code/GameEngine/Include/Common/Dict.h index 8ce7f08680..295ffd2fae 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/Dict.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/Dict.h @@ -125,7 +125,7 @@ class Dict /** Return there is a pair with the given key and datatype, return true. */ - inline Bool known(NameKeyType key, DataType d) const + Bool known(NameKeyType key, DataType d) const { return getType(key) == d; } @@ -278,17 +278,17 @@ class Dict DictPairKeyType m_key; void* m_value; - inline static DictPairKeyType createKey(NameKeyType keyVal, DataType nt) + static DictPairKeyType createKey(NameKeyType keyVal, DataType nt) { return (DictPairKeyType)((((UnsignedInt)(keyVal)) << 8) | ((UnsignedInt)nt)); } - inline static DataType getTypeFromKey(DictPairKeyType nk) + static DataType getTypeFromKey(DictPairKeyType nk) { return (DataType)(((UnsignedInt)nk) & 0xff); } - inline static NameKeyType getNameFromKey(DictPairKeyType nk) + static NameKeyType getNameFromKey(DictPairKeyType nk) { return (NameKeyType)(((UnsignedInt)nk) >> 8); } @@ -298,13 +298,13 @@ class Dict void clear(); void copyFrom(DictPair* that); void setNameAndType(NameKeyType key, DataType type); - inline DataType getType() const { return getTypeFromKey(m_key); } - inline NameKeyType getName() const { return getNameFromKey(m_key); } - inline Bool* asBool() { return (Bool*)&m_value; } - inline Int* asInt() { return (Int*)&m_value; } - inline Real* asReal() { return (Real*)&m_value; } - inline AsciiString* asAsciiString() { return (AsciiString*)&m_value; } - inline UnicodeString* asUnicodeString() { return (UnicodeString*)&m_value; } + DataType getType() const { return getTypeFromKey(m_key); } + NameKeyType getName() const { return getNameFromKey(m_key); } + Bool* asBool() { return (Bool*)&m_value; } + Int* asInt() { return (Int*)&m_value; } + Real* asReal() { return (Real*)&m_value; } + AsciiString* asAsciiString() { return (AsciiString*)&m_value; } + UnicodeString* asUnicodeString() { return (UnicodeString*)&m_value; } }; struct DictPairData @@ -314,13 +314,13 @@ class Dict unsigned short m_numPairsUsed; // length of data allocated //DictPair m_pairs[]; - inline DictPair* peek() { return (DictPair*)(this+1); } + DictPair* peek() { return (DictPair*)(this+1); } }; #ifdef RTS_DEBUG void validate() const; #else - inline void validate() const { } + void validate() const { } #endif }; diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Geometry.h b/GeneralsMD/Code/GameEngine/Include/Common/Geometry.h index c5ce3cbff1..fa4fccad23 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/Geometry.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/Geometry.h @@ -119,30 +119,30 @@ class GeometryInfo : public Snapshot void set(GeometryType type, Bool isSmall, Real height, Real majorRadius, Real minorRadius); // bleah, icky but needed for legacy code - inline void setMajorRadius(Real majorRadius) + void setMajorRadius(Real majorRadius) { m_majorRadius = majorRadius; calcBoundingStuff(); } // bleah, icky but needed for legacy code - inline void setMinorRadius(Real minorRadius) + void setMinorRadius(Real minorRadius) { m_minorRadius = minorRadius; calcBoundingStuff(); } - inline GeometryType getGeomType() const { return m_type; } - inline Bool getIsSmall() const { return m_isSmall; } - inline Real getMajorRadius() const { return m_majorRadius; } // x-axis - inline Real getMinorRadius() const { return m_minorRadius; } // y-axis + GeometryType getGeomType() const { return m_type; } + Bool getIsSmall() const { return m_isSmall; } + Real getMajorRadius() const { return m_majorRadius; } // x-axis + Real getMinorRadius() const { return m_minorRadius; } // y-axis // this has been removed and should never need to be called... // you should generally call getMaxHeightAbovePosition() instead. (srj) //inline Real getGeomHeight() const { return m_height; } // z-axis - inline Real getBoundingCircleRadius() const { return m_boundingCircleRadius; } - inline Real getBoundingSphereRadius() const { return m_boundingSphereRadius; } + Real getBoundingCircleRadius() const { return m_boundingCircleRadius; } + Real getBoundingSphereRadius() const { return m_boundingSphereRadius; } Bool isIntersectedByLineSegment(const Coord3D& loc, const Coord3D& from, const Coord3D& to) const; diff --git a/GeneralsMD/Code/GameEngine/Include/Common/INI.h b/GeneralsMD/Code/GameEngine/Include/Common/INI.h index 3268152780..613cae1406 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/INI.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/INI.h @@ -116,7 +116,7 @@ struct FieldParse const void* userData; ///< field-specific data Int offset; ///< offset to data field - inline void set(const char* t, INIFieldParseProc p, const void* u, Int o) + void set(const char* t, INIFieldParseProc p, const void* u, Int o) { token = t; parse = p; @@ -144,9 +144,9 @@ class MultiIniFieldParse void add(const FieldParse* f, UnsignedInt e = 0); - inline Int getCount() const { return m_count; } - inline const FieldParse* getNthFieldParse(Int i) const { return m_fieldParse[i]; } - inline UnsignedInt getNthExtraOffset(Int i) const { return m_extraOffset[i]; } + Int getCount() const { return m_count; } + const FieldParse* getNthFieldParse(Int i) const { return m_fieldParse[i]; } + UnsignedInt getNthExtraOffset(Int i) const { return m_extraOffset[i]; } }; //------------------------------------------------------------------------------------------------- @@ -248,14 +248,14 @@ class INI static void parseWindowTransitions( INI* ini ); static void parseChallengeModeDefinition( INI* ini ); - inline AsciiString getFilename( void ) const { return m_filename; } - inline INILoadType getLoadType( void ) const { return m_loadType; } - inline UnsignedInt getLineNum( void ) const { return m_lineNum; } - inline const char *getSeps( void ) const { return m_seps; } - inline const char *getSepsPercent( void ) const { return m_sepsPercent; } - inline const char *getSepsColon( void ) const { return m_sepsColon; } - inline const char *getSepsQuote( void ) { return m_sepsQuote; } - inline Bool isEOF( void ) const { return m_endOfFile; } + AsciiString getFilename( void ) const { return m_filename; } + INILoadType getLoadType( void ) const { return m_loadType; } + UnsignedInt getLineNum( void ) const { return m_lineNum; } + const char *getSeps( void ) const { return m_seps; } + const char *getSepsPercent( void ) const { return m_sepsPercent; } + const char *getSepsColon( void ) const { return m_sepsColon; } + const char *getSepsQuote( void ) { return m_sepsQuote; } + Bool isEOF( void ) const { return m_endOfFile; } void initFromINI( void *what, const FieldParse* parseTable ); void initFromINIMulti( void *what, const MultiIniFieldParse& parseTableList ); diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Module.h b/GeneralsMD/Code/GameEngine/Include/Common/Module.h index 0c4619a9de..e6ea3dd33c 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/Module.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/Module.h @@ -192,7 +192,7 @@ class Module : public MemoryPoolObject, virtual NameKeyType getModuleNameKey() const = 0; - inline NameKeyType getModuleTagNameKey() const { return getModuleData()->getModuleTagNameKey(); } + NameKeyType getModuleTagNameKey() const { return getModuleData()->getModuleTagNameKey(); } /** this is called after all the Modules for a given Thing are created; it allows Modules to resolve any inter-Module dependencies. @@ -214,7 +214,7 @@ class Module : public MemoryPoolObject, protected: - inline const ModuleData* getModuleData() const { return m_moduleData; } + const ModuleData* getModuleData() const { return m_moduleData; } virtual void crc( Xfer *xfer ); virtual void xfer( Xfer *xfer ); @@ -252,8 +252,8 @@ class ObjectModule : public Module protected: - inline Object *getObject() { return m_object; } - inline const Object *getObject() const { return m_object; } + Object *getObject() { return m_object; } + const Object *getObject() const { return m_object; } virtual void crc( Xfer *xfer ); virtual void xfer( Xfer *xfer ); @@ -295,8 +295,8 @@ class DrawableModule : public Module protected: - inline Drawable *getDrawable() { return m_drawable; } - inline const Drawable *getDrawable() const { return m_drawable; } + Drawable *getDrawable() { return m_drawable; } + const Drawable *getDrawable() const { return m_drawable; } virtual void crc( Xfer *xfer ); virtual void xfer( Xfer *xfer ); diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Money.h b/GeneralsMD/Code/GameEngine/Include/Common/Money.h index 02e65002b7..4789fa9301 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/Money.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/Money.h @@ -61,7 +61,7 @@ class Money : public Snapshot public: - inline Money() : m_playerIndex(0) + Money() : m_playerIndex(0) { init(); } @@ -71,7 +71,7 @@ class Money : public Snapshot setStartingCash(0); } - inline UnsignedInt countMoney() const + UnsignedInt countMoney() const { return m_money; } diff --git a/GeneralsMD/Code/GameEngine/Include/Common/MultiplayerSettings.h b/GeneralsMD/Code/GameEngine/Include/Common/MultiplayerSettings.h index 7518ef2660..9590ffda76 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/MultiplayerSettings.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/MultiplayerSettings.h @@ -46,11 +46,11 @@ class MultiplayerColorDefinition static const FieldParse m_colorFieldParseTable[]; ///< the parse table for INI definition const FieldParse *getFieldParse( void ) const { return m_colorFieldParseTable; } - inline AsciiString getTooltipName(void) const { return m_tooltipName; }; - inline RGBColor getRGBValue(void) const { return m_rgbValue; }; - inline RGBColor getRGBNightValue(void) const { return m_rgbValueNight; }; - inline Color getColor(void) const { return m_color; } - inline Color getNightColor(void) const { return m_colorNight; } + AsciiString getTooltipName(void) const { return m_tooltipName; }; + RGBColor getRGBValue(void) const { return m_rgbValue; }; + RGBColor getRGBNightValue(void) const { return m_rgbValueNight; }; + Color getColor(void) const { return m_color; } + Color getNightColor(void) const { return m_colorNight; } void setColor( RGBColor rgb ); void setNightColor( RGBColor rgb ); @@ -92,14 +92,14 @@ class MultiplayerSettings : public SubsystemInterface MultiplayerColorDefinition * findMultiplayerColorDefinitionByName(AsciiString name); MultiplayerColorDefinition * newMultiplayerColorDefinition(AsciiString name); - inline Int getStartCountdownTimerSeconds( void ) { return m_startCountdownTimerSeconds; } - inline Int getMaxBeaconsPerPlayer( void ) { return m_maxBeaconsPerPlayer; } - inline Bool isShroudInMultiplayer( void ) { return m_isShroudInMultiplayer; } - inline Bool showRandomPlayerTemplate( void ) { return m_showRandomPlayerTemplate; } - inline Bool showRandomStartPos( void ) { return m_showRandomStartPos; } - inline Bool showRandomColor( void ) { return m_showRandomColor; } + Int getStartCountdownTimerSeconds( void ) { return m_startCountdownTimerSeconds; } + Int getMaxBeaconsPerPlayer( void ) { return m_maxBeaconsPerPlayer; } + Bool isShroudInMultiplayer( void ) { return m_isShroudInMultiplayer; } + Bool showRandomPlayerTemplate( void ) { return m_showRandomPlayerTemplate; } + Bool showRandomStartPos( void ) { return m_showRandomStartPos; } + Bool showRandomColor( void ) { return m_showRandomColor; } - inline Int getNumColors( void ) + Int getNumColors( void ) { if (m_numColors == 0) { m_numColors = m_colorList.size(); diff --git a/GeneralsMD/Code/GameEngine/Include/Common/NameKeyGenerator.h b/GeneralsMD/Code/GameEngine/Include/Common/NameKeyGenerator.h index bc98672b29..a95e000132 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/NameKeyGenerator.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/NameKeyGenerator.h @@ -153,5 +153,5 @@ class StaticNameKey StaticNameKey(const char* p) : m_key(NAMEKEY_INVALID), m_name(p) {} NameKeyType key() const; // ugh, this is a little hokey, but lets us pretend that a StaticNameKey == NameKeyType - inline operator NameKeyType() const { return key(); } + operator NameKeyType() const { return key(); } }; diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Player.h b/GeneralsMD/Code/GameEngine/Include/Common/Player.h index bfe2f34a27..ac292248cd 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/Player.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/Player.h @@ -220,43 +220,43 @@ class Player : public Snapshot void deletePlayerAI(); - inline UnicodeString getPlayerDisplayName() { return m_playerDisplayName; } - inline NameKeyType getPlayerNameKey() const { return m_playerNameKey; } + UnicodeString getPlayerDisplayName() { return m_playerDisplayName; } + NameKeyType getPlayerNameKey() const { return m_playerNameKey; } - inline AsciiString getSide() const { return m_side; } - inline AsciiString getBaseSide() const { return m_baseSide; } + AsciiString getSide() const { return m_side; } + AsciiString getBaseSide() const { return m_baseSide; } - inline const PlayerTemplate* getPlayerTemplate() const { return m_playerTemplate; } + const PlayerTemplate* getPlayerTemplate() const { return m_playerTemplate; } /// return the Player's Handicap sub-object - inline const Handicap *getHandicap() const { return &m_handicap; } - inline Handicap *getHandicap() { return &m_handicap; } + const Handicap *getHandicap() const { return &m_handicap; } + Handicap *getHandicap() { return &m_handicap; } /// return the Player's Money sub-object - inline Money *getMoney() { return &m_money; } - inline const Money *getMoney() const { return &m_money; } + Money *getMoney() { return &m_money; } + const Money *getMoney() const { return &m_money; } UnsignedInt getSupplyBoxValue();///< Many things can affect the alue of a crate, but at heart it is a GlobalData ratio. - inline Energy *getEnergy() { return &m_energy; } - inline const Energy *getEnergy() const { return &m_energy; } + Energy *getEnergy() { return &m_energy; } + const Energy *getEnergy() const { return &m_energy; } // adds a power bonus to this player because of energy upgrade at his power plants - inline void addPowerBonus(Object *obj) { m_energy.addPowerBonus(obj); } - inline void removePowerBonus(Object *obj) { m_energy.removePowerBonus(obj); } + void addPowerBonus(Object *obj) { m_energy.addPowerBonus(obj); } + void removePowerBonus(Object *obj) { m_energy.removePowerBonus(obj); } - inline ResourceGatheringManager *getResourceGatheringManager(){ return m_resourceGatheringManager; } - inline TunnelTracker* getTunnelSystem(){ return m_tunnelSystem; } + ResourceGatheringManager *getResourceGatheringManager(){ return m_resourceGatheringManager; } + TunnelTracker* getTunnelSystem(){ return m_tunnelSystem; } - inline Color getPlayerColor() const { return m_color; } - inline Color getPlayerNightColor() const { return m_nightColor;} + Color getPlayerColor() const { return m_color; } + Color getPlayerNightColor() const { return m_nightColor;} /// return the type of controller - inline PlayerType getPlayerType() const { return m_playerType; } + PlayerType getPlayerType() const { return m_playerType; } void setPlayerType(PlayerType t, Bool skirmish); - inline PlayerIndex getPlayerIndex() const { return m_playerIndex; } + PlayerIndex getPlayerIndex() const { return m_playerIndex; } /// return a bitmask that is unique to this player. - inline PlayerMaskType getPlayerMask() const { return 1 << m_playerIndex; } + PlayerMaskType getPlayerMask() const { return 1 << m_playerIndex; } /// a convenience function to test the ThingTemplate against the players canBuild flags /// called by canBuild @@ -552,9 +552,9 @@ class Player : public Snapshot void removeTeamFromList(TeamPrototype* team); typedef std::list PlayerTeamList; - inline const PlayerTeamList* getPlayerTeams() const { return &m_playerTeamPrototypes; } + const PlayerTeamList* getPlayerTeams() const { return &m_playerTeamPrototypes; } - inline Int getMpStartIndex(void) {return m_mpStartIndex;} + Int getMpStartIndex(void) {return m_mpStartIndex;} /// Set that all units should begin hunting. void setUnitsShouldHunt(Bool unitsShouldHunt, CommandSourceType source); diff --git a/GeneralsMD/Code/GameEngine/Include/Common/PlayerTemplate.h b/GeneralsMD/Code/GameEngine/Include/Common/PlayerTemplate.h index 032e1a5d0f..a7839093fe 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/PlayerTemplate.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/PlayerTemplate.h @@ -74,36 +74,36 @@ class PlayerTemplate PlayerTemplate(); - inline void setNameKey(NameKeyType namekey) { m_nameKey = namekey; } + void setNameKey(NameKeyType namekey) { m_nameKey = namekey; } - inline NameKeyType getNameKey() const { DEBUG_ASSERTCRASH(m_nameKey != NAMEKEY_INVALID, ("bad namekey")); return m_nameKey; } - inline AsciiString getName() const { return KEYNAME(m_nameKey); } + NameKeyType getNameKey() const { DEBUG_ASSERTCRASH(m_nameKey != NAMEKEY_INVALID, ("bad namekey")); return m_nameKey; } + AsciiString getName() const { return KEYNAME(m_nameKey); } - inline UnicodeString getDisplayName() const { return m_displayName; } + UnicodeString getDisplayName() const { return m_displayName; } - inline AsciiString getSide() const { return m_side; } - inline AsciiString getBaseSide() const { return m_baseSide; } + AsciiString getSide() const { return m_side; } + AsciiString getBaseSide() const { return m_baseSide; } /// return the tech tree for the player. - inline const Handicap *getHandicap() const { return &m_handicap; } + const Handicap *getHandicap() const { return &m_handicap; } /// return the money for the player. - inline const Money *getMoney() const { return &m_money; } + const Money *getMoney() const { return &m_money; } - inline const RGBColor* getPreferredColor() const { return &m_preferredColor; } + const RGBColor* getPreferredColor() const { return &m_preferredColor; } - inline AsciiString getStartingBuilding( void ) const { return m_startingBuilding; } + AsciiString getStartingBuilding( void ) const { return m_startingBuilding; } AsciiString getStartingUnit( Int i ) const; - inline const ProductionChangeMap& getProductionCostChanges() const { return m_productionCostChanges; } - inline const ProductionChangeMap& getProductionTimeChanges() const { return m_productionTimeChanges; } - inline const ProductionVeterancyMap& getProductionVeterancyLevels() const { return m_productionVeterancyLevels; } - inline Bool isObserver() const { return m_observer; } - inline Bool isPlayableSide() const { return m_playableSide; } + const ProductionChangeMap& getProductionCostChanges() const { return m_productionCostChanges; } + const ProductionChangeMap& getProductionTimeChanges() const { return m_productionTimeChanges; } + const ProductionVeterancyMap& getProductionVeterancyLevels() const { return m_productionVeterancyLevels; } + Bool isObserver() const { return m_observer; } + Bool isPlayableSide() const { return m_playableSide; } - inline AsciiString getScoreScreen (void ) const { return m_scoreScreenImage; } - inline AsciiString getLoadScreen (void ) const { return m_loadScreenImage; } - inline AsciiString getBeaconTemplate( void ) const { return m_beaconTemplate; } + AsciiString getScoreScreen (void ) const { return m_scoreScreenImage; } + AsciiString getLoadScreen (void ) const { return m_loadScreenImage; } + AsciiString getBeaconTemplate( void ) const { return m_beaconTemplate; } const Image *getHeadWaterMarkImage( void ) const; const Image *getFlagWaterMarkImage( void ) const; @@ -113,8 +113,8 @@ class PlayerTemplate //const Image *getPushedImage( void ) const; const Image *getSideIconImage( void ) const; const Image *getGeneralImage( void ) const; - inline const AsciiString getTooltip() const { return m_tooltip; } - inline const AsciiString getGeneralFeatures( void ) const { return m_strGeneralFeatures; } + const AsciiString getTooltip() const { return m_tooltip; } + const AsciiString getGeneralFeatures( void ) const { return m_strGeneralFeatures; } AsciiString getMedallionNormal() const { return m_strMedallionNormal; } AsciiString getMedallionHilite() const { return m_strMedallionHilite; } @@ -133,7 +133,7 @@ class PlayerTemplate AsciiString getLoadScreenMusic( void ) const {return m_loadScreenMusic; } AsciiString getScoreScreenMusic() const { return m_scoreScreenMusic; } - inline Bool isOldFaction( void ) const { return m_oldFaction; } + Bool isOldFaction( void ) const { return m_oldFaction; } static const FieldParse* getFieldParse(); @@ -215,7 +215,7 @@ class PlayerTemplateStore : public SubsystemInterface const PlayerTemplate* getNthPlayerTemplate(Int i) const; const PlayerTemplate* findPlayerTemplate(NameKeyType namekey) const; - inline Int getPlayerTemplateCount() const { return m_playerTemplates.size(); } + Int getPlayerTemplateCount() const { return m_playerTemplates.size(); } Int getTemplateNumByName(AsciiString name) const; // This function will fill outStringList with all the sides found in all the templates diff --git a/GeneralsMD/Code/GameEngine/Include/Common/SparseMatchFinder.h b/GeneralsMD/Code/GameEngine/Include/Common/SparseMatchFinder.h index c85dc0c618..829c0cb4de 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/SparseMatchFinder.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/SparseMatchFinder.h @@ -111,13 +111,13 @@ class SparseMatchFinder //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- - inline static Int countConditionIntersection(const BITSET& a, const BITSET& b) + static Int countConditionIntersection(const BITSET& a, const BITSET& b) { return a.countIntersection(b); } //------------------------------------------------------------------------------------------------- - inline static Int countConditionInverseIntersection(const BITSET& a, const BITSET& b) + static Int countConditionInverseIntersection(const BITSET& a, const BITSET& b) { return a.countInverseIntersection(b); } diff --git a/GeneralsMD/Code/GameEngine/Include/Common/StateMachine.h b/GeneralsMD/Code/GameEngine/Include/Common/StateMachine.h index 4d62c8c546..c23f802362 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/StateMachine.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/StateMachine.h @@ -153,8 +153,8 @@ class State : public MemoryPoolObject, public Snapshot //Definition of busy -- when explicitly in the busy state. Moving or attacking is not considered busy! virtual Bool isBusy() const { return false; } - inline StateMachine* getMachine() { return m_machine; } ///< return the machine this state is part of - inline StateID getID() const { return m_ID; } ///< get this state's id + StateMachine* getMachine() { return m_machine; } ///< return the machine this state is part of + StateID getID() const { return m_ID; } ///< get this state's id Object* getMachineOwner(); const Object* getMachineOwner() const; @@ -168,7 +168,7 @@ class State : public MemoryPoolObject, public Snapshot #endif // for internal use by the StateMachine class --------------------------------------------------------- - inline void friend_setID( StateID id ) { m_ID = id; } ///< define this state's id (for use only by StateMachine class) + void friend_setID( StateID id ) { m_ID = id; } ///< define this state's id (for use only by StateMachine class) void friend_onSuccess( StateID toStateID ) { m_successStateID = toStateID; } ///< define which state to move to after successful completion void friend_onFailure( StateID toStateID ) { m_failureStateID = toStateID; } ///< define which state to move to after failure void friend_onCondition( StateTransFuncPtr test, StateID toStateID, void* userData, const char* description = NULL ); ///< define when to change state @@ -330,8 +330,8 @@ class StateMachine : public MemoryPoolObject, public Snapshot inline AsciiString getName() const {return m_name;} virtual AsciiString getCurrentStateName() const { return m_currentState ? m_currentState->getName() : AsciiString::TheEmptyString;} #else - inline Bool getWantsDebugOutput() const { return false; } - inline AsciiString getCurrentStateName() const { return AsciiString::TheEmptyString;} + Bool getWantsDebugOutput() const { return false; } + AsciiString getCurrentStateName() const { return AsciiString::TheEmptyString;} #endif protected: diff --git a/GeneralsMD/Code/GameEngine/Include/Common/SubsystemInterface.h b/GeneralsMD/Code/GameEngine/Include/Common/SubsystemInterface.h index 4ef134f756..e7c5725ba1 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/SubsystemInterface.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/SubsystemInterface.h @@ -128,8 +128,8 @@ class SubsystemInterface Bool m_dumpUpdate; Bool m_dumpDraw; #else - inline void UPDATE(void) {update();} - inline void DRAW(void) {draw();} + void UPDATE(void) {update();} + void DRAW(void) {draw();} #endif protected: AsciiString m_name; diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Team.h b/GeneralsMD/Code/GameEngine/Include/Common/Team.h index 1f2b6f7606..b5ac00ce11 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/Team.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/Team.h @@ -525,10 +525,10 @@ class TeamPrototype : public MemoryPoolObject, TeamPrototypeID id ); // virtual destructor prototype provided by memory pool object - inline TeamPrototypeID getID() const { return m_id; } - inline const AsciiString& getName() const { return m_name; } - inline Bool getIsSingleton() const { return (m_flags & TEAM_SINGLETON) != 0; } - inline const TeamTemplateInfo *getTemplateInfo(void) const {return &m_teamTemplate;} + TeamPrototypeID getID() const { return m_id; } + const AsciiString& getName() const { return m_name; } + Bool getIsSingleton() const { return (m_flags & TEAM_SINGLETON) != 0; } + const TeamTemplateInfo *getTemplateInfo(void) const {return &m_teamTemplate;} /** return the team's owner (backtracking up if necessary) */ diff --git a/GeneralsMD/Code/GameEngine/Include/Common/TerrainTypes.h b/GeneralsMD/Code/GameEngine/Include/Common/TerrainTypes.h index 1668c6a09b..2c9ea65d22 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/TerrainTypes.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/TerrainTypes.h @@ -156,40 +156,40 @@ class TerrainType : public MemoryPoolObject // destructor prototype defined by memory pool glue /// get the name for this terrain - inline AsciiString getName( void ) { return m_name; } + AsciiString getName( void ) { return m_name; } /// get whether this terrain is blend edge terrain. - inline Bool isBlendEdge( void ) { return m_blendEdgeTexture; } + Bool isBlendEdge( void ) { return m_blendEdgeTexture; } /// get the type of this terrain - inline TerrainClass getClass( void ) { return m_class; } + TerrainClass getClass( void ) { return m_class; } /// get the construction restrictions - inline Bool getRestrictConstruction( void ) { return m_restrictConstruction; } + Bool getRestrictConstruction( void ) { return m_restrictConstruction; } /// get the texture file for this terrain - inline AsciiString getTexture( void ) { return m_texture; } + AsciiString getTexture( void ) { return m_texture; } /// get next terrain in list, only for use by the terrain collection - inline TerrainType *friend_getNext( void ) { return m_next; } + TerrainType *friend_getNext( void ) { return m_next; } /// set the name for this terrain, for use by terrain collection only - inline void friend_setName( AsciiString name ) { m_name = name; } + void friend_setName( AsciiString name ) { m_name = name; } /// set the next pointer for the terrain list, for use by terrain collection only - inline void friend_setNext( TerrainType *next ) { m_next = next; } + void friend_setNext( TerrainType *next ) { m_next = next; } /// set the texture, for use by terrain collection only - inline void friend_setTexture( AsciiString texture ) { m_texture = texture; } + void friend_setTexture( AsciiString texture ) { m_texture = texture; } /// set the class, for use by terrain collection only - inline void friend_setClass( TerrainClass terrainClass ) { m_class = terrainClass; } + void friend_setClass( TerrainClass terrainClass ) { m_class = terrainClass; } /// set the restrict construction flag, for use by terrain collection only - inline void friend_setRestrictConstruction( Bool restrict ) { m_restrictConstruction = restrict; } + void friend_setRestrictConstruction( Bool restrict ) { m_restrictConstruction = restrict; } /// set whether this terrain is blend edge terrain, for use by terrain collection only - inline void friend_setBlendEdge( Bool isBlend ) { m_blendEdgeTexture = isBlend; } + void friend_setBlendEdge( Bool isBlend ) { m_blendEdgeTexture = isBlend; } /// get the parsing table for INI const FieldParse *getFieldParse( void ) { return m_terrainTypeFieldParseTable; } diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Thing.h b/GeneralsMD/Code/GameEngine/Include/Common/Thing.h index b4e25f0020..982a401ae6 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/Thing.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/Thing.h @@ -84,10 +84,10 @@ class Thing : public MemoryPoolObject { // note, it is explicitly OK to pass null for 'thing' here; // they will check for null and return null in these cases. - friend inline Object *AsObject(Thing *thing) { return thing ? thing->asObjectMeth() : NULL; } - friend inline Drawable *AsDrawable(Thing *thing) { return thing ? thing->asDrawableMeth() : NULL; } - friend inline const Object *AsObject(const Thing *thing) { return thing ? thing->asObjectMeth() : NULL; } - friend inline const Drawable *AsDrawable(const Thing *thing) { return thing ? thing->asDrawableMeth() : NULL; } + friend Object *AsObject(Thing *thing) { return thing ? thing->asObjectMeth() : NULL; } + friend Drawable *AsDrawable(Thing *thing) { return thing ? thing->asDrawableMeth() : NULL; } + friend const Object *AsObject(const Thing *thing) { return thing ? thing->asObjectMeth() : NULL; } + friend const Drawable *AsDrawable(const Thing *thing) { return thing ? thing->asDrawableMeth() : NULL; } MEMORY_POOL_GLUE_ABC(Thing) @@ -116,8 +116,8 @@ class Thing : public MemoryPoolObject // don't want this behavior? then call setTransformMatrix instead. void setOrientation( Real angle ); - inline const Coord3D *getPosition() const { return &m_cachedPos; } - inline Real getOrientation() const { return m_cachedAngle; } + const Coord3D *getPosition() const { return &m_cachedPos; } + Real getOrientation() const { return m_cachedAngle; } Bool isPositioned() const; diff --git a/GeneralsMD/Code/GameEngine/Include/Common/ThingTemplate.h b/GeneralsMD/Code/GameEngine/Include/Common/ThingTemplate.h index 2064295107..77220fbfb8 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/ThingTemplate.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/ThingTemplate.h @@ -398,18 +398,18 @@ class ThingTemplate : public Overridable EditorSortingType getEditorSorting() const { return (EditorSortingType)m_editorSorting; } /// return true iff the template has the specified kindOf flag set. - inline Bool isKindOf(KindOfType t) const + 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 + Bool isKindOfMulti(const KindOfMaskType& mustBeSet, const KindOfMaskType& mustBeClear) const { return TEST_KINDOFMASK_MULTI(m_kindof, mustBeSet, mustBeClear); } - inline Bool isAnyKindOf( const KindOfMaskType& anyKindOf ) const + Bool isAnyKindOf( const KindOfMaskType& anyKindOf ) const { return TEST_KINDOFMASK_ANY(m_kindof, anyKindOf); } @@ -545,10 +545,10 @@ class ThingTemplate : public Overridable // 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; } + void friend_setTemplateName( const AsciiString& name ) { m_nameString = name; } + ThingTemplate *friend_getNextTemplate() const { return m_nextThingTemplate; } + void friend_setNextTemplate(ThingTemplate *tmplate) { m_nextThingTemplate = tmplate; } + void friend_setTemplateID(UnsignedShort id) { m_templateID = id; } Int getEnergyProduction() const { return m_energyProduction; } Int getEnergyBonus() const { return m_energyBonus; } diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Drawable.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Drawable.h index eb2d30454d..b66eb7dc96 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/Drawable.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Drawable.h @@ -324,17 +324,17 @@ class Drawable : public Thing, void setTerrainDecalSize(Real x, Real y); void setTerrainDecalFadeTarget(Real target, Real rate = 0.1f); - inline Object *getObject( void ) { return m_object; } ///< return object ID bound to this drawble - inline const Object *getObject( void ) const { return m_object; } ///< return object ID bound to this drawble + Object *getObject( void ) { return m_object; } ///< return object ID bound to this drawble + const Object *getObject( void ) const { return m_object; } ///< return object ID bound to this drawble - inline DrawableInfo *getDrawableInfo(void) {return &m_drawableInfo;} + DrawableInfo *getDrawableInfo(void) {return &m_drawableInfo;} void setDrawableHidden( Bool hidden ); ///< hide or unhide drawable // // note that this is not necessarily the 'get' reflection of setDrawableHidden, since drawables // can spontaneously hide via stealth. (srj) // - inline Bool isDrawableEffectivelyHidden() const { return m_hidden || m_hiddenByStealth; } + Bool isDrawableEffectivelyHidden() const { return m_hidden || m_hiddenByStealth; } void setSelectable( Bool selectable ); ///< Changes the drawables selectability Bool isSelectable( void ) const; @@ -374,7 +374,7 @@ class Drawable : public Thing, //--------------------------------------------------------------------------- void setDrawableStatus( DrawableStatus bit ) { BitSet( m_status, bit ); } void clearDrawableStatus( DrawableStatus bit ) { BitClear( m_status, bit ); } - inline Bool testDrawableStatus( DrawableStatus bit ) const { return (m_status & bit) != 0; } + Bool testDrawableStatus( DrawableStatus bit ) const { return (m_status & bit) != 0; } void setShroudClearFrame( UnsignedInt frame ) { m_shroudClearFrame = frame; } UnsignedInt getShroudClearFrame( void ) { return m_shroudClearFrame; } @@ -386,7 +386,7 @@ class Drawable : public Thing, void allocateShadows(void); ///< create shadow resources if not already present. Used by Options screen. void setFullyObscuredByShroud(Bool fullyObscured); - inline Bool getFullyObscuredByShroud(void) {return m_drawableFullyObscuredByShroud;} + Bool getFullyObscuredByShroud(void) {return m_drawableFullyObscuredByShroud;} // Put on ice until later... M Lorenzen // inline UnsignedByte getFullyObscuredByShroudWithCheatSpy(void) {return (UnsignedByte)m_drawableFullyObscuredByShroud | 128;}//8 looks like a zero in most fonts @@ -408,9 +408,9 @@ class Drawable : public Thing, // an "instance" matrix defines the local transform of the Drawable, and is concatenated with the global transform void setInstanceMatrix( const Matrix3D *instance ); ///< set the Drawable's instance transform const Matrix3D *getInstanceMatrix( void ) const { return &m_instance; } ///< get drawable instance transform - inline Bool isInstanceIdentity() const { return m_instanceIsIdentity; } + Bool isInstanceIdentity() const { return m_instanceIsIdentity; } - inline Real getInstanceScale( void ) const { return m_instanceScale; } ///< get scale that will be applied to instance matrix + Real getInstanceScale( void ) const { return m_instanceScale; } ///< get scale that will be applied to instance matrix void setInstanceScale(Real value) { m_instanceScale = value;} ///< set scale that will be applied to instance matrix before rendering. const Matrix3D *getTransformMatrix( void ) const; ///< return the world transform @@ -430,7 +430,7 @@ class Drawable : public Thing, void removeFromList(Drawable **pListHead); void setID( DrawableID id ); ///< set this drawable's unique ID - inline const ModelConditionFlags& getModelConditionFlags( void ) const { return m_conditionState; } + const ModelConditionFlags& getModelConditionFlags( void ) const { return m_conditionState; } // // NOTE: avoid repeated calls to the set and clear for the condition state as they @@ -533,16 +533,16 @@ class Drawable : public Thing, const Vector3 * getTintColor( void ) const; ///< get FX color value to add to ALL LIGHTS when drawing const Vector3 * getSelectionColor( void ) const; ///< get FX color value to add to ALL LIGHTS when drawing - inline TerrainDecalType getTerrainDecalType( void ) const { return m_terrainDecalType; } + TerrainDecalType getTerrainDecalType( void ) const { return m_terrainDecalType; } - inline void setDrawableOpacity( Real value ) { m_explicitOpacity = value; } ///< set alpha/opacity value used to override defaults when drawing. + void setDrawableOpacity( Real value ) { m_explicitOpacity = value; } ///< set alpha/opacity value used to override defaults when drawing. // note that this is not the 'get' inverse of setDrawableOpacity, since stealthing can also affect the effective opacity! - inline Real getEffectiveOpacity() const { return m_explicitOpacity * m_effectiveStealthOpacity; } ///< get alpha/opacity value used to override defaults when drawing. + Real getEffectiveOpacity() const { return m_explicitOpacity * m_effectiveStealthOpacity; } ///< get alpha/opacity value used to override defaults when drawing. void setEffectiveOpacity( Real pulseFactor, Real explicitOpacity = -1.0f ); // this is for the add'l pass fx which operates completely independently of the stealth opacity effects. Draw() does the fading every frame. - inline Real getSecondMaterialPassOpacity() const { return m_secondMaterialPassOpacity; } ///< get alpha/opacity value used to render add'l rendering pass. + Real getSecondMaterialPassOpacity() const { return m_secondMaterialPassOpacity; } ///< get alpha/opacity value used to render add'l rendering pass. void setSecondMaterialPassOpacity( Real op ) { m_secondMaterialPassOpacity = op; }; ///< set alpha/opacity value used to render add'l rendering pass. // both of these assume that you are starting at one extreme 100% or 0% opacity and are trying to go to the other!! -- amit @@ -605,13 +605,13 @@ class Drawable : public Thing, Drawable *asDrawableMeth() { return this; } const Drawable *asDrawableMeth() const { return this; } - inline Module** getModuleList(ModuleType i) + Module** getModuleList(ModuleType i) { Module** m = m_modules[i - FIRST_DRAWABLE_MODULE_TYPE]; return m; } - inline Module* const* getModuleList(ModuleType i) const + Module* const* getModuleList(ModuleType i) const { Module** m = m_modules[i - FIRST_DRAWABLE_MODULE_TYPE]; return m; diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.h b/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.h index 21bd126c77..d30b79567f 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.h @@ -531,7 +531,7 @@ friend class Drawable; // for selection/deselection transactions Bool isDrawableCaptionBold( void ) { return m_drawableCaptionBold; } Color getDrawableCaptionColor( void ) { return m_drawableCaptionColor; } - inline Bool shouldMoveRMBScrollAnchor( void ) { return m_moveRMBScrollAnchor; } + Bool shouldMoveRMBScrollAnchor( void ) { return m_moveRMBScrollAnchor; } Bool isClientQuiet( void ) const { return m_clientQuiet; } Bool isInWaypointMode( void ) const { return m_waypointMode; } diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Mouse.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Mouse.h index 8d22891b39..abd5c0c403 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/Mouse.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Mouse.h @@ -304,7 +304,7 @@ class Mouse : public SubsystemInterface virtual void setRedrawMode(RedrawMode mode) {m_currentRedrawMode=mode;} ///* path, Object *ignoreObject, CommandSourceType cmdSource ) + void aiFollowExitProductionPath( const std::vector* path, Object *ignoreObject, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_FOLLOW_EXITPRODUCTION_PATH, cmdSource); parms.m_coords = *path; @@ -558,7 +558,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiFollowPath( const std::vector* path, Object *ignoreObject, CommandSourceType cmdSource ) + void aiFollowPath( const std::vector* path, Object *ignoreObject, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_FOLLOW_PATH, cmdSource); parms.m_coords = *path; @@ -566,14 +566,14 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiFollowPathAppend( const Coord3D* pos, CommandSourceType cmdSource ) + void aiFollowPathAppend( const Coord3D* pos, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_FOLLOW_PATH_APPEND, cmdSource); parms.m_pos = *pos; aiDoCommand(&parms); } - inline void aiAttackObject( Object *victim, Int maxShotsToFire, CommandSourceType cmdSource ) + void aiAttackObject( Object *victim, Int maxShotsToFire, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_ATTACK_OBJECT, cmdSource); parms.m_obj = victim; @@ -581,7 +581,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiForceAttackObject( Object *victim, Int maxShotsToFire, CommandSourceType cmdSource ) + void aiForceAttackObject( Object *victim, Int maxShotsToFire, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_FORCE_ATTACK_OBJECT, cmdSource); parms.m_obj = victim; @@ -589,7 +589,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiGuardRetaliate( Object *victim, const Coord3D *pos, Int maxShotsToFire, CommandSourceType cmdSource ) + void aiGuardRetaliate( Object *victim, const Coord3D *pos, Int maxShotsToFire, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_GUARD_RETALIATE, cmdSource); parms.m_obj = victim; @@ -598,7 +598,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiAttackTeam( const Team *team, Int maxShotsToFire, CommandSourceType cmdSource ) + void aiAttackTeam( const Team *team, Int maxShotsToFire, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_ATTACK_TEAM, cmdSource); parms.m_team = team; @@ -606,7 +606,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiAttackPosition( const Coord3D *pos, Int maxShotsToFire, CommandSourceType cmdSource ) + void aiAttackPosition( const Coord3D *pos, Int maxShotsToFire, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_ATTACK_POSITION, cmdSource); parms.m_pos = *pos; @@ -614,7 +614,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiAttackMoveToPosition( const Coord3D *pos, Int maxShotsToFire, CommandSourceType cmdSource ) + void aiAttackMoveToPosition( const Coord3D *pos, Int maxShotsToFire, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_ATTACKMOVE_TO_POSITION, cmdSource); parms.m_pos = *pos; @@ -622,7 +622,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiAttackFollowWaypointPath( const Waypoint *way, Int maxShotsToFire, CommandSourceType cmdSource ) + void aiAttackFollowWaypointPath( const Waypoint *way, Int maxShotsToFire, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_ATTACKFOLLOW_WAYPOINT_PATH, cmdSource); parms.m_waypoint = way; @@ -630,7 +630,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiAttackFollowWaypointPathAsTeam( const Waypoint *way, Int maxShotsToFire, CommandSourceType cmdSource ) + void aiAttackFollowWaypointPathAsTeam( const Waypoint *way, Int maxShotsToFire, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_ATTACKFOLLOW_WAYPOINT_PATH_AS_TEAM, cmdSource); parms.m_waypoint = way; @@ -638,20 +638,20 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiHunt( CommandSourceType cmdSource ) + void aiHunt( CommandSourceType cmdSource ) { AICommandParms parms(AICMD_HUNT, cmdSource); aiDoCommand(&parms); } - inline void aiAttackArea( const PolygonTrigger *areaToGuard, CommandSourceType cmdSource ) + void aiAttackArea( const PolygonTrigger *areaToGuard, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_ATTACK_AREA, cmdSource); parms.m_polygon = areaToGuard; aiDoCommand(&parms); } - inline void aiRepair( Object *obj, CommandSourceType cmdSource ) + void aiRepair( Object *obj, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_REPAIR, cmdSource); parms.m_obj = obj; @@ -676,56 +676,56 @@ class AICommandInterface } #endif - inline void aiResumeConstruction( Object *obj, CommandSourceType cmdSource ) + void aiResumeConstruction( Object *obj, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_RESUME_CONSTRUCTION, cmdSource); parms.m_obj = obj; aiDoCommand(&parms); } - inline void aiGetHealed( Object *healDepot, CommandSourceType cmdSource ) + void aiGetHealed( Object *healDepot, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_GET_HEALED, cmdSource); parms.m_obj = healDepot; aiDoCommand(&parms); } - inline void aiGetRepaired( Object *repairDepot, CommandSourceType cmdSource ) + void aiGetRepaired( Object *repairDepot, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_GET_REPAIRED, cmdSource); parms.m_obj = repairDepot; aiDoCommand(&parms); } - inline void aiEnter( Object *obj, CommandSourceType cmdSource ) + void aiEnter( Object *obj, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_ENTER, cmdSource); parms.m_obj = obj; aiDoCommand(&parms); } - inline void aiDock( Object *obj, CommandSourceType cmdSource ) + void aiDock( Object *obj, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_DOCK, cmdSource); parms.m_obj = obj; aiDoCommand(&parms); } - inline void aiExit( Object *objectToExit, CommandSourceType cmdSource ) + void aiExit( Object *objectToExit, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_EXIT, cmdSource); parms.m_obj = objectToExit; aiDoCommand(&parms); } - inline void aiExitInstantly( Object *objectToExit, CommandSourceType cmdSource ) + void aiExitInstantly( Object *objectToExit, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_EXIT_INSTANTLY, cmdSource); parms.m_obj = objectToExit; aiDoCommand(&parms); } - inline void aiEvacuate( Bool exposeStealthUnits, CommandSourceType cmdSource ) + void aiEvacuate( Bool exposeStealthUnits, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_EVACUATE, cmdSource); if( exposeStealthUnits ) @@ -735,7 +735,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiEvacuateInstantly( Bool exposeStealthUnits, CommandSourceType cmdSource ) + void aiEvacuateInstantly( Bool exposeStealthUnits, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_EVACUATE_INSTANTLY, cmdSource); if( exposeStealthUnits ) @@ -745,20 +745,20 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiExecuteRailedTransport( CommandSourceType cmdSource ) + void aiExecuteRailedTransport( CommandSourceType cmdSource ) { AICommandParms parms( AICMD_EXECUTE_RAILED_TRANSPORT, cmdSource ); aiDoCommand( &parms ); } - inline void aiGoProne( const DamageInfo *damageInfo, CommandSourceType cmdSource ) + void aiGoProne( const DamageInfo *damageInfo, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_GO_PRONE, cmdSource); parms.m_damage = *damageInfo; aiDoCommand(&parms); } - inline void aiGuardPosition( const Coord3D *pos, GuardMode guardMode, CommandSourceType cmdSource ) + void aiGuardPosition( const Coord3D *pos, GuardMode guardMode, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_GUARD_POSITION, cmdSource); parms.m_pos = *pos; @@ -766,7 +766,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiGuardObject( Object *objToGuard, GuardMode guardMode, CommandSourceType cmdSource ) + void aiGuardObject( Object *objToGuard, GuardMode guardMode, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_GUARD_OBJECT, cmdSource); parms.m_obj = objToGuard; @@ -774,7 +774,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiGuardArea( const PolygonTrigger *areaToGuard, GuardMode guardMode, CommandSourceType cmdSource ) + void aiGuardArea( const PolygonTrigger *areaToGuard, GuardMode guardMode, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_GUARD_AREA, cmdSource); parms.m_polygon = areaToGuard; @@ -782,34 +782,34 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiGuardTunnelNetwork( GuardMode guardMode, CommandSourceType cmdSource ) + void aiGuardTunnelNetwork( GuardMode guardMode, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_GUARD_TUNNEL_NETWORK, cmdSource); parms.m_intValue = guardMode; aiDoCommand(&parms); } - inline void aiHackInternet( CommandSourceType cmdSource ) + void aiHackInternet( CommandSourceType cmdSource ) { AICommandParms parms(AICMD_HACK_INTERNET, cmdSource); aiDoCommand(&parms); } - inline void aiFaceObject( Object *target, CommandSourceType cmdSource ) + void aiFaceObject( Object *target, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_FACE_OBJECT, cmdSource); parms.m_obj = target; aiDoCommand(&parms); } - inline void aiFacePosition( const Coord3D *pos, CommandSourceType cmdSource ) + void aiFacePosition( const Coord3D *pos, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_FACE_POSITION, cmdSource); parms.m_pos = *pos; aiDoCommand(&parms); } - inline void aiRappelInto( Object *target, const Coord3D& pos, CommandSourceType cmdSource ) + void aiRappelInto( Object *target, const Coord3D& pos, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_RAPPEL_INTO, cmdSource); parms.m_obj = target; @@ -817,7 +817,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiCombatDrop( Object *target, const Coord3D& pos, CommandSourceType cmdSource ) + void aiCombatDrop( Object *target, const Coord3D& pos, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_COMBATDROP, cmdSource); parms.m_obj = target; @@ -825,14 +825,14 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiDoCommandButton( const CommandButton *commandButton, CommandSourceType cmdSource ) + void aiDoCommandButton( const CommandButton *commandButton, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_COMMANDBUTTON, cmdSource); parms.m_commandButton = commandButton; aiDoCommand(&parms); } - inline void aiDoCommandButtonAtPosition( const CommandButton *commandButton, const Coord3D *pos, CommandSourceType cmdSource ) + void aiDoCommandButtonAtPosition( const CommandButton *commandButton, const Coord3D *pos, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_COMMANDBUTTON_POS, cmdSource); parms.m_pos = *pos; @@ -840,7 +840,7 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiDoCommandButtonAtObject( const CommandButton *commandButton, Object *obj, CommandSourceType cmdSource ) + void aiDoCommandButtonAtObject( const CommandButton *commandButton, Object *obj, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_COMMANDBUTTON_OBJ, cmdSource); parms.m_obj = obj; @@ -848,27 +848,27 @@ class AICommandInterface aiDoCommand(&parms); } - inline void aiMoveAwayFromUnit( Object *obj, CommandSourceType cmdSource ) + void aiMoveAwayFromUnit( Object *obj, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_MOVE_AWAY_FROM_UNIT, cmdSource); parms.m_obj = obj; aiDoCommand(&parms); } - inline void aiWander( const Waypoint *way, CommandSourceType cmdSource ) + void aiWander( const Waypoint *way, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_WANDER, cmdSource); parms.m_waypoint = way; aiDoCommand(&parms); } - inline void aiWanderInPlace(CommandSourceType cmdSource) + void aiWanderInPlace(CommandSourceType cmdSource) { AICommandParms parms(AICMD_WANDER_IN_PLACE, cmdSource); aiDoCommand(&parms); } - inline void aiPanic( const Waypoint *way, CommandSourceType cmdSource ) + void aiPanic( const Waypoint *way, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_PANIC, cmdSource); parms.m_waypoint = way; diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/ArmorSet.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/ArmorSet.h index 00204fa0eb..6f99fde5fd 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/ArmorSet.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/ArmorSet.h @@ -66,23 +66,23 @@ class ArmorTemplateSet const DamageFX* m_fx; public: - inline ArmorTemplateSet() + ArmorTemplateSet() { clear(); } - inline void clear() + void clear() { m_types.clear(); m_template = NULL; m_fx = NULL; } - inline const ArmorTemplate* getArmorTemplate() const { return m_template; } - inline const DamageFX* getDamageFX() const { return m_fx; } + const ArmorTemplate* getArmorTemplate() const { return m_template; } + const DamageFX* getDamageFX() const { return m_fx; } - inline Int getConditionsYesCount() const { return 1; } - inline const ArmorSetFlags& getNthConditionsYes(Int i) const { return m_types; } + Int getConditionsYesCount() const { return 1; } + const ArmorSetFlags& getNthConditionsYes(Int i) const { return m_types; } #if defined(RTS_DEBUG) inline AsciiString getDescription() const { return "ArmorTemplateSet"; } #endif diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/CrateSystem.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/CrateSystem.h index ef6e956827..01c694803a 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/CrateSystem.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/CrateSystem.h @@ -60,7 +60,7 @@ class CrateTemplate : public Overridable void setName( AsciiString name ) { m_name = name; } AsciiString getName(){ return m_name; } - inline const FieldParse *getFieldParse() const { return TheCrateTemplateFieldParseTable; } + const FieldParse *getFieldParse() const { return TheCrateTemplateFieldParseTable; } static const FieldParse TheCrateTemplateFieldParseTable[]; ///< the parse table for INI definition static void parseCrateCreationEntry( INI* ini, void *instance, void *store, const void* /*userData*/ ); diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/GhostObject.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/GhostObject.h index 06d6d73422..7f2dbf1436 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/GhostObject.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/GhostObject.h @@ -47,13 +47,13 @@ class GhostObject : public Snapshot virtual void snapShot(int playerIndex)=0; virtual void updateParentObject(Object *object, PartitionData *mod)=0; virtual void freeSnapShot(int playerIndex)=0; - inline PartitionData *friend_getPartitionData(void) const {return m_partitionData;} - inline GeometryType getGeometryType(void) const {return m_parentGeometryType;} - inline Bool getGeometrySmall(void) const {return m_parentGeometryIsSmall;} - inline Real getGeometryMajorRadius(void) const {return m_parentGeometryMajorRadius;} - inline Real getGeometryMinorRadius(void) const {return m_parentGeometryminorRadius;} - inline Real getParentAngle(void) const {return m_parentAngle;} - inline const Coord3D *getParentPosition(void) const {return &m_parentPosition;} + PartitionData *friend_getPartitionData(void) const {return m_partitionData;} + GeometryType getGeometryType(void) const {return m_parentGeometryType;} + Bool getGeometrySmall(void) const {return m_parentGeometryIsSmall;} + Real getGeometryMajorRadius(void) const {return m_parentGeometryMajorRadius;} + Real getGeometryMinorRadius(void) const {return m_parentGeometryminorRadius;} + Real getParentAngle(void) const {return m_parentAngle;} + const Coord3D *getParentPosition(void) const {return &m_parentPosition;} protected: virtual void crc( Xfer *xfer ); @@ -80,12 +80,12 @@ class GhostObjectManager : public Snapshot virtual GhostObject *addGhostObject(Object *object, PartitionData *pd); virtual void removeGhostObject(GhostObject *mod); virtual void setLocalPlayerIndex(int playerIndex) { m_localPlayer = playerIndex; } - inline int getLocalPlayerIndex(void) { return m_localPlayer; } + int getLocalPlayerIndex(void) { return m_localPlayer; } virtual void updateOrphanedObjects(int *playerIndexList, int playerIndexCount); virtual void releasePartitionData(void); ///m_preferredHeight; }; - inline Real getPreferredHeightDamping() const { return m_preferredHeightDamping;} - inline LocomotorAppearance getAppearance() const { return m_template->m_appearance; } - inline LocomotorPriority getMovePriority() const { return m_template->m_movePriority; } - inline LocomotorSurfaceTypeMask getLegalSurfaces() const { return m_template->m_surfaces; } - - inline AsciiString getTemplateName() const { return m_template->m_name;} - inline Real getMinSpeed() const { return m_template->m_minSpeed;} - inline Real getAccelPitchLimit() const { return m_template->m_accelPitchLimit;} ///< Maximum amount we will pitch up or down under acceleration (including recoil.) - inline Real getDecelPitchLimit() const { return m_template->m_decelPitchLimit;} ///< Maximum amount we will pitch down under deceleration (including recoil.) - inline Real getBounceKick() const { return m_template->m_bounceKick;} ///< How much simulating rough terrain "bounces" a wheel up. - inline Real getPitchStiffness() const { return m_template->m_pitchStiffness;} ///< How stiff the springs are forward & back. - inline Real getRollStiffness() const { return m_template->m_rollStiffness;} ///< How stiff the springs are side to side. - inline Real getPitchDamping() const { return m_template->m_pitchDamping;} ///< How good the shock absorbers are. - inline Real getRollDamping() const { return m_template->m_rollDamping;} ///< How good the shock absorbers are. - inline Real getPitchByZVelCoef() const { return m_template->m_pitchByZVelCoef;} ///< How much we pitch in response to speed. - inline Real getThrustRoll() const { return m_template->m_thrustRoll; } ///< Thrust roll - inline Real getWobbleRate() const { return m_template->m_wobbleRate; } ///< how fast thrust things "wobble" - inline Real getMaxWobble() const { return m_template->m_maxWobble; } ///< how much thrust things "wobble" - inline Real getMinWobble() const { return m_template->m_minWobble; } ///< how much thrust things "wobble" - - inline Real getForwardVelCoef() const { return m_template->m_forwardVelCoef;} ///< How much we pitch in response to speed. - inline Real getLateralVelCoef() const { return m_template->m_lateralVelCoef;} ///< How much we roll in response to speed. - inline Real getForwardAccelCoef() const { return m_template->m_forwardAccelCoef;} ///< How much we pitch in response to acceleration. - inline Real getLateralAccelCoef() const { return m_template->m_lateralAccelCoef;} ///< How much we roll in response to acceleration. - inline Real getUniformAxialDamping() const { return m_template->m_uniformAxialDamping;} ///< How much we roll in response to acceleration. - inline Real getTurnPivotOffset() const { return m_template->m_turnPivotOffset;} - inline Bool getApply2DFrictionWhenAirborne() const { return m_template->m_apply2DFrictionWhenAirborne; } - inline Bool getIsDownhillOnly() const { return m_template->m_downhillOnly; } - inline Bool getAllowMotiveForceWhileAirborne() const { return m_template->m_allowMotiveForceWhileAirborne; } - inline Int getAirborneTargetingHeight() const { return m_template->m_airborneTargetingHeight; } - inline Bool getLocomotorWorksWhenDead() const { return m_template->m_locomotorWorksWhenDead; } - inline Bool getStickToGround() const { return m_template->m_stickToGround; } - inline Real getCloseEnoughDist() const { return m_closeEnoughDist; } - inline Bool isCloseEnoughDist3D() const { return getFlag(IS_CLOSE_ENOUGH_DIST_3D); } - inline Bool hasSuspension() const {return m_template->m_hasSuspension;} - inline Bool canMoveBackwards() const {return m_template->m_canMoveBackward;} - inline Real getMaxWheelExtension() const {return m_template->m_maximumWheelExtension;} - inline Real getMaxWheelCompression() const {return m_template->m_maximumWheelCompression;} - inline Real getWheelTurnAngle() const {return m_template->m_wheelTurnAngle;} - - - inline Real getRudderCorrectionDegree() const { return m_template->m_rudderCorrectionDegree;} ///< How much we roll in response to acceleration. - inline Real getRudderCorrectionRate() const { return m_template->m_rudderCorrectionRate;} ///< How much we roll in response to acceleration. - inline Real getElevatorCorrectionDegree() const { return m_template->m_elevatorCorrectionDegree;} ///< How much we roll in response to acceleration. - inline Real getElevatorCorrectionRate() const { return m_template->m_elevatorCorrectionRate;} ///< How much we roll in response to acceleration. - - - inline Real getWanderWidthFactor() const {return m_template->m_wanderWidthFactor;} - inline Real getWanderAboutPointRadius() const {return m_template->m_wanderAboutPointRadius;} + Real getPreferredHeight() const { return m_preferredHeight;} ///< Just return preferredheight, no damage consideration + void restorePreferredHeightFromTemplate() { m_preferredHeight = m_template->m_preferredHeight; }; + Real getPreferredHeightDamping() const { return m_preferredHeightDamping;} + LocomotorAppearance getAppearance() const { return m_template->m_appearance; } + LocomotorPriority getMovePriority() const { return m_template->m_movePriority; } + LocomotorSurfaceTypeMask getLegalSurfaces() const { return m_template->m_surfaces; } + + AsciiString getTemplateName() const { return m_template->m_name;} + Real getMinSpeed() const { return m_template->m_minSpeed;} + Real getAccelPitchLimit() const { return m_template->m_accelPitchLimit;} ///< Maximum amount we will pitch up or down under acceleration (including recoil.) + Real getDecelPitchLimit() const { return m_template->m_decelPitchLimit;} ///< Maximum amount we will pitch down under deceleration (including recoil.) + Real getBounceKick() const { return m_template->m_bounceKick;} ///< How much simulating rough terrain "bounces" a wheel up. + Real getPitchStiffness() const { return m_template->m_pitchStiffness;} ///< How stiff the springs are forward & back. + Real getRollStiffness() const { return m_template->m_rollStiffness;} ///< How stiff the springs are side to side. + Real getPitchDamping() const { return m_template->m_pitchDamping;} ///< How good the shock absorbers are. + Real getRollDamping() const { return m_template->m_rollDamping;} ///< How good the shock absorbers are. + Real getPitchByZVelCoef() const { return m_template->m_pitchByZVelCoef;} ///< How much we pitch in response to speed. + Real getThrustRoll() const { return m_template->m_thrustRoll; } ///< Thrust roll + Real getWobbleRate() const { return m_template->m_wobbleRate; } ///< how fast thrust things "wobble" + Real getMaxWobble() const { return m_template->m_maxWobble; } ///< how much thrust things "wobble" + Real getMinWobble() const { return m_template->m_minWobble; } ///< how much thrust things "wobble" + + Real getForwardVelCoef() const { return m_template->m_forwardVelCoef;} ///< How much we pitch in response to speed. + Real getLateralVelCoef() const { return m_template->m_lateralVelCoef;} ///< How much we roll in response to speed. + Real getForwardAccelCoef() const { return m_template->m_forwardAccelCoef;} ///< How much we pitch in response to acceleration. + Real getLateralAccelCoef() const { return m_template->m_lateralAccelCoef;} ///< How much we roll in response to acceleration. + Real getUniformAxialDamping() const { return m_template->m_uniformAxialDamping;} ///< How much we roll in response to acceleration. + Real getTurnPivotOffset() const { return m_template->m_turnPivotOffset;} + Bool getApply2DFrictionWhenAirborne() const { return m_template->m_apply2DFrictionWhenAirborne; } + Bool getIsDownhillOnly() const { return m_template->m_downhillOnly; } + Bool getAllowMotiveForceWhileAirborne() const { return m_template->m_allowMotiveForceWhileAirborne; } + Int getAirborneTargetingHeight() const { return m_template->m_airborneTargetingHeight; } + Bool getLocomotorWorksWhenDead() const { return m_template->m_locomotorWorksWhenDead; } + Bool getStickToGround() const { return m_template->m_stickToGround; } + Real getCloseEnoughDist() const { return m_closeEnoughDist; } + Bool isCloseEnoughDist3D() const { return getFlag(IS_CLOSE_ENOUGH_DIST_3D); } + Bool hasSuspension() const {return m_template->m_hasSuspension;} + Bool canMoveBackwards() const {return m_template->m_canMoveBackward;} + Real getMaxWheelExtension() const {return m_template->m_maximumWheelExtension;} + Real getMaxWheelCompression() const {return m_template->m_maximumWheelCompression;} + Real getWheelTurnAngle() const {return m_template->m_wheelTurnAngle;} + + + Real getRudderCorrectionDegree() const { return m_template->m_rudderCorrectionDegree;} ///< How much we roll in response to acceleration. + Real getRudderCorrectionRate() const { return m_template->m_rudderCorrectionRate;} ///< How much we roll in response to acceleration. + Real getElevatorCorrectionDegree() const { return m_template->m_elevatorCorrectionDegree;} ///< How much we roll in response to acceleration. + Real getElevatorCorrectionRate() const { return m_template->m_elevatorCorrectionRate;} ///< How much we roll in response to acceleration. + + + Real getWanderWidthFactor() const {return m_template->m_wanderWidthFactor;} + Real getWanderAboutPointRadius() const {return m_template->m_wanderAboutPointRadius;} Real calcMinTurnRadius(BodyDamageType condition, Real* timeToTravelThatDist) const; /// this is handy for doing things like forcing helicopters to crash realistically: cut their lift. - inline void setMaxLift(Real lift) { m_maxLift = lift; } - inline void setMaxSpeed(Real speed) + void setMaxLift(Real lift) { m_maxLift = lift; } + void setMaxSpeed(Real speed) { DEBUG_ASSERTCRASH(!(speed <= 0.0f && m_template->m_appearance == LOCO_THRUST), ("THRUST locos may not have zero speeds!")); m_maxSpeed = speed; } - inline void setMaxAcceleration(Real accel) { m_maxAccel = accel; } - inline void setMaxBraking(Real braking) { m_maxBraking = braking; } - inline void setMaxTurnRate(Real turn) { m_maxTurnRate = turn; } - inline void setAllowInvalidPosition(Bool allow) { setFlag(ALLOW_INVALID_POSITION, allow); } - inline void setCloseEnoughDist( Real dist ) { m_closeEnoughDist = dist; } - inline void setCloseEnoughDist3D( Bool setting ) { setFlag(IS_CLOSE_ENOUGH_DIST_3D, setting); } - inline Bool isInvalidPositionAllowed() const { return getFlag( ALLOW_INVALID_POSITION ); } + void setMaxAcceleration(Real accel) { m_maxAccel = accel; } + void setMaxBraking(Real braking) { m_maxBraking = braking; } + void setMaxTurnRate(Real turn) { m_maxTurnRate = turn; } + void setAllowInvalidPosition(Bool allow) { setFlag(ALLOW_INVALID_POSITION, allow); } + void setCloseEnoughDist( Real dist ) { m_closeEnoughDist = dist; } + void setCloseEnoughDist3D( Bool setting ) { setFlag(IS_CLOSE_ENOUGH_DIST_3D, setting); } + Bool isInvalidPositionAllowed() const { return getFlag( ALLOW_INVALID_POSITION ); } - inline void setPreferredHeight( Real height ) { m_preferredHeight = height; } + void setPreferredHeight( Real height ) { m_preferredHeight = height; } #ifdef CIRCLE_FOR_LANDING /** @@ -337,7 +337,7 @@ class Locomotor : public MemoryPoolObject, public Snapshot this is used mainly for force missiles to swoop in on their target, and to force airplane takeoff/landing to go smoothly. */ - inline void setUsePreciseZPos(Bool u) { setFlag(PRECISE_Z_POS, u); } + void setUsePreciseZPos(Bool u) { setFlag(PRECISE_Z_POS, u); } /** when off (the default), units slow down as they approach their target. @@ -346,7 +346,7 @@ class Locomotor : public MemoryPoolObject, public Snapshot this is useful mainly in some weird, temporary situations where we know we are going to follow this move with another one... or for carbombs. */ - inline void setNoSlowDownAsApproachingDest(Bool u) { setFlag(NO_SLOW_DOWN_AS_APPROACHING_DEST, u); } + void setNoSlowDownAsApproachingDest(Bool u) { setFlag(NO_SLOW_DOWN_AS_APPROACHING_DEST, u); } /** when off (the default), units do their normal stuff. @@ -359,10 +359,10 @@ class Locomotor : public MemoryPoolObject, public Snapshot For ground units, it also allows units to have a destination off of a pathfing grid. */ - inline void setUltraAccurate(Bool u) { setFlag(ULTRA_ACCURATE, u); } - inline Bool isUltraAccurate() const { return getFlag(ULTRA_ACCURATE); } + void setUltraAccurate(Bool u) { setFlag(ULTRA_ACCURATE, u); } + Bool isUltraAccurate() const { return getFlag(ULTRA_ACCURATE); } - inline Bool isMovingBackwards(void) const {return getFlag(MOVING_BACKWARDS);} + Bool isMovingBackwards(void) const {return getFlag(MOVING_BACKWARDS);} void startMove(void); ///< Indicates that a move is starting, primarily to reset the donut timer. jba. @@ -437,8 +437,8 @@ class Locomotor : public MemoryPoolObject, public Snapshot OFFSET_INCREASING }; - inline Bool getFlag(LocoFlag f) const { return (m_flags & (1 << f)) != 0; } - inline void setFlag(LocoFlag f, Bool b) { if (b) m_flags |= (1<getCurrentStateID(); } ///< return the id of the current state of the machine + StateID getCurrentStateID() const { return getStateMachine()->getCurrentStateID(); } ///< return the id of the current state of the machine /// @ todo -- srj sez: JBA NUKE THIS CODE, IT IS EVIL - inline void friend_addToWaypointGoalPath( const Coord3D *pathPoint ) { getStateMachine()->addToGoalPath(pathPoint); } + void friend_addToWaypointGoalPath( const Coord3D *pathPoint ) { getStateMachine()->addToGoalPath(pathPoint); } // this is intended for use ONLY by W3dWaypointBuffer and AIFollowPathState. - inline const Coord3D* friend_getGoalPathPosition( Int index ) const { return getStateMachine()->getGoalPathPosition( index ); } + const Coord3D* friend_getGoalPathPosition( Int index ) const { return getStateMachine()->getGoalPathPosition( index ); } // this is intended for use ONLY by W3dWaypointBuffer. Int friend_getWaypointGoalPathSize() const; // this is intended for use ONLY by W3dWaypointBuffer. - inline Int friend_getCurrentGoalPathIndex() const { return m_nextGoalPathIndex; } + Int friend_getCurrentGoalPathIndex() const { return m_nextGoalPathIndex; } // this is intended for use ONLY by AIFollowPathState. - inline void friend_setCurrentGoalPathIndex( Int index ) { m_nextGoalPathIndex = index; } + void friend_setCurrentGoalPathIndex( Int index ) { m_nextGoalPathIndex = index; } #ifdef DEBUG_LOGGING inline const Coord3D *friend_getRequestedDestination() const { return &m_requestedDestination; } inline const Coord3D *friend_getRequestedDestination2() const { return &m_requestedDestination2; } #endif - inline Object* getGoalObject() { return getStateMachine()->getGoalObject(); } ///< return the id of the current state of the machine - inline const Coord3D* getGoalPosition() const { return getStateMachine()->getGoalPosition(); } ///< return the id of the current state of the machine + Object* getGoalObject() { return getStateMachine()->getGoalObject(); } ///< return the id of the current state of the machine + const Coord3D* getGoalPosition() const { return getStateMachine()->getGoalPosition(); } ///< return the id of the current state of the machine - inline WhichTurretType friend_getTurretSync() const { return m_turretSyncFlag; } - inline void friend_setTurretSync(WhichTurretType t) { m_turretSyncFlag = t; } + WhichTurretType friend_getTurretSync() const { return m_turretSyncFlag; } + void friend_setTurretSync(WhichTurretType t) { m_turretSyncFlag = t; } - inline UnsignedInt getPriorWaypointID ( void ) { return m_priorWaypointID; }; - inline UnsignedInt getCurrentWaypointID ( void ) { return m_currentWaypointID; }; + UnsignedInt getPriorWaypointID ( void ) { return m_priorWaypointID; }; + UnsignedInt getCurrentWaypointID ( void ) { return m_currentWaypointID; }; - inline void clearMoveOutOfWay(void) {m_moveOutOfWay1 = INVALID_ID; m_moveOutOfWay2 = INVALID_ID;} + void clearMoveOutOfWay(void) {m_moveOutOfWay1 = INVALID_ID; m_moveOutOfWay2 = INVALID_ID;} - inline void setTmpValue(Int val) {m_tmpInt = val;} - inline Int getTmpValue(void) {return m_tmpInt;} + void setTmpValue(Int val) {m_tmpInt = val;} + Int getTmpValue(void) {return m_tmpInt;} - inline Bool getRetryPath(void) {return m_retryPath;} + Bool getRetryPath(void) {return m_retryPath;} - inline void setAllowedToChase( Bool allow ) { m_allowedToChase = allow; } - inline Bool isAllowedToChase() const { return m_allowedToChase; } + void setAllowedToChase( Bool allow ) { m_allowedToChase = allow; } + Bool isAllowedToChase() const { return m_allowedToChase; } // only for AIStateMachine. virtual void friend_notifyStateMachineChanged(); diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AutoHealBehavior.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AutoHealBehavior.h index edd036f9a3..549bcd5fac 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AutoHealBehavior.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AutoHealBehavior.h @@ -166,7 +166,7 @@ class AutoHealBehavior : public UpdateModule, return getAutoHealBehaviorModuleData()->m_upgradeMuxData.m_requiresAllTriggers; } - inline Bool isUpgradeActive() const { return isAlreadyUpgraded(); } + Bool isUpgradeActive() const { return isAlreadyUpgraded(); } virtual Bool isSubObjectsUpgrade() { return false; } diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CountermeasuresBehavior.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CountermeasuresBehavior.h index 9ca8248b63..c4ed34504a 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CountermeasuresBehavior.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CountermeasuresBehavior.h @@ -173,7 +173,7 @@ class CountermeasuresBehavior : public UpdateModule, public UpgradeMux, public C return getCountermeasuresBehaviorModuleData()->m_upgradeMuxData.m_requiresAllTriggers; } - inline Bool isUpgradeActive() const { return isAlreadyUpgraded(); } + Bool isUpgradeActive() const { return isAlreadyUpgraded(); } virtual Bool isSubObjectsUpgrade() { return false; } diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/DieModule.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/DieModule.h index 803cdde7c5..c3a28c08d9 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/DieModule.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/DieModule.h @@ -76,7 +76,7 @@ class DieModuleData : public BehaviorModuleData p.add(DieMuxData::getFieldParse(), offsetof( DieModuleData, m_dieMuxData )); } - inline Bool isDieApplicable(const Object* obj, const DamageInfo *damageInfo) const { return m_dieMuxData.isDieApplicable(obj, damageInfo); } + Bool isDieApplicable(const Object* obj, const DamageInfo *damageInfo) const { return m_dieMuxData.isDieApplicable(obj, damageInfo); } }; //------------------------------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FXListDie.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FXListDie.h index d299618064..20533a7b50 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FXListDie.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FXListDie.h @@ -121,7 +121,7 @@ class FXListDie : public DieModule, public UpgradeMux return getFXListDieModuleData()->m_upgradeMuxData.m_requiresAllTriggers; } - inline Bool isUpgradeActive() const { return isAlreadyUpgraded(); } + Bool isUpgradeActive() const { return isAlreadyUpgraded(); } virtual Bool isSubObjectsUpgrade() { return false; } diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDamagedBehavior.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDamagedBehavior.h index 801bfaaf24..e675e82a2c 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDamagedBehavior.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDamagedBehavior.h @@ -155,7 +155,7 @@ class FireWeaponWhenDamagedBehavior : public UpdateModule, return getFireWeaponWhenDamagedBehaviorModuleData()->m_upgradeMuxData.m_requiresAllTriggers; } - inline Bool isUpgradeActive() const { return isAlreadyUpgraded(); } + Bool isUpgradeActive() const { return isAlreadyUpgraded(); } virtual Bool isSubObjectsUpgrade() { return false; } diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDeadBehavior.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDeadBehavior.h index 7a1271eca6..5c666599d5 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDeadBehavior.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDeadBehavior.h @@ -120,7 +120,7 @@ class FireWeaponWhenDeadBehavior : public BehaviorModule, return getFireWeaponWhenDeadBehaviorModuleData()->m_upgradeMuxData.m_requiresAllTriggers; } - inline Bool isUpgradeActive() const { return isAlreadyUpgraded(); } + Bool isUpgradeActive() const { return isAlreadyUpgraded(); } virtual Bool isSubObjectsUpgrade() { return false; } diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/PhysicsUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/PhysicsUpdate.h index 4ba389c53d..bd41d3c97f 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/PhysicsUpdate.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/PhysicsUpdate.h @@ -206,7 +206,7 @@ class PhysicsBehavior : public UpdateModule, void setIgnoreCollisionsWith(const Object* obj); Bool isIgnoringCollisionsWith(ObjectID id) const; - inline Bool getAllowCollideForce() const { return getFlag(ALLOW_COLLIDE_FORCE); } + Bool getAllowCollideForce() const { return getFlag(ALLOW_COLLIDE_FORCE); } protected: @@ -282,8 +282,8 @@ class PhysicsBehavior : public UpdateModule, Bool m_originalAllowBounce; ///< orignal state of allow bounce - inline void setFlag(PhysicsFlagsType f, Bool set) { if (set) m_flags |= f; else m_flags &= ~f; } - inline Bool getFlag(PhysicsFlagsType f) const { return (m_flags & f) != 0; } + void setFlag(PhysicsFlagsType f, Bool set) { if (set) m_flags |= f; else m_flags &= ~f; } + Bool getFlag(PhysicsFlagsType f) const { return (m_flags & f) != 0; } }; diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SlowDeathBehavior.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SlowDeathBehavior.h index 7fb3e462f5..db778297fd 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SlowDeathBehavior.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SlowDeathBehavior.h @@ -100,7 +100,7 @@ class SlowDeathBehaviorModuleData : public UpdateModuleData SlowDeathBehaviorModuleData(); static void buildFieldParse(MultiIniFieldParse& p); - inline Bool hasNonLodEffects() const + Bool hasNonLodEffects() const { return (m_maskOfLoadedEffects & SlowDeathBehaviorModuleData::HAS_NON_LOD_EFFECTS) != 0; } @@ -156,8 +156,8 @@ class SlowDeathBehavior : public UpdateModule, protected: void doPhaseStuff(SlowDeathPhaseType sdphase); - inline Bool isSlowDeathActivated() const { return (m_flags & (1<m_upgradeMuxData.m_requiresAllTriggers; } - inline Bool isUpgradeActive() const { return isAlreadyUpgraded(); } + Bool isUpgradeActive() const { return isAlreadyUpgraded(); } virtual Bool isSubObjectsUpgrade() { return false; } private: diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/ObjectCreationList.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/ObjectCreationList.h index d29b0f581b..d39dd19c00 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/ObjectCreationList.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/ObjectCreationList.h @@ -134,7 +134,7 @@ class ObjectCreationList // 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 ) + static Object* create( const ObjectCreationList* ocl, const Object* primaryObj, const Coord3D *primary, const Coord3D *secondary, Bool createOwner, UnsignedInt lifetimeFrames = 0 ) { if( ocl ) return ocl->createInternal( primaryObj, primary, secondary, createOwner, lifetimeFrames ); @@ -144,7 +144,7 @@ class ObjectCreationList // 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 Object* create(const ObjectCreationList* ocl, const Object* primaryObj, const Coord3D *primary, const Coord3D *secondary, Real angle, UnsignedInt lifetimeFrames = 0 ) + static Object* create(const ObjectCreationList* ocl, const Object* primaryObj, const Coord3D *primary, const Coord3D *secondary, Real angle, UnsignedInt lifetimeFrames = 0 ) { if (ocl) return ocl->createInternal( primaryObj, primary, secondary, angle, lifetimeFrames ); @@ -154,7 +154,7 @@ class ObjectCreationList // 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 Object* create( const ObjectCreationList* ocl, const Object* primary, const Object* secondary, UnsignedInt lifetimeFrames = 0 ) + static Object* create( const ObjectCreationList* ocl, const Object* primary, const Object* secondary, UnsignedInt lifetimeFrames = 0 ) { if (ocl) return ocl->createInternal( primary, secondary, lifetimeFrames ); diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h index 00bf6486bd..010418a47c 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h @@ -214,22 +214,22 @@ class CellAndObjectIntersection // not MPO: we allocate these in arrays /** return the Cell for this COI (null if the COI is not in use) */ - inline PartitionCell *getCell() { return m_cell; } + PartitionCell *getCell() { return m_cell; } /** return the Module for this COI (null if the COI is not in use) */ - inline PartitionData *getModule() { return m_module; } + PartitionData *getModule() { return m_module; } /** return the previous COI in the Cell's list of COIs. */ - inline CellAndObjectIntersection *getPrevCoi() { return m_prevCoi; } + CellAndObjectIntersection *getPrevCoi() { return m_prevCoi; } /** return the next COI in the Cell's list of COIs. */ - inline CellAndObjectIntersection *getNextCoi() { return m_nextCoi; } + CellAndObjectIntersection *getNextCoi() { return m_nextCoi; } // only for use by PartitionCell. void friend_addToCellList(CellAndObjectIntersection **pListHead); @@ -342,13 +342,13 @@ class PartitionCell : public Snapshot // not MPO: allocated in an array void invalidateShroudedStatusForAllCois(Int playerIndex); #ifdef PM_CACHE_TERRAIN_HEIGHT - inline Real getLoTerrain() const { return m_loTerrainZ; } - inline Real getHiTerrain() const { return m_hiTerrainZ; } + Real getLoTerrain() const { return m_loTerrainZ; } + Real getHiTerrain() const { return m_hiTerrainZ; } #endif void getCellCenterPos(Real& x, Real& y); - inline CellAndObjectIntersection *getFirstCoiInCell() { return m_firstCoiInCell; } + CellAndObjectIntersection *getFirstCoiInCell() { return m_firstCoiInCell; } #ifdef RTS_DEBUG void validateCoiList(); @@ -511,7 +511,7 @@ class PartitionData : public MemoryPoolObject ObjectShroudStatus getShroudedStatus(Int playerIndex); - inline Int wasSeenByAnyPlayers() const ///isInListDirtyModules(&m_dirtyModules); } - inline void prependToDirtyModules(PartitionData* o) + void prependToDirtyModules(PartitionData* o) { o->prependToDirtyModules(&m_dirtyModules); } - inline void removeFromDirtyModules(PartitionData* o) + void removeFromDirtyModules(PartitionData* o) { o->removeFromDirtyModules(&m_dirtyModules); } - inline void removeAllDirtyModules() + void removeAllDirtyModules() { while (m_dirtyModules) { diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/TerrainLogic.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/TerrainLogic.h index e02d9192eb..f56c268ae6 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/TerrainLogic.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/TerrainLogic.h @@ -194,16 +194,16 @@ class Bridge : public MemoryPoolObject Bool isPointOnBridge(const Coord3D *pLoc); Drawable *pickBridge(const Vector3 &from, const Vector3 &to, Vector3 *pos); void updateDamageState(void); ///< Updates a bridge's damage info. - inline const BridgeInfo *peekBridgeInfo(void) const {return &m_bridgeInfo;} - inline PathfindLayerEnum getLayer(void) const {return m_layer;} - inline void setLayer(PathfindLayerEnum layer) {m_layer = layer;} + const BridgeInfo *peekBridgeInfo(void) const {return &m_bridgeInfo;} + PathfindLayerEnum getLayer(void) const {return m_layer;} + void setLayer(PathfindLayerEnum layer) {m_layer = layer;} const Region2D *getBounds(void) const {return &m_bounds;} Bool isCellOnEnd(const Region2D *cell); // Is pathfind cell on the sides of the bridge Bool isCellOnSide(const Region2D *cell); // Is pathfind cell on the end of the bridge Bool isCellEntryPoint(const Region2D *cell); // Is pathfind cell an entry point to the bridge - inline void setBridgeObjectID( ObjectID id ) { m_bridgeInfo.bridgeObjectID = id; } - inline void setTowerObjectID( ObjectID id, BridgeTowerType which ) { m_bridgeInfo.towerObjectID[ which ] = id; } + void setBridgeObjectID( ObjectID id ) { m_bridgeInfo.bridgeObjectID = id; } + void setTowerObjectID( ObjectID id, BridgeTowerType which ) { m_bridgeInfo.towerObjectID[ which ] = id; } }; diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/VictoryConditions.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/VictoryConditions.h index adf651bda6..27e69fccef 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/VictoryConditions.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/VictoryConditions.h @@ -55,8 +55,8 @@ class VictoryConditionsInterface : public SubsystemInterface virtual void reset( void ) = 0; virtual void update( void ) = 0; - inline void setVictoryConditions( Int victoryConditions ) { m_victoryConditions = victoryConditions; } - inline Int getVictoryConditions( void ) { return m_victoryConditions; } + void setVictoryConditions( Int victoryConditions ) { m_victoryConditions = victoryConditions; } + Int getVictoryConditions( void ) { return m_victoryConditions; } virtual Bool hasAchievedVictory(Player *player) = 0; ///< has a specific player and his allies won? virtual Bool hasBeenDefeated(Player *player) = 0; ///< has a specific player and his allies lost? diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h index fa608967f4..91c03fbb08 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h @@ -276,14 +276,14 @@ class WeaponBonus clear(); } - inline void clear() + void clear() { for (int i = 0; i < FIELD_COUNT; ++i) m_field[i] = 1.0f; } - inline Real getField(Field f) const { return m_field[f]; } - inline void setField(Field f, Real v) { m_field[f] = v; } + Real getField(Field f) const { return m_field[f]; } + void setField(Field f, Real v) { m_field[f] = v; } void appendBonuses(WeaponBonus& bonus) const; @@ -357,7 +357,7 @@ class WeaponTemplate : public MemoryPoolObject Bool isOverride( void ) { return m_nextTemplate != NULL; } /// field table for loading the values from an INI - inline const FieldParse *getFieldParse() const { return TheWeaponTemplateFieldParseTable; } + const FieldParse *getFieldParse() const { return TheWeaponTemplateFieldParseTable; } /** fire the weapon. return the logic-frame in which the damage will be dealt. @@ -407,62 +407,62 @@ class WeaponTemplate : public MemoryPoolObject Int getPreAttackDelay(const WeaponBonus& bonus) const; Bool isContactWeapon() const; - inline Real getShockWaveAmount() const { return m_shockWaveAmount; } - inline Real getShockWaveRadius() const { return m_shockWaveRadius; } - inline Real getShockWaveTaperOff() const { return m_shockWaveTaperOff; } - - inline Real getRequestAssistRange() const {return m_requestAssistRange;} - inline AsciiString getName() const { return m_name; } - inline AsciiString getProjectileStreamName() const { return m_projectileStreamName; } - inline AsciiString getLaserName() const { return m_laserName; } - inline const AsciiString& getLaserBoneName() const { return m_laserBoneName; } - inline NameKeyType getNameKey() const { return m_nameKey; } - inline Real getWeaponSpeed() const { return m_weaponSpeed; } - inline Real getMinWeaponSpeed() const { return m_minWeaponSpeed; } - inline Bool isScaleWeaponSpeed() const { return m_isScaleWeaponSpeed; } - inline Real getWeaponRecoilAmount() const { return m_weaponRecoil; } - inline Real getMinTargetPitch() const { return m_minTargetPitch; } - inline Real getMaxTargetPitch() const { return m_maxTargetPitch; } - inline Real getRadiusDamageAngle() const { return m_radiusDamageAngle; } - inline DamageType getDamageType() const { return m_damageType; } - inline ObjectStatusTypes getDamageStatusType() const { return m_damageStatusType; } - inline DeathType getDeathType() const { return m_deathType; } - inline Real getContinueAttackRange() const { return m_continueAttackRange; } - inline Real getInfantryInaccuracyDist() const { return m_infantryInaccuracyDist; } - inline Real getAimDelta() const { return m_aimDelta; } - inline Real getScatterRadius() const { return m_scatterRadius; } - inline Real getScatterTargetScalar() const { return m_scatterTargetScalar; } - inline const ThingTemplate* getProjectileTemplate() const { return m_projectileTmpl; } - inline Bool getDamageDealtAtSelfPosition() const { return m_damageDealtAtSelfPosition; } - inline Int getAffectsMask() const { return m_affectsMask; } - inline Int getProjectileCollideMask() const { return m_collideMask; } - inline WeaponReloadType getReloadType() const { return m_reloadType; } - inline WeaponPrefireType getPrefireType() const { return m_prefireType; } - inline Bool getAutoReloadsClip() const { return m_reloadType == AUTO_RELOAD; } - inline Int getClipSize() const { return m_clipSize; } - inline Int getContinuousFireOneShotsNeeded() const { return m_continuousFireOneShotsNeeded; } - inline Int getContinuousFireTwoShotsNeeded() const { return m_continuousFireTwoShotsNeeded; } - inline UnsignedInt getContinuousFireCoastFrames() const { return m_continuousFireCoastFrames; } - inline UnsignedInt getAutoReloadWhenIdleFrames() const { return m_autoReloadWhenIdleFrames; } - inline UnsignedInt getSuspendFXDelay() const { return m_suspendFXDelay; } - - inline const FXList* getFireFX(VeterancyLevel v) const { return m_fireFXs[v]; } - inline const FXList* getProjectileDetonateFX(VeterancyLevel v) const { return m_projectileDetonateFXs[v]; } - 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 AudioEventRTS& getFireSound() const { return m_fireSound; } - inline UnsignedInt getFireSoundLoopTime() const { return m_fireSoundLoopTime; } - inline const std::vector& getScatterTargetsVector() const { return m_scatterTargets; } - inline const WeaponBonusSet* getExtraBonus() const { return m_extraBonus; } - inline Int getShotsPerBarrel() const { return m_shotsPerBarrel; } - inline Int getAntiMask() const { return m_antiMask; } - inline Bool isLeechRangeWeapon() const { return m_leechRangeWeapon; } - inline Bool isCapableOfFollowingWaypoint() const { return m_capableOfFollowingWaypoint; } - inline Bool isShowsAmmoPips() const { return m_isShowsAmmoPips; } - inline Bool isPlayFXWhenStealthed() const { return m_playFXWhenStealthed; } - inline Bool getDieOnDetonate() const { return m_dieOnDetonate; } + Real getShockWaveAmount() const { return m_shockWaveAmount; } + Real getShockWaveRadius() const { return m_shockWaveRadius; } + Real getShockWaveTaperOff() const { return m_shockWaveTaperOff; } + + Real getRequestAssistRange() const {return m_requestAssistRange;} + AsciiString getName() const { return m_name; } + AsciiString getProjectileStreamName() const { return m_projectileStreamName; } + AsciiString getLaserName() const { return m_laserName; } + const AsciiString& getLaserBoneName() const { return m_laserBoneName; } + NameKeyType getNameKey() const { return m_nameKey; } + Real getWeaponSpeed() const { return m_weaponSpeed; } + Real getMinWeaponSpeed() const { return m_minWeaponSpeed; } + Bool isScaleWeaponSpeed() const { return m_isScaleWeaponSpeed; } + Real getWeaponRecoilAmount() const { return m_weaponRecoil; } + Real getMinTargetPitch() const { return m_minTargetPitch; } + Real getMaxTargetPitch() const { return m_maxTargetPitch; } + Real getRadiusDamageAngle() const { return m_radiusDamageAngle; } + DamageType getDamageType() const { return m_damageType; } + ObjectStatusTypes getDamageStatusType() const { return m_damageStatusType; } + DeathType getDeathType() const { return m_deathType; } + Real getContinueAttackRange() const { return m_continueAttackRange; } + Real getInfantryInaccuracyDist() const { return m_infantryInaccuracyDist; } + Real getAimDelta() const { return m_aimDelta; } + Real getScatterRadius() const { return m_scatterRadius; } + Real getScatterTargetScalar() const { return m_scatterTargetScalar; } + const ThingTemplate* getProjectileTemplate() const { return m_projectileTmpl; } + Bool getDamageDealtAtSelfPosition() const { return m_damageDealtAtSelfPosition; } + Int getAffectsMask() const { return m_affectsMask; } + Int getProjectileCollideMask() const { return m_collideMask; } + WeaponReloadType getReloadType() const { return m_reloadType; } + WeaponPrefireType getPrefireType() const { return m_prefireType; } + Bool getAutoReloadsClip() const { return m_reloadType == AUTO_RELOAD; } + Int getClipSize() const { return m_clipSize; } + Int getContinuousFireOneShotsNeeded() const { return m_continuousFireOneShotsNeeded; } + Int getContinuousFireTwoShotsNeeded() const { return m_continuousFireTwoShotsNeeded; } + UnsignedInt getContinuousFireCoastFrames() const { return m_continuousFireCoastFrames; } + UnsignedInt getAutoReloadWhenIdleFrames() const { return m_autoReloadWhenIdleFrames; } + UnsignedInt getSuspendFXDelay() const { return m_suspendFXDelay; } + + const FXList* getFireFX(VeterancyLevel v) const { return m_fireFXs[v]; } + const FXList* getProjectileDetonateFX(VeterancyLevel v) const { return m_projectileDetonateFXs[v]; } + const ObjectCreationList* getFireOCL(VeterancyLevel v) const { return m_fireOCLs[v]; } + const ObjectCreationList* getProjectileDetonationOCL(VeterancyLevel v) const { return m_projectileDetonationOCLs[v]; } + const ParticleSystemTemplate* getProjectileExhaust(VeterancyLevel v) const { return m_projectileExhausts[v]; } + + const AudioEventRTS& getFireSound() const { return m_fireSound; } + UnsignedInt getFireSoundLoopTime() const { return m_fireSoundLoopTime; } + const std::vector& getScatterTargetsVector() const { return m_scatterTargets; } + const WeaponBonusSet* getExtraBonus() const { return m_extraBonus; } + Int getShotsPerBarrel() const { return m_shotsPerBarrel; } + Int getAntiMask() const { return m_antiMask; } + Bool isLeechRangeWeapon() const { return m_leechRangeWeapon; } + Bool isCapableOfFollowingWaypoint() const { return m_capableOfFollowingWaypoint; } + Bool isShowsAmmoPips() const { return m_isShowsAmmoPips; } + Bool isPlayFXWhenStealthed() const { return m_playFXWhenStealthed; } + Bool getDieOnDetonate() const { return m_dieOnDetonate; } Bool shouldProjectileCollideWith( const Object* projectileLauncher, @@ -689,32 +689,32 @@ class Weapon : public MemoryPoolObject, Bool isLaser() const { return m_template->getLaserName().isNotEmpty(); } void createLaser( const Object *sourceObj, const Object *victimObj, const Coord3D *victimPos ); - inline const WeaponTemplate* getTemplate() const { return m_template; } - inline WeaponSlotType getWeaponSlot() const { return m_wslot; } - inline AsciiString getName() const { return m_template->getName(); } - inline UnsignedInt getLastShotFrame() const { return m_lastFireFrame; } ///< frame a shot was last fired on + const WeaponTemplate* getTemplate() const { return m_template; } + WeaponSlotType getWeaponSlot() const { return m_wslot; } + AsciiString getName() const { return m_template->getName(); } + UnsignedInt getLastShotFrame() const { return m_lastFireFrame; } ///< frame a shot was last fired on // If we are "reloading", then m_ammoInClip is a lie. It will say full. - inline UnsignedInt getRemainingAmmo() const { return (getStatus() == RELOADING_CLIP) ? 0 : m_ammoInClip; } - inline WeaponReloadType getReloadType() const { return m_template->getReloadType(); } - inline Bool getAutoReloadsClip() const { return m_template->getAutoReloadsClip(); } - inline Real getAimDelta() const { return m_template->getAimDelta(); } - inline Real getScatterRadius() const { return m_template->getScatterRadius(); } - inline Real getScatterTargetScalar() const { return m_template->getScatterTargetScalar(); } - inline Int getAntiMask() const { return m_template->getAntiMask(); } - inline Bool isCapableOfFollowingWaypoint() const { return m_template->isCapableOfFollowingWaypoint(); } - inline Int getContinuousFireOneShotsNeeded() const { return m_template->getContinuousFireOneShotsNeeded(); } - inline Int getContinuousFireTwoShotsNeeded() const { return m_template->getContinuousFireTwoShotsNeeded(); } - inline UnsignedInt getContinuousFireCoastFrames() const { return m_template->getContinuousFireCoastFrames(); } - 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 DamageType getDamageType() const { return m_template->getDamageType(); } - inline DeathType getDeathType() const { return m_template->getDeathType(); } - inline Real getContinueAttackRange() const { return m_template->getContinueAttackRange(); } - inline Bool isShowsAmmoPips() const { return m_template->isShowsAmmoPips(); } - inline Int getClipSize() const { return m_template->getClipSize(); } + UnsignedInt getRemainingAmmo() const { return (getStatus() == RELOADING_CLIP) ? 0 : m_ammoInClip; } + WeaponReloadType getReloadType() const { return m_template->getReloadType(); } + Bool getAutoReloadsClip() const { return m_template->getAutoReloadsClip(); } + Real getAimDelta() const { return m_template->getAimDelta(); } + Real getScatterRadius() const { return m_template->getScatterRadius(); } + Real getScatterTargetScalar() const { return m_template->getScatterTargetScalar(); } + Int getAntiMask() const { return m_template->getAntiMask(); } + Bool isCapableOfFollowingWaypoint() const { return m_template->isCapableOfFollowingWaypoint(); } + Int getContinuousFireOneShotsNeeded() const { return m_template->getContinuousFireOneShotsNeeded(); } + Int getContinuousFireTwoShotsNeeded() const { return m_template->getContinuousFireTwoShotsNeeded(); } + UnsignedInt getContinuousFireCoastFrames() const { return m_template->getContinuousFireCoastFrames(); } + UnsignedInt getAutoReloadWhenIdleFrames() const { return m_template->getAutoReloadWhenIdleFrames(); } + const AudioEventRTS& getFireSound() const { return m_template->getFireSound(); } + UnsignedInt getFireSoundLoopTime() const { return m_template->getFireSoundLoopTime(); } + DamageType getDamageType() const { return m_template->getDamageType(); } + DeathType getDeathType() const { return m_template->getDeathType(); } + Real getContinueAttackRange() const { return m_template->getContinueAttackRange(); } + Bool isShowsAmmoPips() const { return m_template->isShowsAmmoPips(); } + Int getClipSize() const { return m_template->getClipSize(); } // Contact weapons (like car bombs) need to basically collide with their target. - inline Bool isContactWeapon() const { return m_template->isContactWeapon(); } + Bool isContactWeapon() const { return m_template->isContactWeapon(); } Int getClipReloadTime(const Object *source) const; @@ -843,7 +843,7 @@ class WeaponStore : public SubsystemInterface const WeaponTemplate *findWeaponTemplateByNameKey( NameKeyType key ) const { return findWeaponTemplatePrivate( key ); } // this dynamically allocates a new Weapon, which is owned (and must be freed!) by the caller. - inline Weapon* allocateNewWeapon(const WeaponTemplate *tmpl, WeaponSlotType wslot) const + Weapon* allocateNewWeapon(const WeaponTemplate *tmpl, WeaponSlotType wslot) const { return newInstance(Weapon)(tmpl, wslot); // my, that was easy } diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h index ade37299a4..591fb04b03 100644 --- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h +++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h @@ -133,7 +133,7 @@ class BaseHeightMapRenderObjClass : public RenderObjClass, public DX8_CleanupHoo } - inline UnsignedByte getClipHeight(Int x, Int y) const + UnsignedByte getClipHeight(Int x, Int y) const { Int xextent = m_map->getXExtent() - 1; Int yextent = m_map->getYExtent() - 1; diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h index 32bdbc4a53..95c6db84f1 100644 --- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h +++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h @@ -237,7 +237,7 @@ struct ModelConditionInfo PUBLIC_BONES_VALID = 0x0010 }; - inline ModelConditionInfo() + ModelConditionInfo() { clear(); } @@ -246,8 +246,8 @@ struct ModelConditionInfo void loadAnimations() const; void preloadAssets( TimeOfDay timeOfDay, Real scale ); ///< preload any assets for time of day - 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]; } + Int getConditionsYesCount() const { DEBUG_ASSERTCRASH(m_conditionsYesVec.size() > 0, ("empty m_conditionsYesVec.size(), see srj")); return m_conditionsYesVec.size(); } + const ModelConditionFlags& getNthConditionsYes(Int i) const { return m_conditionsYesVec[i]; } #if defined(RTS_DEBUG) inline AsciiString getDescription() const { return m_description; } #endif @@ -422,7 +422,7 @@ class W3DModelDraw : public DrawModule, public ObjectDrawInterface virtual const ObjectDrawInterface* getObjectDrawInterface() const { return this; } ///@todo: I had to make this public because W3DDevice needs access for casting shadows -MW - inline RenderObjClass *getRenderObject() { return m_renderObject; } + RenderObjClass *getRenderObject() { return m_renderObject; } virtual Bool updateBonesForClientParticleSystems( void );///< this will reposition particle systems on the fly ML virtual void onDrawableBoundToObject(); @@ -433,7 +433,7 @@ class W3DModelDraw : public DrawModule, public ObjectDrawInterface virtual void onRenderObjRecreated(void){}; - inline const ModelConditionInfo* getCurState() const { return m_curState; } + const ModelConditionInfo* getCurState() const { return m_curState; } void setModelState(const ModelConditionInfo* newState); const ModelConditionInfo* findBestInfo(const ModelConditionFlags& c) const; @@ -448,7 +448,7 @@ class W3DModelDraw : public DrawModule, public ObjectDrawInterface Bool setCurAnimDurationInMsec(Real duration); - inline Bool getFullyObscuredByShroud() const { return m_fullyObscuredByShroud; } + Bool getFullyObscuredByShroud() const { return m_fullyObscuredByShroud; } private: diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DShadow.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DShadow.h index df0e5d4d01..64124a64a1 100644 --- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DShadow.h +++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DShadow.h @@ -52,8 +52,8 @@ class W3DShadowManager void invalidateCachedLightPositions(void); ///m_width) m_drawWidthX = m_width;} - inline void setDrawHeight(Int height) {m_drawHeightY = height; if (m_drawHeightY>m_height) m_drawHeightY = m_height;} + Int getDrawWidth(void) {return m_drawWidthX;} + Int getDrawHeight(void) {return m_drawHeightY;} + void setDrawWidth(Int width) {m_drawWidthX = width; if (m_drawWidthX>m_width) m_drawWidthX = m_width;} + void setDrawHeight(Int height) {m_drawHeightY = height; if (m_drawHeightY>m_height) m_drawHeightY = m_height;} virtual Int getBorderSize(void) {return m_borderSize;} - inline Int getBorderSizeInline(void) const { return m_borderSize; } + Int getBorderSizeInline(void) const { return m_borderSize; } /// Get height with the offset that HeightMapRenderObjClass uses built in. - inline UnsignedByte getDisplayHeight(Int x, Int y) { return m_data[x+m_drawOriginX+m_width*(y+m_drawOriginY)];} + UnsignedByte getDisplayHeight(Int x, Int y) { return m_data[x+m_drawOriginX+m_width*(y+m_drawOriginY)];} /// Get height in normal coordinates. - inline UnsignedByte getHeight(Int xIndex, Int yIndex) + UnsignedByte getHeight(Int xIndex, Int yIndex) { Int ndx = (yIndex*m_width)+xIndex; if ((ndx>=0) && (ndx> 3)] & (1<<(xIndex&0x7)); } diff --git a/GeneralsMD/Code/Libraries/Include/Lib/BaseType.h b/GeneralsMD/Code/Libraries/Include/Lib/BaseType.h index 0a2c026728..e0a8c74641 100644 --- a/GeneralsMD/Code/Libraries/Include/Lib/BaseType.h +++ b/GeneralsMD/Code/Libraries/Include/Lib/BaseType.h @@ -372,7 +372,7 @@ struct RGBColor { Real red, green, blue; // range between 0 and 1 - inline Int getAsInt() const + Int getAsInt() const { return ((Int)(red * 255.0) << 16) | @@ -380,7 +380,7 @@ struct RGBColor ((Int)(blue * 255.0) << 0); } - inline void setFromInt(Int c) + void setFromInt(Int c) { red = ((c >> 16) & 0xff) / 255.0f; green = ((c >> 8) & 0xff) / 255.0f; diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8fvf.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8fvf.h index 30098c9805..e9137e9301 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8fvf.h +++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8fvf.h @@ -260,22 +260,22 @@ class FVFInfoClass : public W3DMPO public: FVFInfoClass(unsigned FVF, unsigned vertex_size=0); - inline unsigned Get_Location_Offset() const { return location_offset; } - inline unsigned Get_Normal_Offset() const { return normal_offset; } + unsigned Get_Location_Offset() const { return location_offset; } + unsigned Get_Normal_Offset() const { return normal_offset; } #ifdef WWDEBUG inline unsigned Get_Tex_Offset(unsigned int n) const { WWASSERT(n>SHIFT_DEPTHCOMPARE); } - inline DepthMaskType Get_Depth_Mask(void) const { return (DepthMaskType)((ShaderBits&MASK_DEPTHMASK)>>SHIFT_DEPTHMASK); } - inline ColorMaskType Get_Color_Mask(void) const { return (ColorMaskType)((ShaderBits&MASK_COLORMASK)>>SHIFT_COLORMASK); } - inline DetailAlphaFuncType Get_Post_Detail_Alpha_Func(void) const { return (DetailAlphaFuncType)((ShaderBits&MASK_POSTDETAILALPHAFUNC)>>SHIFT_POSTDETAILALPHAFUNC); } - inline DetailColorFuncType Get_Post_Detail_Color_Func(void) const { return (DetailColorFuncType)((ShaderBits&MASK_POSTDETAILCOLORFUNC)>>SHIFT_POSTDETAILCOLORFUNC); } - inline AlphaTestType Get_Alpha_Test(void) const { return (AlphaTestType)((ShaderBits&MASK_ALPHATEST)>>SHIFT_ALPHATEST); } - inline CullModeType Get_Cull_Mode(void) const { return (CullModeType)((ShaderBits&MASK_CULLMODE)>>SHIFT_CULLMODE); } - inline DstBlendFuncType Get_Dst_Blend_Func(void) const { return (DstBlendFuncType)((ShaderBits&MASK_DSTBLEND)>>SHIFT_DSTBLEND); } - inline FogFuncType Get_Fog_Func(void) const { return (FogFuncType)((ShaderBits&MASK_FOG)>>SHIFT_FOG); } - inline PriGradientType Get_Primary_Gradient(void) const { return (PriGradientType)((ShaderBits&MASK_PRIGRADIENT)>>SHIFT_PRIGRADIENT); } - inline SecGradientType Get_Secondary_Gradient(void) const { return (SecGradientType)((ShaderBits&MASK_SECGRADIENT)>>SHIFT_SECGRADIENT); } - inline SrcBlendFuncType Get_Src_Blend_Func(void) const { return (SrcBlendFuncType)((ShaderBits&MASK_SRCBLEND)>>SHIFT_SRCBLEND); } - inline TexturingType Get_Texturing(void) const { return (TexturingType)((ShaderBits&MASK_TEXTURING)>>SHIFT_TEXTURING); } - inline NPatchEnableType Get_NPatch_Enable(void) const { return (NPatchEnableType)((ShaderBits&MASK_NPATCHENABLE)>>SHIFT_NPATCHENABLE); } - - inline void Set_Depth_Compare(DepthCompareType x) { ShaderBits&=~MASK_DEPTHCOMPARE;ShaderBits|=(x<>SHIFT_DEPTHCOMPARE); } + DepthMaskType Get_Depth_Mask(void) const { return (DepthMaskType)((ShaderBits&MASK_DEPTHMASK)>>SHIFT_DEPTHMASK); } + ColorMaskType Get_Color_Mask(void) const { return (ColorMaskType)((ShaderBits&MASK_COLORMASK)>>SHIFT_COLORMASK); } + DetailAlphaFuncType Get_Post_Detail_Alpha_Func(void) const { return (DetailAlphaFuncType)((ShaderBits&MASK_POSTDETAILALPHAFUNC)>>SHIFT_POSTDETAILALPHAFUNC); } + DetailColorFuncType Get_Post_Detail_Color_Func(void) const { return (DetailColorFuncType)((ShaderBits&MASK_POSTDETAILCOLORFUNC)>>SHIFT_POSTDETAILCOLORFUNC); } + AlphaTestType Get_Alpha_Test(void) const { return (AlphaTestType)((ShaderBits&MASK_ALPHATEST)>>SHIFT_ALPHATEST); } + CullModeType Get_Cull_Mode(void) const { return (CullModeType)((ShaderBits&MASK_CULLMODE)>>SHIFT_CULLMODE); } + DstBlendFuncType Get_Dst_Blend_Func(void) const { return (DstBlendFuncType)((ShaderBits&MASK_DSTBLEND)>>SHIFT_DSTBLEND); } + FogFuncType Get_Fog_Func(void) const { return (FogFuncType)((ShaderBits&MASK_FOG)>>SHIFT_FOG); } + PriGradientType Get_Primary_Gradient(void) const { return (PriGradientType)((ShaderBits&MASK_PRIGRADIENT)>>SHIFT_PRIGRADIENT); } + SecGradientType Get_Secondary_Gradient(void) const { return (SecGradientType)((ShaderBits&MASK_SECGRADIENT)>>SHIFT_SECGRADIENT); } + SrcBlendFuncType Get_Src_Blend_Func(void) const { return (SrcBlendFuncType)((ShaderBits&MASK_SRCBLEND)>>SHIFT_SRCBLEND); } + TexturingType Get_Texturing(void) const { return (TexturingType)((ShaderBits&MASK_TEXTURING)>>SHIFT_TEXTURING); } + NPatchEnableType Get_NPatch_Enable(void) const { return (NPatchEnableType)((ShaderBits&MASK_NPATCHENABLE)>>SHIFT_NPATCHENABLE); } + + void Set_Depth_Compare(DepthCompareType x) { ShaderBits&=~MASK_DEPTHCOMPARE;ShaderBits|=(x<=first && cur<=second) is = true; if (cur<=first && cur>=second) is = true; From 3209a5b29f5cf1b610067c84963f104394260d8a Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Thu, 11 Dec 2025 23:33:24 +0100 Subject: [PATCH 26/70] unify(matpass): Merge WW3D2 matpass code (#1982) This fixes a runtime crash in Generals due to incomplete code merging --- Generals/Code/Libraries/Source/WWVegas/WW3D2/matpass.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/matpass.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/matpass.h index a6d9a3f7f9..afa2226464 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/matpass.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/matpass.h @@ -26,12 +26,13 @@ * * * Original Author:: Greg Hjelstrom * * * - * $Author:: Greg_h $* + * Author : Kenny Mitchell * * * - * $Modtime:: 5/13/01 11:25a $* + * $Modtime:: 06/27/02 1:27p $* * * - * $Revision:: 5 $* + * $Revision:: 6 $* * * + * 06/27/02 KM Texture class abstraction * *---------------------------------------------------------------------------------------------* * Functions: * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ @@ -41,7 +42,6 @@ #include "always.h" #include "shader.h" - class TextureClass; class VertexMaterialClass; class MeshModelClass; @@ -93,7 +93,7 @@ class MaterialPassClass : public RefCountClass protected: - enum { MAX_TEX_STAGES = 2 }; + enum { MAX_TEX_STAGES = 8 }; TextureClass * Texture[MAX_TEX_STAGES]; ShaderClass Shader; From d809648761cd26eb6788fc615c7345e5b8a65de0 Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Sun, 7 Dec 2025 12:51:46 +0100 Subject: [PATCH 27/70] refactor(namekey): Reduce code duplication in NameKeyGenerator functions, misc formatting tweaks (#1959) --- .../Include/Common/NameKeyGenerator.h | 43 ++++++------ .../Code/GameEngine/Include/Common/Upgrade.h | 8 +-- .../GameEngine/Include/GameClient/Image.h | 2 +- .../Source/Common/NameKeyGenerator.cpp | 69 ++++++------------- .../Source/Common/System/Upgrade.cpp | 10 ++- .../Source/GameClient/System/Image.cpp | 4 +- .../Include/Common/NameKeyGenerator.h | 43 ++++++------ .../Code/GameEngine/Include/Common/Upgrade.h | 8 +-- .../GameEngine/Include/GameClient/Image.h | 2 +- .../Source/Common/NameKeyGenerator.cpp | 69 ++++++------------- .../Source/Common/System/Upgrade.cpp | 10 ++- .../Source/GameClient/System/Image.cpp | 4 +- 12 files changed, 104 insertions(+), 168 deletions(-) diff --git a/Generals/Code/GameEngine/Include/Common/NameKeyGenerator.h b/Generals/Code/GameEngine/Include/Common/NameKeyGenerator.h index 5c15847900..8b4b0cdb2b 100644 --- a/Generals/Code/GameEngine/Include/Common/NameKeyGenerator.h +++ b/Generals/Code/GameEngine/Include/Common/NameKeyGenerator.h @@ -36,22 +36,20 @@ #include "Common/AsciiString.h" //------------------------------------------------------------------------------------------------- -/** - Note that NameKeyType isn't a "real" enum, but an enum type used to enforce the - fact that NameKeys are really magic cookies, and aren't really interchangeable - with ints. NAMEKEY_INVALID is always a legal value, but all other values are dynamically - determined at runtime. (The generated code is basically identical, of course.) -*/ +// Note that NameKeyType isn't a "real" enum, but an enum type used to enforce the +// fact that NameKeys are really magic cookies, and aren't really interchangeable +// with integers. NAMEKEY_INVALID is always a legal value, but all other values are dynamically +// determined at runtime. (The generated code is basically identical, of course.) //------------------------------------------------------------------------------------------------- enum NameKeyType CPP_11(: Int) { NAMEKEY_INVALID = 0, - NAMEKEY_MAX = 1<<23, // max ordinal value of a NameKey (some code relies on these fitting into 24 bits safely) - FORCE_NAMEKEYTYPE_LONG = 0x7fffffff // a trick to ensure the NameKeyType is a 32-bit int + NAMEKEY_MAX = 1<<23, // max ordinal value of a NameKey (some code relies on these fitting into 24 bits safely) + FORCE_NAMEKEYTYPE_LONG = 0x7fffffff, // a trick to ensure the NameKeyType is a 32-bit int }; //------------------------------------------------------------------------------------------------- -/** A bucket entry for the name key generator */ +// A bucket entry for the name key generator //------------------------------------------------------------------------------------------------- class Bucket : public MemoryPoolObject { @@ -72,12 +70,12 @@ inline Bucket::Bucket() : m_nextInSocket(NULL), m_key(NAMEKEY_INVALID) { } inline Bucket::~Bucket() { } //------------------------------------------------------------------------------------------------- -/** This class implements the conversion of an arbitrary string into a unique - * integer "key". Calling the nameToKey() method with the same string is - * guaranteed to return the same key. Also, all keys generated by an - * instance of this class are guaranteed to be unique with respect to that - * instance's catalog of names. Multiple instances of this class can be - * created to service multiple namespaces. */ +// This class implements the conversion of an arbitrary string into a unique +// integer "key". Calling the nameToKey() method with the same string is +// guaranteed to return the same key. Also, all keys generated by an +// instance of this class are guaranteed to be unique with respect to that +// instance's catalog of names. Multiple instances of this class can be +// created to service multiple namespaces. //------------------------------------------------------------------------------------------------- class NameKeyGenerator : public SubsystemInterface { @@ -99,16 +97,14 @@ class NameKeyGenerator : public SubsystemInterface NameKeyType nameToKey(const char* name); NameKeyType nameToLowercaseKey(const char *name); - /** - given a key, return the name. this is almost never needed, - except for a few rare cases like object serialization. also - note that it's not particularly fast; it does a dumb linear - search for the key. - */ + // given a key, return the name. this is almost never needed, + // except for a few rare cases like object serialization. also + // note that it's not particularly fast; it does a dumb linear + // search for the key. 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 ); + // 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: @@ -126,6 +122,7 @@ class NameKeyGenerator : public SubsystemInterface NameKeyType nameToKeyImpl(const char* name); NameKeyType nameToLowercaseKeyImpl(const char *name); + NameKeyType createNameKey(UnsignedInt hash, const AsciiString& name); void freeSockets(); diff --git a/Generals/Code/GameEngine/Include/Common/Upgrade.h b/Generals/Code/GameEngine/Include/Common/Upgrade.h index f85b56389c..d4fa42813d 100644 --- a/Generals/Code/GameEngine/Include/Common/Upgrade.h +++ b/Generals/Code/GameEngine/Include/Common/Upgrade.h @@ -232,10 +232,10 @@ class UpgradeCenter : public SubsystemInterface void reset( void ); ///< subsystem interface void update( void ) { } ///< subsystem interface - UpgradeTemplate *firstUpgradeTemplate( void ); ///< return the first upgrade template - const UpgradeTemplate *findUpgradeByKey( NameKeyType key ) const; ///< find upgrade by name key - const UpgradeTemplate *findUpgrade( const AsciiString& name ) const; ///< find and return upgrade by name - const UpgradeTemplate *findVeterancyUpgrade(VeterancyLevel level) const; ///< find and return upgrade by name + UpgradeTemplate *firstUpgradeTemplate( void ); ///< return the first upgrade template + const UpgradeTemplate *findUpgradeByKey( NameKeyType key ) const; ///< find upgrade by name key + const UpgradeTemplate *findUpgrade( const AsciiString& name ) const; ///< find and return upgrade by name + const UpgradeTemplate *findVeterancyUpgrade(VeterancyLevel level) const; ///< find and return upgrade by veterancy level UpgradeTemplate *newUpgrade( const AsciiString& name ); ///< allocate, link, and return new upgrade diff --git a/Generals/Code/GameEngine/Include/GameClient/Image.h b/Generals/Code/GameEngine/Include/GameClient/Image.h index c4e0876cb5..45ebfe4478 100644 --- a/Generals/Code/GameEngine/Include/GameClient/Image.h +++ b/Generals/Code/GameEngine/Include/GameClient/Image.h @@ -128,7 +128,7 @@ class ImageCollection : public SubsystemInterface void load( Int textureSize ); ///< load images - const Image *findImageByName( const AsciiString& name ); ///< find image based on name + const Image *findImageByName( const AsciiString& name ) const; ///< find image based on name /// adds the given image to the collection, transfers ownership to this object void addImage(Image *image); diff --git a/Generals/Code/GameEngine/Source/Common/NameKeyGenerator.cpp b/Generals/Code/GameEngine/Source/Common/NameKeyGenerator.cpp index f9bcd8f348..8cbb276063 100644 --- a/Generals/Code/GameEngine/Source/Common/NameKeyGenerator.cpp +++ b/Generals/Code/GameEngine/Source/Common/NameKeyGenerator.cpp @@ -88,7 +88,7 @@ void NameKeyGenerator::freeSockets() } -/* ------------------------------------------------------------------------ */ +//------------------------------------------------------------------------------------------------- inline UnsignedInt calcHashForString(const char* p) { UnsignedInt result = 0; @@ -98,7 +98,7 @@ inline UnsignedInt calcHashForString(const char* p) return result; } -/* ------------------------------------------------------------------------ */ +//------------------------------------------------------------------------------------------------- inline UnsignedInt calcHashForLowercaseString(const char* p) { UnsignedInt result = 0; @@ -164,71 +164,45 @@ NameKeyType NameKeyGenerator::nameToLowercaseKey(const char *name) } //------------------------------------------------------------------------------------------------- -NameKeyType NameKeyGenerator::nameToKeyImpl(const char* nameString) +NameKeyType NameKeyGenerator::nameToKeyImpl(const char* name) { - Bucket *b; - - UnsignedInt hash = calcHashForString(nameString) % SOCKET_COUNT; + const UnsignedInt hash = calcHashForString(name) % SOCKET_COUNT; - // hmm, do we have it already? + // do we have it already? + const Bucket *b; for (b = m_sockets[hash]; b; b = b->m_nextInSocket) { - if (strcmp(nameString, b->m_nameString.str()) == 0) + if (strcmp(name, 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) - // 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%%)",numOverThresh,(Real)numOverThresh/(Real)(SOCKET_COUNT/20))); - } -#endif - - return result; - + return createNameKey(hash, name); } //------------------------------------------------------------------------------------------------- -NameKeyType NameKeyGenerator::nameToLowercaseKeyImpl(const char* nameString) +NameKeyType NameKeyGenerator::nameToLowercaseKeyImpl(const char* name) { - Bucket *b; + const UnsignedInt hash = calcHashForLowercaseString(name) % SOCKET_COUNT; - UnsignedInt hash = calcHashForLowercaseString(nameString) % SOCKET_COUNT; - - // hmm, do we have it already? + // do we have it already? + const Bucket *b; for (b = m_sockets[hash]; b; b = b->m_nextInSocket) { - if (_stricmp(nameString, b->m_nameString.str()) == 0) + if (_stricmp(name, b->m_nameString.str()) == 0) return b->m_key; } // nope, guess not. let's allocate it. - b = newInstance(Bucket); + return createNameKey(hash, name); +} + +//------------------------------------------------------------------------------------------------- +NameKeyType NameKeyGenerator::createNameKey(UnsignedInt hash, const AsciiString& name) +{ + Bucket *b = newInstance(Bucket); b->m_key = (NameKeyType)m_nextID++; - b->m_nameString = nameString; + b->m_nameString = name; b->m_nextInSocket = m_sockets[hash]; m_sockets[hash] = b; @@ -256,7 +230,6 @@ NameKeyType NameKeyGenerator::nameToLowercaseKeyImpl(const char* nameString) #endif return result; - } //------------------------------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Source/Common/System/Upgrade.cpp b/Generals/Code/GameEngine/Source/Common/System/Upgrade.cpp index f3cbb377fe..24f1831806 100644 --- a/Generals/Code/GameEngine/Source/Common/System/Upgrade.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/Upgrade.cpp @@ -292,7 +292,7 @@ void UpgradeCenter::reset( void ) } //------------------------------------------------------------------------------------------------- -/** Find upgrade matching name key */ +/** Find upgrade by veterancy level */ //------------------------------------------------------------------------------------------------- const UpgradeTemplate *UpgradeCenter::findVeterancyUpgrade( VeterancyLevel level ) const { @@ -301,7 +301,7 @@ const UpgradeTemplate *UpgradeCenter::findVeterancyUpgrade( VeterancyLevel level } //------------------------------------------------------------------------------------------------- -/** Find upgrade matching name key */ +/** Find upgrade by name key */ //------------------------------------------------------------------------------------------------- UpgradeTemplate *UpgradeCenter::findNonConstUpgradeByKey( NameKeyType key ) { @@ -328,7 +328,7 @@ UpgradeTemplate *UpgradeCenter::firstUpgradeTemplate( void ) } //------------------------------------------------------------------------------------------------- -/** Find upgrade matching name key */ +/** Find upgrade by name key */ //------------------------------------------------------------------------------------------------- const UpgradeTemplate *UpgradeCenter::findUpgradeByKey( NameKeyType key ) const { @@ -344,13 +344,11 @@ const UpgradeTemplate *UpgradeCenter::findUpgradeByKey( NameKeyType key ) const } //------------------------------------------------------------------------------------------------- -/** Find upgrade matching name */ +/** Find upgrade by name */ //------------------------------------------------------------------------------------------------- const UpgradeTemplate *UpgradeCenter::findUpgrade( const AsciiString& name ) const { - return findUpgradeByKey( TheNameKeyGenerator->nameToKey( name ) ); - } //------------------------------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Source/GameClient/System/Image.cpp b/Generals/Code/GameEngine/Source/GameClient/System/Image.cpp index 29664571b1..80299d0f40 100644 --- a/Generals/Code/GameEngine/Source/GameClient/System/Image.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/System/Image.cpp @@ -219,9 +219,9 @@ void ImageCollection::addImage( Image *image ) //------------------------------------------------------------------------------------------------- /** Find an image given the image name */ //------------------------------------------------------------------------------------------------- -const Image *ImageCollection::findImageByName( const AsciiString& name ) +const Image *ImageCollection::findImageByName( const AsciiString& name ) const { - std::map::iterator i=m_imageMap.find(TheNameKeyGenerator->nameToLowercaseKey(name)); + std::map::const_iterator i=m_imageMap.find(TheNameKeyGenerator->nameToLowercaseKey(name)); return i==m_imageMap.end()?NULL:i->second; } diff --git a/GeneralsMD/Code/GameEngine/Include/Common/NameKeyGenerator.h b/GeneralsMD/Code/GameEngine/Include/Common/NameKeyGenerator.h index a95e000132..afa205409a 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/NameKeyGenerator.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/NameKeyGenerator.h @@ -36,22 +36,20 @@ #include "Common/AsciiString.h" //------------------------------------------------------------------------------------------------- -/** - Note that NameKeyType isn't a "real" enum, but an enum type used to enforce the - fact that NameKeys are really magic cookies, and aren't really interchangeable - with ints. NAMEKEY_INVALID is always a legal value, but all other values are dynamically - determined at runtime. (The generated code is basically identical, of course.) -*/ +// Note that NameKeyType isn't a "real" enum, but an enum type used to enforce the +// fact that NameKeys are really magic cookies, and aren't really interchangeable +// with integers. NAMEKEY_INVALID is always a legal value, but all other values are dynamically +// determined at runtime. (The generated code is basically identical, of course.) //------------------------------------------------------------------------------------------------- enum NameKeyType CPP_11(: Int) { NAMEKEY_INVALID = 0, - NAMEKEY_MAX = 1<<23, // max ordinal value of a NameKey (some code relies on these fitting into 24 bits safely) - FORCE_NAMEKEYTYPE_LONG = 0x7fffffff // a trick to ensure the NameKeyType is a 32-bit int + NAMEKEY_MAX = 1<<23, // max ordinal value of a NameKey (some code relies on these fitting into 24 bits safely) + FORCE_NAMEKEYTYPE_LONG = 0x7fffffff, // a trick to ensure the NameKeyType is a 32-bit int }; //------------------------------------------------------------------------------------------------- -/** A bucket entry for the name key generator */ +// A bucket entry for the name key generator //------------------------------------------------------------------------------------------------- class Bucket : public MemoryPoolObject { @@ -72,12 +70,12 @@ inline Bucket::Bucket() : m_nextInSocket(NULL), m_key(NAMEKEY_INVALID) { } inline Bucket::~Bucket() { } //------------------------------------------------------------------------------------------------- -/** This class implements the conversion of an arbitrary string into a unique - * integer "key". Calling the nameToKey() method with the same string is - * guaranteed to return the same key. Also, all keys generated by an - * instance of this class are guaranteed to be unique with respect to that - * instance's catalog of names. Multiple instances of this class can be - * created to service multiple namespaces. */ +// This class implements the conversion of an arbitrary string into a unique +// integer "key". Calling the nameToKey() method with the same string is +// guaranteed to return the same key. Also, all keys generated by an +// instance of this class are guaranteed to be unique with respect to that +// instance's catalog of names. Multiple instances of this class can be +// created to service multiple namespaces. //------------------------------------------------------------------------------------------------- class NameKeyGenerator : public SubsystemInterface { @@ -99,16 +97,14 @@ class NameKeyGenerator : public SubsystemInterface NameKeyType nameToKey(const char* name); NameKeyType nameToLowercaseKey(const char *name); - /** - given a key, return the name. this is almost never needed, - except for a few rare cases like object serialization. also - note that it's not particularly fast; it does a dumb linear - search for the key. - */ + // given a key, return the name. this is almost never needed, + // except for a few rare cases like object serialization. also + // note that it's not particularly fast; it does a dumb linear + // search for the key. 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 ); + // 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: @@ -124,6 +120,7 @@ class NameKeyGenerator : public SubsystemInterface NameKeyType nameToKeyImpl(const char* name); NameKeyType nameToLowercaseKeyImpl(const char *name); + NameKeyType createNameKey(UnsignedInt hash, const AsciiString& name); void freeSockets(); diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Upgrade.h b/GeneralsMD/Code/GameEngine/Include/Common/Upgrade.h index 07aa657a65..33ce189637 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/Upgrade.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/Upgrade.h @@ -235,10 +235,10 @@ class UpgradeCenter : public SubsystemInterface void reset( void ); ///< subsystem interface void update( void ) { } ///< subsystem interface - UpgradeTemplate *firstUpgradeTemplate( void ); ///< return the first upgrade template - const UpgradeTemplate *findUpgradeByKey( NameKeyType key ) const; ///< find upgrade by name key - const UpgradeTemplate *findUpgrade( const AsciiString& name ) const; ///< find and return upgrade by name - const UpgradeTemplate *findVeterancyUpgrade(VeterancyLevel level) const; ///< find and return upgrade by name + UpgradeTemplate *firstUpgradeTemplate( void ); ///< return the first upgrade template + const UpgradeTemplate *findUpgradeByKey( NameKeyType key ) const; ///< find upgrade by name key + const UpgradeTemplate *findUpgrade( const AsciiString& name ) const; ///< find and return upgrade by name + const UpgradeTemplate *findVeterancyUpgrade(VeterancyLevel level) const; ///< find and return upgrade by veterancy level UpgradeTemplate *newUpgrade( const AsciiString& name ); ///< allocate, link, and return new upgrade diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Image.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Image.h index 25ec6e0cf3..0714a96bb4 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/Image.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Image.h @@ -128,7 +128,7 @@ class ImageCollection : public SubsystemInterface void load( Int textureSize ); ///< load images - const Image *findImageByName( const AsciiString& name ); ///< find image based on name + const Image *findImageByName( const AsciiString& name ) const; ///< find image based on name /// adds the given image to the collection, transfers ownership to this object void addImage(Image *image); diff --git a/GeneralsMD/Code/GameEngine/Source/Common/NameKeyGenerator.cpp b/GeneralsMD/Code/GameEngine/Source/Common/NameKeyGenerator.cpp index 2ece01f373..6990bfa547 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/NameKeyGenerator.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/NameKeyGenerator.cpp @@ -88,7 +88,7 @@ void NameKeyGenerator::freeSockets() } -/* ------------------------------------------------------------------------ */ +//------------------------------------------------------------------------------------------------- inline UnsignedInt calcHashForString(const char* p) { UnsignedInt result = 0; @@ -98,7 +98,7 @@ inline UnsignedInt calcHashForString(const char* p) return result; } -/* ------------------------------------------------------------------------ */ +//------------------------------------------------------------------------------------------------- inline UnsignedInt calcHashForLowercaseString(const char* p) { UnsignedInt result = 0; @@ -164,71 +164,45 @@ NameKeyType NameKeyGenerator::nameToLowercaseKey(const char *name) } //------------------------------------------------------------------------------------------------- -NameKeyType NameKeyGenerator::nameToKeyImpl(const char* nameString) +NameKeyType NameKeyGenerator::nameToKeyImpl(const char* name) { - Bucket *b; - - UnsignedInt hash = calcHashForString(nameString) % SOCKET_COUNT; + const UnsignedInt hash = calcHashForString(name) % SOCKET_COUNT; - // hmm, do we have it already? + // do we have it already? + const Bucket *b; for (b = m_sockets[hash]; b; b = b->m_nextInSocket) { - if (strcmp(nameString, b->m_nameString.str()) == 0) + if (strcmp(name, 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) - // 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%%)",numOverThresh,(Real)numOverThresh/(Real)(SOCKET_COUNT/20))); - } -#endif - - return result; - + return createNameKey(hash, name); } //------------------------------------------------------------------------------------------------- -NameKeyType NameKeyGenerator::nameToLowercaseKeyImpl(const char* nameString) +NameKeyType NameKeyGenerator::nameToLowercaseKeyImpl(const char* name) { - Bucket *b; + const UnsignedInt hash = calcHashForLowercaseString(name) % SOCKET_COUNT; - UnsignedInt hash = calcHashForLowercaseString(nameString) % SOCKET_COUNT; - - // hmm, do we have it already? + // do we have it already? + const Bucket *b; for (b = m_sockets[hash]; b; b = b->m_nextInSocket) { - if (_stricmp(nameString, b->m_nameString.str()) == 0) + if (_stricmp(name, b->m_nameString.str()) == 0) return b->m_key; } // nope, guess not. let's allocate it. - b = newInstance(Bucket); + return createNameKey(hash, name); +} + +//------------------------------------------------------------------------------------------------- +NameKeyType NameKeyGenerator::createNameKey(UnsignedInt hash, const AsciiString& name) +{ + Bucket *b = newInstance(Bucket); b->m_key = (NameKeyType)m_nextID++; - b->m_nameString = nameString; + b->m_nameString = name; b->m_nextInSocket = m_sockets[hash]; m_sockets[hash] = b; @@ -256,7 +230,6 @@ NameKeyType NameKeyGenerator::nameToLowercaseKeyImpl(const char* nameString) #endif return result; - } //------------------------------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/Upgrade.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/Upgrade.cpp index b93fb4de03..65ff23f91f 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/Upgrade.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/Upgrade.cpp @@ -293,7 +293,7 @@ void UpgradeCenter::reset( void ) } //------------------------------------------------------------------------------------------------- -/** Find upgrade matching name key */ +/** Find upgrade by veterancy level */ //------------------------------------------------------------------------------------------------- const UpgradeTemplate *UpgradeCenter::findVeterancyUpgrade( VeterancyLevel level ) const { @@ -302,7 +302,7 @@ const UpgradeTemplate *UpgradeCenter::findVeterancyUpgrade( VeterancyLevel level } //------------------------------------------------------------------------------------------------- -/** Find upgrade matching name key */ +/** Find upgrade by name key */ //------------------------------------------------------------------------------------------------- UpgradeTemplate *UpgradeCenter::findNonConstUpgradeByKey( NameKeyType key ) { @@ -329,7 +329,7 @@ UpgradeTemplate *UpgradeCenter::firstUpgradeTemplate( void ) } //------------------------------------------------------------------------------------------------- -/** Find upgrade matching name key */ +/** Find upgrade by name key */ //------------------------------------------------------------------------------------------------- const UpgradeTemplate *UpgradeCenter::findUpgradeByKey( NameKeyType key ) const { @@ -345,13 +345,11 @@ const UpgradeTemplate *UpgradeCenter::findUpgradeByKey( NameKeyType key ) const } //------------------------------------------------------------------------------------------------- -/** Find upgrade matching name */ +/** Find upgrade by name */ //------------------------------------------------------------------------------------------------- const UpgradeTemplate *UpgradeCenter::findUpgrade( const AsciiString& name ) const { - return findUpgradeByKey( TheNameKeyGenerator->nameToKey( name ) ); - } //------------------------------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/Image.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/Image.cpp index bcd7b6f79c..4949035b42 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/Image.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/Image.cpp @@ -219,9 +219,9 @@ void ImageCollection::addImage( Image *image ) //------------------------------------------------------------------------------------------------- /** Find an image given the image name */ //------------------------------------------------------------------------------------------------- -const Image *ImageCollection::findImageByName( const AsciiString& name ) +const Image *ImageCollection::findImageByName( const AsciiString& name ) const { - std::map::iterator i=m_imageMap.find(TheNameKeyGenerator->nameToLowercaseKey(name)); + std::map::const_iterator i=m_imageMap.find(TheNameKeyGenerator->nameToLowercaseKey(name)); return i==m_imageMap.end()?NULL:i->second; } From 0c993a939dabb27f51211bec53403f8e9fb3a113 Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Thu, 11 Dec 2025 22:49:59 +0100 Subject: [PATCH 28/70] perf(namekey): Remove all superfluous AsciiString allocations for name key lookups (#1959) --- .../Code/GameEngine/Include/Common/DamageFX.h | 4 +- .../Include/Common/NameKeyGenerator.h | 6 +- .../Code/GameEngine/Include/Common/Upgrade.h | 1 + .../GameEngine/Include/GameClient/Image.h | 7 ++- .../Code/GameEngine/Include/GameLogic/Armor.h | 4 +- .../GameEngine/Include/GameLogic/Weapon.h | 3 +- .../GameEngine/Source/Common/DamageFX.cpp | 19 ++++-- .../Code/GameEngine/Source/Common/INI/INI.cpp | 4 +- .../Source/Common/INI/INIMappedImage.cpp | 10 +--- .../Source/Common/NameKeyGenerator.cpp | 58 +++++++++++++++++++ .../Source/Common/System/FunctionLexicon.cpp | 2 +- .../Source/Common/System/Upgrade.cpp | 13 ++++- .../GUICallbacks/Menus/DifficultySelect.cpp | 3 +- .../GUI/GUICallbacks/Menus/DownloadMenu.cpp | 3 +- .../Menus/KeyboardOptionsMenu.cpp | 3 +- .../GUICallbacks/Menus/LanMapSelectMenu.cpp | 9 +-- .../GUI/GUICallbacks/Menus/MapSelectMenu.cpp | 12 ++-- .../GUI/GUICallbacks/Menus/OptionsMenu.cpp | 6 +- .../GUICallbacks/Menus/SinglePlayerMenu.cpp | 6 +- .../Menus/SkirmishMapSelectMenu.cpp | 12 ++-- .../GUICallbacks/Menus/WOLMapSelectMenu.cpp | 9 +-- .../GameClient/GUI/GameWindowGlobal.cpp | 2 +- .../GUI/GameWindowManagerScript.cpp | 4 +- .../Source/GameClient/GUI/LoadScreen.cpp | 6 +- .../Source/GameClient/System/Image.cpp | 20 ++++++- .../Source/GameLogic/Object/Armor.cpp | 19 ++++-- .../Source/GameLogic/Object/Weapon.cpp | 16 ++++- .../GameClient/Drawable/Draw/W3DModelDraw.cpp | 6 +- .../RadioButtonProperties.cpp | 2 +- .../Tools/GUIEdit/Source/LayoutScheme.cpp | 2 +- .../Code/Tools/GUIEdit/Source/Properties.cpp | 2 +- Generals/Code/Tools/GUIEdit/Source/Save.cpp | 2 +- .../WorldBuilder/src/addplayerdialog.cpp | 3 +- .../Code/GameEngine/Include/Common/DamageFX.h | 4 +- .../Include/Common/NameKeyGenerator.h | 6 +- .../Code/GameEngine/Include/Common/Upgrade.h | 1 + .../GameEngine/Include/GameClient/Image.h | 7 ++- .../Code/GameEngine/Include/GameLogic/Armor.h | 4 +- .../GameEngine/Include/GameLogic/Weapon.h | 3 +- .../GameEngine/Source/Common/DamageFX.cpp | 19 ++++-- .../Code/GameEngine/Source/Common/INI/INI.cpp | 4 +- .../Source/Common/INI/INIMappedImage.cpp | 10 +--- .../Source/Common/NameKeyGenerator.cpp | 58 +++++++++++++++++++ .../Source/Common/System/FunctionLexicon.cpp | 2 +- .../Source/Common/System/Upgrade.cpp | 13 ++++- .../GUICallbacks/Menus/DifficultySelect.cpp | 3 +- .../GUI/GUICallbacks/Menus/DownloadMenu.cpp | 3 +- .../Menus/KeyboardOptionsMenu.cpp | 3 +- .../GUICallbacks/Menus/LanMapSelectMenu.cpp | 9 +-- .../GUI/GUICallbacks/Menus/MapSelectMenu.cpp | 12 ++-- .../GUI/GUICallbacks/Menus/OptionsMenu.cpp | 6 +- .../GUICallbacks/Menus/SinglePlayerMenu.cpp | 6 +- .../Menus/SkirmishMapSelectMenu.cpp | 12 ++-- .../GUICallbacks/Menus/WOLMapSelectMenu.cpp | 9 +-- .../GameClient/GUI/GameWindowGlobal.cpp | 2 +- .../GUI/GameWindowManagerScript.cpp | 4 +- .../Source/GameClient/GUI/LoadScreen.cpp | 6 +- .../Source/GameClient/System/Image.cpp | 20 ++++++- .../Source/GameLogic/Object/Armor.cpp | 19 ++++-- .../Object/Upgrade/CommandSetUpgrade.cpp | 2 +- .../Source/GameLogic/Object/Weapon.cpp | 16 ++++- .../GameClient/Drawable/Draw/W3DModelDraw.cpp | 6 +- .../RadioButtonProperties.cpp | 2 +- .../Tools/GUIEdit/Source/LayoutScheme.cpp | 2 +- .../Code/Tools/GUIEdit/Source/Properties.cpp | 2 +- GeneralsMD/Code/Tools/GUIEdit/Source/Save.cpp | 2 +- .../WorldBuilder/src/addplayerdialog.cpp | 3 +- 67 files changed, 375 insertions(+), 183 deletions(-) diff --git a/Generals/Code/GameEngine/Include/Common/DamageFX.h b/Generals/Code/GameEngine/Include/Common/DamageFX.h index 0b6e3ad711..710a76e55c 100644 --- a/Generals/Code/GameEngine/Include/Common/DamageFX.h +++ b/Generals/Code/GameEngine/Include/Common/DamageFX.h @@ -147,7 +147,9 @@ class DamageFXStore : public SubsystemInterface /** Find the DamageFX with the given name. If no such DamageFX exists, return null. */ - const DamageFX *findDamageFX( AsciiString name ) const; + const DamageFX *findDamageFX( NameKeyType namekey ) const; + const DamageFX *findDamageFX( const AsciiString& name ) const; + const DamageFX *findDamageFX( const char* name ) const; static void parseDamageFXDefinition(INI* ini); diff --git a/Generals/Code/GameEngine/Include/Common/NameKeyGenerator.h b/Generals/Code/GameEngine/Include/Common/NameKeyGenerator.h index 8b4b0cdb2b..2662543140 100644 --- a/Generals/Code/GameEngine/Include/Common/NameKeyGenerator.h +++ b/Generals/Code/GameEngine/Include/Common/NameKeyGenerator.h @@ -90,8 +90,8 @@ class NameKeyGenerator : public SubsystemInterface virtual void update() { } /// 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()); } + NameKeyType nameToKey(const AsciiString& name); + NameKeyType nameToLowercaseKey(const AsciiString& name); /// Given a string, convert into a unique integer key. NameKeyType nameToKey(const char* name); @@ -120,6 +120,8 @@ class NameKeyGenerator : public SubsystemInterface Bool addReservedKey(); #endif + NameKeyType nameToKeyImpl(const AsciiString& name); + NameKeyType nameToLowercaseKeyImpl(const AsciiString& name); NameKeyType nameToKeyImpl(const char* name); NameKeyType nameToLowercaseKeyImpl(const char *name); NameKeyType createNameKey(UnsignedInt hash, const AsciiString& name); diff --git a/Generals/Code/GameEngine/Include/Common/Upgrade.h b/Generals/Code/GameEngine/Include/Common/Upgrade.h index d4fa42813d..9f587e36bc 100644 --- a/Generals/Code/GameEngine/Include/Common/Upgrade.h +++ b/Generals/Code/GameEngine/Include/Common/Upgrade.h @@ -235,6 +235,7 @@ class UpgradeCenter : public SubsystemInterface UpgradeTemplate *firstUpgradeTemplate( void ); ///< return the first upgrade template const UpgradeTemplate *findUpgradeByKey( NameKeyType key ) const; ///< find upgrade by name key const UpgradeTemplate *findUpgrade( const AsciiString& name ) const; ///< find and return upgrade by name + const UpgradeTemplate *findUpgrade( const char* name ) const; ///< find and return upgrade by name const UpgradeTemplate *findVeterancyUpgrade(VeterancyLevel level) const; ///< find and return upgrade by veterancy level UpgradeTemplate *newUpgrade( const AsciiString& name ); ///< allocate, link, and return new upgrade diff --git a/Generals/Code/GameEngine/Include/GameClient/Image.h b/Generals/Code/GameEngine/Include/GameClient/Image.h index 45ebfe4478..0f68b50949 100644 --- a/Generals/Code/GameEngine/Include/GameClient/Image.h +++ b/Generals/Code/GameEngine/Include/GameClient/Image.h @@ -116,6 +116,7 @@ friend class ImageCollection; //------------------------------------------------------------------------------------------------- class ImageCollection : public SubsystemInterface { + typedef std::map ImageMap; public: @@ -128,7 +129,9 @@ class ImageCollection : public SubsystemInterface void load( Int textureSize ); ///< load images + const Image *findImage( NameKeyType namekey ) const; ///< find image based on name key const Image *findImageByName( const AsciiString& name ) const; ///< find image based on name + const Image *findImageByName( const char* name ) const; ///< find image based on name /// adds the given image to the collection, transfers ownership to this object void addImage(Image *image); @@ -136,14 +139,14 @@ class ImageCollection : public SubsystemInterface /// enumerates the list of existing images Image *Enum(unsigned index) { - for (std::map::iterator i=m_imageMap.begin();i!=m_imageMap.end();++i) + for (ImageMap::iterator i=m_imageMap.begin();i!=m_imageMap.end();++i) if (!index--) return i->second; return NULL; } protected: - std::map m_imageMap; ///< maps named keys to images + ImageMap m_imageMap; ///< maps named keys to images }; // INLINING /////////////////////////////////////////////////////////////////////////////////////// diff --git a/Generals/Code/GameEngine/Include/GameLogic/Armor.h b/Generals/Code/GameEngine/Include/GameLogic/Armor.h index 798de573a9..829d1e84f1 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Armor.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Armor.h @@ -105,10 +105,12 @@ class ArmorStore : public SubsystemInterface void reset() { } void update() { } + const ArmorTemplate* findArmorTemplate(NameKeyType namekey) const; /** Find the Armor with the given name. If no such Armor exists, return null. */ - const ArmorTemplate* findArmorTemplate(AsciiString name) const; + const ArmorTemplate* findArmorTemplate(const AsciiString& name) const; + const ArmorTemplate* findArmorTemplate(const char* name) const; inline Armor makeArmor(const ArmorTemplate *tmpl) const { diff --git a/Generals/Code/GameEngine/Include/GameLogic/Weapon.h b/Generals/Code/GameEngine/Include/GameLogic/Weapon.h index 2346a3f8a1..d75cb276f5 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Weapon.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Weapon.h @@ -814,7 +814,8 @@ class WeaponStore : public SubsystemInterface /** Find the WeaponTemplate with the given name. If no such WeaponTemplate exists, return null. */ - const WeaponTemplate *findWeaponTemplate(AsciiString name) const; + const WeaponTemplate *findWeaponTemplate(const AsciiString& name) const; + const WeaponTemplate *findWeaponTemplate(const char* name) const; const WeaponTemplate *findWeaponTemplateByNameKey( NameKeyType key ) const { return findWeaponTemplatePrivate( key ); } // this dynamically allocates a new Weapon, which is owned (and must be freed!) by the caller. diff --git a/Generals/Code/GameEngine/Source/Common/DamageFX.cpp b/Generals/Code/GameEngine/Source/Common/DamageFX.cpp index a107020406..cd1a4fa395 100644 --- a/Generals/Code/GameEngine/Source/Common/DamageFX.cpp +++ b/Generals/Code/GameEngine/Source/Common/DamageFX.cpp @@ -274,11 +274,10 @@ DamageFXStore::~DamageFXStore() } //------------------------------------------------------------------------------------------------- -const DamageFX *DamageFXStore::findDamageFX(AsciiString name) const +const DamageFX *DamageFXStore::findDamageFX(NameKeyType namekey) const { - NameKeyType namekey = TheNameKeyGenerator->nameToKey(name); - DamageFXMap::const_iterator it = m_dfxmap.find(namekey); - if (it == m_dfxmap.end()) + DamageFXMap::const_iterator it = m_dfxmap.find(namekey); + if (it == m_dfxmap.end()) { return NULL; } @@ -288,6 +287,18 @@ const DamageFX *DamageFXStore::findDamageFX(AsciiString name) const } } +//------------------------------------------------------------------------------------------------- +const DamageFX *DamageFXStore::findDamageFX(const AsciiString& name) const +{ + return findDamageFX(TheNameKeyGenerator->nameToKey(name)); +} + +//------------------------------------------------------------------------------------------------- +const DamageFX *DamageFXStore::findDamageFX(const char* name) const +{ + return findDamageFX(TheNameKeyGenerator->nameToKey(name)); +} + //------------------------------------------------------------------------------------------------- void DamageFXStore::init() { diff --git a/Generals/Code/GameEngine/Source/Common/INI/INI.cpp b/Generals/Code/GameEngine/Source/Common/INI/INI.cpp index 628a9453ac..8e39f00c65 100644 --- a/Generals/Code/GameEngine/Source/Common/INI/INI.cpp +++ b/Generals/Code/GameEngine/Source/Common/INI/INI.cpp @@ -872,7 +872,7 @@ void INI::parseMappedImage( INI *ini, void * /*instance*/, void *store, const vo if( TheMappedImageCollection ) { typedef const Image* ConstImagePtr; - *(ConstImagePtr*)store = TheMappedImageCollection->findImageByName( AsciiString( token ) ); + *(ConstImagePtr*)store = TheMappedImageCollection->findImageByName( token ); } //KM: If we are in the worldbuilder, we want to parse commandbuttons for informational purposes, @@ -1377,7 +1377,7 @@ void INI::parseUpgradeTemplate( INI* ini, void * /*instance*/, void *store, cons throw ERROR_BUG; } - const UpgradeTemplate *uu = TheUpgradeCenter->findUpgrade( AsciiString( token ) ); + const UpgradeTemplate *uu = TheUpgradeCenter->findUpgrade( token ); DEBUG_ASSERTCRASH( uu || stricmp( token, "None" ) == 0, ("Upgrade %s not found!",token) ); typedef const UpgradeTemplate* ConstUpgradeTemplatePtr; diff --git a/Generals/Code/GameEngine/Source/Common/INI/INIMappedImage.cpp b/Generals/Code/GameEngine/Source/Common/INI/INIMappedImage.cpp index 5614b2c879..8d044752ae 100644 --- a/Generals/Code/GameEngine/Source/Common/INI/INIMappedImage.cpp +++ b/Generals/Code/GameEngine/Source/Common/INI/INIMappedImage.cpp @@ -42,11 +42,8 @@ //------------------------------------------------------------------------------------------------- void INI::parseMappedImageDefinition( INI* ini ) { - AsciiString name; - // read the name - const char* c = ini->getNextToken(); - name.set( c ); + const char* name = ini->getNextToken(); // // find existing item if present, note that we do not support overrides @@ -66,11 +63,10 @@ void INI::parseMappedImageDefinition( INI* ini ) { // image not found, create a new one - image = newInstance(Image); + image = newInstance(Image); image->setName( name ); TheMappedImageCollection->addImage(image); - DEBUG_ASSERTCRASH( image, ("parseMappedImage: unable to allocate image for '%s'", - name.str()) ); + DEBUG_ASSERTCRASH( image, ("parseMappedImage: unable to allocate image for '%s'", name) ); } diff --git a/Generals/Code/GameEngine/Source/Common/NameKeyGenerator.cpp b/Generals/Code/GameEngine/Source/Common/NameKeyGenerator.cpp index 8cbb276063..f1efaf1b04 100644 --- a/Generals/Code/GameEngine/Source/Common/NameKeyGenerator.cpp +++ b/Generals/Code/GameEngine/Source/Common/NameKeyGenerator.cpp @@ -139,6 +139,30 @@ Bool NameKeyGenerator::addReservedKey() } #endif +//------------------------------------------------------------------------------------------------- +NameKeyType NameKeyGenerator::nameToKey(const AsciiString& name) +{ + const NameKeyType key = nameToKeyImpl(name); + +#if RTS_ZEROHOUR && RETAIL_COMPATIBLE_CRC + while (addReservedKey()); +#endif + + return key; +} + +//------------------------------------------------------------------------------------------------- +NameKeyType NameKeyGenerator::nameToLowercaseKey(const AsciiString& name) +{ + const NameKeyType key = nameToLowercaseKeyImpl(name); + +#if RTS_ZEROHOUR && RETAIL_COMPATIBLE_CRC + while (addReservedKey()); +#endif + + return key; +} + //------------------------------------------------------------------------------------------------- NameKeyType NameKeyGenerator::nameToKey(const char* name) { @@ -163,6 +187,40 @@ NameKeyType NameKeyGenerator::nameToLowercaseKey(const char *name) return key; } +//------------------------------------------------------------------------------------------------- +NameKeyType NameKeyGenerator::nameToKeyImpl(const AsciiString& name) +{ + const UnsignedInt hash = calcHashForString(name.str()) % SOCKET_COUNT; + + // do we have it already? + const Bucket *b; + for (b = m_sockets[hash]; b; b = b->m_nextInSocket) + { + if (name.compare(b->m_nameString) == 0) + return b->m_key; + } + + // nope, guess not. let's allocate it. + return createNameKey(hash, name); +} + +//------------------------------------------------------------------------------------------------- +NameKeyType NameKeyGenerator::nameToLowercaseKeyImpl(const AsciiString& name) +{ + const UnsignedInt hash = calcHashForLowercaseString(name.str()) % SOCKET_COUNT; + + // do we have it already? + const Bucket *b; + for (b = m_sockets[hash]; b; b = b->m_nextInSocket) + { + if (name.compareNoCase(b->m_nameString) == 0) + return b->m_key; + } + + // nope, guess not. let's allocate it. + return createNameKey(hash, name); +} + //------------------------------------------------------------------------------------------------- NameKeyType NameKeyGenerator::nameToKeyImpl(const char* name) { diff --git a/Generals/Code/GameEngine/Source/Common/System/FunctionLexicon.cpp b/Generals/Code/GameEngine/Source/Common/System/FunctionLexicon.cpp index 435e71aeb2..093f5e068a 100644 --- a/Generals/Code/GameEngine/Source/Common/System/FunctionLexicon.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/FunctionLexicon.cpp @@ -389,7 +389,7 @@ void FunctionLexicon::loadTable( TableEntry *table, { // assign key from name key based on name provided in table - entry->key = TheNameKeyGenerator->nameToKey( AsciiString(entry->name) ); + entry->key = TheNameKeyGenerator->nameToKey( entry->name ); // next table entry please entry++; diff --git a/Generals/Code/GameEngine/Source/Common/System/Upgrade.cpp b/Generals/Code/GameEngine/Source/Common/System/Upgrade.cpp index 24f1831806..77f89bedf7 100644 --- a/Generals/Code/GameEngine/Source/Common/System/Upgrade.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/Upgrade.cpp @@ -351,6 +351,14 @@ const UpgradeTemplate *UpgradeCenter::findUpgrade( const AsciiString& name ) con return findUpgradeByKey( TheNameKeyGenerator->nameToKey( name ) ); } +//------------------------------------------------------------------------------------------------- +/** Find upgrade by name */ +//------------------------------------------------------------------------------------------------- +const UpgradeTemplate *UpgradeCenter::findUpgrade( const char* name ) const +{ + return findUpgradeByKey( TheNameKeyGenerator->nameToKey( name ) ); +} + //------------------------------------------------------------------------------------------------- /** Allocate a new upgrade template */ //------------------------------------------------------------------------------------------------- @@ -470,8 +478,7 @@ std::vector UpgradeCenter::getUpgradeNames( void ) const void UpgradeCenter::parseUpgradeDefinition( INI *ini ) { // read the name - const char* c = ini->getNextToken(); - AsciiString name = c; + const char* name = ini->getNextToken(); // find existing item if present UpgradeTemplate* upgrade = TheUpgradeCenter->findNonConstUpgradeByKey( NAMEKEY(name) ); @@ -484,7 +491,7 @@ void UpgradeCenter::parseUpgradeDefinition( INI *ini ) } // sanity - DEBUG_ASSERTCRASH( upgrade, ("parseUpgradeDefinition: Unable to allocate upgrade '%s'", name.str()) ); + DEBUG_ASSERTCRASH( upgrade, ("parseUpgradeDefinition: Unable to allocate upgrade '%s'", name) ); // parse the ini definition ini->initFromINI( upgrade, upgrade->getFieldParse() ); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DifficultySelect.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DifficultySelect.cpp index 46446f8dbd..73cef4cd84 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DifficultySelect.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DifficultySelect.cpp @@ -125,8 +125,7 @@ static void SetDifficultyRadioButton( void ) void DifficultySelectInit( WindowLayout *layout, void *userData ) { - AsciiString parentName( "DifficultySelect.wnd:DifficultySelectParent" ); - NameKeyType parentID = TheNameKeyGenerator->nameToKey( parentName ); + NameKeyType parentID = TheNameKeyGenerator->nameToKey( "DifficultySelect.wnd:DifficultySelectParent" ); GameWindow *parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); buttonOkID = TheNameKeyGenerator->nameToKey( "DifficultySelect.wnd:ButtonOk" ); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DownloadMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DownloadMenu.cpp index ac97cee705..0c6d03a267 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DownloadMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DownloadMenu.cpp @@ -349,8 +349,7 @@ WindowMsgHandledType DownloadMenuInput( GameWindow *window, UnsignedInt msg, // if( BitIsSet( state, KEY_STATE_UP ) ) { - AsciiString buttonName( "DownloadMenu.wnd:ButtonCancel" ); - NameKeyType buttonID = TheNameKeyGenerator->nameToKey( buttonName ); + NameKeyType buttonID = TheNameKeyGenerator->nameToKey( "DownloadMenu.wnd:ButtonCancel" ); GameWindow *button = TheWindowManager->winGetWindowFromId( window, buttonID ); TheWindowManager->winSendSystemMsg( window, GBM_SELECTED, diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/KeyboardOptionsMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/KeyboardOptionsMenu.cpp index 1bc075b6f2..b88f31dd09 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/KeyboardOptionsMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/KeyboardOptionsMenu.cpp @@ -499,8 +499,7 @@ WindowMsgHandledType KeyboardOptionsMenuInput( GameWindow *window, UnsignedInt m // if( BitIsSet( state, KEY_STATE_UP ) ) { - AsciiString buttonName( "KeyboardOptionsMenu.wnd:ButtonBack" ); - NameKeyType buttonID = TheNameKeyGenerator->nameToKey( buttonName ); + NameKeyType buttonID = TheNameKeyGenerator->nameToKey( "KeyboardOptionsMenu.wnd:ButtonBack" ); GameWindow *button = TheWindowManager->winGetWindowFromId( window, buttonID ); TheWindowManager->winSendSystemMsg( window, GBM_SELECTED, 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 ff48c172f7..58827aca51 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanMapSelectMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanMapSelectMenu.cpp @@ -122,8 +122,7 @@ void LanMapSelectMenuInit( WindowLayout *layout, void *userData ) showLANGameOptionsUnderlyingGUIElements(FALSE); // set keyboard focus to main parent - AsciiString parentName( "LanMapSelectMenu.wnd:LanMapSelectMenuParent" ); - NameKeyType parentID = TheNameKeyGenerator->nameToKey( parentName ); + NameKeyType parentID = TheNameKeyGenerator->nameToKey( "LanMapSelectMenu.wnd:LanMapSelectMenuParent" ); parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); TheWindowManager->winSetFocus( parent ); @@ -165,8 +164,7 @@ void LanMapSelectMenuInit( WindowLayout *layout, void *userData ) } // get the listbox window - AsciiString listString( "LanMapSelectMenu.wnd:ListboxMap" ); - NameKeyType mapListID = TheNameKeyGenerator->nameToKey( listString ); + NameKeyType mapListID = TheNameKeyGenerator->nameToKey( "LanMapSelectMenu.wnd:ListboxMap" ); mapList = TheWindowManager->winGetWindowFromId( parent, mapListID ); if( mapList ) { @@ -228,8 +226,7 @@ WindowMsgHandledType LanMapSelectMenuInput( GameWindow *window, UnsignedInt msg, // if( BitIsSet( state, KEY_STATE_UP ) ) { - AsciiString buttonName( "LanMapSelectMenu.wnd:ButtonBack" ); - NameKeyType buttonID = TheNameKeyGenerator->nameToKey( buttonName ); + NameKeyType buttonID = TheNameKeyGenerator->nameToKey( "LanMapSelectMenu.wnd:ButtonBack" ); GameWindow *button = TheWindowManager->winGetWindowFromId( window, buttonID ); TheWindowManager->winSendSystemMsg( window, GBM_SELECTED, diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MapSelectMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MapSelectMenu.cpp index 563f242a47..3c6f985275 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MapSelectMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MapSelectMenu.cpp @@ -108,8 +108,7 @@ static void shutdownComplete( WindowLayout *layout ) void SetDifficultyRadioButton( void ) { - AsciiString parentName( "MapSelectMenu.wnd:MapSelectMenuParent" ); - NameKeyType parentID = TheNameKeyGenerator->nameToKey( parentName ); + NameKeyType parentID = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:MapSelectMenuParent" ); GameWindow *parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); if (!TheScriptEngine) @@ -171,8 +170,7 @@ void MapSelectMenuInit( WindowLayout *layout, void *userData ) Bool usesSystemMapDir = pref.usesSystemMapDir(); // get the listbox window - AsciiString listString( "MapSelectMenu.wnd:ListboxMap" ); - NameKeyType mapListID = TheNameKeyGenerator->nameToKey( listString ); + NameKeyType mapListID = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:ListboxMap" ); mapList = TheWindowManager->winGetWindowFromId( NULL, mapListID ); if( mapList ) { @@ -183,8 +181,7 @@ void MapSelectMenuInit( WindowLayout *layout, void *userData ) // set keyboard focus to main parent - AsciiString parentName( "MapSelectMenu.wnd:MapSelectMenuParent" ); - NameKeyType parentID = TheNameKeyGenerator->nameToKey( parentName ); + NameKeyType parentID = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:MapSelectMenuParent" ); GameWindow *parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); TheWindowManager->winSetFocus( parent ); @@ -280,8 +277,7 @@ WindowMsgHandledType MapSelectMenuInput( GameWindow *window, UnsignedInt msg, // if( BitIsSet( state, KEY_STATE_UP ) ) { - AsciiString buttonName( "MapSelectMenu.wnd:ButtonBack" ); - NameKeyType buttonID = TheNameKeyGenerator->nameToKey( buttonName ); + NameKeyType buttonID = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:ButtonBack" ); GameWindow *button = TheWindowManager->winGetWindowFromId( window, buttonID ); TheWindowManager->winSendSystemMsg( window, GBM_SELECTED, 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 1b1d9c9172..dc01e513b3 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp @@ -2046,8 +2046,7 @@ void OptionsMenuInit( WindowLayout *layout, void *userData ) layout->hide( FALSE ); // set keyboard focus to main parent - AsciiString parentName( "OptionsMenu.wnd:OptionsMenuParent" ); - NameKeyType parentID = TheNameKeyGenerator->nameToKey( parentName ); + NameKeyType parentID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:OptionsMenuParent" ); GameWindow *parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); TheWindowManager->winSetFocus( parent ); @@ -2148,8 +2147,7 @@ WindowMsgHandledType OptionsMenuInput( GameWindow *window, UnsignedInt msg, // if( BitIsSet( state, KEY_STATE_UP ) ) { - AsciiString buttonName( "OptionsMenu.wnd:ButtonBack" ); - NameKeyType buttonID = TheNameKeyGenerator->nameToKey( buttonName ); + NameKeyType buttonID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ButtonBack" ); GameWindow *button = TheWindowManager->winGetWindowFromId( window, buttonID ); TheWindowManager->winSendSystemMsg( window, GBM_SELECTED, diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SinglePlayerMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SinglePlayerMenu.cpp index 43b4bc6f62..5078994891 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SinglePlayerMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SinglePlayerMenu.cpp @@ -69,8 +69,7 @@ void SinglePlayerMenuInit( WindowLayout *layout, void *userData ) layout->hide( FALSE ); // set keyboard focus to main parent - AsciiString parentName( "SinglePlayerMenu.wnd:SinglePlayerMenuParent" ); - NameKeyType parentID = TheNameKeyGenerator->nameToKey( parentName ); + NameKeyType parentID = TheNameKeyGenerator->nameToKey( "SinglePlayerMenu.wnd:SinglePlayerMenuParent" ); GameWindow *parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); TheWindowManager->winSetFocus( parent ); @@ -155,8 +154,7 @@ WindowMsgHandledType SinglePlayerMenuInput( GameWindow *window, UnsignedInt msg, // if( BitIsSet( state, KEY_STATE_UP ) ) { - AsciiString buttonName( "SinglePlayerMenu.wnd:ButtonBack" ); - NameKeyType buttonID = TheNameKeyGenerator->nameToKey( buttonName ); + NameKeyType buttonID = TheNameKeyGenerator->nameToKey( "SinglePlayerMenu.wnd:ButtonBack" ); GameWindow *button = TheWindowManager->winGetWindowFromId( window, buttonID ); TheWindowManager->winSendSystemMsg( window, GBM_SELECTED, diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp index 1bf54db904..805f8415cf 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp @@ -127,8 +127,7 @@ void skirmishPositionStartSpots( void ); void skirmishUpdateSlotList( void ); void showSkirmishGameOptionsUnderlyingGUIElements( Bool show ) { - AsciiString parentName( "SkirmishGameOptionsMenu.wnd:SkirmishGameOptionsMenuParent" ); - NameKeyType parentID = TheNameKeyGenerator->nameToKey( parentName ); + NameKeyType parentID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:SkirmishGameOptionsMenuParent" ); GameWindow *parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); if (!parent) return; @@ -249,8 +248,7 @@ void SkirmishMapSelectMenuInit( WindowLayout *layout, void *userData ) { // set keyboard focus to main parent - AsciiString parentName( "SkirmishMapSelectMenu.wnd:SkrimishMapSelectMenuParent" ); - NameKeyType parentID = TheNameKeyGenerator->nameToKey( parentName ); + NameKeyType parentID = TheNameKeyGenerator->nameToKey( "SkirmishMapSelectMenu.wnd:SkrimishMapSelectMenuParent" ); parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); TheWindowManager->winSetFocus( parent ); @@ -295,8 +293,7 @@ void SkirmishMapSelectMenuInit( WindowLayout *layout, void *userData ) showSkirmishGameOptionsUnderlyingGUIElements(FALSE); // get the listbox window - AsciiString listString( "SkirmishMapSelectMenu.wnd:ListboxMap" ); - NameKeyType mapListID = TheNameKeyGenerator->nameToKey( listString ); + NameKeyType mapListID = TheNameKeyGenerator->nameToKey( "SkirmishMapSelectMenu.wnd:ListboxMap" ); mapList = TheWindowManager->winGetWindowFromId( parent, mapListID ); if( mapList ) { @@ -369,8 +366,7 @@ WindowMsgHandledType SkirmishMapSelectMenuInput( GameWindow *window, UnsignedInt // if( BitIsSet( state, KEY_STATE_UP ) ) { - AsciiString buttonName( "SkirmishMapSelectMenu.wnd:ButtonBack" ); - NameKeyType buttonID = TheNameKeyGenerator->nameToKey( buttonName ); + NameKeyType buttonID = TheNameKeyGenerator->nameToKey( "SkirmishMapSelectMenu.wnd:ButtonBack" ); GameWindow *button = TheWindowManager->winGetWindowFromId( window, buttonID ); TheWindowManager->winSendSystemMsg( window, GBM_SELECTED, 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 98d1d12fa5..227c11d2ac 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMapSelectMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMapSelectMenu.cpp @@ -127,8 +127,7 @@ void WOLMapSelectMenuInit( WindowLayout *layout, void *userData ) { // set keyboard focus to main parent - AsciiString parentName( "WOLMapSelectMenu.wnd:WOLMapSelectMenuParent" ); - NameKeyType parentID = TheNameKeyGenerator->nameToKey( parentName ); + NameKeyType parentID = TheNameKeyGenerator->nameToKey( "WOLMapSelectMenu.wnd:WOLMapSelectMenuParent" ); parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); TheWindowManager->winSetFocus( parent ); @@ -173,8 +172,7 @@ void WOLMapSelectMenuInit( WindowLayout *layout, void *userData ) showGameSpyGameOptionsUnderlyingGUIElements( FALSE ); // get the listbox window - AsciiString listString( "WOLMapSelectMenu.wnd:ListboxMap" ); - NameKeyType mapListID = TheNameKeyGenerator->nameToKey( listString ); + NameKeyType mapListID = TheNameKeyGenerator->nameToKey( "WOLMapSelectMenu.wnd:ListboxMap" ); mapList = TheWindowManager->winGetWindowFromId( parent, mapListID ); if( mapList ) { @@ -245,8 +243,7 @@ WindowMsgHandledType WOLMapSelectMenuInput( GameWindow *window, UnsignedInt msg, // if( BitIsSet( state, KEY_STATE_UP ) ) { - AsciiString buttonName( "WOLMapSelectMenu.wnd:ButtonBack" ); - NameKeyType buttonID = TheNameKeyGenerator->nameToKey( buttonName ); + NameKeyType buttonID = TheNameKeyGenerator->nameToKey( "WOLMapSelectMenu.wnd:ButtonBack" ); GameWindow *button = TheWindowManager->winGetWindowFromId( window, buttonID ); TheWindowManager->winSendSystemMsg( window, GBM_SELECTED, diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowGlobal.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowGlobal.cpp index 3820204083..c6a8a72b64 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowGlobal.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowGlobal.cpp @@ -131,7 +131,7 @@ const Image *GameWindowManager::winFindImage( const char *name ) assert( TheMappedImageCollection ); if( TheMappedImageCollection ) - return TheMappedImageCollection->findImageByName( AsciiString( name ) ); + return TheMappedImageCollection->findImageByName( name ); return NULL; diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp index f994ee3bd5..d7c25e469d 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp @@ -1315,7 +1315,7 @@ static Bool parseDrawData( const char *token, WinInstanceData *instData, c = strtok( NULL, seps ); // value if( strcmp( c, "NoImage" ) ) - drawData->image = TheMappedImageCollection->findImageByName( AsciiString( c ) ); + drawData->image = TheMappedImageCollection->findImageByName( c ); else drawData->image = NULL; // COLOR: R G B A @@ -1644,7 +1644,7 @@ static GameWindow *createGadget( char *type, *c = 0; // terminate after filename (format is filename:gadgetname) assert( TheNameKeyGenerator ); if( TheNameKeyGenerator ) - rData->screen = (Int)(TheNameKeyGenerator->nameToKey( AsciiString(filename) )); + rData->screen = (Int)(TheNameKeyGenerator->nameToKey( filename )); instData->m_style |= GWS_RADIO_BUTTON; window = TheWindowManager->gogoGadgetRadioButton( parent, status, x, y, diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp index 5515b6cc21..b58dbc7290 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp @@ -1258,13 +1258,11 @@ void MapTransferLoadScreen::init( GameInfo *game ) Int i; // Load the Filename Text - winName.format( "MapTransferScreen.wnd:StaticTextCurrentFile"); - m_fileNameText = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( winName )); + m_fileNameText = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "MapTransferScreen.wnd:StaticTextCurrentFile" )); DEBUG_ASSERTCRASH(m_fileNameText, ("Can't initialize the filename for the map transfer loadscreen")); // Load the Timeout Text - winName.format( "MapTransferScreen.wnd:StaticTextTimeout"); - m_timeoutText = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( winName )); + m_timeoutText = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "MapTransferScreen.wnd:StaticTextTimeout" )); DEBUG_ASSERTCRASH(m_timeoutText, ("Can't initialize the timeout for the map transfer loadscreen")); Int netSlot = 0; diff --git a/Generals/Code/GameEngine/Source/GameClient/System/Image.cpp b/Generals/Code/GameEngine/Source/GameClient/System/Image.cpp index 80299d0f40..e2fffa78cb 100644 --- a/Generals/Code/GameEngine/Source/GameClient/System/Image.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/System/Image.cpp @@ -204,7 +204,7 @@ ImageCollection::ImageCollection( void ) //------------------------------------------------------------------------------------------------- ImageCollection::~ImageCollection( void ) { - for (std::map::iterator i=m_imageMap.begin();i!=m_imageMap.end();++i) + for (ImageMap::iterator i=m_imageMap.begin();i!=m_imageMap.end();++i) deleteInstance(i->second); } @@ -216,13 +216,27 @@ void ImageCollection::addImage( Image *image ) m_imageMap[TheNameKeyGenerator->nameToLowercaseKey(image->getName())]=image; } +//------------------------------------------------------------------------------------------------- +const Image *ImageCollection::findImage( NameKeyType namekey ) const +{ + ImageMap::const_iterator i = m_imageMap.find(namekey); + return i == m_imageMap.end() ? NULL : i->second; +} + //------------------------------------------------------------------------------------------------- /** Find an image given the image name */ //------------------------------------------------------------------------------------------------- const Image *ImageCollection::findImageByName( const AsciiString& name ) const { - std::map::const_iterator i=m_imageMap.find(TheNameKeyGenerator->nameToLowercaseKey(name)); - return i==m_imageMap.end()?NULL:i->second; + return findImage(TheNameKeyGenerator->nameToLowercaseKey(name)); +} + +//------------------------------------------------------------------------------------------------- +/** Find an image given the image name */ +//------------------------------------------------------------------------------------------------- +const Image *ImageCollection::findImageByName( const char* name ) const +{ + return findImage(TheNameKeyGenerator->nameToLowercaseKey(name)); } //------------------------------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Armor.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Armor.cpp index 2965f21ea5..2fbddabc9f 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Armor.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Armor.cpp @@ -115,11 +115,10 @@ ArmorStore::~ArmorStore() } //------------------------------------------------------------------------------------------------- -const ArmorTemplate* ArmorStore::findArmorTemplate(AsciiString name) const +const ArmorTemplate* ArmorStore::findArmorTemplate(NameKeyType namekey) const { - NameKeyType namekey = TheNameKeyGenerator->nameToKey(name); - ArmorTemplateMap::const_iterator it = m_armorTemplates.find(namekey); - if (it == m_armorTemplates.end()) + ArmorTemplateMap::const_iterator it = m_armorTemplates.find(namekey); + if (it == m_armorTemplates.end()) { return NULL; } @@ -129,6 +128,18 @@ const ArmorTemplate* ArmorStore::findArmorTemplate(AsciiString name) const } } +//------------------------------------------------------------------------------------------------- +const ArmorTemplate* ArmorStore::findArmorTemplate(const AsciiString& name) const +{ + return findArmorTemplate(TheNameKeyGenerator->nameToKey(name)); +} + +//------------------------------------------------------------------------------------------------- +const ArmorTemplate* ArmorStore::findArmorTemplate(const char* name) const +{ + return findArmorTemplate(TheNameKeyGenerator->nameToKey(name)); +} + //------------------------------------------------------------------------------------------------- /*static */ void ArmorStore::parseArmorDefinition(INI *ini) { diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp index 005d5ace98..45aadbb0e9 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp @@ -1477,12 +1477,22 @@ void WeaponStore::createAndFireTempWeapon(const WeaponTemplate* wt, const Object } //------------------------------------------------------------------------------------------------- -const WeaponTemplate *WeaponStore::findWeaponTemplate( AsciiString name ) const +const WeaponTemplate *WeaponStore::findWeaponTemplate( const AsciiString& name ) const { - if (stricmp(name.str(), "None") == 0) + if (name.compareNoCase("None") == 0) return NULL; const WeaponTemplate * wt = findWeaponTemplatePrivate( TheNameKeyGenerator->nameToKey( name ) ); - DEBUG_ASSERTCRASH(wt != NULL, ("Weapon %s not found!",name.str())); + DEBUG_ASSERTCRASH(wt != NULL, ("Weapon %s not found!",name)); + return wt; +} + +//------------------------------------------------------------------------------------------------- +const WeaponTemplate *WeaponStore::findWeaponTemplate( const char* name ) const +{ + if (stricmp(name, "None") == 0) + return NULL; + const WeaponTemplate * wt = findWeaponTemplatePrivate( TheNameKeyGenerator->nameToKey( name ) ); + DEBUG_ASSERTCRASH(wt != NULL, ("Weapon %s not found!",name)); return wt; } 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 c94752fe16..9bab297741 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp @@ -1466,8 +1466,10 @@ void W3DModelDrawModuleData::parseConditionState(INI* ini, void *instance, void case PARSE_TRANSITION: { - AsciiString firstNm = ini->getNextToken(); firstNm.toLower(); - AsciiString secondNm = ini->getNextToken(); secondNm.toLower(); + AsciiString firstNm = ini->getNextToken(); + AsciiString secondNm = ini->getNextToken(); + firstNm.toLower(); + secondNm.toLower(); NameKeyType firstKey = NAMEKEY(firstNm); NameKeyType secondKey = NAMEKEY(secondNm); diff --git a/Generals/Code/Tools/GUIEdit/Source/Dialog Procedures/RadioButtonProperties.cpp b/Generals/Code/Tools/GUIEdit/Source/Dialog Procedures/RadioButtonProperties.cpp index c9514c44b2..762e869b3e 100644 --- a/Generals/Code/Tools/GUIEdit/Source/Dialog Procedures/RadioButtonProperties.cpp +++ b/Generals/Code/Tools/GUIEdit/Source/Dialog Procedures/RadioButtonProperties.cpp @@ -177,7 +177,7 @@ static LRESULT CALLBACK radioButtonPropertiesCallback( HWND hWndDialog, // save group Int group = GetDlgItemInt( hWndDialog, COMBO_GROUP, NULL, FALSE ); - Int screen = TheNameKeyGenerator->nameToKey( AsciiString(TheEditor->getSaveFilename()) ); + Int screen = TheNameKeyGenerator->nameToKey( TheEditor->getSaveFilename() ); GadgetRadioSetGroup( window, group, screen ); } diff --git a/Generals/Code/Tools/GUIEdit/Source/LayoutScheme.cpp b/Generals/Code/Tools/GUIEdit/Source/LayoutScheme.cpp index f9f674f930..9ede862b0f 100644 --- a/Generals/Code/Tools/GUIEdit/Source/LayoutScheme.cpp +++ b/Generals/Code/Tools/GUIEdit/Source/LayoutScheme.cpp @@ -2433,7 +2433,7 @@ Bool LayoutScheme::loadScheme( char *filename ) // store the info storeImageAndColor( (StateIdentifier)state, - TheMappedImageCollection->findImageByName( AsciiString( imageBuffer ) ), + TheMappedImageCollection->findImageByName( imageBuffer ), GameMakeColor( colorR, colorG, colorB, colorA ), GameMakeColor( bColorR, bColorG, bColorB, bColorA ) ); } diff --git a/Generals/Code/Tools/GUIEdit/Source/Properties.cpp b/Generals/Code/Tools/GUIEdit/Source/Properties.cpp index 6cf9dcf002..3a85e20411 100644 --- a/Generals/Code/Tools/GUIEdit/Source/Properties.cpp +++ b/Generals/Code/Tools/GUIEdit/Source/Properties.cpp @@ -1258,7 +1258,7 @@ const Image *ComboBoxSelectionToImage( HWND comboBox ) SendMessage( comboBox, CB_GETLBTEXT, selected, (LPARAM)buffer ); // return the image loc that matches the string - return TheMappedImageCollection->findImageByName( AsciiString( buffer ) ); + return TheMappedImageCollection->findImageByName( buffer ); } diff --git a/Generals/Code/Tools/GUIEdit/Source/Save.cpp b/Generals/Code/Tools/GUIEdit/Source/Save.cpp index 41b68e1805..ad880c3211 100644 --- a/Generals/Code/Tools/GUIEdit/Source/Save.cpp +++ b/Generals/Code/Tools/GUIEdit/Source/Save.cpp @@ -1235,7 +1235,7 @@ Bool GUIEdit::saveData( char *filePathAndFilename, char *filename ) // update all radio button screen identifiers with the filename updateRadioScreenIdentifiers( TheWindowManager->winGetWindowList(), - TheNameKeyGenerator->nameToKey( AsciiString(m_saveFilename) ) ); + TheNameKeyGenerator->nameToKey( m_saveFilename ) ); // open the file fp = fopen( filePathAndFilename, "w" ); diff --git a/Generals/Code/Tools/WorldBuilder/src/addplayerdialog.cpp b/Generals/Code/Tools/WorldBuilder/src/addplayerdialog.cpp index dd02f67f9a..0c0abb1afa 100644 --- a/Generals/Code/Tools/WorldBuilder/src/addplayerdialog.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/addplayerdialog.cpp @@ -76,9 +76,8 @@ void AddPlayerDialog::OnOK() } else { faction->GetWindowText(theText); } - AsciiString name((LPCTSTR)theText); - const PlayerTemplate* pt = ThePlayerTemplateStore->findPlayerTemplate(NAMEKEY(name)); + const PlayerTemplate* pt = ThePlayerTemplateStore->findPlayerTemplate(NAMEKEY((LPCTSTR)theText)); if (pt) { m_addedSide = pt ? pt->getName() : AsciiString::TheEmptyString; diff --git a/GeneralsMD/Code/GameEngine/Include/Common/DamageFX.h b/GeneralsMD/Code/GameEngine/Include/Common/DamageFX.h index bca57a3ce7..af9bfadd78 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/DamageFX.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/DamageFX.h @@ -147,7 +147,9 @@ class DamageFXStore : public SubsystemInterface /** Find the DamageFX with the given name. If no such DamageFX exists, return null. */ - const DamageFX *findDamageFX( AsciiString name ) const; + const DamageFX *findDamageFX( NameKeyType namekey ) const; + const DamageFX *findDamageFX( const AsciiString& name ) const; + const DamageFX *findDamageFX( const char* name ) const; static void parseDamageFXDefinition(INI* ini); diff --git a/GeneralsMD/Code/GameEngine/Include/Common/NameKeyGenerator.h b/GeneralsMD/Code/GameEngine/Include/Common/NameKeyGenerator.h index afa205409a..ffa939baf7 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/NameKeyGenerator.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/NameKeyGenerator.h @@ -90,8 +90,8 @@ class NameKeyGenerator : public SubsystemInterface virtual void update() { } /// 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()); } + NameKeyType nameToKey(const AsciiString& name); + NameKeyType nameToLowercaseKey(const AsciiString& name); /// Given a string, convert into a unique integer key. NameKeyType nameToKey(const char* name); @@ -118,6 +118,8 @@ class NameKeyGenerator : public SubsystemInterface Bool addReservedKey(); #endif + NameKeyType nameToKeyImpl(const AsciiString& name); + NameKeyType nameToLowercaseKeyImpl(const AsciiString& name); NameKeyType nameToKeyImpl(const char* name); NameKeyType nameToLowercaseKeyImpl(const char *name); NameKeyType createNameKey(UnsignedInt hash, const AsciiString& name); diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Upgrade.h b/GeneralsMD/Code/GameEngine/Include/Common/Upgrade.h index 33ce189637..accd45dc04 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/Upgrade.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/Upgrade.h @@ -238,6 +238,7 @@ class UpgradeCenter : public SubsystemInterface UpgradeTemplate *firstUpgradeTemplate( void ); ///< return the first upgrade template const UpgradeTemplate *findUpgradeByKey( NameKeyType key ) const; ///< find upgrade by name key const UpgradeTemplate *findUpgrade( const AsciiString& name ) const; ///< find and return upgrade by name + const UpgradeTemplate *findUpgrade( const char* name ) const; ///< find and return upgrade by name const UpgradeTemplate *findVeterancyUpgrade(VeterancyLevel level) const; ///< find and return upgrade by veterancy level UpgradeTemplate *newUpgrade( const AsciiString& name ); ///< allocate, link, and return new upgrade diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Image.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Image.h index 0714a96bb4..5c791363fd 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/Image.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Image.h @@ -116,6 +116,7 @@ friend class ImageCollection; //------------------------------------------------------------------------------------------------- class ImageCollection : public SubsystemInterface { + typedef std::map ImageMap; public: @@ -128,7 +129,9 @@ class ImageCollection : public SubsystemInterface void load( Int textureSize ); ///< load images + const Image *findImage( NameKeyType namekey ) const; ///< find image based on name key const Image *findImageByName( const AsciiString& name ) const; ///< find image based on name + const Image *findImageByName( const char* name ) const; ///< find image based on name /// adds the given image to the collection, transfers ownership to this object void addImage(Image *image); @@ -136,14 +139,14 @@ class ImageCollection : public SubsystemInterface /// enumerates the list of existing images Image *Enum(unsigned index) { - for (std::map::iterator i=m_imageMap.begin();i!=m_imageMap.end();++i) + for (ImageMap::iterator i=m_imageMap.begin();i!=m_imageMap.end();++i) if (!index--) return i->second; return NULL; } protected: - std::map m_imageMap; ///< maps named keys to images + ImageMap m_imageMap; ///< maps named keys to images }; // INLINING /////////////////////////////////////////////////////////////////////////////////////// diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Armor.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Armor.h index 8e876d7813..b98b2ba8d9 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Armor.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Armor.h @@ -105,10 +105,12 @@ class ArmorStore : public SubsystemInterface void reset() { } void update() { } + const ArmorTemplate* findArmorTemplate(NameKeyType namekey) const; /** Find the Armor with the given name. If no such Armor exists, return null. */ - const ArmorTemplate* findArmorTemplate(AsciiString name) const; + const ArmorTemplate* findArmorTemplate(const AsciiString& name) const; + const ArmorTemplate* findArmorTemplate(const char* name) const; inline Armor makeArmor(const ArmorTemplate *tmpl) const { diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h index 91c03fbb08..6b39c95758 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h @@ -839,7 +839,8 @@ class WeaponStore : public SubsystemInterface /** Find the WeaponTemplate with the given name. If no such WeaponTemplate exists, return null. */ - const WeaponTemplate *findWeaponTemplate(AsciiString name) const; + const WeaponTemplate *findWeaponTemplate(const AsciiString& name) const; + const WeaponTemplate *findWeaponTemplate(const char* name) const; const WeaponTemplate *findWeaponTemplateByNameKey( NameKeyType key ) const { return findWeaponTemplatePrivate( key ); } // this dynamically allocates a new Weapon, which is owned (and must be freed!) by the caller. diff --git a/GeneralsMD/Code/GameEngine/Source/Common/DamageFX.cpp b/GeneralsMD/Code/GameEngine/Source/Common/DamageFX.cpp index 6ba5997c44..8975fa7d60 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/DamageFX.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/DamageFX.cpp @@ -272,11 +272,10 @@ DamageFXStore::~DamageFXStore() } //------------------------------------------------------------------------------------------------- -const DamageFX *DamageFXStore::findDamageFX(AsciiString name) const +const DamageFX *DamageFXStore::findDamageFX(NameKeyType namekey) const { - NameKeyType namekey = TheNameKeyGenerator->nameToKey(name); - DamageFXMap::const_iterator it = m_dfxmap.find(namekey); - if (it == m_dfxmap.end()) + DamageFXMap::const_iterator it = m_dfxmap.find(namekey); + if (it == m_dfxmap.end()) { return NULL; } @@ -286,6 +285,18 @@ const DamageFX *DamageFXStore::findDamageFX(AsciiString name) const } } +//------------------------------------------------------------------------------------------------- +const DamageFX *DamageFXStore::findDamageFX(const AsciiString& name) const +{ + return findDamageFX(TheNameKeyGenerator->nameToKey(name)); +} + +//------------------------------------------------------------------------------------------------- +const DamageFX *DamageFXStore::findDamageFX(const char* name) const +{ + return findDamageFX(TheNameKeyGenerator->nameToKey(name)); +} + //------------------------------------------------------------------------------------------------- void DamageFXStore::init() { diff --git a/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp b/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp index 890eeb4f65..edda2599bf 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp @@ -871,7 +871,7 @@ void INI::parseMappedImage( INI *ini, void * /*instance*/, void *store, const vo if( TheMappedImageCollection ) { typedef const Image* ConstImagePtr; - *(ConstImagePtr*)store = TheMappedImageCollection->findImageByName( AsciiString( token ) ); + *(ConstImagePtr*)store = TheMappedImageCollection->findImageByName( token ); } //KM: If we are in the worldbuilder, we want to parse commandbuttons for informational purposes, @@ -1376,7 +1376,7 @@ void INI::parseUpgradeTemplate( INI* ini, void * /*instance*/, void *store, cons throw ERROR_BUG; } - const UpgradeTemplate *uu = TheUpgradeCenter->findUpgrade( AsciiString( token ) ); + const UpgradeTemplate *uu = TheUpgradeCenter->findUpgrade( token ); DEBUG_ASSERTCRASH( uu || stricmp( token, "None" ) == 0, ("Upgrade %s not found!",token) ); typedef const UpgradeTemplate* ConstUpgradeTemplatePtr; diff --git a/GeneralsMD/Code/GameEngine/Source/Common/INI/INIMappedImage.cpp b/GeneralsMD/Code/GameEngine/Source/Common/INI/INIMappedImage.cpp index 159da910fa..f7a4c80154 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/INI/INIMappedImage.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/INI/INIMappedImage.cpp @@ -42,11 +42,8 @@ //------------------------------------------------------------------------------------------------- void INI::parseMappedImageDefinition( INI* ini ) { - AsciiString name; - // read the name - const char* c = ini->getNextToken(); - name.set( c ); + const char* name = ini->getNextToken(); // // find existing item if present, note that we do not support overrides @@ -66,11 +63,10 @@ void INI::parseMappedImageDefinition( INI* ini ) { // image not found, create a new one - image = newInstance(Image); + image = newInstance(Image); image->setName( name ); TheMappedImageCollection->addImage(image); - DEBUG_ASSERTCRASH( image, ("parseMappedImage: unable to allocate image for '%s'", - name.str()) ); + DEBUG_ASSERTCRASH( image, ("parseMappedImage: unable to allocate image for '%s'", name) ); } diff --git a/GeneralsMD/Code/GameEngine/Source/Common/NameKeyGenerator.cpp b/GeneralsMD/Code/GameEngine/Source/Common/NameKeyGenerator.cpp index 6990bfa547..44894061da 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/NameKeyGenerator.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/NameKeyGenerator.cpp @@ -139,6 +139,30 @@ Bool NameKeyGenerator::addReservedKey() } #endif +//------------------------------------------------------------------------------------------------- +NameKeyType NameKeyGenerator::nameToKey(const AsciiString& name) +{ + const NameKeyType key = nameToKeyImpl(name); + +#if RTS_ZEROHOUR && RETAIL_COMPATIBLE_CRC + while (addReservedKey()); +#endif + + return key; +} + +//------------------------------------------------------------------------------------------------- +NameKeyType NameKeyGenerator::nameToLowercaseKey(const AsciiString& name) +{ + const NameKeyType key = nameToLowercaseKeyImpl(name); + +#if RTS_ZEROHOUR && RETAIL_COMPATIBLE_CRC + while (addReservedKey()); +#endif + + return key; +} + //------------------------------------------------------------------------------------------------- NameKeyType NameKeyGenerator::nameToKey(const char* name) { @@ -163,6 +187,40 @@ NameKeyType NameKeyGenerator::nameToLowercaseKey(const char *name) return key; } +//------------------------------------------------------------------------------------------------- +NameKeyType NameKeyGenerator::nameToKeyImpl(const AsciiString& name) +{ + const UnsignedInt hash = calcHashForString(name.str()) % SOCKET_COUNT; + + // do we have it already? + const Bucket *b; + for (b = m_sockets[hash]; b; b = b->m_nextInSocket) + { + if (name.compare(b->m_nameString) == 0) + return b->m_key; + } + + // nope, guess not. let's allocate it. + return createNameKey(hash, name); +} + +//------------------------------------------------------------------------------------------------- +NameKeyType NameKeyGenerator::nameToLowercaseKeyImpl(const AsciiString& name) +{ + const UnsignedInt hash = calcHashForLowercaseString(name.str()) % SOCKET_COUNT; + + // do we have it already? + const Bucket *b; + for (b = m_sockets[hash]; b; b = b->m_nextInSocket) + { + if (name.compareNoCase(b->m_nameString) == 0) + return b->m_key; + } + + // nope, guess not. let's allocate it. + return createNameKey(hash, name); +} + //------------------------------------------------------------------------------------------------- NameKeyType NameKeyGenerator::nameToKeyImpl(const char* name) { diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/FunctionLexicon.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/FunctionLexicon.cpp index f922900cd1..3eccb5ef08 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/FunctionLexicon.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/FunctionLexicon.cpp @@ -395,7 +395,7 @@ void FunctionLexicon::loadTable( TableEntry *table, { // assign key from name key based on name provided in table - entry->key = TheNameKeyGenerator->nameToKey( AsciiString(entry->name) ); + entry->key = TheNameKeyGenerator->nameToKey( entry->name ); // next table entry please entry++; diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/Upgrade.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/Upgrade.cpp index 65ff23f91f..1047f7970a 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/Upgrade.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/Upgrade.cpp @@ -352,6 +352,14 @@ const UpgradeTemplate *UpgradeCenter::findUpgrade( const AsciiString& name ) con return findUpgradeByKey( TheNameKeyGenerator->nameToKey( name ) ); } +//------------------------------------------------------------------------------------------------- +/** Find upgrade by name */ +//------------------------------------------------------------------------------------------------- +const UpgradeTemplate *UpgradeCenter::findUpgrade( const char* name ) const +{ + return findUpgradeByKey( TheNameKeyGenerator->nameToKey( name ) ); +} + //------------------------------------------------------------------------------------------------- /** Allocate a new upgrade template */ //------------------------------------------------------------------------------------------------- @@ -471,8 +479,7 @@ std::vector UpgradeCenter::getUpgradeNames( void ) const void UpgradeCenter::parseUpgradeDefinition( INI *ini ) { // read the name - const char* c = ini->getNextToken(); - AsciiString name = c; + const char* name = ini->getNextToken(); // find existing item if present UpgradeTemplate* upgrade = TheUpgradeCenter->findNonConstUpgradeByKey( NAMEKEY(name) ); @@ -485,7 +492,7 @@ void UpgradeCenter::parseUpgradeDefinition( INI *ini ) } // sanity - DEBUG_ASSERTCRASH( upgrade, ("parseUpgradeDefinition: Unable to allocate upgrade '%s'", name.str()) ); + DEBUG_ASSERTCRASH( upgrade, ("parseUpgradeDefinition: Unable to allocate upgrade '%s'", name) ); // parse the ini definition ini->initFromINI( upgrade, upgrade->getFieldParse() ); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DifficultySelect.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DifficultySelect.cpp index ae20452c8e..4e8d80624a 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DifficultySelect.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DifficultySelect.cpp @@ -125,8 +125,7 @@ static void SetDifficultyRadioButton( void ) void DifficultySelectInit( WindowLayout *layout, void *userData ) { - AsciiString parentName( "DifficultySelect.wnd:DifficultySelectParent" ); - NameKeyType parentID = TheNameKeyGenerator->nameToKey( parentName ); + NameKeyType parentID = TheNameKeyGenerator->nameToKey( "DifficultySelect.wnd:DifficultySelectParent" ); GameWindow *parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); buttonOkID = TheNameKeyGenerator->nameToKey( "DifficultySelect.wnd:ButtonOk" ); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DownloadMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DownloadMenu.cpp index b1b12b87fe..61a4e89ee7 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DownloadMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/DownloadMenu.cpp @@ -349,8 +349,7 @@ WindowMsgHandledType DownloadMenuInput( GameWindow *window, UnsignedInt msg, // if( BitIsSet( state, KEY_STATE_UP ) ) { - AsciiString buttonName( "DownloadMenu.wnd:ButtonCancel" ); - NameKeyType buttonID = TheNameKeyGenerator->nameToKey( buttonName ); + NameKeyType buttonID = TheNameKeyGenerator->nameToKey( "DownloadMenu.wnd:ButtonCancel" ); GameWindow *button = TheWindowManager->winGetWindowFromId( window, buttonID ); TheWindowManager->winSendSystemMsg( window, GBM_SELECTED, diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/KeyboardOptionsMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/KeyboardOptionsMenu.cpp index 9468c4500f..0c466741cc 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/KeyboardOptionsMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/KeyboardOptionsMenu.cpp @@ -499,8 +499,7 @@ WindowMsgHandledType KeyboardOptionsMenuInput( GameWindow *window, UnsignedInt m // if( BitIsSet( state, KEY_STATE_UP ) ) { - AsciiString buttonName( "KeyboardOptionsMenu.wnd:ButtonBack" ); - NameKeyType buttonID = TheNameKeyGenerator->nameToKey( buttonName ); + NameKeyType buttonID = TheNameKeyGenerator->nameToKey( "KeyboardOptionsMenu.wnd:ButtonBack" ); GameWindow *button = TheWindowManager->winGetWindowFromId( window, buttonID ); TheWindowManager->winSendSystemMsg( window, GBM_SELECTED, 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 537352824c..5ff05f9ff1 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanMapSelectMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanMapSelectMenu.cpp @@ -122,8 +122,7 @@ void LanMapSelectMenuInit( WindowLayout *layout, void *userData ) showLANGameOptionsUnderlyingGUIElements(FALSE); // set keyboard focus to main parent - AsciiString parentName( "LanMapSelectMenu.wnd:LanMapSelectMenuParent" ); - NameKeyType parentID = TheNameKeyGenerator->nameToKey( parentName ); + NameKeyType parentID = TheNameKeyGenerator->nameToKey( "LanMapSelectMenu.wnd:LanMapSelectMenuParent" ); parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); TheWindowManager->winSetFocus( parent ); @@ -165,8 +164,7 @@ void LanMapSelectMenuInit( WindowLayout *layout, void *userData ) } // get the listbox window - AsciiString listString( "LanMapSelectMenu.wnd:ListboxMap" ); - NameKeyType mapListID = TheNameKeyGenerator->nameToKey( listString ); + NameKeyType mapListID = TheNameKeyGenerator->nameToKey( "LanMapSelectMenu.wnd:ListboxMap" ); mapList = TheWindowManager->winGetWindowFromId( parent, mapListID ); if( mapList ) { @@ -228,8 +226,7 @@ WindowMsgHandledType LanMapSelectMenuInput( GameWindow *window, UnsignedInt msg, // if( BitIsSet( state, KEY_STATE_UP ) ) { - AsciiString buttonName( "LanMapSelectMenu.wnd:ButtonBack" ); - NameKeyType buttonID = TheNameKeyGenerator->nameToKey( buttonName ); + NameKeyType buttonID = TheNameKeyGenerator->nameToKey( "LanMapSelectMenu.wnd:ButtonBack" ); GameWindow *button = TheWindowManager->winGetWindowFromId( window, buttonID ); TheWindowManager->winSendSystemMsg( window, GBM_SELECTED, diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MapSelectMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MapSelectMenu.cpp index ca0cf4fe1f..429d921a4f 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MapSelectMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MapSelectMenu.cpp @@ -108,8 +108,7 @@ static void shutdownComplete( WindowLayout *layout ) void SetDifficultyRadioButton( void ) { - AsciiString parentName( "MapSelectMenu.wnd:MapSelectMenuParent" ); - NameKeyType parentID = TheNameKeyGenerator->nameToKey( parentName ); + NameKeyType parentID = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:MapSelectMenuParent" ); GameWindow *parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); if (!TheScriptEngine) @@ -171,8 +170,7 @@ void MapSelectMenuInit( WindowLayout *layout, void *userData ) Bool usesSystemMapDir = pref.usesSystemMapDir(); // get the listbox window - AsciiString listString( "MapSelectMenu.wnd:ListboxMap" ); - NameKeyType mapListID = TheNameKeyGenerator->nameToKey( listString ); + NameKeyType mapListID = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:ListboxMap" ); mapList = TheWindowManager->winGetWindowFromId( NULL, mapListID ); if( mapList ) { @@ -183,8 +181,7 @@ void MapSelectMenuInit( WindowLayout *layout, void *userData ) // set keyboard focus to main parent - AsciiString parentName( "MapSelectMenu.wnd:MapSelectMenuParent" ); - NameKeyType parentID = TheNameKeyGenerator->nameToKey( parentName ); + NameKeyType parentID = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:MapSelectMenuParent" ); GameWindow *parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); TheWindowManager->winSetFocus( parent ); @@ -280,8 +277,7 @@ WindowMsgHandledType MapSelectMenuInput( GameWindow *window, UnsignedInt msg, // if( BitIsSet( state, KEY_STATE_UP ) ) { - AsciiString buttonName( "MapSelectMenu.wnd:ButtonBack" ); - NameKeyType buttonID = TheNameKeyGenerator->nameToKey( buttonName ); + NameKeyType buttonID = TheNameKeyGenerator->nameToKey( "MapSelectMenu.wnd:ButtonBack" ); GameWindow *button = TheWindowManager->winGetWindowFromId( window, buttonID ); TheWindowManager->winSendSystemMsg( window, GBM_SELECTED, 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 782cc525c8..16e2cc0311 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp @@ -2117,8 +2117,7 @@ void OptionsMenuInit( WindowLayout *layout, void *userData ) layout->hide( FALSE ); // set keyboard focus to main parent - AsciiString parentName( "OptionsMenu.wnd:OptionsMenuParent" ); - NameKeyType parentID = TheNameKeyGenerator->nameToKey( parentName ); + NameKeyType parentID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:OptionsMenuParent" ); GameWindow *parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); TheWindowManager->winSetFocus( parent ); @@ -2219,8 +2218,7 @@ WindowMsgHandledType OptionsMenuInput( GameWindow *window, UnsignedInt msg, // if( BitIsSet( state, KEY_STATE_UP ) ) { - AsciiString buttonName( "OptionsMenu.wnd:ButtonBack" ); - NameKeyType buttonID = TheNameKeyGenerator->nameToKey( buttonName ); + NameKeyType buttonID = TheNameKeyGenerator->nameToKey( "OptionsMenu.wnd:ButtonBack" ); GameWindow *button = TheWindowManager->winGetWindowFromId( window, buttonID ); TheWindowManager->winSendSystemMsg( window, GBM_SELECTED, diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SinglePlayerMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SinglePlayerMenu.cpp index e30311d80d..5f72983f75 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SinglePlayerMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SinglePlayerMenu.cpp @@ -69,8 +69,7 @@ void SinglePlayerMenuInit( WindowLayout *layout, void *userData ) layout->hide( FALSE ); // set keyboard focus to main parent - AsciiString parentName( "SinglePlayerMenu.wnd:SinglePlayerMenuParent" ); - NameKeyType parentID = TheNameKeyGenerator->nameToKey( parentName ); + NameKeyType parentID = TheNameKeyGenerator->nameToKey( "SinglePlayerMenu.wnd:SinglePlayerMenuParent" ); GameWindow *parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); TheWindowManager->winSetFocus( parent ); @@ -155,8 +154,7 @@ WindowMsgHandledType SinglePlayerMenuInput( GameWindow *window, UnsignedInt msg, // if( BitIsSet( state, KEY_STATE_UP ) ) { - AsciiString buttonName( "SinglePlayerMenu.wnd:ButtonBack" ); - NameKeyType buttonID = TheNameKeyGenerator->nameToKey( buttonName ); + NameKeyType buttonID = TheNameKeyGenerator->nameToKey( "SinglePlayerMenu.wnd:ButtonBack" ); GameWindow *button = TheWindowManager->winGetWindowFromId( window, buttonID ); TheWindowManager->winSendSystemMsg( window, GBM_SELECTED, diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp index 8d66cac120..42ad7642cb 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp @@ -130,8 +130,7 @@ void skirmishPositionStartSpots( void ); void skirmishUpdateSlotList( void ); void showSkirmishGameOptionsUnderlyingGUIElements( Bool show ) { - AsciiString parentName( "SkirmishGameOptionsMenu.wnd:SkirmishGameOptionsMenuParent" ); - NameKeyType parentID = TheNameKeyGenerator->nameToKey( parentName ); + NameKeyType parentID = TheNameKeyGenerator->nameToKey( "SkirmishGameOptionsMenu.wnd:SkirmishGameOptionsMenuParent" ); GameWindow *parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); if (!parent) return; @@ -252,8 +251,7 @@ void SkirmishMapSelectMenuInit( WindowLayout *layout, void *userData ) { // set keyboard focus to main parent - AsciiString parentName( "SkirmishMapSelectMenu.wnd:SkrimishMapSelectMenuParent" ); - NameKeyType parentID = TheNameKeyGenerator->nameToKey( parentName ); + NameKeyType parentID = TheNameKeyGenerator->nameToKey( "SkirmishMapSelectMenu.wnd:SkrimishMapSelectMenuParent" ); parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); TheWindowManager->winSetFocus( parent ); @@ -298,8 +296,7 @@ void SkirmishMapSelectMenuInit( WindowLayout *layout, void *userData ) showSkirmishGameOptionsUnderlyingGUIElements(FALSE); // get the listbox window - AsciiString listString( "SkirmishMapSelectMenu.wnd:ListboxMap" ); - NameKeyType mapListID = TheNameKeyGenerator->nameToKey( listString ); + NameKeyType mapListID = TheNameKeyGenerator->nameToKey( "SkirmishMapSelectMenu.wnd:ListboxMap" ); mapList = TheWindowManager->winGetWindowFromId( parent, mapListID ); if( mapList ) { @@ -372,8 +369,7 @@ WindowMsgHandledType SkirmishMapSelectMenuInput( GameWindow *window, UnsignedInt // if( BitIsSet( state, KEY_STATE_UP ) ) { - AsciiString buttonName( "SkirmishMapSelectMenu.wnd:ButtonBack" ); - NameKeyType buttonID = TheNameKeyGenerator->nameToKey( buttonName ); + NameKeyType buttonID = TheNameKeyGenerator->nameToKey( "SkirmishMapSelectMenu.wnd:ButtonBack" ); GameWindow *button = TheWindowManager->winGetWindowFromId( window, buttonID ); TheWindowManager->winSendSystemMsg( window, GBM_SELECTED, 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 fffd934564..ea60f55856 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMapSelectMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMapSelectMenu.cpp @@ -127,8 +127,7 @@ void WOLMapSelectMenuInit( WindowLayout *layout, void *userData ) { // set keyboard focus to main parent - AsciiString parentName( "WOLMapSelectMenu.wnd:WOLMapSelectMenuParent" ); - NameKeyType parentID = TheNameKeyGenerator->nameToKey( parentName ); + NameKeyType parentID = TheNameKeyGenerator->nameToKey( "WOLMapSelectMenu.wnd:WOLMapSelectMenuParent" ); parent = TheWindowManager->winGetWindowFromId( NULL, parentID ); TheWindowManager->winSetFocus( parent ); @@ -182,8 +181,7 @@ void WOLMapSelectMenuInit( WindowLayout *layout, void *userData ) showGameSpyGameOptionsUnderlyingGUIElements( FALSE ); // get the listbox window - AsciiString listString( "WOLMapSelectMenu.wnd:ListboxMap" ); - NameKeyType mapListID = TheNameKeyGenerator->nameToKey( listString ); + NameKeyType mapListID = TheNameKeyGenerator->nameToKey( "WOLMapSelectMenu.wnd:ListboxMap" ); mapList = TheWindowManager->winGetWindowFromId( parent, mapListID ); if( mapList ) { @@ -254,8 +252,7 @@ WindowMsgHandledType WOLMapSelectMenuInput( GameWindow *window, UnsignedInt msg, // if( BitIsSet( state, KEY_STATE_UP ) ) { - AsciiString buttonName( "WOLMapSelectMenu.wnd:ButtonBack" ); - NameKeyType buttonID = TheNameKeyGenerator->nameToKey( buttonName ); + NameKeyType buttonID = TheNameKeyGenerator->nameToKey( "WOLMapSelectMenu.wnd:ButtonBack" ); GameWindow *button = TheWindowManager->winGetWindowFromId( window, buttonID ); TheWindowManager->winSendSystemMsg( window, GBM_SELECTED, diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowGlobal.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowGlobal.cpp index 8125a7c4fb..d0fb42146a 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowGlobal.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowGlobal.cpp @@ -131,7 +131,7 @@ const Image *GameWindowManager::winFindImage( const char *name ) assert( TheMappedImageCollection ); if( TheMappedImageCollection ) - return TheMappedImageCollection->findImageByName( AsciiString( name ) ); + return TheMappedImageCollection->findImageByName( name ); return NULL; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp index 2684dfd832..f5e2871c92 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp @@ -1323,7 +1323,7 @@ static Bool parseDrawData( const char *token, WinInstanceData *instData, c = strtok( NULL, seps ); // value if( strcmp( c, "NoImage" ) ) - drawData->image = TheMappedImageCollection->findImageByName( AsciiString( c ) ); + drawData->image = TheMappedImageCollection->findImageByName( c ); else drawData->image = NULL; // COLOR: R G B A @@ -1652,7 +1652,7 @@ static GameWindow *createGadget( char *type, *c = 0; // terminate after filename (format is filename:gadgetname) assert( TheNameKeyGenerator ); if( TheNameKeyGenerator ) - rData->screen = (Int)(TheNameKeyGenerator->nameToKey( AsciiString(filename) )); + rData->screen = (Int)(TheNameKeyGenerator->nameToKey( filename )); instData->m_style |= GWS_RADIO_BUTTON; window = TheWindowManager->gogoGadgetRadioButton( parent, status, x, y, diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp index 19cb7a2aea..ef054982de 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp @@ -1903,13 +1903,11 @@ void MapTransferLoadScreen::init( GameInfo *game ) Int i; // Load the Filename Text - winName.format( "MapTransferScreen.wnd:StaticTextCurrentFile"); - m_fileNameText = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( winName )); + m_fileNameText = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "MapTransferScreen.wnd:StaticTextCurrentFile" )); DEBUG_ASSERTCRASH(m_fileNameText, ("Can't initialize the filename for the map transfer loadscreen")); // Load the Timeout Text - winName.format( "MapTransferScreen.wnd:StaticTextTimeout"); - m_timeoutText = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( winName )); + m_timeoutText = TheWindowManager->winGetWindowFromId( m_loadScreen,TheNameKeyGenerator->nameToKey( "MapTransferScreen.wnd:StaticTextTimeout" )); DEBUG_ASSERTCRASH(m_timeoutText, ("Can't initialize the timeout for the map transfer loadscreen")); Int netSlot = 0; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/Image.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/Image.cpp index 4949035b42..a701c03790 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/Image.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/Image.cpp @@ -204,7 +204,7 @@ ImageCollection::ImageCollection( void ) //------------------------------------------------------------------------------------------------- ImageCollection::~ImageCollection( void ) { - for (std::map::iterator i=m_imageMap.begin();i!=m_imageMap.end();++i) + for (ImageMap::iterator i=m_imageMap.begin();i!=m_imageMap.end();++i) deleteInstance(i->second); } @@ -216,13 +216,27 @@ void ImageCollection::addImage( Image *image ) m_imageMap[TheNameKeyGenerator->nameToLowercaseKey(image->getName())]=image; } +//------------------------------------------------------------------------------------------------- +const Image *ImageCollection::findImage( NameKeyType namekey ) const +{ + ImageMap::const_iterator i = m_imageMap.find(namekey); + return i == m_imageMap.end() ? NULL : i->second; +} + //------------------------------------------------------------------------------------------------- /** Find an image given the image name */ //------------------------------------------------------------------------------------------------- const Image *ImageCollection::findImageByName( const AsciiString& name ) const { - std::map::const_iterator i=m_imageMap.find(TheNameKeyGenerator->nameToLowercaseKey(name)); - return i==m_imageMap.end()?NULL:i->second; + return findImage(TheNameKeyGenerator->nameToLowercaseKey(name)); +} + +//------------------------------------------------------------------------------------------------- +/** Find an image given the image name */ +//------------------------------------------------------------------------------------------------- +const Image *ImageCollection::findImageByName( const char* name ) const +{ + return findImage(TheNameKeyGenerator->nameToLowercaseKey(name)); } //------------------------------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Armor.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Armor.cpp index a313d54b67..6d4578d197 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Armor.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Armor.cpp @@ -116,11 +116,10 @@ ArmorStore::~ArmorStore() } //------------------------------------------------------------------------------------------------- -const ArmorTemplate* ArmorStore::findArmorTemplate(AsciiString name) const +const ArmorTemplate* ArmorStore::findArmorTemplate(NameKeyType namekey) const { - NameKeyType namekey = TheNameKeyGenerator->nameToKey(name); - ArmorTemplateMap::const_iterator it = m_armorTemplates.find(namekey); - if (it == m_armorTemplates.end()) + ArmorTemplateMap::const_iterator it = m_armorTemplates.find(namekey); + if (it == m_armorTemplates.end()) { return NULL; } @@ -130,6 +129,18 @@ const ArmorTemplate* ArmorStore::findArmorTemplate(AsciiString name) const } } +//------------------------------------------------------------------------------------------------- +const ArmorTemplate* ArmorStore::findArmorTemplate(const AsciiString& name) const +{ + return findArmorTemplate(TheNameKeyGenerator->nameToKey(name)); +} + +//------------------------------------------------------------------------------------------------- +const ArmorTemplate* ArmorStore::findArmorTemplate(const char* name) const +{ + return findArmorTemplate(TheNameKeyGenerator->nameToKey(name)); +} + //------------------------------------------------------------------------------------------------- /*static */ void ArmorStore::parseArmorDefinition(INI *ini) { diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/CommandSetUpgrade.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/CommandSetUpgrade.cpp index 7d0286eb18..56c7b3b76b 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/CommandSetUpgrade.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/CommandSetUpgrade.cpp @@ -68,7 +68,7 @@ void CommandSetUpgrade::upgradeImplementation( ) { Object *obj = getObject(); - const char * upgradeAlt = getCommandSetUpgradeModuleData()->m_triggerAlt.str(); + const AsciiString& upgradeAlt = getCommandSetUpgradeModuleData()->m_triggerAlt; const UpgradeTemplate *upgradeTemplate = TheUpgradeCenter->findUpgrade( upgradeAlt ); if (upgradeTemplate) diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp index d9b9431ad8..5d700cbb1f 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp @@ -1622,12 +1622,22 @@ void WeaponStore::createAndFireTempWeapon(const WeaponTemplate* wt, const Object } //------------------------------------------------------------------------------------------------- -const WeaponTemplate *WeaponStore::findWeaponTemplate( AsciiString name ) const +const WeaponTemplate *WeaponStore::findWeaponTemplate( const AsciiString& name ) const { - if (stricmp(name.str(), "None") == 0) + if (name.compareNoCase("None") == 0) return NULL; const WeaponTemplate * wt = findWeaponTemplatePrivate( TheNameKeyGenerator->nameToKey( name ) ); - DEBUG_ASSERTCRASH(wt != NULL, ("Weapon %s not found!",name.str())); + DEBUG_ASSERTCRASH(wt != NULL, ("Weapon %s not found!",name)); + return wt; +} + +//------------------------------------------------------------------------------------------------- +const WeaponTemplate *WeaponStore::findWeaponTemplate( const char* name ) const +{ + if (stricmp(name, "None") == 0) + return NULL; + const WeaponTemplate * wt = findWeaponTemplatePrivate( TheNameKeyGenerator->nameToKey( name ) ); + DEBUG_ASSERTCRASH(wt != NULL, ("Weapon %s not found!",name)); return wt; } 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 469b401b45..d7ca602a5a 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp @@ -1490,8 +1490,10 @@ void W3DModelDrawModuleData::parseConditionState(INI* ini, void *instance, void case PARSE_TRANSITION: { - AsciiString firstNm = ini->getNextToken(); firstNm.toLower(); - AsciiString secondNm = ini->getNextToken(); secondNm.toLower(); + AsciiString firstNm = ini->getNextToken(); + AsciiString secondNm = ini->getNextToken(); + firstNm.toLower(); + secondNm.toLower(); NameKeyType firstKey = NAMEKEY(firstNm); NameKeyType secondKey = NAMEKEY(secondNm); diff --git a/GeneralsMD/Code/Tools/GUIEdit/Source/Dialog Procedures/RadioButtonProperties.cpp b/GeneralsMD/Code/Tools/GUIEdit/Source/Dialog Procedures/RadioButtonProperties.cpp index 5695ad0781..524f483be8 100644 --- a/GeneralsMD/Code/Tools/GUIEdit/Source/Dialog Procedures/RadioButtonProperties.cpp +++ b/GeneralsMD/Code/Tools/GUIEdit/Source/Dialog Procedures/RadioButtonProperties.cpp @@ -177,7 +177,7 @@ static LRESULT CALLBACK radioButtonPropertiesCallback( HWND hWndDialog, // save group Int group = GetDlgItemInt( hWndDialog, COMBO_GROUP, NULL, FALSE ); - Int screen = TheNameKeyGenerator->nameToKey( AsciiString(TheEditor->getSaveFilename()) ); + Int screen = TheNameKeyGenerator->nameToKey( TheEditor->getSaveFilename() ); GadgetRadioSetGroup( window, group, screen ); } diff --git a/GeneralsMD/Code/Tools/GUIEdit/Source/LayoutScheme.cpp b/GeneralsMD/Code/Tools/GUIEdit/Source/LayoutScheme.cpp index 5e828d1837..bb83dbe0d3 100644 --- a/GeneralsMD/Code/Tools/GUIEdit/Source/LayoutScheme.cpp +++ b/GeneralsMD/Code/Tools/GUIEdit/Source/LayoutScheme.cpp @@ -2433,7 +2433,7 @@ Bool LayoutScheme::loadScheme( char *filename ) // store the info storeImageAndColor( (StateIdentifier)state, - TheMappedImageCollection->findImageByName( AsciiString( imageBuffer ) ), + TheMappedImageCollection->findImageByName( imageBuffer ), GameMakeColor( colorR, colorG, colorB, colorA ), GameMakeColor( bColorR, bColorG, bColorB, bColorA ) ); } diff --git a/GeneralsMD/Code/Tools/GUIEdit/Source/Properties.cpp b/GeneralsMD/Code/Tools/GUIEdit/Source/Properties.cpp index f5c1815382..1b6c26daf0 100644 --- a/GeneralsMD/Code/Tools/GUIEdit/Source/Properties.cpp +++ b/GeneralsMD/Code/Tools/GUIEdit/Source/Properties.cpp @@ -1258,7 +1258,7 @@ const Image *ComboBoxSelectionToImage( HWND comboBox ) SendMessage( comboBox, CB_GETLBTEXT, selected, (LPARAM)buffer ); // return the image loc that matches the string - return TheMappedImageCollection->findImageByName( AsciiString( buffer ) ); + return TheMappedImageCollection->findImageByName( buffer ); } diff --git a/GeneralsMD/Code/Tools/GUIEdit/Source/Save.cpp b/GeneralsMD/Code/Tools/GUIEdit/Source/Save.cpp index 02f7e27f3d..7849582e6b 100644 --- a/GeneralsMD/Code/Tools/GUIEdit/Source/Save.cpp +++ b/GeneralsMD/Code/Tools/GUIEdit/Source/Save.cpp @@ -1235,7 +1235,7 @@ Bool GUIEdit::saveData( char *filePathAndFilename, char *filename ) // update all radio button screen identifiers with the filename updateRadioScreenIdentifiers( TheWindowManager->winGetWindowList(), - TheNameKeyGenerator->nameToKey( AsciiString(m_saveFilename) ) ); + TheNameKeyGenerator->nameToKey( m_saveFilename ) ); // open the file fp = fopen( filePathAndFilename, "w" ); diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/addplayerdialog.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/addplayerdialog.cpp index bf608910a0..21e6149dc0 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/addplayerdialog.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/addplayerdialog.cpp @@ -76,9 +76,8 @@ void AddPlayerDialog::OnOK() } else { faction->GetWindowText(theText); } - AsciiString name((LPCTSTR)theText); - const PlayerTemplate* pt = ThePlayerTemplateStore->findPlayerTemplate(NAMEKEY(name)); + const PlayerTemplate* pt = ThePlayerTemplateStore->findPlayerTemplate(NAMEKEY((LPCTSTR)theText)); if (pt) { m_addedSide = pt ? pt->getName() : AsciiString::TheEmptyString; From 38abe9e35753f3bd5aaef8bc77a0f396601d1899 Mon Sep 17 00:00:00 2001 From: Mauller <26652186+Mauller@users.noreply.github.com> Date: Sat, 13 Dec 2025 10:54:13 +0000 Subject: [PATCH 29/70] bugfix(network): Prevent buffer overflow in NetPacket::readFileMessage() and NetPacket::readFileAnnounceMessage() (#1981) Co-authored-by: JBremer Co-authored-by: SkyAero --- .../Source/GameNetwork/NetPacket.cpp | 22 +++++-------------- 1 file changed, 6 insertions(+), 16 deletions(-) diff --git a/Core/GameEngine/Source/GameNetwork/NetPacket.cpp b/Core/GameEngine/Source/GameNetwork/NetPacket.cpp index ea92f9c498..8b9590124c 100644 --- a/Core/GameEngine/Source/GameNetwork/NetPacket.cpp +++ b/Core/GameEngine/Source/GameNetwork/NetPacket.cpp @@ -5807,15 +5807,10 @@ NetCommandMsg * NetPacket::readWrapperMessage(UnsignedByte *data, Int &i) { NetCommandMsg * NetPacket::readFileMessage(UnsignedByte *data, Int &i) { NetFileCommandMsg *msg = newInstance(NetFileCommandMsg); char filename[_MAX_PATH]; - char *c = filename; - while (data[i] != 0) { - *c = data[i]; - ++c; - ++i; - } - *c = 0; - ++i; + // TheSuperHackers @security Mauller/Jbremer/SkyAero 11/12/2025 Prevent buffer overflow when copying filepath string + i += strlcpy(filename, reinterpret_cast(data), ARRAY_SIZE(filename)); + ++i; //Increment for null terminator msg->setPortableFilename(AsciiString(filename)); // it's transferred as a portable filename UnsignedInt dataLength = 0; @@ -5834,15 +5829,10 @@ NetCommandMsg * NetPacket::readFileMessage(UnsignedByte *data, Int &i) { NetCommandMsg * NetPacket::readFileAnnounceMessage(UnsignedByte *data, Int &i) { NetFileAnnounceCommandMsg *msg = newInstance(NetFileAnnounceCommandMsg); char filename[_MAX_PATH]; - char *c = filename; - while (data[i] != 0) { - *c = data[i]; - ++c; - ++i; - } - *c = 0; - ++i; + // TheSuperHackers @security Mauller/Jbremer/SkyAero 11/12/2025 Prevent buffer overflow when copying filepath string + i += strlcpy(filename, reinterpret_cast(data), ARRAY_SIZE(filename)); + ++i; //Increment for null terminator msg->setPortableFilename(AsciiString(filename)); // it's transferred as a portable filename UnsignedShort fileID = 0; From c5aa3cd8104c8ed7b434fbff0cc70cf4cd2c12b4 Mon Sep 17 00:00:00 2001 From: Bobby Battista Date: Sat, 13 Dec 2025 07:14:31 -0500 Subject: [PATCH 30/70] fix(network): Fix missing value initialization of LANGameInfo::m_isDirectConnect (#1836) --- Core/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp | 1 + Core/GameEngine/Source/GameNetwork/LANGameInfo.cpp | 2 ++ 2 files changed, 3 insertions(+) diff --git a/Core/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp b/Core/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp index 3c79e60cac..d6dbba0823 100644 --- a/Core/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp +++ b/Core/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp @@ -65,6 +65,7 @@ void LANAPI::handleRequestLocations( LANMessage *msg, UnsignedInt senderIP ) strlcpy(reply.GameInfo.options, gameOpts.str(), ARRAY_SIZE(reply.GameInfo.options)); wcslcpy(reply.GameInfo.gameName, m_currentGame->getName().str(), ARRAY_SIZE(reply.GameInfo.gameName)); reply.GameInfo.inProgress = m_currentGame->isGameInProgress(); + reply.GameInfo.isDirectConnect = m_currentGame->getIsDirectConnect(); sendMessage(&reply); } diff --git a/Core/GameEngine/Source/GameNetwork/LANGameInfo.cpp b/Core/GameEngine/Source/GameNetwork/LANGameInfo.cpp index c86a8d844a..a34b6ea0e7 100644 --- a/Core/GameEngine/Source/GameNetwork/LANGameInfo.cpp +++ b/Core/GameEngine/Source/GameNetwork/LANGameInfo.cpp @@ -90,6 +90,8 @@ LANGameInfo::LANGameInfo() { m_lastHeard = 0; m_next = NULL; + m_isDirectConnect = false; + // for (Int i = 0; i< MAX_SLOTS; ++i) setSlotPointer(i, &m_LANSlot[i]); From 746c017c368a3dd0b1d6cad83fa3b88130566bbe Mon Sep 17 00:00:00 2001 From: Bobby Battista Date: Sun, 14 Dec 2025 15:52:28 -0500 Subject: [PATCH 31/70] refactor: Apply the readability-container-size-empty check with clang-tidy (#1957) --- .../Source/Common/Audio/AudioEventRTS.cpp | 2 +- Core/GameEngine/Source/Common/System/Xfer.cpp | 6 +++--- .../Source/GameNetwork/GameSpy/LadderDefs.cpp | 8 ++++---- .../GameNetwork/GameSpy/MainMenuUtils.cpp | 2 +- .../Source/GameNetwork/GameSpy/PeerDefs.cpp | 2 +- .../GameNetwork/GameSpy/Thread/PeerThread.cpp | 4 ++-- .../Thread/PersistentStorageThread.cpp | 20 +++++++++---------- .../StdDevice/Common/StdLocalFileSystem.cpp | 2 +- .../Libraries/Source/WWVegas/WWLib/notifier.h | 2 +- .../Include/GameClient/AnimateWindowManager.h | 2 +- .../GameEngine/Source/Common/RTS/Player.cpp | 6 +++--- .../Common/RTS/ProductionPrerequisite.cpp | 2 +- .../Source/Common/RTS/TunnelTracker.cpp | 2 +- .../GameEngine/Source/GameClient/Credits.cpp | 2 +- .../Code/GameEngine/Source/GameClient/Eva.cpp | 2 +- .../GUI/ControlBar/ControlBarScheme.cpp | 2 +- .../GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp | 6 +++--- .../GUICallbacks/Menus/WOLQuickMatchMenu.cpp | 6 +++--- .../GameClient/GUI/GameWindowManager.cpp | 4 ++-- .../GameEngine/Source/GameClient/InGameUI.cpp | 6 +++--- .../GameEngine/Source/GameLogic/AI/AI.cpp | 2 +- .../Source/GameLogic/AI/AIGroup.cpp | 4 ++-- .../Source/GameLogic/AI/AIStates.cpp | 4 ++-- .../GameEngine/Source/GameLogic/AI/Squad.cpp | 2 +- .../Object/Behavior/BridgeBehavior.cpp | 2 +- .../GameLogic/Object/ObjectCreationList.cpp | 4 ++-- .../GameLogic/Object/PartitionManager.cpp | 2 +- .../GameLogic/Object/Update/AIUpdate.cpp | 2 +- .../AIUpdate/DeliverPayloadAIUpdate.cpp | 2 +- .../Source/GameLogic/Object/Weapon.cpp | 4 ++-- .../GameLogic/ScriptEngine/ScriptEngine.cpp | 2 +- .../GameClient/Module/W3DModelDraw.h | 2 +- .../GameClient/Drawable/Draw/W3DModelDraw.cpp | 8 ++++---- .../W3DDevice/GameLogic/W3DTerrainLogic.cpp | 2 +- .../ParticleEditor/ParticleEditorDialog.cpp | 2 +- .../Tools/WorldBuilder/src/LayersList.cpp | 2 +- .../WorldBuilder/src/MeshMoldOptions.cpp | 2 +- .../Tools/WorldBuilder/src/ObjectOptions.cpp | 2 +- .../Tools/WorldBuilder/src/RoadOptions.cpp | 2 +- .../WorldBuilder/src/SelectMacrotexture.cpp | 2 +- .../Tools/WorldBuilder/src/WHeightMapEdit.cpp | 4 ++-- .../WorldBuilder/src/WorldBuilderDoc.cpp | 8 ++++---- .../Tools/WorldBuilder/src/mapobjectprops.cpp | 2 +- .../Include/GameClient/AnimateWindowManager.h | 2 +- .../GameEngine/Source/Common/RTS/Player.cpp | 6 +++--- .../Common/RTS/ProductionPrerequisite.cpp | 2 +- .../Source/Common/RTS/TunnelTracker.cpp | 2 +- .../GameEngine/Source/GameClient/Credits.cpp | 2 +- .../Code/GameEngine/Source/GameClient/Eva.cpp | 2 +- .../GUI/ControlBar/ControlBarScheme.cpp | 2 +- .../GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp | 6 +++--- .../GUICallbacks/Menus/WOLQuickMatchMenu.cpp | 6 +++--- .../GameClient/GUI/GameWindowManager.cpp | 4 ++-- .../GameEngine/Source/GameClient/InGameUI.cpp | 6 +++--- .../GameEngine/Source/GameLogic/AI/AI.cpp | 2 +- .../Source/GameLogic/AI/AIGroup.cpp | 4 ++-- .../Source/GameLogic/AI/AIStates.cpp | 4 ++-- .../GameEngine/Source/GameLogic/AI/Squad.cpp | 2 +- .../Object/Behavior/BridgeBehavior.cpp | 2 +- .../GameLogic/Object/ObjectCreationList.cpp | 4 ++-- .../GameLogic/Object/PartitionManager.cpp | 2 +- .../GameLogic/Object/Update/AIUpdate.cpp | 2 +- .../AIUpdate/DeliverPayloadAIUpdate.cpp | 2 +- .../Source/GameLogic/Object/Weapon.cpp | 4 ++-- .../GameLogic/ScriptEngine/ScriptEngine.cpp | 2 +- .../GameClient/Module/W3DModelDraw.h | 2 +- .../GameClient/Drawable/Draw/W3DModelDraw.cpp | 8 ++++---- .../W3DDevice/GameLogic/W3DTerrainLogic.cpp | 2 +- .../ParticleEditor/ParticleEditorDialog.cpp | 2 +- .../Tools/WorldBuilder/src/LayersList.cpp | 4 ++-- .../WorldBuilder/src/MeshMoldOptions.cpp | 2 +- .../Tools/WorldBuilder/src/ObjectOptions.cpp | 2 +- .../Tools/WorldBuilder/src/RoadOptions.cpp | 2 +- .../WorldBuilder/src/SelectMacrotexture.cpp | 2 +- .../Tools/WorldBuilder/src/WHeightMapEdit.cpp | 4 ++-- .../WorldBuilder/src/WorldBuilderDoc.cpp | 8 ++++---- .../Tools/WorldBuilder/src/mapobjectprops.cpp | 2 +- 77 files changed, 133 insertions(+), 133 deletions(-) diff --git a/Core/GameEngine/Source/Common/Audio/AudioEventRTS.cpp b/Core/GameEngine/Source/Common/Audio/AudioEventRTS.cpp index 666b8e6021..eda40c71c7 100644 --- a/Core/GameEngine/Source/Common/Audio/AudioEventRTS.cpp +++ b/Core/GameEngine/Source/Common/Audio/AudioEventRTS.cpp @@ -329,7 +329,7 @@ void AudioEventRTS::generateFilename( void ) adjustForLocalization(m_filenameToLoad); return; } else { - if (m_eventInfo->m_sounds.size() == 0) { + if (m_eventInfo->m_sounds.empty()) { m_filenameToLoad = AsciiString::TheEmptyString; return; } diff --git a/Core/GameEngine/Source/Common/System/Xfer.cpp b/Core/GameEngine/Source/Common/System/Xfer.cpp index a9c55059a7..4427a7dd0a 100644 --- a/Core/GameEngine/Source/Common/System/Xfer.cpp +++ b/Core/GameEngine/Source/Common/System/Xfer.cpp @@ -395,7 +395,7 @@ void Xfer::xferSTLObjectIDVector( std::vector *objectIDVectorData ) { // sanity, the list should be empty before we transfer more data into it - if( objectIDVectorData->size() != 0 ) + if( !objectIDVectorData->empty() ) { DEBUG_CRASH(( "Xfer::xferSTLObjectIDList - object vector should be empty before loading" )); @@ -462,7 +462,7 @@ void Xfer::xferSTLObjectIDList( std::list< ObjectID > *objectIDListData ) { // sanity, the list should be empty before we transfer more data into it - if( objectIDListData->size() != 0 ) + if( !objectIDListData->empty() ) { DEBUG_CRASH(( "Xfer::xferSTLObjectIDList - object list should be empty before loading" )); @@ -528,7 +528,7 @@ void Xfer::xferSTLIntList( std::list< Int > *intListData ) { // sanity, the list should be empty before we transfer more data into it - if( intListData->size() != 0 ) + if( !intListData->empty() ) { DEBUG_CRASH(( "Xfer::xferSTLIntList - int list should be empty before loading" )); diff --git a/Core/GameEngine/Source/GameNetwork/GameSpy/LadderDefs.cpp b/Core/GameEngine/Source/GameNetwork/GameSpy/LadderDefs.cpp index 5c566feb60..c59f0613a2 100644 --- a/Core/GameEngine/Source/GameNetwork/GameSpy/LadderDefs.cpp +++ b/Core/GameEngine/Source/GameNetwork/GameSpy/LadderDefs.cpp @@ -163,7 +163,7 @@ static LadderInfo *parseLadder(AsciiString raw) // end of a ladder if (lad->playersPerTeam >= 1 && lad->playersPerTeam <= MAX_SLOTS/2) { - if (lad->validFactions.size() == 0) + if (lad->validFactions.empty()) { DEBUG_LOG(("No factions specified. Using all.")); lad->validFactions.clear(); @@ -190,7 +190,7 @@ static LadderInfo *parseLadder(AsciiString raw) } } - if (lad->validMaps.size() == 0) + if (lad->validMaps.empty()) { DEBUG_LOG(("No maps specified. Using all.")); std::list qmMaps = TheGameSpyConfig->getQMMaps(); @@ -503,9 +503,9 @@ void LadderList::checkLadder( AsciiString fname, Int index ) return; } - if (li->validMaps.size() == 0) + if (li->validMaps.empty()) { - DEBUG_LOG(("Bailing because of li->validMaps.size() == 0")); + DEBUG_LOG(("Bailing because of li->validMaps.empty()")); delete li; return; } diff --git a/Core/GameEngine/Source/GameNetwork/GameSpy/MainMenuUtils.cpp b/Core/GameEngine/Source/GameNetwork/GameSpy/MainMenuUtils.cpp index 81c8ebcc69..c6585cef93 100644 --- a/Core/GameEngine/Source/GameNetwork/GameSpy/MainMenuUtils.cpp +++ b/Core/GameEngine/Source/GameNetwork/GameSpy/MainMenuUtils.cpp @@ -191,7 +191,7 @@ static void startOnline( void ) noPatchBeforeOnlineCallback); return; } - if (queuedDownloads.size()) + if (!queuedDownloads.empty()) { if (!hasWriteAccess()) { diff --git a/Core/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp b/Core/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp index 047ddd1bb1..4e64c1b167 100644 --- a/Core/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp +++ b/Core/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp @@ -378,7 +378,7 @@ void GameSpyInfo::joinBestGroupRoom( void ) return; } - if (m_groupRooms.size()) + if (!m_groupRooms.empty()) { int minID = -1; int minPlayers = 1000; diff --git a/Core/GameEngine/Source/GameNetwork/GameSpy/Thread/PeerThread.cpp b/Core/GameEngine/Source/GameNetwork/GameSpy/Thread/PeerThread.cpp index 05f7bbb75f..40c5c660e9 100644 --- a/Core/GameEngine/Source/GameNetwork/GameSpy/Thread/PeerThread.cpp +++ b/Core/GameEngine/Source/GameNetwork/GameSpy/Thread/PeerThread.cpp @@ -1663,7 +1663,7 @@ void PeerThreadClass::Thread_Function() m_playerFactions[i] = 0; m_playerColors[i] = 0; } - if (incomingRequest.password.length() > 0) + if (!incomingRequest.password.empty()) m_hasPassword = true; else m_hasPassword = false; @@ -1714,7 +1714,7 @@ void PeerThreadClass::Thread_Function() case PeerRequest::PEERREQUEST_UTMPLAYER: { - if (incomingRequest.nick.length() > 0) + if (!incomingRequest.nick.empty()) { peerUTMPlayer( peer, incomingRequest.nick.c_str(), incomingRequest.id.c_str(), incomingRequest.options.c_str(), PEERFalse ); } diff --git a/Core/GameEngine/Source/GameNetwork/GameSpy/Thread/PersistentStorageThread.cpp b/Core/GameEngine/Source/GameNetwork/GameSpy/Thread/PersistentStorageThread.cpp index d21dc20533..959004fc32 100644 --- a/Core/GameEngine/Source/GameNetwork/GameSpy/Thread/PersistentStorageThread.cpp +++ b/Core/GameEngine/Source/GameNetwork/GameSpy/Thread/PersistentStorageThread.cpp @@ -102,12 +102,12 @@ static void debugDumpPlayerStats( const PSPlayerStats& stats ) DEBUG_LOG(("gamesAsRandom: %d", stats.gamesAsRandom)); } - if (stats.options.length()) + if (!stats.options.empty()) { DEBUG_LOG(("Options: %s", stats.options.c_str())); } - if (stats.systemSpec.length()) + if (!stats.systemSpec.empty()) { DEBUG_LOG(("systemSpec: %s", stats.systemSpec.c_str())); } @@ -184,7 +184,7 @@ static void debugDumpPlayerStats( const PSPlayerStats& stats ) DEBUG_LOG(("lastLadderPort: %d", stats.lastLadderPort)); } - if (stats.lastLadderHost.length()) + if (!stats.lastLadderHost.empty()) { DEBUG_LOG(("lastLadderHost: %s", stats.lastLadderHost.c_str())); } @@ -246,12 +246,12 @@ void PSPlayerStats::incorporate( const PSPlayerStats& other ) gamesAsRandom = other.gamesAsRandom; } - if (other.options.length()) + if (!other.options.empty()) { options = other.options; } - if (other.systemSpec.length()) + if (!other.systemSpec.empty()) { systemSpec = other.systemSpec; } @@ -325,7 +325,7 @@ void PSPlayerStats::incorporate( const PSPlayerStats& other ) { lastLadderPort = other.lastLadderPort; } - if (other.lastLadderHost.length()) + if (!other.lastLadderHost.empty()) { lastLadderHost = other.lastLadderHost; } @@ -971,7 +971,7 @@ void PSThreadClass::Thread_Function() addedInDesyncs4 + req.addDesync, addedInDiscons4 + req.addDiscon)); } pref.write(); - if (req.password.size() == 0) + if (req.password.empty()) return; } if (!req.player.id) @@ -1370,13 +1370,13 @@ std::string GameSpyPSMessageQueueInterface::formatPlayerKVPairs( PSPlayerStats s s.append(kvbuf); } - if (stats.options.length()) + if (!stats.options.empty()) { snprintf(kvbuf, 256, "\\options\\%s", stats.options.c_str()); s.append(kvbuf); } - if (stats.systemSpec.length()) + if (!stats.systemSpec.empty()) { snprintf(kvbuf, 256, "\\systemSpec\\%s", stats.systemSpec.c_str()); s.append(kvbuf); @@ -1472,7 +1472,7 @@ std::string GameSpyPSMessageQueueInterface::formatPlayerKVPairs( PSPlayerStats s sprintf(kvbuf, "\\ladderPort\\%d", stats.lastLadderPort); s.append(kvbuf); } - if (stats.lastLadderHost.length()) + if (!stats.lastLadderHost.empty()) { snprintf(kvbuf, 256, "\\ladderHost\\%s", stats.lastLadderHost.c_str()); s.append(kvbuf); diff --git a/Core/GameEngineDevice/Source/StdDevice/Common/StdLocalFileSystem.cpp b/Core/GameEngineDevice/Source/StdDevice/Common/StdLocalFileSystem.cpp index a9a3362c6c..b20aa0eda6 100644 --- a/Core/GameEngineDevice/Source/StdDevice/Common/StdLocalFileSystem.cpp +++ b/Core/GameEngineDevice/Source/StdDevice/Common/StdLocalFileSystem.cpp @@ -323,7 +323,7 @@ Bool StdLocalFileSystem::createDirectory(AsciiString directory) std::replace(fixedDirectory.begin(), fixedDirectory.end(), '\\', '/'); #endif - if ((fixedDirectory.length() > 0) && (fixedDirectory.length() < _MAX_DIR)) { + if ((!fixedDirectory.empty()) && (fixedDirectory.length() < _MAX_DIR)) { // Convert to host path std::filesystem::path path(std::move(fixedDirectory)); diff --git a/Core/Libraries/Source/WWVegas/WWLib/notifier.h b/Core/Libraries/Source/WWVegas/WWLib/notifier.h index 037dceb2c4..97aaca0831 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/notifier.h +++ b/Core/Libraries/Source/WWVegas/WWLib/notifier.h @@ -88,7 +88,7 @@ template class Observer //! Stop observing event void StopObserving() { - while (mNotifiers.size() > 0) + while (!mNotifiers.empty()) { Notifier* notifier = mNotifiers.back(); assert(notifier && "ERROR: NULL pointer in collection."); diff --git a/Generals/Code/GameEngine/Include/GameClient/AnimateWindowManager.h b/Generals/Code/GameEngine/Include/GameClient/AnimateWindowManager.h index a3e72e0dae..523a4276f5 100644 --- a/Generals/Code/GameEngine/Include/GameClient/AnimateWindowManager.h +++ b/Generals/Code/GameEngine/Include/GameClient/AnimateWindowManager.h @@ -229,7 +229,7 @@ namespace wnd inline Bool AnimateWindowManager::isFinished( void ) { return !m_needsUpdate; }; inline Bool AnimateWindowManager::isReversed( void ) { return m_reverse; }; - inline Bool AnimateWindowManager::isEmpty( void ){return (m_winList.size() == 0 && m_winMustFinishList.size() == 0); } + inline Bool AnimateWindowManager::isEmpty( void ){return (m_winList.empty() && m_winMustFinishList.empty()); } //----------------------------------------------------------------------------- // EXTERNALS ////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Source/Common/RTS/Player.cpp b/Generals/Code/GameEngine/Source/Common/RTS/Player.cpp index 90b9fc6008..6fe1d4fca4 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/Player.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/Player.cpp @@ -352,7 +352,7 @@ Player::Player( Int playerIndex ) void Player::init(const PlayerTemplate* pt) { - DEBUG_ASSERTCRASH(m_playerTeamPrototypes.size() == 0, ("Player::m_playerTeamPrototypes is not empty at game start!")); + DEBUG_ASSERTCRASH(m_playerTeamPrototypes.empty(), ("Player::m_playerTeamPrototypes is not empty at game start!")); m_skillPointsModifier = 1.0f; m_attackedFrame = 0; @@ -3913,7 +3913,7 @@ void Player::xfer( Xfer *xfer ) { // sanity, list must be empty right now - if( m_kindOfPercentProductionChangeList.size() != 0 ) + if( !m_kindOfPercentProductionChangeList.empty() ) { DEBUG_CRASH(( "Player::xfer - m_kindOfPercentProductionChangeList should be empty but is not" )); @@ -3966,7 +3966,7 @@ void Player::xfer( Xfer *xfer ) } else { - if( m_specialPowerReadyTimerList.size() != 0 ) // sanity, list must be empty right now + if( !m_specialPowerReadyTimerList.empty() ) // sanity, list must be empty right now { DEBUG_CRASH(( "Player::xfer - m_specialPowerReadyTimerList should be empty but is not" )); throw SC_INVALID_DATA; diff --git a/Generals/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp b/Generals/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp index bc70cbb12b..1decc6c6e6 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp @@ -128,7 +128,7 @@ Int ProductionPrerequisite::getAllPossibleBuildFacilityTemplates(const ThingTemp const ThingTemplate *ProductionPrerequisite::getExistingBuildFacilityTemplate( const Player *player ) const { DEBUG_ASSERTCRASH(player, ("player may not be null")); - if (m_prereqUnits.size()) + if (!m_prereqUnits.empty()) { Int ownCount[MAX_PREREQ]; Int cnt = calcNumPrereqUnitsOwned(player, ownCount); diff --git a/Generals/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp b/Generals/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp index cac0a999b1..541d644a7c 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp @@ -414,7 +414,7 @@ void TunnelTracker::loadPostProcess( void ) { // sanity, the contain list should be empty until we post process the id list - if( m_containList.size() != 0 ) + if( !m_containList.empty() ) { DEBUG_CRASH(( "TunnelTracker::loadPostProcess - m_containList should be empty but is not" )); diff --git a/Generals/Code/GameEngine/Source/GameClient/Credits.cpp b/Generals/Code/GameEngine/Source/GameClient/Credits.cpp index 7d132eae2b..2774ced465 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Credits.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Credits.cpp @@ -221,7 +221,7 @@ void CreditsManager::update( void ) if(!((m_scrollDown && (yTest >= start)) || (!m_scrollDown && (yTest <= start)))) return; - if(m_displayedCreditLineList.size() == 0 && m_creditLineListIt == m_creditLineList.end()) + if(m_displayedCreditLineList.empty() && m_creditLineListIt == m_creditLineList.end()) m_isFinished = TRUE; if(m_creditLineListIt == m_creditLineList.end()) diff --git a/Generals/Code/GameEngine/Source/GameClient/Eva.cpp b/Generals/Code/GameEngine/Source/GameClient/Eva.cpp index f2e86d0498..60c7ec34f5 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Eva.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Eva.cpp @@ -436,7 +436,7 @@ void Eva::processPlayingMessages(UnsignedInt currentFrame) for (Int i = 0; i < numSides; ++i) { if (side.compareNoCase(storedIt->m_evaInfo->m_evaSideSounds[i].m_side) == 0) { // Its this one. - if (storedIt->m_evaInfo->m_evaSideSounds[i].m_soundNames.size() > 0) { + if (!storedIt->m_evaInfo->m_evaSideSounds[i].m_soundNames.empty()) { Int soundToPlay = GameClientRandomValue(0, storedIt->m_evaInfo->m_evaSideSounds[i].m_soundNames.size() - 1); m_evaSpeech.setEventName(storedIt->m_evaInfo->m_evaSideSounds[i].m_soundNames[soundToPlay]); } else { diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp index f5ec055e12..949284420c 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp @@ -1009,7 +1009,7 @@ void ControlBarSchemeManager::init( void ) // if (FindFirstFile(userDataPath.str(), &findData) !=INVALID_HANDLE_VALUE) // ini.loadFileDirectory(userDataPath, INI_LOAD_OVERWRITE, NULL ); // } - if( m_schemeList.size() <= 0 ) + if( m_schemeList.empty() ) { DEBUG_ASSERTCRASH(FALSE,("There's no ControlBarScheme in the ControlBarSchemeList:m_schemeList that was just read from the INI file")); return; 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 e719999f2f..ee6569ab86 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp @@ -563,7 +563,7 @@ void PopulateLobbyPlayerListbox(void) } // restore selection - if (indicesToSelect.size()) + if (!indicesToSelect.empty()) { std::set::const_iterator indexIt = indicesToSelect.begin(); const size_t count = indicesToSelect.size(); @@ -1148,7 +1148,7 @@ void WOLLobbyMenuUpdate( WindowLayout * layout, void *userData) //if (ParseAsciiStringToGameInfo(&room, resp.stagingRoomMapName.c_str())) //if (ParseAsciiStringToGameInfo(&room, resp.stagingServerGameOptions.c_str())) Bool serverOk = TRUE; - if (!resp.stagingRoomMapName.length()) + if (resp.stagingRoomMapName.empty()) { serverOk = FALSE; } @@ -1220,7 +1220,7 @@ void WOLLobbyMenuUpdate( WindowLayout * layout, void *userData) slot->setState(SLOT_BRUTAL_AI); ++numPlayers; } - else if (resp.stagingRoomPlayerNames[i].length()) + else if (!resp.stagingRoomPlayerNames[i].empty()) { UnicodeString nameUStr; nameUStr.translate(resp.stagingRoomPlayerNames[i].c_str()); 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 35d8a0bf6e..10018d7577 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp @@ -786,9 +786,9 @@ void WOLQuickMatchMenuInit( WindowLayout *layout, void *userData ) comboBoxSide = TheWindowManager->winGetWindowFromId( parentWOLQuickMatch, comboBoxSideID ); comboBoxColor = TheWindowManager->winGetWindowFromId( parentWOLQuickMatch, comboBoxColorID ); - if (TheLadderList->getStandardLadders()->size() == 0 - && TheLadderList->getSpecialLadders()->size() == 0 - && TheLadderList->getLocalLadders()->size() == 0) + if (TheLadderList->getStandardLadders()->empty() + && TheLadderList->getSpecialLadders()->empty() + && TheLadderList->getLocalLadders()->empty()) { // no ladders, so just disable them comboBoxDisabledLadder = comboBoxLadder; diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp index ddddb59367..de8aa1c029 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp @@ -3976,7 +3976,7 @@ Bool GameWindowManager::initTestGUI( void ) void GameWindowManager::winNextTab( GameWindow *window ) { - if(m_tabList.size() == 0|| m_modalHead) + if(m_tabList.empty()|| m_modalHead) return; GameWindowList::iterator it = m_tabList.begin(); @@ -4000,7 +4000,7 @@ void GameWindowManager::winNextTab( GameWindow *window ) void GameWindowManager::winPrevTab( GameWindow *window ) { - if(m_tabList.size() == 0 || m_modalHead) + if(m_tabList.empty() || m_modalHead) return; GameWindowList::reverse_iterator it = m_tabList.rbegin(); diff --git a/Generals/Code/GameEngine/Source/GameClient/InGameUI.cpp b/Generals/Code/GameEngine/Source/GameClient/InGameUI.cpp index 773aed31c2..32df1e7dd2 100644 --- a/Generals/Code/GameEngine/Source/GameClient/InGameUI.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/InGameUI.cpp @@ -623,7 +623,7 @@ Bool InGameUI::removeSuperweapon(Int playerIndex, const AsciiString& powerName, SuperweaponInfo *info = *listIt; swList.erase(listIt); deleteInstance(info); - if (swList.size() == 0) + if (swList.empty()) { m_superweapons[playerIndex].erase(mapIt); } @@ -4522,7 +4522,7 @@ Bool InGameUI::canSelectedObjectsDoSpecialPower( const CommandButton *command, c if (ignoreSelDraw) tmpList.push_back(ignoreSelDraw); - const DrawableList* selected = (tmpList.size() > 0) ? &tmpList : TheInGameUI->getAllSelectedDrawables(); + const DrawableList* selected = (!tmpList.empty()) ? &tmpList : TheInGameUI->getAllSelectedDrawables(); // set up counters for rule checking Int count = 0; @@ -4785,7 +4785,7 @@ Int InGameUI::selectMatchingAcrossRegion( IRegion2D *region ) } } - if (drawableList.size() == 0) + if (drawableList.empty()) return -1; // nothing useful selected to begin with - don't bother iterating std::set::iterator iter; diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/AI.cpp index 72ba53e678..430028eb38 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/AI.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/AI.cpp @@ -324,7 +324,7 @@ void AI::reset( void ) } #if RETAIL_COMPATIBLE_AIGROUP - while (m_groupList.size()) + while (!m_groupList.empty()) { AIGroup *groupToRemove = m_groupList.front(); if (groupToRemove) diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp index abe1e67bf6..aa09e57472 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp @@ -1042,7 +1042,7 @@ Bool AIGroup::friend_moveInfantryToPos( const Coord3D *pos, CommandSourceType cm dest.y -= factor*offset*endVector.y; dest.z = TheTerrainLogic->getLayerHeight( dest.x, dest.y, layer ); - while (path.size()>0) { + while (!path.empty()) { Coord2D curVector; prevPos = path[path.size()-1]; curVector.x = dest.x-prevPos.x; @@ -1520,7 +1520,7 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmd dest.y -= factor*offset*endVector.y; dest.z = TheTerrainLogic->getLayerHeight( dest.x, dest.y, layer ); - while (path.size()>0) { + while (!path.empty()) { Coord2D curVector; prevPos = path[path.size()-1]; curVector.x = dest.x-prevPos.x; diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp index 79913a7c7d..05ce1ea359 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp @@ -966,7 +966,7 @@ StateReturnType AIStateMachine::setTemporaryState( StateID newStateID, Int frame */ void AIStateMachine::addToGoalPath( const Coord3D *pathPoint) { - if (m_goalPath.size()==0) { + if (m_goalPath.empty()) { m_goalPath.push_back(*pathPoint); } else { Coord3D *finalPoint = &m_goalPath[ m_goalPath.size() - 1 ]; @@ -5793,7 +5793,7 @@ Object *AIAttackSquadState::chooseVictim(void) { // everyone picks the same unit VecObjectPtr objects = victimSquad->getLiveObjects(); - if (objects.size() > 0) + if (!objects.empty()) { return objects[0]; } diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/Squad.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/Squad.cpp index 6db457e90f..157899e690 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/Squad.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/Squad.cpp @@ -233,7 +233,7 @@ void Squad::xfer( Xfer *xfer ) { // the cached objects list should be empty - if( m_objectsCached.size() != 0 ) + if( !m_objectsCached.empty() ) { DEBUG_CRASH(( "Squad::xfer - m_objectsCached should be emtpy, but is not" )); diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/BridgeBehavior.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/BridgeBehavior.cpp index af4d7ea89f..1bdc37c657 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/BridgeBehavior.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/BridgeBehavior.cpp @@ -1451,7 +1451,7 @@ void BridgeBehavior::xfer( Xfer *xfer ) { // read all object IDs - DEBUG_ASSERTCRASH( m_scaffoldObjectIDList.size() == 0, + DEBUG_ASSERTCRASH( m_scaffoldObjectIDList.empty(), ("BridgeBehavior::xfer - scaffold object list should be empty") ); for( Int i = 0; i < scaffoldObjectCount; ++i ) { diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp index 93e792bb46..2398127315 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp @@ -938,7 +938,7 @@ class GenericObjectCreationNugget : public ObjectCreationNugget if (di) { di->setModelName(modelName, m_okToChangeModelColor ? obj->getIndicatorColor() : 0, m_shadowType); - if (m_animSets.size() > 0) + if (!m_animSets.empty()) { Int which = GameLogicRandomValue(0, m_animSets.size()-1); di->setAnimNames(m_animSets[which].m_animInitial, m_animSets[which].m_animFlying, m_animSets[which].m_animFinal, m_fxFinal); @@ -1217,7 +1217,7 @@ class GenericObjectCreationNugget : public ObjectCreationNugget { static const ThingTemplate* debrisTemplate = TheThingFactory->findTemplate("GenericDebris"); - if (m_names.size() <= 0) + if (m_names.empty()) return NULL; if (m_requiresLivePlayer && (!sourceObj || !sourceObj->getControllingPlayer()->isPlayerActive())) diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp index ce28b73cbe..b2c353701d 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp @@ -4653,7 +4653,7 @@ void PartitionManager::xfer( Xfer *xfer ) // have to remove this assert, because during load there is a setTeam call for each guy on a sub-team, and that results // in a queued unlook, so we actually have stuff in here at the start. I am fairly certain that setTeam should wait // until loadPostProcess, but I ain't gonna change it now. -// DEBUG_ASSERTCRASH(m_pendingUndoShroudReveals.size() == 0, ("At load, we appear to not be in a reset state.") ); +// DEBUG_ASSERTCRASH(m_pendingUndoShroudReveals.empty(), ("At load, we appear to not be in a reset state.") ); // I have to split this up though, since on Load I need to make new instances. for( Int infoIndex = 0; infoIndex < queueSize; infoIndex++ ) diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp index e515ff54a4..678d87cfeb 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp @@ -3254,7 +3254,7 @@ void AIUpdateInterface::privateFollowPath( const std::vector* path, Obj // clear current state machine getStateMachine()->clear(); - if (path->size()>0) { + if (!path->empty()) { const Coord3D goal = (*path)[path->size()-1]; getStateMachine()->setGoalPosition(&goal); } 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 51d2a7813e..a8c7c8876c 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeliverPayloadAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeliverPayloadAIUpdate.cpp @@ -681,7 +681,7 @@ StateReturnType DeliveringState::update() // Kick a dude out every so often return STATE_FAILURE; const ContainedItemsList* items = owner->getContain() ? owner->getContain()->getContainedItemsList() : NULL; - if( (!items || !items->size()) && ai->getVisibleItemsDelivered() == ai->getData()->m_visibleNumBones ) + if( (!items || items->empty()) && ai->getVisibleItemsDelivered() == ai->getData()->m_visibleNumBones ) { //We are out of payload to drop AND our visible payload is empty. It's possible for deliverers to //have one or the other or even both. diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp index 45aadbb0e9..7bae95eebb 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp @@ -1103,7 +1103,7 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate void WeaponTemplate::trimOldHistoricDamage() const { UnsignedInt expirationDate = TheGameLogic->getFrame() - TheGlobalData->m_historicDamageLimit; - while (m_historicDamage.size() > 0) + while (!m_historicDamage.empty()) { HistoricWeaponDamageInfo& h = m_historicDamage.front(); if (h.frame <= expirationDate) @@ -2471,7 +2471,7 @@ Bool Weapon::privateFireWeapon( m_numShotsForCurBarrel = m_template->getShotsPerBarrel(); } - if( m_scatterTargetsUnused.size() ) + if( !m_scatterTargetsUnused.empty() ) { // If I have a set scatter pattern, I need to offset the target by a random pick from that pattern if( victimObj ) diff --git a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp index 6ff9d7e76e..3430b6352a 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp @@ -8147,7 +8147,7 @@ void ScriptEngine::xfer( Xfer *xfer ) { // this list should be empty on loading - if( m_sequentialScripts.size() != 0 ) + if( !m_sequentialScripts.empty() ) { DEBUG_CRASH(( "ScriptEngine::xfer - m_sequentialScripts should be empty but is not" )); diff --git a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h index 3db0b660f3..226dc9c769 100644 --- a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h +++ b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h @@ -245,7 +245,7 @@ struct ModelConditionInfo void loadAnimations() const; void preloadAssets( TimeOfDay timeOfDay, Real scale ); ///< preload any assets for time of day - Int getConditionsYesCount() const { DEBUG_ASSERTCRASH(m_conditionsYesVec.size() > 0, ("empty m_conditionsYesVec.size(), see srj")); return m_conditionsYesVec.size(); } + Int getConditionsYesCount() const { DEBUG_ASSERTCRASH(!m_conditionsYesVec.empty(), ("empty m_conditionsYesVec.size(), see srj")); return m_conditionsYesVec.size(); } const ModelConditionFlags& getNthConditionsYes(Int i) const { return m_conditionsYesVec[i]; } #if defined(RTS_DEBUG) inline AsciiString getDescription() const { return m_description; } 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 9bab297741..aab8c0ebf9 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp @@ -647,7 +647,7 @@ void ModelConditionInfo::validateCachedBones(RenderObjClass* robj, Real scale) c // if we have any animations in this state, always choose the first, since the animations // vary on a per-client basis. HAnimClass* animToUse; - if (m_animations.size() > 0) + if (!m_animations.empty()) { animToUse = m_animations.front().getAnimHandle(); // return an AddRef'ed handle } @@ -1601,7 +1601,7 @@ void W3DModelDrawModuleData::parseConditionState(INI* ini, void *instance, void throw INI_INVALID_DATA; } - DEBUG_ASSERTCRASH(info.m_conditionsYesVec.size() == 0, ("*** ASSET ERROR: nonempty m_conditionsYesVec.size(), see srj")); + DEBUG_ASSERTCRASH(info.m_conditionsYesVec.empty(), ("*** ASSET ERROR: nonempty m_conditionsYesVec.size(), see srj")); info.m_conditionsYesVec.clear(); info.m_conditionsYesVec.push_back(conditionsYes); } @@ -3750,8 +3750,8 @@ void W3DModelDraw::setAnimationLoopDuration(UnsignedInt numFrames) */ void W3DModelDraw::setAnimationCompletionTime(UnsignedInt numFrames) { - if (m_curState != NULL && m_curState->m_transitionSig != NO_TRANSITION && m_curState->m_animations.size() > 0 && - m_nextState != NULL && m_nextState->m_transitionSig == NO_TRANSITION && m_nextState->m_animations.size() > 0) + if (m_curState != NULL && m_curState->m_transitionSig != NO_TRANSITION && !m_curState->m_animations.empty() && + m_nextState != NULL && m_nextState->m_transitionSig == NO_TRANSITION && !m_nextState->m_animations.empty()) { // we have a transition; split up the time suitably. // note that this is just a guess, and assumes that the states diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DTerrainLogic.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DTerrainLogic.cpp index cb4ed6f216..6ece16cdf7 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DTerrainLogic.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DTerrainLogic.cpp @@ -183,7 +183,7 @@ void W3DTerrainLogic::getExtent( Region3D *extent ) const // Note - m_boundaries are stored in height map grids wide, so we have to // multiply by the grid width. - if (m_boundaries.size() > 0) { + if (!m_boundaries.empty()) { extent->hi.x = m_boundaries[m_activeBoundary].x*MAP_XY_FACTOR; extent->hi.y = m_boundaries[m_activeBoundary].y*MAP_XY_FACTOR; } else { diff --git a/Generals/Code/Tools/ParticleEditor/ParticleEditorDialog.cpp b/Generals/Code/Tools/ParticleEditor/ParticleEditorDialog.cpp index 5ce153562c..670b92543b 100644 --- a/Generals/Code/Tools/ParticleEditor/ParticleEditorDialog.cpp +++ b/Generals/Code/Tools/ParticleEditor/ParticleEditorDialog.cpp @@ -336,7 +336,7 @@ void DebugWindowDialog::getSelectedParticleAsciiStringParm( IN int parmNum, OUT return; } - if (m_particleParmValues[parmNum].length()) { + if (!m_particleParmValues[parmNum].empty()) { strcpy(bufferToCopyInto, m_particleParmValues[parmNum].c_str()); } else { bufferToCopyInto[0] = 0; diff --git a/Generals/Code/Tools/WorldBuilder/src/LayersList.cpp b/Generals/Code/Tools/WorldBuilder/src/LayersList.cpp index a055af1b36..5a44b9c464 100644 --- a/Generals/Code/Tools/WorldBuilder/src/LayersList.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/LayersList.cpp @@ -826,7 +826,7 @@ void LayersList::OnMergeViewSelection(UINT commandID) mapObject = mapObject->getNext(); } - while (allSelectedObjects.size() > 0) { + while (!allSelectedObjects.empty()) { changeMapObjectLayer(allSelectedObjects.top(), layerIt->layerName); allSelectedObjects.pop(); } diff --git a/Generals/Code/Tools/WorldBuilder/src/MeshMoldOptions.cpp b/Generals/Code/Tools/WorldBuilder/src/MeshMoldOptions.cpp index a8018940ae..fc0ec4df85 100644 --- a/Generals/Code/Tools/WorldBuilder/src/MeshMoldOptions.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/MeshMoldOptions.cpp @@ -86,7 +86,7 @@ BOOL MeshMoldOptions::OnInitDialog() FilenameList filenameList; TheFileSystem->getFileListInDirectory(".\\data\\Editor\\Molds\\", "*.w3d", filenameList, FALSE); - if (filenameList.size() > 0) { + if (!filenameList.empty()) { HTREEITEM child = NULL; FilenameList::iterator it = filenameList.begin(); do { diff --git a/Generals/Code/Tools/WorldBuilder/src/ObjectOptions.cpp b/Generals/Code/Tools/WorldBuilder/src/ObjectOptions.cpp index 4490424518..941cee4d11 100644 --- a/Generals/Code/Tools/WorldBuilder/src/ObjectOptions.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/ObjectOptions.cpp @@ -283,7 +283,7 @@ BOOL ObjectOptions::OnInitDialog() FilenameList filenameList; TheFileSystem->getFileListInDirectory(TEST_W3D_DIR_PATH, "*.w3d", filenameList, FALSE); - if (filenameList.size() > 0) { + if (!filenameList.empty()) { FilenameList::iterator it = filenameList.begin(); do { AsciiString filename = *it; diff --git a/Generals/Code/Tools/WorldBuilder/src/RoadOptions.cpp b/Generals/Code/Tools/WorldBuilder/src/RoadOptions.cpp index 744d8d857a..68d0820454 100644 --- a/Generals/Code/Tools/WorldBuilder/src/RoadOptions.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/RoadOptions.cpp @@ -247,7 +247,7 @@ BOOL RoadOptions::OnInitDialog() FilenameList filenameList; TheFileSystem->getFileListInDirectory(ROAD_DIRECTORY, "*.tga", filenameList, FALSE); - if (filenameList.size() > 0) { + if (!filenameList.empty()) { FilenameList::iterator it = filenameList.begin(); do { AsciiString filename = *it; diff --git a/Generals/Code/Tools/WorldBuilder/src/SelectMacrotexture.cpp b/Generals/Code/Tools/WorldBuilder/src/SelectMacrotexture.cpp index fe8584c298..d2de095c9e 100644 --- a/Generals/Code/Tools/WorldBuilder/src/SelectMacrotexture.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/SelectMacrotexture.cpp @@ -78,7 +78,7 @@ BOOL SelectMacrotexture::OnInitDialog() FilenameList filenameList; TheFileSystem->getFileListInDirectory("..\\TestArt\\", "*.tga", filenameList, FALSE); - if (filenameList.size() > 0) { + if (!filenameList.empty()) { TVINSERTSTRUCT ins; HTREEITEM child = NULL; FilenameList::iterator it = filenameList.begin(); diff --git a/Generals/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp b/Generals/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp index 9a8ed55116..e667ac3f90 100644 --- a/Generals/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp @@ -427,7 +427,7 @@ void WorldHeightMapEdit::loadDirectoryOfImages(const char *pFilePath) FilenameList filenameList; TheFileSystem->getFileListInDirectory(AsciiString(dirBuf), "*.*", filenameList, TRUE); - if (filenameList.size() == 0) { + if (filenameList.empty()) { return; } FilenameList::iterator it = filenameList.begin(); @@ -3378,7 +3378,7 @@ void WorldHeightMapEdit::changeBoundary(Int ndx, ICoord2D *border) void WorldHeightMapEdit::removeLastBoundary(void) { - if (m_boundaries.size() == 0) { + if (m_boundaries.empty()) { DEBUG_CRASH(("Invalid border remove request. jkmcd")); return; } diff --git a/Generals/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp b/Generals/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp index 833e10e66c..da3eb6fb1c 100644 --- a/Generals/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp @@ -194,7 +194,7 @@ class CachedMFCFileOutputStream : public OutputStream return(numBytes); }; virtual void flush(void) { - while (m_cachedChunks.size() != 0)//!m_cachedChunks.empty()) + while (!m_cachedChunks.empty())//!m_cachedChunks.empty()) { CachedChunk c = m_cachedChunks.front(); m_cachedChunks.pop_front(); @@ -232,7 +232,7 @@ class CompressedCachedMFCFileOutputStream : public OutputStream return; UnsignedByte *srcBuffer = NEW UnsignedByte[m_totalBytes]; UnsignedByte *insertPos = srcBuffer; - while (m_cachedChunks.size() != 0) + while (!m_cachedChunks.empty()) { CachedChunk c = m_cachedChunks.front(); m_cachedChunks.pop_front(); @@ -1474,7 +1474,7 @@ Bool CWorldBuilderDoc::getAllIndexesInRect(const Coord3D* bl, const Coord3D* br, FindIndexNearest(this, ¢er, &ndx, PREFER_BOTTOM); AddUniqueAndNeighbors(this, bl, br, tl, tr, ndx, allIndices); - return (allIndices->size() > 0); + return (!allIndices->empty()); } @@ -2245,7 +2245,7 @@ void CWorldBuilderDoc::OnDumpDocToText(void) fprintf(theLogFile, "Total Map Objects (with ThingTemplates): %d\n", totalObjectCount); - while (mapOfTemplates.size() > 0) { + while (!mapOfTemplates.empty()) { std::map::iterator storedIt = mapOfTemplates.begin(); for (it = mapOfTemplates.begin(); it != mapOfTemplates.end(); ++it) { diff --git a/Generals/Code/Tools/WorldBuilder/src/mapobjectprops.cpp b/Generals/Code/Tools/WorldBuilder/src/mapobjectprops.cpp index fe8c46bd54..59d8b88363 100644 --- a/Generals/Code/Tools/WorldBuilder/src/mapobjectprops.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/mapobjectprops.cpp @@ -749,7 +749,7 @@ void MapObjectProps::_DictToPrebuiltUpgrades(void) if (!gmbmd) { continue; } - if (gmbmd->m_upgradeMuxData.m_activationUpgradeNames.size() > 0) { + if (!gmbmd->m_upgradeMuxData.m_activationUpgradeNames.empty()) { cstr = gmbmd->m_upgradeMuxData.m_activationUpgradeNames[0].str(); if (pBox->FindString(-1, cstr) == LB_ERR) { pBox->AddString(cstr); diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/AnimateWindowManager.h b/GeneralsMD/Code/GameEngine/Include/GameClient/AnimateWindowManager.h index bd74f4c3d8..a43b0c8222 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/AnimateWindowManager.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/AnimateWindowManager.h @@ -229,7 +229,7 @@ namespace wnd inline Bool AnimateWindowManager::isFinished( void ) { return !m_needsUpdate; }; inline Bool AnimateWindowManager::isReversed( void ) { return m_reverse; }; - inline Bool AnimateWindowManager::isEmpty( void ){return (m_winList.size() == 0 && m_winMustFinishList.size() == 0); } + inline Bool AnimateWindowManager::isEmpty( void ){return (m_winList.empty() && m_winMustFinishList.empty()); } //----------------------------------------------------------------------------- // EXTERNALS ////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp index 9088ec4bd1..ec98aa370d 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp @@ -352,7 +352,7 @@ Player::Player( Int playerIndex ) void Player::init(const PlayerTemplate* pt) { - DEBUG_ASSERTCRASH(m_playerTeamPrototypes.size() == 0, ("Player::m_playerTeamPrototypes is not empty at game start!")); + DEBUG_ASSERTCRASH(m_playerTeamPrototypes.empty(), ("Player::m_playerTeamPrototypes is not empty at game start!")); m_skillPointsModifier = 1.0f; m_attackedFrame = 0; @@ -4376,7 +4376,7 @@ void Player::xfer( Xfer *xfer ) { // sanity, list must be empty right now - if( m_kindOfPercentProductionChangeList.size() != 0 ) + if( !m_kindOfPercentProductionChangeList.empty() ) { DEBUG_CRASH(( "Player::xfer - m_kindOfPercentProductionChangeList should be empty but is not" )); @@ -4429,7 +4429,7 @@ void Player::xfer( Xfer *xfer ) } else { - if( m_specialPowerReadyTimerList.size() != 0 ) // sanity, list must be empty right now + if( !m_specialPowerReadyTimerList.empty() ) // sanity, list must be empty right now { DEBUG_CRASH(( "Player::xfer - m_specialPowerReadyTimerList should be empty but is not" )); throw SC_INVALID_DATA; diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp index 61770bd035..0e5bc0904e 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp @@ -131,7 +131,7 @@ Int ProductionPrerequisite::getAllPossibleBuildFacilityTemplates(const ThingTemp const ThingTemplate *ProductionPrerequisite::getExistingBuildFacilityTemplate( const Player *player ) const { DEBUG_ASSERTCRASH(player, ("player may not be null")); - if (m_prereqUnits.size()) + if (!m_prereqUnits.empty()) { Int ownCount[MAX_PREREQ]; Int cnt = calcNumPrereqUnitsOwned(player, ownCount); diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp index 55bc3f6671..72ea6a2822 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp @@ -415,7 +415,7 @@ void TunnelTracker::loadPostProcess( void ) { // sanity, the contain list should be empty until we post process the id list - if( m_containList.size() != 0 ) + if( !m_containList.empty() ) { DEBUG_CRASH(( "TunnelTracker::loadPostProcess - m_containList should be empty but is not" )); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Credits.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Credits.cpp index a26d9eee66..14c845436a 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Credits.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Credits.cpp @@ -221,7 +221,7 @@ void CreditsManager::update( void ) if(!((m_scrollDown && (yTest >= start)) || (!m_scrollDown && (yTest <= start)))) return; - if(m_displayedCreditLineList.size() == 0 && m_creditLineListIt == m_creditLineList.end()) + if(m_displayedCreditLineList.empty() && m_creditLineListIt == m_creditLineList.end()) m_isFinished = TRUE; if(m_creditLineListIt == m_creditLineList.end()) diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Eva.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Eva.cpp index 25b02f109a..31db3b8761 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Eva.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Eva.cpp @@ -513,7 +513,7 @@ void Eva::processPlayingMessages(UnsignedInt currentFrame) for (Int i = 0; i < numSides; ++i) { if (side.compareNoCase(storedIt->m_evaInfo->m_evaSideSounds[i].m_side) == 0) { // Its this one. - if (storedIt->m_evaInfo->m_evaSideSounds[i].m_soundNames.size() > 0) { + if (!storedIt->m_evaInfo->m_evaSideSounds[i].m_soundNames.empty()) { Int soundToPlay = GameClientRandomValue(0, storedIt->m_evaInfo->m_evaSideSounds[i].m_soundNames.size() - 1); m_evaSpeech.setEventName(storedIt->m_evaInfo->m_evaSideSounds[i].m_soundNames[soundToPlay]); } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp index dd3ff335ae..32b2752719 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp @@ -1022,7 +1022,7 @@ void ControlBarSchemeManager::init( void ) // if (FindFirstFile(userDataPath.str(), &findData) !=INVALID_HANDLE_VALUE) // ini.loadFileDirectory(userDataPath, INI_LOAD_OVERWRITE, NULL ); // } - if( m_schemeList.size() <= 0 ) + if( m_schemeList.empty() ) { DEBUG_ASSERTCRASH(FALSE,("There's no ControlBarScheme in the ControlBarSchemeList:m_schemeList that was just read from the INI file")); return; 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 da15a065ab..6ad99be4c4 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp @@ -580,7 +580,7 @@ void PopulateLobbyPlayerListbox(void) } // restore selection - if (indicesToSelect.size()) + if (!indicesToSelect.empty()) { std::set::const_iterator indexIt = indicesToSelect.begin(); const size_t count = indicesToSelect.size(); @@ -1166,7 +1166,7 @@ void WOLLobbyMenuUpdate( WindowLayout * layout, void *userData) //if (ParseAsciiStringToGameInfo(&room, resp.stagingRoomMapName.c_str())) //if (ParseAsciiStringToGameInfo(&room, resp.stagingServerGameOptions.c_str())) Bool serverOk = TRUE; - if (!resp.stagingRoomMapName.length()) + if (resp.stagingRoomMapName.empty()) { serverOk = FALSE; } @@ -1238,7 +1238,7 @@ void WOLLobbyMenuUpdate( WindowLayout * layout, void *userData) slot->setState(SLOT_BRUTAL_AI); ++numPlayers; } - else if (resp.stagingRoomPlayerNames[i].length()) + else if (!resp.stagingRoomPlayerNames[i].empty()) { UnicodeString nameUStr; nameUStr.translate(resp.stagingRoomPlayerNames[i].c_str()); 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 d793702957..5557eade74 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp @@ -765,9 +765,9 @@ void WOLQuickMatchMenuInit( WindowLayout *layout, void *userData ) comboBoxSide = TheWindowManager->winGetWindowFromId( parentWOLQuickMatch, comboBoxSideID ); comboBoxColor = TheWindowManager->winGetWindowFromId( parentWOLQuickMatch, comboBoxColorID ); - if (TheLadderList->getStandardLadders()->size() == 0 - && TheLadderList->getSpecialLadders()->size() == 0 - && TheLadderList->getLocalLadders()->size() == 0) + if (TheLadderList->getStandardLadders()->empty() + && TheLadderList->getSpecialLadders()->empty() + && TheLadderList->getLocalLadders()->empty()) { // no ladders, so just disable them comboBoxDisabledLadder = comboBoxLadder; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp index a0d01be715..197fdd05ec 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp @@ -3976,7 +3976,7 @@ Bool GameWindowManager::initTestGUI( void ) void GameWindowManager::winNextTab( GameWindow *window ) { - if(m_tabList.size() == 0|| m_modalHead) + if(m_tabList.empty()|| m_modalHead) return; GameWindowList::iterator it = m_tabList.begin(); @@ -4000,7 +4000,7 @@ void GameWindowManager::winNextTab( GameWindow *window ) void GameWindowManager::winPrevTab( GameWindow *window ) { - if(m_tabList.size() == 0 || m_modalHead) + if(m_tabList.empty() || m_modalHead) return; GameWindowList::reverse_iterator it = m_tabList.rbegin(); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp index 8bbebf42c0..de61454f1d 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp @@ -647,7 +647,7 @@ Bool InGameUI::removeSuperweapon(Int playerIndex, const AsciiString& powerName, SuperweaponInfo *info = *listIt; swList.erase(listIt); deleteInstance(info); - if (swList.size() == 0) + if (swList.empty()) { m_superweapons[playerIndex].erase(mapIt); } @@ -4695,7 +4695,7 @@ Bool InGameUI::canSelectedObjectsDoSpecialPower( const CommandButton *command, c if (ignoreSelDraw) tmpList.push_back(ignoreSelDraw); - const DrawableList* selected = (tmpList.size() > 0) ? &tmpList : TheInGameUI->getAllSelectedDrawables(); + const DrawableList* selected = (!tmpList.empty()) ? &tmpList : TheInGameUI->getAllSelectedDrawables(); // set up counters for rule checking Int count = 0; @@ -4958,7 +4958,7 @@ Int InGameUI::selectMatchingAcrossRegion( IRegion2D *region ) } } - if (drawableList.size() == 0) + if (drawableList.empty()) return -1; // nothing useful selected to begin with - don't bother iterating std::set::iterator iter; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp index fa9ad40747..5cf8868c99 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp @@ -327,7 +327,7 @@ void AI::reset( void ) } #if RETAIL_COMPATIBLE_AIGROUP - while (m_groupList.size()) + while (!m_groupList.empty()) { AIGroup *groupToRemove = m_groupList.front(); if (groupToRemove) diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp index cb9569d3a2..e09a4f24a7 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp @@ -1046,7 +1046,7 @@ Bool AIGroup::friend_moveInfantryToPos( const Coord3D *pos, CommandSourceType cm dest.y -= factor*offset*endVector.y; dest.z = TheTerrainLogic->getLayerHeight( dest.x, dest.y, layer ); - while (path.size()>0) { + while (!path.empty()) { Coord2D curVector; prevPos = path[path.size()-1]; curVector.x = dest.x-prevPos.x; @@ -1529,7 +1529,7 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmd dest.y -= factor*offset*endVector.y; dest.z = TheTerrainLogic->getLayerHeight( dest.x, dest.y, layer ); - while (path.size()>0) { + while (!path.empty()) { Coord2D curVector; prevPos = path[path.size()-1]; curVector.x = dest.x-prevPos.x; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp index 6988747599..63b3474662 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp @@ -971,7 +971,7 @@ StateReturnType AIStateMachine::setTemporaryState( StateID newStateID, Int frame */ void AIStateMachine::addToGoalPath( const Coord3D *pathPoint) { - if (m_goalPath.size()==0) { + if (m_goalPath.empty()) { m_goalPath.push_back(*pathPoint); } else { Coord3D *finalPoint = &m_goalPath[ m_goalPath.size() - 1 ]; @@ -6005,7 +6005,7 @@ Object *AIAttackSquadState::chooseVictim(void) { // everyone picks the same unit VecObjectPtr objects = victimSquad->getLiveObjects(); - if (objects.size() > 0) + if (!objects.empty()) { return objects[0]; } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/Squad.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/Squad.cpp index 293a6dbce8..291e622e71 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/Squad.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/Squad.cpp @@ -233,7 +233,7 @@ void Squad::xfer( Xfer *xfer ) { // the cached objects list should be empty - if( m_objectsCached.size() != 0 ) + if( !m_objectsCached.empty() ) { DEBUG_CRASH(( "Squad::xfer - m_objectsCached should be emtpy, but is not" )); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/BridgeBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/BridgeBehavior.cpp index df75da3aa3..464e4f11b5 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/BridgeBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/BridgeBehavior.cpp @@ -1451,7 +1451,7 @@ void BridgeBehavior::xfer( Xfer *xfer ) { // read all object IDs - DEBUG_ASSERTCRASH( m_scaffoldObjectIDList.size() == 0, + DEBUG_ASSERTCRASH( m_scaffoldObjectIDList.empty(), ("BridgeBehavior::xfer - scaffold object list should be empty") ); for( Int i = 0; i < scaffoldObjectCount; ++i ) { diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp index 78847445fc..215763f9c5 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp @@ -953,7 +953,7 @@ class GenericObjectCreationNugget : public ObjectCreationNugget if (di) { di->setModelName(modelName, m_okToChangeModelColor ? obj->getIndicatorColor() : 0, m_shadowType); - if (m_animSets.size() > 0) + if (!m_animSets.empty()) { Int which = GameLogicRandomValue(0, m_animSets.size()-1); di->setAnimNames(m_animSets[which].m_animInitial, m_animSets[which].m_animFlying, m_animSets[which].m_animFinal, m_fxFinal); @@ -1304,7 +1304,7 @@ class GenericObjectCreationNugget : public ObjectCreationNugget { static const ThingTemplate* debrisTemplate = TheThingFactory->findTemplate("GenericDebris"); - if (m_names.size() <= 0) + if (m_names.empty()) return NULL; if (m_requiresLivePlayer && (!sourceObj || !sourceObj->getControllingPlayer() || !sourceObj->getControllingPlayer()->isPlayerActive())) diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp index 4eb90530ce..e92ad16f32 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp @@ -4689,7 +4689,7 @@ void PartitionManager::xfer( Xfer *xfer ) // have to remove this assert, because during load there is a setTeam call for each guy on a sub-team, and that results // in a queued unlook, so we actually have stuff in here at the start. I am fairly certain that setTeam should wait // until loadPostProcess, but I ain't gonna change it now. -// DEBUG_ASSERTCRASH(m_pendingUndoShroudReveals.size() == 0, ("At load, we appear to not be in a reset state.") ); +// DEBUG_ASSERTCRASH(m_pendingUndoShroudReveals.empty(), ("At load, we appear to not be in a reset state.") ); // I have to split this up though, since on Load I need to make new instances. for( Int infoIndex = 0; infoIndex < queueSize; infoIndex++ ) diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp index 797879498b..bfc97640c3 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp @@ -3391,7 +3391,7 @@ void AIUpdateInterface::privateFollowPath( const std::vector* path, Obj // clear current state machine getStateMachine()->clear(); - if (path->size()>0) { + if (!path->empty()) { const Coord3D goal = (*path)[path->size()-1]; getStateMachine()->setGoalPosition(&goal); } 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 63cf5c78cb..f69f7004ad 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeliverPayloadAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeliverPayloadAIUpdate.cpp @@ -697,7 +697,7 @@ StateReturnType DeliveringState::update() // Kick a dude out every so often return STATE_FAILURE; const ContainedItemsList* items = owner->getContain() ? owner->getContain()->getContainedItemsList() : NULL; - if( (!items || !items->size()) && ai->getVisibleItemsDelivered() == ai->getData()->m_visibleNumBones ) + if( (!items || items->empty()) && ai->getVisibleItemsDelivered() == ai->getData()->m_visibleNumBones ) { //We are out of payload to drop AND our visible payload is empty. It's possible for deliverers to //have one or the other or even both. diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp index 5d700cbb1f..69bcca6606 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp @@ -1180,7 +1180,7 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate void WeaponTemplate::trimOldHistoricDamage() const { UnsignedInt expirationDate = TheGameLogic->getFrame() - TheGlobalData->m_historicDamageLimit; - while (m_historicDamage.size() > 0) + while (!m_historicDamage.empty()) { HistoricWeaponDamageInfo& h = m_historicDamage.front(); if (h.frame <= expirationDate) @@ -2682,7 +2682,7 @@ Bool Weapon::privateFireWeapon( m_numShotsForCurBarrel = m_template->getShotsPerBarrel(); } - if( m_scatterTargetsUnused.size() ) + if( !m_scatterTargetsUnused.empty() ) { // If I have a set scatter pattern, I need to offset the target by a random pick from that pattern if( victimObj ) diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp index ee2d05bf22..865d1bd2d8 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp @@ -8870,7 +8870,7 @@ void ScriptEngine::xfer( Xfer *xfer ) { // this list should be empty on loading - if( m_sequentialScripts.size() != 0 ) + if( !m_sequentialScripts.empty() ) { DEBUG_CRASH(( "ScriptEngine::xfer - m_sequentialScripts should be empty but is not" )); diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h index 95c6db84f1..1d33cb947e 100644 --- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h +++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h @@ -246,7 +246,7 @@ struct ModelConditionInfo void loadAnimations() const; void preloadAssets( TimeOfDay timeOfDay, Real scale ); ///< preload any assets for time of day - Int getConditionsYesCount() const { DEBUG_ASSERTCRASH(m_conditionsYesVec.size() > 0, ("empty m_conditionsYesVec.size(), see srj")); return m_conditionsYesVec.size(); } + Int getConditionsYesCount() const { DEBUG_ASSERTCRASH(!m_conditionsYesVec.empty(), ("empty m_conditionsYesVec.size(), see srj")); return m_conditionsYesVec.size(); } const ModelConditionFlags& getNthConditionsYes(Int i) const { return m_conditionsYesVec[i]; } #if defined(RTS_DEBUG) inline AsciiString getDescription() const { return m_description; } 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 d7ca602a5a..fccd5c32e0 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp @@ -647,7 +647,7 @@ void ModelConditionInfo::validateCachedBones(RenderObjClass* robj, Real scale) c // if we have any animations in this state, always choose the first, since the animations // vary on a per-client basis. HAnimClass* animToUse; - if (m_animations.size() > 0) + if (!m_animations.empty()) { animToUse = m_animations.front().getAnimHandle(); // return an AddRef'ed handle } @@ -1625,7 +1625,7 @@ void W3DModelDrawModuleData::parseConditionState(INI* ini, void *instance, void throw INI_INVALID_DATA; } - DEBUG_ASSERTCRASH(info.m_conditionsYesVec.size() == 0, ("*** ASSET ERROR: nonempty m_conditionsYesVec.size(), see srj")); + DEBUG_ASSERTCRASH(info.m_conditionsYesVec.empty(), ("*** ASSET ERROR: nonempty m_conditionsYesVec.size(), see srj")); info.m_conditionsYesVec.clear(); info.m_conditionsYesVec.push_back(conditionsYes); } @@ -3805,8 +3805,8 @@ void W3DModelDraw::setAnimationLoopDuration(UnsignedInt numFrames) */ void W3DModelDraw::setAnimationCompletionTime(UnsignedInt numFrames) { - if (m_curState != NULL && m_curState->m_transitionSig != NO_TRANSITION && m_curState->m_animations.size() > 0 && - m_nextState != NULL && m_nextState->m_transitionSig == NO_TRANSITION && m_nextState->m_animations.size() > 0) + if (m_curState != NULL && m_curState->m_transitionSig != NO_TRANSITION && !m_curState->m_animations.empty() && + m_nextState != NULL && m_nextState->m_transitionSig == NO_TRANSITION && !m_nextState->m_animations.empty()) { // we have a transition; split up the time suitably. // note that this is just a guess, and assumes that the states diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DTerrainLogic.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DTerrainLogic.cpp index e65d5f7c5a..0b7a8ef24a 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DTerrainLogic.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DTerrainLogic.cpp @@ -183,7 +183,7 @@ void W3DTerrainLogic::getExtent( Region3D *extent ) const // Note - m_boundaries are stored in height map grids wide, so we have to // multiply by the grid width. - if (m_boundaries.size() > 0) { + if (!m_boundaries.empty()) { extent->hi.x = m_boundaries[m_activeBoundary].x*MAP_XY_FACTOR; extent->hi.y = m_boundaries[m_activeBoundary].y*MAP_XY_FACTOR; } else { diff --git a/GeneralsMD/Code/Tools/ParticleEditor/ParticleEditorDialog.cpp b/GeneralsMD/Code/Tools/ParticleEditor/ParticleEditorDialog.cpp index f059533d6b..b41df2cc2f 100644 --- a/GeneralsMD/Code/Tools/ParticleEditor/ParticleEditorDialog.cpp +++ b/GeneralsMD/Code/Tools/ParticleEditor/ParticleEditorDialog.cpp @@ -336,7 +336,7 @@ void DebugWindowDialog::getSelectedParticleAsciiStringParm( IN int parmNum, OUT return; } - if (m_particleParmValues[parmNum].length()) { + if (!m_particleParmValues[parmNum].empty()) { strcpy(bufferToCopyInto, m_particleParmValues[parmNum].c_str()); } else { bufferToCopyInto[0] = 0; diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/LayersList.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/LayersList.cpp index bc30af05a1..edd9ebd3e8 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/LayersList.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/LayersList.cpp @@ -1160,7 +1160,7 @@ void LayersList::OnMergeViewSelection(UINT commandID) mapObject = mapObject->getNext(); } - while (allSelectedObjects.size() > 0) { + while (!allSelectedObjects.empty()) { changeMapObjectLayer(allSelectedObjects.top(), layerIt->layerName); allSelectedObjects.pop(); } @@ -1177,7 +1177,7 @@ void LayersList::OnMergeViewSelection(UINT commandID) polygonTrigger = polygonTrigger->getNext(); } - while (allSelectedTriggers.size() > 0) { + while (!allSelectedTriggers.empty()) { changePolygonTriggerLayer(allSelectedTriggers.top(), layerIt->layerName); allSelectedTriggers.pop(); } diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/MeshMoldOptions.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/MeshMoldOptions.cpp index a21de4cd64..7dd0407756 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/MeshMoldOptions.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/MeshMoldOptions.cpp @@ -86,7 +86,7 @@ BOOL MeshMoldOptions::OnInitDialog() FilenameList filenameList; TheFileSystem->getFileListInDirectory(".\\data\\Editor\\Molds\\", "*.w3d", filenameList, FALSE); - if (filenameList.size() > 0) { + if (!filenameList.empty()) { HTREEITEM child = NULL; FilenameList::iterator it = filenameList.begin(); do { diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/ObjectOptions.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/ObjectOptions.cpp index cbb6f666df..dc1dc5b7f5 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/ObjectOptions.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/ObjectOptions.cpp @@ -283,7 +283,7 @@ BOOL ObjectOptions::OnInitDialog() FilenameList filenameList; TheFileSystem->getFileListInDirectory(TEST_W3D_DIR_PATH, "*.w3d", filenameList, FALSE); - if (filenameList.size() > 0) { + if (!filenameList.empty()) { FilenameList::iterator it = filenameList.begin(); do { AsciiString filename = *it; diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/RoadOptions.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/RoadOptions.cpp index d1c31678f0..769a02996c 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/RoadOptions.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/RoadOptions.cpp @@ -247,7 +247,7 @@ BOOL RoadOptions::OnInitDialog() FilenameList filenameList; TheFileSystem->getFileListInDirectory(ROAD_DIRECTORY, "*.tga", filenameList, FALSE); - if (filenameList.size() > 0) { + if (!filenameList.empty()) { FilenameList::iterator it = filenameList.begin(); do { AsciiString filename = *it; diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/SelectMacrotexture.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/SelectMacrotexture.cpp index 47eef54dcb..b5a2d134a2 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/SelectMacrotexture.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/SelectMacrotexture.cpp @@ -78,7 +78,7 @@ BOOL SelectMacrotexture::OnInitDialog() FilenameList filenameList; TheFileSystem->getFileListInDirectory("..\\TestArt\\", "*.tga", filenameList, FALSE); - if (filenameList.size() > 0) { + if (!filenameList.empty()) { TVINSERTSTRUCT ins; HTREEITEM child = NULL; FilenameList::iterator it = filenameList.begin(); diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp index 42564af5e6..186fbd80e7 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp @@ -428,7 +428,7 @@ void WorldHeightMapEdit::loadDirectoryOfImages(const char *pFilePath) FilenameList filenameList; TheFileSystem->getFileListInDirectory(AsciiString(dirBuf), "*.*", filenameList, TRUE); - if (filenameList.size() == 0) { + if (filenameList.empty()) { return; } FilenameList::iterator it = filenameList.begin(); @@ -3350,7 +3350,7 @@ void WorldHeightMapEdit::changeBoundary(Int ndx, ICoord2D *border) void WorldHeightMapEdit::removeLastBoundary(void) { - if (m_boundaries.size() == 0) { + if (m_boundaries.empty()) { DEBUG_CRASH(("Invalid border remove request. jkmcd")); return; } diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp index a2c5d7836c..dae135ea3e 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp @@ -196,7 +196,7 @@ class CachedMFCFileOutputStream : public OutputStream return(numBytes); }; virtual void flush(void) { - while (m_cachedChunks.size() != 0)//!m_cachedChunks.empty()) + while (!m_cachedChunks.empty())//!m_cachedChunks.empty()) { CachedChunk c = m_cachedChunks.front(); m_cachedChunks.pop_front(); @@ -234,7 +234,7 @@ class CompressedCachedMFCFileOutputStream : public OutputStream return; UnsignedByte *srcBuffer = NEW UnsignedByte[m_totalBytes]; UnsignedByte *insertPos = srcBuffer; - while (m_cachedChunks.size() != 0) + while (!m_cachedChunks.empty()) { CachedChunk c = m_cachedChunks.front(); m_cachedChunks.pop_front(); @@ -1531,7 +1531,7 @@ Bool CWorldBuilderDoc::getAllIndexesInRect(const Coord3D* bl, const Coord3D* br, FindIndexNearest(this, ¢er, &ndx, PREFER_BOTTOM); AddUniqueAndNeighbors(this, bl, br, tl, tr, ndx, allIndices); - return (allIndices->size() > 0); + return (!allIndices->empty()); } @@ -2302,7 +2302,7 @@ void CWorldBuilderDoc::OnDumpDocToText(void) fprintf(theLogFile, "Total Map Objects (with ThingTemplates): %d\n", totalObjectCount); - while (mapOfTemplates.size() > 0) { + while (!mapOfTemplates.empty()) { std::map::iterator storedIt = mapOfTemplates.begin(); for (it = mapOfTemplates.begin(); it != mapOfTemplates.end(); ++it) { diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/mapobjectprops.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/mapobjectprops.cpp index 9917fa1ec4..2b0bab8720 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/mapobjectprops.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/mapobjectprops.cpp @@ -802,7 +802,7 @@ void MapObjectProps::_DictToPrebuiltUpgrades(void) if (!gmbmd) { continue; } - if (gmbmd->m_upgradeMuxData.m_activationUpgradeNames.size() > 0) { + if (!gmbmd->m_upgradeMuxData.m_activationUpgradeNames.empty()) { cstr = gmbmd->m_upgradeMuxData.m_activationUpgradeNames[0].str(); if (pBox->FindString(-1, cstr) == LB_ERR) { pBox->AddString(cstr); From fa9cb0cc2984c17c0bd75d3616d2dfd239eea99c Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Sat, 13 Dec 2025 23:12:18 +0100 Subject: [PATCH 32/70] unify(texture): Merge W3DWater and WW3D2 texture code (#1989) --- .../GameClient/Drawable/Draw/W3DLaserDraw.cpp | 3 + .../GameClient/Shadow/W3DProjectedShadow.cpp | 2 +- .../W3DDevice/GameClient/W3DAssetManager.cpp | 2 +- .../W3DDevice/GameClient/W3DDisplay.cpp | 1 - .../W3DDevice/GameClient/Water/W3DWater.cpp | 86 +- .../GameClient/Water/W3DWaterTracks.cpp | 30 + .../Source/WWVegas/WW3D2/assetmgr.cpp | 64 +- .../Libraries/Source/WWVegas/WW3D2/assetmgr.h | 1 - .../Libraries/Source/WWVegas/WW3D2/bmp2d.cpp | 26 +- .../Source/WWVegas/WW3D2/dx8caps.cpp | 2 + .../Source/WWVegas/WW3D2/dx8texman.h | 44 +- .../Source/WWVegas/WW3D2/dx8wrapper.cpp | 652 +++- .../Source/WWVegas/WW3D2/dx8wrapper.h | 62 +- .../Source/WWVegas/WW3D2/texproject.cpp | 58 +- .../Source/WWVegas/WW3D2/texproject.h | 21 +- .../Source/WWVegas/WW3D2/texture.cpp | 2112 ++++++++--- .../Libraries/Source/WWVegas/WW3D2/texture.h | 542 ++- .../Source/WWVegas/WW3D2/texturefilter.cpp | 149 +- .../Source/WWVegas/WW3D2/texturefilter.h | 4 +- .../Source/WWVegas/WW3D2/textureloader.cpp | 3142 ++++++++++++----- .../Source/WWVegas/WW3D2/textureloader.h | 339 +- .../Source/WWVegas/WW3D2/texturethumbnail.cpp | 435 ++- .../Source/WWVegas/WW3D2/texturethumbnail.h | 84 +- .../Libraries/Source/WWVegas/WW3D2/ww3d.cpp | 12 +- .../Libraries/Source/WWVegas/WW3D2/ww3d.h | 2 +- .../Tools/WorldBuilder/src/ObjectPreview.cpp | 2 +- .../Tools/WorldBuilder/src/WorldBuilder.cpp | 1 - .../W3DDevice/GameClient/Water/W3DWater.cpp | 10 +- .../GameClient/Water/W3DWaterTracks.cpp | 6 +- 29 files changed, 5861 insertions(+), 2033 deletions(-) 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 c79b154f01..cf4944e264 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp @@ -124,6 +124,9 @@ W3DLaserDraw::W3DLaserDraw( Thing *thing, const ModuleData* moduleData ) : 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; m_texture->Get_Level_Description(surfaceDesc); m_textureAspectRatio = (Real)surfaceDesc.Width/(Real)surfaceDesc.Height; diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp index 7466599e10..49c3c00e9b 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp @@ -261,7 +261,7 @@ Bool W3DProjectedShadowManager::ReAcquireResources(void) DEBUG_ASSERTCRASH(m_dynamicRenderTarget == NULL, ("Acquire of existing shadow render target")); m_renderTargetHasAlpha=TRUE; - if ((m_dynamicRenderTarget=DX8Wrapper::Create_Render_Target (DEFAULT_RENDER_TARGET_WIDTH, DEFAULT_RENDER_TARGET_HEIGHT, true)) == NULL) + if ((m_dynamicRenderTarget=DX8Wrapper::Create_Render_Target (DEFAULT_RENDER_TARGET_WIDTH, DEFAULT_RENDER_TARGET_HEIGHT, WW3D_FORMAT_A8R8G8B8)) == NULL) { m_renderTargetHasAlpha=FALSE; diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp index 55a53a8596..a0143fd001 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp @@ -627,7 +627,7 @@ TextureClass * W3DAssetManager::Recolor_Texture_One_Time(TextureClass *texture, // make sure texture is loaded if (!texture->Is_Initialized()) - TextureLoader::Request_High_Priority_Loading(texture, (MipCountType)texture->Get_Mip_Level_Count()); + TextureLoader::Request_Foreground_Loading(texture); SurfaceClass::SurfaceDescription desc; SurfaceClass *newsurf, *oldsurf; diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp index b8ce435c76..88b25cd33a 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp @@ -402,7 +402,6 @@ W3DDisplay::~W3DDisplay() // shutdown Debug_Statistics::Shutdown_Statistics(); - TextureLoadTaskClass::shutdown(); if (!TheGlobalData->m_headless) W3DShaderManager::shutdown(); m_assetManager->Free_Assets(); diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp index 258bf46c86..3b15a0667e 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp @@ -209,6 +209,8 @@ void WaterRenderObjClass::setupJbaWaterShader(void) DX8Wrapper::Apply_Render_State_Changes(); //force update of view and projection matrices DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAOP, D3DTOP_ADD ); + if (!m_riverAlphaEdge->Is_Initialized()) + m_riverAlphaEdge->Init(); DX8Wrapper::_Get_D3D_Device8()->SetTexture(3,m_riverAlphaEdge->Peek_D3D_Texture()); DX8Wrapper::Set_DX8_Texture_Stage_State(3, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); DX8Wrapper::Set_DX8_Texture_Stage_State(3, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); @@ -219,7 +221,12 @@ void WaterRenderObjClass::setupJbaWaterShader(void) Bool doSparkles = true; if (m_riverWaterPixelShader && doSparkles) { + if (!m_waterSparklesTexture->Is_Initialized()) + m_waterSparklesTexture->Init(); DX8Wrapper::_Get_D3D_Device8()->SetTexture(1,m_waterSparklesTexture->Peek_D3D_Texture()); + + if (!m_waterNoiseTexture->Is_Initialized()) + m_waterNoiseTexture->Init(); DX8Wrapper::_Get_D3D_Device8()->SetTexture(2,m_waterNoiseTexture->Peek_D3D_Texture()); DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); @@ -526,7 +533,7 @@ HRESULT WaterRenderObjClass::initBumpMap(LPDIRECT3DTEXTURE8 *pTex, TextureClass pSrc=(unsigned char *)surf->Lock((int *)&dwSrcPitch); // Create the bumpmap's surface and texture objects - m_pBumpTexture[i]=DX8Wrapper::_Create_DX8_Texture(d3dsd.Width,d3dsd.Height,WW3D_FORMAT_U8V8,MIP_LEVELS_1,D3DPOOL_MANAGED,false); + m_pBumpTexture[i]=DX8Wrapper::_Create_DX8_Texture(d3dsd.Width,d3dsd.Height,WW3D_FORMAT_U8V8,TextureClass::MIP_LEVELS_1,D3DPOOL_MANAGED,false); // Fill the bits of the new texture surface with bits from // a private format. @@ -944,6 +951,22 @@ void WaterRenderObjClass::ReAcquireResources(void) } } + //W3D Invalidate textures after losing the device and since we peek at the textures directly, it won't + //know to reinit them for us. Do it here manually: + if (m_riverTexture && !m_riverTexture->Is_Initialized()) + m_riverTexture->Init(); + if (m_waterNoiseTexture && !m_waterNoiseTexture->Is_Initialized()) + m_waterNoiseTexture->Init(); + if (m_riverAlphaEdge && !m_riverAlphaEdge->Is_Initialized()) + m_riverAlphaEdge->Init(); + if (m_waterSparklesTexture && !m_waterSparklesTexture->Is_Initialized()) + m_waterSparklesTexture->Init(); + if (m_whiteTexture && !m_whiteTexture->Is_Initialized()) + { m_whiteTexture->Init(); + SurfaceClass *surface=m_whiteTexture->Get_Surface_Level(); + surface->DrawPixel(0,0,0xffffffff); + REF_PTR_RELEASE(surface); + } } void WaterRenderObjClass::load(void) @@ -1428,7 +1451,7 @@ void WaterRenderObjClass::renderMirror(CameraClass *cam) Matrix3D reflectedTransform(rRight,rUp,rN,rPos); - DX8Wrapper::Set_Render_Target(m_pReflectionTexture); + DX8Wrapper::Set_Render_Target_With_Z((TextureClass*)m_pReflectionTexture); // Clear the backbuffer WW3D::Begin_Render(false,true,Vector3(0.0f,0.0f,0.0f)); //clearing only z-buffer since background always filled with clouds @@ -1619,11 +1642,11 @@ void WaterRenderObjClass::Render(RenderInfoClass & rinfo) DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHATESTENABLE, true); //test pixels if transparent(clipped) before rendering. // Set clipping texture - m_alphaClippingTexture->Set_U_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); - m_alphaClippingTexture->Set_V_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); - m_alphaClippingTexture->Set_Min_Filter(TextureFilterClass::FILTER_TYPE_NONE); - m_alphaClippingTexture->Set_Mag_Filter(TextureFilterClass::FILTER_TYPE_NONE); - m_alphaClippingTexture->Set_Mip_Mapping(TextureFilterClass::FILTER_TYPE_NONE); + m_alphaClippingTexture->Set_U_Addr_Mode(TextureClass::TEXTURE_ADDRESS_CLAMP); + m_alphaClippingTexture->Set_V_Addr_Mode(TextureClass::TEXTURE_ADDRESS_CLAMP); + m_alphaClippingTexture->Set_Min_Filter(TextureClass::FILTER_TYPE_NONE); + m_alphaClippingTexture->Set_Mag_Filter(TextureClass::FILTER_TYPE_NONE); + m_alphaClippingTexture->Set_Mip_Mapping(TextureClass::FILTER_TYPE_NONE); DX8Wrapper::Set_Texture(0,m_alphaClippingTexture); @@ -2904,6 +2927,22 @@ void WaterRenderObjClass::drawRiverWater(PolygonTrigger *pTrig) void WaterRenderObjClass::setupFlatWaterShader(void) { + + DX8Wrapper::Set_Texture(0,m_riverTexture); + 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); + m_riverTexture->Get_Filter().Set_Mag_Filter(TextureFilterClass::FILTER_TYPE_BEST); + m_riverTexture->Get_Filter().Set_Min_Filter(TextureFilterClass::FILTER_TYPE_BEST); + m_riverTexture->Get_Filter().Set_Mip_Mapping(TextureFilterClass::FILTER_TYPE_BEST); + + DX8Wrapper::Apply_Render_State_Changes(); //force update of view and projection matrices + //Setup shroud to render in same pass as water if (m_trapezoidWaterPixelShader) { if (TheTerrainRenderObject->getShroud()) @@ -2911,10 +2950,6 @@ void WaterRenderObjClass::setupFlatWaterShader(void) W3DShaderManager::setTexture(0,TheTerrainRenderObject->getShroud()->getShroudTexture()); //Use stage 3 to apply the shroud W3DShaderManager::setShader(W3DShaderManager::ST_SHROUD_TEXTURE, 3); - m_pDev->SetTextureStageState( 3, D3DTSS_MINFILTER, D3DTEXF_LINEAR ); - m_pDev->SetTextureStageState( 3, D3DTSS_MAGFILTER, D3DTEXF_LINEAR ); - m_pDev->SetTextureStageState( 3, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP); - m_pDev->SetTextureStageState( 3, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP); //Shroud shader uses z-compare of EQUAL which wouldn't work on water because it doesn't //write to the zbuffer. Change to LESSEQUAL. DX8Wrapper::_Get_D3D_Device8()->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESSEQUAL); @@ -2922,25 +2957,16 @@ void WaterRenderObjClass::setupFlatWaterShader(void) else { //Assume no shroud, so stage 3 will be "NULL" texture but using actual white because //pixel shader on GF4 generates random colors with SetTexture(3,NULL). + if (!m_whiteTexture->Is_Initialized()) + { m_whiteTexture->Init(); + SurfaceClass *surface=m_whiteTexture->Get_Surface_Level(); + surface->DrawPixel(0,0,0xffffffff); + REF_PTR_RELEASE(surface); + } DX8Wrapper::_Get_D3D_Device8()->SetTexture(3,m_whiteTexture->Peek_D3D_Texture()); } } - DX8Wrapper::Set_Texture(0,m_riverTexture); - 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); - m_riverTexture->Get_Filter().Set_Mag_Filter(TextureFilterClass::FILTER_TYPE_BEST); - m_riverTexture->Get_Filter().Set_Min_Filter(TextureFilterClass::FILTER_TYPE_BEST); - m_riverTexture->Get_Filter().Set_Mip_Mapping(TextureFilterClass::FILTER_TYPE_BEST); - - DX8Wrapper::Apply_Render_State_Changes(); //force update of view and projection matrices - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAOP, D3DTOP_ADD ); DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_TEXCOORDINDEX, 0); DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_TEXCOORDINDEX, 0); @@ -2948,7 +2974,15 @@ void WaterRenderObjClass::setupFlatWaterShader(void) Bool doSparkles = true; if (m_trapezoidWaterPixelShader && doSparkles) { + + if (!m_waterSparklesTexture->Is_Initialized()) + m_waterSparklesTexture->Init(); + DX8Wrapper::_Get_D3D_Device8()->SetTexture(1,m_waterSparklesTexture->Peek_D3D_Texture()); + + if (!m_waterNoiseTexture->Is_Initialized()) + m_waterNoiseTexture->Init(); + DX8Wrapper::_Get_D3D_Device8()->SetTexture(2,m_waterNoiseTexture->Peek_D3D_Texture()); DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp index c5cb7e4168..5c60664aae 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp @@ -45,7 +45,10 @@ #include "W3DDevice/GameClient/HeightMap.h" #include "W3DDevice/GameClient/W3DWaterTracks.h" +#include "W3DDevice/GameClient/W3DShaderManager.h" +#include "W3DDevice/GameClient/W3DShroud.h" #include "GameClient/InGameUI.h" +#include "GameClient/Water.h" #include "GameLogic/TerrainLogic.h" #include "Common/FramePacer.h" #include "Common/GlobalData.h" @@ -851,6 +854,9 @@ Try improving the fit to vertical surfaces like cliffs. */ Int diffuseLight; + if (!TheGlobalData->m_showSoftWaterEdge || TheWaterTransparency->m_transparentWaterDepth ==0 ) + return; + if (TheGlobalData->m_usingWaterTrackEditor) TestWaterUpdate(); @@ -887,6 +893,24 @@ Try improving the fit to vertical surfaces like cliffs. DX8Wrapper::Set_Vertex_Buffer(m_vertexBuffer); DX8Wrapper::Set_DX8_Render_State(D3DRS_ZBIAS,8); + //Force apply of render states so we can override them. + DX8Wrapper::Apply_Render_State_Changes(); + + if (TheTerrainRenderObject->getShroud()) + { + W3DShaderManager::setTexture(0,TheTerrainRenderObject->getShroud()->getShroudTexture()); + W3DShaderManager::setShader(W3DShaderManager::ST_SHROUD_TEXTURE, 1); + + //modulate with shroud texture + DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLORARG1, D3DTA_TEXTURE ); //stage 1 texture + DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLORARG2, D3DTA_CURRENT ); //previous stage texture + DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLOROP, D3DTOP_MODULATE ); + DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAOP, D3DTOP_MODULATE ); + + //Shroud shader uses z-compare of EQUAL which wouldn't work on water because it doesn't + //write to the zbuffer. Change to LESSEQUAL. + DX8Wrapper::Set_DX8_Render_State(D3DRS_ZFUNC, D3DCMP_LESSEQUAL); + } Int LastTextureType=-1; @@ -905,6 +929,12 @@ Try improving the fit to vertical surfaces like cliffs. } DX8Wrapper::Set_DX8_Render_State(D3DRS_ZBIAS,0); + + if (TheTerrainRenderObject->getShroud()) + { //we used the shroud shader, so reset it. + DX8Wrapper::Set_DX8_Render_State(D3DRS_ZFUNC, D3DCMP_EQUAL); + W3DShaderManager::resetShader(W3DShaderManager::ST_SHROUD_TEXTURE); + } } WaterTracksObj *WaterTracksRenderSystem::findTrack(Vector2 &start, Vector2 &end, waveType type) diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.cpp index 40931555aa..2afb91369d 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.cpp @@ -16,7 +16,7 @@ ** along with this program. If not, see . */ -/* $Header: /Commando/Code/ww3d2/assetmgr.cpp 36 8/24/01 3:23p Jani_p $ */ +/* $Header: /Commando/Code/ww3d2/assetmgr.cpp 43 11/01/01 1:11a Jani_p $ */ /*********************************************************************************************** *** Confidential - Westwood Studios *** *********************************************************************************************** @@ -25,12 +25,16 @@ * * * $Archive:: /Commando/Code/ww3d2/assetmgr.cpp $* * * - * Author:: Greg_h * + * Org Author:: Greg_h * * * - * $Modtime:: 8/22/01 6:54p $* + * Author : Kenny Mitchell * * * - * $Revision:: 36 $* + * $Modtime:: 08/05/02 10:14a $* * * + * $Revision:: 46 $* + * * + * 06/27/02 KM Texture class abstraction * + * 08/05/02 KM Texture class redesign (revisited) *---------------------------------------------------------------------------------------------* * Functions: * * WW3DAssetManager::WW3DAssetManager -- Constructor * @@ -1040,46 +1044,6 @@ HTreeClass * WW3DAssetManager::Get_HTree(const char * name) return htree; } -/*********************************************************************************************** - * WW3DAssetManager::Get_Bumpmap_Based_On_Texture -- Generate a bumpmap from texture. The * - * resulting texture is stored to the hash table so that any further requests will share it. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/31/2001 NH : Created. * - *=============================================================================================*/ - -TextureClass* WW3DAssetManager::Get_Bumpmap_Based_On_Texture(TextureClass* texture) -{ - WWASSERT(texture->Get_Texture_Name() && strlen(texture->Get_Texture_Name())); - StringClass bump_name="__Bumpmap-"; - bump_name+=texture->Get_Texture_Name(); - _strlwr(bump_name.Peek_Buffer()); // lower case - - /* - ** See if the texture has already been generated. - */ - - TextureClass* tex = TextureHash.Get(bump_name); - - /* - ** Didn't have it so we have to create a new texture - */ - if (!tex) { - tex = NEW_REF(BumpmapTextureClass,(texture)); - tex->Set_Texture_Name(bump_name); - TextureHash.Insert(tex->Get_Texture_Name(),tex); - } - - tex->Add_Ref(); - return tex; -} - /*********************************************************************************************** * WW3DAssetManager::Get_Texture -- get a TextureClass from the specified file * * * @@ -1127,7 +1091,7 @@ 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) + if (tex && (tex->Is_Initialized() == true) && (texture_format!=WW3D_FORMAT_UNKNOWN)) { WWASSERT_PRINT(tex->Get_Texture_Format()==texture_format,("Texture %s has already been loaded with different format",filename)); } @@ -1139,7 +1103,15 @@ TextureClass * WW3DAssetManager::Get_Texture { if (type==TextureBaseClass::TEX_REGULAR) { - tex = NEW_REF (TextureClass, (lower_case_name, NULL, mip_level_count, texture_format, allow_compression)); + tex = NEW_REF (TextureClass, (lower_case_name, NULL, mip_level_count, texture_format, allow_compression, allow_reduction)); + } + else if (type==TextureBaseClass::TEX_CUBEMAP) + { + tex = NEW_REF (CubeTextureClass, (lower_case_name, NULL, mip_level_count, texture_format, allow_compression, allow_reduction)); + } + else if (type==TextureBaseClass::TEX_VOLUME) + { + tex = NEW_REF (VolumeTextureClass, (lower_case_name, NULL, mip_level_count, texture_format, allow_compression, allow_reduction)); } else { diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.h index c68dd00020..f3f1ca83f7 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.h @@ -269,7 +269,6 @@ class WW3DAssetManager TextureBaseClass::TexAssetType type=TextureBaseClass::TEX_REGULAR, bool allow_reduction=true ); - TextureClass* Get_Bumpmap_Based_On_Texture(TextureClass* texture); virtual void Release_All_Textures(void); virtual void Release_Unused_Textures(void); diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/bmp2d.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/bmp2d.cpp index 0f72cdd87c..8f0ba147a0 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/bmp2d.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/bmp2d.cpp @@ -24,12 +24,15 @@ * * * $Archive:: /Commando/Code/ww3d2/bmp2d.cpp $* * * - * $Author:: Naty_h $* + * $Org Author:: Jani_p $* * * - * $Modtime:: 4/13/01 1:37p $* + * $Author:: Kenny_m $* * * - * $Revision:: 10 $* + * $Modtime:: 08/05/02 10:44a $* * * + * $Revision:: 12 $* + * * + * 08/05/02 KM Texture class redesign *-------------------------------------------------------------------------* * Functions: * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ @@ -39,6 +42,9 @@ #include "ww3d.h" #include "texture.h" #include "surfaceclass.h" +#include "assetmgr.h" +#include "textureloader.h" +#include "ww3dformat.h" Bitmap2DObjClass::Bitmap2DObjClass ( @@ -67,7 +73,15 @@ Bitmap2DObjClass::Bitmap2DObjClass // load up the surfaces file name - SurfaceClass *surface=NEW_REF(SurfaceClass,(filename)); + TextureClass *tex = WW3DAssetManager::Get_Instance()->Get_Texture(filename, MIP_LEVELS_1); + if (!tex->Is_Initialized()) + TextureLoader::Request_Foreground_Loading(tex); + + SurfaceClass *surface = tex->Get_Surface_Level(0); + + if (!surface) { + surface = NEW_REF(SurfaceClass, (32, 32, Get_Valid_Texture_Format(WW3D_FORMAT_R8G8B8,true))); + } SurfaceClass::SurfaceDescription sd; surface->Get_Description(sd); @@ -185,6 +199,7 @@ Bitmap2DObjClass::Bitmap2DObjClass REF_PTR_RELEASE(piece_texture); } } + REF_PTR_RELEASE(tex); REF_PTR_RELEASE(surface); Set_Dirty(); @@ -216,6 +231,9 @@ Bitmap2DObjClass::Bitmap2DObjClass // SurfaceClass::SurfaceDescription sd; // texture->Get_Level_Description(sd); + if (!texture->Is_Initialized()) + TextureLoader::Request_Foreground_Loading(texture); + // convert image width and image height to normalized values float vw = (float) texture->Get_Width() / (float)resw; float vh = (float) texture->Get_Height() / (float)resh; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.cpp index 7dd3dc6638..38477273fe 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.cpp @@ -539,6 +539,8 @@ void DX8Caps::Compute_Caps(WW3DFormat display_format, const D3DADAPTER_IDENTIFIE MaxTexturesPerPass=MAX_TEXTURE_STAGES; Check_Texture_Format_Support(display_format,caps); + Check_Render_To_Texture_Support(display_format,caps); + Check_Depth_Stencil_Support(display_format,caps); Check_Texture_Compression_Support(caps); Check_Bumpmap_Support(caps); Check_Shader_Support(caps); diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8texman.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8texman.h index f97ab5fb7f..bc18832207 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8texman.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8texman.h @@ -26,12 +26,13 @@ * * * Original Author:: Hector Yee * * * - * $Author:: Jani_p $* + * Author : Kenny Mitchell * * * - * $Modtime:: 7/26/01 5:12p $* + * $Modtime:: 06/27/02 1:27p $* * * - * $Revision:: 3 $* + * $Revision:: 4 $* * * + * 06/27/02 KM Texture class abstraction * *---------------------------------------------------------------------------------------------* * Functions: * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ @@ -120,6 +121,43 @@ class DX8TextureTrackerClass : public TextureTrackerClass bool RenderTarget; }; +class DX8ZTextureTrackerClass : public TextureTrackerClass +{ +public: + DX8ZTextureTrackerClass + ( + unsigned int w, + unsigned int h, + WW3DZFormat zformat, + MipCountType count, + TextureBaseClass* tex + ) + : TextureTrackerClass(w,h,count,tex), ZFormat(zformat) + { + } + + virtual void Recreate() const + { + WWASSERT(Texture->Peek_D3D_Base_Texture()==NULL); + Texture->Poke_Texture + ( + DX8Wrapper::_Create_DX8_ZTexture + ( + Width, + Height, + ZFormat, + Mip_level_count, + D3DPOOL_DEFAULT + ) + ); + } + + +private: + WW3DZFormat ZFormat; +}; + + class DX8TextureManagerClass { public: diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp index 44b7056ff3..b669695788 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp @@ -32,6 +32,7 @@ * * * $Revision:: 134 $* * * + * 08/05/02 KM Texture class redesign *---------------------------------------------------------------------------------------------* * Functions: * * DX8Wrapper::_Update_Texture -- Copies a texture from system memory to video memory * @@ -125,8 +126,11 @@ LightEnvironmentClass* DX8Wrapper::Light_Environment = NULL; RenderInfoClass* DX8Wrapper::Render_Info = NULL; DWORD DX8Wrapper::Vertex_Processing_Behavior = 0; +ZTextureClass* DX8Wrapper::Shadow_Map[MAX_SHADOW_MAPS]; + Vector3 DX8Wrapper::Ambient_Color; // shader system additions KJM ^ + bool DX8Wrapper::world_identity; unsigned DX8Wrapper::RenderStates[256]; unsigned DX8Wrapper::TextureStageStates[MAX_TEXTURE_STAGES][32]; @@ -140,7 +144,9 @@ D3DCOLOR DX8Wrapper::FogColor = 0; IDirect3D8 * DX8Wrapper::D3DInterface = NULL; IDirect3DDevice8 * DX8Wrapper::D3DDevice = NULL; IDirect3DSurface8 * DX8Wrapper::CurrentRenderTarget = NULL; +IDirect3DSurface8 * DX8Wrapper::CurrentDepthBuffer = NULL; IDirect3DSurface8 * DX8Wrapper::DefaultRenderTarget = NULL; +IDirect3DSurface8 * DX8Wrapper::DefaultDepthBuffer = NULL; bool DX8Wrapper::IsRenderToTexture = false; unsigned DX8Wrapper::matrix_changes = 0; @@ -268,6 +274,7 @@ bool DX8Wrapper::Init(void * hwnd, bool lite) memset(Vertex_Shader_Constants,0,sizeof(Vector4)*MAX_VERTEX_SHADER_CONSTANTS); memset(Pixel_Shader_Constants,0,sizeof(Vector4)*MAX_PIXEL_SHADER_CONSTANTS); memset(&render_state,0,sizeof(RenderStateStruct)); + memset(Shadow_Map,0,sizeof(ZTextureClass*)*MAX_SHADOW_MAPS); /* ** Initialize all variables! @@ -396,7 +403,7 @@ void DX8Wrapper::Do_Onetime_Device_Dependent_Inits(void) ** Initalize any other subsystems inside of WW3D */ MissingTexture::_Init(); - TextureFilterClass::_Init_Filters(); + TextureFilterClass::_Init_Filters((TextureFilterClass::TextureFilterMode)WW3D::Get_Texture_Filter()); TheDX8MeshRenderer.Init(); BoxRenderObjClass::Init(); VertexMaterialClass::Init(); @@ -603,6 +610,8 @@ bool DX8Wrapper::Reset_Device(bool reload_assets) DX8_THREAD_ASSERT(); if ((IsInitted) && (D3DDevice != NULL)) { // Release all non-MANAGED stuff + WW3D::_Invalidate_Textures(); + Set_Vertex_Buffer (NULL); Set_Index_Buffer (NULL, 0); if (m_pCleanupHook) { @@ -2378,6 +2387,305 @@ IDirect3DTexture8 * DX8Wrapper::_Create_DX8_Texture } +/*! + * KJM create depth stencil texture + */ +IDirect3DTexture8 * DX8Wrapper::_Create_DX8_ZTexture +( + unsigned int width, + unsigned int height, + WW3DZFormat zformat, + MipCountType mip_level_count, + D3DPOOL pool +) +{ + DX8_THREAD_ASSERT(); + DX8_Assert(); + IDirect3DTexture8* texture = NULL; + + D3DFORMAT zfmt=WW3DZFormat_To_D3DFormat(zformat); + + unsigned ret=DX8Wrapper::_Get_D3D_Device8()->CreateTexture + ( + width, + height, + mip_level_count, + D3DUSAGE_DEPTHSTENCIL, + zfmt, + pool, + &texture + ); + + if (ret==D3DERR_NOTAVAILABLE) + { + Non_Fatal_Log_DX8_ErrorCode(ret,__FILE__,__LINE__); + return NULL; + } + + // If ran out of texture ram, try invalidating some textures and mesh cache. + if (ret==D3DERR_OUTOFVIDEOMEMORY) + { + WWDEBUG_SAY(("Error: Out of memory while creating render target. Trying to release assets...")); + // Free all textures that haven't been used in the last 5 seconds + TextureClass::Invalidate_Old_Unused_Textures(5000); + + // Invalidate the mesh cache + WW3D::_Invalidate_Mesh_Cache(); + + ret=DX8Wrapper::_Get_D3D_Device8()->CreateTexture + ( + width, + height, + mip_level_count, + D3DUSAGE_DEPTHSTENCIL, + zfmt, + pool, + &texture + ); + + if (SUCCEEDED(ret)) + { + WWDEBUG_SAY(("...Render target creation succesful.")); + } + else + { + WWDEBUG_SAY(("...Render target creation failed.")); + } + if (ret==D3DERR_OUTOFVIDEOMEMORY) + { + Non_Fatal_Log_DX8_ErrorCode(ret,__FILE__,__LINE__); + return NULL; + } + } + + DX8_ErrorCode(ret); + + texture->AddRef(); // don't release this texture + + // Just return the texture, no reduction + // allowed for render targets. + + return texture; +} + +/*! + * KJM create cube map texture + */ +IDirect3DCubeTexture8* DX8Wrapper::_Create_DX8_Cube_Texture +( + unsigned int width, + unsigned int height, + WW3DFormat format, + MipCountType mip_level_count, + D3DPOOL pool, + bool rendertarget +) +{ + WWASSERT(width==height); + DX8_THREAD_ASSERT(); + DX8_Assert(); + IDirect3DCubeTexture8* texture=NULL; + + // Paletted textures not supported! + WWASSERT(format!=D3DFMT_P8); + + // NOTE: If 'format' is not supported as a texture format, this function will find the closest + // format that is supported and use that instead. + + // Render target may return NOTAVAILABLE, in + // which case we return NULL. + if (rendertarget) + { + unsigned ret=D3DXCreateCubeTexture + ( + DX8Wrapper::_Get_D3D_Device8(), + width, + mip_level_count, + D3DUSAGE_RENDERTARGET, + WW3DFormat_To_D3DFormat(format), + pool, + &texture + ); + + if (ret==D3DERR_NOTAVAILABLE) + { + Non_Fatal_Log_DX8_ErrorCode(ret,__FILE__,__LINE__); + return NULL; + } + + // If ran out of texture ram, try invalidating some textures and mesh cache. + if (ret==D3DERR_OUTOFVIDEOMEMORY) + { + WWDEBUG_SAY(("Error: Out of memory while creating render target. Trying to release assets...")); + // Free all textures that haven't been used in the last 5 seconds + TextureClass::Invalidate_Old_Unused_Textures(5000); + + // Invalidate the mesh cache + WW3D::_Invalidate_Mesh_Cache(); + + ret=D3DXCreateCubeTexture + ( + DX8Wrapper::_Get_D3D_Device8(), + width, + mip_level_count, + D3DUSAGE_RENDERTARGET, + WW3DFormat_To_D3DFormat(format), + pool, + &texture + ); + + if (SUCCEEDED(ret)) + { + WWDEBUG_SAY(("...Render target creation succesful.")); + } + else + { + WWDEBUG_SAY(("...Render target creation failed.")); + } + if (ret==D3DERR_OUTOFVIDEOMEMORY) + { + Non_Fatal_Log_DX8_ErrorCode(ret,__FILE__,__LINE__); + return NULL; + } + } + + DX8_ErrorCode(ret); + // Just return the texture, no reduction + // allowed for render targets. + return texture; + } + + // We should never run out of video memory when allocating a non-rendertarget texture. + // However, it seems to happen sometimes when there are a lot of textures in memory and so + // if it happens we'll release assets and try again (anything is better than crashing). + unsigned ret=D3DXCreateCubeTexture + ( + DX8Wrapper::_Get_D3D_Device8(), + width, + mip_level_count, + 0, + WW3DFormat_To_D3DFormat(format), + pool, + &texture + ); + + // If ran out of texture ram, try invalidating some textures and mesh cache. + if (ret==D3DERR_OUTOFVIDEOMEMORY) + { + WWDEBUG_SAY(("Error: Out of memory while creating texture. Trying to release assets...")); + // Free all textures that haven't been used in the last 5 seconds + TextureClass::Invalidate_Old_Unused_Textures(5000); + + // Invalidate the mesh cache + WW3D::_Invalidate_Mesh_Cache(); + + ret=D3DXCreateCubeTexture + ( + DX8Wrapper::_Get_D3D_Device8(), + width, + mip_level_count, + 0, + WW3DFormat_To_D3DFormat(format), + pool, + &texture + ); + if (SUCCEEDED(ret)) + { + WWDEBUG_SAY(("...Texture creation succesful.")); + } + else + { + StringClass format_name(0,true); + Get_WW3D_Format_Name(format, format_name); + WWDEBUG_SAY(("...Texture creation failed. (%d x %d, format: %s, mips: %d",width,height,format_name.str(),mip_level_count)); + } + + } + DX8_ErrorCode(ret); + + return texture; +} + +/*! + * KJM create volume texture + */ +IDirect3DVolumeTexture8* DX8Wrapper::_Create_DX8_Volume_Texture +( + unsigned int width, + unsigned int height, + unsigned int depth, + WW3DFormat format, + MipCountType mip_level_count, + D3DPOOL pool +) +{ + DX8_THREAD_ASSERT(); + DX8_Assert(); + IDirect3DVolumeTexture8* texture=NULL; + + // Paletted textures not supported! + WWASSERT(format!=D3DFMT_P8); + + // NOTE: If 'format' is not supported as a texture format, this function will find the closest + // format that is supported and use that instead. + + + // We should never run out of video memory when allocating a non-rendertarget texture. + // However, it seems to happen sometimes when there are a lot of textures in memory and so + // if it happens we'll release assets and try again (anything is better than crashing). + unsigned ret=D3DXCreateVolumeTexture + ( + DX8Wrapper::_Get_D3D_Device8(), + width, + height, + depth, + mip_level_count, + 0, + WW3DFormat_To_D3DFormat(format), + pool, + &texture + ); + + // If ran out of texture ram, try invalidating some textures and mesh cache. + if (ret==D3DERR_OUTOFVIDEOMEMORY) + { + WWDEBUG_SAY(("Error: Out of memory while creating texture. Trying to release assets...")); + // Free all textures that haven't been used in the last 5 seconds + TextureClass::Invalidate_Old_Unused_Textures(5000); + + // Invalidate the mesh cache + WW3D::_Invalidate_Mesh_Cache(); + + ret=D3DXCreateVolumeTexture + ( + DX8Wrapper::_Get_D3D_Device8(), + width, + height, + depth, + mip_level_count, + 0, + WW3DFormat_To_D3DFormat(format), + pool, + &texture + ); + if (SUCCEEDED(ret)) + { + WWDEBUG_SAY(("...Texture creation succesful.")); + } + else + { + StringClass format_name(0,true); + Get_WW3D_Format_Name(format, format_name); + WWDEBUG_SAY(("...Texture creation failed. (%d x %d, format: %s, mips: %d",width,height,format_name.str(),mip_level_count)); + } + + } + DX8_ErrorCode(ret); + + return texture; +} + + IDirect3DSurface8 * DX8Wrapper::_Create_DX8_Surface(unsigned int width, unsigned int height, WW3DFormat format) { DX8_THREAD_ASSERT(); @@ -2660,10 +2968,24 @@ SurfaceClass * DX8Wrapper::_Get_DX8_Back_Buffer(unsigned int num) TextureClass * -DX8Wrapper::Create_Render_Target (int width, int height, bool alpha) +DX8Wrapper::Create_Render_Target (int width, int height, WW3DFormat format) { DX8_THREAD_ASSERT(); DX8_Assert(); + number_of_DX8_calls++; + + // Use the current display format if format isn't specified + if (format==WW3D_FORMAT_UNKNOWN) { + D3DDISPLAYMODE mode; + DX8CALL(GetDisplayMode(&mode)); + format=D3DFormat_To_WW3DFormat(mode.Format); + } + + // If render target format isn't supported return NULL + if (!Get_Current_Caps()->Support_Render_To_Texture_Format(format)) { + WWDEBUG_SAY(("DX8Wrapper - Render target format is not supported")); + return NULL; + } // // Note: We're going to force the width and height to be powers of two and equal @@ -2685,49 +3007,81 @@ DX8Wrapper::Create_Render_Target (int width, int height, bool alpha) width = height = poweroftwosize; // - // Get the current format of the display + // Attempt to create the render target // - D3DDISPLAYMODE mode; - DX8CALL(GetDisplayMode(&mode)); + TextureClass * tex = NEW_REF(TextureClass,(width,height,format,MIP_LEVELS_1,TextureClass::POOL_DEFAULT,true)); + + // 3dfx drivers are lying in the CheckDeviceFormat call and claiming + // that they support render targets! + if (tex->Peek_D3D_Base_Texture() == NULL) + { + WWDEBUG_SAY(("DX8Wrapper - Render target creation failed!")); + REF_PTR_RELEASE(tex); + } + + return tex; +} + +//********************************************************************************************** +//! Create render target with associated depth stencil buffer +/*! KJM +*/ +void DX8Wrapper::Create_Render_Target +( + int width, + int height, + WW3DFormat format, + WW3DZFormat zformat, + TextureClass** target, + ZTextureClass** depth_buffer +) +{ + DX8_THREAD_ASSERT(); + DX8_Assert(); + number_of_DX8_calls++; - // If the user requested a render-target texture and this device does not support that - // feature, return NULL - HRESULT hr; + // Use the current display format if format isn't specified + if (format==WW3D_FORMAT_UNKNOWN) + { + *target=NULL; + *depth_buffer=NULL; + return; +/* D3DDISPLAYMODE mode; + DX8CALL(GetDisplayMode(&mode)); + format=D3DFormat_To_WW3DFormat(mode.Format);*/ + } - if (alpha) + // If render target format isn't supported return NULL + if (!Get_Current_Caps()->Support_Render_To_Texture_Format(format) || + !Get_Current_Caps()->Support_Depth_Stencil_Format(zformat)) { - //user wants a texture with destination alpha channel - only 1 such format - //ever exists on current hardware - D3DFMT_A8R8G8B8 - hr = D3DInterface->CheckDeviceFormat( D3DADAPTER_DEFAULT, - WW3D_DEVTYPE, - mode.Format, - D3DUSAGE_RENDERTARGET, - D3DRTYPE_TEXTURE, - D3DFMT_A8R8G8B8 ); - mode.Format=D3DFMT_A8R8G8B8; + WWDEBUG_SAY(("DX8Wrapper - Render target with depth format is not supported")); + return; } - else + + // Note: We're going to force the width and height to be powers of two and equal + const D3DCAPS8& dx8caps=Get_Current_Caps()->Get_DX8_Caps(); + float poweroftwosize = width; + if (height > 0 && height < width) { - hr = D3DInterface->CheckDeviceFormat( D3DADAPTER_DEFAULT, - WW3D_DEVTYPE, - mode.Format, - D3DUSAGE_RENDERTARGET, - D3DRTYPE_TEXTURE, - mode.Format ); + poweroftwosize = height; } + poweroftwosize = ::Find_POT (poweroftwosize); - number_of_DX8_calls++; - if (hr != D3D_OK) { - WWDEBUG_SAY(("DX8Wrapper - Driver cannot create render target!")); - return NULL; + if (poweroftwosize>dx8caps.MaxTextureWidth) + { + poweroftwosize=dx8caps.MaxTextureWidth; } - // + if (poweroftwosize>dx8caps.MaxTextureHeight) + { + poweroftwosize=dx8caps.MaxTextureHeight; + } + + width = height = poweroftwosize; + // Attempt to create the render target - // - DX8_Assert(); - WW3DFormat format=D3DFormat_To_WW3DFormat(mode.Format); - TextureClass * tex = NEW_REF(TextureClass,(width,height,format,MIP_LEVELS_1,TextureClass::POOL_DEFAULT,true)); + TextureClass* tex=NEW_REF(TextureClass,(width,height,format,MIP_LEVELS_1,TextureClass::POOL_DEFAULT,true)); // 3dfx drivers are lying in the CheckDeviceFormat call and claiming // that they support render targets! @@ -2737,19 +3091,52 @@ DX8Wrapper::Create_Render_Target (int width, int height, bool alpha) REF_PTR_RELEASE(tex); } - return tex; -} + *target=tex; + // attempt to create the depth stencil buffer + *depth_buffer=NEW_REF + ( + ZTextureClass, + ( + width, + height, + zformat, + MIP_LEVELS_1, + TextureClass::POOL_DEFAULT + ) + ); +} -void -DX8Wrapper::Set_Render_Target -(TextureClass * texture) +/*! + * Set render target + * KM Added optional custom z target + */ +void DX8Wrapper::Set_Render_Target_With_Z +( + TextureClass* texture, + ZTextureClass* ztexture +) { - WWASSERT(texture != NULL); - SurfaceClass * surf = texture->Get_Surface_Level(); - WWASSERT(surf != NULL); - Set_Render_Target(surf->Peek_D3D_Surface()); - REF_PTR_RELEASE(surf); + WWASSERT(texture!=NULL); + IDirect3DSurface8 * d3d_surf = texture->Get_D3D_Surface_Level(); + WWASSERT(d3d_surf != NULL); + + IDirect3DSurface8* d3d_zbuf=NULL; + if (ztexture!=NULL) + { + + d3d_zbuf=ztexture->Get_D3D_Surface_Level(); + WWASSERT(d3d_zbuf!=NULL); + Set_Render_Target(d3d_surf,d3d_zbuf); + d3d_zbuf->Release(); + } + else + { + Set_Render_Target(d3d_surf,true); + } + d3d_surf->Release(); + + IsRenderToTexture = true; } void @@ -2767,7 +3154,7 @@ DX8Wrapper::Set_Render_Target(IDirect3DSwapChain8 *swap_chain) // // Set this back buffer as the render targer // - Set_Render_Target (render_target); + Set_Render_Target (render_target, true); // // Release our hold on the back buffer @@ -2783,31 +3170,36 @@ DX8Wrapper::Set_Render_Target(IDirect3DSwapChain8 *swap_chain) } void -DX8Wrapper::Set_Render_Target(IDirect3DSurface8 *render_target) +DX8Wrapper::Set_Render_Target(IDirect3DSurface8 *render_target, bool use_default_depth_buffer) { +//#ifndef _XBOX DX8_THREAD_ASSERT(); DX8_Assert(); - // - // We'll need the depth buffer later... - // - IDirect3DSurface8 *depth_buffer = NULL; - DX8CALL(GetDepthStencilSurface (&depth_buffer)); - // // Should we restore the default render target set a new one? // if (render_target == NULL || render_target == DefaultRenderTarget) { + // If there is currently a custom render target, default must NOT be NULL. + if (CurrentRenderTarget) + { + WWASSERT(DefaultRenderTarget!=NULL); + } // // Restore the default render target // if (DefaultRenderTarget != NULL) { - DX8CALL(SetRenderTarget (DefaultRenderTarget, depth_buffer)); + DX8CALL(SetRenderTarget (DefaultRenderTarget, DefaultDepthBuffer)); DefaultRenderTarget->Release (); DefaultRenderTarget = NULL; + if (DefaultDepthBuffer) + { + DefaultDepthBuffer->Release (); + DefaultDepthBuffer = NULL; + } } // @@ -2819,9 +3211,25 @@ DX8Wrapper::Set_Render_Target(IDirect3DSurface8 *render_target) CurrentRenderTarget = NULL; } + if (CurrentDepthBuffer!=NULL) + { + CurrentDepthBuffer->Release(); + CurrentDepthBuffer=NULL; + } + } else if (render_target != CurrentRenderTarget) { + WWASSERT(DefaultRenderTarget==NULL); + + // + // We'll need the depth buffer later... + // + if (DefaultDepthBuffer == NULL) + { +// IDirect3DSurface8 *depth_buffer = NULL; + DX8CALL(GetDepthStencilSurface (&DefaultDepthBuffer)); + } // // Get a pointer to the default render target (if necessary) @@ -2840,6 +3248,12 @@ DX8Wrapper::Set_Render_Target(IDirect3DSurface8 *render_target) CurrentRenderTarget = NULL; } + if (CurrentDepthBuffer!=NULL) + { + CurrentDepthBuffer->Release(); + CurrentDepthBuffer=NULL; + } + // // Keep a copy of the current render target (for housekeeping) // @@ -2852,20 +3266,142 @@ DX8Wrapper::Set_Render_Target(IDirect3DSurface8 *render_target) // // Switch render targets // - DX8CALL(SetRenderTarget (CurrentRenderTarget, depth_buffer)); + if (use_default_depth_buffer) + { + DX8CALL(SetRenderTarget (CurrentRenderTarget, DefaultDepthBuffer)); + } + else + { + DX8CALL(SetRenderTarget (CurrentRenderTarget, NULL)); + } } } // // Free our hold on the depth buffer // - if (depth_buffer != NULL) { - depth_buffer->Release (); - depth_buffer = NULL; - } +// if (depth_buffer != NULL) { +// depth_buffer->Release (); +// depth_buffer = NULL; +// } IsRenderToTexture = false; return ; +//#endif // XBOX +} + + +//********************************************************************************************** +//! Set render target with depth stencil buffer +/*! KJM +*/ +void DX8Wrapper::Set_Render_Target +( + IDirect3DSurface8* render_target, + IDirect3DSurface8* depth_buffer +) +{ +//#ifndef _XBOX + DX8_THREAD_ASSERT(); + DX8_Assert(); + + // + // Should we restore the default render target set a new one? + // + if (render_target == NULL || render_target == DefaultRenderTarget) + { + // If there is currently a custom render target, default must NOT be NULL. + if (CurrentRenderTarget) + { + WWASSERT(DefaultRenderTarget!=NULL); + } + + // + // Restore the default render target + // + if (DefaultRenderTarget != NULL) + { + DX8CALL(SetRenderTarget (DefaultRenderTarget, DefaultDepthBuffer)); + DefaultRenderTarget->Release (); + DefaultRenderTarget = NULL; + if (DefaultDepthBuffer) + { + DefaultDepthBuffer->Release (); + DefaultDepthBuffer = NULL; + } + } + + // + // Release our hold on the "current" render target + // + if (CurrentRenderTarget != NULL) + { + CurrentRenderTarget->Release (); + CurrentRenderTarget = NULL; + } + + if (CurrentDepthBuffer!=NULL) + { + CurrentDepthBuffer->Release(); + CurrentDepthBuffer=NULL; + } + } + else if (render_target != CurrentRenderTarget) + { + WWASSERT(DefaultRenderTarget==NULL); + + // + // We'll need the depth buffer later... + // + if (DefaultDepthBuffer == NULL) + { +// IDirect3DSurface8 *depth_buffer = NULL; + DX8CALL(GetDepthStencilSurface (&DefaultDepthBuffer)); + } + + // + // Get a pointer to the default render target (if necessary) + // + if (DefaultRenderTarget == NULL) + { + DX8CALL(GetRenderTarget (&DefaultRenderTarget)); + } + + // + // Release our hold on the old "current" render target + // + if (CurrentRenderTarget != NULL) + { + CurrentRenderTarget->Release (); + CurrentRenderTarget = NULL; + } + + if (CurrentDepthBuffer!=NULL) + { + CurrentDepthBuffer->Release(); + CurrentDepthBuffer=NULL; + } + + // + // Keep a copy of the current render target (for housekeeping) + // + CurrentRenderTarget = render_target; + CurrentDepthBuffer = depth_buffer; + WWASSERT (CurrentRenderTarget != NULL); + if (CurrentRenderTarget != NULL) + { + CurrentRenderTarget->AddRef (); + CurrentDepthBuffer->AddRef(); + + // + // Switch render targets + // + DX8CALL(SetRenderTarget (CurrentRenderTarget, CurrentDepthBuffer)); + } + } + + IsRenderToTexture=true; +//#endif // XBOX } diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h index c5404ad3ff..f72ce2e13e 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h @@ -349,6 +349,37 @@ class DX8Wrapper ** Resources */ + static IDirect3DVolumeTexture8* _Create_DX8_Volume_Texture + ( + unsigned int width, + unsigned int height, + unsigned int depth, + WW3DFormat format, + MipCountType mip_level_count, + D3DPOOL pool=D3DPOOL_MANAGED + ); + + static IDirect3DCubeTexture8* _Create_DX8_Cube_Texture + ( + unsigned int width, + unsigned int height, + WW3DFormat format, + MipCountType mip_level_count, + D3DPOOL pool=D3DPOOL_MANAGED, + bool rendertarget=false + ); + + + static IDirect3DTexture8* _Create_DX8_ZTexture + ( + unsigned int width, + unsigned int height, + WW3DZFormat zformat, + MipCountType mip_level_count, + D3DPOOL pool=D3DPOOL_MANAGED + ); + + static IDirect3DTexture8 * _Create_DX8_Texture ( unsigned int width, @@ -436,15 +467,32 @@ class DX8Wrapper static IDirect3DSwapChain8 * Create_Additional_Swap_Chain (HWND render_window); /* - ** Render target interface + ** Render target interface. If render target format is WW3D_FORMAT_UNKNOWN, current display format is used. */ - static TextureClass * Create_Render_Target (int width, int height, bool alpha=false); + static TextureClass * Create_Render_Target (int width, int height, WW3DFormat format = WW3D_FORMAT_UNKNOWN); + + static void Set_Render_Target (IDirect3DSurface8 *render_target, bool use_default_depth_buffer = false); + static void Set_Render_Target (IDirect3DSurface8* render_target, IDirect3DSurface8* dpeth_buffer); - 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; } + // for depth map support KJM V + static void Create_Render_Target + ( + int width, + int height, + WW3DFormat format, + WW3DZFormat zformat, + TextureClass** target, + ZTextureClass** depth_buffer + ); + static void Set_Render_Target_With_Z (TextureClass * texture, ZTextureClass* ztexture=NULL); + + static void Set_Shadow_Map(int idx, ZTextureClass* ztex) { Shadow_Map[idx]=ztex; } + static ZTextureClass* Get_Shadow_Map(int idx) { return Shadow_Map[idx]; } + // for depth map support KJM ^ + // shader system udpates KJM v static void Apply_Default_State(); @@ -597,6 +645,9 @@ class DX8Wrapper static RenderInfoClass* Render_Info; static DWORD Vertex_Processing_Behavior; + + static ZTextureClass* Shadow_Map[MAX_SHADOW_MAPS]; + static Vector3 Ambient_Color; // shader system updates KJM ^ @@ -631,7 +682,10 @@ class DX8Wrapper static IDirect3DDevice8 * D3DDevice; //d3ddevice8; static IDirect3DSurface8 * CurrentRenderTarget; + static IDirect3DSurface8 * CurrentDepthBuffer; static IDirect3DSurface8 * DefaultRenderTarget; + static IDirect3DSurface8 * DefaultDepthBuffer; + static unsigned DrawPolygonLowBoundLimit; static bool IsRenderToTexture; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texproject.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texproject.cpp index 2e819962eb..79ea6d9804 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texproject.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texproject.cpp @@ -26,12 +26,15 @@ * * * Original Author:: Greg Hjelstrom * * * - * $Author:: Jani_p $* + * $Author:: Kenny Mitchell * * * - * $Modtime:: 7/23/01 5:31p $* + * $Modtime:: 08/05/02 10:03a $* * * - * $Revision:: 15 $* + * $Revision:: 22 $* * * + * 06/26/02 KM Matrix name change to avoid MAX conflicts * + * 06/27/02 KM Render to shadow buffer texture support * + * 08/05/02 KM Texture class redesign *---------------------------------------------------------------------------------------------* * Functions: * * TexProjectClass::TexProjectClass -- Constructor * @@ -88,7 +91,7 @@ #include "MPU.h" #define DEBUG_SHADOW_RENDERING 0 -#define DEFAULT_TEXTURE_SIZE 64 +//#define DEFAULT_TEXTURE_SIZE 64 const float INTENSITY_RATE_OF_CHANGE = 1.0f; // change in intensity per second @@ -186,6 +189,7 @@ TexProjectClass::TexProjectClass(void) : MaterialPass(NULL), Mapper1(NULL), RenderTarget(NULL), + DepthStencilTarget(NULL), HFov(90.0f), VFov(90.0f), XMin(-10.0f), @@ -195,9 +199,6 @@ TexProjectClass::TexProjectClass(void) : ZNear(1.0f), ZFar(1000.0f) { - // set a default texture size - Set_Texture_Size(DEFAULT_TEXTURE_SIZE); - // create a material pass class MaterialPass = NEW_REF(MaterialPassClass,()); MaterialPass->Set_Cull_Volume(&WorldBoundingVolume); @@ -236,6 +237,7 @@ TexProjectClass::~TexProjectClass(void) REF_PTR_RELEASE(Mapper1); REF_PTR_RELEASE(MaterialPass); REF_PTR_RELEASE(RenderTarget); + REF_PTR_RELEASE(DepthStencilTarget); } @@ -1108,6 +1110,7 @@ bool TexProjectClass::Compute_Ortho_Projection * * * HISTORY: * * 1/11/00 gth : Created. * + * 5/16/02 kjm : Added optional custom depth/stencil target * *=============================================================================================*/ bool TexProjectClass::Compute_Texture ( @@ -1122,15 +1125,20 @@ bool TexProjectClass::Compute_Texture /* ** Render to texture */ - TextureClass * rtarget = Peek_Render_Target(); + TextureClass * rtarget=NULL; + ZTextureClass* ztarget=NULL; + + Peek_Render_Target(&rtarget,&ztarget); if (rtarget != NULL) { + // set projector for render context KJM + context->Texture_Projector=this; /* ** Set the render target */ - DX8Wrapper::Set_Render_Target(rtarget); + DX8Wrapper::Set_Render_Target_With_Z (rtarget,ztarget); /* ** Set up the camera @@ -1145,9 +1153,15 @@ bool TexProjectClass::Compute_Texture color.Set(1.0f,1.0f,1.0f); } - WW3D::Begin_Render(true,true,color); + bool zclear=ztarget!=NULL; + + bool snapshot=WW3D::Is_Snapshot_Activated(); + SNAPSHOT_SAY(("TexProjectCLass::Begin_Render()")); + WW3D::Begin_Render(true,zclear,color); // false to zclear as we don't have z-buffer WW3D::Render(*model,*context); + SNAPSHOT_SAY(("TexProjectCLass::End_Render()")); WW3D::End_Render(false); + WW3D::Activate_Snapshot(snapshot); // End_Render() ends the shapsnot, so restore the state DX8Wrapper::Set_Render_Target((IDirect3DSurface8 *)NULL); @@ -1200,11 +1214,13 @@ bool TexProjectClass::Needs_Render_Target(void) *=============================================================================================*/ void TexProjectClass::Set_Render_Target ( - TextureClass* render_target + TextureClass* render_target, + ZTextureClass* zbuffer ) { REF_PTR_SET(RenderTarget,render_target); Set_Texture(RenderTarget); + REF_PTR_SET(DepthStencilTarget,zbuffer); } /*********************************************************************************************** @@ -1218,12 +1234,23 @@ void TexProjectClass::Set_Render_Target * * * HISTORY: * * 4/5/2001 gth : Created. * + * 5/16/2002 kjm : Added optional custom zbuffer * *=============================================================================================*/ TextureClass* TexProjectClass::Peek_Render_Target ( - void + TextureClass** rtarget, + ZTextureClass** ztarget ) { + // some uses of this function just want to know if a render target exists + if (rtarget==NULL) return RenderTarget; + + *rtarget=RenderTarget; + + // don't set if pointer isn't supplied + if (ztarget!=NULL) + *ztarget=DepthStencilTarget; + return RenderTarget; } @@ -1252,6 +1279,13 @@ void TexProjectClass::Configure_Camera(CameraClass & camera) camera.Set_Projection_Type(CameraClass::ORTHO); camera.Set_View_Plane(Vector2(XMin,YMin),Vector2(XMax,YMax)); } + + // Set one-pixel borders to the texture to avoid "flooding" shadows... + float size=Get_Texture_Size(); + float inv_size=1.0f/size; + Vector2 vmin(1.0f*inv_size,1.0f*inv_size); + Vector2 vmax((size-1.0f)*inv_size,(size-1.0f)*inv_size); + camera.Set_Viewport(vmin,vmax); } diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texproject.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texproject.h index 88ebc09e64..0ad5aa9efd 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texproject.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texproject.h @@ -26,12 +26,13 @@ * * * Original Author:: Greg Hjelstrom * * * - * $Author:: Greg_h $* + * $Author:: Kenny Mitchell * * * - * $Modtime:: 4/23/01 7:29p $* + * $Modtime:: 06/26/02 4:04p $* * * - * $Revision:: 6 $* + * $Revision:: 8 $* * * + * 06/27/02 KM Render to shadow buffer texture support * *---------------------------------------------------------------------------------------------* * Functions: * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ @@ -54,6 +55,8 @@ class RenderObjClass; class MaterialPassClass; class SurfaceClass; +class TextureClass; +class ZTextureClass; /** @@ -139,6 +142,11 @@ class TexProjectClass : public ProjectorClass, public CullableClass, public Mult TextureClass * Get_Texture(void) const; TextureClass * Peek_Texture(void) const; + + void Set_DepthStencilBuffer(ZTextureClass* ztex); + ZTextureClass* Get_DepthStencilBuffer() const; + ZTextureClass* Peek_DepthStencilBuffer() const; + /* ** Automatic initialization of a TexProjectClass. ** First set up your projection parameters, give the projector a render target, then call Compute_Texture @@ -150,8 +158,8 @@ class TexProjectClass : public ProjectorClass, public CullableClass, public Mult bool Compute_Ortho_Projection(const AABoxClass & obj_box,const Matrix3D & tm,const Vector3 & lightdir,float znear=-1.0f,float zfar=-1.0f); bool Needs_Render_Target(void); - void Set_Render_Target(TextureClass * render_target); - TextureClass * Peek_Render_Target(void); + void Set_Render_Target(TextureClass* render_target, ZTextureClass* ztarget=NULL); + TextureClass* Peek_Render_Target(TextureClass** rtarget=NULL, ZTextureClass** ztarget=NULL); bool Compute_Texture(RenderObjClass * model,SpecialRenderInfoClass * context); @@ -190,7 +198,7 @@ class TexProjectClass : public ProjectorClass, public CullableClass, public Mult SIZE_MASK = 0xFFF00000, // desired texture size stored in upper 3 nibbles SIZE_SHIFT = 20, - DEFAULT_FLAGS = ATTENUATE | AFFECT_DYNAMIC_OBJS | AFFECT_STATIC_OBJS | (64<(texture)->Peek_D3D_Texture(); - if (!d3d_texture) return 0; - for (unsigned i=red_factor;iGetLevelCount();++i) { - D3DSURFACE_DESC desc; - DX8_ErrorCode(d3d_texture->GetLevelDesc(i,&desc)); - size+=desc.Size; - } - return size; -} +// This throttles submissions to the background texture loading queue. +static unsigned TexturesAppliedPerFrame; +const unsigned MAX_TEXTURES_APPLIED_PER_FRAME=2; -/************************************************************************* -** TextureClass -*************************************************************************/ -TextureClass::TextureClass(unsigned width, unsigned height, WW3DFormat format, MipCountType mip_level_count, PoolType pool,bool rendertarget) - : +/*! + * KM General base constructor for texture classes + */ +TextureBaseClass::TextureBaseClass +( + unsigned int width, + unsigned int height, + enum MipCountType mip_level_count, + enum PoolType pool, + bool rendertarget, + bool reducible +) +: MipLevelCount(mip_level_count), D3DTexture(NULL), + Initialized(false), + Name(""), + FullPath(""), texture_id(unused_texture_id++), - Initialized(true), - Filter(mip_level_count), - MipLevelCount(mip_level_count), - Pool(pool), - Dirty(false), IsLightmap(false), - IsProcedural(true), - Name(""), - TextureFormat(format), + IsProcedural(false), + IsReducible(reducible), IsCompressionAllowed(false), - TextureLoadTask(NULL), + InactivationTime(0), + ExtendedInactivationTime(0), + LastInactivationSyncTime(0), + LastAccessed(0), Width(width), - Height(height) + Height(height), + Pool(pool), + Dirty(false), + TextureLoadTask(NULL), + ThumbnailLoadTask(NULL), + HSVShift(0.0f,0.0f,0.0f) { - switch (format) - { - case WW3D_FORMAT_DXT1: - case WW3D_FORMAT_DXT2: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: - IsCompressionAllowed=true; - break; - default : break; - } +} - D3DPOOL d3dpool=(D3DPOOL)0; - switch(pool) - { - case POOL_DEFAULT : d3dpool=D3DPOOL_DEFAULT; break; - case POOL_MANAGED : d3dpool=D3DPOOL_MANAGED; break; - case POOL_SYSTEMMEM : d3dpool=D3DPOOL_SYSTEMMEM; break; - default: WWASSERT(0); - } - D3DTexture = DX8Wrapper::_Create_DX8_Texture(width, height, format, mip_level_count,d3dpool,rendertarget); - if (pool==POOL_DEFAULT) + +//********************************************************************************************** +//! Base texture class destructor +/*! KJM +*/ +TextureBaseClass::~TextureBaseClass(void) +{ + delete TextureLoadTask; + TextureLoadTask=NULL; + delete ThumbnailLoadTask; + ThumbnailLoadTask=NULL; + + if (D3DTexture) { - Dirty=true; - DX8TextureTrackerClass *track=W3DNEW DX8TextureTrackerClass - ( - width, - height, - format, - mip_level_count, - this, - rendertarget - ); - DX8TextureManagerClass::Add(track); + D3DTexture->Release(); + D3DTexture = NULL; } - LastAccessed=WW3D::Get_Sync_Time(); + + DX8TextureManagerClass::Remove(this); } -// ---------------------------------------------------------------------------- -TextureClass::TextureClass -( - const char *name, - const char *full_path, - MipCountType mip_level_count, - WW3DFormat texture_format, - bool allow_compression) - : - D3DTexture(NULL), - texture_id(unused_texture_id++), - Initialized(false), - Filter(mip_level_count), - MipLevelCount(mip_level_count), - Pool(POOL_MANAGED), - Dirty(false), - IsLightmap(false), - IsProcedural(false), - TextureFormat(texture_format), - IsCompressionAllowed(allow_compression), - TextureLoadTask(NULL), - Width(0), - Height(0) + + +//********************************************************************************************** +//! Invalidate old unused textures +/*! +*/ +void TextureBaseClass::Invalidate_Old_Unused_Textures(unsigned invalidation_time_override) { - switch (TextureFormat) - { - case WW3D_FORMAT_DXT1: - case WW3D_FORMAT_DXT2: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: - IsCompressionAllowed=true; - break; - case WW3D_FORMAT_U8V8: // Bumpmap - case WW3D_FORMAT_L6V5U5: // Bumpmap - case WW3D_FORMAT_X8L8V8U8: // Bumpmap - // If requesting bumpmap format that isn't available we'll just return the surface in whatever color - // format the texture file is in. (This is illegal case, the format support should always be queried - // before creating a bump texture!) - if (!DX8Wrapper::Get_Current_Caps()->Support_Texture_Format(TextureFormat)) - { - TextureFormat=WW3D_FORMAT_UNKNOWN; - } - // If bump format is valid, make sure compression is not allowed so that we don't even attempt to load - // from a compressed file (quality isn't good enough for bump map). Also disable mipmapping. - else - { - IsCompressionAllowed=false; - MipLevelCount=MIP_LEVELS_1; - Filter.Set_Mip_Mapping(TextureFilterClass::FILTER_TYPE_NONE); - } - break; - default: break; + // (gth) If thumbnails are not enabled, then we don't run this code. + if (WW3D::Get_Thumbnail_Enabled() == false) { + return; } - WWASSERT_PRINT(name && name[0], "TextureClass CTor: NULL or empty texture name"); - int len=strlen(name); - for (int i=0;i ite(WW3DAssetManager::Get_Instance()->Texture_Hash()); + // Loop through all the textures in the manager + + for (ite.First ();!ite.Is_Done();ite.Next ()) { - if (name[i]=='+') + TextureClass* tex=ite.Peek_Value(); + + // Consider invalidating if texture has been initialized and defines inactivation time + if (tex->Initialized && tex->InactivationTime) { - IsLightmap=true; + unsigned age=synctime-tex->LastAccessed; - // Set bilinear filtering for lightmaps (they are very stretched and - // low detail so we don't care for anisotropic or trilinear filtering...) - Filter.Set_Min_Filter(TextureFilterClass::FILTER_TYPE_FAST); - Filter.Set_Mag_Filter(TextureFilterClass::FILTER_TYPE_FAST); - if (mip_level_count!=MIP_LEVELS_1) Filter.Set_Mip_Mapping(TextureFilterClass::FILTER_TYPE_FAST); - break; + if (invalidation_time_override) + { + if (age>invalidation_time_override) + { + tex->Invalidate(); + tex->LastInactivationSyncTime=synctime; + } + } + else + { + // Not used in the last n milliseconds? + if (age>(tex->InactivationTime+tex->ExtendedInactivationTime)) + { + tex->Invalidate(); + tex->LastInactivationSyncTime=synctime; + } + } } } - Set_Texture_Name(name); - Set_Full_Path(full_path); - WWASSERT(name[0]!='\0'); - if (!WW3D::Is_Texturing_Enabled()) - { - Initialized=true; - D3DTexture=0; - } - else if (WW3D::Get_Thumbnail_Enabled()==false || mip_level_count==MIP_LEVELS_1) - { - Initialized=true; - D3DTexture=0; - TextureLoader::Request_High_Priority_Loading(this,mip_level_count); - } - else { - Load_Locked_Surface(); - TextureFormat=texture_format; // Locked surface may be in a wrong format - } - LastAccessed=WW3D::Get_Sync_Time(); } -// ---------------------------------------------------------------------------- -TextureClass::TextureClass(SurfaceClass *surface, MipCountType mip_level_count) - : - D3DTexture(NULL), - texture_id(unused_texture_id++), - Initialized(true), - Filter(mip_level_count), - MipLevelCount(mip_level_count), - Pool(POOL_MANAGED), - Dirty(false), - IsLightmap(false), - Name(""), - IsProcedural(true), - TextureFormat(surface->Get_Surface_Format()), - IsCompressionAllowed(false), - 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: - case WW3D_FORMAT_DXT2: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: - IsCompressionAllowed=true; - break; - default: break; - } - D3DTexture = DX8Wrapper::_Create_DX8_Texture(surface->Peek_D3D_Surface(), mip_level_count); - LastAccessed=WW3D::Get_Sync_Time(); -} -// ---------------------------------------------------------------------------- -TextureClass::TextureClass(IDirect3DTexture8* d3d_texture) - : - D3DTexture(d3d_texture), - texture_id(unused_texture_id++), - Initialized(true), - Filter((MipCountType)d3d_texture->GetLevelCount()), - MipLevelCount((MipCountType)d3d_texture->GetLevelCount()), - Pool(POOL_MANAGED), - Dirty(false), - IsLightmap(false), - Name(""), - IsProcedural(true), - IsCompressionAllowed(false), - TextureLoadTask(NULL), - Width(0), - Height(0) +//********************************************************************************************** +//! Invalidate this texture +/*! +*/ +void TextureBaseClass::Invalidate() { - D3DTexture->AddRef(); - IDirect3DSurface8* 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) - { - case WW3D_FORMAT_DXT1: - case WW3D_FORMAT_DXT2: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: - IsCompressionAllowed=true; - break; - default: break; + if (TextureLoadTask) { + return; + } + if (ThumbnailLoadTask) { + return; } - LastAccessed=WW3D::Get_Sync_Time(); -} - -// ---------------------------------------------------------------------------- - -TextureClass::~TextureClass(void) -{ - TextureLoadTaskClass::Release_Instance(TextureLoadTask); - TextureLoadTask=NULL; - - if (!Initialized) { - WWDEBUG_SAY(("Warning: Texture %s was loaded but never used",Get_Texture_Name().str())); + // Don't invalidate procedural textures + if (IsProcedural) { + return; } - if (D3DTexture) { + if (D3DTexture) + { D3DTexture->Release(); D3DTexture = NULL; } - DX8TextureManagerClass::Remove(this); -} - -// ---------------------------------------------------------------------------- -void TextureClass::Init() -{ - // If the texture has already been initialised we should exit now - if (Initialized) return; + Initialized=false; - TextureLoader::Add_Load_Task(this); LastAccessed=WW3D::Get_Sync_Time(); -} +/* was battlefield version// If the texture has already been initialised we should exit now + if (Initialized) return; -void TextureClass::Invalidate() -{ - // Don't invalidate procedural textures - if (IsProcedural) return; + WWPROFILE(("TextureClass::Init()")); - // Don't invalidate missing texture - if (Is_Missing_Texture()) return; + // If the texture has recently been inactivated, increase the inactivation time (this texture obviously + // should not have been inactivated yet). - if (D3DTexture) { - D3DTexture->Release(); - D3DTexture = NULL; + if (InactivationTime && LastInactivationSyncTime) { + if ((WW3D::Get_Sync_Time()-LastInactivationSyncTime)Release(); + D3DTexture = NULL; } + + Initialized=false; + + LastAccessed=WW3D::Get_Sync_Time();*/ } //********************************************************************************************** //! Returns a pointer to the d3d texture /*! */ -IDirect3DBaseTexture8 * TextureClass::Peek_D3D_Base_Texture() const +IDirect3DBaseTexture8 * TextureBaseClass::Peek_D3D_Base_Texture() const { LastAccessed=WW3D::Get_Sync_Time(); return D3DTexture; @@ -383,7 +261,7 @@ IDirect3DBaseTexture8 * TextureClass::Peek_D3D_Base_Texture() const //! Set the d3d texture pointer. Handles ref counts properly. /*! */ -void TextureClass::Set_D3D_Base_Texture(IDirect3DBaseTexture8* tex) +void TextureBaseClass::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. @@ -398,212 +276,176 @@ void TextureClass::Set_D3D_Base_Texture(IDirect3DBaseTexture8* tex) } } -// ---------------------------------------------------------------------------- -void TextureClass::Load_Locked_Surface() +//********************************************************************************************** +//! Load locked surface +/*! +*/ +void TextureBaseClass::Load_Locked_Surface() { + WWPROFILE(("TextureClass::Load_Locked_Surface()")); if (D3DTexture) D3DTexture->Release(); D3DTexture=0; TextureLoader::Request_Thumbnail(this); Initialized=false; } -// ---------------------------------------------------------------------------- -bool TextureClass::Is_Missing_Texture() +//********************************************************************************************** +//! Is missing texture +/*! +*/ +bool TextureBaseClass::Is_Missing_Texture() { bool flag = false; - IDirect3DTexture8 *missing_texture = MissingTexture::_Get_Missing_Texture(); + IDirect3DBaseTexture8 *missing_texture = MissingTexture::_Get_Missing_Texture(); - if(D3DTexture == missing_texture) + if (D3DTexture == missing_texture) flag = true; - if(missing_texture) + if (missing_texture) + { missing_texture->Release(); + } return flag; } -// ---------------------------------------------------------------------------- -void TextureClass::Set_Texture_Name(const char * name) +//********************************************************************************************** +//! Set texture name +/*! +*/ +void TextureBaseClass::Set_Texture_Name(const char * name) { Name=name; } -// ---------------------------------------------------------------------------- - -unsigned int TextureClass::Get_Mip_Level_Count(void) -{ - if (!D3DTexture) { - WWASSERT_PRINT(0, "Get_Mip_Level_Count: D3DTexture is NULL!"); - return 0; - } - - return D3DTexture->GetLevelCount(); -} - -// ---------------------------------------------------------------------------- - -void TextureClass::Get_Level_Description(SurfaceClass::SurfaceDescription &surface_desc, unsigned int level) -{ - if (!D3DTexture) { - WWASSERT_PRINT(0, "Get_Surface_Description: D3DTexture is NULL!"); - } - - D3DSURFACE_DESC 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; -} - -// ---------------------------------------------------------------------------- -SurfaceClass *TextureClass::Get_Surface_Level(unsigned int level) -{ - IDirect3DSurface8 *d3d_surface = NULL; - DX8_ErrorCode(Peek_D3D_Texture()->GetSurfaceLevel(level, &d3d_surface)); - SurfaceClass *surface = W3DNEW SurfaceClass(d3d_surface); - d3d_surface->Release(); - return surface; -} -// ---------------------------------------------------------------------------- -unsigned int TextureClass::Get_Priority(void) +//********************************************************************************************** +//! Get priority +/*! +*/ +unsigned int TextureBaseClass::Get_Priority(void) { - if (!D3DTexture) { + if (!D3DTexture) + { WWASSERT_PRINT(0, "Get_Priority: D3DTexture is NULL!"); return 0; } +#ifndef _XBOX return D3DTexture->GetPriority(); +#else + return 0; +#endif } -// ---------------------------------------------------------------------------- -unsigned int TextureClass::Set_Priority(unsigned int priority) +//********************************************************************************************** +//! Set priority +/*! +*/ +unsigned int TextureBaseClass::Set_Priority(unsigned int priority) { - if (!D3DTexture) { + if (!D3DTexture) + { WWASSERT_PRINT(0, "Set_Priority: D3DTexture is NULL!"); return 0; } +#ifndef _XBOX return D3DTexture->SetPriority(priority); +#else + return 0; +#endif } -unsigned TextureClass::Get_Reduction() const + +//********************************************************************************************** +//! Get reduction mip levels +/*! +*/ +unsigned TextureBaseClass::Get_Reduction() const { + // don't reduce if the texture is too small already or + // has no mip map levels if (MipLevelCount==MIP_LEVELS_1) return 0; + if (Width <= 32 || Height <= 32) return 0; int reduction=WW3D::Get_Texture_Reduction(); + + // 'large texture extra reduction' causes textures above 256x256 to be reduced one more step. + if (WW3D::Is_Large_Texture_Extra_Reduction_Enabled() && (Width > 256 || Height > 256)) { + reduction++; + } if (MipLevelCount && reduction>MipLevelCount) { reduction=MipLevelCount; } return reduction; } -// ---------------------------------------------------------------------------- - -void TextureClass::Apply(unsigned int stage) -{ - if (!Initialized) - { - Init(); - } - LastAccessed=WW3D::Get_Sync_Time(); - - DX8_RECORD_TEXTURE(this); - - // Set texture itself - if (WW3D::Is_Texturing_Enabled()) - { - DX8Wrapper::Set_DX8_Texture(stage, D3DTexture); - } - else - { - DX8Wrapper::Set_DX8_Texture(stage, NULL); - } - - Filter.Apply(stage); -} -// ---------------------------------------------------------------------------- -void TextureClass::Apply_Null(unsigned int stage) +//********************************************************************************************** +//! Apply NULL texture state +/*! +*/ +void TextureBaseClass::Apply_Null(unsigned int stage) { // This function sets the render states for a "NULL" texture DX8Wrapper::Set_DX8_Texture(stage, NULL); } // ---------------------------------------------------------------------------- - -void TextureClass::Apply_New_Surface(bool initialized) -{ - if (D3DTexture) D3DTexture->Release(); - D3DTexture=TextureLoadTask->Peek_D3D_Texture(); - D3DTexture->AddRef(); - if (initialized) Initialized=true; - - WWASSERT(D3DTexture); - IDirect3DSurface8* 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); -// } - surface->Release(); -} - +// Setting HSV_Shift value is always relative to the original texture. This function invalidates the +// texture surface and causes the texture to be reloaded. For thumbnailable textures, the hue shifting +// is done in the background loading thread. // ---------------------------------------------------------------------------- - -unsigned TextureClass::Get_Texture_Memory_Usage() const +void TextureBaseClass::Set_HSV_Shift(const Vector3 &hsv_shift) { - if (/*!ReductionEnabled || */!Initialized) return Calculate_Texture_Memory_Usage(this,0); -// unsigned reduction=WW3D::Get_Texture_Reduction(); -// if (CurrentReductionFactor>reduction) reduction=CurrentReductionFactor; - return Calculate_Texture_Memory_Usage(this,0);//reduction); + Invalidate(); + HSVShift=hsv_shift; } -// ---------------------------------------------------------------------------- - -int TextureClass::_Get_Total_Locked_Surface_Size() +//********************************************************************************************** +//! Get total locked surface size +/*! KM +*/ +int TextureBaseClass::_Get_Total_Locked_Surface_Size() { int total_locked_surface_size=0; HashTemplateIterator ite(WW3DAssetManager::Get_Instance()->Texture_Hash()); // Loop through all the textures in the manager - for (ite.First ();!ite.Is_Done();ite.Next ()) { - + for (ite.First ();!ite.Is_Done();ite.Next ()) + { // Get the current texture - TextureClass* tex=ite.Peek_Value(); - if (!tex->Initialized) { -// total_locked_surface_size+=tex->Get_Non_Reduced_Texture_Memory_Usage(); + TextureBaseClass* tex=ite.Peek_Value(); + if (!tex->Initialized) + { total_locked_surface_size+=tex->Get_Texture_Memory_Usage(); } } return total_locked_surface_size; } -// ---------------------------------------------------------------------------- - -int TextureClass::_Get_Total_Texture_Size() +//********************************************************************************************** +//! Get total texture size +/*! KM +*/ +int TextureBaseClass::_Get_Total_Texture_Size() { int total_texture_size=0; HashTemplateIterator ite(WW3DAssetManager::Get_Instance()->Texture_Hash()); // Loop through all the textures in the manager - for (ite.First ();!ite.Is_Done();ite.Next ()) { + for (ite.First ();!ite.Is_Done();ite.Next ()) + { // Get the current texture - TextureClass* tex=ite.Peek_Value(); + TextureBaseClass* tex=ite.Peek_Value(); total_texture_size+=tex->Get_Texture_Memory_Usage(); } return total_texture_size; @@ -611,49 +453,64 @@ int TextureClass::_Get_Total_Texture_Size() // ---------------------------------------------------------------------------- -int TextureClass::_Get_Total_Lightmap_Texture_Size() + +//********************************************************************************************** +//! Get total lightmap texture size +/*! +*/ +int TextureBaseClass::_Get_Total_Lightmap_Texture_Size() { int total_texture_size=0; HashTemplateIterator ite(WW3DAssetManager::Get_Instance()->Texture_Hash()); // Loop through all the textures in the manager - for (ite.First ();!ite.Is_Done();ite.Next ()) { + for (ite.First ();!ite.Is_Done();ite.Next ()) + { // Get the current texture - TextureClass* tex=ite.Peek_Value(); - if (tex->Is_Lightmap()) { + TextureBaseClass* tex=ite.Peek_Value(); + if (tex->Is_Lightmap()) + { total_texture_size+=tex->Get_Texture_Memory_Usage(); } } return total_texture_size; } -// ---------------------------------------------------------------------------- -int TextureClass::_Get_Total_Procedural_Texture_Size() +//********************************************************************************************** +//! Get total procedural texture size +/*! +*/ +int TextureBaseClass::_Get_Total_Procedural_Texture_Size() { int total_texture_size=0; HashTemplateIterator ite(WW3DAssetManager::Get_Instance()->Texture_Hash()); // Loop through all the textures in the manager - for (ite.First ();!ite.Is_Done();ite.Next ()) { + for (ite.First ();!ite.Is_Done();ite.Next ()) + { // Get the current texture - TextureClass* tex=ite.Peek_Value(); - if (tex->Is_Procedural()) { + TextureBaseClass* tex=ite.Peek_Value(); + if (tex->Is_Procedural()) + { total_texture_size+=tex->Get_Texture_Memory_Usage(); } } return total_texture_size; } -// ---------------------------------------------------------------------------- - -int TextureClass::_Get_Total_Texture_Count() +//********************************************************************************************** +//! Get total texture count +/*! +*/ +int TextureBaseClass::_Get_Total_Texture_Count() { int texture_count=0; HashTemplateIterator ite(WW3DAssetManager::Get_Instance()->Texture_Hash()); // Loop through all the textures in the manager - for (ite.First ();!ite.Is_Done();ite.Next ()) { + for (ite.First ();!ite.Is_Done();ite.Next ()) + { texture_count++; } @@ -662,14 +519,21 @@ int TextureClass::_Get_Total_Texture_Count() // ---------------------------------------------------------------------------- -int TextureClass::_Get_Total_Lightmap_Texture_Count() + +//********************************************************************************************** +//! Get total light map texture count +/*! +*/ +int TextureBaseClass::_Get_Total_Lightmap_Texture_Count() { int texture_count=0; HashTemplateIterator ite(WW3DAssetManager::Get_Instance()->Texture_Hash()); // Loop through all the textures in the manager - for (ite.First ();!ite.Is_Done();ite.Next ()) { - if (ite.Peek_Value()->Is_Lightmap()) { + for (ite.First ();!ite.Is_Done();ite.Next ()) + { + if (ite.Peek_Value()->Is_Lightmap()) + { texture_count++; } } @@ -677,16 +541,20 @@ int TextureClass::_Get_Total_Lightmap_Texture_Count() return texture_count; } -// ---------------------------------------------------------------------------- - -int TextureClass::_Get_Total_Procedural_Texture_Count() +//********************************************************************************************** +//! Get total procedural texture count +/*! +*/ +int TextureBaseClass::_Get_Total_Procedural_Texture_Count() { int texture_count=0; HashTemplateIterator ite(WW3DAssetManager::Get_Instance()->Texture_Hash()); // Loop through all the textures in the manager - for (ite.First ();!ite.Is_Done();ite.Next ()) { - if (ite.Peek_Value()->Is_Procedural()) { + for (ite.First ();!ite.Is_Done();ite.Next ()) + { + if (ite.Peek_Value()->Is_Procedural()) + { texture_count++; } } @@ -694,199 +562,1347 @@ int TextureClass::_Get_Total_Procedural_Texture_Count() return texture_count; } -// ---------------------------------------------------------------------------- -int TextureClass::_Get_Total_Locked_Surface_Count() +//********************************************************************************************** +//! Get total locked surface count +/*! +*/ +int TextureBaseClass::_Get_Total_Locked_Surface_Count() { int texture_count=0; HashTemplateIterator ite(WW3DAssetManager::Get_Instance()->Texture_Hash()); // Loop through all the textures in the manager - for (ite.First ();!ite.Is_Done();ite.Next ()) { + for (ite.First ();!ite.Is_Done();ite.Next ()) + { // Get the current texture - TextureClass* tex=ite.Peek_Value(); - if (!tex->Initialized) { + TextureBaseClass* tex=ite.Peek_Value(); + if (!tex->Initialized) + { texture_count++; } } return texture_count; } -/* -bool Validate_Filters(unsigned type) -{ - ShaderClass shader=ShaderClass::_PresetOpaqueShader; - shader.Apply(); - DX8Wrapper::Set_DX8_Texture(0, MissingTexture::_Get_Missing_Texture()); - DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_MINFILTER,_MinTextureFilters[type]); - DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_MAGFILTER,_MagTextureFilters[type]); - DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_MIPFILTER,_MipMapFilters[type]); - unsigned long passes; - HRESULT hres=DX8Wrapper::_Get_D3D_Device8()->ValidateDevice(&passes); - return !FAILED(hres); -} -*/ - -// Utility functions -TextureClass* Load_Texture(ChunkLoadClass & cload) +/************************************************************************* +** TextureClass +*************************************************************************/ +TextureClass::TextureClass +( + unsigned width, + unsigned height, + WW3DFormat format, + MipCountType mip_level_count, + PoolType pool, + bool rendertarget, + bool allow_reduction +) +: TextureBaseClass(width, height, mip_level_count, pool, rendertarget,allow_reduction), + Filter(mip_level_count), + TextureFormat(format) { - // Assume failure - TextureClass *newtex = NULL; + Initialized=true; + IsProcedural=true; + IsReducible=false; - char name[256]; - if (cload.Open_Chunk () && (cload.Cur_Chunk_ID () == W3D_CHUNK_TEXTURE)) + switch (format) { + case WW3D_FORMAT_DXT1: + case WW3D_FORMAT_DXT2: + case WW3D_FORMAT_DXT3: + case WW3D_FORMAT_DXT4: + case WW3D_FORMAT_DXT5: + IsCompressionAllowed=true; + break; + default : break; + } - W3dTextureInfoStruct texinfo; - bool hastexinfo = false; - - /* - ** Read in the texture filename, and a possible texture info structure. - */ - while (cload.Open_Chunk()) { - switch (cload.Cur_Chunk_ID()) { - case W3D_CHUNK_TEXTURE_NAME: - cload.Read(&name,cload.Cur_Chunk_Length()); - break; - - case W3D_CHUNK_TEXTURE_INFO: - cload.Read(&texinfo,sizeof(W3dTextureInfoStruct)); - hastexinfo = true; - break; - }; - cload.Close_Chunk(); - } - cload.Close_Chunk(); - - /* - ** Get the texture from the asset manager - */ - if (hastexinfo) - { - - MipCountType mipcount; - - bool no_lod = ((texinfo.Attributes & W3DTEXTURE_NO_LOD) == W3DTEXTURE_NO_LOD); + D3DPOOL d3dpool=(D3DPOOL)0; + switch(pool) + { + case POOL_DEFAULT : d3dpool=D3DPOOL_DEFAULT; break; + case POOL_MANAGED : d3dpool=D3DPOOL_MANAGED; break; + case POOL_SYSTEMMEM : d3dpool=D3DPOOL_SYSTEMMEM; break; + default: WWASSERT(0); + } - if (no_lod) - { - mipcount = MIP_LEVELS_1; - } - else - { - switch (texinfo.Attributes & W3DTEXTURE_MIP_LEVELS_MASK) { + Poke_Texture + ( + DX8Wrapper::_Create_DX8_Texture + ( + width, + height, + format, + mip_level_count, + d3dpool, + rendertarget + ) + ); - case W3DTEXTURE_MIP_LEVELS_ALL: - mipcount = MIP_LEVELS_ALL; - break; + if (pool==POOL_DEFAULT) + { + Set_Dirty(); + DX8TextureTrackerClass *track=new DX8TextureTrackerClass + ( + width, + height, + format, + mip_level_count, + this, + rendertarget + ); + DX8TextureManagerClass::Add(track); + } + LastAccessed=WW3D::Get_Sync_Time(); +} - case W3DTEXTURE_MIP_LEVELS_2: - mipcount = MIP_LEVELS_2; - break; - case W3DTEXTURE_MIP_LEVELS_3: - mipcount = MIP_LEVELS_3; - break; - case W3DTEXTURE_MIP_LEVELS_4: - mipcount = MIP_LEVELS_4; - break; +// ---------------------------------------------------------------------------- +TextureClass::TextureClass +( + const char *name, + const char *full_path, + MipCountType mip_level_count, + WW3DFormat texture_format, + bool allow_compression, + bool allow_reduction +) +: TextureBaseClass(0, 0, mip_level_count), + Filter(mip_level_count), + TextureFormat(texture_format) +{ + IsCompressionAllowed=allow_compression; + InactivationTime=DEFAULT_INACTIVATION_TIME; // Default inactivation time 30 seconds + IsReducible=allow_reduction; - default: - WWASSERT (false); - mipcount = MIP_LEVELS_ALL; - break; + switch (TextureFormat) + { + case WW3D_FORMAT_DXT1: + case WW3D_FORMAT_DXT2: + case WW3D_FORMAT_DXT3: + case WW3D_FORMAT_DXT4: + case WW3D_FORMAT_DXT5: + IsCompressionAllowed=true; + break; + case WW3D_FORMAT_U8V8: // Bumpmap + case WW3D_FORMAT_L6V5U5: // Bumpmap + case WW3D_FORMAT_X8L8V8U8: // Bumpmap + // If requesting bumpmap format that isn't available we'll just return the surface in whatever color + // format the texture file is in. (This is illegal case, the format support should always be queried + // before creating a bump texture!) + if (!DX8Wrapper::Is_Initted() || !DX8Wrapper::Get_Current_Caps()->Support_Texture_Format(TextureFormat)) + { + TextureFormat=WW3D_FORMAT_UNKNOWN; + } + // If bump format is valid, make sure compression is not allowed so that we don't even attempt to load + // from a compressed file (quality isn't good enough for bump map). Also disable mipmapping. + else + { + IsCompressionAllowed=false; + MipLevelCount=MIP_LEVELS_1; + Filter.Set_Mip_Mapping(TextureFilterClass::FILTER_TYPE_NONE); + } + break; + default: break; + } + + WWASSERT_PRINT(name && name[0], "TextureClass CTor: NULL or empty texture name"); + int len=strlen(name); + for (int i=0;iGet_Original_Texture_Width(); + Height=thumb->Get_Original_Texture_Height(); + if (MipLevelCount!=MIP_LEVELS_1) { + MipLevelCount=(MipCountType)thumb->Get_Original_Texture_Mip_Level_Count(); + } + } + + LastAccessed=WW3D::Get_Sync_Time(); + + // If the thumbnails are not enabled, init the texture at this point to avoid stalling when the + // mesh is rendered. + if (!WW3D::Get_Thumbnail_Enabled()) + { + if (TextureLoader::Is_DX8_Thread()) + { + Init(); + } + } +} + +// ---------------------------------------------------------------------------- +TextureClass::TextureClass +( + SurfaceClass *surface, + MipCountType mip_level_count +) +: TextureBaseClass(0,0,mip_level_count), + Filter(mip_level_count), + TextureFormat(surface->Get_Surface_Format()) +{ + IsProcedural=true; + Initialized=true; + IsReducible=false; + + SurfaceClass::SurfaceDescription sd; + surface->Get_Description(sd); + Width=sd.Width; + Height=sd.Height; + switch (sd.Format) + { + case WW3D_FORMAT_DXT1: + case WW3D_FORMAT_DXT2: + case WW3D_FORMAT_DXT3: + case WW3D_FORMAT_DXT4: + case WW3D_FORMAT_DXT5: + IsCompressionAllowed=true; + break; + default: break; + } + + Poke_Texture + ( + DX8Wrapper::_Create_DX8_Texture + ( + surface->Peek_D3D_Surface(), + mip_level_count + ) + ); + LastAccessed=WW3D::Get_Sync_Time(); +} + +// ---------------------------------------------------------------------------- +TextureClass::TextureClass(IDirect3DBaseTexture8* d3d_texture) +: TextureBaseClass + ( + 0, + 0, + ((MipCountType)d3d_texture->GetLevelCount()) + ), + Filter((MipCountType)d3d_texture->GetLevelCount()) +{ + Initialized=true; + IsProcedural=true; + IsReducible=false; + + Set_D3D_Base_Texture(d3d_texture); + IDirect3DSurface8* 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) + { + case WW3D_FORMAT_DXT1: + case WW3D_FORMAT_DXT2: + case WW3D_FORMAT_DXT3: + case WW3D_FORMAT_DXT4: + case WW3D_FORMAT_DXT5: + IsCompressionAllowed=true; + break; + default: break; + } + + LastAccessed=WW3D::Get_Sync_Time(); +} + +//********************************************************************************************** +//! Initialise the texture +/*! +*/ +void TextureClass::Init() +{ + // If the texture has already been initialised we should exit now + if (Initialized) return; + + WWPROFILE("TextureClass::Init"); + + // If the texture has recently been inactivated, increase the inactivation time (this texture obviously + // should not have been inactivated yet). + if (InactivationTime && LastInactivationSyncTime) + { + if ((WW3D::Get_Sync_Time()-LastInactivationSyncTime)Release(); + + Poke_Texture(d3d_texture);//TextureLoadTask->Peek_D3D_Texture(); + d3d_texture->AddRef(); + + if (initialized) Initialized=true; + if (disable_auto_invalidation) InactivationTime = 0; + + WWASSERT(d3d_texture); + IDirect3DSurface8* 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 (initialized) + { + TextureFormat=D3DFormat_To_WW3DFormat(d3d_desc.Format); + Width=d3d_desc.Width; + Height=d3d_desc.Height; + } + surface->Release(); + +} + + +//********************************************************************************************** +//! Apply texture states +/*! +*/ +void TextureClass::Apply(unsigned int stage) +{ + // Initialization needs to be done when texture is used if it hasn't been done before. + // XBOX always initializes textures at creation time. + if (!Initialized) + { + Init(); + + /* was in battlefield// Non-thumbnailed textures are always initialized when used + if (MipLevelCount==MIP_LEVELS_1) + { + } + // Thumbnailed textures have delayed initialization and a background loading system + else + { + // Limit the number of texture initializations per frame to reduce stuttering + if (TexturesAppliedPerFrameGet_Texture (name, mipcount); + }*/ + } + LastAccessed=WW3D::Get_Sync_Time(); + + DX8_RECORD_TEXTURE(this); + + // Set texture itself + if (WW3D::Is_Texturing_Enabled()) + { + DX8Wrapper::Set_DX8_Texture(stage, Peek_D3D_Base_Texture()); + } + else + { + DX8Wrapper::Set_DX8_Texture(stage, NULL); + } + + Filter.Apply(stage); +} + +//********************************************************************************************** +//! Get surface from mip level +/*! +*/ +SurfaceClass *TextureClass::Get_Surface_Level(unsigned int level) +{ + if (!Peek_D3D_Texture()) + { + WWASSERT_PRINT(0, "Get_Surface_Level: D3DTexture is NULL!"); + return 0; + } + + IDirect3DSurface8 *d3d_surface = NULL; + DX8_ErrorCode(Peek_D3D_Texture()->GetSurfaceLevel(level, &d3d_surface)); + SurfaceClass *surface = new SurfaceClass(d3d_surface); + d3d_surface->Release(); + + return surface; +} + +//********************************************************************************************** +//! Get surface description for a mip level +/*! +*/ +void TextureClass::Get_Level_Description( SurfaceClass::SurfaceDescription & desc, unsigned int level ) +{ + SurfaceClass * surf = Get_Surface_Level(level); + if (surf != NULL) { + surf->Get_Description(desc); + } + REF_PTR_RELEASE(surf); +} + +//********************************************************************************************** +//! Get D3D surface from mip level +/*! +*/ +IDirect3DSurface8 *TextureClass::Get_D3D_Surface_Level(unsigned int level) +{ + if (!Peek_D3D_Texture()) + { + WWASSERT_PRINT(0, "Get_D3D_Surface_Level: D3DTexture is NULL!"); + return 0; + } + + IDirect3DSurface8 *d3d_surface = NULL; + DX8_ErrorCode(Peek_D3D_Texture()->GetSurfaceLevel(level, &d3d_surface)); + return d3d_surface; +} + +//********************************************************************************************** +//! Get texture memory usage +/*! +*/ +unsigned TextureClass::Get_Texture_Memory_Usage() const +{ + int size=0; + if (!Peek_D3D_Texture()) return 0; + for (unsigned i=0;iGetLevelCount();++i) + { + D3DSURFACE_DESC desc; + DX8_ErrorCode(Peek_D3D_Texture()->GetLevelDesc(i,&desc)); + size+=desc.Size; + } + return size; +} + + +// Utility functions +TextureClass* Load_Texture(ChunkLoadClass & cload) +{ + // Assume failure + TextureClass *newtex = NULL; + + char name[256]; + if (cload.Open_Chunk () && (cload.Cur_Chunk_ID () == W3D_CHUNK_TEXTURE)) + { + + W3dTextureInfoStruct texinfo; + bool hastexinfo = false; + + /* + ** Read in the texture filename, and a possible texture info structure. + */ + while (cload.Open_Chunk()) { + switch (cload.Cur_Chunk_ID()) { + case W3D_CHUNK_TEXTURE_NAME: + cload.Read(&name,cload.Cur_Chunk_Length()); + break; + + case W3D_CHUNK_TEXTURE_INFO: + cload.Read(&texinfo,sizeof(W3dTextureInfoStruct)); + hastexinfo = true; + break; + }; + cload.Close_Chunk(); + } + cload.Close_Chunk(); + + /* + ** Get the texture from the asset manager + */ + if (hastexinfo) + { + + MipCountType mipcount; + + bool no_lod = ((texinfo.Attributes & W3DTEXTURE_NO_LOD) == W3DTEXTURE_NO_LOD); + + if (no_lod) + { + mipcount = MIP_LEVELS_1; + } + else + { + switch (texinfo.Attributes & W3DTEXTURE_MIP_LEVELS_MASK) { + + case W3DTEXTURE_MIP_LEVELS_ALL: + mipcount = MIP_LEVELS_ALL; + break; + + case W3DTEXTURE_MIP_LEVELS_2: + mipcount = MIP_LEVELS_2; + break; + + case W3DTEXTURE_MIP_LEVELS_3: + mipcount = MIP_LEVELS_3; + break; + + case W3DTEXTURE_MIP_LEVELS_4: + mipcount = MIP_LEVELS_4; + break; + + default: + WWASSERT (false); + mipcount = MIP_LEVELS_ALL; + break; + } + } + + WW3DFormat format=WW3D_FORMAT_UNKNOWN; + + switch (texinfo.Attributes & W3DTEXTURE_TYPE_MASK) + { + + case W3DTEXTURE_TYPE_COLORMAP: + // Do nothing. + break; + + case W3DTEXTURE_TYPE_BUMPMAP: + { + if (DX8Wrapper::Is_Initted() && DX8Wrapper::Get_Current_Caps()->Support_Bump_Envmap()) + { + // No mipmaps to bumpmap for now + mipcount=MIP_LEVELS_1; + + if (DX8Wrapper::Get_Current_Caps()->Support_Texture_Format(WW3D_FORMAT_U8V8)) format=WW3D_FORMAT_U8V8; + else if (DX8Wrapper::Get_Current_Caps()->Support_Texture_Format(WW3D_FORMAT_X8L8V8U8)) format=WW3D_FORMAT_X8L8V8U8; + else if (DX8Wrapper::Get_Current_Caps()->Support_Texture_Format(WW3D_FORMAT_L6V5U5)) format=WW3D_FORMAT_L6V5U5; + } + break; + } + + default: + WWASSERT (false); + break; + } + + newtex = WW3DAssetManager::Get_Instance()->Get_Texture (name, mipcount, format); + + if (no_lod) + { + newtex->Get_Filter().Set_Mip_Mapping(TextureFilterClass::FILTER_TYPE_NONE); + } + bool u_clamp = ((texinfo.Attributes & W3DTEXTURE_CLAMP_U) != 0); + newtex->Get_Filter().Set_U_Addr_Mode(u_clamp ? TextureFilterClass::TEXTURE_ADDRESS_CLAMP : TextureFilterClass::TEXTURE_ADDRESS_REPEAT); + bool v_clamp = ((texinfo.Attributes & W3DTEXTURE_CLAMP_V) != 0); + newtex->Get_Filter().Set_V_Addr_Mode(v_clamp ? TextureFilterClass::TEXTURE_ADDRESS_CLAMP : TextureFilterClass::TEXTURE_ADDRESS_REPEAT); + + } else + { + newtex = WW3DAssetManager::Get_Instance()->Get_Texture(name); + } + + WWASSERT(newtex); + } + + // Return a pointer to the new texture + return newtex; +} + +// Utility function used by Save_Texture +void setup_texture_attributes(TextureClass * tex, W3dTextureInfoStruct * texinfo) +{ + texinfo->Attributes = 0; + + if (tex->Get_Filter().Get_Mip_Mapping() == TextureFilterClass::FILTER_TYPE_NONE) texinfo->Attributes |= W3DTEXTURE_NO_LOD; + if (tex->Get_Filter().Get_U_Addr_Mode() == TextureFilterClass::TEXTURE_ADDRESS_CLAMP) texinfo->Attributes |= W3DTEXTURE_CLAMP_U; + if (tex->Get_Filter().Get_V_Addr_Mode() == TextureFilterClass::TEXTURE_ADDRESS_CLAMP) texinfo->Attributes |= W3DTEXTURE_CLAMP_V; +} + + +void Save_Texture(TextureClass * texture,ChunkSaveClass & csave) +{ + const char * filename; + W3dTextureInfoStruct texinfo; + memset(&texinfo,0,sizeof(texinfo)); + + filename = texture->Get_Full_Path(); + + setup_texture_attributes(texture, &texinfo); + + csave.Begin_Chunk(W3D_CHUNK_TEXTURE_NAME); + csave.Write(filename,strlen(filename)+1); + csave.End_Chunk(); + + if ((texinfo.Attributes != 0) || (texinfo.AnimType != 0) || (texinfo.FrameCount != 0)) { + csave.Begin_Chunk(W3D_CHUNK_TEXTURE_INFO); + csave.Write(&texinfo, sizeof(texinfo)); + csave.End_Chunk(); + } +} + + +/*! + * KJM depth stencil texture constructor + */ +ZTextureClass::ZTextureClass +( + unsigned width, + unsigned height, + WW3DZFormat zformat, + MipCountType mip_level_count, + PoolType pool +) +: TextureBaseClass(width,height, mip_level_count, pool), + DepthStencilTextureFormat(zformat) +{ + D3DPOOL d3dpool=(D3DPOOL)0; + switch (pool) + { + case POOL_DEFAULT: d3dpool=D3DPOOL_DEFAULT; break; + case POOL_MANAGED: d3dpool=D3DPOOL_MANAGED; break; + case POOL_SYSTEMMEM: d3dpool=D3DPOOL_SYSTEMMEM; break; + default: WWASSERT(0); + } + + Poke_Texture + ( + DX8Wrapper::_Create_DX8_ZTexture + ( + width, + height, + zformat, + mip_level_count, + d3dpool + ) + ); + + if (pool==POOL_DEFAULT) + { + Set_Dirty(); + DX8ZTextureTrackerClass *track=new DX8ZTextureTrackerClass + ( + width, + height, + zformat, + mip_level_count, + this + ); + DX8TextureManagerClass::Add(track); + } + Initialized=true; + IsProcedural=true; + IsReducible=false; + + LastAccessed=WW3D::Get_Sync_Time(); +} + + +//********************************************************************************************** +//! Apply depth stencil texture +/*! KM +*/ +void ZTextureClass::Apply(unsigned int stage) +{ + DX8Wrapper::Set_DX8_Texture(stage, Peek_D3D_Base_Texture()); +} + +//********************************************************************************************** +//! Apply new surface to texture +/*! KM +*/ +void ZTextureClass::Apply_New_Surface +( + IDirect3DBaseTexture8* d3d_texture, + bool initialized, + bool disable_auto_invalidation +) +{ + IDirect3DBaseTexture8* d3d_tex=Peek_D3D_Base_Texture(); + + if (d3d_tex) d3d_tex->Release(); + + Poke_Texture(d3d_texture);//TextureLoadTask->Peek_D3D_Texture(); + d3d_texture->AddRef(); + + if (initialized) Initialized=true; + if (disable_auto_invalidation) InactivationTime = 0; + + WWASSERT(Peek_D3D_Texture()); + IDirect3DSurface8* 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 (initialized) + { + DepthStencilTextureFormat=D3DFormat_To_WW3DZFormat(d3d_desc.Format); + Width=d3d_desc.Width; + Height=d3d_desc.Height; + } + surface->Release(); +} + +//********************************************************************************************** +//! Get D3D surface from mip level +/*! +*/ +IDirect3DSurface8* ZTextureClass::Get_D3D_Surface_Level(unsigned int level) +{ + if (!Peek_D3D_Texture()) + { + WWASSERT_PRINT(0, "Get_D3D_Surface_Level: D3DTexture is NULL!"); + return 0; + } + + IDirect3DSurface8 *d3d_surface = NULL; + DX8_ErrorCode(Peek_D3D_Texture()->GetSurfaceLevel(level, &d3d_surface)); + return d3d_surface; +} + +//********************************************************************************************** +//! Get texture memory usage +/*! +*/ +unsigned ZTextureClass::Get_Texture_Memory_Usage() const +{ + int size=0; + if (!Peek_D3D_Texture()) return 0; + for (unsigned i=0;iGetLevelCount();++i) + { + D3DSURFACE_DESC desc; + DX8_ErrorCode(Peek_D3D_Texture()->GetLevelDesc(i,&desc)); + size+=desc.Size; + } + return size; +} + + + +/************************************************************************* +** CubeTextureClass +*************************************************************************/ +CubeTextureClass::CubeTextureClass +( + unsigned width, + unsigned height, + WW3DFormat format, + MipCountType mip_level_count, + PoolType pool, + bool rendertarget, + bool allow_reduction +) +: TextureClass(width, height, format, mip_level_count, pool, rendertarget) +{ + Initialized=true; + IsProcedural=true; + IsReducible=false; + + switch (format) + { + case WW3D_FORMAT_DXT1: + case WW3D_FORMAT_DXT2: + case WW3D_FORMAT_DXT3: + case WW3D_FORMAT_DXT4: + case WW3D_FORMAT_DXT5: + IsCompressionAllowed=true; + break; + default : break; + } + + D3DPOOL d3dpool=(D3DPOOL)0; + switch(pool) + { + case POOL_DEFAULT : d3dpool=D3DPOOL_DEFAULT; break; + case POOL_MANAGED : d3dpool=D3DPOOL_MANAGED; break; + case POOL_SYSTEMMEM : d3dpool=D3DPOOL_SYSTEMMEM; break; + default: WWASSERT(0); + } + + Poke_Texture + ( + DX8Wrapper::_Create_DX8_Cube_Texture + ( + width, + height, + format, + mip_level_count, + d3dpool, + rendertarget + ) + ); + + if (pool==POOL_DEFAULT) + { + Set_Dirty(); + DX8TextureTrackerClass *track=new DX8TextureTrackerClass + ( + width, + height, + format, + mip_level_count, + this, + rendertarget + ); + DX8TextureManagerClass::Add(track); + } + LastAccessed=WW3D::Get_Sync_Time(); +} + + + +// ---------------------------------------------------------------------------- +CubeTextureClass::CubeTextureClass +( + const char *name, + const char *full_path, + MipCountType mip_level_count, + WW3DFormat texture_format, + bool allow_compression, + bool allow_reduction +) +: TextureClass(0,0,mip_level_count, POOL_MANAGED, false, texture_format) +{ + IsCompressionAllowed=allow_compression; + InactivationTime=DEFAULT_INACTIVATION_TIME; // Default inactivation time 30 seconds + + switch (TextureFormat) + { + case WW3D_FORMAT_DXT1: + case WW3D_FORMAT_DXT2: + case WW3D_FORMAT_DXT3: + case WW3D_FORMAT_DXT4: + case WW3D_FORMAT_DXT5: + IsCompressionAllowed=true; + break; + case WW3D_FORMAT_U8V8: // Bumpmap + case WW3D_FORMAT_L6V5U5: // Bumpmap + case WW3D_FORMAT_X8L8V8U8: // Bumpmap + // If requesting bumpmap format that isn't available we'll just return the surface in whatever color + // format the texture file is in. (This is illegal case, the format support should always be queried + // before creating a bump texture!) + if (!DX8Wrapper::Is_Initted() || !DX8Wrapper::Get_Current_Caps()->Support_Texture_Format(TextureFormat)) + { + TextureFormat=WW3D_FORMAT_UNKNOWN; + } + // If bump format is valid, make sure compression is not allowed so that we don't even attempt to load + // from a compressed file (quality isn't good enough for bump map). Also disable mipmapping. + else + { + IsCompressionAllowed=false; + MipLevelCount=MIP_LEVELS_1; + Filter.Set_Mip_Mapping(TextureFilterClass::FILTER_TYPE_NONE); + } + break; + default: break; + } + + WWASSERT_PRINT(name && name[0], "TextureClass CTor: NULL or empty texture name"); + int len=strlen(name); + for (int i=0;iGet_Original_Texture_Width(); + Height=thumb->Get_Original_Texture_Height(); + if (MipLevelCount!=MIP_LEVELS_1) { + MipLevelCount=(MipCountType)thumb->Get_Original_Texture_Mip_Level_Count(); + } + } + + LastAccessed=WW3D::Get_Sync_Time(); + + // If the thumbnails are not enabled, init the texture at this point to avoid stalling when the + // mesh is rendered. + if (!WW3D::Get_Thumbnail_Enabled()) + { + if (TextureLoader::Is_DX8_Thread()) + { + Init(); + } + } +} + +// don't know if these are needed +#if 0 +// ---------------------------------------------------------------------------- +CubeTextureClass::CubeTextureClass +( + SurfaceClass *surface, + MipCountType mip_level_count +) +: TextureClass(0,0,mip_level_count, POOL_MANAGED, false, surface->Get_Surface_Format()) +{ + IsProcedural=true; + Initialized=true; + IsReducible=false; + + SurfaceClass::SurfaceDescription sd; + surface->Get_Description(sd); + Width=sd.Width; + Height=sd.Height; + switch (sd.Format) + { + case WW3D_FORMAT_DXT1: + case WW3D_FORMAT_DXT2: + case WW3D_FORMAT_DXT3: + case WW3D_FORMAT_DXT4: + case WW3D_FORMAT_DXT5: + IsCompressionAllowed=true; + break; + default: break; + } + + Poke_Texture + ( + DX8Wrapper::_Create_DX8_Cube_Texture + ( + surface->Peek_D3D_Surface(), + mip_level_count + ) + ); + LastAccessed=WW3D::Get_Sync_Time(); +} + +// ---------------------------------------------------------------------------- +CubeTextureClass::CubeTextureClass(IDirect3DBaseTexture8* d3d_texture) +: TextureBaseClass + ( + 0, + 0, + ((MipCountType)d3d_texture->GetLevelCount()) + ), + Filter((MipCountType)d3d_texture->GetLevelCount()) +{ + Initialized=true; + IsProcedural=true; + IsReducible=false; - if (no_lod) - { - newtex->Get_Filter().Set_Mip_Mapping(TextureFilterClass::FILTER_TYPE_NONE); - } - bool u_clamp = ((texinfo.Attributes & W3DTEXTURE_CLAMP_U) != 0); - newtex->Get_Filter().Set_U_Addr_Mode(u_clamp ? TextureFilterClass::TEXTURE_ADDRESS_CLAMP : TextureFilterClass::TEXTURE_ADDRESS_REPEAT); - bool v_clamp = ((texinfo.Attributes & W3DTEXTURE_CLAMP_V) != 0); - newtex->Get_Filter().Set_V_Addr_Mode(v_clamp ? TextureFilterClass::TEXTURE_ADDRESS_CLAMP : TextureFilterClass::TEXTURE_ADDRESS_REPEAT); + Peek_Texture()->AddRef(); + IDirect3DSurface8* 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) + { + case WW3D_FORMAT_DXT1: + case WW3D_FORMAT_DXT2: + case WW3D_FORMAT_DXT3: + case WW3D_FORMAT_DXT4: + case WW3D_FORMAT_DXT5: + IsCompressionAllowed=true; + break; + default: break; + } - switch (texinfo.Attributes & W3DTEXTURE_TYPE_MASK) - { + LastAccessed=WW3D::Get_Sync_Time(); +} +#endif - case W3DTEXTURE_TYPE_COLORMAP: - // Do nothing. - break; +//********************************************************************************************** +//! Apply new surface to texture +/*! +*/ +void CubeTextureClass::Apply_New_Surface +( + IDirect3DBaseTexture8* d3d_texture, + bool initialized, + bool disable_auto_invalidation +) +{ + IDirect3DBaseTexture8* d3d_tex=Peek_D3D_Base_Texture(); - case W3DTEXTURE_TYPE_BUMPMAP: - { - TextureClass *releasetex = newtex; + if (d3d_tex) d3d_tex->Release(); - // Format is assumed to be a grayscale heightmap. Convert it to a bump map. - newtex = WW3DAssetManager::Get_Instance()->Get_Bumpmap_Based_On_Texture (newtex); - WW3DAssetManager::Get_Instance()->Release_Texture (releasetex); - break; - } + Poke_Texture(d3d_texture);//TextureLoadTask->Peek_D3D_Texture(); + d3d_texture->AddRef(); - default: - WWASSERT (false); - break; - } + if (initialized) Initialized=true; + if (disable_auto_invalidation) InactivationTime = 0; - } else { - newtex = WW3DAssetManager::Get_Instance()->Get_Texture(name); - } + WWASSERT(d3d_texture); + D3DSURFACE_DESC d3d_desc; + ::ZeroMemory(&d3d_desc, sizeof(D3DSURFACE_DESC)); + DX8_ErrorCode(Peek_D3D_CubeTexture()->GetLevelDesc(0,&d3d_desc)); - WWASSERT(newtex); + if (initialized) + { + TextureFormat=D3DFormat_To_WW3DFormat(d3d_desc.Format); + Width=d3d_desc.Width; + Height=d3d_desc.Height; } - - // Return a pointer to the new texture - return newtex; } -// Utility function used by Save_Texture -void setup_texture_attributes(TextureClass * tex, W3dTextureInfoStruct * texinfo) + +/************************************************************************* +** VolumeTextureClass +*************************************************************************/ +VolumeTextureClass::VolumeTextureClass +( + unsigned width, + unsigned height, + unsigned depth, + WW3DFormat format, + MipCountType mip_level_count, + PoolType pool, + bool rendertarget, + bool allow_reduction +) +: TextureClass(width, height, format, mip_level_count, pool, rendertarget), + Depth(depth) { - texinfo->Attributes = 0; + Initialized=true; + IsProcedural=true; + IsReducible=false; - if (tex->Get_Filter().Get_Mip_Mapping() == TextureFilterClass::FILTER_TYPE_NONE) texinfo->Attributes |= W3DTEXTURE_NO_LOD; - if (tex->Get_Filter().Get_U_Addr_Mode() == TextureFilterClass::TEXTURE_ADDRESS_CLAMP) texinfo->Attributes |= W3DTEXTURE_CLAMP_U; - if (tex->Get_Filter().Get_V_Addr_Mode() == TextureFilterClass::TEXTURE_ADDRESS_CLAMP) texinfo->Attributes |= W3DTEXTURE_CLAMP_V; + switch (format) + { + case WW3D_FORMAT_DXT1: + case WW3D_FORMAT_DXT2: + case WW3D_FORMAT_DXT3: + case WW3D_FORMAT_DXT4: + case WW3D_FORMAT_DXT5: + IsCompressionAllowed=true; + break; + default : break; + } + + D3DPOOL d3dpool=(D3DPOOL)0; + switch(pool) + { + case POOL_DEFAULT : d3dpool=D3DPOOL_DEFAULT; break; + case POOL_MANAGED : d3dpool=D3DPOOL_MANAGED; break; + case POOL_SYSTEMMEM : d3dpool=D3DPOOL_SYSTEMMEM; break; + default: WWASSERT(0); + } + + Poke_Texture + ( + DX8Wrapper::_Create_DX8_Volume_Texture + ( + width, + height, + depth, + format, + mip_level_count, + d3dpool + ) + ); + + if (pool==POOL_DEFAULT) + { + Set_Dirty(); + DX8TextureTrackerClass *track=new DX8TextureTrackerClass + ( + width, + height, + format, + mip_level_count, + this, + rendertarget + ); + DX8TextureManagerClass::Add(track); + } + LastAccessed=WW3D::Get_Sync_Time(); } -void Save_Texture(TextureClass * texture,ChunkSaveClass & csave) + +// ---------------------------------------------------------------------------- +VolumeTextureClass::VolumeTextureClass +( + const char *name, + const char *full_path, + MipCountType mip_level_count, + WW3DFormat texture_format, + bool allow_compression, + bool allow_reduction +) +: TextureClass(0,0,mip_level_count, POOL_MANAGED, false, texture_format), + Depth(0) { - const char * filename; - W3dTextureInfoStruct texinfo; - memset(&texinfo,0,sizeof(texinfo)); + IsCompressionAllowed=allow_compression; + InactivationTime=DEFAULT_INACTIVATION_TIME; // Default inactivation time 30 seconds - filename = texture->Get_Full_Path(); + switch (TextureFormat) + { + case WW3D_FORMAT_DXT1: + case WW3D_FORMAT_DXT2: + case WW3D_FORMAT_DXT3: + case WW3D_FORMAT_DXT4: + case WW3D_FORMAT_DXT5: + IsCompressionAllowed=true; + break; + case WW3D_FORMAT_U8V8: // Bumpmap + case WW3D_FORMAT_L6V5U5: // Bumpmap + case WW3D_FORMAT_X8L8V8U8: // Bumpmap + // If requesting bumpmap format that isn't available we'll just return the surface in whatever color + // format the texture file is in. (This is illegal case, the format support should always be queried + // before creating a bump texture!) + if (!DX8Wrapper::Is_Initted() || !DX8Wrapper::Get_Current_Caps()->Support_Texture_Format(TextureFormat)) + { + TextureFormat=WW3D_FORMAT_UNKNOWN; + } + // If bump format is valid, make sure compression is not allowed so that we don't even attempt to load + // from a compressed file (quality isn't good enough for bump map). Also disable mipmapping. + else + { + IsCompressionAllowed=false; + MipLevelCount=MIP_LEVELS_1; + Filter.Set_Mip_Mapping(TextureFilterClass::FILTER_TYPE_NONE); + } + break; + default: break; + } - setup_texture_attributes(texture, &texinfo); + WWASSERT_PRINT(name && name[0], "TextureClass CTor: NULL or empty texture name"); + int len=strlen(name); + for (int i=0;iGet_Original_Texture_Width(); + Height=thumb->Get_Original_Texture_Height(); + if (MipLevelCount!=MIP_LEVELS_1) { + MipLevelCount=(MipCountType)thumb->Get_Original_Texture_Mip_Level_Count(); + } + } + + LastAccessed=WW3D::Get_Sync_Time(); + + // If the thumbnails are not enabled, init the texture at this point to avoid stalling when the + // mesh is rendered. + if (!WW3D::Get_Thumbnail_Enabled()) + { + if (TextureLoader::Is_DX8_Thread()) + { + Init(); + } } } +// don't know if these are needed +#if 0 // ---------------------------------------------------------------------------- - -BumpmapTextureClass::BumpmapTextureClass(TextureClass* texture) - : -// TextureClass(texture->Get_Width(),texture->Get_Height(),texture->Get_Textur4e_Format(),MIP_LEVELS_1) - TextureClass(TextureLoader::Generate_Bumpmap(texture)) +CubeTextureClass::CubeTextureClass +( + SurfaceClass *surface, + MipCountType mip_level_count +) +: TextureClass(0,0,mip_level_count, POOL_MANAGED, false, surface->Get_Surface_Format()) { -// D3DTexture=TextureLoader::Generate_Bumpmap(texture); -// TextureLoader:::Generage_Bumpmap + IsProcedural=true; + Initialized=true; + IsReducible=false; + + SurfaceClass::SurfaceDescription sd; + surface->Get_Description(sd); + Width=sd.Width; + Height=sd.Height; + switch (sd.Format) + { + case WW3D_FORMAT_DXT1: + case WW3D_FORMAT_DXT2: + case WW3D_FORMAT_DXT3: + case WW3D_FORMAT_DXT4: + case WW3D_FORMAT_DXT5: + IsCompressionAllowed=true; + break; + default: break; + } + + Poke_Texture + ( + DX8Wrapper::_Create_DX8_Cube_Texture + ( + surface->Peek_D3D_Surface(), + mip_level_count + ) + ); + LastAccessed=WW3D::Get_Sync_Time(); } -BumpmapTextureClass::~BumpmapTextureClass() +// ---------------------------------------------------------------------------- +CubeTextureClass::CubeTextureClass(IDirect3DBaseTexture8* d3d_texture) +: TextureBaseClass + ( + 0, + 0, + ((MipCountType)d3d_texture->GetLevelCount()) + ), + Filter((MipCountType)d3d_texture->GetLevelCount()) { + Initialized=true; + IsProcedural=true; + IsReducible=false; + + Peek_Texture()->AddRef(); + IDirect3DSurface8* 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) + { + case WW3D_FORMAT_DXT1: + case WW3D_FORMAT_DXT2: + case WW3D_FORMAT_DXT3: + case WW3D_FORMAT_DXT4: + case WW3D_FORMAT_DXT5: + IsCompressionAllowed=true; + break; + default: break; + } + + LastAccessed=WW3D::Get_Sync_Time(); } +#endif + + + + +//********************************************************************************************** +//! Apply new surface to texture +/*! +*/ +void VolumeTextureClass::Apply_New_Surface +( + IDirect3DBaseTexture8* d3d_texture, + bool initialized, + bool disable_auto_invalidation +) +{ + IDirect3DBaseTexture8* d3d_tex=Peek_D3D_Base_Texture(); + + if (d3d_tex) d3d_tex->Release(); + + Poke_Texture(d3d_texture);//TextureLoadTask->Peek_D3D_Texture(); + d3d_texture->AddRef(); + + if (initialized) Initialized=true; + if (disable_auto_invalidation) InactivationTime = 0; + WWASSERT(d3d_texture); + D3DVOLUME_DESC d3d_desc; + ::ZeroMemory(&d3d_desc, sizeof(D3DVOLUME_DESC)); + + DX8_ErrorCode(Peek_D3D_VolumeTexture()->GetLevelDesc(0,&d3d_desc)); + + if (initialized) + { + TextureFormat=D3DFormat_To_WW3DFormat(d3d_desc.Format); + Width=d3d_desc.Width; + Height=d3d_desc.Height; + Depth=d3d_desc.Depth; + } +} diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texture.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texture.h index 2efaef8a16..47eff85d7f 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texture.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texture.h @@ -24,12 +24,17 @@ * * * $Archive:: /Commando/Code/ww3d2/texture.h $* * * - * $Author:: Jani_p $* + * $Org Author:: Jani_p $* * * - * $Modtime:: 8/17/01 9:41a $* + * Author : Kenny Mitchell * * * - * $Revision:: 35 $* + * $Modtime:: 08/05/02 1:27p $* * * + * $Revision:: 46 $* + * * + * 05/16/02 KM Base texture class to abstract major texture types, e.g. 3d, z, cube, etc. + * 06/27/02 KM Texture class abstraction * + * 08/05/02 KM Texture class redesign (revisited) *---------------------------------------------------------------------------------------------* * Functions: * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ @@ -41,219 +46,430 @@ #include "surfaceclass.h" #include "ww3dformat.h" #include "wwstring.h" +#include "vector3.h" #include "texturefilter.h" struct IDirect3DBaseTexture8; struct IDirect3DTexture8; +struct IDirect3DCubeTexture8; +struct IDirect3DVolumeTexture8; class DX8Wrapper; class TextureLoader; class LoaderThreadClass; -class DX8TextureManagerClass; class TextureLoadTaskClass; +class CubeTextureClass; +class VolumeTextureClass; -/************************************************************************* -** TextureClass -** -** This is our texture class. For legacy reasons it contains some -** information beyond the D3D texture itself, such as texture addressing -** modes. -** -*************************************************************************/ -class TextureClass : public W3DMPO, public RefCountClass +class TextureBaseClass : public RefCountClass { - W3DMPO_GLUE(TextureClass) - + friend class TextureLoader; + friend class LoaderThreadClass; friend class DX8TextureTrackerClass; //(gth) so it can call Poke_Texture, + friend class DX8ZTextureTrackerClass; + +public: + + enum PoolType + { + POOL_DEFAULT=0, + POOL_MANAGED, + POOL_SYSTEMMEM + }; + + enum TexAssetType + { + TEX_REGULAR, + TEX_CUBEMAP, + TEX_VOLUME + }; + + // base constructor for derived classes + TextureBaseClass + ( + unsigned width, + unsigned height, + MipCountType mip_level_count=MIP_LEVELS_ALL, + PoolType pool=POOL_MANAGED, + bool rendertarget=false, + bool reducible=true + ); + + virtual ~TextureBaseClass(); + + virtual TexAssetType Get_Asset_Type() const=0; + + // Names + void Set_Texture_Name(const char * name); + void Set_Full_Path(const char * path) { FullPath = path; } + const StringClass& Get_Texture_Name(void) const { return Name; } + const StringClass& Get_Full_Path(void) const { if (FullPath.Is_Empty ()) return Name; return FullPath; } + + unsigned Get_ID() const { return texture_id; } // Each textrure has a unique id + + // The number of Mip levels in the texture + unsigned int Get_Mip_Level_Count(void) const + { + return MipLevelCount; + } + + // 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; + } + + // Time, after which the texture is invalidated if not used. Set to zero to indicate infinite. + // Time is in milliseconds. + void Set_Inactivation_Time(unsigned time) { InactivationTime=time; } + int Get_Inactivation_Time() const { return InactivationTime; } + + // Texture priority affects texture management and caching. + unsigned int Get_Priority(void); + unsigned int Set_Priority(unsigned int priority); // Returns previous priority + + // Debug utility functions for returning the texture memory usage + virtual unsigned Get_Texture_Memory_Usage() const=0; + + bool Is_Initialized() const { return Initialized; } + bool Is_Lightmap() const { return IsLightmap; } + bool Is_Procedural() const { return IsProcedural; } + bool Is_Reducible() const { return IsReducible; } //can texture be reduced in resolution for LOD purposes? + + static int _Get_Total_Locked_Surface_Size(); + static int _Get_Total_Texture_Size(); + static int _Get_Total_Lightmap_Texture_Size(); + static int _Get_Total_Procedural_Texture_Size(); + static int _Get_Total_Locked_Surface_Count(); + static int _Get_Total_Texture_Count(); + static int _Get_Total_Lightmap_Texture_Count(); + static int _Get_Total_Procedural_Texture_Count(); + + virtual void Init()=0; + + // This utility function processes the texture reduction (used during rendering) + void Invalidate(); + + // 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(); - friend DX8Wrapper; - friend TextureLoader; - friend LoaderThreadClass; - friend DX8TextureManagerClass; - - public: - - enum PoolType { - POOL_DEFAULT=0, - POOL_MANAGED, - POOL_SYSTEMMEM - }; - - enum TexAssetType - { - TEX_REGULAR, - }; - - // Create texture with desired height, width and format. - TextureClass( - unsigned width, - unsigned height, - WW3DFormat format, - MipCountType mip_level_count=MIP_LEVELS_ALL, - PoolType pool=POOL_MANAGED, - bool rendertarget=false); - - // Create texture from a file. If format is specified the texture is converted to that format. - // Note that the format must be supported by the current device and that a texture can't exist - // in the system with the same name in multiple formats. - TextureClass( - const char *name, - const char *full_path=NULL, - MipCountType mip_level_count=MIP_LEVELS_ALL, - WW3DFormat texture_format=WW3D_FORMAT_UNKNOWN, - bool allow_compression=true); + // 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; }; - // Create texture from a surface. - TextureClass( - SurfaceClass *surface, - MipCountType mip_level_count=MIP_LEVELS_ALL); + void Set_HSV_Shift(const Vector3 &hsv_shift); + const Vector3& Get_HSV_Shift() { return HSVShift; } - TextureClass(IDirect3DTexture8* d3d_texture); - - virtual TexAssetType Get_Asset_Type() const { return TEX_REGULAR; } + bool Is_Compression_Allowed() const { return IsCompressionAllowed; } - virtual ~TextureClass(void); + unsigned Get_Reduction() const; - // Names - void Set_Texture_Name(const char * name); - void Set_Full_Path(const char * path) { FullPath = path; } - const StringClass& Get_Texture_Name(void) const { return Name; } - const StringClass& Get_Full_Path(void) const { if (FullPath.Is_Empty ()) return Name; return FullPath; } + // Background texture loader will call this when texture has been loaded + virtual void Apply_New_Surface(IDirect3DBaseTexture8* tex, bool initialized, bool disable_auto_invalidation = false)=0; // If the parameter is true, the texture will be flagged as initialised - unsigned Get_ID() const { return texture_id; } // Each textrure has a unique id - - // 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; - } + MipCountType MipLevelCount; - // 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); + // Inactivate textures that haven't been used in a while. Pass zero to use textures' + // own inactive times (default). In urgent need to free up texture memory, try + // calling with relatively small (just few seconds) time override to free up everything + // but the currently used textures. + static void Invalidate_Old_Unused_Textures(unsigned inactive_time_override); - TextureFilterClass& Get_Filter() { return Filter; } + // Apply this texture's settings into D3D + virtual void Apply(unsigned int stage)=0; - // Get the surface of one of the mipmap levels (defaults to highest-resolution one) - SurfaceClass *Get_Surface_Level(unsigned int level = 0); + // Apply a Null texture's settings into D3D + static void Apply_Null(unsigned int stage); - // Texture priority affects texture management and caching. - unsigned int Get_Priority(void); - unsigned int Set_Priority(unsigned int priority); // Returns previous priority + virtual TextureClass* As_TextureClass() { return NULL; } + virtual CubeTextureClass* As_CubeTextureClass() { return NULL; } + virtual VolumeTextureClass* As_VolumeTextureClass() { return NULL; } - // Debug utility functions for returning the texture memory usage - unsigned Get_Texture_Memory_Usage() const; - bool Is_Initialized() const { return Initialized; } - bool Is_Lightmap() const { return IsLightmap; } - bool Is_Procedural() const { return IsProcedural; } + IDirect3DTexture8* Peek_D3D_Texture() const { return (IDirect3DTexture8*)Peek_D3D_Base_Texture(); } + IDirect3DVolumeTexture8* Peek_D3D_VolumeTexture() const { return (IDirect3DVolumeTexture8*)Peek_D3D_Base_Texture(); } + IDirect3DCubeTexture8* Peek_D3D_CubeTexture() const { return (IDirect3DCubeTexture8*)Peek_D3D_Base_Texture(); } - static int _Get_Total_Locked_Surface_Size(); - static int _Get_Total_Texture_Size(); - static int _Get_Total_Lightmap_Texture_Size(); - static int _Get_Total_Procedural_Texture_Size(); - static int _Get_Total_Locked_Surface_Count(); - static int _Get_Total_Texture_Count(); - static int _Get_Total_Lightmap_Texture_Count(); - static int _Get_Total_Procedural_Texture_Count(); +protected: - static void _Set_Default_Min_Filter(TextureFilterClass::FilterType filter); - static void _Set_Default_Mag_Filter(TextureFilterClass::FilterType filter); - static void _Set_Default_Mip_Filter(TextureFilterClass::FilterType filter); + void Load_Locked_Surface(); + void Poke_Texture(IDirect3DBaseTexture8* tex) { D3DTexture = tex; } - // This utility function processes the texture reduction (used during rendering) - void Invalidate(); + bool Initialized; - IDirect3DTexture8 *Peek_D3D_Texture() const { return (IDirect3DTexture8 *)Peek_D3D_Base_Texture(); } + // For debug purposes the texture sets this true if it is a lightmap texture + bool IsLightmap; + bool IsCompressionAllowed; + bool IsProcedural; + bool IsReducible; - // 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(); + unsigned InactivationTime; // In milliseconds + unsigned ExtendedInactivationTime; // This is set by the engine, if needed + unsigned LastInactivationSyncTime; + mutable unsigned LastAccessed; - // 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; }; + // If this is non-zero, the texture will have a hue shift done at the next init (this + // value should only be changed by Set_HSV_Shift() function, which also invalidates the + // texture). + Vector3 HSVShift; - unsigned Get_Reduction() const; - WW3DFormat Get_Texture_Format() const { return TextureFormat; } - bool Is_Compression_Allowed() const { return IsCompressionAllowed; } + int Width; + int Height; - protected: - void Poke_Texture(IDirect3DBaseTexture8* tex) { D3DTexture = tex; } +private: - // Apply this texture's settings into D3D - virtual void Apply(unsigned int stage); - void Load_Locked_Surface(); + // Direct3D texture object + IDirect3DBaseTexture8 *D3DTexture; - void Init(); + // Name + StringClass Name; + StringClass FullPath; - // Apply a Null texture's settings into D3D - static void Apply_Null(unsigned int stage); + // Unique id + unsigned texture_id; - // State not contained in the Direct3D texture object: - TextureFilterClass Filter; + // Support for self-managed textures - // Direct3D texture object - IDirect3DBaseTexture8 *D3DTexture; - bool Initialized; + PoolType Pool; + bool Dirty; - // Name - StringClass Name; - StringClass FullPath; + friend class TextureLoadTaskClass; + friend class CubeTextureLoadTaskClass; + friend class VolumeTextureLoadTaskClass; + TextureLoadTaskClass* TextureLoadTask; + TextureLoadTaskClass* ThumbnailLoadTask; - // Unique id - unsigned texture_id; +}; - // NOTE: Since "texture wrapping" (NOT TEXTURE WRAP MODE - THIS IS - // SOMETHING ELSE) is a global state that affects all texture stages, - // and this class only affects its own stage, we will not worry about - // it for now. Later (probably when we implement world-oriented - // environment maps) we will consider where to put it. - // For debug purposes the texture sets this true if it is a lightmap texture - bool IsLightmap; - bool IsProcedural; - bool IsCompressionAllowed; +/************************************************************************* +** TextureClass +** +** This is our regular texture class. For legacy reasons it contains some +** information beyond the D3D texture itself, such as texture addressing +** modes. +** +*************************************************************************/ +class TextureClass : public TextureBaseClass +{ + W3DMPO_GLUE(TextureClass) +// friend DX8Wrapper; - mutable unsigned LastAccessed; - WW3DFormat TextureFormat; +public: - int Width; - int Height; + // Create texture with desired height, width and format. + TextureClass + ( + unsigned width, + unsigned height, + WW3DFormat format, + MipCountType mip_level_count=MIP_LEVELS_ALL, + PoolType pool=POOL_MANAGED, + bool rendertarget=false, + bool allow_reduction=true + ); + + // Create texture from a file. If format is specified the texture is converted to that format. + // Note that the format must be supported by the current device and that a texture can't exist + // in the system with the same name in multiple formats. + TextureClass + ( + const char *name, + const char *full_path=NULL, + MipCountType mip_level_count=MIP_LEVELS_ALL, + WW3DFormat texture_format=WW3D_FORMAT_UNKNOWN, + bool allow_compression=true, + bool allow_reduction=true + ); + + // Create texture from a surface. + TextureClass + ( + SurfaceClass *surface, + MipCountType mip_level_count=MIP_LEVELS_ALL + ); + + TextureClass(IDirect3DBaseTexture8* d3d_texture); + + // defualt constructors for derived classes (cube & vol) + TextureClass + ( + unsigned width, + unsigned height, + MipCountType mip_level_count=MIP_LEVELS_ALL, + PoolType pool=POOL_MANAGED, + bool rendertarget=false, + WW3DFormat format=WW3D_FORMAT_UNKNOWN, + bool allow_reduction=true + ) + : TextureBaseClass(width,height,mip_level_count,pool,rendertarget,allow_reduction), TextureFormat(format), Filter(mip_level_count) { } + + virtual TexAssetType Get_Asset_Type() const { return TEX_REGULAR; } + + virtual void Init(); + + // Background texture loader will call this when texture has been loaded + virtual void Apply_New_Surface(IDirect3DBaseTexture8* tex, bool initialized, bool disable_auto_invalidation = false); // If the parameter is true, the texture will be flagged as initialised + + // Get the surface of one of the mipmap levels (defaults to highest-resolution one) + SurfaceClass *Get_Surface_Level(unsigned int level = 0); + IDirect3DSurface8 *Get_D3D_Surface_Level(unsigned int level = 0); + void Get_Level_Description( SurfaceClass::SurfaceDescription & desc, unsigned int level = 0 ); + + TextureFilterClass& Get_Filter() { return Filter; } + + WW3DFormat Get_Texture_Format() const { return TextureFormat; } + + virtual void Apply(unsigned int stage); + + virtual unsigned Get_Texture_Memory_Usage() const; + + virtual TextureClass* As_TextureClass() { return this; } + +protected: + + WW3DFormat TextureFormat; + + // legacy + TextureFilterClass Filter; +}; - // Support for self-managed textures +class ZTextureClass : public TextureBaseClass +{ +public: + // Create a z texture with desired height, width and format + ZTextureClass + ( + unsigned width, + unsigned height, + WW3DZFormat zformat, + MipCountType mip_level_count=MIP_LEVELS_ALL, + PoolType pool=POOL_MANAGED + ); + + WW3DZFormat Get_Texture_Format() const { return DepthStencilTextureFormat; } + + virtual TexAssetType Get_Asset_Type() const { return TEX_REGULAR; } + + virtual void Init() {} + + // Background texture loader will call this when texture has been loaded + virtual void Apply_New_Surface(IDirect3DBaseTexture8* tex, bool initialized, bool disable_auto_invalidation = false); // If the parameter is true, the texture will be flagged as initialised + + virtual void Apply(unsigned int stage); - PoolType Pool; - bool Dirty; + IDirect3DSurface8 *Get_D3D_Surface_Level(unsigned int level = 0); + virtual unsigned Get_Texture_Memory_Usage() const; + +private: + + WW3DZFormat DepthStencilTextureFormat; +}; + +class CubeTextureClass : public TextureClass +{ public: - MipCountType MipLevelCount; - TextureLoadTaskClass* TextureLoadTask; - // Background texture loader will call this when texture has been loaded - void Apply_New_Surface(bool initialized); // If the parameter is true, the texture will be flagged as initialised + // Create texture with desired height, width and format. + CubeTextureClass + ( + unsigned width, + unsigned height, + WW3DFormat format, + MipCountType mip_level_count=MIP_LEVELS_ALL, + PoolType pool=POOL_MANAGED, + bool rendertarget=false, + bool allow_reduction=true + ); + + // Create texture from a file. If format is specified the texture is converted to that format. + // Note that the format must be supported by the current device and that a texture can't exist + // in the system with the same name in multiple formats. + CubeTextureClass + ( + const char *name, + const char *full_path=NULL, + MipCountType mip_level_count=MIP_LEVELS_ALL, + WW3DFormat texture_format=WW3D_FORMAT_UNKNOWN, + bool allow_compression=true, + bool allow_reduction=true + ); + + // Create texture from a surface. + CubeTextureClass + ( + SurfaceClass *surface, + MipCountType mip_level_count=MIP_LEVELS_ALL + ); + + CubeTextureClass(IDirect3DBaseTexture8* d3d_texture); + + virtual void Apply_New_Surface(IDirect3DBaseTexture8* tex, bool initialized, bool disable_auto_invalidation = false); // If the parameter is true, the texture will be flagged as initialised + + virtual TexAssetType Get_Asset_Type() const { return TEX_CUBEMAP; } + + virtual CubeTextureClass* As_CubeTextureClass() { return this; } }; -class BumpmapTextureClass : public TextureClass +class VolumeTextureClass : public TextureClass { public: - // Generate bumpmap texture procedurally from the source texture - BumpmapTextureClass(TextureClass* texture); - virtual ~BumpmapTextureClass(); + // Create texture with desired height, width and format. + VolumeTextureClass + ( + unsigned width, + unsigned height, + unsigned depth, + WW3DFormat format, + MipCountType mip_level_count=MIP_LEVELS_ALL, + PoolType pool=POOL_MANAGED, + bool rendertarget=false, + bool allow_reduction=true + ); + + // Create texture from a file. If format is specified the texture is converted to that format. + // Note that the format must be supported by the current device and that a texture can't exist + // in the system with the same name in multiple formats. + VolumeTextureClass + ( + const char *name, + const char *full_path=NULL, + MipCountType mip_level_count=MIP_LEVELS_ALL, + WW3DFormat texture_format=WW3D_FORMAT_UNKNOWN, + bool allow_compression=true, + bool allow_reduction=true + ); + + // Create texture from a surface. + VolumeTextureClass + ( + SurfaceClass *surface, + MipCountType mip_level_count=MIP_LEVELS_ALL + ); + + VolumeTextureClass(IDirect3DBaseTexture8* d3d_texture); + + virtual void Apply_New_Surface(IDirect3DBaseTexture8* tex, bool initialized, bool disable_auto_invalidation = false); // If the parameter is true, the texture will be flagged as initialised + + virtual TexAssetType Get_Asset_Type() const { return TEX_VOLUME; } + + virtual VolumeTextureClass* As_VolumeTextureClass() { return this; } + +protected: + + int Depth; }; // Utility functions for loading and saving texture descriptions from/to W3D files TextureClass *Load_Texture(ChunkLoadClass & cload); void Save_Texture(TextureClass * texture, ChunkSaveClass & csave); - -// TheSuperHackers @todo TextureBaseClass abstraction -typedef TextureClass TextureBaseClass; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texturefilter.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texturefilter.cpp index 6ccbabc5c3..690faf2ef4 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texturefilter.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texturefilter.cpp @@ -1,5 +1,5 @@ /* -** Command & Conquer Generals Zero Hour(tm) +** Command & Conquer Generals(tm) ** Copyright 2025 Electronic Arts Inc. ** ** This program is free software: you can redistribute it and/or modify @@ -39,11 +39,10 @@ #include "texturefilter.h" #include "dx8wrapper.h" -#include "meshmatdesc.h" -unsigned _MinTextureFilters[TextureFilterClass::FILTER_TYPE_COUNT]; -unsigned _MagTextureFilters[TextureFilterClass::FILTER_TYPE_COUNT]; -unsigned _MipMapFilters[TextureFilterClass::FILTER_TYPE_COUNT]; +unsigned _MinTextureFilters[MAX_TEXTURE_STAGES][TextureFilterClass::FILTER_TYPE_COUNT]; +unsigned _MagTextureFilters[MAX_TEXTURE_STAGES][TextureFilterClass::FILTER_TYPE_COUNT]; +unsigned _MipMapFilters[MAX_TEXTURE_STAGES][TextureFilterClass::FILTER_TYPE_COUNT]; /************************************************************************* ** TextureFilterClass @@ -70,9 +69,9 @@ TextureFilterClass::TextureFilterClass(MipCountType mip_level_count) */ void TextureFilterClass::Apply(unsigned int stage) { - DX8Wrapper::Set_DX8_Texture_Stage_State(stage,D3DTSS_MINFILTER,_MinTextureFilters[TextureMinFilter]); - DX8Wrapper::Set_DX8_Texture_Stage_State(stage,D3DTSS_MAGFILTER,_MagTextureFilters[TextureMagFilter]); - DX8Wrapper::Set_DX8_Texture_Stage_State(stage,D3DTSS_MIPFILTER,_MipMapFilters[MipMapFilter]); + DX8Wrapper::Set_DX8_Texture_Stage_State(stage,D3DTSS_MINFILTER,_MinTextureFilters[stage][TextureMinFilter]); + DX8Wrapper::Set_DX8_Texture_Stage_State(stage,D3DTSS_MAGFILTER,_MagTextureFilters[stage][TextureMagFilter]); + DX8Wrapper::Set_DX8_Texture_Stage_State(stage,D3DTSS_MIPFILTER,_MipMapFilters[stage][MipMapFilter]); switch (Get_U_Addr_Mode()) { @@ -101,51 +100,102 @@ void TextureFilterClass::Apply(unsigned int stage) //! Init filters (legacy) /*! */ -void TextureFilterClass::_Init_Filters(void) +void TextureFilterClass::_Init_Filters(TextureFilterMode filter_type) { const D3DCAPS8& dx8caps=DX8Wrapper::Get_Current_Caps()->Get_DX8_Caps(); - _MinTextureFilters[FILTER_TYPE_NONE]=D3DTEXF_POINT; - _MagTextureFilters[FILTER_TYPE_NONE]=D3DTEXF_POINT; - _MipMapFilters[FILTER_TYPE_NONE]=D3DTEXF_NONE; - - _MinTextureFilters[FILTER_TYPE_FAST]=D3DTEXF_LINEAR; - _MagTextureFilters[FILTER_TYPE_FAST]=D3DTEXF_LINEAR; - _MipMapFilters[FILTER_TYPE_FAST]=D3DTEXF_POINT; - - // Jani: Disabling anisotropic filtering as it doesn't seem to work with the latest nVidia drivers. - if (dx8caps.TextureFilterCaps&D3DPTFILTERCAPS_MAGFAFLATCUBIC) _MagTextureFilters[FILTER_TYPE_BEST]=D3DTEXF_FLATCUBIC; - else if (dx8caps.TextureFilterCaps&D3DPTFILTERCAPS_MAGFANISOTROPIC) _MagTextureFilters[FILTER_TYPE_BEST]=D3DTEXF_ANISOTROPIC; - else if (dx8caps.TextureFilterCaps&D3DPTFILTERCAPS_MAGFGAUSSIANCUBIC) _MagTextureFilters[FILTER_TYPE_BEST]=D3DTEXF_GAUSSIANCUBIC; - else if (dx8caps.TextureFilterCaps&D3DPTFILTERCAPS_MAGFLINEAR) _MagTextureFilters[FILTER_TYPE_BEST]=D3DTEXF_LINEAR; - else if (dx8caps.TextureFilterCaps&D3DPTFILTERCAPS_MAGFPOINT) _MagTextureFilters[FILTER_TYPE_BEST]=D3DTEXF_POINT; - else { - WWASSERT_PRINT(0,("No magnification filter found!")); +#ifndef _XBOX + _MinTextureFilters[0][FILTER_TYPE_NONE]=D3DTEXF_POINT; + _MagTextureFilters[0][FILTER_TYPE_NONE]=D3DTEXF_POINT; + _MipMapFilters[0][FILTER_TYPE_NONE]=D3DTEXF_NONE; + + _MinTextureFilters[0][FILTER_TYPE_FAST]=D3DTEXF_LINEAR; + _MagTextureFilters[0][FILTER_TYPE_FAST]=D3DTEXF_LINEAR; + _MipMapFilters[0][FILTER_TYPE_FAST]=D3DTEXF_POINT; + + _MagTextureFilters[0][FILTER_TYPE_BEST]=D3DTEXF_POINT; + _MinTextureFilters[0][FILTER_TYPE_BEST]=D3DTEXF_POINT; + _MipMapFilters[0][FILTER_TYPE_BEST]=D3DTEXF_POINT; +#else + _MinTextureFilters[0][FILTER_TYPE_NONE]=D3DTEXF_ANISOTROPIC; + _MagTextureFilters[0][FILTER_TYPE_NONE]=D3DTEXF_ANISOTROPIC; + _MipMapFilters[0][FILTER_TYPE_NONE]=D3DTEXF_LINEAR; + + _MinTextureFilters[0][FILTER_TYPE_FAST]=D3DTEXF_ANISOTROPIC; + _MagTextureFilters[0][FILTER_TYPE_FAST]=D3DTEXF_ANISOTROPIC; + _MipMapFilters[0][FILTER_TYPE_FAST]=D3DTEXF_LINEAR; + + _MagTextureFilters[0][FILTER_TYPE_BEST]=D3DTEXF_ANISOTROPIC; + _MinTextureFilters[0][FILTER_TYPE_BEST]=D3DTEXF_ANISOTROPIC; + _MipMapFilters[0][FILTER_TYPE_BEST]=D3DTEXF_LINEAR; +#endif + +#ifndef _XBOX + if (dx8caps.TextureFilterCaps&D3DPTFILTERCAPS_MAGFLINEAR) _MagTextureFilters[0][FILTER_TYPE_BEST]=D3DTEXF_LINEAR; + if (dx8caps.TextureFilterCaps&D3DPTFILTERCAPS_MINFLINEAR) _MinTextureFilters[0][FILTER_TYPE_BEST]=D3DTEXF_LINEAR; + + // Set anisotropic filtering only if requested and available + if (filter_type==TEXTURE_FILTER_ANISOTROPIC) { + if (dx8caps.TextureFilterCaps&D3DPTFILTERCAPS_MAGFANISOTROPIC) _MagTextureFilters[0][FILTER_TYPE_BEST]=D3DTEXF_ANISOTROPIC; + if (dx8caps.TextureFilterCaps&D3DPTFILTERCAPS_MINFANISOTROPIC) _MinTextureFilters[0][FILTER_TYPE_BEST]=D3DTEXF_ANISOTROPIC; } - if (dx8caps.TextureFilterCaps&D3DPTFILTERCAPS_MINFANISOTROPIC) _MinTextureFilters[FILTER_TYPE_BEST]=D3DTEXF_ANISOTROPIC; - else if (dx8caps.TextureFilterCaps&D3DPTFILTERCAPS_MINFLINEAR) _MinTextureFilters[FILTER_TYPE_BEST]=D3DTEXF_LINEAR; - else if (dx8caps.TextureFilterCaps&D3DPTFILTERCAPS_MINFPOINT) _MinTextureFilters[FILTER_TYPE_BEST]=D3DTEXF_POINT; - else { - WWASSERT_PRINT(0,("No minification filter found!")); + // Set linear mip filter only if requested trilinear or anisotropic, and linear available + if (filter_type==TEXTURE_FILTER_ANISOTROPIC || filter_type==TEXTURE_FILTER_TRILINEAR) { + if (dx8caps.TextureFilterCaps&D3DPTFILTERCAPS_MIPFLINEAR) _MipMapFilters[0][FILTER_TYPE_BEST]=D3DTEXF_LINEAR; } +#endif + + // For stages above zero, set best filter to the same as the stage zero, except if anisotropic + int i=1; + 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 : DX8 Texture Manager * + * * + * $Archive:: /Commando/Code/ww3d2/textureloader.h $* + * * + * Original Author:: vss_sync * + * * + * Author : Kenny Mitchell * + * * + * $Modtime:: 08/05/02 10:03a $* + * * + * $Revision:: 3 $* + * * + * 06/27/02 KM Texture class abstraction * + * 08/05/02 KM Texture class redesign (revisited) + *---------------------------------------------------------------------------------------------* + * Functions: * + * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ + #include "textureloader.h" #include "mutex.h" #include "thread.h" @@ -36,14 +58,225 @@ #include "texturethumbnail.h" #include "ddsfile.h" #include "bitmaphandler.h" +#include "wwprofile.h" + +bool TextureLoader::TextureLoadSuspended; +int TextureLoader::TextureInactiveOverrideTime = 0; + +#define USE_MANAGED_TEXTURES + +//////////////////////////////////////////////////////////////////////////////// +// +// TextureLoadTaskListClass implementation +// +//////////////////////////////////////////////////////////////////////////////// + +TextureLoadTaskListClass::TextureLoadTaskListClass(void) +: Root() +{ + Root.Next = Root.Prev = &Root; +} + +void TextureLoadTaskListClass::Push_Front (TextureLoadTaskClass *task) +{ + // task should non-null and not on any list + WWASSERT(task != NULL && task->Next == NULL && task->Prev == NULL); + + // update inserted task to point to list + task->Next = Root.Next; + task->Prev = &Root; + task->List = this; + + // update list to point to inserted task + Root.Next->Prev = task; + Root.Next = task; +} + +void TextureLoadTaskListClass::Push_Back(TextureLoadTaskClass *task) +{ + // task should be non-null and not on any list + WWASSERT(task != NULL && task->Next == NULL && task->Prev == NULL); + + // update inserted task to point to list + task->Next = &Root; + task->Prev = Root.Prev; + task->List = this; + + // update list to point to inserted task + Root.Prev->Next = task; + Root.Prev = task; +} + +TextureLoadTaskClass *TextureLoadTaskListClass::Pop_Front(void) +{ + // exit early if list is empty + if (Is_Empty()) { + return 0; + } + + // otherwise, grab first task and remove it. + TextureLoadTaskClass *task = (TextureLoadTaskClass *)Root.Next; + Remove(task); + return task; + +} + +TextureLoadTaskClass *TextureLoadTaskListClass::Pop_Back(void) +{ + // exit early if list is empty + if (Is_Empty()) { + return 0; + } + + // otherwise, grab last task and remove it. + TextureLoadTaskClass *task = (TextureLoadTaskClass *)Root.Prev; + Remove(task); + return task; +} + +void TextureLoadTaskListClass::Remove(TextureLoadTaskClass *task) +{ + // exit early if task is not on this list. + if (task->List != this) { + return; + } + + // update list to skip task + task->Prev->Next = task->Next; + task->Next->Prev = task->Prev; + + // update task to no longer point at list + task->Prev = 0; + task->Next = 0; + task->List = 0; +} + + +//////////////////////////////////////////////////////////////////////////////// +// +// SynchronizedTextureLoadTaskListClass implementation +// +//////////////////////////////////////////////////////////////////////////////// + +SynchronizedTextureLoadTaskListClass::SynchronizedTextureLoadTaskListClass(void) +: TextureLoadTaskListClass(), + CriticalSection() +{ +} + +void SynchronizedTextureLoadTaskListClass::Push_Front(TextureLoadTaskClass *task) +{ + FastCriticalSectionClass::LockClass lock(CriticalSection); + TextureLoadTaskListClass::Push_Front(task); +} + +void SynchronizedTextureLoadTaskListClass::Push_Back(TextureLoadTaskClass *task) +{ + FastCriticalSectionClass::LockClass lock(CriticalSection); + TextureLoadTaskListClass::Push_Back(task); +} + +TextureLoadTaskClass *SynchronizedTextureLoadTaskListClass::Pop_Front(void) +{ + // this duplicates code inside base class, but saves us an unnecessary lock. + if (Is_Empty()) { + return 0; + } + + FastCriticalSectionClass::LockClass lock(CriticalSection); + return TextureLoadTaskListClass::Pop_Front(); + +} + +TextureLoadTaskClass *SynchronizedTextureLoadTaskListClass::Pop_Back(void) +{ + // this duplicates code inside base class, but saves us an unnecessary lock. + if (Is_Empty()) { + return 0; + } + + FastCriticalSectionClass::LockClass lock(CriticalSection); + return TextureLoadTaskListClass::Pop_Back(); +} + +void SynchronizedTextureLoadTaskListClass::Remove(TextureLoadTaskClass *task) +{ + FastCriticalSectionClass::LockClass lock(CriticalSection); + TextureLoadTaskListClass::Remove(task); +} + + +// Locks + +// To prevent deadlock, threads should acquire locks in the order in which +// they are defined below. No ordering is necessary for the task list locks, +// since one thread can never hold two at once. + +static FastCriticalSectionClass _ForegroundCriticalSection; +static FastCriticalSectionClass _BackgroundCriticalSection; + +// Lists + +static SynchronizedTextureLoadTaskListClass _ForegroundQueue; +static SynchronizedTextureLoadTaskListClass _BackgroundQueue; + +static TextureLoadTaskListClass _TexLoadFreeList; +static TextureLoadTaskListClass _CubeTexLoadFreeList; +static TextureLoadTaskListClass _VolTexLoadFreeList; + + +// The background texture loading thread. +static class LoaderThreadClass : public ThreadClass +{ +public: +#ifdef Exception_Handler + LoaderThreadClass(const char *thread_name = "Texture loader thread") : ThreadClass(thread_name, &Exception_Handler) {} +#else + LoaderThreadClass(const char *thread_name = "Texture loader thread") : ThreadClass(thread_name) {} +#endif + + void Thread_Function(); +} _TextureLoadThread; + + +// TODO: Legacy - remove this call! +IDirect3DTexture8* Load_Compressed_Texture( + const StringClass& filename, + unsigned reduction_factor, + MipCountType mip_level_count, + WW3DFormat dest_format) +{ + // If DDS file isn't available, use TGA file to convert to DDS. + + DDSFileClass dds_file(filename,reduction_factor); + if (!dds_file.Is_Available()) return NULL; + if (!dds_file.Load()) return NULL; + + unsigned width=dds_file.Get_Width(0); + unsigned height=dds_file.Get_Height(0); + unsigned mips=dds_file.Get_Mip_Level_Count(); + + // If format isn't defined get the nearest valid texture format to the compressed file format + // Note that the nearest valid format could be anything, even uncompressed. + if (dest_format==WW3D_FORMAT_UNKNOWN) dest_format=Get_Valid_Texture_Format(dds_file.Get_Format(),true); -static TextureLoadTaskClass* LoadListHead; -static TextureLoadTaskClass* DeferredListHead; -static TextureLoadTaskClass* FinishedListHead; -static TextureLoadTaskClass* ThumbnailListHead; -static TextureLoadTaskClass* DeleteTaskListHead; + IDirect3DTexture8* d3d_texture = DX8Wrapper::_Create_DX8_Texture + ( + width, + height, + dest_format, + (MipCountType)mips + ); -TextureLoadTaskClass* TextureLoadTaskClass::FreeTaskListHead; + for (unsigned level=0;levelGetSurfaceLevel(level/*-reduction_factor*/,&d3d_surface)); + dds_file.Copy_Level_To_Surface(level,d3d_surface); + d3d_surface->Release(); + } + return d3d_texture; +} static bool Is_Format_Compressed(WW3DFormat texture_format,bool allow_compression) { @@ -77,46 +310,41 @@ static bool Is_Format_Compressed(WW3DFormat texture_format,bool allow_compressio return compressed; } -// ---------------------------------------------------------------------------- - -static CriticalSectionClass mutex; -static class LoaderThreadClass : public ThreadClass -{ - TextureLoadTaskClass* Get_Task_From_Load_List(); - - static void Add_Task_To_Finished_List(TextureLoadTaskClass* task); - -public: - LoaderThreadClass() : ThreadClass() {} - - void Thread_Function(); - - static void Add_Task_To_Load_List(TextureLoadTaskClass* task); -} thread; - -// ---------------------------------------------------------------------------- +//////////////////////////////////////////////////////////////////////////////// +// +// TextureLoader implementation +// +//////////////////////////////////////////////////////////////////////////////// void TextureLoader::Init() { - WWASSERT(!thread.Is_Running()); + WWASSERT(!_TextureLoadThread.Is_Running()); - ThumbnailClass::Init(); + ThumbnailManagerClass::Init(); - thread.Execute(); - thread.Set_Priority(-3); + _TextureLoadThread.Execute(); + _TextureLoadThread.Set_Priority(-4); + TextureInactiveOverrideTime = 0; } -// ---------------------------------------------------------------------------- void TextureLoader::Deinit() { - CriticalSectionClass::LockClass m(mutex); - thread.Stop(); + FastCriticalSectionClass::LockClass lock(_BackgroundCriticalSection); + _TextureLoadThread.Stop(); + + ThumbnailManagerClass::Deinit(); + TextureLoadTaskClass::Delete_Free_Pool(); +} + - ThumbnailClass::Deinit(); +bool TextureLoader::Is_DX8_Thread(void) +{ + return (ThreadClass::_Get_Current_Thread_ID() == DX8Wrapper::_Get_Main_Thread_ID()); } + // ---------------------------------------------------------------------------- // // Modify given texture size to nearest valid size on current hardware. @@ -183,42 +411,49 @@ void TextureLoader::Validate_Texture_Size depth=poweroftwodepth; } -IDirect3DTexture8* TextureLoader::Load_Thumbnail(const StringClass& filename,WW3DFormat texture_format) +IDirect3DTexture8* TextureLoader::Load_Thumbnail(const StringClass& filename, const Vector3& hsv_shift)//,WW3DFormat texture_format) { - ThumbnailClass* thumb=ThumbnailClass::Peek_Instance(filename); + WWASSERT(Is_DX8_Thread()); + + ThumbnailClass* thumb=NULL; + thumb=ThumbnailManagerClass::Peek_Thumbnail_Instance_From_Any_Manager(filename); + + // If no thumb is found return a missing texture if (!thumb) { - thumb=W3DNEW ThumbnailClass(filename); - // If load failed, return missing texture - if (!thumb->Peek_Bitmap()) { - delete thumb; - return MissingTexture::_Get_Missing_Texture(); - } + return MissingTexture::_Get_Missing_Texture(); } - unsigned src_pitch=thumb->Get_Width()*4; // Thumbs are always 32 bits + WWASSERT(thumb->Get_Format()==WW3D_FORMAT_A4R4G4B4); + unsigned src_pitch=thumb->Get_Width()*2; // Thumbs are always 16 bits WW3DFormat dest_format; + WW3DFormat texture_format=WW3D_FORMAT_UNKNOWN; if (texture_format==WW3D_FORMAT_UNKNOWN) { - dest_format=Get_Valid_Texture_Format(WW3D_FORMAT_A8R8G8B8,false); // no compressed formats please + dest_format=Get_Valid_Texture_Format(WW3D_FORMAT_A4R4G4B4,false); // no compressed formats please } else { dest_format=Get_Valid_Texture_Format(texture_format,false); // no compressed formats please WWASSERT(dest_format==texture_format); } - IDirect3DTexture8* d3d_texture = DX8Wrapper::_Create_DX8_Texture( + IDirect3DTexture8* sysmem_texture = DX8Wrapper::_Create_DX8_Texture( thumb->Get_Width(), thumb->Get_Height(), dest_format, - MIP_LEVELS_ALL); + MIP_LEVELS_ALL, +#ifdef USE_MANAGED_TEXTURES + D3DPOOL_MANAGED); +#else + D3DPOOL_SYSTEMMEM); +#endif unsigned level=0; D3DLOCKED_RECT locked_rects[12]={0}; - WWASSERT(d3d_texture->GetLevelCount()<=12); + WWASSERT(sysmem_texture->GetLevelCount()<=12); // Lock all surfaces - for (level=0;levelGetLevelCount();++level) { + for (level=0;levelGetLevelCount();++level) { DX8_ErrorCode( - d3d_texture->LockRect( + sysmem_texture->LockRect( level, &locked_rects[level], NULL, @@ -226,11 +461,12 @@ IDirect3DTexture8* TextureLoader::Load_Thumbnail(const StringClass& filename,WW3 } unsigned char* src_surface=thumb->Peek_Bitmap(); - WW3DFormat src_format=WW3D_FORMAT_A8R8G8B8; + WW3DFormat src_format=thumb->Get_Format(); unsigned width=thumb->Get_Width(); unsigned height=thumb->Get_Height(); - for (level=0;levelGetLevelCount()-1;++level) { + Vector3 hsv=hsv_shift; + for (level=0;levelGetLevelCount()-1;++level) { BitmapHandlerClass::Copy_Image_Generate_Mipmap( width, height, @@ -241,7 +477,9 @@ IDirect3DTexture8* TextureLoader::Load_Thumbnail(const StringClass& filename,WW3 src_pitch, src_format, (unsigned char*)locked_rects[level+1].pBits, // mipmap - locked_rects[level+1].Pitch);// mipmap + locked_rects[level+1].Pitch, + hsv); + hsv=Vector3(0.0f,0.0f,0.0f); // Only do the shift for the first level, as the mipmaps are based on it. src_format=dest_format; src_surface=(unsigned char*)locked_rects[level].pBits; @@ -251,64 +489,27 @@ IDirect3DTexture8* TextureLoader::Load_Thumbnail(const StringClass& filename,WW3 } // Unlock all surfaces - for (level=0;levelGetLevelCount();++level) { - DX8_ErrorCode(d3d_texture->UnlockRect(level)); - } - - return d3d_texture; -} - -static bool Is_Power_Of_Two(unsigned i) -{ - if (!i) return false; - unsigned n=i; - unsigned shift=0; - while (n) { - shift++; - n>>=1; + for (level=0;levelGetLevelCount();++level) { + DX8_ErrorCode(sysmem_texture->UnlockRect(level)); } - return ((i>>(shift-1))<<(shift-1))==i; -} - -// ---------------------------------------------------------------------------- - -// TODO: Legacy - remove this call! -IDirect3DTexture8* Load_Compressed_Texture( - const StringClass& filename, - unsigned reduction_factor, - MipCountType mip_level_count, - WW3DFormat dest_format) -{ - // If DDS file isn't available, use TGA file to convert to DDS. - - DDSFileClass dds_file(filename,reduction_factor); - if (!dds_file.Is_Available()) return NULL; - if (!dds_file.Load()) return NULL; - - unsigned width=dds_file.Get_Width(0); - unsigned height=dds_file.Get_Height(0); - unsigned mips=dds_file.Get_Mip_Level_Count(); - - // If format isn't defined get the nearest valid texture format to the compressed file format - // Note that the nearest valid format could be anything, even uncompressed. - if (dest_format==WW3D_FORMAT_UNKNOWN) dest_format=Get_Valid_Texture_Format(dds_file.Get_Format(),true); - +#ifdef USE_MANAGED_TEXTURES + return sysmem_texture; +#else IDirect3DTexture8* d3d_texture = DX8Wrapper::_Create_DX8_Texture( - width, - height, + thumb->Get_Width(), + thumb->Get_Height(), dest_format, - (MipCountType)mips); + TextureBaseClass::MIP_LEVELS_ALL, + D3DPOOL_DEFAULT); + DX8CALL(UpdateTexture(sysmem_texture,d3d_texture)); + sysmem_texture->Release(); - for (unsigned level=0;levelGetSurfaceLevel(level/*-reduction_factor*/,&d3d_surface)); - dds_file.Copy_Level_To_Surface(level,d3d_surface); - d3d_surface->Release(); - } + WWDEBUG_SAY(("Created non-managed texture (%s)",filename)); return d3d_texture; +#endif } + // ---------------------------------------------------------------------------- // // Load image to a surface. The function tries to create texture that matches @@ -321,6 +522,8 @@ IDirect3DSurface8* TextureLoader::Load_Surface_Immediate( WW3DFormat texture_format, bool allow_compression) { + WWASSERT(Is_DX8_Thread()); + bool compressed=Is_Format_Compressed(texture_format,allow_compression); if (compressed) { @@ -423,967 +626,2194 @@ IDirect3DSurface8* TextureLoader::Load_Surface_Immediate( } -// ---------------------------------------------------------------------------- -// -// Load mipmap levels to a pre-generated and locked texture object based on -// information in load task object. Try loading from a DDS file first and if -// that fails try a TGA. -// -// ---------------------------------------------------------------------------- - -void TextureLoader::Load_Mipmap_Levels(TextureLoadTaskClass* task) +void TextureLoader::Request_Thumbnail(TextureBaseClass *tc) { - WWASSERT(task->Peek_D3D_Texture()); - WWMEMLOG(MEM_TEXTURE); + // Grab the foreground lock. This prevents the foreground thread + // from retiring any tasks related to this texture. It also + // serializes calls to Request_Thumbnail from multiple threads. + FastCriticalSectionClass::LockClass lock(_ForegroundCriticalSection); - if (task->Peek_Texture()->Is_Compression_Allowed()) { - DDSFileClass dds_file(task->Peek_Texture()->Get_Full_Path(),task->Get_Reduction()); - if (dds_file.Is_Available() && dds_file.Load()) { - unsigned width=task->Get_Width(); - unsigned height=task->Get_Height(); - for (unsigned level=0;levelGet_Mip_Level_Count();++level) { - WWASSERT(width && height); - dds_file.Copy_Level_To_Surface( - level, - task->Get_Format(), - width, - height, - task->Get_Locked_Surface_Ptr(level), - task->Get_Locked_Surface_Pitch(level)); - width>>=1; - height>>=1; - } - return; + // Has a Direct3D texture already been loaded? + if (tc->Peek_D3D_Base_Texture()) { + return; + } + + TextureLoadTaskClass *task = tc->ThumbnailLoadTask; + + if (Is_DX8_Thread()) { + // load the thumbnail immediately + TextureLoader::Load_Thumbnail(tc); + + // clear any pending thumbnail load + if (task) { + _ForegroundQueue.Remove(task); + task->Destroy(); + } + + } else { + TextureLoadTaskClass *load_task = tc->TextureLoadTask; + + // if texture is not already loading a thumbnail and there is no + // background load near completion. (a background load waiting + // to be applied will be ready at the same time as a queued thumbnail. + // Why do the extra work?) + if (!task && (!load_task || load_task->Get_State() < TextureLoadTaskClass::STATE_LOAD_MIPMAP)) { + + // create a thumbnail load task and add to foreground queue. + task = TextureLoadTaskClass::Create(tc, TextureLoadTaskClass::TASK_THUMBNAIL, TextureLoadTaskClass::PRIORITY_LOW); + _ForegroundQueue.Push_Back(task); } } - if (Load_Uncompressed_Mipmap_Levels_From_TGA(task)) return; } -// ---------------------------------------------------------------------------- -// -// Use load task to load texture surface from a targa file. Calculate mipmaps -// if needed. -// -// ---------------------------------------------------------------------------- -bool TextureLoader::Load_Uncompressed_Mipmap_Levels_From_TGA(TextureLoadTaskClass* task) +void TextureLoader::Request_Background_Loading(TextureBaseClass *tc) { - if (!task->Get_Mip_Level_Count()) return false; - TextureBaseClass* texture=task->Peek_Texture(); - - Targa targa; - if (TARGA_ERROR_HANDLER(targa.Open(texture->Get_Full_Path(), TGA_READMODE),texture->Get_Full_Path())) { - task->Set_Fail(true); - return false; + WWPROFILE(("TextureLoader::Request_Background_Loading()")); + // Grab the foreground lock. This prevents the foreground thread + // from retiring any tasks related to this texture. It also + // serializes calls to Request_Background_Loading from other + // threads. + FastCriticalSectionClass::LockClass foreground_lock(_ForegroundCriticalSection); + + // Has the texture already been loaded? + if (tc->Is_Initialized()) { + return; } - // DX8 uses image upside down compared to TGA - targa.Header.ImageDescriptor ^= TGAIDF_YORIGIN; - WW3DFormat src_format,dest_format; - unsigned src_bpp=0; - Get_WW3D_Format(dest_format,src_format,src_bpp,targa); -// WWASSERT(task->Get_Format()==dest_format); - dest_format=task->Get_Format(); // Texture can be requested in different format than the most obvious from the TGA + TextureLoadTaskClass *task = tc->TextureLoadTask; - char palette[256*4]; - targa.SetPalette(palette); + // if texture already has a load task, we don't need to create another one. + if (task) { + return; + } - unsigned src_width=targa.Header.Width; - unsigned src_height=targa.Header.Height; - unsigned width=task->Get_Width(); - unsigned height=task->Get_Height(); + task = TextureLoadTaskClass::Create(tc, TextureLoadTaskClass::TASK_LOAD, TextureLoadTaskClass::PRIORITY_LOW); - // NOTE: We load the palette but we do not yet support paletted textures! - if (TARGA_ERROR_HANDLER(targa.Load(texture->Get_Full_Path(), TGAF_IMAGE, false),texture->Get_Full_Path())) { - task->Set_Fail(true); - return false; + if (Is_DX8_Thread()) { + Begin_Load_And_Queue(task); + } else { + _ForegroundQueue.Push_Back(task); } - unsigned char* src_surface=(unsigned char*)targa.GetImage(); +} - // No paletted format allowed when generating mipmaps - unsigned char* converted_surface=NULL; - if (src_format==WW3D_FORMAT_A1R5G5B5 || src_format==WW3D_FORMAT_R5G6B5 || src_format==WW3D_FORMAT_A4R4G4B4 || - src_format==WW3D_FORMAT_P8 || src_format==WW3D_FORMAT_L8 || src_width!=width || src_height!=height) { - converted_surface=W3DNEWARRAY unsigned char[width*height*4]; - dest_format=Get_Valid_Texture_Format(WW3D_FORMAT_A8R8G8B8,false); - BitmapHandlerClass::Copy_Image( - converted_surface, - width, - height, - width*4, - WW3D_FORMAT_A8R8G8B8, //dest_format, - src_surface, - src_width, - src_height, - src_width*src_bpp, - src_format, - (unsigned char*)targa.GetPalette(), - targa.Header.CMapDepth>>3, - false); - src_surface=converted_surface; - src_format=WW3D_FORMAT_A8R8G8B8; //dest_format; - src_width=width; - src_height=height; - src_bpp=Get_Bytes_Per_Pixel(src_format); + +void TextureLoader::Request_Foreground_Loading(TextureBaseClass *tc) +{ + WWPROFILE(("TextureLoader::Request_Foreground_Loading()")); + // Grab the foreground lock. This prevents the foreground thread + // from retiring the load tasks for this texture. It also + // serializes calls to Request_Foreground_Loading from other + // threads. + FastCriticalSectionClass::LockClass foreground_lock(_ForegroundCriticalSection); + + // Has the texture already been loaded? + if (tc->Is_Initialized()) { + return; } - unsigned src_pitch=src_width*src_bpp; + TextureLoadTaskClass *task = tc->TextureLoadTask; + TextureLoadTaskClass *task_thumb = tc->ThumbnailLoadTask; - for (unsigned level=0;levelGet_Mip_Level_Count();++level) { - WWASSERT(task->Get_Locked_Surface_Ptr(level)); - BitmapHandlerClass::Copy_Image( - task->Get_Locked_Surface_Ptr(level), - width, - height, - task->Get_Locked_Surface_Pitch(level), - task->Get_Format(), - src_surface, - src_width, - src_height, - src_pitch, - src_format, - NULL, - 0, - true); + if (Is_DX8_Thread()) { - width>>=1; - height>>=1; - src_width>>=1; - src_height>>=1; - if (!width || !height || !src_width || !src_height) break; - } + // since we're in the DX8 thread, we can load the entire + // texture right now. - delete[] converted_surface; + // if we have a thumbnail task waiting, kill it. + if (task_thumb) { + _ForegroundQueue.Remove(task_thumb); + task_thumb->Destroy(); + } - return true; -} + if (task) { + // we need to remove the task from any queue, since we're going + // to finish it up right now. + + // halt background thread. After we're holding this lock, + // we know the background thread cannot begin loading + // mipmap levels for this texture. + FastCriticalSectionClass::LockClass background_lock(_BackgroundCriticalSection); + _ForegroundQueue.Remove(task); + _BackgroundQueue.Remove(task); + } else { + // Since the task manages all the state associated with loading + // a texture, we temporarily create one. + task = TextureLoadTaskClass::Create(tc, TextureLoadTaskClass::TASK_LOAD, TextureLoadTaskClass::PRIORITY_HIGH); + } -// ---------------------------------------------------------------------------- -// -// Return a task from the load list head. The loading thread uses this function -// to retrieve tasks from the load list. -// -// ---------------------------------------------------------------------------- + // finish loading the task and destroy it. + task->Finish_Load(); + task->Destroy(); -TextureLoadTaskClass* LoaderThreadClass::Get_Task_From_Load_List() -{ - CriticalSectionClass::LockClass m(mutex); + } else { + // we are not in the DX8 thread. We need to add a high-priority loading + // task to the foreground queue. - TextureLoadTaskClass* task=LoadListHead; - if (task) { - LoadListHead=task->Peek_Succ(); - task->Set_Succ(NULL); + // Grab the background lock. After we're holding this lock, we + // know the background thread cannot begin loading mipmap levels + // for this texture. + FastCriticalSectionClass::LockClass background_lock(_BackgroundCriticalSection); + + // if we have a thumbnail task, we should cancel it. Since we are not + // the foreground thread, we are not allowed to call Destroy(). Instead, + // leave it queued in the completed state so it will be destroyed by Update(). + if (task_thumb) { + task_thumb->Set_State(TextureLoadTaskClass::STATE_COMPLETE); + } + + if (task) { + // if a load task is waiting on the background queue, we need to + // move it to the foreground queue. + if (task->Get_List() == &_BackgroundQueue) { + + // remove task from list + _BackgroundQueue.Remove(task); + + // add to foreground queue. + _ForegroundQueue.Push_Back(task); + } + + // upgrade the task priority + task->Set_Priority(TextureLoadTaskClass::PRIORITY_HIGH); + + } else { + // allocate high priority load task + task = TextureLoadTaskClass::Create(tc, TextureLoadTaskClass::TASK_LOAD, TextureLoadTaskClass::PRIORITY_HIGH); + + // add to back of foreground queue. + _ForegroundQueue.Push_Back(task); + } } - return task; } -// ---------------------------------------------------------------------------- -// -// This function adds a load task to the head of the loading thread task list. -// The latest added task will be the next processed (There are good reasons -// for such ordering). The loading thread will process tasks from this list -// as soons as it can and then move the tasks to finished list. -// -// ---------------------------------------------------------------------------- -void LoaderThreadClass::Add_Task_To_Load_List(TextureLoadTaskClass* task) +void TextureLoader::Flush_Pending_Load_Tasks(void) { - CriticalSectionClass::LockClass m(mutex); + // This function can only be called from the main thread. + // (Only the main thread can make the DX8 calls necessary + // to complete texture loading. If we wanted to flush + // the pending tasks from another thread, we'd probably + // want to set a bool that is checked by Update(). + WWASSERT(Is_DX8_Thread()); - WWASSERT(task->Peek_Succ()==NULL); + for (;;) { + bool done = false; - task->Set_Succ(LoadListHead); - LoadListHead=task; + { + // we have no pending load tasks when both queues are empty + // and the background thread is not processing a texture. + + // Grab the background lock. Once we're holding it, we + // know that the background thread is not processing any + // textures. + + // NOTE: It's important that we do only hold on to the background + // lock while we check for completion. Otherwise, we will either + // violate the lock order when we call Update() (which grabs + // the foreground lock) or never give the background thread + // a chance to empty its queue. + FastCriticalSectionClass::LockClass background_lock(_BackgroundCriticalSection); + done = _BackgroundQueue.Is_Empty() && _ForegroundQueue.Is_Empty(); + } + + // exit loop if no entries in list + if (done) { + break; + } + + Update(); + ThreadClass::Switch_Thread(); + } } -// ---------------------------------------------------------------------------- -// -// After the loading thread is done with the texture, it is moved to the list -// of finished tasks so that the main thread can then finish up by unlocking -// the surfaces and applying the changes to the texture class object. -// -// ---------------------------------------------------------------------------- -void LoaderThreadClass::Add_Task_To_Finished_List(TextureLoadTaskClass* task) +// Nework update macro for texture loader. +#pragma warning(disable:4201) // warning C4201: nonstandard extension used : nameless struct/union +#include +#define UPDATE_NETWORK \ + if (network_callback) { \ + unsigned long time2 = timeGetTime(); \ + if (time2 - time > 20) { \ + network_callback(); \ + time = time2; \ + } \ + } \ + + +void TextureLoader::Update(void (*network_callback)(void)) { - CriticalSectionClass::LockClass m(mutex); + WWASSERT_PRINT(Is_DX8_Thread(), "TextureLoader::Update must be called from the main thread!"); + + if (TextureLoadSuspended) { + return; + } + + // grab foreground lock to prevent any other thread from + // modifying texture tasks. + FastCriticalSectionClass::LockClass lock(_ForegroundCriticalSection); + + unsigned long time = timeGetTime(); - WWASSERT(task->Peek_Succ()==NULL); + // while we have tasks on the foreground queue + while (TextureLoadTaskClass *task = _ForegroundQueue.Pop_Front()) { + UPDATE_NETWORK; + // dispatch to proper task handler + switch (task->Get_Type()) { + case TextureLoadTaskClass::TASK_THUMBNAIL: + Process_Foreground_Thumbnail(task); + break; + + case TextureLoadTaskClass::TASK_LOAD: + Process_Foreground_Load(task); + break; + } + } - task->Set_Succ(FinishedListHead); - FinishedListHead=task; + TextureBaseClass::Invalidate_Old_Unused_Textures(TextureInactiveOverrideTime); } -// ---------------------------------------------------------------------------- -// -// If we need to find out if the load task list is empty this is the function -// to use. We can't use Get_Task_From_Load_List() as if the list isn't empty -// it also removes the head node from the list. -// -// ---------------------------------------------------------------------------- +void TextureLoader::Suspend_Texture_Load() +{ + WWASSERT_PRINT(Is_DX8_Thread(),"TextureLoader::Suspend_Texture_Load must be called from the main thread!"); + TextureLoadSuspended=true; +} -bool Is_Load_List_Empty() +void TextureLoader::Continue_Texture_Load() { - return !LoadListHead; + WWASSERT_PRINT(Is_DX8_Thread(),"TextureLoader::Continue_Texture_Load must be called from the main thread!"); + TextureLoadSuspended=false; } -// ---------------------------------------------------------------------------- -// -// Texture loading thread loads textures that appear in loading_task_list. -// If the list is empty the thread sleeps. -// -// ---------------------------------------------------------------------------- -void LoaderThreadClass::Thread_Function() +void TextureLoader::Process_Foreground_Thumbnail(TextureLoadTaskClass *task) { - while (running) { - TextureLoadTaskClass* task=Get_Task_From_Load_List(); - if (task) { - TextureLoader::Load_Mipmap_Levels(task); - Add_Task_To_Finished_List(task); - } + switch (task->Get_State()) { + case TextureLoadTaskClass::STATE_NONE: + Load_Thumbnail(task->Peek_Texture()); + FALLTHROUGH; // NOTE: fall-through is intentional - Switch_Thread(); + case TextureLoadTaskClass::STATE_COMPLETE: + task->Destroy(); + break; } } -// ---------------------------------------------------------------------------- -// -// Update refreshes all completed texture loading tasks -// -// ---------------------------------------------------------------------------- -TextureLoadTaskClass* Get_Finished_Task() +void TextureLoader::Process_Foreground_Load(TextureLoadTaskClass *task) { - CriticalSectionClass::LockClass m(mutex); + // Is high-priority task? + if (task->Get_Priority() == TextureLoadTaskClass::PRIORITY_HIGH) { + task->Finish_Load(); + task->Destroy(); + return; + } - TextureLoadTaskClass* task=FinishedListHead; - if (task) { - FinishedListHead=task->Peek_Succ(); - task->Set_Succ(NULL); + // otherwise, must be a low-priority task. + + switch (task->Get_State()) { + case TextureLoadTaskClass::STATE_NONE: + Begin_Load_And_Queue(task); + break; + + case TextureLoadTaskClass::STATE_LOAD_MIPMAP: + task->End_Load(); + task->Destroy(); + break; } - return task; } -TextureLoadTaskClass* Get_Thumbnail_Task() -{ - CriticalSectionClass::LockClass m(mutex); - TextureLoadTaskClass* task=ThumbnailListHead; - if (task) { - ThumbnailListHead=task->Peek_Succ(); - task->Set_Succ(NULL); +void TextureLoader::Begin_Load_And_Queue(TextureLoadTaskClass *task) +{ + // should only be called from the DX8 thread. + WWASSERT(Is_DX8_Thread()); + + if (task->Begin_Load()) { + // add to front of background queue. This means the + // background load thread will service tasks in LIFO + // (last in, first out) order. + + // NOTE: this was how the old code did it, with a + // comment that mentioned good reasons for doing so, + // without actually listing the reasons. I suspect + // it has something to do with visually important textures, + // like those in the foreground, starting their load last. + _BackgroundQueue.Push_Front(task); + } else { + // unable to load. + task->Apply_Missing_Texture(); + task->Destroy(); } - return task; } -void Add_Thumbnail_Task(TextureLoadTaskClass* task) + +void TextureLoader::Load_Thumbnail(TextureBaseClass *tc) { - CriticalSectionClass::LockClass m(mutex); + // All D3D operations must run from main thread + WWASSERT(Is_DX8_Thread()); - WWASSERT(task->Peek_Succ()==NULL); + // load thumbnail texture + IDirect3DTexture8 *d3d_texture = Load_Thumbnail(tc->Get_Full_Path(),tc->Get_HSV_Shift()); - task->Set_Succ(ThumbnailListHead); - ThumbnailListHead=task; + // apply thumbnail to texture + if (tc->Get_Asset_Type()==TextureBaseClass::TEX_REGULAR) + { + tc->Apply_New_Surface(d3d_texture, false); + } + // release our reference to thumbnail texture + d3d_texture->Release(); + d3d_texture = 0; } -// ---------------------------------------------------------------------------- -// -// The main thread's update function deletes tasks from the load task list -// once a frame. -// -// ---------------------------------------------------------------------------- -TextureLoadTaskClass* Get_Task_From_Delete_List() +void LoaderThreadClass::Thread_Function(void) { - WWASSERT(ThreadClass::_Get_Current_Thread_ID()==DX8Wrapper::_Get_Main_Thread_ID()); + while (running) { + // if there are no tasks on the background queue, no need to grab background lock. + if (!_BackgroundQueue.Is_Empty()) { + // Grab background load so other threads know we could be + // loading a texture. + FastCriticalSectionClass::LockClass lock(_BackgroundCriticalSection); + + // try to remove a task from the background queue. This could fail + // if another thread modified the queue between our test above and + // grabbing the lock. + TextureLoadTaskClass* task = _BackgroundQueue.Pop_Front(); + if (task) { + // verify task is in proper state for background processing. + WWASSERT(task->Get_Type() == TextureLoadTaskClass::TASK_LOAD); + WWASSERT(task->Get_State() == TextureLoadTaskClass::STATE_LOAD_BEGUN); + + // load mip map levels and return to foreground queue for final step. + task->Load(); + _ForegroundQueue.Push_Back(task); + } + } - TextureLoadTaskClass* task=DeleteTaskListHead; - if (task) { - DeleteTaskListHead=task->Peek_Succ(); - task->Set_Succ(NULL); + Switch_Thread(); } - return task; } -// ---------------------------------------------------------------------------- + +//////////////////////////////////////////////////////////////////////////////// // -// When task wants to delete itself it adds itself to a delete list. This list -// can only be accessed from the main thread. +// TextureLoaderTaskClass implementation // -// ---------------------------------------------------------------------------- +//////////////////////////////////////////////////////////////////////////////// -void Add_Task_To_Delete_List(TextureLoadTaskClass* task) +TextureLoadTaskClass::TextureLoadTaskClass() +: Texture (0), + D3DTexture (0), + Format (WW3D_FORMAT_UNKNOWN), + Width (0), + Height (0), + MipLevelCount (0), + Reduction (0), + Type (TASK_NONE), + Priority (PRIORITY_LOW), + State (STATE_NONE), + HSVShift (0.0f,0.0f,0.0f) { - WWASSERT(ThreadClass::_Get_Current_Thread_ID()==DX8Wrapper::_Get_Main_Thread_ID()); + // because texture load tasks are pooled, the constructor and destructor + // don't need to do much. The work of attaching a task to a texture is + // is done by Init() and Deinit(). + + for (int i = 0; i < MIP_LEVELS_MAX; ++i) { + LockedSurfacePtr[i] = NULL; + LockedSurfacePitch[i] = 0; + } +} - WWASSERT(task->Peek_Succ()==NULL); - task->Set_Succ(DeleteTaskListHead); - DeleteTaskListHead=task; +TextureLoadTaskClass::~TextureLoadTaskClass(void) +{ + Deinit(); } -TextureLoadTaskClass* Get_Deferred_Task() + +TextureLoadTaskClass *TextureLoadTaskClass::Create(TextureBaseClass *tc, TaskType type, PriorityType priority) { - CriticalSectionClass::LockClass m(mutex); + // recycle or create a new texture load task with the given type + // and priority, then associate the texture with the task. - TextureLoadTaskClass* task=DeferredListHead; - if (task) { - DeferredListHead=task->Peek_Succ(); - task->Set_Succ(NULL); + // pull a load task from front of free list + TextureLoadTaskClass *task = NULL; + switch (tc->Get_Asset_Type()) + { + case TextureBaseClass::TEX_REGULAR : task=_TexLoadFreeList.Pop_Front(); break; + case TextureBaseClass::TEX_CUBEMAP : task=_CubeTexLoadFreeList.Pop_Front(); break; + case TextureBaseClass::TEX_VOLUME : task=_VolTexLoadFreeList.Pop_Front(); break; + default : WWASSERT(0); + }; + + // if no tasks on free list, allocate a new task + if (!task) + { + switch (tc->Get_Asset_Type()) + { + case TextureBaseClass::TEX_REGULAR : task=new TextureLoadTaskClass; break; + case TextureBaseClass::TEX_CUBEMAP : task=new CubeTextureLoadTaskClass; break; + case TextureBaseClass::TEX_VOLUME : task=new VolumeTextureLoadTaskClass; break; + default : WWASSERT(0); + } } + task->Init(tc, type, priority); return task; } -void Add_Deferred_Task(TextureLoadTaskClass* task) -{ - CriticalSectionClass::LockClass m(mutex); - - WWASSERT(task->Peek_Succ()==NULL); - task->Set_Succ(DeferredListHead); - DeferredListHead=task; -} -void TextureLoader::Flush_Pending_Load_Tasks() +void TextureLoadTaskClass::Destroy(void) { - while (!Is_Load_List_Empty()) { - Update(); - ThreadClass::Switch_Thread(); - } + // detach the task from its texture, and return to free pool. + Deinit(); + _TexLoadFreeList.Push_Front(this); } -void TextureLoader::Update() -{ - WWASSERT_PRINT(DX8Wrapper::_Get_Main_Thread_ID()==ThreadClass::_Get_Current_Thread_ID(),"TextureLoader::Update must be called from the main thread!"); - - while (TextureLoadTaskClass* task=Get_Deferred_Task()) { - task->Begin_Texture_Load(); // This will add the task to load list - } - while (TextureLoadTaskClass* task=Get_Finished_Task()) { - task->End_Load(); - task->Apply(true); - TextureLoadTaskClass::Release_Instance(task); +void TextureLoadTaskClass::Delete_Free_Pool(void) +{ + // (gth) We should probably just MEMPool these task objects... + while (TextureLoadTaskClass *task = _TexLoadFreeList.Pop_Front()) { + delete task; } - - while (TextureLoadTaskClass* task=Get_Thumbnail_Task()) { - task->Begin_Thumbnail_Load(); + while (TextureLoadTaskClass *task = _CubeTexLoadFreeList.Pop_Front()) { + delete task; } - - while (TextureLoadTaskClass* task=Get_Task_From_Delete_List()) { -// delete task; - TextureLoadTaskClass::Release_Instance(task); + while (TextureLoadTaskClass *task = _VolTexLoadFreeList.Pop_Front()) { + delete task; } } -// ---------------------------------------------------------------------------- -static DWORD VectortoRGBA( D3DXVECTOR3* v, FLOAT fHeight ) +void TextureLoadTaskClass::Init(TextureBaseClass* tc, TaskType type, PriorityType priority) { - DWORD r = (DWORD)( 127.0f * v->x + 128.0f ); - DWORD g = (DWORD)( 127.0f * v->y + 128.0f ); - DWORD b = (DWORD)( 127.0f * v->z + 128.0f ); - DWORD a = (DWORD)( 255.0f * fHeight ); + WWASSERT(tc); - return( (a<<24L) + (r<<16L) + (g<<8L) + (b<<0L) ); -} + // NOTE: we must be in the main thread to avoid corrupting the texture's refcount. + WWASSERT(TextureLoader::Is_DX8_Thread()); + REF_PTR_SET(Texture, tc); -IDirect3DTexture8* TextureLoader::Generate_Bumpmap(TextureBaseClass* texture) -{ - WW3DFormat bump_format=WW3D_FORMAT_U8V8; - if (!DX8Wrapper::Get_Current_Caps()->Support_Texture_Format(bump_format)) { - return MissingTexture::_Get_Missing_Texture(); - } + // Make sure texture has a filename. + WWASSERT(!Texture->Get_Full_Path().Is_Empty()); - D3DSURFACE_DESC desc; - IDirect3DTexture8* src_d3d_tex=texture->Peek_D3D_Texture(); - WWASSERT(src_d3d_tex); - DX8_ErrorCode(src_d3d_tex->GetLevelDesc(0,&desc)); - unsigned width=desc.Width; - unsigned height=desc.Height; + Type = type; + Priority = priority; + State = STATE_NONE; - IDirect3DTexture8* d3d_texture = DX8Wrapper::_Create_DX8_Texture( - width, - height, - bump_format, - MIP_LEVELS_1); + D3DTexture = 0; - D3DLOCKED_RECT src_locked_rect; - DX8_ErrorCode( - texture->Peek_D3D_Texture()->LockRect( - 0, - &src_locked_rect, - NULL, - D3DLOCK_READONLY)); + TextureClass* tex=Texture->As_TextureClass(); + + if (tex) + { + Format = tex->Get_Texture_Format(); // don't assume format yet KM + } + else + { + Format = WW3D_FORMAT_UNKNOWN; + } + + Width = 0; + Height = 0; + MipLevelCount = Texture->MipLevelCount; + Reduction = Texture->Get_Reduction(); + HSVShift = Texture->Get_HSV_Shift(); - D3DLOCKED_RECT dest_locked_rect; - DX8_ErrorCode( - d3d_texture->LockRect( - 0, - &dest_locked_rect, - NULL, - 0)); - WW3DFormat format=D3DFormat_To_WW3DFormat(desc.Format); - unsigned bpp=Get_Bytes_Per_Pixel(format); + for (int i = 0; i < MIP_LEVELS_MAX; ++i) + { + LockedSurfacePtr[i] = NULL; + LockedSurfacePitch[i] = 0; + } - for( unsigned y=0; yThumbnailLoadTask == NULL); + Texture->ThumbnailLoadTask = this; + break; - if( y == desc.Height-1 ) // Don't go past the last line - src_ptr_next_line = src_ptr_mid; - if( y == 0 ) // Don't go before first line - src_ptr_prev_line = src_ptr_mid; + case TASK_LOAD: + WWASSERT(Texture->TextureLoadTask == NULL); + Texture->TextureLoadTask = this; + break; + } +} - for( unsigned x=0; x1 ) ? 63 : 127; +void TextureLoadTaskClass::Deinit() +{ + // task should not be on any list when it is being detached from texture. + WWASSERT(Next == NULL); + WWASSERT(Prev == NULL); - switch( bump_format ) - { - case WW3D_FORMAT_U8V8: - *dest_ptr++ = (unsigned char)iDu; - *dest_ptr++ = (unsigned char)iDv; - break; + WWASSERT(D3DTexture == NULL); - 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; + for (int i = 0; i < MIP_LEVELS_MAX; ++i) { + WWASSERT(LockedSurfacePtr[i] == NULL); + } - case WW3D_FORMAT_X8L8V8U8: - *dest_ptr++ = (unsigned char)iDu; - *dest_ptr++ = (unsigned char)iDv; - *dest_ptr++ = (unsigned char)uL; - *dest_ptr++ = (unsigned char)0L; + if (Texture) { + switch (Type) { + case TASK_THUMBNAIL: + WWASSERT(Texture->ThumbnailLoadTask == this); + Texture->ThumbnailLoadTask = NULL; break; - } - // Move one pixel to the left (src is 32-bpp) - src_ptr_mid+=bpp; - src_ptr_prev_line+=bpp; - src_ptr_next_line+=bpp; + case TASK_LOAD: + WWASSERT(Texture->TextureLoadTask == this); + Texture->TextureLoadTask = NULL; + break; } - } - DX8_ErrorCode(d3d_texture->UnlockRect(0)); - DX8_ErrorCode(texture->Peek_D3D_Texture()->UnlockRect(0)); - return d3d_texture; + // NOTE: we must be in main thread to avoid corrupting Texture's refcount. + WWASSERT(TextureLoader::Is_DX8_Thread()); + REF_PTR_RELEASE(Texture); + } } -// ---------------------------------------------------------------------------- -// -// Public texture request functions. These functions can be used to request -// texture loading. -// -// ---------------------------------------------------------------------------- -void TextureLoader::Add_Load_Task(TextureBaseClass* tc) +bool TextureLoadTaskClass::Begin_Load(void) { - // If the texture is already being loaded we just exit here. - if (tc->TextureLoadTask) return; - - TextureLoadTaskClass* task=TextureLoadTaskClass::Get_Instance(tc,false); - task->Begin_Texture_Load(); -} + WWASSERT(TextureLoader::Is_DX8_Thread()); -// ---------------------------------------------------------------------------- + bool loaded = false; -void TextureLoader::Request_High_Priority_Loading( - TextureBaseClass* tc, - MipCountType mip_level_count) -{ - TextureLoadTaskClass* task=TextureLoadTaskClass::Get_Instance(tc,true); - task->Begin_Texture_Load(); -} + // if allowed, begin a compressed load + if (Texture->Is_Compression_Allowed()) { + loaded = Begin_Compressed_Load(); + } -// ---------------------------------------------------------------------------- + // otherwise, begin an uncompressed load + if (!loaded) { + loaded = Begin_Uncompressed_Load(); + } -void TextureLoader::Request_Thumbnail(TextureBaseClass* tc) -{ - // If the texture is already being loaded we just exit here. - if (tc->TextureLoadTask) return; + // if not loaded, abort. + if (!loaded) { + return false; + } - TextureLoadTaskClass* task=TextureLoadTaskClass::Get_Instance(tc,false); - task->Begin_Thumbnail_Load(); -} + // lock surfaces in preparation for copy + Lock_Surfaces(); -// ---------------------------------------------------------------------------- -// -// Texture loader task handler -// -// ---------------------------------------------------------------------------- + State = STATE_LOAD_BEGUN; -TextureLoadTaskClass::TextureLoadTaskClass() - : - Texture(0), - Succ(0), - D3DTexture(0), - Width(0), - Height(0), - Format(WW3D_FORMAT_UNKNOWN), - IsLoading(false), - HasFailed(false), - MipLevelCount(0), - HighPriorityRequested(false), - Reduction(0) -{ + return true; } + // ---------------------------------------------------------------------------- // -// Destruct texture load task. The load task deinitialization will fail from -// any other than the main thread so the task must be either deleted from the -// main thread or deinitialized in the main thread prior to deleting it in -// another thread. +// Load mipmap levels to a pre-generated and locked texture object based on +// information in load task object. Try loading from a DDS file first and if +// that fails try a TGA. // // ---------------------------------------------------------------------------- - -TextureLoadTaskClass::~TextureLoadTaskClass() -{ - Deinit(); -} - -void TextureLoadTaskClass::Init(TextureBaseClass* tc,bool high_priority) +bool TextureLoadTaskClass::Load(void) { - // Make sure texture has a filename. - REF_PTR_SET(Texture,tc); - //WWASSERT(!Texture->Get_Full_Path().Is_Empty()); + WWMEMLOG(MEM_TEXTURE); + WWASSERT(Peek_D3D_Texture()); - Reduction=Texture->Get_Reduction(); - HighPriorityRequested=high_priority; - IsLoading=false; - HasFailed=false; - MipLevelCount=tc->MipLevelCount; - D3DTexture=0; - Width=0; - Height=0; - Format=Texture->Get_Texture_Format(); + bool loaded = false; - Texture->TextureLoadTask=this; - for (int i=0;iIs_Compression_Allowed()) { + loaded = Load_Compressed_Mipmap(); } -} -void TextureLoadTaskClass::Deinit() -{ - WWASSERT(Succ==NULL); - WWASSERT(D3DTexture==NULL); - WWASSERT(IsLoading==false); - for (int i=0;iTextureLoadTask==this); - Texture->TextureLoadTask=NULL; + // otherwise, load uncompressed mipmaps + if (!loaded) { + loaded = Load_Uncompressed_Mipmap(); } - REF_PTR_RELEASE(Texture); - WWASSERT(!D3DTexture); -} - -// ---------------------------------------------------------------------------- -// -// -// -// ---------------------------------------------------------------------------- + State = STATE_LOAD_MIPMAP; -void TextureLoadTaskClass::Begin_Texture_Load() -{ - // If we're in main thread, init for loading and add to the load list - if (ThreadClass::_Get_Current_Thread_ID()==DX8Wrapper::_Get_Main_Thread_ID()) { - - bool loaded=false; - if (Texture->Is_Compression_Allowed()) { - DDSFileClass dds_file(Texture->Get_Full_Path(),Get_Reduction()); - if (dds_file.Is_Available()) { - // Destination size will be the next power of two square from the larger width and height... - unsigned width=0, height=0, depth=1; - width=dds_file.Get_Width(0); - height=dds_file.Get_Height(0); - TextureLoader::Validate_Texture_Size(width,height,depth); - - // If the size doesn't match, try and see if texture reduction would help... (mainly for - // cases where loaded texture is larger than hardware limit) - if (width!=dds_file.Get_Width(0) || height!=dds_file.Get_Height(0)) { - for (unsigned i=1;iIs_Compression_Allowed()); - - unsigned mip_level_count=Get_Mip_Level_Count(); - // If texture wants all mip levels, take as many as the file contains (not necessarily all) - // Otherwise take as many mip levels as the texture wants, not to exceed the count in file... - if (!mip_level_count) mip_level_count=dds_file.Get_Mip_Level_Count(); - else if (mip_level_count>dds_file.Get_Mip_Level_Count()) mip_level_count=dds_file.Get_Mip_Level_Count(); - - // Once more, verify that the mip level count is correct (in case it was changed here it might not - // match the size...well actually it doesn't have to match but it can't be bigger than the size) - unsigned max_mip_level_count=1; - unsigned w=4; - unsigned h=4; - while (wmax_mip_level_count) mip_level_count=max_mip_level_count; - - D3DTexture=DX8Wrapper::_Create_DX8_Texture(Width,Height,Format,(MipCountType)mip_level_count); - MipLevelCount=mip_level_count; - //Texture->MipLevelCount); - loaded=true; - } - } + return loaded; +} - if (!loaded) { - Targa targa; - if (TARGA_ERROR_HANDLER(targa.Open(Texture->Get_Full_Path(), TGA_READMODE),Texture->Get_Full_Path())) { - D3DTexture=MissingTexture::_Get_Missing_Texture(); - HasFailed=true; - IsLoading=false; - End_Load(); - Apply(true); - Add_Task_To_Delete_List(this); - return; - } +void TextureLoadTaskClass::End_Load(void) +{ + WWASSERT(TextureLoader::Is_DX8_Thread()); - unsigned bpp; - WW3DFormat src_format,dest_format; - Get_WW3D_Format(dest_format,src_format,bpp,targa); - if (src_format!=WW3D_FORMAT_A8R8G8B8 && - src_format!=WW3D_FORMAT_R8G8B8 && - src_format!=WW3D_FORMAT_X8R8G8B8) { - WWDEBUG_SAY(("Invalid TGA format used in %s - only 24 and 32 bit formats should be used!",Texture->Get_Full_Path().str())); - } + Unlock_Surfaces(); + Apply(true); - // Destination size will be the next power of two square from the larger width and height... - unsigned width=targa.Header.Width, height=targa.Header.Height, depth=1; - int ReductionFactor=Get_Reduction(); - int MipLevels=0; - - //Figure out how many mip levels this texture will occupy - for (int i=width, j=height; i > 0 && j > 0; i>>=1, j>>=1) - MipLevels++; - - //Adjust the reduction factor to keep textures above some minimum dimensions - if (MipLevels <= WW3D::Get_Texture_Min_Dimension()) - ReductionFactor=0; - else - { int mipToDrop=MipLevels-WW3D::Get_Texture_Min_Dimension(); - if (ReductionFactor >= mipToDrop) - ReductionFactor=mipToDrop; - } + State = STATE_LOAD_COMPLETE; +} - width=targa.Header.Width>>ReductionFactor; - height=targa.Header.Height>>ReductionFactor; - unsigned ow=width; - unsigned oh=height; - TextureLoader::Validate_Texture_Size(width,height,depth); - if (width!=ow || height!=oh) { - WWDEBUG_SAY(("Invalid texture size, scaling required. Texture: %s, size: %d x %d -> %d x %d",Texture->Get_Full_Path().str(),ow,oh,width,height)); - } - IsLoading=true; - Width=width; - Height=height; +void TextureLoadTaskClass::Finish_Load(void) +{ + switch (State) { + // NOTE: fall-through below is intentional. - if (Format==WW3D_FORMAT_UNKNOWN) { - Format=Get_Valid_Texture_Format(dest_format,false); - } - else { - Format=Get_Valid_Texture_Format(Format,false); + case STATE_NONE: + if (!Begin_Load()) { + Apply_Missing_Texture(); + break; } + FALLTHROUGH; - D3DTexture=DX8Wrapper::_Create_DX8_Texture(Width,Height,Format,Texture->MipLevelCount); - } - - MipLevelCount=D3DTexture->GetLevelCount(); - for (unsigned i=0;iLockRect( - i, - &locked_rect, - NULL, - 0)); - LockedSurfacePtr[i]=(unsigned char*)locked_rect.pBits; - LockedSurfacePitch[i]=locked_rect.Pitch; - } + case STATE_LOAD_BEGUN: + Load(); + FALLTHROUGH; - if (HighPriorityRequested) { - TextureLoader::Load_Mipmap_Levels(this); + case STATE_LOAD_MIPMAP: End_Load(); - Apply(true); - Add_Task_To_Delete_List(this); - } - else { - LoaderThreadClass::Add_Task_To_Load_List(this); - } - } - // Otherwise add to deferred list which will be handled by main thread - else { - Add_Deferred_Task(this); + FALLTHROUGH; + + default: + break; } } -/* file_auto_ptr my_tga_file(_TheFileFactory,Texture->Get_Full_Path()); - if (my_tga_file->Is_Available()) { - my_tga_file->Open(); - unsigned size=my_tga_file->Size(); - char* tga_memory=W3DNEWARRAY char[size]; - my_tga_file->Read(tga_memory,size); - my_tga_file->Close(); - StringClass pth("data\\"); - pth+=Texture->Get_Texture_Name(); - RawFileClass tmp_tga_file(pth); - tmp_tga_file.Create(); - tmp_tga_file.Write(tga_memory,size); - tmp_tga_file.Close(); - delete[] tga_memory; +void TextureLoadTaskClass::Apply_Missing_Texture(void) +{ + WWASSERT(TextureLoader::Is_DX8_Thread()); + WWASSERT(!D3DTexture); + + D3DTexture = MissingTexture::_Get_Missing_Texture(); + Apply(true); +} + + +void TextureLoadTaskClass::Apply(bool initialize) +{ + WWASSERT(D3DTexture); + + // Verify that none of the mip levels are locked + for (unsigned i=0;iApply_New_Surface(D3DTexture, initialize); + + D3DTexture->Release(); + D3DTexture = NULL; +} + +static bool Get_Texture_Information +( + const char* filename, + unsigned& reduction, + unsigned& w, + unsigned& h, + unsigned& d, + WW3DFormat& format, + unsigned& mip_count, + bool compressed +) +{ + ThumbnailClass* thumb=ThumbnailManagerClass::Peek_Thumbnail_Instance_From_Any_Manager(filename); + + if (!thumb) + { + if (compressed) + { + DDSFileClass dds_file(filename, 0); + if (!dds_file.Is_Available()) return false; + + // Destination size will be the next power of two square from the larger width and height... + w = dds_file.Get_Width(0); + h = dds_file.Get_Height(0); + d = dds_file.Get_Depth(0); + format = dds_file.Get_Format(); + mip_count = dds_file.Get_Mip_Level_Count(); + //Figure out correct reduction + int reqReduction=WW3D::Get_Texture_Reduction(); //requested reduction + + if (reqReduction >= mip_count) + reqReduction=mip_count-1; //leave only the lowest level + + //Clamp reduction + int curReduction=0; + int curWidth=w; + int curHeight=h; + int minDim=WW3D::Get_Texture_Min_Dimension(); + + while (curReduction < reqReduction && curWidth > minDim && curHeight > minDim) + { curWidth >>=1; //keep dividing + curHeight >>=1; + curReduction++; + } + reduction=curReduction; + return true; + } + + Targa targa; + if (TARGA_ERROR_HANDLER(targa.Open(filename, TGA_READMODE), filename)) + { + return false; + } + + unsigned int bpp; + WW3DFormat dest_format; + Get_WW3D_Format(dest_format,format,bpp,targa); + + mip_count = 0; + + //Figure out how many mip levels this texture will occupy + for (int i=targa.Header.Width, j=targa.Header.Height; i > 0 && j > 0; i>>=1, j>>=1) + mip_count++; + + //Figure out correct reduction + int reqReduction=WW3D::Get_Texture_Reduction(); //requested reduction + + if (reqReduction >= mip_count) + reqReduction=mip_count-1; //leave only the lowest level + + //Clamp reduction + int curReduction=0; + int curWidth=targa.Header.Width; + int curHeight=targa.Header.Height; + int minDim=WW3D::Get_Texture_Min_Dimension(); + + while (curReduction < reqReduction && curWidth > minDim && curHeight > minDim) + { curWidth >>=1; //keep dividing + curHeight >>=1; + curReduction++; + } + reduction=curReduction; + + // Destination size will be the next power of two square from the larger width and height... + w = targa.Header.Width; + h = targa.Header.Height; + d = 1; + return true; + } + + if (compressed && + thumb->Get_Original_Texture_Format()!=WW3D_FORMAT_DXT1 && + thumb->Get_Original_Texture_Format()!=WW3D_FORMAT_DXT2 && + thumb->Get_Original_Texture_Format()!=WW3D_FORMAT_DXT3 && + thumb->Get_Original_Texture_Format()!=WW3D_FORMAT_DXT4 && + thumb->Get_Original_Texture_Format()!=WW3D_FORMAT_DXT5) { + return false; + } + + w=thumb->Get_Original_Texture_Width() >> reduction; + h=thumb->Get_Original_Texture_Height() >> reduction; + //d=thumb->Get_Original_Texture_Depth() >> reduction; // need to a volume texture support to thumbnails...maybe + mip_count=thumb->Get_Original_Texture_Mip_Level_Count(); + format=thumb->Get_Original_Texture_Format(); + return true; +} + + +bool TextureLoadTaskClass::Begin_Compressed_Load(void) +{ + unsigned orig_w,orig_h,orig_d,orig_mip_count,reduction; + WW3DFormat orig_format; + if (!Get_Texture_Information + ( + Texture->Get_Full_Path(), + reduction, + orig_w, + orig_h, + orig_d, + orig_format, + orig_mip_count, + true + ) + ) + { + return false; + } + + // Destination size will be the next power of two square from the larger width and height... + unsigned int width = orig_w; + unsigned int height = orig_h; + TextureLoader::Validate_Texture_Size(width, height,orig_d); + + // If the size doesn't match, try and see if texture reduction would help... (mainly for + // cases where loaded texture is larger than hardware limit) + if (width != orig_w || height != orig_h) + { + for (unsigned int i = 1; i < orig_mip_count; ++i) + { + unsigned w=orig_w>>i; + if (w<4) w=4; + unsigned h=orig_h>>i; + if (h<4) h=4; + unsigned tmp_w=w; + unsigned tmp_h=h; + + TextureLoader::Validate_Texture_Size(w,h,orig_d); + + if (w == tmp_w && h == tmp_h) + { + Reduction += i; + width = w; + height = h; + break; + } + } + } + + Width = width; + Height = height; + Format = Get_Valid_Texture_Format(orig_format, Texture->Is_Compression_Allowed()); + Reduction = reduction; + + + if (!Texture->Is_Reducible() || Texture->MipLevelCount == MIP_LEVELS_1) + Reduction = 0; //app doesn't want this texture to ever be reduced. + else + //Make sure we don't reduce below the level requested by the app + if (Texture->MipLevelCount != MIP_LEVELS_ALL && (Texture->MipLevelCount - Reduction) < 1) + Reduction = Texture->MipLevelCount - 1; + + //Another sanity check + if (Reduction >= orig_mip_count) + Reduction = 0; //should not be possible to get here, but check just in case. + + unsigned int mip_level_count = Get_Mip_Level_Count(); + int reducedWidth=Width; + int reducedHeight=Height; + + // If texture wants all mip levels, take as many as the file contains (not necessarily all) + // Otherwise take as many mip levels as the texture wants, not to exceed the count in file... + if (!mip_level_count) + { + reducedWidth >>= Reduction; + reducedHeight >>= Reduction; + mip_level_count = orig_mip_count-Reduction;//dds_file.Get_Mip_Level_Count(); + if (mip_level_count < 1) + mip_level_count = 1; //sanity check to make sure something gets loaded. + } + else + { + if (mip_level_count > orig_mip_count) + { //dds_file.Get_Mip_Level_Count()) { + mip_level_count = orig_mip_count;//dds_file.Get_Mip_Level_Count(); + } + + if (Reduction) + { reducedWidth >>= Reduction; + reducedHeight >>= Reduction; + mip_level_count -= Reduction; //reduced requested number by those removed. + } + } + + // Once more, verify that the mip level count is correct (in case it was changed here it might not + // match the size...well actually it doesn't have to match but it can't be bigger than the size) + unsigned int max_mip_level_count = 1; + unsigned int w = 4; + unsigned int h = 4; + + while (w < Width && h < Height) + { + w += w; + h += h; + max_mip_level_count++; + } + + if (mip_level_count > max_mip_level_count) + { + mip_level_count = max_mip_level_count; + } + + D3DTexture = DX8Wrapper::_Create_DX8_Texture + ( + reducedWidth, + reducedHeight, + Format, + (MipCountType)mip_level_count, +#ifdef USE_MANAGED_TEXTURES + D3DPOOL_MANAGED +#else + D3DPOOL_SYSTEMMEM +#endif + ); + + MipLevelCount = mip_level_count; + + return true; +} + +bool TextureLoadTaskClass::Begin_Uncompressed_Load(void) +{ + unsigned width,height,depth,orig_mip_count,reduction; + WW3DFormat orig_format; + if (!Get_Texture_Information + ( + Texture->Get_Full_Path(), + reduction, + width, + height, + depth, + orig_format, + orig_mip_count, + false + ) + ) + { + return false; + } + + WW3DFormat src_format=orig_format; + WW3DFormat dest_format=src_format; + dest_format=Get_Valid_Texture_Format(dest_format,false); // No compressed destination format if reading from targa... + + if ( src_format != WW3D_FORMAT_A8R8G8B8 + && src_format != WW3D_FORMAT_R8G8B8 + && src_format != WW3D_FORMAT_X8R8G8B8 ) + { + WWDEBUG_SAY(("Invalid TGA format used in %s - only 24 and 32 bit formats should be used!", Texture->Get_Full_Path().str())); + } + + // Destination size will be the next power of two square from the larger width and height... + unsigned ow = width; + unsigned oh = height; + TextureLoader::Validate_Texture_Size(width, height,depth); + if (width != ow || height != oh) + { + WWDEBUG_SAY(("Invalid texture size, scaling required. Texture: %s, size: %d x %d -> %d x %d", Texture->Get_Full_Path().str(), ow, oh, width, height)); + } + + Width = width; + Height = height; + Reduction = reduction; + + if (!Texture->Is_Reducible() || Texture->MipLevelCount == MIP_LEVELS_1) + Reduction = 0; //app doesn't want this texture to ever be reduced. + else + //Make sure we don't reduce below the level requested by the app + if (Texture->MipLevelCount != MIP_LEVELS_ALL && (Texture->MipLevelCount - Reduction) < 1) + Reduction = Texture->MipLevelCount - 1; + + //Another sanity check + if (Reduction >= orig_mip_count) + Reduction = 0; //should not be possible to get here, but check just in case. + + if (Format == WW3D_FORMAT_UNKNOWN) + { + Format=dest_format; + // Format = Get_Valid_Texture_Format(dest_format, false); validated above + } + else + { + Format = Get_Valid_Texture_Format(Format, false); + } + + int reducedWidth=Width; + int reducedHeight=Height; + int reducedMipCount=Texture->MipLevelCount; + + if (Reduction) + { //we don't care about specific levels so reduce them if needed. + reducedWidth >>= Reduction; + reducedHeight >>= Reduction; + if (reducedMipCount != MIP_LEVELS_ALL) + reducedMipCount -= Reduction; + } + + D3DTexture = DX8Wrapper::_Create_DX8_Texture + ( + reducedWidth, + reducedHeight, + Format, + (MipCountType)reducedMipCount, +#ifdef USE_MANAGED_TEXTURES + D3DPOOL_MANAGED +#else + D3DPOOL_SYSTEMMEM +#endif + ); + + return true; +} + +/* +bool TextureLoadTaskClass::Begin_Compressed_Load(void) +{ + DDSFileClass dds_file(Texture->Get_Full_Path(), Get_Reduction()); + if (!dds_file.Is_Available()) { + return false; + } + + // Destination size will be the next power of two square from the larger width and height... + unsigned int width = dds_file.Get_Width(0); + unsigned int height = dds_file.Get_Height(0); + TextureLoader::Validate_Texture_Size(width, height); + + // If the size doesn't match, try and see if texture reduction would help... (mainly for + // cases where loaded texture is larger than hardware limit) + if (width != dds_file.Get_Width(0) || height != dds_file.Get_Height(0)) { + for (unsigned int i = 1; i < dds_file.Get_Mip_Level_Count(); ++i) { + unsigned int w = dds_file.Get_Width(i); + unsigned int h = dds_file.Get_Height(i); + TextureLoader::Validate_Texture_Size(w,h); + + if (w == dds_file.Get_Width(i) && h == dds_file.Get_Height(i)) { + Reduction += i; + width = w; + height = h; + break; + } + } + } + + Width = width; + Height = height; + Format = Get_Valid_Texture_Format(dds_file.Get_Format(), Texture->Is_Compression_Allowed()); + + unsigned int mip_level_count = Get_Mip_Level_Count(); + + // If texture wants all mip levels, take as many as the file contains (not necessarily all) + // Otherwise take as many mip levels as the texture wants, not to exceed the count in file... + if (!mip_level_count) { + mip_level_count = dds_file.Get_Mip_Level_Count(); + } else if (mip_level_count > dds_file.Get_Mip_Level_Count()) { + mip_level_count = dds_file.Get_Mip_Level_Count(); + } + + // Once more, verify that the mip level count is correct (in case it was changed here it might not + // match the size...well actually it doesn't have to match but it can't be bigger than the size) + unsigned int max_mip_level_count = 1; + unsigned int w = 4; + unsigned int h = 4; + + while (w < Width && h < Height) { + w += w; + h += h; + max_mip_level_count++; + } + + if (mip_level_count > max_mip_level_count) { + mip_level_count = max_mip_level_count; + } + + D3DTexture = DX8Wrapper::_Create_DX8_Texture( + Width, + Height, + Format, + (TextureBaseClass::MipCountType)mip_level_count, +#ifdef USE_MANAGED_TEXTURES + D3DPOOL_MANAGED); +#else + D3DPOOL_SYSTEMMEM); +#endif + MipLevelCount = mip_level_count; + return true; +} + + +bool TextureLoadTaskClass::Begin_Uncompressed_Load(void) +{ + Targa targa; + if (TARGA_ERROR_HANDLER(targa.Open(Texture->Get_Full_Path(), TGA_READMODE), Texture->Get_Full_Path())) { + return false; + } + + unsigned int bpp; + WW3DFormat src_format, dest_format; + Get_WW3D_Format(dest_format,src_format,bpp,targa); + + if ( src_format != WW3D_FORMAT_A8R8G8B8 + && src_format != WW3D_FORMAT_R8G8B8 + && src_format != WW3D_FORMAT_X8R8G8B8) { + WWDEBUG_SAY(("Invalid TGA format used in %s - only 24 and 32 bit formats should be used!", Texture->Get_Full_Path())); + } + + // Destination size will be the next power of two square from the larger width and height... + unsigned width=targa.Header.Width, height=targa.Header.Height; + int ReductionFactor=Get_Reduction(); + int MipLevels=0; + + //Figure out how many mip levels this texture will occupy + for (int i=width, j=height; i > 0 && j > 0; i>>=1, j>>=1) + MipLevels++; + + //Adjust the reduction factor to keep textures above some minimum dimensions + if (MipLevels <= WW3D::Get_Texture_Min_Mip_Levels()) + ReductionFactor=0; + else + { int mipToDrop=MipLevels-WW3D::Get_Texture_Min_Mip_Levels(); + if (ReductionFactor >= mipToDrop) + ReductionFactor=mipToDrop; + } + + width=targa.Header.Width>>ReductionFactor; + height=targa.Header.Height>>ReductionFactor; + unsigned ow = width; + unsigned oh = height; + TextureLoader::Validate_Texture_Size(width, height); + if (width != ow || height != oh) { + WWDEBUG_SAY(("Invalid texture size, scaling required. Texture: %s, size: %d x %d -> %d x %d", Texture->Get_Full_Path(), ow, oh, width, height)); + } + + Width = width; + Height = height; + + // changed because format was being read from previous loading task?! KJM + Format=dest_format; + //if (Format == WW3D_FORMAT_UNKNOWN) { + // Format = Get_Valid_Texture_Format(dest_format, false); + //} else { + // Format = Get_Valid_Texture_Format(Format, false); + //} + + D3DTexture = DX8Wrapper::_Create_DX8_Texture + ( + Width, + Height, + Format, + Texture->MipLevelCount, +#ifdef USE_MANAGED_TEXTURES + D3DPOOL_MANAGED); +#else + D3DPOOL_SYSTEMMEM); +#endif + return true; +} +*/ + +void TextureLoadTaskClass::Lock_Surfaces(void) +{ + MipLevelCount = D3DTexture->GetLevelCount(); + + for (unsigned int i = 0; i < MipLevelCount; ++i) + { + D3DLOCKED_RECT locked_rect; + DX8_ErrorCode + ( + Peek_D3D_Texture()->LockRect + ( + i, + &locked_rect, + NULL, + 0 + ) + ); + LockedSurfacePtr[i] = (unsigned char *)locked_rect.pBits; + LockedSurfacePitch[i] = locked_rect.Pitch; + } +} + + +void TextureLoadTaskClass::Unlock_Surfaces(void) +{ + for (unsigned int i = 0; i < MipLevelCount; ++i) + { + if (LockedSurfacePtr[i]) + { + WWASSERT(ThreadClass::_Get_Current_Thread_ID() == DX8Wrapper::_Get_Main_Thread_ID()); + DX8_ErrorCode(Peek_D3D_Texture()->UnlockRect(i)); + } + LockedSurfacePtr[i] = NULL; + } + +#ifndef USE_MANAGED_TEXTURES + IDirect3DTexture8* tex = DX8Wrapper::_Create_DX8_Texture(Width, Height, Format, Texture->MipLevelCount,D3DPOOL_DEFAULT); + DX8CALL(UpdateTexture(Peek_D3D_Texture(),tex)); + Peek_D3D_Texture()->Release(); + D3DTexture=tex; + WWDEBUG_SAY(("Created non-managed texture (%s)",Texture->Get_Full_Path())); +#endif + +} + + +bool TextureLoadTaskClass::Load_Compressed_Mipmap(void) +{ + DDSFileClass dds_file(Texture->Get_Full_Path(), Get_Reduction()); + + // if we can't load from file, indicate rror. + if (!dds_file.Is_Available() || !dds_file.Load()) + { + return false; + } + + // regular 2d texture + unsigned int width = Get_Width(); + unsigned int height = Get_Height(); + + if (Reduction) + { for (unsigned int level = 0; level < Reduction; ++level) { + width >>= 1; + height >>= 1; + } + } + + for (unsigned int level = 0; level < Get_Mip_Level_Count(); ++level) + { + WWASSERT(width && height); + dds_file.Copy_Level_To_Surface + ( + level, + Get_Format(), + width, + height, + Get_Locked_Surface_Ptr(level), + Get_Locked_Surface_Pitch(level), + HSVShift + ); + + width >>= 1; + height >>= 1; + } + + return true; +} + + +bool TextureLoadTaskClass::Load_Uncompressed_Mipmap(void) +{ + if (!Get_Mip_Level_Count()) + { + return false; + } + + Targa targa; + if (TARGA_ERROR_HANDLER(targa.Open(Texture->Get_Full_Path(), TGA_READMODE), Texture->Get_Full_Path())) { + return false; + } + + // DX8 uses image upside down compared to TGA + targa.Header.ImageDescriptor ^= TGAIDF_YORIGIN; + + WW3DFormat src_format; + WW3DFormat dest_format; + unsigned int src_bpp = 0; + Get_WW3D_Format(dest_format,src_format,src_bpp,targa); + if (src_format==WW3D_FORMAT_UNKNOWN) return false; + + dest_format = Get_Format(); // Texture can be requested in different format than the most obvious from the TGA + + char palette[256*4]; + targa.SetPalette(palette); + + unsigned int src_width = targa.Header.Width; + unsigned int src_height = targa.Header.Height; + unsigned int width = Get_Width(); + unsigned int height = Get_Height(); + + // NOTE: We load the palette but we do not yet support paletted textures! + if (TARGA_ERROR_HANDLER(targa.Load(Texture->Get_Full_Path(), TGAF_IMAGE, false), Texture->Get_Full_Path())) { + return false; + } + + unsigned char * src_surface = (unsigned char*)targa.GetImage(); + unsigned char * converted_surface = NULL; + + // No paletted format allowed when generating mipmaps + Vector3 hsv_shift=HSVShift; + if ( src_format == WW3D_FORMAT_A1R5G5B5 + || src_format == WW3D_FORMAT_R5G6B5 + || src_format == WW3D_FORMAT_A4R4G4B4 + || src_format == WW3D_FORMAT_P8 + || src_format == WW3D_FORMAT_L8 + || src_width != width + || src_height != height) { + + converted_surface = new unsigned char[width*height*4]; + dest_format = Get_Valid_Texture_Format(WW3D_FORMAT_A8R8G8B8, false); + + BitmapHandlerClass::Copy_Image( + converted_surface, + width, + height, + width*4, + WW3D_FORMAT_A8R8G8B8, //dest_format, + src_surface, + src_width, + src_height, + src_width*src_bpp, + src_format, + (unsigned char*)targa.GetPalette(), + targa.Header.CMapDepth>>3, + false, + hsv_shift); + hsv_shift=Vector3(0.0f,0.0f,0.0f); + + src_surface = converted_surface; + src_format = WW3D_FORMAT_A8R8G8B8; //dest_format; + src_width = width; + src_height = height; + src_bpp = Get_Bytes_Per_Pixel(src_format); + } + + unsigned src_pitch = src_width * src_bpp; + + if (Reduction) + { //texture needs to be reduced so allocate storage for full-sized version. + unsigned char * destination_surface = new unsigned char[width*height*4]; + //generate upper mip-levels that will be dropped in final texture + for (unsigned int level = 0; level < Reduction; ++level) { + BitmapHandlerClass::Copy_Image( + (unsigned char *)destination_surface, + width, + height, + src_pitch, + Get_Format(), + src_surface, + src_width, + src_height, + src_pitch, + src_format, + NULL, + 0, + true, + hsv_shift); + + width >>= 1; + height >>= 1; + src_width >>= 1; + src_height >>= 1; + } + delete [] destination_surface; + } + + for (unsigned int level = 0; level < Get_Mip_Level_Count(); ++level) { + WWASSERT(Get_Locked_Surface_Ptr(level)); + BitmapHandlerClass::Copy_Image( + Get_Locked_Surface_Ptr(level), + width, + height, + Get_Locked_Surface_Pitch(level), + Get_Format(), + src_surface, + src_width, + src_height, + src_pitch, + src_format, + NULL, + 0, + true, + hsv_shift); + hsv_shift=Vector3(0.0f,0.0f,0.0f); + + width >>= 1; + height >>= 1; + src_width >>= 1; + src_height >>= 1; + + if (!width || !height || !src_width || !src_height) { + break; + } + } + + delete[] converted_surface; + + return true; +} + + +unsigned char * TextureLoadTaskClass::Get_Locked_Surface_Ptr(unsigned int level) +{ + WWASSERT(levelGet_Full_Path().Is_Empty()); + + Type = type; + Priority = priority; + State = STATE_NONE; + + D3DTexture = 0; + + CubeTextureClass* tex=Texture->As_CubeTextureClass(); + + if (tex) + { + Format = tex->Get_Texture_Format(); // don't assume format yet KM + } + else + { + Format = WW3D_FORMAT_UNKNOWN; + } + + Width = 0; + Height = 0; + MipLevelCount = Texture->MipLevelCount; + Reduction = Texture->Get_Reduction(); + HSVShift = Texture->Get_HSV_Shift(); + + + for (int f=0; f<6; f++) + { + for (int i = 0; i < MIP_LEVELS_MAX; ++i) + { + LockedCubeSurfacePtr[f][i] = NULL; + LockedCubeSurfacePitch[f][i] = 0; + } + } + + switch (Type) + { + case TASK_THUMBNAIL: + WWASSERT(Texture->ThumbnailLoadTask == NULL); + Texture->ThumbnailLoadTask = this; + break; + + case TASK_LOAD: + WWASSERT(Texture->TextureLoadTask == NULL); + Texture->TextureLoadTask = this; + break; + } +} + + +void CubeTextureLoadTaskClass::Deinit() +{ + // task should not be on any list when it is being detached from texture. + WWASSERT(Next == NULL); + WWASSERT(Prev == NULL); + + WWASSERT(D3DTexture == NULL); + + for (int f=0; f<6; f++) + { + for (int i = 0; i < MIP_LEVELS_MAX; ++i) + { + WWASSERT(LockedCubeSurfacePtr[f][i] == NULL); + } + } + + if (Texture) + { + switch (Type) + { + case TASK_THUMBNAIL: + WWASSERT(Texture->ThumbnailLoadTask == this); + Texture->ThumbnailLoadTask = NULL; + break; + + case TASK_LOAD: + WWASSERT(Texture->TextureLoadTask == this); + Texture->TextureLoadTask = NULL; + break; + } + + // NOTE: we must be in main thread to avoid corrupting Texture's refcount. + WWASSERT(TextureLoader::Is_DX8_Thread()); + REF_PTR_RELEASE(Texture); + } +} + +void CubeTextureLoadTaskClass::Lock_Surfaces(void) +{ + for (unsigned int f=0; f<6; f++) + { + for (unsigned int i=0; iLockRect + ( + (D3DCUBEMAP_FACES)f, + i, + &locked_rect, + NULL, + 0 + ) + ); + LockedCubeSurfacePtr[f][i] = (unsigned char *)locked_rect.pBits; + LockedCubeSurfacePitch[f][i]= locked_rect.Pitch; + } + } +} +void CubeTextureLoadTaskClass::Unlock_Surfaces(void) +{ + for (unsigned int f=0; f<6; f++) + { + for (unsigned int i = 0; i < MipLevelCount; ++i) + { + if (LockedCubeSurfacePtr[f][i]) + { + WWASSERT(ThreadClass::_Get_Current_Thread_ID() == DX8Wrapper::_Get_Main_Thread_ID()); + DX8_ErrorCode + ( + Peek_D3D_Cube_Texture()->UnlockRect((D3DCUBEMAP_FACES)f,i) + ); + } + LockedCubeSurfacePtr[f][i] = NULL; + } } -*/ -// ---------------------------------------------------------------------------- -// -// -// -// ---------------------------------------------------------------------------- +#ifndef USE_MANAGED_TEXTURES + IDirect3DCubeTexture8* tex = DX8Wrapper::_Create_DX8_Cube_Texture + ( + Width, + Height, + Format, + Texture->MipLevelCount, + D3DPOOL_DEFAULT + ); + DX8CALL(UpdateTexture(Peek_D3D_Volume_Texture(),tex)); + Peek_D3D_Volume_Texture()->Release(); + D3DTexture=tex; + WWDEBUG_SAY(("Created non-managed texture (%s)",Texture->Get_Full_Path())); +#endif -void TextureLoadTaskClass::Begin_Thumbnail_Load() -{ -// CriticalSectionClass::LockClass m(mutex); - - unsigned thread_id=ThreadClass::_Get_Current_Thread_ID(); - if (thread_id==DX8Wrapper::_Get_Main_Thread_ID()) { - WW3DFormat format=Texture->Get_Texture_Format(); - // No compressed thumbnails - switch (format) { - case WW3D_FORMAT_DXT1: - case WW3D_FORMAT_DXT2: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: - format=WW3D_FORMAT_A8R8G8B8; break; - default: - break; +} + + + +bool CubeTextureLoadTaskClass::Begin_Compressed_Load() +{ + unsigned orig_w,orig_h,orig_d,orig_mip_count,reduction; + WW3DFormat orig_format; + if (!Get_Texture_Information + ( + Texture->Get_Full_Path(), + reduction, + orig_w, + orig_h, + orig_d, + orig_format, + orig_mip_count, + true + ) + ) + { + return false; + } + + // Destination size will be the next power of two square from the larger width and height... + unsigned int width = orig_w; + unsigned int height = orig_h; + TextureLoader::Validate_Texture_Size(width, height,orig_d); + + // If the size doesn't match, try and see if texture reduction would help... (mainly for + // cases where loaded texture is larger than hardware limit) + if (width != orig_w || height != orig_h) + { + for (unsigned int i = 1; i < orig_mip_count; ++i) + { + unsigned w=orig_w>>i; + if (w<4) w=4; + unsigned h=orig_h>>i; + if (h<4) h=4; + unsigned tmp_w=w; + unsigned tmp_h=h; + + TextureLoader::Validate_Texture_Size(w,h,orig_d); + + if (w == tmp_w && h == tmp_h) + { + Reduction += i; + width = w; + height = h; + break; + } } - D3DTexture=TextureLoader::Load_Thumbnail(Texture->Get_Full_Path(),format); + } - // Thumbnail loads are always high priority, so apply immediatelly - End_Load(); - Apply(false); - Add_Task_To_Delete_List(this); - return; + Width = width; + Height = height; + Format = Get_Valid_Texture_Format(orig_format, Texture->Is_Compression_Allowed()); + + unsigned int mip_level_count = Get_Mip_Level_Count(); + + // If texture wants all mip levels, take as many as the file contains (not necessarily all) + // Otherwise take as many mip levels as the texture wants, not to exceed the count in file... + if (!mip_level_count) + { + mip_level_count = orig_mip_count;//dds_file.Get_Mip_Level_Count(); } - else { - Add_Thumbnail_Task(this); + else if (mip_level_count > orig_mip_count) + {//dds_file.Get_Mip_Level_Count()) { + mip_level_count = orig_mip_count;//dds_file.Get_Mip_Level_Count(); + } + + // Once more, verify that the mip level count is correct (in case it was changed here it might not + // match the size...well actually it doesn't have to match but it can't be bigger than the size) + unsigned int max_mip_level_count = 1; + unsigned int w = 4; + unsigned int h = 4; + + while (w < Width && h < Height) + { + w += w; + h += h; + max_mip_level_count++; } + + if (mip_level_count > max_mip_level_count) + { + mip_level_count = max_mip_level_count; + } + + D3DTexture = DX8Wrapper::_Create_DX8_Cube_Texture + ( + Width, + Height, + Format, + (MipCountType)mip_level_count, +#ifdef USE_MANAGED_TEXTURES + D3DPOOL_MANAGED +#else + D3DPOOL_SYSTEMMEM +#endif + ); + + MipLevelCount = mip_level_count; + return true; } -// ---------------------------------------------------------------------------- -// -// Deinit can be called multiple times. If any surfaces are locked this call -// can only be called from the main thread. -// -// ---------------------------------------------------------------------------- +bool CubeTextureLoadTaskClass::Begin_Uncompressed_Load(void) +{ + unsigned width,height,depth,orig_mip_count,reduction; + WW3DFormat orig_format; + if (!Get_Texture_Information + ( + Texture->Get_Full_Path(), + reduction, + width, + height, + depth, + orig_format, + orig_mip_count, + false + ) + ) + { + return false; + } + + WW3DFormat src_format=orig_format; + WW3DFormat dest_format=src_format; + dest_format=Get_Valid_Texture_Format(dest_format,false); // No compressed destination format if reading from targa... + + if ( src_format != WW3D_FORMAT_A8R8G8B8 + && src_format != WW3D_FORMAT_R8G8B8 + && src_format != WW3D_FORMAT_X8R8G8B8 ) + { + WWDEBUG_SAY(("Invalid TGA format used in %s - only 24 and 32 bit formats should be used!", Texture->Get_Full_Path().str())); + } + + // Destination size will be the next power of two square from the larger width and height... + unsigned ow = width; + unsigned oh = height; + TextureLoader::Validate_Texture_Size(width, height,depth); + if (width != ow || height != oh) + { + WWDEBUG_SAY(("Invalid texture size, scaling required. Texture: %s, size: %d x %d -> %d x %d", Texture->Get_Full_Path().str(), ow, oh, width, height)); + } + + Width = width; + Height = height; + + if (Format == WW3D_FORMAT_UNKNOWN) + { + Format=dest_format; + } + else + { + Format = Get_Valid_Texture_Format(Format, false); + } + + D3DTexture = DX8Wrapper::_Create_DX8_Cube_Texture + ( + Width, + Height, + Format, + Texture->MipLevelCount, +#ifdef USE_MANAGED_TEXTURES + D3DPOOL_MANAGED +#else + D3DPOOL_SYSTEMMEM +#endif + ); + + return true; +} -void TextureLoadTaskClass::End_Load() +bool CubeTextureLoadTaskClass::Load_Compressed_Mipmap(void) { - for (unsigned i=0;iUnlockRect(i)); + DDSFileClass dds_file(Texture->Get_Full_Path(), Get_Reduction()); + + // if we can't load from file, indicate rror. + if (!dds_file.Is_Available() || !dds_file.Load()) + { + return false; + } + + // load cube map faces + for (unsigned int face=0; face<6; face++) + { + unsigned int width = Get_Width(); + unsigned int height = Get_Height(); + + for (unsigned int level=0; level>=1; + height>>=1; } - LockedSurfacePtr[i]=NULL; } - IsLoading=false; + return true; } -// ---------------------------------------------------------------------------- -// -// Link the node to another task node. This can only be done if the node isn't -// linked to something else already. If the node is linked to some other node, -// the only acceptable parameter to this function is NULL, which will unlink -// the connection. -// -// ---------------------------------------------------------------------------- +unsigned char* CubeTextureLoadTaskClass::Get_Locked_CubeMap_Surface_Pointer(unsigned int face, unsigned int level) +{ + WWASSERT(face<6 && levelGet_Full_Path().Is_Empty()); + + Type = type; + Priority = priority; + State = STATE_NONE; + + D3DTexture = 0; + + VolumeTextureClass* tex=Texture->As_VolumeTextureClass(); + + if (tex) + { + Format = tex->Get_Texture_Format(); // don't assume format yet KM + } + else + { + Format = WW3D_FORMAT_UNKNOWN; } - Texture->Apply_New_Surface(initialize); + Width = 0; + Height = 0; + Depth = 0; + MipLevelCount = Texture->MipLevelCount; + Reduction = Texture->Get_Reduction(); + HSVShift = Texture->Get_HSV_Shift(); - D3DTexture->Release(); - D3DTexture=NULL; -} -// ---------------------------------------------------------------------------- -// -// Return locked surface pointer at a specific level. The call will -// assert if level is greater or equal to the number of mip levels or if the -// requested level has not been locked. -// -// ---------------------------------------------------------------------------- + for (int i = 0; i < MIP_LEVELS_MAX; ++i) + { + LockedSurfacePtr[i] = NULL; + LockedSurfacePitch[i] = 0; + LockedSurfaceSlicePitch[i] = 0; + } -unsigned char* TextureLoadTaskClass::Get_Locked_Surface_Ptr(unsigned level) + switch (Type) + { + case TASK_THUMBNAIL: + WWASSERT(Texture->ThumbnailLoadTask == NULL); + Texture->ThumbnailLoadTask = this; + break; + + case TASK_LOAD: + WWASSERT(Texture->TextureLoadTask == NULL); + Texture->TextureLoadTask = this; + break; + } +} + +void VolumeTextureLoadTaskClass::Lock_Surfaces() { - WWASSERT(levelLockBox + ( + i, + &locked_box, + NULL, + 0 + ) + ); + LockedSurfacePtr[i] = (unsigned char *)locked_box.pBits; + LockedSurfacePitch[i] = locked_box.RowPitch; + LockedSurfaceSlicePitch[i] = locked_box.SlicePitch; + } } -// ---------------------------------------------------------------------------- -// -// Return locked surface pitch (in bytes) at a specific level. The call will -// assert if level is greater or equal to the number of mip levels or if the -// requested level has not been locked. -// -// ---------------------------------------------------------------------------- -unsigned TextureLoadTaskClass::Get_Locked_Surface_Pitch(unsigned level) const +void VolumeTextureLoadTaskClass::Unlock_Surfaces() { - WWASSERT(levelUnlockBox(i) + ); + } + LockedSurfacePtr[i] = NULL; + } + +#ifndef USE_MANAGED_TEXTURES + IDirect3DTexture8* tex = DX8Wrapper::_Create_DX8_Volume_Texture(Width, Height, Depth, Format, Texture->MipLevelCount,D3DPOOL_DEFAULT); + DX8CALL(UpdateTexture(Peek_D3D_Volume_Texture(),tex)); + Peek_D3D_Volume_Texture()->Release(); + D3DTexture=tex; + WWDEBUG_SAY(("Created non-managed texture (%s)",Texture->Get_Full_Path())); +#endif + } -// ---------------------------------------------------------------------------- -// -// Load tasks are stored in a pool when they are not used. If the pool is empty -// a new task is created. -// -// ---------------------------------------------------------------------------- -TextureLoadTaskClass* TextureLoadTaskClass::Get_Instance(TextureBaseClass* tc, bool high_priority) + +bool VolumeTextureLoadTaskClass::Begin_Compressed_Load() { - CriticalSectionClass::LockClass m(mutex); + unsigned orig_w,orig_h,orig_d,orig_mip_count,reduction; + WW3DFormat orig_format; + if (!Get_Texture_Information + ( + Texture->Get_Full_Path(), + reduction, + orig_w, + orig_h, + orig_d, + orig_format, + orig_mip_count, + true + ) + ) + { + return false; + } - TextureLoadTaskClass* task=FreeTaskListHead; - if (task) { - FreeTaskListHead=task->Peek_Succ(); - task->Set_Succ(NULL); + // Destination size will be the next power of two square from the larger width and height... + unsigned int width = orig_w; + unsigned int height = orig_h; + unsigned int depth = orig_d; + TextureLoader::Validate_Texture_Size(width, height, depth); + + // If the size doesn't match, try and see if texture reduction would help... (mainly for + // cases where loaded texture is larger than hardware limit) + if (width != orig_w || height != orig_h || depth != orig_d) + { + for (unsigned int i = 1; i < orig_mip_count; ++i) + { + unsigned w=orig_w>>i; + if (w<4) w=4; + unsigned h=orig_h>>i; + if (h<4) h=4; + unsigned d=orig_d>>i; + if (d<1) d=1; + unsigned tmp_w=w; + unsigned tmp_h=h; + unsigned tmp_d=d; + + TextureLoader::Validate_Texture_Size(w,h,d); + + if (w == tmp_w && h == tmp_h && d== tmp_d) + { + Reduction += i; + width = w; + height = h; + depth = d; + break; + } + } } - else { - task=W3DNEW TextureLoadTaskClass(); + + Width = width; + Height = height; + Depth = depth; + Format = Get_Valid_Texture_Format(orig_format, Texture->Is_Compression_Allowed()); + + unsigned int mip_level_count = Get_Mip_Level_Count(); + + // If texture wants all mip levels, take as many as the file contains (not necessarily all) + // Otherwise take as many mip levels as the texture wants, not to exceed the count in file... + if (!mip_level_count) + { + mip_level_count = orig_mip_count;//dds_file.Get_Mip_Level_Count(); } - task->Init(tc,high_priority); - return task; + else if (mip_level_count > orig_mip_count) + {//dds_file.Get_Mip_Level_Count()) { + mip_level_count = orig_mip_count;//dds_file.Get_Mip_Level_Count(); + } + + // Once more, verify that the mip level count is correct (in case it was changed here it might not + // match the size...well actually it doesn't have to match but it can't be bigger than the size) + unsigned int max_mip_level_count = 1; + unsigned int w = 4; + unsigned int h = 4; + + while (w < Width && h < Height) + { + w += w; + h += h; + max_mip_level_count++; + } + if (mip_level_count > max_mip_level_count) + { + mip_level_count = max_mip_level_count; + } + + D3DTexture = DX8Wrapper::_Create_DX8_Volume_Texture + ( + Width, + Height, + Depth, + Format, + (MipCountType)mip_level_count, +#ifdef USE_MANAGED_TEXTURES + D3DPOOL_MANAGED +#else + D3DPOOL_SYSTEMMEM +#endif + ); + + MipLevelCount = mip_level_count; + return true; } -// ---------------------------------------------------------------------------- -// -// When task is no longer needed it is returned to the pool. -// -// ---------------------------------------------------------------------------- +bool VolumeTextureLoadTaskClass::Begin_Uncompressed_Load(void) +{ + unsigned width,height,depth,orig_mip_count,reduction; + WW3DFormat orig_format; + if (!Get_Texture_Information + ( + Texture->Get_Full_Path(), + reduction, + width, + height, + depth, + orig_format, + orig_mip_count, + false + ) + ) + { + return false; + } + + WW3DFormat src_format=orig_format; + WW3DFormat dest_format=src_format; + dest_format=Get_Valid_Texture_Format(dest_format,false); // No compressed destination format if reading from targa... + + if ( src_format != WW3D_FORMAT_A8R8G8B8 + && src_format != WW3D_FORMAT_R8G8B8 + && src_format != WW3D_FORMAT_X8R8G8B8 ) + { + WWDEBUG_SAY(("Invalid TGA format used in %s - only 24 and 32 bit formats should be used!", Texture->Get_Full_Path().str())); + } + + // Destination size will be the next power of two square from the larger width and height... + unsigned ow = width; + unsigned oh = height; + unsigned od = depth; + TextureLoader::Validate_Texture_Size(width, height, depth); + if (width != ow || height != oh || depth != od) + { + WWDEBUG_SAY(("Invalid texture size, scaling required. Texture: %s, size: %d x %d -> %d x %d", Texture->Get_Full_Path().str(), ow, oh, width, height)); + } + + Width = width; + Height = height; + Depth = depth; + + if (Format == WW3D_FORMAT_UNKNOWN) + { + Format=dest_format; + } + else + { + Format = Get_Valid_Texture_Format(Format, false); + } -void TextureLoadTaskClass::Release_Instance(TextureLoadTaskClass* task) + D3DTexture = DX8Wrapper::_Create_DX8_Volume_Texture + ( + Width, + Height, + Depth, + Format, + Texture->MipLevelCount, +#ifdef USE_MANAGED_TEXTURES + D3DPOOL_MANAGED +#else + D3DPOOL_SYSTEMMEM +#endif + ); + + return true; +} + +bool VolumeTextureLoadTaskClass::Load_Compressed_Mipmap(void) { - if (!task) return; + DDSFileClass dds_file(Texture->Get_Full_Path(), Get_Reduction()); + + // if we can't load from file, indicate rror. + if (!dds_file.Is_Available() || !dds_file.Load()) + { + return false; + } - CriticalSectionClass::LockClass m(mutex); + // load volume + unsigned int depth=dds_file.Get_Depth(0); + unsigned int width=Get_Width(); + unsigned int height=Get_Height(); + + WWASSERT(width && height && depth); + + for (unsigned int level=0; level>=1; + height>>=1; + depth>>=1; + } - task->Deinit(); + return true; +} - // Task must not be in any list when it is being freed - WWASSERT(task->Peek_Succ()==NULL); +unsigned char* VolumeTextureLoadTaskClass::Get_Locked_Volume_Pointer(unsigned int level) +{ + WWASSERT(levelSet_Succ(FreeTaskListHead); - FreeTaskListHead=task; +unsigned int VolumeTextureLoadTaskClass::Get_Locked_Volume_Row_Pitch(unsigned int level) +{ + WWASSERT(level. */ +/*********************************************************************************************** + *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** + *********************************************************************************************** + * * + * Project Name : DX8 Texture Manager * + * * + * $Archive:: /Commando/Code/ww3d2/textureloader.h $* + * * + * Original Author:: vss_sync * + * * + * Author : Kenny Mitchell * + * * + * $Modtime:: 06/27/02 1:27p $* + * * + * $Revision:: 2 $* + * * + * 06/27/02 KM Texture class abstraction * + *---------------------------------------------------------------------------------------------* + * Functions: * + * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ + #pragma once #include "always.h" @@ -27,107 +48,279 @@ class TextureLoadTaskClass; class TextureLoader { - static void Init_Load_Task(TextureBaseClass* tc); - - static bool Load_Uncompressed_Mipmap_Levels_From_TGA(TextureLoadTaskClass* texture); - public: - static void Init(); - static void Deinit(); + static void Init(void); + static void Deinit(void); // Modify given texture size to nearest valid size on current hardware. static void Validate_Texture_Size(unsigned& width, unsigned& height, unsigned& depth); - // Adds a loading task to the system. The task if processed in a separate - // thread as soon as possible. The task will appear in finished tasks list - // when it's been completed. The texture will be refreshed on the next - // update call after appearing to the finished tasks list. - static void Add_Load_Task(TextureBaseClass* tc); - static IDirect3DTexture8* Load_Thumbnail( - const StringClass& filename, - WW3DFormat texture_format); // Pass WW3D_FORMAT_UNKNOWN if you don't care - static void Load_Mipmap_Levels(TextureLoadTaskClass* texture); + static IDirect3DTexture8 * Load_Thumbnail( + const StringClass& filename,const Vector3& hsv_shift); +// WW3DFormat texture_format); // Pass WW3D_FORMAT_UNKNOWN if you don't care - static IDirect3DSurface8* Load_Surface_Immediate( + static IDirect3DSurface8 * Load_Surface_Immediate( const StringClass& filename, WW3DFormat surface_format, // Pass WW3D_FORMAT_UNKNOWN if you don't care bool allow_compression); + static void Request_Thumbnail(TextureBaseClass* tc); + + // Adds a loading task to the system. The task if processed in a separate + // thread as soon as possible. The task will appear in finished tasks list + // when it's been completed. The texture will be refreshed on the next + // update call after appearing to the finished tasks list. + static void Request_Background_Loading(TextureBaseClass* tc); + // Textures can only be created and locked by the main thread so this function sends a request to the texture // handling system to load the texture immediatelly next time it enters the main thread. If this function // is called from the main thread the texture is loaded immediatelly. - static void Request_High_Priority_Loading( - TextureBaseClass* texture, - MipCountType mip_level_count); - static void Request_Thumbnail(TextureBaseClass* tc); + static void Request_Foreground_Loading(TextureBaseClass* tc); + + static void Flush_Pending_Load_Tasks(void); + static void Update(void(*network_callback)(void) = NULL); + + // returns true if current thread of execution is allowed to make DX8 calls. + static bool Is_DX8_Thread(void); + + static void Suspend_Texture_Load(); + static void Continue_Texture_Load(); + + static void Set_Texture_Inactive_Override_Time(int time_ms) {TextureInactiveOverrideTime = time_ms;} + +private: + static void Process_Foreground_Load (TextureLoadTaskClass *task); + static void Process_Foreground_Thumbnail (TextureLoadTaskClass *task); + + static void Begin_Load_And_Queue (TextureLoadTaskClass *task); + static void Load_Thumbnail (TextureBaseClass *tc); + + static bool TextureLoadSuspended; + + // The time in ms before a texture is thrown out. + // The default is zero. The scripted movies set this to reduce texture stalls in movies. + static int TextureInactiveOverrideTime; +}; + +class TextureLoadTaskListNodeClass +{ + friend class TextureLoadTaskListClass; + + public: + TextureLoadTaskListNodeClass(void) : Next(0), Prev(0) { } + + TextureLoadTaskListClass *Get_List(void) { return List; } + + TextureLoadTaskListNodeClass *Next; + TextureLoadTaskListNodeClass *Prev; + TextureLoadTaskListClass * List; +}; + + +class TextureLoadTaskListClass +{ + // This class implements an unsynchronized, double-linked list of TextureLoadTaskClass + // objects, using an embedded list node. + + public: + TextureLoadTaskListClass(void); + + // Returns true if list is empty, false otherwise. + bool Is_Empty (void) const { return (Root.Next == &Root); } + + // Add a task to beginning of list + void Push_Front (TextureLoadTaskClass *task); + + // Add a task to end of list + void Push_Back (TextureLoadTaskClass *task); + + // Remove and return a task from beginning of list, or NULL if list is empty. + TextureLoadTaskClass * Pop_Front (void); + + // Remove and return a task from end of list, or NULL if list is empty + TextureLoadTaskClass * Pop_Back (void); + + // Remove specified task from list, if present + void Remove (TextureLoadTaskClass *task); + + private: + // This list is implemented using a sentinel node. + TextureLoadTaskListNodeClass Root; +}; + + +class SynchronizedTextureLoadTaskListClass : public TextureLoadTaskListClass +{ + // This class added thread-safety to the basic TextureLoadTaskListClass. - static void Update(); - static void Flush_Pending_Load_Tasks(); + public: + SynchronizedTextureLoadTaskListClass(void); - static IDirect3DTexture8* Generate_Bumpmap(TextureBaseClass* texture); + // See comments above for description of member functions. + void Push_Front (TextureLoadTaskClass *task); + void Push_Back (TextureLoadTaskClass *task); + TextureLoadTaskClass * Pop_Front (void); + TextureLoadTaskClass * Pop_Back (void); + void Remove (TextureLoadTaskClass *task); + private: + FastCriticalSectionClass CriticalSection; }; -// ---------------------------------------------------------------------------- -// -// Texture loader task handler -// -// ---------------------------------------------------------------------------- +/* +** (gth) The allocation system we're using for TextureLoadTaskClass has gotten a little +** complicated since Kenny added the new task types for Cube and Volume textures. The +** ::Destroy member is used to return a task to the pool now and must be over-ridden in +** each derived class to put the task back into the correct free list. +*/ + + +class TextureLoadTaskClass : public TextureLoadTaskListNodeClass +{ + public: + enum TaskType { + TASK_NONE, + TASK_THUMBNAIL, + TASK_LOAD, + }; + + enum PriorityType { + PRIORITY_LOW, + PRIORITY_HIGH, + }; + + enum StateType { + STATE_NONE, + + STATE_LOAD_BEGUN, + STATE_LOAD_MIPMAP, + STATE_LOAD_COMPLETE, + + STATE_COMPLETE, + }; + + + TextureLoadTaskClass(void); + ~TextureLoadTaskClass(void); + + static TextureLoadTaskClass * Create (TextureBaseClass *tc, TaskType type, PriorityType priority); + static void Delete_Free_Pool (void); + + virtual void Destroy (void); + virtual void Init (TextureBaseClass *tc, TaskType type, PriorityType priority); + virtual void Deinit (void); + + TaskType Get_Type (void) const { return Type; } + PriorityType Get_Priority (void) const { return Priority; } + StateType Get_State (void) const { return State; } + + WW3DFormat Get_Format (void) const { return Format; } + unsigned int Get_Width (void) const { return Width; } + unsigned int Get_Height (void) const { return Height; } + unsigned int Get_Mip_Level_Count (void) const { return MipLevelCount; } + unsigned int Get_Reduction (void) const { return Reduction; } + + unsigned char * Get_Locked_Surface_Ptr (unsigned int level); + unsigned int Get_Locked_Surface_Pitch(unsigned int level) const; + + TextureBaseClass * Peek_Texture (void) { return Texture; } + IDirect3DTexture8 * Peek_D3D_Texture (void) { return (IDirect3DTexture8*)D3DTexture; } -class TextureLoadTaskClass : public W3DMPO + void Set_Type (TaskType t) { Type = t; } + void Set_Priority (PriorityType p) { Priority = p; } + void Set_State (StateType s) { State = s; } + + bool Begin_Load (void); + bool Load (void); + void End_Load (void); + void Finish_Load (void); + void Apply_Missing_Texture (void); + + protected: + virtual bool Begin_Compressed_Load (void); + virtual bool Begin_Uncompressed_Load (void); + + virtual bool Load_Compressed_Mipmap (void); + virtual bool Load_Uncompressed_Mipmap(void); + + virtual void Lock_Surfaces (void); + virtual void Unlock_Surfaces (void); + + void Apply (bool initialize); + + TextureBaseClass* Texture; + IDirect3DBaseTexture8* D3DTexture; + WW3DFormat Format; + + unsigned int Width; + unsigned int Height; + unsigned int MipLevelCount; + unsigned int Reduction; + Vector3 HSVShift; + + unsigned char * LockedSurfacePtr[MIP_LEVELS_MAX]; + unsigned int LockedSurfacePitch[MIP_LEVELS_MAX]; + + TaskType Type; + PriorityType Priority; + StateType State; +}; + +class CubeTextureLoadTaskClass : public TextureLoadTaskClass { - W3DMPO_GLUE(TextureLoadTaskClass) - - static TextureLoadTaskClass* FreeTaskListHead; - - TextureBaseClass* Texture; - IDirect3DTexture8 *D3DTexture; - unsigned Width; - unsigned Height; - WW3DFormat Format; - unsigned char* LockedSurfacePtr[MIP_LEVELS_MAX]; - unsigned LockedSurfacePitch[MIP_LEVELS_MAX]; - unsigned MipLevelCount; - unsigned Reduction; - TextureLoadTaskClass* Succ; - bool IsLoading; - bool HasFailed; - bool HighPriorityRequested; - - ~TextureLoadTaskClass(); - TextureLoadTaskClass(); public: - static TextureLoadTaskClass* Get_Instance(TextureBaseClass* tc, bool high_priority); - static void Release_Instance(TextureLoadTaskClass* task); - static void shutdown(void) {TextureLoadTaskClass *pT; while (FreeTaskListHead) {pT = FreeTaskListHead; FreeTaskListHead = pT->Peek_Succ(); pT->Set_Succ(NULL); delete pT;} }; + CubeTextureLoadTaskClass(); - void Init(TextureBaseClass* tc,bool high_priority); - void Deinit(); + virtual void Destroy (void); + virtual void Init (TextureBaseClass *tc, TaskType type, PriorityType priority); + virtual void Deinit (void); + +protected: + virtual bool Begin_Compressed_Load (void); + virtual bool Begin_Uncompressed_Load (void); + + virtual bool Load_Compressed_Mipmap (void); +// virtual bool Load_Uncompressed_Mipmap(void); + + virtual void Lock_Surfaces (void); + virtual void Unlock_Surfaces (void); + +private: + unsigned char* Get_Locked_CubeMap_Surface_Pointer(unsigned int face, unsigned int level); + unsigned int Get_Locked_CubeMap_Surface_Pitch(unsigned int face, unsigned int level) const; + + IDirect3DCubeTexture8* Peek_D3D_Cube_Texture(void) { return (IDirect3DCubeTexture8*)D3DTexture; } + + unsigned char* LockedCubeSurfacePtr[6][MIP_LEVELS_MAX]; + unsigned int LockedCubeSurfacePitch[6][MIP_LEVELS_MAX]; +}; + +class VolumeTextureLoadTaskClass : public TextureLoadTaskClass +{ +public: + VolumeTextureLoadTaskClass(); - unsigned Get_Mip_Level_Count() const { return MipLevelCount; } - unsigned Get_Width() const { return Width; } - unsigned Get_Height() const { return Height; } - WW3DFormat Get_Format() const { return Format; } - unsigned Get_Reduction() const { return Reduction; } + virtual void Destroy (void); + virtual void Init (TextureBaseClass *tc, TaskType type, PriorityType priority); - unsigned char* Get_Locked_Surface_Ptr(unsigned level); - unsigned Get_Locked_Surface_Pitch(unsigned level) const; +protected: + virtual bool Begin_Compressed_Load (void); + virtual bool Begin_Uncompressed_Load (void); - bool Has_Failed() const { return HasFailed; } - void Set_Fail(bool b) { HasFailed=b; } + virtual bool Load_Compressed_Mipmap (void); +// virtual bool Load_Uncompressed_Mipmap(void); - // Init the task or put it to a deferred init list if called from outside the main thread - void Begin_Texture_Load(); - void Begin_Thumbnail_Load(); - void End_Load(); // Deinit must be called before Applying() + virtual void Lock_Surfaces (void); + virtual void Unlock_Surfaces (void); - void Apply(bool initialize); +private: + unsigned char* Get_Locked_Volume_Pointer(unsigned int level); + unsigned int Get_Locked_Volume_Row_Pitch(unsigned int level); + unsigned int Get_Locked_Volume_Slice_Pitch(unsigned int level); - TextureLoadTaskClass* Peek_Succ() { return Succ; } - void Set_Succ(TextureLoadTaskClass* succ); + IDirect3DVolumeTexture8* Peek_D3D_Volume_Texture(void) { return (IDirect3DVolumeTexture8*)D3DTexture; } - TextureBaseClass* Peek_Texture() { return Texture; } - IDirect3DTexture8* Peek_D3D_Texture() { return D3DTexture; } + unsigned int LockedSurfaceSlicePitch[MIP_LEVELS_MAX]; - void Set_D3D_Texture(IDirect3DTexture8* texture); + unsigned int Depth; }; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp index 65744fb913..24d385fbf2 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp @@ -25,21 +25,69 @@ #include "textureloader.h" #include "bitmaphandler.h" #include "ffactory.h" +#include "RAWFILE.h" +#include "wwprofile.h" +#include -static HashTemplateClass thumbnail_hash; -static bool _ThumbHashModified; -static unsigned char* _ThumbnailMemory; -static const char *THUMBNAIL_FILENAME = "thumbnails.dat"; +static DLListClass ThumbnailManagerList; +static ThumbnailManagerClass* GlobalThumbnailManager; +bool ThumbnailManagerClass::CreateThumbnailIfNotFound=false; -ThumbnailClass::ThumbnailClass(const char* name, unsigned char* bitmap, unsigned w, unsigned h, bool allocated) +static void Create_Hash_Name(StringClass& name, const StringClass& thumb_name) +{ + name=thumb_name; + int len=name.Get_Length(); + WWASSERT(!stricmp(&name[len-4],".tga") || !stricmp(&name[len-4],".dds")); + name[len-4]='\0'; + _strlwr(name.Peek_Buffer()); +} + + /* file_auto_ptr my_tga_file(_TheFileFactory,filename); + if (my_tga_file->Is_Available()) { + my_tga_file->Open(); + unsigned size=my_tga_file->Size(); + char* tga_memory=new char[size]; + my_tga_file->Read(tga_memory,size); + my_tga_file->Close(); + + StringClass pth("data\\"); + pth+=filename; + RawFileClass tmp_tga_file(pth); + tmp_tga_file.Create(); + tmp_tga_file.Write(tga_memory,size); + tmp_tga_file.Close(); + delete[] tga_memory; + + } +*/ + + +ThumbnailClass::ThumbnailClass( + ThumbnailManagerClass* manager, + const char* name, + unsigned char* bitmap, + unsigned w, + unsigned h, + unsigned original_w, + unsigned original_h, + unsigned original_mip_level_count, + WW3DFormat original_format, + bool allocated, + unsigned long date_time) : + Manager(manager), Name(name), Bitmap(bitmap), Allocated(allocated), Width(w), - Height(h) + Height(h), + OriginalTextureWidth(original_w), + OriginalTextureHeight(original_h), + OriginalTextureMipLevelCount(original_mip_level_count), + OriginalTextureFormat(original_format), + DateTime(date_time) { - thumbnail_hash.Insert(Name,this); + Manager->Insert_To_Hash(this); } // ---------------------------------------------------------------------------- @@ -51,30 +99,56 @@ ThumbnailClass::ThumbnailClass(const char* name, unsigned char* bitmap, unsigned // // ---------------------------------------------------------------------------- -ThumbnailClass::ThumbnailClass(const StringClass& filename) +ThumbnailClass::ThumbnailClass(ThumbnailManagerClass* manager, const StringClass& filename) : + Manager(manager), Bitmap(0), Name(filename), Allocated(false), Width(0), - Height(0) + Height(0), + OriginalTextureWidth(0), + OriginalTextureHeight(0), + OriginalTextureMipLevelCount(0), + OriginalTextureFormat(WW3D_FORMAT_UNKNOWN), + DateTime(0) { + WWPROFILE(("ThumbnailClass::ThumbnailClass")); unsigned reduction_factor=3; // First, try loading image from a DDS file DDSFileClass dds_file(filename,reduction_factor); if (dds_file.Is_Available() && dds_file.Load()) { + DateTime=dds_file.Get_Date_Time(); + + int len=Name.Get_Length(); + WWASSERT(len>4); + Name[len-3]='d'; + Name[len-2]='d'; + Name[len-1]='s'; + + unsigned level=0; + while (dds_file.Get_Width(level)>32 || dds_file.Get_Height(level)>32) { + if (level>=dds_file.Get_Mip_Level_Count()) break; + level++; + } + + OriginalTextureWidth=dds_file.Get_Full_Width(); + OriginalTextureHeight=dds_file.Get_Full_Height(); + OriginalTextureFormat=dds_file.Get_Format(); + OriginalTextureMipLevelCount=dds_file.Get_Mip_Level_Count(); Width=dds_file.Get_Width(0); Height=dds_file.Get_Height(0); - Bitmap=W3DNEWARRAY unsigned char[Width*Height*4]; + Bitmap=W3DNEWARRAY unsigned char[Width*Height*2]; Allocated=true; dds_file.Copy_Level_To_Surface( 0, // Level - WW3D_FORMAT_A8R8G8B8, + WW3D_FORMAT_A4R4G4B4, Width, Height, Bitmap, - Width*4); + Width*2, + Vector3(0.0f,0.0f,0.0f));// We don't want to HSV-shift here } // If DDS file can't be used try loading from TGA else { @@ -87,13 +161,46 @@ ThumbnailClass::ThumbnailClass(const StringClass& filename) WW3DFormat src_format,dest_format; unsigned src_bpp=0; - Get_WW3D_Format(dest_format,src_format,src_bpp,targa); + Get_WW3D_Format(src_format,src_bpp,targa); + if (src_format==WW3D_FORMAT_UNKNOWN) { + WWDEBUG_SAY(("Unknown texture format for %s",filename.str())); + return; + } // Destination size will be the next power of two square from the larger width and height... + OriginalTextureWidth=targa.Header.Width; + OriginalTextureHeight=targa.Header.Height; + OriginalTextureFormat=src_format; Width=targa.Header.Width>>reduction_factor; Height=targa.Header.Height>>reduction_factor; - unsigned depth=1; - TextureLoader::Validate_Texture_Size(Width,Height,depth); + OriginalTextureMipLevelCount=1; + unsigned iw=1; + unsigned ih=1; + while (iw32 || Height>32) { + reduction_factor++; + Width>>=2; + Height>>=2; + } + + unsigned poweroftwowidth = 1; + while (poweroftwowidth < Width) { + poweroftwowidth <<= 1; + } + + unsigned poweroftwoheight = 1; + while (poweroftwoheight < Height) { + poweroftwoheight <<= 1; + } + + Width=poweroftwowidth; + Height=poweroftwoheight; + unsigned src_width=targa.Header.Width; unsigned src_height=targa.Header.Height; @@ -102,9 +209,24 @@ ThumbnailClass::ThumbnailClass(const StringClass& filename) targa.SetPalette(palette); if (TARGA_ERROR_HANDLER(targa.Load(filename, TGAF_IMAGE, false),filename)) return; + // Get time stamp from the tga file + { + file_auto_ptr my_tga_file(_TheFileFactory,filename); + WWASSERT(my_tga_file->Is_Available()); + my_tga_file->Open(); + DateTime=my_tga_file->Get_Date_Time(); + my_tga_file->Close(); + } + unsigned char* src_surface=(unsigned char*)targa.GetImage(); - Bitmap=W3DNEWARRAY unsigned char[Width*Height*4]; + int len=Name.Get_Length(); + WWASSERT(len>4); + Name[len-3]='t'; + Name[len-2]='g'; + Name[len-1]='a'; + + Bitmap=W3DNEWARRAY unsigned char[Width*Height*2]; Allocated=true; dest_format=WW3D_FORMAT_A8R8G8B8; @@ -112,8 +234,8 @@ ThumbnailClass::ThumbnailClass(const StringClass& filename) Bitmap, Width, Height, - Width*4, - WW3D_FORMAT_A8R8G8B8, + Width*2, + WW3D_FORMAT_A4R4G4B4, src_surface, src_width, src_height, @@ -124,168 +246,165 @@ ThumbnailClass::ThumbnailClass(const StringClass& filename) false); } - _ThumbHashModified=true; - thumbnail_hash.Insert(Name,this); + Manager->Insert_To_Hash(this); } ThumbnailClass::~ThumbnailClass() { if (Allocated) delete[] Bitmap; - thumbnail_hash.Remove(Name); + Manager->Remove_From_Hash(this); } -ThumbnailClass* ThumbnailClass::Peek_Instance(const StringClass& name) + +// ---------------------------------------------------------------------------- +ThumbnailManagerClass::ThumbnailManagerClass(const char* thumbnail_filename) + : + ThumbnailMemory(NULL), + ThumbnailFileName(thumbnail_filename), + PerTextureTimeStampUsed(false), + Changed(false), + DateTime(0) { - return thumbnail_hash.Get(name); } -void ThumbnailClass::Init() +// ---------------------------------------------------------------------------- +ThumbnailManagerClass::~ThumbnailManagerClass() { - WWASSERT(!_ThumbnailMemory); - - // If the thumbnail hash table file is available, init hash table -#if 0 // don't do thumbnail file. - file_auto_ptr thumb_file(_TheFileFactory, THUMBNAIL_FILENAME); - if (thumb_file->Is_Available()) { - thumb_file->Open(FileClass::READ); - - char tmp[4]; - thumb_file->Read(tmp,4); - if (tmp[0]=='T' && tmp[1]=='M' && tmp[2]=='B' && tmp[3]=='1') { - - 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(&offset,sizeof(int)); - thumb_file->Read(&width,sizeof(int)); - thumb_file->Read(&height,sizeof(int)); - thumb_file->Read(&date_time,sizeof(unsigned long)); - thumb_file->Read(&name_len,sizeof(int)); - WWASSERT(name_len<255); - thumb_file->Read(name,name_len); - name[name_len]='\0'; - - - // Make sure the file is available and the timestamp matches - file_auto_ptr myfile(_TheFileFactory,name); - if (myfile->Is_Available()) { - myfile->Open(FileClass::READ); - if (date_time==myfile->Get_Date_Time()) { - W3DNEW ThumbnailClass( - name, - _ThumbnailMemory+offset-total_header_length, - width, - height, - false); - } - myfile->Close(); - } - } - thumb_file->Read(_ThumbnailMemory,total_data_length); - } - } - thumb_file->Close(); + HashTemplateIterator ite(ThumbnailHash); + ite.First(); + while (!ite.Is_Done()) { + ThumbnailClass* thumb=ite.Peek_Value(); + delete thumb; + ite.First(); } -#endif + + delete[] ThumbnailMemory; + ThumbnailMemory=NULL; } -void ThumbnailClass::Deinit() +// ---------------------------------------------------------------------------- +ThumbnailManagerClass* ThumbnailManagerClass::Peek_Thumbnail_Manager(const char* thumbnail_filename) { - // If the thumbnail hash table was modified, save it to disk - HashTemplateIterator ite(thumbnail_hash); - if (_ThumbHashModified) { -#if 0 // don't write thumbnails. jba. - int total_header_length=0; - int total_data_length=0; - int total_thumb_count=0; - total_header_length+=4; // header 'TMB1' - 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()) { - 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; // unsigned long date_time - total_header_length+=4; // int name string length - ThumbnailClass* thumb=ite.Peek_Value(); - total_header_length+=strlen(thumb->Get_Name()); - total_data_length+=thumb->Get_Width()*thumb->Get_Height()*4; - total_thumb_count++; - } - int offset=total_header_length; + ThumbnailManagerClass* man=ThumbnailManagerList.Head(); + while (man) { + if (man->ThumbnailFileName==thumbnail_filename) return man; + man=man->Succ(); + } + if (GlobalThumbnailManager && + GlobalThumbnailManager->ThumbnailFileName==thumbnail_filename) return GlobalThumbnailManager; + return NULL; +} - file_auto_ptr thumb_file(_TheWritingFileFactory, THUMBNAIL_FILENAME); - if (thumb_file->Is_Available()) { - thumb_file->Delete(); +// ---------------------------------------------------------------------------- +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, + // so we'll do pure string compares here... + + // Must NOT add global manager with this function + WWASSERT(stricmp(thumbnail_filename,GLOBAL_THUMBNAIL_MANAGER_FILENAME)); + + ThumbnailManagerClass* man=Peek_Thumbnail_Manager(thumbnail_filename); + if (man) return; + + // Not found, create and add to the list. + man=new ThumbnailManagerClass(thumbnail_filename); + ThumbnailManagerList.Add_Tail(man); +} +// ---------------------------------------------------------------------------- +void ThumbnailManagerClass::Remove_Thumbnail_Manager(const char* thumbnail_filename) +{ + ThumbnailManagerClass* man=ThumbnailManagerList.Head(); + while (man) { + if (man->ThumbnailFileName==thumbnail_filename) { + delete man; + return; } - thumb_file->Create(); - thumb_file->Open(FileClass::WRITE); - - char* header="TMB1"; - thumb_file->Write(header,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(); - unsigned long date_time=0; - file_auto_ptr myfile(_TheFileFactory,name); - if (myfile->Is_Available()) { - myfile->Open(FileClass::READ); - date_time=myfile->Get_Date_Time(); - myfile->Close(); + man=man->Succ(); + } + if (GlobalThumbnailManager && + GlobalThumbnailManager->ThumbnailFileName==thumbnail_filename) { + delete GlobalThumbnailManager; + GlobalThumbnailManager=NULL; + } +} +// ---------------------------------------------------------------------------- +ThumbnailClass* ThumbnailManagerClass::Peek_Thumbnail_Instance(const StringClass& name) +{ + + return Get_From_Hash(name); +} + +ThumbnailClass* ThumbnailManagerClass::Peek_Thumbnail_Instance_From_Any_Manager(const StringClass& filename) +{ + WWPROFILE(("Peek_Thumbnail_Instance_From_Any_Manager")); + ThumbnailManagerClass* thumb_man=ThumbnailManagerList.Head(); + while (thumb_man) { + ThumbnailClass* thumb=thumb_man->Peek_Thumbnail_Instance(filename); + if (thumb) return thumb; + thumb_man=thumb_man->Succ(); + } + + if (GlobalThumbnailManager) { + ThumbnailClass* thumb=GlobalThumbnailManager->Peek_Thumbnail_Instance(filename); + if (thumb) return thumb; + } + +// If thumbnail is not found, see if we can find a texture. It is possible that the texture is outside of +// a mix file and didn't get included in any thumbnail database based on a mixfile. If so, we'll add it to +// our global thumbnail database. + if (Is_Thumbnail_Created_If_Not_Found()) { + if (GlobalThumbnailManager) { + ThumbnailClass* thumb=new ThumbnailClass(GlobalThumbnailManager,filename); + if (!thumb->Peek_Bitmap()) { + delete thumb; + thumb=NULL; } - thumb_file->Write(&offset,sizeof(int)); - thumb_file->Write(&width,sizeof(int)); - thumb_file->Write(&height,sizeof(int)); - thumb_file->Write(&date_time,sizeof(unsigned long)); - thumb_file->Write(&name_len,sizeof(int)); - thumb_file->Write(name,name_len); - offset+=width*height*4; + return thumb; } + } - // 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*4); - } + return NULL; +} - thumb_file->Close(); -#endif - } - ite.First(); - while (!ite.Is_Done()) { - ThumbnailClass* thumb=ite.Peek_Value(); - delete thumb; - ite.First(); +void ThumbnailManagerClass::Insert_To_Hash(ThumbnailClass* thumb) +{ + Changed=true; + StringClass hash_name(0,true); + Create_Hash_Name(hash_name,thumb->Get_Name()); + ThumbnailHash.Insert(hash_name,thumb); +} + +ThumbnailClass* ThumbnailManagerClass::Get_From_Hash(const StringClass& name) +{ + StringClass hash_name(0,true); + Create_Hash_Name(hash_name,name); + return ThumbnailHash.Get(hash_name); +} + +void ThumbnailManagerClass::Remove_From_Hash(ThumbnailClass* thumb) +{ + Changed=true; + StringClass hash_name(0,true); + Create_Hash_Name(hash_name,thumb->Get_Name()); + ThumbnailHash.Remove(hash_name); +} + +void ThumbnailManagerClass::Init() +{ + WWASSERT(GlobalThumbnailManager == NULL); + GlobalThumbnailManager=new ThumbnailManagerClass(GLOBAL_THUMBNAIL_MANAGER_FILENAME); + GlobalThumbnailManager->Enable_Per_Texture_Time_Stamp(true); +} + +void ThumbnailManagerClass::Deinit() +{ + while (ThumbnailManagerClass* man=ThumbnailManagerList.Head()) { + delete man; } - delete [] _ThumbnailMemory; - _ThumbnailMemory=NULL; + delete GlobalThumbnailManager; + GlobalThumbnailManager=NULL; } diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.h index b61e427117..4d740af636 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.h @@ -16,31 +16,107 @@ ** along with this program. If not, see . */ +// 08/07/02 KM Texture class redesign (revisited) + #pragma once #include "always.h" #include "wwstring.h" +#include "hashtemplate.h" +#include "dllist.h" +#include "ww3dformat.h" + +#define GLOBAL_THUMBNAIL_MANAGER_FILENAME "global.th6" + +class ThumbnailManagerClass; // ---------------------------------------------------------------------------- class ThumbnailClass { + friend ThumbnailManagerClass; + StringClass Name; unsigned char* Bitmap; unsigned Width; unsigned Height; + unsigned OriginalTextureWidth; + unsigned OriginalTextureHeight; + unsigned OriginalTextureMipLevelCount; + WW3DFormat OriginalTextureFormat; + unsigned long DateTime; bool Allocated; // if true, destructor will free the memory -public: - ThumbnailClass(const char* name, unsigned char* bitmap, unsigned w, unsigned h, bool allocated); - ThumbnailClass(const StringClass& filename); + ThumbnailManagerClass* Manager; + + ThumbnailClass( + ThumbnailManagerClass* manager, + const char* name, + unsigned char* bitmap, + unsigned w, + unsigned h, + unsigned original_w, + unsigned original_h, + unsigned original_mip_level_count, + WW3DFormat original_format, + bool allocated, + unsigned long date_time); + ThumbnailClass( + ThumbnailManagerClass* manager, + const StringClass& filename); ~ThumbnailClass(); +public: unsigned char* Peek_Bitmap() { return Bitmap; } + WW3DFormat Get_Format() { return WW3D_FORMAT_A4R4G4B4; } unsigned Get_Width() const { return Width; } unsigned Get_Height() const { return Height; } + unsigned Get_Original_Texture_Width() const { return OriginalTextureWidth; } + unsigned Get_Original_Texture_Height() const { return OriginalTextureHeight; } + unsigned Get_Original_Texture_Mip_Level_Count() const { return OriginalTextureMipLevelCount; } + WW3DFormat Get_Original_Texture_Format() const { return OriginalTextureFormat; } + unsigned long Get_Date_Time() const { return DateTime; } const StringClass& Get_Name() const { return Name; } - static ThumbnailClass* Peek_Instance(const StringClass& name); +}; + +// ---------------------------------------------------------------------------- + +class ThumbnailManagerClass : public DLNodeClass +{ + W3DMPO_GLUE(ThumbnailManagerClass); + + friend ThumbnailClass; + + static bool CreateThumbnailIfNotFound; + bool PerTextureTimeStampUsed; + StringClass ThumbnailFileName; + HashTemplateClass ThumbnailHash; + unsigned char* ThumbnailMemory; + bool Changed; + unsigned long DateTime; + + 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); + +public: + ThumbnailClass* Peek_Thumbnail_Instance(const StringClass& 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); + + static ThumbnailClass* Peek_Thumbnail_Instance_From_Any_Manager(const StringClass& name); + + static bool Is_Thumbnail_Created_If_Not_Found() { return CreateThumbnailIfNotFound; } + static void Create_Thumbnail_If_Not_Found(bool create) { CreateThumbnailIfNotFound=create; } + + bool Is_Per_Texture_Time_Stamp_Used() const { return PerTextureTimeStampUsed; } + void Enable_Per_Texture_Time_Stamp(bool enable) { PerTextureTimeStampUsed=enable; } + static void Init(); static void Deinit(); }; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3d.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3d.cpp index dac6fcc1ae..38d966e513 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3d.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3d.cpp @@ -248,14 +248,6 @@ void WW3D::Set_NPatches_Level(unsigned level) NPatchesLevel = level; } -void WW3D::Set_Thumbnail_Enabled (bool b) -{ - if (ThumbnailEnabled!=b) { - ThumbnailEnabled = b; - _Invalidate_Textures(); - } -} - /*********************************************************************************************** * WW3D::Init -- Initialize the WW3D Library * * * @@ -775,7 +767,7 @@ 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(); + TextureFilterClass::_Init_Filters((TextureFilterClass::TextureFilterMode)TextureFilter); } @@ -826,7 +818,7 @@ WW3DErrorType WW3D::Begin_Render(bool clear,bool clearz,const Vector3 & color, f LastFrameMemoryFrees=WWMemoryLogClass::Get_Free_Count(); WWMemoryLogClass::Reset_Counters(); - TextureLoader::Update(); + TextureLoader::Update(network_callback); // TextureClass::_Reset_Time_Stamp(); DynamicVBAccessClass::_Reset(true); DynamicIBAccessClass::_Reset(true); diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3d.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3d.h index 1e0c158cec..f169690b69 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3d.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3d.h @@ -228,7 +228,7 @@ class WW3D static void _Invalidate_Mesh_Cache(); static void _Invalidate_Textures(); - static void Set_Thumbnail_Enabled(bool b);// { ThumbnailEnabled=b; } + static void Set_Thumbnail_Enabled(bool b) { ThumbnailEnabled=b; } static bool Get_Thumbnail_Enabled() { return ThumbnailEnabled; } static void Enable_Sorting(bool onoff); diff --git a/Generals/Code/Tools/WorldBuilder/src/ObjectPreview.cpp b/Generals/Code/Tools/WorldBuilder/src/ObjectPreview.cpp index 7be46780dd..0e3cc1618f 100644 --- a/Generals/Code/Tools/WorldBuilder/src/ObjectPreview.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/ObjectPreview.cpp @@ -218,7 +218,7 @@ static UnsignedByte * generatePreview( const ThingTemplate *tt ) } // Set the render target - DX8Wrapper::Set_Render_Target(objectTexture); + DX8Wrapper::Set_Render_Target_With_Z(objectTexture); // create the camera Bool orthoCamera = false; diff --git a/Generals/Code/Tools/WorldBuilder/src/WorldBuilder.cpp b/Generals/Code/Tools/WorldBuilder/src/WorldBuilder.cpp index 0759139665..9603cd1ec8 100644 --- a/Generals/Code/Tools/WorldBuilder/src/WorldBuilder.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/WorldBuilder.cpp @@ -637,7 +637,6 @@ int CWorldBuilderApp::ExitInstance() delete TheFileSystem; TheFileSystem = NULL; - TextureLoadTaskClass::shutdown(); delete TheW3DFileSystem; TheW3DFileSystem = NULL; diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp index f3189e931e..2addc0e8ba 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp @@ -619,8 +619,8 @@ HRESULT WaterRenderObjClass::generateVertexBuffer( Int sizeX, Int sizeY, Int ver { m_numVertices=sizeX*sizeY; //Assuming dynamic vertex buffer, allocate maximum multiple of required size to allow rendering from - //different parts of the buffer. 5-15-03: Disabled this since we use DISCARD mode instead to avoid Nvidia Runtime bug. -MW - //m_numVertices=(65536 / (sizeX*sizeY))*sizeX*sizeY; + //different parts of the buffer. 5-15-03: Disabled this since we use DISCARD mode instead to avoid Nvidia Runtime bug. -MW + //m_numVertices=(65536 / (sizeX*sizeY))*sizeX*sizeY; SEA_PATCH_VERTEX* pVertices; @@ -2229,9 +2229,9 @@ void WaterRenderObjClass::renderWaterMesh(void) if (!m_doWaterGrid) return; //the water grid is disabled. - //According to Nvidia there's a D3D bug that happens if you don't start with a - //new dynamic VB each frame - so we force a DISCARD by overflowing the counter. - m_vertexBufferD3DOffset = 0xffff; + //According to Nvidia there's a D3D bug that happens if you don't start with a + //new dynamic VB each frame - so we force a DISCARD by overflowing the counter. + m_vertexBufferD3DOffset = 0xffff; Setting *setting=&m_settings[m_tod]; diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp index 964eb896ac..afc6ed9013 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp @@ -867,9 +867,9 @@ Try improving the fit to vertical surfaces like cliffs. if (!m_usedModules || ShaderClass::Is_Backface_Culling_Inverted()) return; //don't render track marks in reflections. - //According to Nvidia there's a D3D bug that happens if you don't start with a - //new dynamic VB each frame - so we force a DISCARD by overflowing the counter. - m_batchStart = 0xffff; + //According to Nvidia there's a D3D bug that happens if you don't start with a + //new dynamic VB each frame - so we force a DISCARD by overflowing the counter. + m_batchStart = 0xffff; // adjust shading for time of day. Real shadeR, shadeG, shadeB; From c110a0e144e3d97bcb0955c42cd73d83ff0919ee Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Sun, 14 Dec 2025 11:46:18 +0100 Subject: [PATCH 33/70] unify(texture): Move W3DWater, W3DLaserDraw and WW3D2 texture related files to Core (#1989) --- Core/GameEngine/CMakeLists.txt | 4 +- .../GameEngine/Include/GameClient/Water.h | 0 .../GameEngine/Source/GameClient/Water.cpp | 0 Core/GameEngineDevice/CMakeLists.txt | 12 +- .../GameClient/Module/W3DLaserDraw.h | 0 .../Include/W3DDevice/GameClient/W3DWater.h | 0 .../W3DDevice/GameClient/W3DWaterTracks.h | 0 .../GameClient/Drawable/Draw/W3DLaserDraw.cpp | 0 .../W3DDevice/GameClient/Water/W3DWater.cpp | 0 .../GameClient/Water/W3DWaterTracks.cpp | 0 .../W3DDevice/GameClient/Water/wave.nvp | 0 .../W3DDevice/GameClient/Water/wave.nvv | 0 .../Source/WWVegas/WW3D2/CMakeLists.txt | 32 +- .../Libraries/Source/WWVegas/WW3D2/bmp2d.cpp | 0 .../Libraries/Source/WWVegas/WW3D2/bmp2d.h | 0 .../Source/WWVegas/WW3D2/dx8texman.cpp | 0 .../Source/WWVegas/WW3D2/dx8texman.h | 0 .../Source/WWVegas/WW3D2/matpass.cpp | 0 .../Libraries/Source/WWVegas/WW3D2/matpass.h | 0 .../Source/WWVegas/WW3D2/texproject.cpp | 0 .../Source/WWVegas/WW3D2/texproject.h | 0 .../Source/WWVegas/WW3D2/texture.cpp | 0 .../Libraries/Source/WWVegas/WW3D2/texture.h | 0 .../Source/WWVegas/WW3D2/texturefilter.cpp | 0 .../Source/WWVegas/WW3D2/texturefilter.h | 0 .../Source/WWVegas/WW3D2/textureloader.cpp | 0 .../Source/WWVegas/WW3D2/textureloader.h | 0 .../Source/WWVegas/WW3D2/texturethumbnail.cpp | 0 .../Source/WWVegas/WW3D2/texturethumbnail.h | 0 Generals/Code/GameEngine/CMakeLists.txt | 4 +- .../GameEngine/Include/GameClient/Water.h | 124 - .../GameEngine/Source/GameClient/Water.cpp | 134 - Generals/Code/GameEngineDevice/CMakeLists.txt | 16 +- .../GameClient/Module/W3DLaserDraw.h | 98 - .../Include/W3DDevice/GameClient/W3DWater.h | 290 -- .../W3DDevice/GameClient/W3DWaterTracks.h | 140 - .../GameClient/Drawable/Draw/W3DLaserDraw.cpp | 468 --- .../W3DDevice/GameClient/Water/W3DWater.cpp | 3489 ----------------- .../GameClient/Water/W3DWaterTracks.cpp | 1309 ------- .../W3DDevice/GameClient/Water/wave.nvp | 54 - .../W3DDevice/GameClient/Water/wave.nvv | 72 - .../Source/WWVegas/WW3D2/CMakeLists.txt | 32 +- .../Libraries/Source/WWVegas/WW3D2/bmp2d.cpp | 299 -- .../Libraries/Source/WWVegas/WW3D2/bmp2d.h | 52 - .../Source/WWVegas/WW3D2/dx8texman.cpp | 198 - .../Source/WWVegas/WW3D2/dx8texman.h | 171 - .../Source/WWVegas/WW3D2/matpass.cpp | 234 -- .../Libraries/Source/WWVegas/WW3D2/matpass.h | 114 - .../Source/WWVegas/WW3D2/texproject.cpp | 1389 ------- .../Source/WWVegas/WW3D2/texproject.h | 239 -- .../Source/WWVegas/WW3D2/texture.cpp | 1908 --------- .../Libraries/Source/WWVegas/WW3D2/texture.h | 475 --- .../Source/WWVegas/WW3D2/texturefilter.cpp | 251 -- .../Source/WWVegas/WW3D2/texturefilter.h | 130 - .../Source/WWVegas/WW3D2/textureloader.cpp | 2819 ------------- .../Source/WWVegas/WW3D2/textureloader.h | 326 -- .../Source/WWVegas/WW3D2/texturethumbnail.cpp | 410 -- .../Source/WWVegas/WW3D2/texturethumbnail.h | 124 - GeneralsMD/Code/GameEngine/CMakeLists.txt | 4 +- .../Code/GameEngineDevice/CMakeLists.txt | 12 +- .../Source/WWVegas/WW3D2/CMakeLists.txt | 32 +- scripts/cpp/unify_move_files.py | 28 + 62 files changed, 102 insertions(+), 15391 deletions(-) rename {GeneralsMD/Code => Core}/GameEngine/Include/GameClient/Water.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Source/GameClient/Water.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DLaserDraw.h (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Include/W3DDevice/GameClient/W3DWaterTracks.h (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvp (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvv (100%) rename {GeneralsMD/Code => Core}/Libraries/Source/WWVegas/WW3D2/bmp2d.cpp (100%) rename {GeneralsMD/Code => Core}/Libraries/Source/WWVegas/WW3D2/bmp2d.h (100%) rename {GeneralsMD/Code => Core}/Libraries/Source/WWVegas/WW3D2/dx8texman.cpp (100%) rename {GeneralsMD/Code => Core}/Libraries/Source/WWVegas/WW3D2/dx8texman.h (100%) rename {GeneralsMD/Code => Core}/Libraries/Source/WWVegas/WW3D2/matpass.cpp (100%) rename {GeneralsMD/Code => Core}/Libraries/Source/WWVegas/WW3D2/matpass.h (100%) rename {GeneralsMD/Code => Core}/Libraries/Source/WWVegas/WW3D2/texproject.cpp (100%) rename {GeneralsMD/Code => Core}/Libraries/Source/WWVegas/WW3D2/texproject.h (100%) rename {GeneralsMD/Code => Core}/Libraries/Source/WWVegas/WW3D2/texture.cpp (100%) rename {GeneralsMD/Code => Core}/Libraries/Source/WWVegas/WW3D2/texture.h (100%) rename {GeneralsMD/Code => Core}/Libraries/Source/WWVegas/WW3D2/texturefilter.cpp (100%) rename {GeneralsMD/Code => Core}/Libraries/Source/WWVegas/WW3D2/texturefilter.h (100%) rename {GeneralsMD/Code => Core}/Libraries/Source/WWVegas/WW3D2/textureloader.cpp (100%) rename {GeneralsMD/Code => Core}/Libraries/Source/WWVegas/WW3D2/textureloader.h (100%) rename {GeneralsMD/Code => Core}/Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp (100%) rename {GeneralsMD/Code => Core}/Libraries/Source/WWVegas/WW3D2/texturethumbnail.h (100%) delete mode 100644 Generals/Code/GameEngine/Include/GameClient/Water.h delete mode 100644 Generals/Code/GameEngine/Source/GameClient/Water.cpp delete mode 100644 Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DLaserDraw.h delete mode 100644 Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h delete mode 100644 Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWaterTracks.h delete mode 100644 Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp delete mode 100644 Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp delete mode 100644 Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp delete mode 100644 Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvp delete mode 100644 Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvv delete mode 100644 Generals/Code/Libraries/Source/WWVegas/WW3D2/bmp2d.cpp delete mode 100644 Generals/Code/Libraries/Source/WWVegas/WW3D2/bmp2d.h delete mode 100644 Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8texman.cpp delete mode 100644 Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8texman.h delete mode 100644 Generals/Code/Libraries/Source/WWVegas/WW3D2/matpass.cpp delete mode 100644 Generals/Code/Libraries/Source/WWVegas/WW3D2/matpass.h delete mode 100644 Generals/Code/Libraries/Source/WWVegas/WW3D2/texproject.cpp delete mode 100644 Generals/Code/Libraries/Source/WWVegas/WW3D2/texproject.h delete mode 100644 Generals/Code/Libraries/Source/WWVegas/WW3D2/texture.cpp delete mode 100644 Generals/Code/Libraries/Source/WWVegas/WW3D2/texture.h delete mode 100644 Generals/Code/Libraries/Source/WWVegas/WW3D2/texturefilter.cpp delete mode 100644 Generals/Code/Libraries/Source/WWVegas/WW3D2/texturefilter.h delete mode 100644 Generals/Code/Libraries/Source/WWVegas/WW3D2/textureloader.cpp delete mode 100644 Generals/Code/Libraries/Source/WWVegas/WW3D2/textureloader.h delete mode 100644 Generals/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp delete mode 100644 Generals/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.h diff --git a/Core/GameEngine/CMakeLists.txt b/Core/GameEngine/CMakeLists.txt index 8c720b6238..e486efe32e 100644 --- a/Core/GameEngine/CMakeLists.txt +++ b/Core/GameEngine/CMakeLists.txt @@ -230,7 +230,7 @@ set(GAMEENGINE_SRC # Include/GameClient/TerrainVisual.h Include/GameClient/VideoPlayer.h Include/GameClient/View.h -# Include/GameClient/Water.h + Include/GameClient/Water.h # Include/GameClient/WindowLayout.h Include/GameClient/WindowVideoManager.h # Include/GameClient/WindowXlat.h @@ -835,7 +835,7 @@ set(GAMEENGINE_SRC Source/GameClient/VideoPlayer.cpp Source/GameClient/VideoStream.cpp Source/GameClient/View.cpp -# Source/GameClient/Water.cpp + Source/GameClient/Water.cpp # Source/GameLogic/AI/AI.cpp # Source/GameLogic/AI/AIDock.cpp # Source/GameLogic/AI/AIGroup.cpp diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Water.h b/Core/GameEngine/Include/GameClient/Water.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/GameClient/Water.h rename to Core/GameEngine/Include/GameClient/Water.h diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Water.cpp b/Core/GameEngine/Source/GameClient/Water.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/GameClient/Water.cpp rename to Core/GameEngine/Source/GameClient/Water.cpp diff --git a/Core/GameEngineDevice/CMakeLists.txt b/Core/GameEngineDevice/CMakeLists.txt index c53c29220f..66dff03ecc 100644 --- a/Core/GameEngineDevice/CMakeLists.txt +++ b/Core/GameEngineDevice/CMakeLists.txt @@ -13,7 +13,7 @@ set(GAMEENGINEDEVICE_SRC # Include/W3DDevice/GameClient/Module/W3DDebrisDraw.h # Include/W3DDevice/GameClient/Module/W3DDefaultDraw.h # Include/W3DDevice/GameClient/Module/W3DDependencyModelDraw.h -# Include/W3DDevice/GameClient/Module/W3DLaserDraw.h + Include/W3DDevice/GameClient/Module/W3DLaserDraw.h # Include/W3DDevice/GameClient/Module/W3DModelDraw.h # Include/W3DDevice/GameClient/Module/W3DOverlordAircraftDraw.h # Include/W3DDevice/GameClient/Module/W3DOverlordTankDraw.h @@ -73,8 +73,8 @@ set(GAMEENGINEDEVICE_SRC Include/W3DDevice/GameClient/W3DVideoBuffer.h Include/W3DDevice/GameClient/W3DView.h # Include/W3DDevice/GameClient/W3DVolumetricShadow.h -# Include/W3DDevice/GameClient/W3DWater.h -# Include/W3DDevice/GameClient/W3DWaterTracks.h + Include/W3DDevice/GameClient/W3DWater.h + Include/W3DDevice/GameClient/W3DWaterTracks.h # Include/W3DDevice/GameClient/W3DWaypointBuffer.h # Include/W3DDevice/GameClient/W3DWebBrowser.h # Include/W3DDevice/GameClient/WorldHeightMap.h @@ -102,7 +102,7 @@ set(GAMEENGINEDEVICE_SRC # Source/W3DDevice/GameClient/Drawable/Draw/W3DDebrisDraw.cpp # Source/W3DDevice/GameClient/Drawable/Draw/W3DDefaultDraw.cpp # Source/W3DDevice/GameClient/Drawable/Draw/W3DDependencyModelDraw.cpp -# Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp + Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp # Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp # Source/W3DDevice/GameClient/Drawable/Draw/W3DOverlordAircraftDraw.cpp # Source/W3DDevice/GameClient/Drawable/Draw/W3DOverlordTankDraw.cpp @@ -176,8 +176,8 @@ set(GAMEENGINEDEVICE_SRC Source/W3DDevice/GameClient/W3DView.cpp # Source/W3DDevice/GameClient/W3dWaypointBuffer.cpp # Source/W3DDevice/GameClient/W3DWebBrowser.cpp -# Source/W3DDevice/GameClient/Water/W3DWater.cpp -# Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp + Source/W3DDevice/GameClient/Water/W3DWater.cpp + Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp # Source/W3DDevice/GameClient/WorldHeightMap.cpp # Source/W3DDevice/GameLogic/W3DGameLogic.cpp # Source/W3DDevice/GameLogic/W3DGhostObject.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DLaserDraw.h b/Core/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DLaserDraw.h similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DLaserDraw.h rename to Core/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DLaserDraw.h diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h b/Core/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h rename to Core/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWaterTracks.h b/Core/GameEngineDevice/Include/W3DDevice/GameClient/W3DWaterTracks.h similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWaterTracks.h rename to Core/GameEngineDevice/Include/W3DDevice/GameClient/W3DWaterTracks.h diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp rename to Core/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp rename to Core/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp rename to Core/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvp similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvp rename to Core/GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvp diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvv b/Core/GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvv similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvv rename to Core/GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvv diff --git a/Core/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt b/Core/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt index 29a8f9a3ba..35c7ff4bd6 100644 --- a/Core/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt +++ b/Core/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt @@ -15,8 +15,8 @@ set(WW3D2_SRC assetstatus.h bitmaphandler.cpp bitmaphandler.h - #bmp2d.cpp - #bmp2d.h + bmp2d.cpp + bmp2d.h #boxrobj.cpp #boxrobj.h bwrender.cpp @@ -56,8 +56,8 @@ set(WW3D2_SRC #dx8renderer.h #dx8rendererdebugger.cpp #dx8rendererdebugger.h - #dx8texman.cpp - #dx8texman.h + dx8texman.cpp + dx8texman.h #dx8vertexbuffer.cpp #dx8vertexbuffer.h dx8webbrowser.cpp @@ -108,8 +108,8 @@ set(WW3D2_SRC #mapper.h matinfo.cpp matinfo.h - #matpass.cpp - #matpass.h + matpass.cpp + matpass.h #matrixmapper.cpp #matrixmapper.h #mesh.cpp @@ -200,18 +200,18 @@ set(WW3D2_SRC stripoptimizer.h surfaceclass.cpp surfaceclass.h - #texproject.cpp - #texproject.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 + texture.cpp + texture.h + texturefilter.cpp + texturefilter.h + textureloader.cpp + textureloader.h + texturethumbnail.cpp + texturethumbnail.h #vertmaterial.cpp #vertmaterial.h visrasterizer.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/bmp2d.cpp b/Core/Libraries/Source/WWVegas/WW3D2/bmp2d.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/bmp2d.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/bmp2d.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/bmp2d.h b/Core/Libraries/Source/WWVegas/WW3D2/bmp2d.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/bmp2d.h rename to Core/Libraries/Source/WWVegas/WW3D2/bmp2d.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8texman.cpp b/Core/Libraries/Source/WWVegas/WW3D2/dx8texman.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8texman.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/dx8texman.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8texman.h b/Core/Libraries/Source/WWVegas/WW3D2/dx8texman.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8texman.h rename to Core/Libraries/Source/WWVegas/WW3D2/dx8texman.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/matpass.cpp b/Core/Libraries/Source/WWVegas/WW3D2/matpass.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/matpass.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/matpass.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/matpass.h b/Core/Libraries/Source/WWVegas/WW3D2/matpass.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/matpass.h rename to Core/Libraries/Source/WWVegas/WW3D2/matpass.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texproject.cpp b/Core/Libraries/Source/WWVegas/WW3D2/texproject.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texproject.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/texproject.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texproject.h b/Core/Libraries/Source/WWVegas/WW3D2/texproject.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texproject.h rename to Core/Libraries/Source/WWVegas/WW3D2/texproject.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texture.cpp b/Core/Libraries/Source/WWVegas/WW3D2/texture.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texture.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/texture.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texture.h b/Core/Libraries/Source/WWVegas/WW3D2/texture.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texture.h rename to Core/Libraries/Source/WWVegas/WW3D2/texture.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texturefilter.cpp b/Core/Libraries/Source/WWVegas/WW3D2/texturefilter.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texturefilter.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/texturefilter.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texturefilter.h b/Core/Libraries/Source/WWVegas/WW3D2/texturefilter.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texturefilter.h rename to Core/Libraries/Source/WWVegas/WW3D2/texturefilter.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/textureloader.cpp b/Core/Libraries/Source/WWVegas/WW3D2/textureloader.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/textureloader.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/textureloader.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/textureloader.h b/Core/Libraries/Source/WWVegas/WW3D2/textureloader.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/textureloader.h rename to Core/Libraries/Source/WWVegas/WW3D2/textureloader.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp b/Core/Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.h b/Core/Libraries/Source/WWVegas/WW3D2/texturethumbnail.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.h rename to Core/Libraries/Source/WWVegas/WW3D2/texturethumbnail.h diff --git a/Generals/Code/GameEngine/CMakeLists.txt b/Generals/Code/GameEngine/CMakeLists.txt index 730e1ec6be..357a3a48b6 100644 --- a/Generals/Code/GameEngine/CMakeLists.txt +++ b/Generals/Code/GameEngine/CMakeLists.txt @@ -215,7 +215,7 @@ set(GAMEENGINE_SRC Include/GameClient/TerrainVisual.h # Include/GameClient/VideoPlayer.h # Include/GameClient/View.h - Include/GameClient/Water.h +# Include/GameClient/Water.h Include/GameClient/WindowLayout.h # Include/GameClient/WindowVideoManager.h Include/GameClient/WindowXlat.h @@ -777,7 +777,7 @@ set(GAMEENGINE_SRC Source/GameClient/Terrain/TerrainVisual.cpp # Source/GameClient/VideoPlayer.cpp # Source/GameClient/View.cpp - Source/GameClient/Water.cpp +# Source/GameClient/Water.cpp Source/GameLogic/AI/AI.cpp Source/GameLogic/AI/AIDock.cpp Source/GameLogic/AI/AIGroup.cpp diff --git a/Generals/Code/GameEngine/Include/GameClient/Water.h b/Generals/Code/GameEngine/Include/GameClient/Water.h deleted file mode 100644 index 7814c543bd..0000000000 --- a/Generals/Code/GameEngine/Include/GameClient/Water.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) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: Water.h ////////////////////////////////////////////////////////////////////////////////// -// Author: Colin Day, December 2001 -// Desc: Water settings -/////////////////////////////////////////////////////////////////////////////////////////////////// - -#pragma once - -// INLCLUDES ////////////////////////////////////////////////////////////////////////////////////// -#include "Common/GameType.h" -#include "Common/Overridable.h" -#include "Common/Override.h" - -//------------------------------------------------------------------------------------------------- -struct FieldParse; - -//------------------------------------------------------------------------------------------------- -/** This structures keeps the settings for how our water will look */ -//------------------------------------------------------------------------------------------------- -class WaterSetting -{ - -public: - - WaterSetting( void ); - virtual ~WaterSetting( void ); - - /// Get the INI parsing table for loading - const FieldParse *getFieldParse( void ) { return m_waterSettingFieldParseTable; } - - static const FieldParse m_waterSettingFieldParseTable[]; ///< the parse table for INI definition - AsciiString m_skyTextureFile; - AsciiString m_waterTextureFile; - Int m_waterRepeatCount; - Real m_skyTexelsPerUnit; //texel density of sky plane (higher value repeats texture more). - RGBAColorInt m_vertex00Diffuse; - RGBAColorInt m_vertex10Diffuse; - RGBAColorInt m_vertex11Diffuse; - RGBAColorInt m_vertex01Diffuse; - RGBAColorInt m_waterDiffuseColor; - RGBAColorInt m_transparentWaterDiffuse; - Real m_uScrollPerMs; - Real m_vScrollPerMs; - -}; - -//------------------------------------------------------------------------------------------------- -/** This structure keeps the transparency and vertex settings, which are the same regardless of the - time of day. They can be overridden on a per-map basis. */ -//------------------------------------------------------------------------------------------------- -class WaterTransparencySetting : public Overridable -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( WaterTransparencySetting, "WaterTransparencySetting" ) - - 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; - AsciiString m_skyboxTextureS; - AsciiString m_skyboxTextureW; - AsciiString m_skyboxTextureT; - - public: - WaterTransparencySetting() - { - 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"; - m_skyboxTextureW = "TSMorningW.tga"; - m_skyboxTextureT = "TSMorningT.tga"; - } - - static const FieldParse m_waterTransparencySettingFieldParseTable[]; ///< the parse table for INI definition - - /// Get the INI parsing table for loading - const FieldParse *getFieldParse( void ) const { return m_waterTransparencySettingFieldParseTable; } -}; - -EMPTY_DTOR(WaterTransparencySetting) - -// EXTERNAL /////////////////////////////////////////////////////////////////////////////////////// -extern WaterSetting WaterSettings[ TIME_OF_DAY_COUNT ]; - -extern OVERRIDE TheWaterTransparency; diff --git a/Generals/Code/GameEngine/Source/GameClient/Water.cpp b/Generals/Code/GameEngine/Source/GameClient/Water.cpp deleted file mode 100644 index f59a942086..0000000000 --- a/Generals/Code/GameEngine/Source/GameClient/Water.cpp +++ /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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: Water.cpp //////////////////////////////////////////////////////////////////////////////// -// Author: Colin Day, December 2001 -// Desc: Map water settings -/////////////////////////////////////////////////////////////////////////////////////////////////// - -// INCLUDES /////////////////////////////////////////////////////////////////////////////////////// -#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine - -#include "GameClient/Water.h" -#include "Common/INI.h" - -// GLOBALS //////////////////////////////////////////////////////////////////////////////////////// -WaterSetting WaterSettings[ TIME_OF_DAY_COUNT ]; -OVERRIDE TheWaterTransparency = NULL; - -// PRIVATE DATA /////////////////////////////////////////////////////////////////////////////////// -const FieldParse WaterSetting::m_waterSettingFieldParseTable[] = -{ - - { "SkyTexture", INI::parseAsciiString, NULL, offsetof( WaterSetting, m_skyTextureFile ) }, - { "WaterTexture", INI::parseAsciiString, NULL, offsetof( WaterSetting, m_waterTextureFile ) }, - { "Vertex00Color", INI::parseRGBAColorInt, NULL, offsetof( WaterSetting, m_vertex00Diffuse ) }, - { "Vertex10Color", INI::parseRGBAColorInt, NULL, offsetof( WaterSetting, m_vertex10Diffuse ) }, - { "Vertex01Color", INI::parseRGBAColorInt, NULL, offsetof( WaterSetting, m_vertex01Diffuse ) }, - { "Vertex11Color", INI::parseRGBAColorInt, NULL, offsetof( WaterSetting, m_vertex11Diffuse ) }, - { "DiffuseColor", INI::parseRGBAColorInt, NULL, offsetof( WaterSetting, m_waterDiffuseColor ) }, - { "TransparentDiffuseColor", INI::parseRGBAColorInt, NULL, offsetof( WaterSetting, m_transparentWaterDiffuse ) }, - { "UScrollPerMS", INI::parseReal, NULL, offsetof( WaterSetting, m_uScrollPerMs ) }, - { "VScrollPerMS", INI::parseReal, NULL, offsetof( WaterSetting, m_vScrollPerMs ) }, - { "SkyTexelsPerUnit", INI::parseReal, NULL, offsetof( WaterSetting, m_skyTexelsPerUnit ) }, - { "WaterRepeatCount", INI::parseInt, NULL, offsetof( WaterSetting, m_waterRepeatCount ) }, - - { NULL, NULL, NULL, 0 }, - -}; - -// PRIVATE DATA /////////////////////////////////////////////////////////////////////////////////// -const FieldParse WaterTransparencySetting::m_waterTransparencySettingFieldParseTable[] = -{ - - { "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 ) }, - { "SkyboxTextureW", INI::parseAsciiString,NULL, offsetof( WaterTransparencySetting, m_skyboxTextureW ) }, - { "SkyboxTextureT", INI::parseAsciiString,NULL, offsetof( WaterTransparencySetting, m_skyboxTextureT ) }, - - - { 0, 0, 0, 0 }, -}; - - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -WaterSetting::WaterSetting( void ) -{ - - m_skyTextureFile.clear(); - m_waterTextureFile.clear(); - m_waterRepeatCount = 0; - m_skyTexelsPerUnit = 0.0f; - - m_vertex00Diffuse.red = 0; - m_vertex00Diffuse.green = 0; - m_vertex00Diffuse.blue = 0; - m_vertex00Diffuse.alpha = 0; - - m_vertex01Diffuse.red = 0; - m_vertex01Diffuse.green = 0; - m_vertex01Diffuse.blue = 0; - m_vertex01Diffuse.alpha = 0; - - m_vertex10Diffuse.red = 0; - m_vertex10Diffuse.green = 0; - m_vertex10Diffuse.blue = 0; - m_vertex10Diffuse.alpha = 0; - - m_vertex11Diffuse.red = 0; - m_vertex11Diffuse.green = 0; - m_vertex11Diffuse.blue = 0; - m_vertex11Diffuse.alpha = 0; - - m_waterDiffuseColor.red = 0; - m_waterDiffuseColor.green = 0; - m_waterDiffuseColor.blue = 0; - m_waterDiffuseColor.alpha = 0; - - m_transparentWaterDiffuse.red = 0; - m_transparentWaterDiffuse.green = 0; - m_transparentWaterDiffuse.blue = 0; - m_transparentWaterDiffuse.alpha = 0; - - m_uScrollPerMs = 0.0f; - m_vScrollPerMs = 0.0f; - -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -WaterSetting::~WaterSetting( void ) -{ - -} - - diff --git a/Generals/Code/GameEngineDevice/CMakeLists.txt b/Generals/Code/GameEngineDevice/CMakeLists.txt index de6e7bd69a..37a9ed2334 100644 --- a/Generals/Code/GameEngineDevice/CMakeLists.txt +++ b/Generals/Code/GameEngineDevice/CMakeLists.txt @@ -10,7 +10,7 @@ set(GAMEENGINEDEVICE_SRC Include/W3DDevice/GameClient/Module/W3DDebrisDraw.h Include/W3DDevice/GameClient/Module/W3DDefaultDraw.h Include/W3DDevice/GameClient/Module/W3DDependencyModelDraw.h - Include/W3DDevice/GameClient/Module/W3DLaserDraw.h +# Include/W3DDevice/GameClient/Module/W3DLaserDraw.h Include/W3DDevice/GameClient/Module/W3DModelDraw.h Include/W3DDevice/GameClient/Module/W3DOverlordTankDraw.h Include/W3DDevice/GameClient/Module/W3DPoliceCarDraw.h @@ -62,8 +62,8 @@ set(GAMEENGINEDEVICE_SRC # Include/W3DDevice/GameClient/W3DVideoBuffer.h # Include/W3DDevice/GameClient/W3DView.h Include/W3DDevice/GameClient/W3DVolumetricShadow.h - Include/W3DDevice/GameClient/W3DWater.h - Include/W3DDevice/GameClient/W3DWaterTracks.h +# Include/W3DDevice/GameClient/W3DWater.h +# Include/W3DDevice/GameClient/W3DWaterTracks.h Include/W3DDevice/GameClient/W3DWaypointBuffer.h Include/W3DDevice/GameClient/W3DWebBrowser.h Include/W3DDevice/GameClient/WorldHeightMap.h @@ -88,7 +88,7 @@ set(GAMEENGINEDEVICE_SRC Source/W3DDevice/GameClient/Drawable/Draw/W3DDebrisDraw.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DDefaultDraw.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DDependencyModelDraw.cpp - Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp +# Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DOverlordTankDraw.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DPoliceCarDraw.cpp @@ -161,10 +161,10 @@ set(GAMEENGINEDEVICE_SRC # Source/W3DDevice/GameClient/W3DView.cpp Source/W3DDevice/GameClient/W3dWaypointBuffer.cpp Source/W3DDevice/GameClient/W3DWebBrowser.cpp - Source/W3DDevice/GameClient/Water/W3DWater.cpp - Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp - Source/W3DDevice/GameClient/Water/wave.nvp - Source/W3DDevice/GameClient/Water/wave.nvv +# Source/W3DDevice/GameClient/Water/W3DWater.cpp +# Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp +# Source/W3DDevice/GameClient/Water/wave.nvp +# Source/W3DDevice/GameClient/Water/wave.nvv Source/W3DDevice/GameClient/WorldHeightMap.cpp Source/W3DDevice/GameLogic/W3DGameLogic.cpp Source/W3DDevice/GameLogic/W3DGhostObject.cpp diff --git a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DLaserDraw.h b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DLaserDraw.h deleted file mode 100644 index 122af0b5aa..0000000000 --- a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DLaserDraw.h +++ /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) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: W3DLaserDraw.h /////////////////////////////////////////////////////////////////////////// -// Author: -// Desc: -/////////////////////////////////////////////////////////////////////////////////////////////////// - -#pragma once - -// INCLUDES /////////////////////////////////////////////////////////////////////////////////////// -#include "Common/DrawModule.h" -//#include "WW3D2/Line3D.h" -#include "GameClient/Color.h" - -class SegmentedLineClass; -class TextureClass; - -class W3DLaserDrawModuleData : public ModuleData -{ -public: - - Color m_innerColor; - Color m_outerColor; - Real m_innerBeamWidth; - Real m_outerBeamWidth; - Real m_scrollRate; - Bool m_tile; - UnsignedInt m_numBeams; - UnsignedInt m_maxIntensityFrames; - UnsignedInt m_fadeFrames; - AsciiString m_textureName; - UnsignedInt m_segments; - Real m_arcHeight; - Real m_segmentOverlapRatio; - Real m_tilingScalar; - - W3DLaserDrawModuleData(); - ~W3DLaserDrawModuleData(); - static void buildFieldParse(MultiIniFieldParse& p); -}; - -//------------------------------------------------------------------------------------------------- -/** W3D laser draw */ -//------------------------------------------------------------------------------------------------- -class W3DLaserDraw : public DrawModule, public LaserDrawInterface -{ - - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( W3DLaserDraw, "W3DLaserDraw" ) - MAKE_STANDARD_MODULE_MACRO_WITH_MODULE_DATA( W3DLaserDraw, W3DLaserDrawModuleData ) - -public: - - W3DLaserDraw( Thing *thing, const ModuleData* moduleData ); - // virtual destructor prototype provided by memory pool declaration - - virtual void doDrawModule(const Matrix3D* transformMtx); - virtual void releaseShadows(void) {}; ///< we don't care about preserving temporary shadows. - virtual void allocateShadows(void) {}; ///< we don't care about preserving temporary shadows. - virtual void setShadowsEnabled(Bool enable) { } - virtual void setFullyObscuredByShroud(Bool fullyObscured) { }; - virtual void reactToTransformChange(const Matrix3D* oldMtx, const Coord3D* oldPos, Real oldAngle) { } - virtual void reactToGeometryChange() { } - virtual Bool isLaser() const { return true; } - Real getLaserTemplateWidth() const; - - virtual LaserDrawInterface* getLaserDrawInterface() { return this; } - virtual const LaserDrawInterface* getLaserDrawInterface() const { return this; } - -protected: - - SegmentedLineClass **m_line3D; ///< line 3D for effect - TextureClass *m_texture; - Real m_textureAspectRatio; ///< aspect ratio of texture - Bool m_selfDirty; // not saved - -}; diff --git a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h deleted file mode 100644 index 42e71a3fbc..0000000000 --- a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h +++ /dev/null @@ -1,290 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public 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: W3DWater.h /////////////////////////////////////////////////// - -#pragma once - -#include "always.h" -#include "rendobj.h" -#include "w3d_file.h" -#include "dx8vertexbuffer.h" -#include "dx8indexbuffer.h" -#include "shader.h" -#include "vertmaterial.h" -#include "light.h" -#include "Lib/BaseType.h" -#include "Common/GameType.h" -#include "Common/Snapshot.h" - -#define INVALID_WATER_HEIGHT 0.0f ///water height guaranteed to be below all terrain. - -#define NUM_BUMP_FRAMES 32 ///number of animation frames in bump map -//Offsets in constant register file to Vertex shader constants -#define CV_ZERO 0 -#define CV_ONE 1 -#define CV_WORLDVIEWPROJ_0 2 -#define CV_TEXPROJ_0 6 -#define CV_PATCH_SCALE_OFFSET 10 - -class PolygonTrigger; -class WaterTracksRenderSystem; -class Xfer; -/// Custom render object that draws mirrors, water, and skies. -/** -This render object handles drawing reflected W3D scenes. It will only work -with rectangular planar surfaces and was tuned with an emphasis on water. -Since skies are only visible in reflections, this code will also -render clouds and sky bodies. -*/ -class WaterRenderObjClass : public Snapshot, - public RenderObjClass -{ - -public: - - enum WaterType - { - WATER_TYPE_0_TRANSLUCENT = 0, //translucent water, no reflection - WATER_TYPE_1_FB_REFLECTION, //legacy frame buffer reflection (non translucent) - WATER_TYPE_2_PVSHADER, //pixel/vertex shader, texture reflection - WATER_TYPE_3_GRIDMESH, //3D Mesh based water - }; - - WaterRenderObjClass(void); - ~WaterRenderObjClass(void); - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface (W3D methods) - ///////////////////////////////////////////////////////////////////////////// - virtual RenderObjClass * Clone(void) const; - virtual int Class_ID(void) const; - virtual void Render(RenderInfoClass & rinfo); -/// @todo: Add methods for collision detection with water surface -// 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 Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const; - virtual void Get_Obj_Space_Bounding_Box(AABoxClass & aabox) const; - // Get and set static sort level - virtual int Get_Sort_Level(void) const { return m_sortLevel; } - virtual void Set_Sort_Level(int level) { m_sortLevel = level;} - - ///allocate W3D resources needed to render water - void renderWater(void); /// m_gridCellsX-1 ) - return FALSE; - if (gridY < 0) - return FALSE; - if (gridY > m_gridCellsY-1 ) - return FALSE; - - return TRUE; -} - -extern WaterRenderObjClass *TheWaterRenderObj; ///. -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -#pragma once - -enum waveType CPP_11(: Int); //forward reference - -/// Custom render object that draws animated tracks/waves on the water. -/** - This is an object which draws a small breaking wave or splash animation. These objects are - to be managed/accessed only by the WaterTracksRenderObjClassSystem -*/ -class WaterTracksObj -{ - friend class WaterTracksRenderSystem; - -public: - - WaterTracksObj(void); - ~WaterTracksObj(void); - - virtual void Render(void) {}; ///. -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: W3DLaserDraw.cpp ///////////////////////////////////////////////////////////////////////// -// Author: Colin Day, May 2001 -// Desc: W3DLaserDraw -// Updated: Kris Morness July 2002 -- made it data driven and added new features to make it flexible. -/////////////////////////////////////////////////////////////////////////////////////////////////// - -// INCLUDES /////////////////////////////////////////////////////////////////////////////////////// -#include - -#include "Common/Thing.h" -#include "Common/ThingTemplate.h" -#include "Common/Xfer.h" -#include "GameClient/Color.h" -#include "GameClient/Drawable.h" -#include "GameClient/GameClient.h" -#include "GameClient/RayEffect.h" -#include "GameLogic/GameLogic.h" -#include "GameLogic/Object.h" -#include "GameLogic/TerrainLogic.h" -#include "GameLogic/Module/LaserUpdate.h" -#include "W3DDevice/GameClient/Module/W3DLaserDraw.h" -#include "W3DDevice/GameClient/W3DDisplay.h" -#include "W3DDevice/GameClient/W3DScene.h" -#include "WW3D2/rinfo.h" -#include "WW3D2/camera.h" -#include "WW3D2/segline.h" -#include "WWMath/vector3.h" -#include "WW3D2/assetmgr.h" - - - -// PUBLIC FUNCTIONS /////////////////////////////////////////////////////////////////////////////// - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -W3DLaserDrawModuleData::W3DLaserDrawModuleData() -{ - m_innerBeamWidth = 0.0f; //The total width of beam - m_outerBeamWidth = 1.0f; //The total width of beam - m_numBeams = 1; //Number of overlapping cylinders that make the beam. 1 beam will just use inner data. - m_maxIntensityFrames = 0; //Laser stays at max intensity for specified time in ms. - m_fadeFrames = 0; //Laser will fade and delete. - m_scrollRate = 0.0f; - m_tile = false; - m_segments = 1; - m_arcHeight = 0.0f; - m_segmentOverlapRatio = 0.0f; - m_tilingScalar = 1.0f; -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -W3DLaserDrawModuleData::~W3DLaserDrawModuleData() -{ -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -void W3DLaserDrawModuleData::buildFieldParse(MultiIniFieldParse& p) -{ - ModuleData::buildFieldParse(p); - - static const FieldParse dataFieldParse[] = - { - { "NumBeams", INI::parseUnsignedInt, NULL, offsetof( W3DLaserDrawModuleData, m_numBeams ) }, - { "InnerBeamWidth", INI::parseReal, NULL, offsetof( W3DLaserDrawModuleData, m_innerBeamWidth ) }, - { "OuterBeamWidth", INI::parseReal, NULL, offsetof( W3DLaserDrawModuleData, m_outerBeamWidth ) }, - { "InnerColor", INI::parseColorInt, NULL, offsetof( W3DLaserDrawModuleData, m_innerColor ) }, - { "OuterColor", INI::parseColorInt, NULL, offsetof( W3DLaserDrawModuleData, m_outerColor ) }, - { "MaxIntensityLifetime", INI::parseDurationUnsignedInt, NULL, offsetof( W3DLaserDrawModuleData, m_maxIntensityFrames ) }, - { "FadeLifetime", INI::parseDurationUnsignedInt, NULL, offsetof( W3DLaserDrawModuleData, m_fadeFrames ) }, - { "Texture", INI::parseAsciiString, NULL, offsetof( W3DLaserDrawModuleData, m_textureName ) }, - { "ScrollRate", INI::parseReal, NULL, offsetof( W3DLaserDrawModuleData, m_scrollRate ) }, - { "Tile", INI::parseBool, NULL, offsetof( W3DLaserDrawModuleData, m_tile ) }, - { "Segments", INI::parseUnsignedInt, NULL, offsetof( W3DLaserDrawModuleData, m_segments ) }, - { "ArcHeight", INI::parseReal, NULL, offsetof( W3DLaserDrawModuleData, m_arcHeight ) }, - { "SegmentOverlapRatio", INI::parseReal, NULL, offsetof( W3DLaserDrawModuleData, m_segmentOverlapRatio ) }, - { "TilingScalar", INI::parseReal, NULL, offsetof( W3DLaserDrawModuleData, m_tilingScalar ) }, - { 0, 0, 0, 0 } - }; - p.add(dataFieldParse); -} - - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -W3DLaserDraw::W3DLaserDraw( Thing *thing, const ModuleData* moduleData ) : - DrawModule( thing, moduleData ), - m_line3D(NULL), - m_texture(NULL), - m_textureAspectRatio(1.0f), - m_selfDirty(TRUE) -{ - Vector3 dummyPos1( 0.0f, 0.0f, 0.0f ); - Vector3 dummyPos2( 1.0f, 1.0f, 1.0f ); - Int i; - - const W3DLaserDrawModuleData *data = getW3DLaserDrawModuleData(); - - 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; - m_texture->Get_Level_Description(surfaceDesc); - 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 ); - - //Make sure our beams range between 1 and the maximum cap. -#ifdef I_WANT_TO_BE_FIRED -// srj sez: this data is const for a reason. casting away the constness because we don't like the values -// isn't an acceptable solution. if you need to constrain the values, do so at parsing time, when -// it's still legal to modify these values. (In point of fact, there's not even really any reason to limit -// the numBeams or segments anymore.) - data->m_numBeams = __min( __max( 1, data->m_numBeams ), MAX_LASER_LINES ); - data->m_segments = __min( __max( 1, data->m_segments ), MAX_SEGMENTS ); - data->m_tilingScalar = __max( 0.01f, data->m_tilingScalar ); -#endif - - //Allocate an array of lines equal to the number of beams * segments - m_line3D = NEW SegmentedLineClass *[ data->m_numBeams * data->m_segments ]; - - for( UnsignedInt segment = 0; segment < data->m_segments; segment++ ) - { - //We don't care about segment positioning yet until we actually set the position - - // create all the lines we need at the right transparency level - for( i = data->m_numBeams - 1; i >= 0; i-- ) - { - int index = segment * data->m_numBeams + i; - - Real red, green, blue, alpha, width; - - if( data->m_numBeams == 1 ) - { - width = data->m_innerBeamWidth; - alpha = innerAlpha; - red = innerRed * innerAlpha; - green = innerGreen * innerAlpha; - blue = innerBlue * innerAlpha; - } - else - { - //Calculate the scale between min and max values - //0 means use min value, 1 means use max value - //0.2 means min value + 20% of the diff between min and max - Real scale = i / ( data->m_numBeams - 1.0f); - - width = data->m_innerBeamWidth + scale * (data->m_outerBeamWidth - data->m_innerBeamWidth); - alpha = innerAlpha + scale * (outerAlpha - innerAlpha); - red = innerRed + scale * (outerRed - innerRed) * innerAlpha; - green = innerGreen + scale * (outerGreen - innerGreen) * innerAlpha; - blue = innerBlue + scale * (outerBlue - innerBlue) * innerAlpha; - } - - m_line3D[ index ] = NEW SegmentedLineClass; - - SegmentedLineClass *line = m_line3D[ index ]; - if( line ) - { - line->Set_Texture( m_texture ); - line->Set_Shader( ShaderClass::_PresetAdditiveShader ); //pick the alpha blending mode you want - see shader.h for others. - line->Set_Width( width ); - line->Set_Color( Vector3( red, green, blue ) ); - 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 - } - - // add to scene - if (W3DDisplay::m_3DScene != NULL) - W3DDisplay::m_3DScene->Add_Render_Object( line ); //add it to our scene so it gets rendered with other objects. - - // hide the render object until the first time we come to draw it and - // set the correct position - line->Set_Visible( 0 ); - } - - - } - - } - -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -W3DLaserDraw::~W3DLaserDraw( void ) -{ - const W3DLaserDrawModuleData *data = getW3DLaserDrawModuleData(); - - for( UnsignedInt i = 0; i < data->m_numBeams * data->m_segments; i++ ) - { - - // remove line from scene - if (W3DDisplay::m_3DScene != NULL) - W3DDisplay::m_3DScene->Remove_Render_Object( m_line3D[ i ] ); - - // delete line - REF_PTR_RELEASE( m_line3D[ i ] ); - - } - - delete [] m_line3D; - // TheSuperHackers @fix Mauller 11/03/2025 Free reference counted material - REF_PTR_RELEASE(m_texture); -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -Real W3DLaserDraw::getLaserTemplateWidth() const -{ - const W3DLaserDrawModuleData *data = getW3DLaserDrawModuleData(); - return data->m_outerBeamWidth * 0.5f; -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -void W3DLaserDraw::doDrawModule(const Matrix3D* transformMtx) -{ - //UnsignedInt currentFrame = TheGameClient->getFrame(); - const W3DLaserDrawModuleData *data = getW3DLaserDrawModuleData(); - - //Get the updatemodule that drives it... - Drawable *draw = getDrawable(); - static NameKeyType key_LaserUpdate = NAMEKEY( "LaserUpdate" ); - LaserUpdate *update = (LaserUpdate*)draw->findClientUpdateModule( key_LaserUpdate ); - if( !update ) - { - DEBUG_ASSERTCRASH( 0, ("W3DLaserDraw::doDrawModule() expects its owner drawable %s to have a ClientUpdate = LaserUpdate module.", draw->getTemplate()->getName().str() )); - return; - } - - //If the update has moved the laser, it requires a reset of the laser. - if (update->isDirty() || m_selfDirty) - { - update->setDirty(false); - m_selfDirty = false; - - Vector3 laserPoints[ 2 ]; - - for( UnsignedInt segment = 0; segment < data->m_segments; segment++ ) - { - if( data->m_arcHeight > 0.0f && data->m_segments > 1 ) - { - //CALCULATE A CURVED LINE BASED ON TOTAL LENGTH AND DESIRED HEIGHT INCREASE - //To do this we will use a portion of the cos wave ranging between -0.25PI - //and +0.25PI. 0PI is 1.0 and 0.25PI is 0.70 -- resulting in a somewhat - //gentle curve depending on the line height and length. We also have to make - //the line *level* for this phase of the calculations. - - //Get the desired direct line - Coord3D lineStart, lineEnd, lineVector; - lineStart.set( update->getStartPos() ); - lineEnd.set( update->getEndPos() ); - //This is critical -- in the case we have sloped lines (at the end, we'll fix it) -// lineEnd.z = lineStart.z; - - //Get the length of the line - lineVector.set( &lineEnd ); - lineVector.sub( &lineStart ); - Real lineLength = lineVector.length(); - - //Get the middle point (we'll use this to determine how far we are from - //that to calculate our height -- middle point is the highest). - Coord3D lineMiddle; - lineMiddle.set( &lineStart ); - lineMiddle.add( &lineEnd ); - lineMiddle.scale( 0.5 ); - - //The half length is used to scale with the distance from middle to - //get our cos( 0 to 0.25 PI) cos value - Real halfLength = lineLength * 0.5f; - - //Now calculate which segment we will use. - Real startSegmentRatio = segment / ((Real)data->m_segments); - Real endSegmentRatio = (segment + 1.0f) / ((Real)data->m_segments); - - //Offset the segment ever-so-slightly to minimize overlap -- only apply - //to segments that are not the start/end point - if( segment > 0 ) - { - startSegmentRatio -= data->m_segmentOverlapRatio; - } - if( segment < data->m_segments - 1 ) - { - endSegmentRatio += data->m_segmentOverlapRatio; - } - - //Calculate our start segment position on the *ground*. - Coord3D segmentStart, segmentEnd, vector; - vector.set( &lineVector ); - vector.scale( startSegmentRatio ); - segmentStart.set( &lineStart ); - segmentStart.add( &vector ); - - //Calculate our end segment position on the *ground*. - vector.set( &lineVector ); - vector.scale( endSegmentRatio ); - segmentEnd.set( &lineStart ); - segmentEnd.add( &vector ); - - //-------------------------------------------------------------------------------- - //Now at this point, we have our segment line in the level positions that we want. - //Calculate the raised height for the start/end segment positions using cosine. - //-------------------------------------------------------------------------------- - - //Calculate the distance from midpoint for the start positions. - vector.set( &lineMiddle ); - vector.sub( &segmentStart ); - Real dist = vector.length(); - Real scaledRadians = dist / halfLength * PI * 0.5f; - Real height = cos( scaledRadians ); - height *= data->m_arcHeight; - segmentStart.z += height; - - //Now do the same thing for the end position. - vector.set( &lineMiddle ); - vector.sub( &segmentEnd ); - dist = vector.length(); - scaledRadians = dist / halfLength * PI * 0.5f; - height = cos( scaledRadians ); - height *= data->m_arcHeight; - segmentEnd.z += height; - - //This makes the laser skim the ground rather than penetrate it! - laserPoints[ 0 ].Set( segmentStart.x, segmentStart.y, - MAX( segmentStart.z, 2.0f + TheTerrainLogic->getGroundHeight(segmentStart.x, segmentStart.y) ) ); - laserPoints[ 1 ].Set( segmentEnd.x, segmentEnd.y, - MAX( segmentEnd.z, 2.0f + TheTerrainLogic->getGroundHeight(segmentEnd.x, segmentEnd.y) ) ); - - } - else - { - //No arc -- way simpler! - laserPoints[ 0 ].Set( update->getStartPos()->x, update->getStartPos()->y, update->getStartPos()->z ); - laserPoints[ 1 ].Set( update->getEndPos()->x, update->getEndPos()->y, update->getEndPos()->z ); - } - - //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 ); - - for( Int i = data->m_numBeams - 1; i >= 0; i-- ) - { - - Real alpha, width; - int index = segment * data->m_numBeams + i; - - if( data->m_numBeams == 1 ) - { - width = data->m_innerBeamWidth * update->getWidthScale(); - alpha = innerAlpha; - } - else - { - //Calculate the scale between min and max values - //0 means use min value, 1 means use max value - //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(); - width = (data->m_innerBeamWidth + scale * (data->m_outerBeamWidth - data->m_innerBeamWidth)); - width *= ultimateScale; - alpha = innerAlpha + scale * (outerAlpha - innerAlpha); - } - - - //Calculate the number of times to tile the line based on the height of the texture used. - if( m_texture && data->m_tile ) - { - //Calculate the length of the line. - Vector3 lineVector; - Vector3::Subtract( laserPoints[1], laserPoints[0], &lineVector ); - Real length = lineVector.Length(); - - //Adjust tile factor so texture is NOT stretched but tiled equally in both width and length. - Real tileFactor = length/width*m_textureAspectRatio*data->m_tilingScalar; - - //Set the tile factor - m_line3D[ index ]->Set_Texture_Tile_Factor( tileFactor ); //number of times to tile texture across each segment - } - - m_line3D[ index ]->Set_Width( width ); - m_line3D[ index ]->Set_Points( 2, &laserPoints[0] ); - } - } - } - - return; -} - -// ------------------------------------------------------------------------------------------------ -/** CRC */ -// ------------------------------------------------------------------------------------------------ -void W3DLaserDraw::crc( Xfer *xfer ) -{ - - // extend base class - DrawModule::crc( xfer ); - -} - -// ------------------------------------------------------------------------------------------------ -/** Xfer method - * Version Info: - * 1: Initial version */ -// ------------------------------------------------------------------------------------------------ -void W3DLaserDraw::xfer( Xfer *xfer ) -{ - - // version - const XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // extend base class - DrawModule::xfer( xfer ); - - // Kris says there is no data to save for these, go ask him. - // m_selfDirty is not saved, is runtime only - -} - -// ------------------------------------------------------------------------------------------------ -/** Load post process */ -// ------------------------------------------------------------------------------------------------ -void W3DLaserDraw::loadPostProcess( void ) -{ - - // extend base class - DrawModule::loadPostProcess(); - - m_selfDirty = true; // so we update the first time after reload - -} diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp deleted file mode 100644 index 3b15a0667e..0000000000 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp +++ /dev/null @@ -1,3489 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public 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: W3DWater.cpp ///////////////////////////////////////////////////////////////////////////// -// Created: Mark Wilczynski, June 2001 -// Desc: Draw reflective water surface. Also handles drawing of waves/ripples -// on the surface. -/////////////////////////////////////////////////////////////////////////////////////////////////// - -#define SCROLL_UV - -// INCLUDES /////////////////////////////////////////////////////////////////////////////////////// -#include "W3DDevice/GameClient/W3DWater.h" -#include "W3DDevice/GameClient/HeightMap.h" -#include "W3DDevice/GameClient/W3DShroud.h" -#include "W3DDevice/GameClient/W3DWaterTracks.h" -#include "W3DDevice/GameClient/W3DAssetManager.h" -#include "texture.h" -#include "assetmgr.h" -#include "rinfo.h" -#include "camera.h" -#include "scene.h" -#include "dx8wrapper.h" -#include "light.h" -#include "d3dx8math.h" -#include "simplevec.h" -#include "mesh.h" -#include "matinfo.h" - -#include "Common/FramePacer.h" -#include "Common/GameState.h" -#include "Common/GlobalData.h" -#include "Common/PerfTimer.h" -#include "Common/Xfer.h" -#include "Common/GameLOD.h" - -#include "GameClient/Water.h" -#include "GameLogic/GameLogic.h" -#include "GameLogic/PolygonTrigger.h" -#include "GameLogic/ScriptEngine.h" -#include "W3DDevice/GameClient/W3DShaderManager.h" -#include "W3DDevice/GameClient/W3DDisplay.h" -#include "W3DDevice/GameClient/W3DPoly.h" -#include "W3DDevice/GameClient/W3DScene.h" -#include "W3DDevice/GameClient/W3DCustomScene.h" - - - -#define MIPMAP_BUMP_TEXTURE - -// DEFINES //////////////////////////////////////////////////////////////////////////////////////// -#define SKYPLANE_SIZE (384.0f*MAP_XY_FACTOR) -#define SKYPLANE_HEIGHT (30.0f) - -#define SKYBODY_TEXTURE "TSMoonLarg.tga" -#define SKYBODY_SIZE 45.0f //extent or radius of sky body - -#define SKYBODY_X 150.0f //location of skybody -#define SKYBODY_Y 550.0f //location of skybody - -/* in the bay -#define SKYBODY_X 120.0f //location of skybody -#define SKYBODY_Y 75.0f //location of skybody -*/ - -#define SKYBODY_HEIGHT SKYPLANE_HEIGHT //altitude of sky body (z-buffer disabled, so can equal sky height). - -//GeForce3 water system defines -#define PATCH_SIZE 15 //number of vertices on patch edge. Large patches may waste vertices off edge of screen. -#define PATCH_UV_TILES 42 //number of times the bump map texture is tiled across patch (must be integer!). -#define PATCH_SCALE (4.0f * MAP_XY_FACTOR) //horizontal scale factor. Adjust this and size to get desired vertex density. -#define SEA_REFLECTION_SIZE 256 //dimensions of reflection texture - -#define SEA_BUMP_SCALE (0.06f) //scales the du/dv offsets stored in bump map (~ amount to perturb) -#define BUMP_SIZE (50.f) -#define REFLECTION_FACTOR 0.1f - -#define PATCH_WIDTH (PATCH_SIZE-1) //internal defines -#define PATCH_UV_SCALE ((Real)PATCH_UV_TILES/(Real)PATCH_WIDTH) - -//3D Grid Mesh Water defines. -#define WATER_MESH_OPACITY 0.5f -#define WATER_MESH_X_VERTICES 128 -#define WATER_MESH_Y_VERTICES 128 -#define WATER_MESH_SPACING MAP_XY_FACTOR //same as terrain - -#ifdef USE_MESH_NORMALS -#define WATER_MESH_FVF DX8_FVF_XYZNDUV2 -typedef VertexFormatXYZNDUV2 MaterMeshVertexFormat; -#else -#define WATER_MESH_FVF DX8_FVF_XYZDUV2 -typedef VertexFormatXYZDUV2 MaterMeshVertexFormat; -#endif - -// Converts a FLOAT to a DWORD for use in SetRenderState() calls -static inline DWORD F2DW( FLOAT f ) { return *((DWORD*)&f); } - -#define DRAW_WATER_WAKES -/// @todo: Fix clipping of objects that intersect the mirror surface -//#define CLIP_GEOMETRY_TO_PLANE // this enables clipping of objects that intersect the mirror surfaces - -// Some shader combinations that can be useful in rendering water: - -// Modulate stage0 with stage1 texture. Also modulate stage 0 with vertex color. -#define SC_DETAIL_BLEND ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_ENABLE, ShaderClass::COLOR_WRITE_ENABLE,\ - ShaderClass::SRCBLEND_SRC_ALPHA,ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE, ShaderClass::SECONDARY_GRADIENT_DISABLE, \ - ShaderClass::TEXTURING_ENABLE, ShaderClass::ALPHATEST_DISABLE, ShaderClass::CULL_MODE_ENABLE, ShaderClass::DETAILCOLOR_DETAILBLEND, ShaderClass::DETAILALPHA_DISABLE) ) - -// Just a z-buffer fill, nothing is written to the color buffer. -#define SC_ZFILL_BLEND ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_ENABLE, ShaderClass::COLOR_WRITE_DISABLE, ShaderClass::SRCBLEND_ZERO, \ - ShaderClass::DSTBLEND_ONE, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE, ShaderClass::SECONDARY_GRADIENT_DISABLE, ShaderClass::TEXTURING_ENABLE, \ - ShaderClass::DETAILCOLOR_SCALE, ShaderClass::DETAILALPHA_DISABLE, ShaderClass::ALPHATEST_DISABLE, ShaderClass::CULL_MODE_ENABLE, \ - ShaderClass::DETAILCOLOR_SCALE, ShaderClass::DETAILALPHA_DISABLE) ) - -// No texturing, just vertex color with vertex alpha -#define SC_ZFILL_BLENDx ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_ENABLE, ShaderClass::COLOR_WRITE_ENABLE, \ - ShaderClass::SRCBLEND_ZERO, ShaderClass::DSTBLEND_SRC_COLOR, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE, ShaderClass::SECONDARY_GRADIENT_DISABLE, \ - ShaderClass::TEXTURING_DISABLE, ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE, ShaderClass::ALPHATEST_DISABLE, ShaderClass::CULL_MODE_ENABLE, \ - ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE) ) - -// Modulate blended with vertex alpha modulation -#define SC_ZFILL_MODULATE_TEX ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_ENABLE, ShaderClass::COLOR_WRITE_ENABLE,\ - ShaderClass::SRCBLEND_ZERO, ShaderClass::DSTBLEND_SRC_COLOR, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE, ShaderClass::SECONDARY_GRADIENT_DISABLE, \ - ShaderClass::TEXTURING_ENABLE, ShaderClass::ALPHATEST_DISABLE, ShaderClass::CULL_MODE_DISABLE, ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE) ) - -// Alpha blended with vertex alpha modulation -#define SC_ZFILL_ALPHA_TEX ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_ENABLE, ShaderClass::COLOR_WRITE_ENABLE,\ - ShaderClass::SRCBLEND_SRC_ALPHA, ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_DISABLE, ShaderClass::SECONDARY_GRADIENT_DISABLE, \ - ShaderClass::TEXTURING_ENABLE, ShaderClass::ALPHATEST_DISABLE, ShaderClass::CULL_MODE_DISABLE, ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE) ) - -// Alpha blended with vertex alpha modulation -#define SC_OPAQUE_TEXONLY ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_ENABLE, ShaderClass::COLOR_WRITE_ENABLE,\ - ShaderClass::SRCBLEND_ONE, ShaderClass::DSTBLEND_ZERO, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_DISABLE, ShaderClass::SECONDARY_GRADIENT_DISABLE, \ - ShaderClass::TEXTURING_ENABLE, ShaderClass::ALPHATEST_DISABLE, ShaderClass::CULL_MODE_DISABLE, ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE) ) - -// Alpha blended with vertex alpha modulation -#define SC_ZFILL_BLEND3 ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_ENABLE, ShaderClass::COLOR_WRITE_ENABLE,\ - ShaderClass::SRCBLEND_SRC_ALPHA, ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE, ShaderClass::SECONDARY_GRADIENT_DISABLE, \ - ShaderClass::TEXTURING_ENABLE, ShaderClass::ALPHATEST_DISABLE, ShaderClass::CULL_MODE_DISABLE, ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE) ) - -static ShaderClass zFillAlphaShader(SC_ZFILL_BLEND3); -static ShaderClass blendStagesShader(SC_DETAIL_BLEND); - -WaterRenderObjClass *TheWaterRenderObj=NULL; ///Release(); (p)=NULL; } } - -void doSkyBoxSet(Bool startDraw) -{ - if (TheWritableGlobalData) - TheWritableGlobalData->m_drawSkyBox = startDraw; -} - - -#define DONUT_SIDES 90 -#define INNER_RADIUS 200.0f -#define OUTER_RADIUS 250.0f -#define TEXTURE_REPEAT_COUNT 16 -#define DONUT_HEIGHT 15.0f -//#define DO_FLAT_DONUT -#define AMP_SCALE (30.0f/120.0f) -#define WAVE_FREQ 0.3f -#define AMP_SCALE2 (10.0f/120.0f) -#define NOISE_FREQ (2.0f*PI/WAVE_FREQ) - -#define NOISE_REPEAT_FACTOR ((float)(1.0f/(16.0f))) - - -static Bool wireframeForDebug = 0; - -void WaterRenderObjClass::setupJbaWaterShader(void) -{ - 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); - m_riverTexture->Get_Filter().Set_Mag_Filter(TextureFilterClass::FILTER_TYPE_BEST); - m_riverTexture->Get_Filter().Set_Min_Filter(TextureFilterClass::FILTER_TYPE_BEST); - m_riverTexture->Get_Filter().Set_Mip_Mapping(TextureFilterClass::FILTER_TYPE_BEST); - - -// Setting *setting=&m_settings[m_tod]; - - - DX8Wrapper::Apply_Render_State_Changes(); //force update of view and projection matrices - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAOP, D3DTOP_ADD ); - if (!m_riverAlphaEdge->Is_Initialized()) - m_riverAlphaEdge->Init(); - DX8Wrapper::_Get_D3D_Device8()->SetTexture(3,m_riverAlphaEdge->Peek_D3D_Texture()); - DX8Wrapper::Set_DX8_Texture_Stage_State(3, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); - DX8Wrapper::Set_DX8_Texture_Stage_State(3, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); - DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_TEXCOORDINDEX, 0); - DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_TEXCOORDINDEX, 0); - DX8Wrapper::Set_DX8_Texture_Stage_State(3, D3DTSS_TEXCOORDINDEX, 1); - - Bool doSparkles = true; - - if (m_riverWaterPixelShader && doSparkles) { - if (!m_waterSparklesTexture->Is_Initialized()) - m_waterSparklesTexture->Init(); - DX8Wrapper::_Get_D3D_Device8()->SetTexture(1,m_waterSparklesTexture->Peek_D3D_Texture()); - - if (!m_waterNoiseTexture->Is_Initialized()) - m_waterNoiseTexture->Init(); - DX8Wrapper::_Get_D3D_Device8()->SetTexture(2,m_waterNoiseTexture->Peek_D3D_Texture()); - - DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); - DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); - - DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION); - // Two output coordinates are used. - DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2); - DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); - DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); - D3DXMATRIX inv; - float det; - - Matrix4x4 curView; - DX8Wrapper::_Get_DX8_Transform(D3DTS_VIEW, curView); - D3DXMatrixInverse(&inv, &det, (D3DXMATRIX*)&curView); - D3DXMATRIX scale; - - D3DXMatrixScaling(&scale, NOISE_REPEAT_FACTOR, NOISE_REPEAT_FACTOR,1); - D3DXMATRIX destMatrix = inv * scale; - D3DXMatrixTranslation(&scale, m_riverVOrigin, m_riverVOrigin,0); - destMatrix = destMatrix*scale; - DX8Wrapper::_Set_DX8_Transform(D3DTS_TEXTURE2, *(Matrix4x4*)&destMatrix); - - } - m_pDev->SetTextureStageState( 0, D3DTSS_MINFILTER, D3DTEXF_LINEAR ); - m_pDev->SetTextureStageState( 0, D3DTSS_MAGFILTER, D3DTEXF_LINEAR ); - m_pDev->SetTextureStageState( 1, D3DTSS_MINFILTER, D3DTEXF_LINEAR ); - m_pDev->SetTextureStageState( 1, D3DTSS_MAGFILTER, D3DTEXF_LINEAR ); - m_pDev->SetTextureStageState( 2, D3DTSS_MINFILTER, D3DTEXF_LINEAR ); - m_pDev->SetTextureStageState( 2, D3DTSS_MAGFILTER, D3DTEXF_LINEAR ); - m_pDev->SetTextureStageState( 3, D3DTSS_MINFILTER, D3DTEXF_LINEAR ); - m_pDev->SetTextureStageState( 3, D3DTSS_MAGFILTER, D3DTEXF_LINEAR ); - if (m_riverWaterPixelShader){ - DX8Wrapper::_Get_D3D_Device8()->SetPixelShaderConstant(0, D3DXVECTOR4(REFLECTION_FACTOR, REFLECTION_FACTOR, REFLECTION_FACTOR, 1.0f), 1); - DX8Wrapper::_Get_D3D_Device8()->SetPixelShader(m_riverWaterPixelShader); - } -} - - - - -//------------------------------------------------------------------------------------------------- -/** Destructor. Releases w3d assets. */ -//------------------------------------------------------------------------------------------------- -WaterRenderObjClass::~WaterRenderObjClass(void) -{ - REF_PTR_RELEASE(m_meshVertexMaterialClass); - REF_PTR_RELEASE(m_vertexMaterialClass); - REF_PTR_RELEASE(m_meshLight); - REF_PTR_RELEASE(m_alphaClippingTexture); - REF_PTR_RELEASE (m_skyBox); - - REF_PTR_RELEASE (m_riverTexture); - REF_PTR_RELEASE (m_whiteTexture); - REF_PTR_RELEASE (m_waterNoiseTexture); - REF_PTR_RELEASE (m_riverAlphaEdge); - REF_PTR_RELEASE (m_waterSparklesTexture); - - Int i; - - for(i=0; iGet_Level_Description(d3dsd); - - if (Get_Bytes_Per_Pixel(d3dsd.Format) != 4) - { - // LORENZEN WAS BUGGED BY THIS, - // DEBUG_CRASH(("WaterRenderObjClass::Invalid BumpMap format - Was it compressed?") ); - 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++) - { - surf=pBumpSource->Get_Surface_Level(level); - surf->Get_Description(d3dsd); - pSrc=(unsigned char *)surf->Lock((int *)&dwSrcPitch); - - pTex[0]->LockRect( level, &d3dlr, 0, 0 ); - DWORD dwDstPitch = (DWORD)d3dlr.Pitch; - BYTE* pDst = (BYTE*)d3dlr.pBits; - - for( DWORD y=0; y1 ) ? 63 : 127; - - switch( D3DFMT_V8U8)//m_BumpMapFormat ) - { - case D3DFMT_V8U8: - *pDstT++ = (BYTE)iDu; - *pDstT++ = (BYTE)iDv; - break; - - case D3DFMT_L6V5U5: - *(WORD*)pDstT = (WORD)( ( (iDu>>3) & 0x1f ) << 0 ); - *(WORD*)pDstT |= (WORD)( ( (iDv>>3) & 0x1f ) << 5 ); - *(WORD*)pDstT |= (WORD)( ( ( uL>>2) & 0x3f ) << 10 ); - pDstT += 2; - break; - - case D3DFMT_X8L8V8U8: - *pDstT++ = (BYTE)iDu; - *pDstT++ = (BYTE)iDv; - *pDstT++ = (BYTE)uL; - *pDstT++ = (BYTE)0L; - break; - } - - // Move one pixel to the left (src is 32-bpp) - pSrcB0+=4; pSrcB1+=4; pSrcB2+=4; - } - - // Move to the next line - pSrc += dwSrcPitch; pDst += dwDstPitch; - } - - pTex[0]->UnlockRect(level); - surf->Unlock(); - REF_PTR_RELEASE (surf); - } - -#else - surf=pBumpSource->Get_Surface_Level(); - surf->Get_Description(d3dsd); - pSrc=(unsigned char *)surf->Lock((int *)&dwSrcPitch); - - // Create the bumpmap's surface and texture objects - m_pBumpTexture[i]=DX8Wrapper::_Create_DX8_Texture(d3dsd.Width,d3dsd.Height,WW3D_FORMAT_U8V8,TextureClass::MIP_LEVELS_1,D3DPOOL_MANAGED,false); - - // Fill the bits of the new texture surface with bits from - // a private format. - - m_pBumpTexture[i]->LockRect( 0, &d3dlr, 0, 0 ); - DWORD dwDstPitch = (DWORD)d3dlr.Pitch; - BYTE* pDst = (BYTE*)d3dlr.pBits; - - for( DWORD y=0; y1 ) ? 63 : 127; - - switch( D3DFMT_V8U8)//m_BumpMapFormat ) - { - case D3DFMT_V8U8: - *pDstT++ = (BYTE)iDu; - *pDstT++ = (BYTE)iDv; - break; - - case D3DFMT_L6V5U5: - *(WORD*)pDstT = (WORD)( ( (iDu>>3) & 0x1f ) << 0 ); - *(WORD*)pDstT |= (WORD)( ( (iDv>>3) & 0x1f ) << 5 ); - *(WORD*)pDstT |= (WORD)( ( ( uL>>2) & 0x3f ) << 10 ); - pDstT += 2; - break; - - case D3DFMT_X8L8V8U8: - *pDstT++ = (BYTE)iDu; - *pDstT++ = (BYTE)iDv; - *pDstT++ = (BYTE)uL; - *pDstT++ = (BYTE)0L; - break; - } - - // Move one pixel to the left (src is 32-bpp) - pSrcB0+=4; pSrcB1+=4; pSrcB2+=4; - } - - // Move to the next line - pSrc += dwSrcPitch; pDst += dwDstPitch; - } - - m_pBumpTexture[i]->UnlockRect(0); - surf->Unlock(); -#endif - - return S_OK; -} - -//------------------------------------------------------------------------------------------------- -/** Create and fill a D3D vertex buffer with water surface vertices */ -//------------------------------------------------------------------------------------------------- -HRESULT WaterRenderObjClass::generateVertexBuffer( Int sizeX, Int sizeY, Int vertexSize, Bool doStatic) -{ - m_numVertices=sizeX*sizeY; - //Assuming dynamic vertex buffer, allocate maximum multiple of required size to allow rendering from - //different parts of the buffer. 5-15-03: Disabled this since we use DISCARD mode instead to avoid Nvidia Runtime bug. -MW - //m_numVertices=(65536 / (sizeX*sizeY))*sizeX*sizeY; - - SEA_PATCH_VERTEX* pVertices; - - Setting *setting=&m_settings[m_tod]; - - HRESULT hr; - - //default setting for a dynamic vertex buffer - D3DPOOL pool = D3DPOOL_DEFAULT; - DWORD usage = D3DUSAGE_WRITEONLY | D3DUSAGE_DYNAMIC; - DWORD fvf = WATER_MESH_FVF; - - if (doStatic) - { //change settings for a static vertex buffer - pool = D3DPOOL_MANAGED; - usage = D3DUSAGE_WRITEONLY; - fvf=0;// DX8 Docs confusing on this. Say no FVF for vertex shaders. Else DX8_FVF_XYZDUV1; - m_numVertices=sizeX*sizeY; - } - - if (m_vertexBufferD3D == NULL) - { // Create vertex buffer - - if (FAILED(hr=m_pDev->CreateVertexBuffer - ( - m_numVertices*vertexSize, - usage, - fvf, - pool, - &m_vertexBufferD3D - ))) - return hr; - } - - m_vertexBufferD3DOffset=0; - - if (!doStatic) - return S_OK; //only create the buffer, other code will fill it. - - // load results into buffer - if (FAILED(hr=m_vertexBufferD3D->Lock - ( - 0, - m_numVertices*sizeof(SEA_PATCH_VERTEX), - (BYTE**)&pVertices, - 0//D3DLOCK_DISCARD - ))) - return hr; - - Int x,z; - for (z=0; zx=(float)x; - pVertices->y=m_level; - pVertices->z=(float)z; - - pVertices->tu=(float)x*PATCH_UV_SCALE; - pVertices->tv=(float)z*PATCH_UV_SCALE; - pVertices->c=setting->transparentWaterDiffuse; //vertex alpha/color - pVertices++; - } - } - - if (FAILED(hr=m_vertexBufferD3D->Unlock())) return hr; - - return S_OK; -} - -//------------------------------------------------------------------------------------------------- -/** Create and fill a D3D index buffer with water surface strip indices */ -//------------------------------------------------------------------------------------------------- -HRESULT WaterRenderObjClass::generateIndexBuffer(Int sizeX, Int sizeY) -{ - HRESULT hr; - - //Will need SizeY-1 strips, each of length SizeX*2 (2 indices per strip segment). - //Will also need 2 extra indices to connect each strip to next one (except last strip) - //Total index buffer size = (SizeY-1)*(SizeX*2+2) - 2 (drop the extra 2 indices from last strip) - - m_numIndices=(sizeY-1)*(sizeX*2+2) - 2; - - //old way - - // Create index buffer - WORD* pIndices; - - if (FAILED(hr=m_pDev->CreateIndexBuffer - ( - (m_numIndices+2)*sizeof(WORD), - D3DUSAGE_WRITEONLY, - D3DFMT_INDEX16, - D3DPOOL_MANAGED, - &m_indexBufferD3D - ))) - return hr; - - if (FAILED(hr=m_indexBufferD3D->Lock - ( - 0, - m_numIndices*sizeof(WORD), - (BYTE**)&pIndices, - 0 - ))) - return hr; - - Int i,j,k; - - for (i=0,j=0,k=0; i0; x-=step) - { - *pIndices++=(WORD)((z-step)*size+(x-step)); - *pIndices++=(WORD)((z-0)*size+(x-step)); - } - // insert additional degenerate to start next row - *pIndices++=pIndices[-1]; - *pIndices++=pIndices[-1]; - } - - s_toggle=!s_toggle; - } -*/ - if (FAILED(hr=m_indexBufferD3D->Unlock())) return hr; - - return S_OK; -} - -//------------------------------------------------------------------------------------------------- -/** Releases all w3d assets, to prepare for Reset device call. */ -//------------------------------------------------------------------------------------------------- -void WaterRenderObjClass::ReleaseResources(void) -{ - - REF_PTR_RELEASE(m_indexBuffer); - - REF_PTR_RELEASE(m_pReflectionTexture); - SAFE_RELEASE(m_vertexBufferD3D); - SAFE_RELEASE(m_indexBufferD3D); - - if (m_waterTrackSystem) - m_waterTrackSystem->ReleaseResources(); - - if (m_dwWavePixelShader) - m_pDev->DeletePixelShader(m_dwWavePixelShader); - - if (m_dwWaveVertexShader) - m_pDev->DeleteVertexShader(m_dwWaveVertexShader); - - if (m_waterPixelShader) - m_pDev->DeletePixelShader(m_waterPixelShader); - - if (m_trapezoidWaterPixelShader) - m_pDev->DeletePixelShader(m_trapezoidWaterPixelShader); - - if (m_riverWaterPixelShader) - m_pDev->DeletePixelShader(m_riverWaterPixelShader); - - m_dwWavePixelShader=0; - m_dwWaveVertexShader=0; - m_waterPixelShader = 0; - m_trapezoidWaterPixelShader=0; - m_riverWaterPixelShader=0; -} - -//------------------------------------------------------------------------------------------------- -/** (Re)allocates all W3D assets after a reset.. */ -//------------------------------------------------------------------------------------------------- -void WaterRenderObjClass::ReAcquireResources(void) -{ - HRESULT hr; - - m_indexBuffer=NEW_REF(DX8IndexBufferClass,(6)); - // Fill up the IB - { - DX8IndexBufferClass::WriteLockClass lockIdxBuffer(m_indexBuffer); - UnsignedShort *ib=lockIdxBuffer.Get_Index_Array(); - //quad of 2 triangles: - // 3-----2 - // | /| - // | / | - // |/ | - // 0-----1 - ib[0]=3; - ib[1]=0; - ib[2]=2; - ib[3]=2; - ib[4]=0; - ib[5]=1; - } - - m_pDev=DX8Wrapper::_Get_D3D_Device8(); - - //We're using the same grid for either 3D Water Mesh or Pixel/Vertex shader. Just - //allocate the right size depending on usage - if (m_meshData) - { - //Create new grid data - if (FAILED(generateIndexBuffer(m_gridCellsX+1,m_gridCellsY+1))) - return; - if (FAILED(generateVertexBuffer(m_gridCellsX+1,m_gridCellsY+1,sizeof(MaterMeshVertexFormat),false))) - return; - } - else - if (m_waterType == WATER_TYPE_2_PVSHADER) - { //pixel/vertex shader based water assets. - if (FAILED(hr=generateIndexBuffer(PATCH_SIZE,PATCH_SIZE))) - return; - - if (FAILED(hr=generateVertexBuffer(PATCH_SIZE,PATCH_SIZE,sizeof(SEA_PATCH_VERTEX),true))) - return; - - //shader decleration - DWORD Declaration[]= - { - (D3DVSD_STREAM(0)), - (D3DVSD_REG(0, D3DVSDT_FLOAT3)), // Position - (D3DVSD_REG(1, D3DVSDT_D3DCOLOR)), // Diffuse - (D3DVSD_REG(2, D3DVSDT_FLOAT2)), // Bump map texture - (D3DVSD_END()) - }; - - hr = W3DShaderManager::LoadAndCreateD3DShader("shaders\\wave.pso", &Declaration[0], 0, false, &m_dwWavePixelShader); - if (FAILED(hr)) - return; - - hr = W3DShaderManager::LoadAndCreateD3DShader("shaders\\wave.vso", &Declaration[0], 0, true, &m_dwWaveVertexShader); - if (FAILED(hr)) - return; - - // Create reflection texture - m_pReflectionTexture = DX8Wrapper::Create_Render_Target (SEA_REFLECTION_SIZE, SEA_REFLECTION_SIZE); - } - - if (m_waterTrackSystem) - m_waterTrackSystem->ReAcquireResources(); - - if (W3DShaderManager::getChipset() >= DC_GENERIC_PIXEL_SHADER_1_1) - { - ID3DXBuffer *compiledShader; - const char *shader = - "ps.1.1\n \ - tex t0 \n\ - tex t1 \n\ - tex t2 \n\ - tex t3\n\ - mul r0,v0,t0 ; blend vertex color into t0. \n\ - mul r1, t1, t2 ; mul\n\ - add r0.rgb, r0, t3\n\ - +mul r0.a, r0, t3\n\ - add r0.rgb, r0, r1\n"; - hr = D3DXAssembleShader( shader, strlen(shader), 0, NULL, &compiledShader, NULL); - if (hr==0) { - hr = DX8Wrapper::_Get_D3D_Device8()->CreatePixelShader((DWORD*)compiledShader->GetBufferPointer(), &m_riverWaterPixelShader); - compiledShader->Release(); - } - shader = - "ps.1.1\n \ - tex t0 \n\ - tex t1 \n\ - texbem t2, t1 ; use t1 as env map adjustment on t2.\n\ - mul r0,v0,t0 ; blend vertex color into t0. \n\ - mul r1.rgb,t2,c0 ; reduce t2 (environment mapped reflection) by constant\n\ - add r0.rgb, r0, r1"; - hr = D3DXAssembleShader( shader, strlen(shader), 0, NULL, &compiledShader, NULL); - if (hr==0) { - hr = DX8Wrapper::_Get_D3D_Device8()->CreatePixelShader((DWORD*)compiledShader->GetBufferPointer(), &m_waterPixelShader); - compiledShader->Release(); - } - shader = - "ps.1.1\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\ - mul r0.rgb, r0, t3 ; blend in black shroud \n\ - ;\n"; - hr = D3DXAssembleShader( shader, strlen(shader), 0, NULL, &compiledShader, NULL); - if (hr==0) { - hr = DX8Wrapper::_Get_D3D_Device8()->CreatePixelShader((DWORD*)compiledShader->GetBufferPointer(), &m_trapezoidWaterPixelShader); - compiledShader->Release(); - } - } - - //W3D Invalidate textures after losing the device and since we peek at the textures directly, it won't - //know to reinit them for us. Do it here manually: - if (m_riverTexture && !m_riverTexture->Is_Initialized()) - m_riverTexture->Init(); - if (m_waterNoiseTexture && !m_waterNoiseTexture->Is_Initialized()) - m_waterNoiseTexture->Init(); - if (m_riverAlphaEdge && !m_riverAlphaEdge->Is_Initialized()) - m_riverAlphaEdge->Init(); - if (m_waterSparklesTexture && !m_waterSparklesTexture->Is_Initialized()) - m_waterSparklesTexture->Init(); - if (m_whiteTexture && !m_whiteTexture->Is_Initialized()) - { m_whiteTexture->Init(); - SurfaceClass *surface=m_whiteTexture->Get_Surface_Level(); - surface->DrawPixel(0,0,0xffffffff); - REF_PTR_RELEASE(surface); - } -} - -void WaterRenderObjClass::load(void) -{ - if (m_waterTrackSystem) - m_waterTrackSystem->loadTracks(); -} - -//------------------------------------------------------------------------------------------------- -/** Initializes water with dimensions and parent scene. - * During rendering, we will render a water surface of given dimensions - * and reflect the parent scene in its surface. For now, waters are - * forced to be rectangles. */ -//------------------------------------------------------------------------------------------------- -Int WaterRenderObjClass::init(Real waterLevel, Real dx, Real dy, SceneClass *parentScene, WaterType type) -{ - - m_fBumpFrame=0; - m_fBumpScale=SEA_BUMP_SCALE; - - m_dx=dx; - m_dy=dy; - m_level=waterLevel; - - m_LastUpdateTime=timeGetTime(); - m_uScrollPerMs=0.001f; - m_vScrollPerMs=0.001f; - m_uOffset=0; - m_vOffset=0; - - m_parentScene=parentScene; - m_waterType = type; - - /// Hack for now - //m_waterType = WATER_TYPE_0_TRANSLUCENT; - - ///@todo: calculate a real normal/distance for arbitrary planes. - m_planeNormal=Vector3(0,0,1); //water plane normal - m_planeDistance=m_level; //water plane distance(always at zero for now) - - m_meshLight=NEW_REF(LightClass,(LightClass::DIRECTIONAL)); - m_meshLight->Set_Ambient(Vector3(0.1f,0.1f,0.1f)); - m_meshLight->Set_Diffuse(Vector3(1.0f,1.0f,1.0f)); - m_meshLight->Set_Specular(Vector3(1.0f,1.0f,1.0f)); - m_meshLight->Set_Position(Vector3(1000,1000,1000)); - //testLight->Set_Spot_Direction(Vector3(TheGlobalData->m_terrainLightX,TheGlobalData->m_terrainLightY,TheGlobalData->m_terrainLightZ)); - m_meshLight->Set_Spot_Direction(Vector3(-0.57f,-0.57f,-0.57f)); - - //Setup material for 3D Mesh water. - m_meshVertexMaterialClass=NEW_REF(VertexMaterialClass,()); - m_meshVertexMaterialClass->Set_Shininess(20.0); - m_meshVertexMaterialClass->Set_Ambient(1.0f,1.0f,1.0f); - m_meshVertexMaterialClass->Set_Diffuse(1.0f,1.0f,1.0f); - m_meshVertexMaterialClass->Set_Specular(0.5,0.5,0.5); - m_meshVertexMaterialClass->Set_Opacity(WATER_MESH_OPACITY); - m_meshVertexMaterialClass->Set_Lighting(true); - - // - // assign the data from the WaterSettings[] global to the data for this - // render object (we at present only have one water plane) - // - loadSetting( &m_settings[ TIME_OF_DAY_MORNING ], TIME_OF_DAY_MORNING ); - loadSetting( &m_settings[ TIME_OF_DAY_AFTERNOON ], TIME_OF_DAY_AFTERNOON ); - loadSetting( &m_settings[ TIME_OF_DAY_EVENING ], TIME_OF_DAY_EVENING ); - loadSetting( &m_settings[ TIME_OF_DAY_NIGHT ], TIME_OF_DAY_NIGHT ); - - Set_Sort_Level(2); //force water to be drawn after all other non translucent objects in scene. - Set_Force_Visible(TRUE); //water is always visible since it's a composite object made of multiple planes all over the map. - - ReAcquireResources(); -#if 0 //MD does not support the old bump-mapped water at all so no point loading textures. -MW 8-11-03 - if (type == WATER_TYPE_2_PVSHADER || (W3DShaderManager::getChipset() >= DC_GENERIC_PIXEL_SHADER_1_1)) - { //geforce3 specific water requires some extra D3D assets - m_pDev=DX8Wrapper::_Get_D3D_Device8(); - //save previous thumbnail mode - bool thumbnails_enabled = WW3D::Get_Thumbnail_Enabled(); - WW3D::Set_Thumbnail_Enabled(false); - - //load bump map textures off disk - TextureClass *pBumpSource; //temporary textures in a format W3D understands - TextureClass *pBumpSource2; //temporary textures in a format W3D understands - Int i; - i=NUM_BUMP_FRAMES; - while (i--) - { - char bump_name[128]; - - sprintf(bump_name,"caust%.2d.tga",i); - pBumpSource=WW3DAssetManager::Get_Instance()->Get_Texture(bump_name); - sprintf(bump_name,"caustS%.2d.tga",i); - pBumpSource2=WW3DAssetManager::Get_Instance()->Get_Texture(bump_name); - initBumpMap(m_pBumpTexture+i, pBumpSource); - initBumpMap(m_pBumpTexture2+i, pBumpSource2); - WW3DAssetManager::Get_Instance()->Release_Texture(pBumpSource); - WW3DAssetManager::Get_Instance()->Release_Texture(pBumpSource2); - REF_PTR_RELEASE(pBumpSource); - REF_PTR_RELEASE(pBumpSource2); - } - //restore previous thumpnail mode - WW3D::Set_Thumbnail_Enabled(thumbnails_enabled); - } -#endif - - //Setup material for regular water - m_vertexMaterialClass=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_DIFFUSE); - - - - m_shaderClass = zFillAlphaShader;//ShaderClass::_PresetAlphaShader;ShaderClass::_PresetOpaqueShader;//detailOpaqueShader; - m_shaderClass.Set_Cull_Mode(ShaderClass::CULL_MODE_DISABLE); //water should be visible from both sides - - //Assets used for all types of water - m_alphaClippingTexture=WW3DAssetManager::Get_Instance()->Get_Texture(SKYBODY_TEXTURE); - -#ifdef CLIP_GEOMETRY_TO_PLANE - m_alphaClippingTexture=WW3DAssetManager::Get_Instance()->Get_Texture("alphaclip.tga"); -#endif - - m_skyBox = ((W3DAssetManager*)W3DAssetManager::Get_Instance())->Create_Render_Obj( "new_skybox", TheGlobalData->m_skyBoxScale, 0); - - //Enable clamping on all textures used by the skybox (to reduce corner seams). - if (m_skyBox && m_skyBox->Class_ID() == RenderObjClass::CLASSID_MESH) - { - MeshClass *mesh=(MeshClass*) m_skyBox; - MaterialInfoClass *material = mesh->Get_Material_Info(); - - for (Int i=0; iTexture_Count(); i++) - { - if (material->Peek_Texture(i)) - { - material->Peek_Texture(i)->Get_Filter().Set_U_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); - 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(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(); - surface->DrawPixel(0,0,0xffffffff); - REF_PTR_RELEASE(surface); - - m_waterNoiseTexture=WW3DAssetManager::Get_Instance()->Get_Texture("Noise0000.tga"); - m_riverAlphaEdge=WW3DAssetManager::Get_Instance()->Get_Texture("TWAlphaEdge.tga"); - m_waterSparklesTexture=WW3DAssetManager::Get_Instance()->Get_Texture("WaterSurfaceBubbles.tga"); -#ifdef DRAW_WATER_WAKES - m_waterTrackSystem = NEW WaterTracksRenderSystem; - m_waterTrackSystem->init(); -#endif - - 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 ) -{ - - // for vertex animated water mesh reset the values - if( m_meshData) - { - Int i, j; - WaterMeshData *pData; - Int mx = m_gridCellsX + 1; - Int my = m_gridCellsY + 1; - - // go through each mesh point and adjust the height according to the velocity - for( j = 0, pData = m_meshData; j < (my + 2); j++ ) - { - - for( i = 0; i < (mx + 2); i++ ) - { - - // areset grid values for this cell - pData->velocity = 0.0f; - pData->height = 0.0f; - pData->preferredHeight = 0.0f; - pData->status = WaterRenderObjClass::AT_REST; - - // on to the next one - pData++; - - } - - } - - // mesh data is no longer in motion - m_meshInMotion = FALSE; - - } - - if (m_waterTrackSystem) - m_waterTrackSystem->reset(); -} - -void WaterRenderObjClass::enableWaterGrid(Bool state) -{ - m_doWaterGrid = state; - - m_drawingRiver = false; - m_disableRiver = false; - - if (state && m_meshData == NULL) - { //water type has changed, must allocate necessary assets for new water. - //contains the current deformed water surface z(height) values. With 1 vertex invisible border - //around surface to speed up normal calculations. - m_meshDataSize = (m_gridCellsX+1+2)*(m_gridCellsY+1+2); - m_meshData=NEW WaterMeshData[ m_meshDataSize ]; - memset(m_meshData,0,sizeof(WaterMeshData)*(m_gridCellsX+1+2)*(m_gridCellsY+1+2)); - reset(); - - //Release existing grid data - SAFE_RELEASE(m_vertexBufferD3D); - SAFE_RELEASE(m_indexBufferD3D); - - //Create new grid data - if (FAILED(generateIndexBuffer(m_gridCellsX+1,m_gridCellsY+1))) - return; - if (FAILED(generateVertexBuffer(m_gridCellsX+1,m_gridCellsY+1,sizeof(MaterMeshVertexFormat),false))) - return; - } -} - -// ------------------------------------------------------------------------------------------------ -/** Update phase for water if we need it. */ -// ------------------------------------------------------------------------------------------------ -void WaterRenderObjClass::update( void ) -{ - // TheSuperHackers @tweak The water movement time step is now decoupled from the render update. - const Real timeScale = TheFramePacer->getActualLogicTimeScaleOverFpsRatio(); - - { - constexpr const Real MagicOffset = 0.0125f * 33 / 5000; ///< the work of top Munkees; do not question it - - m_riverVOrigin += 0.002f * timeScale; - m_riverXOffset += (Real)(MagicOffset * timeScale); - m_riverYOffset += (Real)(2 * MagicOffset * timeScale); - - // This moves offsets towards zero when smaller -1.0 or larger 1.0 - m_riverXOffset -= (Int)m_riverXOffset; - m_riverYOffset -= (Int)m_riverYOffset; - - m_fBumpFrame += timeScale; - if (m_fBumpFrame >= NUM_BUMP_FRAMES) - m_fBumpFrame = 0.0f; - - // for vertex animated water we need to update the vector field - if( m_doWaterGrid && m_meshInMotion == TRUE ) - { - const Real PREFERRED_HEIGHT_FUDGE = 1.0f; ///< this is close enough to at rest - const Real AT_REST_VELOCITY_FUDGE = 1.0f; ///< when we're close enough to at rest height and velocity we will stop - const Real WATER_DAMPENING = 0.93f; ///< use with up force of 15.0 - Int i, j; - Int mx = m_gridCellsX+1; - Int my = m_gridCellsY+1; - WaterMeshData *pData; - - // - // we will mark the mesh as clean now ... if any of the fields are still in motion - // they will continue to mark the mesh as dirty so processing continues next frame - // - m_meshInMotion = FALSE; - - // go through each mesh point and adjust the height according to the velocity - for( j = 0, pData = m_meshData; j < (my + 2); j++ ) - { - - for( i = 0; i < (mx + 2); i++ ) - { - - // only pay attention to mesh points that are in motion - if( BitIsSet( pData->status, WaterRenderObjClass::IN_MOTION ) ) - { - - // DAMPENING to slow the changes down - pData->velocity *= WATER_DAMPENING; - - // if the height here is below our preferred height, we want to add upward force to counteract it - if( pData->height < pData->preferredHeight ) - pData->velocity -= TheGlobalData->m_gravity * 3.0f; - else - pData->velocity += TheGlobalData->m_gravity * 3.0f; - - // adjust the height at this grid location according to the current velocity - pData->height = pData->height + pData->velocity; - - // - // if we are close enough to our preferred height and our velocity is small enough - // this will be our resting location - // - if( fabs( pData->height - pData->preferredHeight ) < PREFERRED_HEIGHT_FUDGE && - fabs( pData->velocity ) < AT_REST_VELOCITY_FUDGE ) - { - - BitClear( pData->status, WaterRenderObjClass::IN_MOTION ); - pData->height = pData->preferredHeight; - pData->velocity = 0.0f; - - } - else - { - - // there is still motion in the mesh, we need to process next frame - m_meshInMotion = TRUE; - - } - - } - - // on to the next one - pData++; - - } - - } - - } - - } - -} - - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -void WaterRenderObjClass::replaceSkyboxTexture(const AsciiString& oldTexName, const AsciiString& newTextName) -{ - W3DAssetManager* assetManager = ((W3DAssetManager*)W3DAssetManager::Get_Instance()); - - assetManager->replacePrototypeTexture(m_skyBox, oldTexName.str(), newTextName.str()); - - //Enable clamping on all textures used by the skybox (to reduce corner seams). - if (m_skyBox && m_skyBox->Class_ID() == RenderObjClass::CLASSID_MESH) - { - MeshClass *mesh=(MeshClass*) m_skyBox; - MaterialInfoClass *material = mesh->Get_Material_Info(); - - for (Int i=0; iTexture_Count(); i++) - { - if (material->Peek_Texture(i)) - { - material->Peek_Texture(i)->Get_Filter().Set_U_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); - material->Peek_Texture(i)->Get_Filter().Set_V_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); - } - } - } - -} - -//------------------------------------------------------------------------------------------------- -/** Adjusts various water/sky rendering settings that depend on time of day. */ -//------------------------------------------------------------------------------------------------- -void WaterRenderObjClass::setTimeOfDay(TimeOfDay tod) -{ - m_tod=tod; - if (m_waterType == WATER_TYPE_2_PVSHADER) - generateVertexBuffer(PATCH_SIZE,PATCH_SIZE,sizeof(SEA_PATCH_VERTEX),true); //update the water mesh with new lighting/alpha -} - -//------------------------------------------------------------------------------------------------- -/**Copies GDF settings dealing with a particular time of day into our own - * structures. Also allocates any required W3D assets (textures). */ -//------------------------------------------------------------------------------------------------- -void WaterRenderObjClass::loadSetting( Setting *setting, TimeOfDay timeOfDay ) -{ - SurfaceClass::SurfaceDescription surfaceDesc; - - // sanity - DEBUG_ASSERTCRASH( setting, ("WaterRenderObjClass::loadSetting, NULL setting") ); - - // textures - setting->skyTexture = WW3DAssetManager::Get_Instance()->Get_Texture( WaterSettings[ timeOfDay ].m_skyTextureFile.str() ); - setting->waterTexture = WW3DAssetManager::Get_Instance()->Get_Texture( WaterSettings[ timeOfDay ].m_waterTextureFile.str() ); - - // texelss per unit - setting->skyTexelsPerUnit = WaterSettings[ timeOfDay ].m_skyTexelsPerUnit; - setting->waterTexture->Get_Level_Description( surfaceDesc, 0 ); - setting->skyTexelsPerUnit /= (Real)surfaceDesc.Width; - - // water repeat - setting->waterRepeatCount = WaterSettings[ timeOfDay ].m_waterRepeatCount; - - // U and V scroll per ms - setting->uScrollPerMs = WaterSettings[ timeOfDay ].m_uScrollPerMs; - setting->vScrollPerMs = WaterSettings[ timeOfDay ].m_vScrollPerMs; - - // - // vertex colors - // - // bottom left - setting->vertex00Diffuse = (WaterSettings[ timeOfDay ].m_vertex00Diffuse.red << 16) | - (WaterSettings[ timeOfDay ].m_vertex00Diffuse.green << 8) | - WaterSettings[ timeOfDay ].m_vertex00Diffuse.blue; - // top left - setting->vertex01Diffuse = (WaterSettings[ timeOfDay ].m_vertex01Diffuse.red << 16) | - (WaterSettings[ timeOfDay ].m_vertex01Diffuse.green << 8) | - WaterSettings[ timeOfDay ].m_vertex01Diffuse.blue; - // bottom right - setting->vertex10Diffuse = (WaterSettings[ timeOfDay ].m_vertex10Diffuse.red << 16) | - (WaterSettings[ timeOfDay ].m_vertex10Diffuse.green << 8) | - WaterSettings[ timeOfDay ].m_vertex10Diffuse.blue; - // top right - setting->vertex11Diffuse = (WaterSettings[ timeOfDay ].m_vertex11Diffuse.red << 16) | - (WaterSettings[ timeOfDay ].m_vertex11Diffuse.green << 8) | - WaterSettings[ timeOfDay ].m_vertex11Diffuse.blue; - - // diffuse water color - setting->waterDiffuse = (WaterSettings[ timeOfDay ].m_waterDiffuseColor.alpha << 24) | - (WaterSettings[ timeOfDay ].m_waterDiffuseColor.red << 16) | - (WaterSettings[ timeOfDay ].m_waterDiffuseColor.green << 8) | - WaterSettings[ timeOfDay ].m_waterDiffuseColor.blue; - - // transparent water color - setting->transparentWaterDiffuse = (WaterSettings[ timeOfDay ].m_transparentWaterDiffuse.alpha << 24) | - (WaterSettings[ timeOfDay ].m_transparentWaterDiffuse.red << 16) | - (WaterSettings[ timeOfDay ].m_transparentWaterDiffuse.green << 8) | - WaterSettings[ timeOfDay ].m_transparentWaterDiffuse.blue; - -} - -//------------------------------------------------------------------------------------------------- -/** Our water may use effects that require run-time rendered textures. These - * textures need to be updated before we start rendering to the main screen - * render target because D3D doesn't multiple render targets. */ -//------------------------------------------------------------------------------------------------- -void WaterRenderObjClass::updateRenderTargetTextures(CameraClass *cam) -{ - if (m_waterType == WATER_TYPE_2_PVSHADER && getClippedWaterPlane(cam, NULL) && - TheTerrainRenderObject && TheTerrainRenderObject->getMap()) - renderMirror(cam); //generate texture containing reflected scene -} - -//------------------------------------------------------------------------------------------------- -/** Renders the reflected scene into an offscreen texture. */ -//------------------------------------------------------------------------------------------------- -void WaterRenderObjClass::renderMirror(CameraClass *cam) -{ -#ifdef EXTENDED_STATS - if (DX8Wrapper::stats.m_disableWater) { - return; - } -#endif - Matrix3D OldCameraMatrix=cam->Get_Transform(); - Matrix4x4 FullMatrix4(cam->Get_Transform()); //copy 3x4 matrix into a 4x4 - Vector3 WaterNormal(0,0,1); //normal of plane used for reflection - Vector4 WaterPlane(WaterNormal.X,WaterNormal.Y,WaterNormal.Z,m_level); - Vector3 rRight,rUp,rN,rPos; //orientation and translation vectors of camera - - Matrix4x4 FullMatrix(FullMatrix4.Transpose()); //swap rows/columns - - //reflect camera right vector - Real axis_distance=Vector3::Dot_Product((Vector3&)FullMatrix[0],WaterNormal); - rRight = (Vector3&)FullMatrix[0] - (2.0f*axis_distance*WaterNormal); - - //reflect camera up vector - axis_distance=Vector3::Dot_Product((Vector3&)FullMatrix[1],WaterNormal); - rUp = (Vector3&)FullMatrix[1] - (2.0f*axis_distance*WaterNormal); - - //reflect camera n vector - axis_distance=Vector3::Dot_Product((Vector3&)FullMatrix[2],WaterNormal); - rN = (Vector3&)FullMatrix[2] - (2.0f*axis_distance*WaterNormal); - - //reflect camera position - axis_distance=Vector3::Dot_Product((Vector3&)FullMatrix[3],WaterNormal); //distance cam to origin - axis_distance -= WaterPlane.W; // subtract mirror plane distance to get distance camera to plane - rPos = (Vector3&)FullMatrix[3] - (2.0f*axis_distance*WaterNormal); - - //generate a new camera matrix from reflected vectors - Matrix3D reflectedTransform(rRight,rUp,rN,rPos); - - - DX8Wrapper::Set_Render_Target_With_Z((TextureClass*)m_pReflectionTexture); - - // Clear the backbuffer - WW3D::Begin_Render(false,true,Vector3(0.0f,0.0f,0.0f)); //clearing only z-buffer since background always filled with clouds - - cam->Set_Transform( reflectedTransform ); - - //Force reflected image to be drawn into full texture size - not a viewport inside texture. - Vector2 vMin,vMax,vOldMax,vOldMin; - cam->Get_Viewport(vOldMin,vOldMax); - vMax.X=vMax.Y=1.0f; - vMin.X=vMin.Y=0.0f; - cam->Set_Viewport(vMin,vMax); - - cam->Apply(); //force an update of all the camera dependent parameters like frustum clip planes - - //flip the winding order of polygons to draw the reflected back sides. - ShaderClass::Invert_Backface_Culling(true); - - // Render the scene - renderSky(); - if (m_tod == TIME_OF_DAY_NIGHT) - renderSkyBody(&reflectedTransform); - - WW3D::Render(m_parentScene,cam); - - cam->Set_Transform(OldCameraMatrix); //restore original non-reflected matrix - cam->Set_Viewport(vOldMin,vOldMax); - - cam->Apply(); //force an update of all the camera dependent parameters like frustum clip planes - - ShaderClass::Invert_Backface_Culling(false); - - WW3D::End_Render(false); - - // Change the rendertarget back to the main backbuffer - DX8Wrapper::Set_Render_Target((IDirect3DSurface8 *)NULL); -} - -//------------------------------------------------------------------------------------------------- -/** Renders (draws) the water. - * Algorithm: - * Draw reflected scene. - * Draw reflected sky layer(s) and bodies. - * Clear Zbuffer - * Fill Zbuffer by drawing water surface (allows proper sorting into regular scene). - * Draw non-reflected scene (done in regular app render loop). - * - * This algorithm doesn't apply to translucent water, which is rendered into a - * texture and rendered at end of scene. */ -//------------------------------------------------------------------------------------------------- -//DECLARE_PERF_TIMER(Water) -void WaterRenderObjClass::Render(RenderInfoClass & rinfo) -{ - //USE_PERF_TIMER(Water) - if (TheTerrainRenderObject && !TheTerrainRenderObject->getMap()) - return; //no map has been loaded yet. - - if (((RTS3DScene *)rinfo.Camera.Get_User_Data())->getCustomPassMode() == SCENE_PASS_ALPHA_MASK || - ((SceneClass *)rinfo.Camera.Get_User_Data())->Get_Extra_Pass_Polygon_Mode() == SceneClass::EXTRA_PASS_CLEAR_LINE) - return; //water is not drawn in wireframe or custom scene passes - -#ifdef EXTENDED_STATS - if (DX8Wrapper::stats.m_disableWater) { - return; - } -#endif - if (ShaderClass::Is_Backface_Culling_Inverted()) - return; //the water object will not reflect in itself, so don't do anything if rendering a mirror. - - //this water type needs to rendered after the rest of scene, so buffer it up for later - - // 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; - } - - switch(m_waterType) - { - case WATER_TYPE_0_TRANSLUCENT: - case WATER_TYPE_3_GRIDMESH: - //Draw the water surface as a bunch of alpha blended tiles covering areas where water is visible - renderWater(); - if (!m_drawingRiver || m_disableRiver) { - renderWaterMesh(); //Draw water surface as 3D deforming mesh if it's enabled on this map. - } - break; - - case WATER_TYPE_2_PVSHADER: - //Pixel/Vertex Shader based water which uses an off-screen rendered reflection texture - drawSea(rinfo); //draw water surface - break; - - case WATER_TYPE_1_FB_REFLECTION: - { - //Normal frame buffer reflection water type. Non translucent. Legacy code we're not using anymore. - Matrix3D OldCameraMatrix=rinfo.Camera.Get_Transform(); - Matrix4x4 FullMatrix4(rinfo.Camera.Get_Transform()); //copy 3x4 matrix into a 4x4 - Vector3 WaterNormal(0,0,1); //normal of plane used for reflection - Vector4 WaterPlane(WaterNormal.X,WaterNormal.Y,WaterNormal.Z,m_level); //assume distance to origin 0 - Vector3 rRight,rUp,rN,rPos; //orientation and translation vectors of camera - - Matrix4x4 FullMatrix(FullMatrix4.Transpose()); //swap rows/columns - - //reflect camera right vector - Real axis_distance=Vector3::Dot_Product((Vector3&)FullMatrix[0],WaterNormal); - rRight = (Vector3&)FullMatrix[0] - (2.0f*axis_distance*WaterNormal); - - //reflect camera up vector - axis_distance=Vector3::Dot_Product((Vector3&)FullMatrix[1],WaterNormal); - rUp = (Vector3&)FullMatrix[1] - (2.0f*axis_distance*WaterNormal); - - //reflect camera n vector - axis_distance=Vector3::Dot_Product((Vector3&)FullMatrix[2],WaterNormal); - rN = (Vector3&)FullMatrix[2] - (2.0f*axis_distance*WaterNormal); - - //reflect camera position - axis_distance=Vector3::Dot_Product((Vector3&)FullMatrix[3],WaterNormal); //distance cam to origin - axis_distance -= WaterPlane.W; // subtract mirror plane distance to get distance camera to plane - rPos = (Vector3&)FullMatrix[3] - (2.0f*axis_distance*WaterNormal); - - //generate a new camera matrix from reflected vectors - Matrix3D reflectedTransform(rRight,rUp,rN,rPos); - - //flip the winding order of polygons to draw the reflected back sides. - ShaderClass::Invert_Backface_Culling(true); - - #ifdef CLIP_GEOMETRY_TO_PLANE - // Set a clip plane, so that only objects above the water are reflected - WaterPlane.W *= -1.0f; //flip sign of plane distance for D3D use. - - // DX8Wrapper::Set_DX8_Clip_Plane( 0, &WaterPlane.X ); - // DX8Wrapper::Set_DX8_Render_State(D3DRS_CLIPPLANEENABLE, D3DCLIPPLANE0 ); //turn on first clip plane - - // Alternate Clipping Method using alpha testing hack! - /**************************************************************************************/ - - D3DXMATRIX inv; - D3DXMATRIX clipMatrix; - Real det; - Matrix4x4 curView; - - //get current view matrix - DX8Wrapper::_Get_DX8_Transform(D3DTS_VIEW, curView); - - //get inverse of view matrix(= view to world matrix) - D3DXMatrixInverse(&inv, &det, (D3DXMATRIX*)&curView); - - //create clipping matrix by inserting our plane equation into the 1st column - D3DXMatrixIdentity(&clipMatrix); - clipMatrix(0,0)=WaterNormal.X; - clipMatrix(1,0)=WaterNormal.Y; - clipMatrix(2,0)=WaterNormal.Z; - clipMatrix(3,0)=WaterPlane.W+0.5f; - inv *=clipMatrix; - - // Change texture wrapping mode to 'clamp' for texture stage 1 - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP); - - // Use CameraSpace vertices as input to matrix and use texture wrap mode from stage 1 - DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION|1); - // Two output coordinates are used. - DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2); - - // Set texture generation matrix for stage 1 - DX8Wrapper::_Set_DX8_Transform(D3DTS_TEXTURE1, *((Matrix4*)&inv)); - - // Disable bilinear filtering - DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_MINFILTER, D3DTEXF_POINT); - DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_MAGFILTER, D3DTEXF_POINT); - - // Pass stage 0 texture data untouched(by modulating with white) - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLORARG1, D3DTA_TEXTURE ); //stage 1 texture - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLORARG2, D3DTA_CURRENT ); //previous stage texture - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLOROP, D3DTOP_MODULATE ); //module with white => does nothing - - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAARG1, D3DTA_TEXTURE ); //stage 1 texture - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAARG2, D3DTA_CURRENT ); //previous stage texture - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAOP, D3DTOP_MODULATE ); //modulate with clipping texture - - DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHAREF,0x00); - DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHAFUNC,D3DCMP_NOTEQUAL); //pass pixels who's alpha is not zero - DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHATESTENABLE, true); //test pixels if transparent(clipped) before rendering. - - // Set clipping texture - m_alphaClippingTexture->Set_U_Addr_Mode(TextureClass::TEXTURE_ADDRESS_CLAMP); - m_alphaClippingTexture->Set_V_Addr_Mode(TextureClass::TEXTURE_ADDRESS_CLAMP); - m_alphaClippingTexture->Set_Min_Filter(TextureClass::FILTER_TYPE_NONE); - m_alphaClippingTexture->Set_Mag_Filter(TextureClass::FILTER_TYPE_NONE); - m_alphaClippingTexture->Set_Mip_Mapping(TextureClass::FILTER_TYPE_NONE); - - DX8Wrapper::Set_Texture(0,m_alphaClippingTexture); - - //TODO: Will have to make sure that the shader system is not resetting my stage 1 setup - //while rendering the scene - - /*************************************************************************************/ - #endif - - #if 0 // No longer do simple rendering. - if (TheGlobalData->m_useWaterPlane) - { - //@todo : Would it be better to create a new camera or change the transform of the - //existing one? - rinfo.Camera.Set_Transform( reflectedTransform ); - rinfo.Camera.Apply(); //force an update of all the camera dependent parameters like frustum clip planes - - if(m_useCloudLayer) - { - if (TheGlobalData && TheGlobalData->m_drawEntireTerrain) - m_skyBox->Render(rinfo); - else - { - renderSky(); - if (m_tod == TIME_OF_DAY_NIGHT) - renderSkyBody(&reflectedTransform); - } - } - - WW3D::Render(m_parentScene,&rinfo.Camera); - - rinfo.Camera.Set_Transform(OldCameraMatrix); //restore original non-reflected matrix - rinfo.Camera.Apply(); //force an update of all the camera dependent parameters like frustum clip planes - - //clear the z-buffer to remove changes made by objects inside mirror - DX8Wrapper::Clear(false,true,Vector3(0.1f,0.1f,0.1f)); - } - #endif - - #ifdef CLIP_GEOMETRY_TO_PLANE - //restore default culling mode - // DX8Wrapper::Set_DX8_Render_State(D3DRS_CLIPPLANEENABLE, 0 ); //turn off first clip plane - - //disable texture coordinate generation - DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE); - DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHATESTENABLE, false); //disable alpha testing - #endif - - ShaderClass::Invert_Backface_Culling(false); //return culling back to normal - - ShaderClass::Invalidate(); //reset shading system so it forces full state set. - - renderWater(); - } - break; - - default: - break; - } - - if (TheGlobalData && TheGlobalData->m_drawSkyBox) - { //center skybox around camera - Vector3 pos=rinfo.Camera.Get_Position(); - pos.Z = TheGlobalData->m_skyBoxPositionZ; - m_skyBox->Set_Position(pos); - m_skyBox->Render(rinfo); - } - - //Clean up after any pixel shaders. - //Force render state apply so that the "NULL" texture gets applied to D3D, thus releasing shroud reference count. - DX8Wrapper::Apply_Render_State_Changes(); - DX8Wrapper::Invalidate_Cached_Render_States(); - - if (m_waterTrackSystem) - m_waterTrackSystem->flush(rinfo); - -// renderWaterMesh(); -// renderWaterWave(); -} - -//------------------------------------------------------------------------------------------------- -/** Clips the water plane to the current camera frustum and returns a bounding - * box enclosing the clipped plane. Returns false if water plane is not visible. */ -//------------------------------------------------------------------------------------------------- -Bool WaterRenderObjClass::getClippedWaterPlane(CameraClass *cam, AABoxClass *box) -{ - const FrustumClass & frustum = cam->Get_Frustum(); - - ClipPolyClass ClippedPoly0; - ClipPolyClass ClippedPoly1; - - ///@todo: generate proper sized polygon - ClippedPoly0.Reset(); - ClippedPoly0.Add_Vertex(Vector3(0,0,m_level)); - ClippedPoly0.Add_Vertex(Vector3(0,m_dy,m_level)); - ClippedPoly0.Add_Vertex(Vector3(m_dx,m_dy,m_level)); - ClippedPoly0.Add_Vertex(Vector3(m_dx,0,m_level)); - - //clip against all 6 frustum planes - ClippedPoly0.Clip(frustum.Planes[0],ClippedPoly1); - ClippedPoly1.Clip(frustum.Planes[1],ClippedPoly0); - ClippedPoly0.Clip(frustum.Planes[2],ClippedPoly1); - ClippedPoly1.Clip(frustum.Planes[3],ClippedPoly0); - ClippedPoly0.Clip(frustum.Planes[4],ClippedPoly1); - ClippedPoly1.Clip(frustum.Planes[5],ClippedPoly0); - - Int final_vcount = ClippedPoly0.Verts.Count(); - - //make sure the polygon is visible - if (final_vcount >= 3) - { - //find axis aligned bounding box around visible polygon - if (box) - box->Init(&(ClippedPoly0.Verts[0]),final_vcount); - return TRUE; - } - - return FALSE; //water plane is not visible -} - -//------------------------------------------------------------------------------------------------- -/** Draws the water surface using a custom D3D vertex/pixel shader and a - * reflection texture. Only tested to work on GeForce3. */ -//------------------------------------------------------------------------------------------------- -void WaterRenderObjClass::drawSea(RenderInfoClass & rinfo) -{ - AABoxClass seaBox; - - if (!getClippedWaterPlane(&rinfo.Camera,&seaBox)) - return; //the sea is not visible - - D3DXMATRIX matProj, matView, matWW3D; - - //create a transform which will flip the y and z coordinates to fit our system - memset(&matWW3D,0,sizeof(D3DMATRIX)); - matWW3D._11=1.0f; - matWW3D._32=1.0f; - matWW3D._23=1.0f; - matWW3D._44=1.0f; - - Matrix3D tm(Transform); - - DX8Wrapper::Set_Transform(D3DTS_WORLD,tm); //position the water surface - DX8Wrapper::Set_Texture(0,NULL); //we'll be setting our own textures, so reset W3D - DX8Wrapper::Set_Texture(1,NULL); //we'll be setting our own textures, so reset W3D - - - DX8Wrapper::Apply_Render_State_Changes(); //force update of view and projection matrices - - Vector3 camTran; - - rinfo.Camera.Get_Transform().Get_Translation(&camTran); - - DX8Wrapper::_Get_DX8_Transform(D3DTS_VIEW, *(Matrix4x4*)&matView); - DX8Wrapper::_Get_DX8_Transform(D3DTS_PROJECTION, *(Matrix4x4*)&matProj); - - //default setup from Kenny's demo - m_pDev->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE ); - m_pDev->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); - m_pDev->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE); - m_pDev->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); - m_pDev->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, 0 ); - - m_pDev->SetTextureStageState( 1, D3DTSS_COLORARG1, D3DTA_TEXTURE ); - m_pDev->SetTextureStageState( 1, D3DTSS_COLORARG2, D3DTA_CURRENT ); - m_pDev->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_MODULATE); - m_pDev->SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); - m_pDev->SetTextureStageState( 1, D3DTSS_TEXCOORDINDEX, 1 ); - - m_pDev->SetTextureStageState( 2, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE); - m_pDev->SetTextureStageState( 2, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU|2); - - m_pDev->SetTextureStageState( 3, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE); - m_pDev->SetTextureStageState( 3, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU|3); - -// m_pDev->SetTextureStageState( 0, D3DTSS_MINFILTER, D3DTEXF_LINEAR ); -// m_pDev->SetTextureStageState( 0, D3DTSS_MAGFILTER, D3DTEXF_LINEAR ); -// m_pDev->SetTextureStageState( 0, D3DTSS_MIPFILTER, D3DTEXF_POINT ); - -// m_pDev->SetTextureStageState( 1, D3DTSS_MINFILTER, D3DTEXF_POINT ); -// m_pDev->SetTextureStageState( 1, D3DTSS_MAGFILTER, D3DTEXF_POINT ); -// m_pDev->SetTextureStageState( 1, D3DTSS_MIPFILTER, D3DTEXF_NONE ); - //end of default setup - - m_pDev->SetTextureStageState(0, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); - m_pDev->SetTextureStageState(0, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); - m_pDev->SetRenderState( D3DRS_WRAP0, D3DWRAP_U | D3DWRAP_V); - - m_pDev->SetTextureStageState(1, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP); - m_pDev->SetTextureStageState(1, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP); - - m_pDev->SetTexture( 0, m_pBumpTexture[(Int)m_fBumpFrame]); -#ifdef MIPMAP_BUMP_TEXTURE - m_pDev->SetTextureStageState( 0, D3DTSS_MIPFILTER, D3DTEXF_POINT ); - m_pDev->SetTextureStageState( 0, D3DTSS_MINFILTER, D3DTEXF_LINEAR ); - m_pDev->SetTextureStageState( 0, D3DTSS_MAGFILTER, D3DTEXF_LINEAR ); -#endif - m_pDev->SetTextureStageState( 1, D3DTSS_BUMPENVMAT00, F2DW(m_fBumpScale) ); - m_pDev->SetTextureStageState( 1, D3DTSS_BUMPENVMAT01, F2DW(0.0f) ); - m_pDev->SetTextureStageState( 1, D3DTSS_BUMPENVMAT10, F2DW(0.0f) ); - m_pDev->SetTextureStageState( 1, D3DTSS_BUMPENVMAT11, F2DW(m_fBumpScale) ); - m_pDev->SetTextureStageState( 1, D3DTSS_BUMPENVLSCALE, F2DW(1.0f) ); - m_pDev->SetTextureStageState( 1, D3DTSS_BUMPENVLOFFSET, F2DW(0.0f) ); - - m_pDev->SetTextureStageState( 2, D3DTSS_COLOROP, D3DTOP_DISABLE ); - m_pDev->SetTextureStageState( 2, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); - - m_pDev->SetRenderState(D3DRS_ZWRITEENABLE , FALSE); - - D3DXMATRIX mat; - memset(&mat,0,sizeof(D3DXMATRIX)); - - mat._11 = 0.5f; mat._12 = -0.5f; mat._13 = 0.5f; mat._14=0.5f; - mat._21 = 0.5f; mat._22 = 0.5f; mat._23 = 0.0f; mat._24=0.0f; - mat._31 = 0.0f; mat._32 = 0.0f; mat._33 = 0.0f; mat._34=1.0f; - mat._41 = 0.0f; mat._42 = 0.0f; mat._43 = 0.0f; mat._44=1.0f; - - m_pDev->SetVertexShaderConstant(CV_TEXPROJ_0, &mat, 4); - - // Setup constants - m_pDev->SetVertexShaderConstant(CV_ZERO, D3DXVECTOR4(0.0f, 0.0f, 0.0f, 0.0f), 1); - m_pDev->SetVertexShaderConstant(CV_ONE, D3DXVECTOR4(1.0f, 1.0f, 1.0f, 1.0f), 1); - - m_pDev->SetVertexShader(m_dwWaveVertexShader); - m_pDev->SetPixelShader(m_dwWavePixelShader); - -// Make reflection brighter to compensate for darker coloring on sea floor -// m_pDev->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_ONE ); -// m_pDev->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_SRCCOLOR ); - - m_pDev->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA ); - m_pDev->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA ); - - m_pDev->SetRenderState(D3DRS_ALPHABLENDENABLE , TRUE); - m_pDev->SetTexture( 1, m_pReflectionTexture->Peek_D3D_Texture()); - -// m_pDev->SetRenderState(D3DRS_FILLMODE,D3DFILL_WIREFRAME);//LORENZEN - - Int patchX,patchY,startX,startY; - - D3DXMATRIX patchMatrix; - memset(&patchMatrix,0,sizeof(D3DXMATRIX)); - patchMatrix._11=PATCH_SCALE; - patchMatrix._22=1.0f; - patchMatrix._33=PATCH_SCALE; - patchMatrix._44=1.0f; - - m_pDev->SetStreamSource(0,m_vertexBufferD3D,sizeof(WaterRenderObjClass::SEA_PATCH_VERTEX)); - m_pDev->SetIndices(m_indexBufferD3D,0); - - for (startY=patchY=(seaBox.Center.Y-seaBox.Extent.Y)/(PATCH_WIDTH*PATCH_SCALE); (patchY*PATCH_WIDTH*PATCH_SCALE)<(seaBox.Center.Y+seaBox.Extent.Y); patchY++) - { - for (startX=patchX=(seaBox.Center.X-seaBox.Extent.X)/(PATCH_WIDTH*PATCH_SCALE); (patchX*PATCH_WIDTH*PATCH_SCALE)<(seaBox.Center.X+seaBox.Extent.X); patchX++) - { - D3DXMATRIX matWorldViewProj, matTemp, matTempWorld; - patchMatrix._41=(float)(patchX*PATCH_WIDTH*PATCH_SCALE ); - patchMatrix._43=(float)(patchY*PATCH_WIDTH*PATCH_SCALE ); - //convert the default D3D coordinate system into ours - D3DXMatrixMultiply(&matTempWorld, &patchMatrix, &matWW3D); - - D3DXMatrixMultiply(&matTemp, &matTempWorld, &matView); - D3DXMatrixMultiply(&matWorldViewProj, &matTemp, &matProj); - //matrices must be transposed before loading into vertex shader registers - D3DXMatrixTranspose(&matWorldViewProj, &matWorldViewProj); - m_pDev->SetVertexShaderConstant(CV_WORLDVIEWPROJ_0, &matWorldViewProj, 4); //pass transform matrix into shader - - m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP,0,m_numVertices,0,m_numIndices); - } - } -// m_pDev->SetRenderState(D3DRS_FILLMODE,D3DFILL_SOLID); - m_pDev->SetRenderState(D3DRS_ALPHABLENDENABLE , FALSE); - m_pDev->SetTexture( 0, NULL); //release reference to bump texture - m_pDev->SetTexture( 1, NULL); //release reference to reflection texture - m_pDev->SetTexture( 2, NULL); //release reference to reflection texture - - m_pDev->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE); - m_pDev->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU|0); - m_pDev->SetTextureStageState( 1, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE); - m_pDev->SetTextureStageState( 1, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU|1); - m_pDev->SetRenderState(D3DRS_ZWRITEENABLE , TRUE); - - m_pDev->SetTextureStageState(1, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); - m_pDev->SetTextureStageState(1, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); - - m_pDev->SetRenderState( D3DRS_WRAP0, 0); //turn off texture wrapping - - m_pDev->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_DISABLE ); - m_pDev->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); - m_pDev->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_DISABLE ); - m_pDev->SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); - m_pDev->SetTextureStageState( 2, D3DTSS_COLOROP, D3DTOP_DISABLE ); - m_pDev->SetTextureStageState( 2, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); - - //Restore old transforms - DX8Wrapper::_Set_DX8_Transform(D3DTS_VIEW, *(Matrix4x4*)&matView); - DX8Wrapper::_Set_DX8_Transform(D3DTS_PROJECTION, *(Matrix4x4*)&matProj); - - m_pDev->SetPixelShader(0); //turn off pixel shader - m_pDev->SetVertexShader(DX8_FVF_XYZDUV1); //turn off custom vertex shader - - DX8Wrapper::Invalidate_Cached_Render_States(); - - if (TheTerrainRenderObject->getShroud()) - { - //do second pass to apply the shroud on water plane - W3DShaderManager::setTexture(0,TheTerrainRenderObject->getShroud()->getShroudTexture()); - W3DShaderManager::setShader(W3DShaderManager::ST_SHROUD_TEXTURE, 0); - m_pDev->SetStreamSource(0,m_vertexBufferD3D,sizeof(WaterRenderObjClass::SEA_PATCH_VERTEX)); - m_pDev->SetIndices(m_indexBufferD3D,0); - for (startY=patchY=(seaBox.Center.Y-seaBox.Extent.Y)/(PATCH_WIDTH*PATCH_SCALE); (patchY*PATCH_WIDTH*PATCH_SCALE)<(seaBox.Center.Y+seaBox.Extent.Y); patchY++) - { - for (startX=patchX=(seaBox.Center.X-seaBox.Extent.X)/(PATCH_WIDTH*PATCH_SCALE); (patchX*PATCH_WIDTH*PATCH_SCALE)<(seaBox.Center.X+seaBox.Extent.X); patchX++) - { - D3DXMATRIX matTemp; - patchMatrix._41=(float)(patchX*PATCH_WIDTH*PATCH_SCALE); - patchMatrix._43=(float)(patchY*PATCH_WIDTH*PATCH_SCALE); - - D3DXMatrixMultiply(&matTemp, &patchMatrix, &matWW3D); - - DX8Wrapper::_Set_DX8_Transform(D3DTS_WORLD, *(Matrix4x4*)&matTemp); - - m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP,0,m_numVertices,0,m_numIndices); - } - } - W3DShaderManager::resetShader(W3DShaderManager::ST_SHROUD_TEXTURE); - } - -} - - -#define FEATHER_LAYER_COUNT (5.0f) -#define FEATHER_THICKNESS (4.0f) - -//------------------------------------------------------------------------------------------------- -/** Renders (draws) the water surface.*/ -//------------------------------------------------------------------------------------------------- -void WaterRenderObjClass::renderWater(void) -{ - for (PolygonTrigger *pTrig=PolygonTrigger::getFirstPolygonTrigger(); pTrig; pTrig = pTrig->getNext()) { - if (pTrig->isWaterArea()) { - if (pTrig->getNumPoints()>2) { - if (pTrig->isRiver()) { - drawRiverWater(pTrig); - continue; - } - Int k; - for (k=1; kgetNumPoints()-1; k=k+2) { - ICoord3D pt3 = *pTrig->getPoint(0); - ICoord3D pt2 = *pTrig->getPoint(k); - ICoord3D pt1 = *pTrig->getPoint(k+1); - ICoord3D pt0 = *pTrig->getPoint(k+1); - if (k+2getNumPoints()) { - pt0 = *pTrig->getPoint(k+2); - } - Vector3 points[4]; - points[0].Set(pt0.x, pt0.y, pt0.z); - points[1].Set(pt1.x, pt1.y, pt1.z); - points[2].Set(pt2.x, pt2.y, pt2.z); - points[3].Set(pt3.x, pt3.y, pt3.z); - - if ( TheGlobalData->m_featherWater ) - { - for (int r = 0; r < TheGlobalData->m_featherWater; ++r) - { - drawTrapezoidWater(points); - points[0].Z += (FEATHER_THICKNESS/TheGlobalData->m_featherWater); - } - } - - else - drawTrapezoidWater(points); - - - } - } - } - } - -} - -//------------------------------------------------------------------------------------------------- -/** Renders (draws) the sky plane. Will apply current time-of-day settings including - * some simple UV scrolling animation. */ -//------------------------------------------------------------------------------------------------- -void WaterRenderObjClass::renderSky(void) -{ - Int timeNow,timeDiff; - Real fu,fv; - - Setting *setting=&m_settings[m_tod]; - - timeNow=timeGetTime(); - - timeDiff=timeNow-m_LastUpdateTime; - m_LastUpdateTime=timeNow; - - m_uOffset += timeDiff * setting->uScrollPerMs * setting->skyTexelsPerUnit; - m_vOffset += timeDiff * setting->vScrollPerMs * setting->skyTexelsPerUnit; - - //clamp uv coordinate into 0,1 range - m_uOffset = m_uOffset - (Real)((Int) m_uOffset); - m_vOffset = m_vOffset - (Real)((Int) m_vOffset); - - fu= m_uOffset + (SKYPLANE_SIZE * 2) * setting->skyTexelsPerUnit; - fv= m_vOffset + (SKYPLANE_SIZE * 2) * setting->skyTexelsPerUnit; - - - VertexMaterialClass *vmat=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_DIFFUSE); - DX8Wrapper::Set_Material(vmat); - REF_PTR_RELEASE(vmat); - - ShaderClass m_shader2=ShaderClass::_PresetOpaqueShader; - m_shader2.Set_Cull_Mode(ShaderClass::CULL_MODE_DISABLE); - m_shader2.Set_Depth_Compare(ShaderClass::PASS_ALWAYS); //no need to check against z-buffer, sky always rendered first. - m_shader2.Set_Depth_Mask(ShaderClass::DEPTH_WRITE_DISABLE); //sky is always behind everything so no need to update z-buffer - - DX8Wrapper::Set_Shader(m_shader2); - - DX8Wrapper::Set_Texture(0,setting->skyTexture); - - //draw an infinite sky plane - DynamicVBAccessClass vb_access(BUFFER_TYPE_DYNAMIC_DX8,dynamic_fvf_type,4); - { - DynamicVBAccessClass::WriteLockClass lock(&vb_access); - VertexFormatXYZNDUV2* verts=lock.Get_Formatted_Vertex_Array(); - if(verts) - { - verts[0].x=-SKYPLANE_SIZE; - verts[0].y=SKYPLANE_SIZE; - verts[0].z=SKYPLANE_HEIGHT; - verts[0].u1=m_uOffset; - verts[0].v1=fv; - verts[0].diffuse=setting->vertex01Diffuse; - - verts[1].x=SKYPLANE_SIZE; - verts[1].y=SKYPLANE_SIZE; - verts[1].z=SKYPLANE_HEIGHT; - verts[1].u1=fu; - verts[1].v1=fv; - verts[1].diffuse=setting->vertex11Diffuse; - - verts[2].x=SKYPLANE_SIZE; - verts[2].y=-SKYPLANE_SIZE; - verts[2].z=SKYPLANE_HEIGHT; - verts[2].u1=fu; - verts[2].v1=m_vOffset; - verts[2].diffuse=setting->vertex10Diffuse; - - verts[3].x=-SKYPLANE_SIZE; - verts[3].y=-SKYPLANE_SIZE; - verts[3].z=SKYPLANE_HEIGHT; - verts[3].u1=m_uOffset; - verts[3].v1=m_vOffset; - verts[3].diffuse=setting->vertex00Diffuse; - } - } - - DX8Wrapper::Set_Index_Buffer(m_indexBuffer,0); - DX8Wrapper::Set_Vertex_Buffer(vb_access); - - Matrix3D tm(1); - tm.Set_Translation(Vector3(0,0,0)); - DX8Wrapper::Set_Transform(D3DTS_WORLD,tm); - - DX8Wrapper::Draw_Triangles( 0,2, 0, 4); //draw a quad, 2 triangles, 4 verts -} - -//------------------------------------------------------------------------------------------------- -/** Renders (draws) the sky body. Used for moon and sun. We rotate the image - * so that it always faces the camera. This removes perspective and helps hide that - * it's a flat image. */ -//------------------------------------------------------------------------------------------------- -/// @todo: Add code to render properly sorted sun sky body. -void WaterRenderObjClass::renderSkyBody(Matrix3D *mat) -{ - Vector3 cPos; - - Vector3 pView,pRight,pUp,pPos(SKYBODY_X,SKYBODY_Y,SKYBODY_HEIGHT); - - mat->Get_Translation(&cPos); - - pView=cPos-pPos; //billboard to camera - pView.Normalize(); //particle view direction - - Vector3 WorldUp(0,0,-1); ///@todo: hacked so only works for reflections across xy plane - -#ifdef ALLOW_TEMPORARIES - Vector3 rotAxis=Vector3::Cross_Product(WorldUp,pView); //get axis of rotation. - rotAxis.Normalize(); -#else - Vector3 rotAxis; - Vector3::Normalized_Cross_Product(WorldUp, pView, &rotAxis); -#endif - - Real angle=Vector3::Dot_Product(WorldUp,pView); - - angle = acos(angle); - - - Matrix3D tm(1); - tm.Set(rotAxis,angle); - tm.Adjust_Translation(Vector3(SKYBODY_X,SKYBODY_Y,SKYBODY_HEIGHT)); - - - DX8Wrapper::Set_Transform(D3DTS_WORLD,tm); - - - VertexMaterialClass *vmat=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_DIFFUSE); - DX8Wrapper::Set_Material(vmat); - REF_PTR_RELEASE(vmat); - - ShaderClass m_shader2=ShaderClass::_PresetAlphaShader; - m_shader2.Set_Cull_Mode(ShaderClass::CULL_MODE_DISABLE); - m_shader2.Set_Depth_Compare(ShaderClass::PASS_ALWAYS); //no need to check against z-buffer, sky always rendered first. - m_shader2.Set_Depth_Mask(ShaderClass::DEPTH_WRITE_DISABLE); //sky is always behind everything so no need to update z-buffer - - DX8Wrapper::Set_Shader(m_shader2); - - -// DX8Wrapper::Set_Shader(ShaderClass::/*_PresetAdditiveShader*//*_PresetOpaqueShader*/_PresetAlphaShader); -// DX8Wrapper::Set_Texture(0,setting->skyBodyTexture); - - DX8Wrapper::Set_Texture(0,m_alphaClippingTexture); - - //draw an infinite sky plane - DynamicVBAccessClass vb_access(BUFFER_TYPE_DYNAMIC_DX8,dynamic_fvf_type,4); - { - DynamicVBAccessClass::WriteLockClass lock(&vb_access); - VertexFormatXYZNDUV2* verts=lock.Get_Formatted_Vertex_Array(); - if(verts) - { - verts[0].x=-SKYBODY_SIZE; - verts[0].y=SKYBODY_SIZE; - verts[0].z=0; - verts[0].u2=0; - verts[0].v2=1; - verts[0].diffuse=0xffffffff; - - verts[1].x=SKYBODY_SIZE; - verts[1].y=SKYBODY_SIZE; - verts[1].z=0; - verts[1].u2=1; - verts[1].v2=1; - verts[1].diffuse=0xffffffff; - - verts[2].x=SKYBODY_SIZE; - verts[2].y=-SKYBODY_SIZE; - verts[2].z=0; - verts[2].u2=1; - verts[2].v2=0; - verts[2].diffuse=0xffffffff; - - verts[3].x=-SKYBODY_SIZE; - verts[3].y=-SKYBODY_SIZE; - verts[3].z=0; - verts[3].u2=0; - verts[3].v2=0; - verts[3].diffuse=0xffffffff; - } - } - - DX8Wrapper::Set_Index_Buffer(m_indexBuffer,0); - DX8Wrapper::Set_Vertex_Buffer(vb_access); - - DX8Wrapper::Draw_Triangles( 0,2, 0, 4); //draw a quad, 2 triangles, 4 verts -} - -//Defines for procedural water animation. -#define WATER_FREQ (2.0*3.2831/4.0) //2pi (full cycle) cover 4 units -#define WATER_AMP (1.0f) -#define WATER_OFFSET (0.1f) - -//------------------------------------------------------------------------------------------------- -/** Renders (draws) the water surface mesh geometry. - * This is a work-in-progress! Do not use this code! */ -//------------------------------------------------------------------------------------------------- -void WaterRenderObjClass::renderWaterMesh(void) -{ - - if (!m_doWaterGrid) - return; //the water grid is disabled. - - //According to Nvidia there's a D3D bug that happens if you don't start with a - //new dynamic VB each frame - so we force a DISCARD by overflowing the counter. - m_vertexBufferD3DOffset = 0xffff; - - Setting *setting=&m_settings[m_tod]; - - WaterMeshData *pData; - Int mx=m_gridCellsX+1; - Int my=m_gridCellsY+1; - Int i,j; - - Real cellSizeX=m_gridCellSize; - Real cellSizeY=m_gridCellSize; -// Real uScale2=5.0f*setting->waterRepeatCount/(128.0f)*cellSizeX/10.0f; -// Real vScale2=5.0f*setting->waterRepeatCount/(128.0f)*cellSizeY/10.0f; - - //Old waterRepeatCount settings in INI were based on 128x128 water grid of cellsize=10 - //Scale values to correct size. - Real uScale=setting->waterRepeatCount/(128.0f)*cellSizeX/10.0f*0.2f; - Real vScale=setting->waterRepeatCount/(128.0f)*cellSizeY/10.0f*0.2f; - - Vector3 nx(cellSizeX*2.0f,0,0); - Vector3 ny(0,cellSizeY*2.0f,0); - Vector3 C; - -#ifdef DO_WATER_SIMULATION //Debug code used to create a dummy water animation - // - // Mark: If you re-enable this water simulation, you might want to consider moving - // this code to the update() method of the water render object (Colin) - // - - static Real PhasePerFrameX=0.1f; - static Real PhasePerFrameY=0.1f; - - //update the mesh heights for this frame (update buffer is 2 samples wider/taller due to border) - for (j=0,pData=m_meshData; j<(my+2); j++) - { - for (i=0; i<(mx+2); i++) - { - //*pData = WATER_AMP * sin(WATER_FREQ*(0.7f*i + 0.7f*j) - PhasePerFrame); - - pData->height=WATER_OFFSET+WATER_AMP*(sin((float)i*WATER_FREQ*0.4+PhasePerFrameX*0.5)+sin((float)i*WATER_FREQ*0.6+PhasePerFrameX*0.2)+sin((float)j*WATER_FREQ+PhasePerFrameX)+sin((float)j*WATER_FREQ*0.7+PhasePerFrameX*0.3)); -// *pData=WATER_OFFSET+WATER_AMP*(sin((float)i*WATER_FREQ*0.4+PhasePerFrameX*0.5)+sin((float)i*WATER_FREQ*0.6+PhasePerFrameX*0.2)+sin((float)j*WATER_FREQ+PhasePerFrameX)+sin((float)j*WATER_FREQ*0.7+PhasePerFrameX*0.3)); - pData++; - } - } - - PhasePerFrameX -= 0.08f; - PhasePerFrameY -= 0.1f; -#endif - - MaterMeshVertexFormat *vb; - if (m_vertexBufferD3DOffset < m_numVertices) - { //we have room in current VB, append new verts - if(m_vertexBufferD3D->Lock(m_vertexBufferD3DOffset*sizeof(MaterMeshVertexFormat),mx*my*sizeof(MaterMeshVertexFormat),(unsigned char**)&vb,D3DLOCK_NOOVERWRITE) != D3D_OK) - return; - } - else - { //ran out of room in last VB, request a substitute VB. - if(m_vertexBufferD3D->Lock(0,mx*my*sizeof(MaterMeshVertexFormat),(unsigned char**)&vb,D3DLOCK_DISCARD) != D3D_OK) - return; - m_vertexBufferD3DOffset=0; //reset start of page to first vertex - } - Int diffuse; - diffuse = setting->waterDiffuse&0x00ffffff; - Int alpha = (setting->waterDiffuse & 0xff000000)>>24; - // Reduce alpha for wave mesh - alpha -= 0x20; - diffuse |= alpha<<24; - - //I pulled some of these constants out of the loops for speed: - Real uvCosScale=0.02*cos(3*m_riverVOrigin); - Real sinOffset=25*m_riverVOrigin; - Real originScale=m_riverVOrigin/vScale; - Real bumpSizeDiv=cellSizeY/BUMP_SIZE; - Real bumpSizeDiv2=0.3f*cellSizeY/BUMP_SIZE; - - //Data has a 1 vertex padding all around it so we don't need to special-case edges. Improves performance - for (j=0,pData=m_meshData+mx+2+1; jheight - (pData-1)->height; - ny.Z=(pData+mx+2)->height - (pData-mx-2)->height; -// nx.Z=*(pData+1)-*(pData-1); -// ny.Z=*(pData+mx+2)-*(pData-mx-2); - Vector3::Cross_Product(nx,ny,&C); - C.Normalize(); - vb->nx = C.X; - vb->ny = C.X; - vb->nz = C.X; -#endif - Real x = (float)i*cellSizeX; - vb->x= x; - vb->y= y; - vb->z= pData->height;//WATER_OFFSET+WATER_AMP*(sin((float)i*WATER_FREQ+PhasePerFrame)+cos((float)j*WATER_FREQ+PhasePerFrame)); - - vb->diffuse = diffuse; -#ifdef SCROLL_UV -// vb->diffuse=0x80ffffff; - vb->u1=(float)i*uScale; - vb->v1=v1Offset; - - //old slow version - //vb->v1=m_riverVOrigin+(float)j*vScale + 0.02*cos(3*m_riverVOrigin)*sin(25*m_riverVOrigin+y*PI/(8*MAP_XY_FACTOR)); - -// vb->u2=m_initialGridU2+(float)i*uScale2; -// vb->v2=m_initialGridV2+(float)j*vScale2; -#else - vb->u1=(float)i*uScale; - vb->v1=(float)j*vScale; -#endif - vb->u2=(float)(i)*cellSizeX/BUMP_SIZE; - vb->v2=v2Offset; - //old slow code - //vb->v2=(float)(j+m_riverVOrigin/vScale )*cellSizeY/BUMP_SIZE+ 0.3f*(float)j*cellSizeY/BUMP_SIZE; - vb++; - pData++; - } - } - - m_vertexBufferD3D->Unlock(); - - Matrix3D tm(Transform); - - DX8Wrapper::Set_Transform(D3DTS_WORLD,tm); //position the water surface - DX8Wrapper::Set_Material(m_meshVertexMaterialClass); - - ShaderClass::CullModeType oldCullMode=m_shaderClass.Get_Cull_Mode(); - - ShaderClass::DepthMaskType oldDepthMask=m_shaderClass.Get_Depth_Mask(); - m_shaderClass.Set_Depth_Mask(ShaderClass::DEPTH_WRITE_DISABLE); //disable writing to z-buffer to prevent particle clipping. - - m_shaderClass.Set_Cull_Mode(ShaderClass::CULL_MODE_ENABLE); //water should be visible from both sides - - DX8Wrapper::Set_Shader(m_shaderClass); -#if 1 - setupFlatWaterShader(); -#else - //DX8Wrapper::Set_Shader(ShaderClass::_PresetOpaqueShader); - DX8Wrapper::Set_Texture(0,setting->waterTexture); - DX8Wrapper::Set_Texture(1,setting->waterTexture); - - DX8Wrapper::Set_Light(0,*m_meshLight); - DX8Wrapper::Set_Light(1,NULL); - DX8Wrapper::Set_Light(2,NULL); - DX8Wrapper::Set_Light(3,NULL); -/* - DX8Wrapper::Set_DX8_Render_State(D3DRS_AMBIENT,0); //turn off scene ambient - DX8Wrapper::Set_DX8_Render_State(D3DRS_SPECULARENABLE,TRUE); - DX8Wrapper::Set_DX8_Render_State(D3DRS_LOCALVIEWER,TRUE); -*/ - - DX8Wrapper::Apply_Render_State_Changes(); //force update of view and projection matrices -#endif - - -// m_pDev->SetRenderState(D3DRS_ZFUNC,D3DCMP_ALWAYS); //used to display grid under map. - - m_pDev->SetIndices(m_indexBufferD3D,m_vertexBufferD3DOffset); - m_pDev->SetStreamSource(0,m_vertexBufferD3D,sizeof(MaterMeshVertexFormat)); - m_pDev->SetVertexShader(WATER_MESH_FVF); - - - if (TheTerrainRenderObject->getShroud() && !m_trapezoidWaterPixelShader) - { //we have a shroud to apply and can't do it inside the pixel shader. - //so do it in stage1 - W3DShaderManager::setTexture(0,TheTerrainRenderObject->getShroud()->getShroudTexture()); - W3DShaderManager::setShader(W3DShaderManager::ST_SHROUD_TEXTURE, 1); - - //modulate with shroud texture - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLORARG1, D3DTA_TEXTURE ); //stage 1 texture - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLORARG2, D3DTA_CURRENT ); //previous stage texture - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLOROP, D3DTOP_MODULATE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAOP, D3DTOP_MODULATE ); - - //Shroud shader uses z-compare of EQUAL which wouldn't work on water because it doesn't - //write to the zbuffer. Change to LESSEQUAL. - DX8Wrapper::_Get_D3D_Device8()->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESSEQUAL); - m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP,0,mx*my,0,m_numIndices-2); - DX8Wrapper::_Get_D3D_Device8()->SetRenderState(D3DRS_ZFUNC, D3DCMP_EQUAL); - W3DShaderManager::resetShader(W3DShaderManager::ST_SHROUD_TEXTURE); - } - else - m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP,0,mx*my,0,m_numIndices-2); - - Debug_Statistics::Record_DX8_Polys_And_Vertices(m_numIndices-2,mx*my,ShaderClass::_PresetOpaqueShader); - -// m_pDev->SetRenderState(D3DRS_FILLMODE,D3DFILL_SOLID); - - if (m_trapezoidWaterPixelShader) DX8Wrapper::_Get_D3D_Device8()->SetPixelShader(NULL); - - m_vertexBufferD3DOffset += mx*my; //advance past vertices already in buffer - - DX8Wrapper::Set_Texture(0,NULL); - DX8Wrapper::Set_Texture(1,NULL); - ShaderClass::Invalidate(); - m_shaderClass.Set_Cull_Mode(oldCullMode); //water should be visible from both sides - - // restore shader to old mask - m_shaderClass.Set_Depth_Mask(oldDepthMask); - - //W3DShaderManager::resetShader(W3DShaderManager::ST_SHROUD_TEXTURE); - -} - -inline void WaterRenderObjClass::setGridVertexHeight(Int x, Int y, Real value) -{ - DEBUG_ASSERTCRASH( x < (m_gridCellsX+1) && y < (m_gridCellsY+1), ("Invalid Water Mesh Coordinates") ); - - if (m_meshData) - { - m_meshData[(y+1)*(m_gridCellsX+1+2)+x+1].height = value; - } -} - -void WaterRenderObjClass::setGridHeightClamps(Real minz, Real maxz) -{ - m_minGridHeight = minz; - m_maxGridHeight = maxz; -} - -void WaterRenderObjClass::addVelocity( Real worldX, Real worldY, - Real zVelocity, Real preferredHeight ) -{ - - if( m_doWaterGrid) - { - Real gx,gy; - Real minX,maxX,minY,maxY; - Int x,y; - WaterMeshData *meshPoint; - m_disableRiver = true; - - //check if center falls within grid bounds - if (worldToGridSpace(worldX, worldY, gx, gy)) - { - - //find extents of influence - minX = floorf(gx - m_gridChangeMaxRange); - if (minX < 0 ) - minX = 0; //clamp extent to fall within box - maxX = ceilf(gx + m_gridChangeMaxRange); - if (maxX > m_gridCellsX) - maxX = m_gridCellsX; //clamp extent to fall within box - - minY = floorf(gy - m_gridChangeMaxRange); - if (minY < 0 ) - minY = 0; //clamp extent to fall within box - maxY = ceilf(gy + m_gridChangeMaxRange); - if (maxY > m_gridCellsY) - maxY = m_gridCellsY; //clamp extent to fall within box - - for (y=minY; y<=maxY; y++) - { - for (x=minX; x<=maxX; x++) - { - - // get the mesh point that we're concerned with - meshPoint = &m_meshData[ (y + 1) * (m_gridCellsX + 1 + 2) + x + 1 ]; - - // we now have a new preferred height - meshPoint->preferredHeight = preferredHeight; - - // - // set the velocity of this point based on the distance from the center of the - // "core" point for this call - // - meshPoint->velocity = meshPoint->velocity + zVelocity; - - // this point is now "in motion" - BitSet( meshPoint->status, WaterRenderObjClass::IN_MOTION ); - - } - } - - // - // the mesh data is now dirty, we need to pass through the velocity field - // during an update phase to update the positions - // - m_meshInMotion = TRUE; - - } - - } - -} - -void WaterRenderObjClass::changeGridHeight(Real wx, Real wy, Real delta) -{ - Real gx,gy; - Real *oldData; - Real newData; - Real distance; - Real minX,maxX,minY,maxY; - Int x,y; - - //check if center falls within grid bounds - if (worldToGridSpace(wx, wy, gx, gy)) - { //find extents of influence - minX = floorf(gx - m_gridChangeMaxRange); - if (minX < 0 ) - minX = 0; //clamp extent to fall within box - maxX = ceilf(gx + m_gridChangeMaxRange); - if (maxX > m_gridCellsX) - maxX = m_gridCellsX; //clamp extent to fall within box - - minY = floorf(gy - m_gridChangeMaxRange); - if (minY < 0 ) - minY = 0; //clamp extent to fall within box - maxY = ceilf(gy + m_gridChangeMaxRange); - if (maxY > m_gridCellsY) - maxY = m_gridCellsY; //clamp extent to fall within box - - for (y=minY; y<=maxY; y++) - { - for (x=minX; x<=maxX; x++) - { oldData = &m_meshData[(y+1)*(m_gridCellsX+1+2)+x+1].height; - distance = (gx - (Real)x)*(gx - (Real)x) + (gy - (Real)y)*(gy - (Real)y); - distance = sqrt(distance); - newData = *oldData + 1.0f/(m_gridChangeAtt0+m_gridChangeAtt1*distance+distance*distance*m_gridChangeAtt2)*delta; - //Clamp to min/max values - if (newData < m_minGridHeight) - newData = m_minGridHeight; - if (newData > m_maxGridHeight) - newData = m_maxGridHeight; - *oldData = newData; - } - } - } -} - -void WaterRenderObjClass::setGridChangeAttenuationFactors(Real a, Real b, Real c, Real range) -{ - m_gridChangeAtt0 = a; - m_gridChangeAtt1 = b; - m_gridChangeAtt2 = c; - m_gridChangeMaxRange = range/m_gridCellSize; //convert range to grid space -} - -void WaterRenderObjClass::setGridTransform(Real angle, Real x, Real y, Real z) -{ - m_gridDirectionX = Vector2(1.0f,0.0f); - - m_gridOrigin.X = x; - m_gridOrigin.Y = y; - - Matrix3D xform(1); - xform.Rotate_Z(angle); - - m_gridDirectionX.X = xform.Get_X_Vector().X; - m_gridDirectionX.Y = xform.Get_X_Vector().Y; - - m_gridDirectionY.X = xform.Get_Y_Vector().X; - m_gridDirectionY.Y = xform.Get_Y_Vector().Y; - - xform.Set_Translation(Vector3(x,y,z)); - Set_Transform(xform); -} - -void WaterRenderObjClass::setGridTransform(const Matrix3D *transform ) -{ - - if( transform ) - Set_Transform( *transform ); - -} - -void WaterRenderObjClass::getGridTransform(Matrix3D *transform ) -{ - - if( transform ) - *transform = Get_Transform(); - -} - -void WaterRenderObjClass::setGridResolution(Real gridCellsX, Real gridCellsY, Real cellSize) -{ - m_gridCellSize=cellSize; - - if (m_gridCellsX != gridCellsX || m_gridCellsY != gridCellsY) - { //resolution has changed - m_gridCellsX=gridCellsX; - m_gridCellsY=gridCellsY; - - if (m_meshData) - { - - delete [] m_meshData;//free previously allocated grid and allocate new size - m_meshData = NULL; // must set to NULL so that we properly re-allocate - m_meshDataSize = 0; - - Bool enable = m_doWaterGrid; - enableWaterGrid(true); // allocates buffers. - m_doWaterGrid = enable; - - } - } -} - -void WaterRenderObjClass::getGridResolution( Real *gridCellsX, Real *gridCellsY, Real *cellSize ) -{ - - if( gridCellsX ) - *gridCellsX = m_gridCellsX; - if( gridCellsY ) - *gridCellsY = m_gridCellsY; - if( cellSize ) - *cellSize = m_gridCellSize; - -} - -static Real wobble(Real baseV, Real offset, Bool wobble) -{ - if (!wobble) return 0; - offset = sin(2*PI*baseV - 3*offset); - return offset/22; -} - -/**Utility function used to query water heights in a manner that works in both RTS and WB.*/ -Real WaterRenderObjClass::getWaterHeight(Real x, Real y) -{ - const WaterHandle *waterHandle = NULL; - Real waterZ = 0.0f; - ICoord3D iLoc; - - iLoc.x = REAL_TO_INT_FLOOR( x + 0.5f ); - iLoc.y = REAL_TO_INT_FLOOR( y + 0.5f ); - iLoc.z = 0; - - for( PolygonTrigger *pTrig = PolygonTrigger::getFirstPolygonTrigger(); pTrig; pTrig = pTrig->getNext() ) - { - - if( !pTrig->isWaterArea() ) - continue; - - // See if point is in a water area - if( pTrig->pointInTrigger( iLoc ) ) - { - - if( pTrig->getPoint( 0 )->z >= waterZ ) - { - - waterZ = pTrig->getPoint( 0 )->z; - waterHandle = pTrig->getWaterHandle(); - - } - - } - - } - - if (waterHandle) - return waterHandle->m_polygon->getPoint( 0 )->z; - return INVALID_WATER_HEIGHT; //point not underwater -} - -//------------------------------------------------------------------------------------------------- -//Draw a many sided river polygon. -//------------------------------------------------------------------------------------------------- -void WaterRenderObjClass::drawRiverWater(PolygonTrigger *pTrig) -{ - DX8Wrapper::Invalidate_Cached_Render_States(); ///@todo: Figure out why rivers don't draw without reset of all states. - - Int rectangleCount = pTrig->getNumPoints()/2; - rectangleCount--; - - Real bumpFactor = 5; - static Bool doWobble = true; - - if (m_disableRiver) return; - m_drawingRiver = true; - - //allocate 2 triangles per side with 3 indices per triangle - DynamicIBAccessClass ib_access(BUFFER_TYPE_DYNAMIC_DX8,(rectangleCount+1)*2*3); - { - DynamicIBAccessClass::WriteLockClass lockib(&ib_access); - UnsignedShort *curIb = lockib.Get_Index_Array(); - for (Int i=0; im_standingWaterColor.red; - Real shadeG=TheWaterTransparency->m_standingWaterColor.green; - Real shadeB=TheWaterTransparency->m_standingWaterColor.blue; - - //If the water color is not overridden, use legacy lighting code. - if ( shadeR==1.0f && shadeG==1.0f && shadeB==1.0f) - { - 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; - - 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); - - //Keep diffuse from lighting calculations but substitute custom alpha - diffuse |= m_settings[m_tod].waterDiffuse & 0xff000000; //copy alpha/opacity from ini setting - - Int innerNdx = pTrig->getRiverStart(); - Int outerNdx = innerNdx+1; - - Real endLen=0; - Real totalLen=0; - Int i; - for (i=0; igetNumPoints()-1; i++) { - ICoord3D innerPt = *pTrig->getPoint(i); - ICoord3D outerPt = *pTrig->getPoint(i+1); - Real dx = innerPt.x-outerPt.x; - Real dy = innerPt.y-outerPt.y; - Real curLen = sqrt(dx*dx+dy*dy); - totalLen += curLen; - if ( i==innerNdx) { - endLen = curLen; - } - } - bumpFactor = endLen/BUMP_SIZE; - - Real lengthOfRiver = (totalLen/2)-endLen; - Real repeatCount = lengthOfRiver / (endLen); - - Real vScale=(Real)repeatCount/(Real)rectangleCount; - -#define HEIGHT_TO_USE (0.5f) - if (innerNdx >= pTrig->getNumPoints()-1) return; - //allocate 2 vertices per side - DynamicVBAccessClass vb_access(BUFFER_TYPE_DYNAMIC_DX8,dynamic_fvf_type,(rectangleCount+1)*2); - { - DynamicVBAccessClass::WriteLockClass lock(&vb_access); - VertexFormatXYZNDUV2* vb=lock.Get_Formatted_Vertex_Array(); - - Real constA=3*m_riverVOrigin; - - for (i=0; i<(pTrig->getNumPoints()/2); i++) - { - Real x,y; - ICoord3D innerPt = *pTrig->getPoint(outerNdx); - ICoord3D outerPt = *pTrig->getPoint(innerNdx); - outerNdx++; - innerNdx--; - if (innerNdx<0) { - innerNdx = pTrig->getNumPoints()-1; - } - if (outerNdx >= pTrig->getNumPoints()) { - outerNdx = 0; - } - x=innerPt.x; - y=innerPt.y; - - vb->x=x; - vb->y=y; - - vb->z=innerPt.z; - vb->diffuse= diffuse; - - Real wobbleConst=-m_riverVOrigin+vScale*(Real)i + WWMath::Fast_Sin(2*PI*(vScale*(Real)i) - constA)/22.0f; - //old slower version - //vb->v1=-m_riverVOrigin+vScale*(Real)i + wobble(vScale*i, m_riverVOrigin, doWobble); - vb->v1=wobbleConst; - vb->u1=HEIGHT_TO_USE ; - //old slower version - //vb->v2 = -m_riverVOrigin+vScale*(Real)i + wobble(vScale*i, m_riverVOrigin, doWobble); - vb->v2=wobbleConst; - vb->u2 = 1.0f; - vb->nx = 0; - vb->ny = 0; - vb->nz = 1.0f; - vb++; - - x=outerPt.x; - y=outerPt.y; - - vb->x=x; - vb->y=y; - vb->z=outerPt.z; - vb->diffuse= diffuse; - //old slower version - //vb->v1=-m_riverVOrigin+vScale*(Real)i + wobble(vScale*i, m_riverVOrigin, doWobble); - vb->v1=wobbleConst; - vb->u1=0; - //old slower version - //vb->v2 = -m_riverVOrigin+vScale*(Real)i + wobble(vScale*i, m_riverVOrigin, doWobble); - vb->v2 =wobbleConst; - vb->u2 = 0; - vb->nx = 0; - vb->ny = 0; - vb->nz = 1.0f; - vb++; - - } - } - - Matrix3D tm(1); - - 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 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); - DX8Wrapper::_Get_D3D_Device8()->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); - - - - if (wireframeForDebug) { - DX8Wrapper::_Get_D3D_Device8()->SetRenderState(D3DRS_FILLMODE,D3DFILL_WIREFRAME); - } - DX8Wrapper::Draw_Triangles( 0,rectangleCount*2, 0, (rectangleCount+1)*2); - if (wireframeForDebug) { - DX8Wrapper::_Get_D3D_Device8()->SetRenderState(D3DRS_FILLMODE,D3DFILL_SOLID); - } - - 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()) - { - W3DShaderManager::setTexture(0,TheTerrainRenderObject->getShroud()->getShroudTexture()); - W3DShaderManager::setShader(W3DShaderManager::ST_SHROUD_TEXTURE, 0); - DX8Wrapper::_Get_D3D_Device8()->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); - //Shroud shader uses z-compare of EQUAL which wouldn't work on water because it doesn't - //write to the zbuffer. Change to LESSEQUAL. - DX8Wrapper::_Get_D3D_Device8()->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESSEQUAL); - DX8Wrapper::Draw_Triangles( 0,rectangleCount*2, 0, (rectangleCount+1)*2); - DX8Wrapper::_Get_D3D_Device8()->SetRenderState(D3DRS_ZFUNC, D3DCMP_EQUAL); - W3DShaderManager::resetShader(W3DShaderManager::ST_SHROUD_TEXTURE); - } - DX8Wrapper::_Get_D3D_Device8()->SetRenderState(D3DRS_CULLMODE, cull); - - -} - -void WaterRenderObjClass::setupFlatWaterShader(void) -{ - - DX8Wrapper::Set_Texture(0,m_riverTexture); - 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); - m_riverTexture->Get_Filter().Set_Mag_Filter(TextureFilterClass::FILTER_TYPE_BEST); - m_riverTexture->Get_Filter().Set_Min_Filter(TextureFilterClass::FILTER_TYPE_BEST); - m_riverTexture->Get_Filter().Set_Mip_Mapping(TextureFilterClass::FILTER_TYPE_BEST); - - DX8Wrapper::Apply_Render_State_Changes(); //force update of view and projection matrices - - //Setup shroud to render in same pass as water - if (m_trapezoidWaterPixelShader) - { if (TheTerrainRenderObject->getShroud()) - { - W3DShaderManager::setTexture(0,TheTerrainRenderObject->getShroud()->getShroudTexture()); - //Use stage 3 to apply the shroud - W3DShaderManager::setShader(W3DShaderManager::ST_SHROUD_TEXTURE, 3); - //Shroud shader uses z-compare of EQUAL which wouldn't work on water because it doesn't - //write to the zbuffer. Change to LESSEQUAL. - DX8Wrapper::_Get_D3D_Device8()->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESSEQUAL); - } - else - { //Assume no shroud, so stage 3 will be "NULL" texture but using actual white because - //pixel shader on GF4 generates random colors with SetTexture(3,NULL). - if (!m_whiteTexture->Is_Initialized()) - { m_whiteTexture->Init(); - SurfaceClass *surface=m_whiteTexture->Get_Surface_Level(); - surface->DrawPixel(0,0,0xffffffff); - REF_PTR_RELEASE(surface); - } - DX8Wrapper::_Get_D3D_Device8()->SetTexture(3,m_whiteTexture->Peek_D3D_Texture()); - } - } - - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAOP, D3DTOP_ADD ); - DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_TEXCOORDINDEX, 0); - DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_TEXCOORDINDEX, 0); - - Bool doSparkles = true; - - if (m_trapezoidWaterPixelShader && doSparkles) { - - if (!m_waterSparklesTexture->Is_Initialized()) - m_waterSparklesTexture->Init(); - - DX8Wrapper::_Get_D3D_Device8()->SetTexture(1,m_waterSparklesTexture->Peek_D3D_Texture()); - - if (!m_waterNoiseTexture->Is_Initialized()) - m_waterNoiseTexture->Init(); - - DX8Wrapper::_Get_D3D_Device8()->SetTexture(2,m_waterNoiseTexture->Peek_D3D_Texture()); - - DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); - DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); - - DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION); - // Two output coordinates are used. - DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2); - DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); - DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); - D3DXMATRIX inv; - float det; - - Matrix4x4 curView; - DX8Wrapper::_Get_DX8_Transform(D3DTS_VIEW, curView); - D3DXMatrixInverse(&inv, &det, (D3DXMATRIX*)&curView); - D3DXMATRIX scale; - - D3DXMatrixScaling(&scale, NOISE_REPEAT_FACTOR, NOISE_REPEAT_FACTOR,1); - D3DXMATRIX destMatrix = inv * scale; - D3DXMatrixTranslation(&scale, m_riverVOrigin, m_riverVOrigin,0); - destMatrix = destMatrix*scale; - DX8Wrapper::_Set_DX8_Transform(D3DTS_TEXTURE2, *(Matrix4x4*)&destMatrix); - - } - m_pDev->SetTextureStageState( 0, D3DTSS_MINFILTER, D3DTEXF_LINEAR ); - m_pDev->SetTextureStageState( 0, D3DTSS_MAGFILTER, D3DTEXF_LINEAR ); - m_pDev->SetTextureStageState( 1, D3DTSS_MINFILTER, D3DTEXF_LINEAR ); - m_pDev->SetTextureStageState( 1, D3DTSS_MAGFILTER, D3DTEXF_LINEAR ); - m_pDev->SetTextureStageState( 2, D3DTSS_MINFILTER, D3DTEXF_LINEAR ); - m_pDev->SetTextureStageState( 2, D3DTSS_MAGFILTER, D3DTEXF_LINEAR ); - if (m_trapezoidWaterPixelShader){ - DX8Wrapper::_Get_D3D_Device8()->SetPixelShaderConstant(0, D3DXVECTOR4(REFLECTION_FACTOR, REFLECTION_FACTOR, REFLECTION_FACTOR, 1.0f), 1); - DX8Wrapper::_Get_D3D_Device8()->SetPixelShader(m_trapezoidWaterPixelShader); - } -} - -//------------------------------------------------------------------------------------------------- -//Draw a 4 sided flat water area. -//------------------------------------------------------------------------------------------------- -void WaterRenderObjClass::drawTrapezoidWater(Vector3 points[4]) -{ - Vector3 origin(points[0]); - Vector3 uVec1(points[1]); - Vector3 vVec1(points[3]); - Vector3 uVec2(points[2]); - Vector3 vVec2(points[2]); - uVec2 -= vVec1; - vVec2 -= uVec1; - uVec1 -= origin; - vVec1 -= origin; - Int uCount = (uVec1.Length()+uVec2.Length()) / (8*MAP_XY_FACTOR); - if (uCount<1) uCount = 1; - Int vCount = (vVec1.Length()+vVec2.Length()) / (8*MAP_XY_FACTOR); - if (vCount<1) vCount = 1; - - if (uCount>50) uCount = 50; - if (vCount>50) vCount = 50; - - static Bool doWobble = true; - - Int rectangleCount = uCount*vCount; - - uCount++; - vCount++; - - Int i, j; - //allocate 2 triangles per side with 3 indices per triangle - DynamicIBAccessClass ib_access(BUFFER_TYPE_DYNAMIC_DX8,(rectangleCount+1)*2*3); - { - DynamicIBAccessClass::WriteLockClass lockib(&ib_access); - UnsignedShort *curIb = lockib.Get_Index_Array(); - for (j=0; jm_standingWaterColor.red; - Real shadeG=TheWaterTransparency->m_standingWaterColor.green; - Real shadeB=TheWaterTransparency->m_standingWaterColor.blue; - - //If the water color is not overridden, use legacy lighting code. - if ( shadeR==1.0f && shadeG==1.0f && shadeB==1.0f) - { - 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; - - 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); - - //Keep diffuse from lighting calculations but substitute custom alpha - diffuse |= m_settings[m_tod].waterDiffuse & 0xff000000; //copy alpha/opacity from ini setting - - DynamicVBAccessClass vb_access(BUFFER_TYPE_DYNAMIC_DX8,dynamic_fvf_type,(rectangleCount+1)*2); - -//#define WAVY_WATER -//#define FEATHER_LAYER_COUNT (3) //LORENZEN -//#define FEATHER_LAYER_THICKNESS (2.5f) -//#define FEATHER_WATER - -//#ifdef WAVY_WATER // the NEW WATER a'la LORENZEN - if ( TheGlobalData->m_featherWater ) - { - - DynamicVBAccessClass::WriteLockClass lock(&vb_access); - VertexFormatXYZNDUV2* vb=lock.Get_Formatted_Vertex_Array(); - - Real phase = 0; - Real mapCoeff = PI/(4*MAP_XY_FACTOR); - Real wave = 0; - Real amplitude = 0.5f; - - //The first (high order) byte is the Alpha value for this patch - // It needs to be set proportional to the number of feather layers - // this comes from TheGlobalData->m_featherWater, which is a count of layers - - - Int Alpha = 0; - if ( TheGlobalData->m_featherWater == 5) Alpha = 80; - if ( TheGlobalData->m_featherWater == 4) Alpha = 110; - if ( TheGlobalData->m_featherWater == 3) Alpha = 140; - if ( TheGlobalData->m_featherWater == 2) Alpha = 200; - if ( TheGlobalData->m_featherWater == 1) Alpha = 255; - - //Keep diffuse from lighting calculations but substitute custom alpha - Int customDiffuse = (diffuse & 0x00ffffff) | (Alpha<< 24);//(0x80 << 16)|(0x90 << 8)|0xa0; - - for (j=0; jx=vertex.X; - vb->y=vertex.Y; - - // common to all the waving effects - phase = 25 * m_riverVOrigin + vertex.X * mapCoeff; - wave = (sin(phase) - 1.0f) * amplitude; - - vb->z = (vertex.Z + wave); - vb->diffuse = customDiffuse; - vb->u1 = (vertex.X/waterFactor) + 0.02*cos(11*m_riverVOrigin)*wave; - vb->v1 = (vertex.Y/waterFactor) + 0.02*cos(5*m_riverVOrigin)*wave; - vb->u2 = vertex.X/BUMP_SIZE; - vb->v2 = vertex.Y/BUMP_SIZE + 0.3f*vertex.X/BUMP_SIZE; - vb->nx = 0; - vb->ny = 0; - vb->nz = 1.0f; - vb++; - } - } - } -//#else // STILL THE OLD FLAT WATER - else - - { - DynamicVBAccessClass::WriteLockClass lock(&vb_access); - VertexFormatXYZNDUV2* vb=lock.Get_Formatted_Vertex_Array(); - - //Pulling some constants out of the inner loops to improve performance -MW - Real constA=0.02*cos(11*m_riverVOrigin); - Real constB=0.02*cos(5*m_riverVOrigin); - Real constC=25*m_riverVOrigin; - Real ooWaterFactor = 1.0f/waterFactor; - const Real constD=PI/(4*MAP_XY_FACTOR); - Real constE=1.0f/(Real)(vCount-1); - Real constF=1.0f/(Real)(uCount-1); - - for (j=0; jx=vertex.X; - vb->y=vertex.Y; - vb->z=vertex.Z; - - vb->diffuse= diffuse; - //Old slower version - //vb->u1=(vertex.X/waterFactor) + 0.02*cos(11*m_riverVOrigin)*sin(25*m_riverVOrigin+vertex.X*PI/(4*MAP_XY_FACTOR)); - //vb->v1=(vertex.Y/waterFactor) + 0.02*cos(5*m_riverVOrigin)*sin(25*m_riverVOrigin+vertex.Y*PI/(4*MAP_XY_FACTOR)); - vb->u1=vertex.X*ooWaterFactor + constA*WWMath::Fast_Sin(constC+vertex.X*constD); - vb->v1=vertex.Y*ooWaterFactor + constB*WWMath::Fast_Sin(constC+vertex.Y*constD); - vb->u2 = vertex.X/BUMP_SIZE; - //Old slower version - //vb->v2 = vertex.Y/BUMP_SIZE + 0.3f*vertex.X/BUMP_SIZE; - vb->v2 = (vertex.Y+0.3f*vertex.X)/BUMP_SIZE; - vb->nx = 0; - vb->ny = 0; - vb->nz = 1.0f; - vb++; - } - } - } - -//#endif // OLD VS NEW WATER - - - - Matrix3D tm(1); - - DX8Wrapper::Set_Transform(D3DTS_WORLD,tm); //position the water surface - DX8Wrapper::Set_Index_Buffer(ib_access,0); - DX8Wrapper::Set_Vertex_Buffer(vb_access); - - setupFlatWaterShader();// lorenzen sez use the alpha shader - - //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 ); - if (!TheWaterTransparency->m_additiveBlend) - DX8Wrapper::Set_DX8_Render_State(D3DRS_DESTBLEND, D3DBLEND_INVDESTALPHA ); - } - - - DWORD cull; - DX8Wrapper::_Get_D3D_Device8()->GetRenderState(D3DRS_CULLMODE, &cull); - DX8Wrapper::_Get_D3D_Device8()->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); - - - -//#ifdef FEATHER_WATER // the NEW WATER a'la LORENZEN - -// int layer = 0;//LORENZEN -// for (layer = 0; layer < FEATHER_LAYER_COUNT; ++layer)//LORENZEN -//#endif // FEATHER_WATER - { -//#ifdef WAVY_WATER // the NEW WATER a'la LORENZEN - - //increment the depth of the water's surface for every vert in the buffer -//#ifdef FEATHER_WATER -// VertexFormatXYZNDUV2 *vertBuf = vertexBufferStart; -// while (vertBuf < vertexBufferStart + vCount * uCount) -// { -// vertBuf->z *= FEATHER_LAYER_THICKNESS; -// ++vertBuf; -// } -//#endif // FEATHER_WATER -//#endif //WAVY_WATER - DX8Wrapper::Draw_Triangles( 0,rectangleCount*2, 0, (rectangleCount+1)*2);//lorenzen thinks this is where to itereate the soft shoreline effect - } - - - - - if (false) { - DX8Wrapper::_Get_D3D_Device8()->SetRenderState(D3DRS_FILLMODE,D3DFILL_WIREFRAME); - m_pDev->SetRenderState(D3DRS_ALPHABLENDENABLE , false); - DX8Wrapper::Draw_Triangles( 0,rectangleCount*2, 0, (rectangleCount+1)*2); - m_pDev->SetRenderState(D3DRS_ALPHABLENDENABLE , true); - DX8Wrapper::_Get_D3D_Device8()->SetRenderState(D3DRS_FILLMODE,D3DFILL_SOLID); - } - - if (m_riverWaterPixelShader) DX8Wrapper::_Get_D3D_Device8()->SetPixelShader(NULL); - //Restore alpha blend to default values since we may have changed them to feather edges. - 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()) - { - if (m_trapezoidWaterPixelShader) - { //shroud was applied in stage3 of main pass so just need to restore state here. - W3DShaderManager::resetShader(W3DShaderManager::ST_SHROUD_TEXTURE); - DX8Wrapper::_Get_D3D_Device8()->SetTexture(3,NULL); //free possible reference to shroud texture - DX8Wrapper::_Get_D3D_Device8()->SetRenderState(D3DRS_ZFUNC, D3DCMP_EQUAL); - } - else - { //do second pass to apply the shroud on water plane for cards that can't do it in main pass. - W3DShaderManager::setTexture(0,TheTerrainRenderObject->getShroud()->getShroudTexture()); - W3DShaderManager::setShader(W3DShaderManager::ST_SHROUD_TEXTURE, 0); - DX8Wrapper::_Get_D3D_Device8()->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); - //Shroud shader uses z-compare of EQUAL which wouldn't work on water because it doesn't - //write to the zbuffer. Change to LESSEQUAL. - DX8Wrapper::_Get_D3D_Device8()->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESSEQUAL); - DX8Wrapper::Draw_Triangles( 0,rectangleCount*2, 0, (rectangleCount+1)*2); - DX8Wrapper::_Get_D3D_Device8()->SetRenderState(D3DRS_ZFUNC, D3DCMP_EQUAL); - W3DShaderManager::resetShader(W3DShaderManager::ST_SHROUD_TEXTURE); - } - } - DX8Wrapper::_Get_D3D_Device8()->SetRenderState(D3DRS_CULLMODE, cull); -} - - - -//------------------------------------------------------------------------------------------------- -//debug version where moon rotates with the camera (always upright on screen) -//------------------------------------------------------------------------------------------------- -#if 0 -void WaterRenderObjClass::renderSkyBody(Matrix3D *mat) -{ - Vector3 vRight,vUp,V0,V1,V2,V3; - - mat->Get_X_Vector(&vRight); - mat->Get_Y_Vector(&vUp); - - //calculate offsets from quad center to each of the 4 corners - // 0-----1 - // | /| - // | / | - // |/ | - // 3-----2 - V0=-vRight+vUp; - V2=vRight+vUp; - V2=vRight-vUp; - V3=-vRight-vUp; - - VertexMaterialClass *vmat=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_DIFFUSE); - DX8Wrapper::Set_Material(vmat); - REF_PTR_RELEASE(vmat); - DX8Wrapper::Set_Shader(ShaderClass::/*_PresetAdditiveShader*//*_PresetOpaqueShader*/_PresetAlphaShader); -// DX8Wrapper::Set_Texture(0,setting->skyBodyTexture); - - DX8Wrapper::Set_Texture(0,m_alphaClippingTexture); - - //draw an infinite sky plane - DynamicVBAccessClass vb_access(BUFFER_TYPE_DYNAMIC_DX8,4); - { - DynamicVBAccessClass::WriteLockClass lock(&vb_access); - VertexFormatXYZNDUV2* verts=lock.Get_Formatted_Vertex_Array(); - if(verts) - { - verts[0].x=SKYBODY_SIZE*V0.X; - verts[0].y=SKYBODY_SIZE*V0.Y; - verts[0].z=SKYBODY_SIZE*V0.Z; - verts[0].u2=0; - verts[0].v2=1; - verts[0].diffuse=0xffffffff; - - verts[1].x=SKYBODY_SIZE*V1.X; - verts[1].y=SKYBODY_SIZE*V1.Y; - verts[1].z=SKYBODY_SIZE*V1.Z; - verts[1].u2=1; - verts[1].v2=1; - verts[1].diffuse=0xffffffff; - - verts[2].x=SKYBODY_SIZE*V2.X; - verts[2].y=SKYBODY_SIZE*V2.Y; - verts[2].z=SKYBODY_SIZE*V2.Z; - verts[2].u2=1; - verts[2].v2=0; - verts[2].diffuse=0xffffffff; - - verts[3].x=SKYBODY_SIZE*V3.X; - verts[3].y=SKYBODY_SIZE*V3.Y; - verts[3].z=SKYBODY_SIZE*V3.Z; - verts[3].u2=0; - verts[3].v2=0; - verts[3].diffuse=0xffffffff; - } - } - - DX8Wrapper::Set_Index_Buffer(m_indexBuffer,0); - DX8Wrapper::Set_Vertex_Buffer(vb_access); - - Matrix3D tm(1); - //set postion of skybody in world -// tm.Set_Translation(Vector3(40,0,0)); - DX8Wrapper::Set_Transform(D3DTS_WORLD,tm); - - DX8Wrapper::Draw_Triangles( 0,2, 0, 4); //draw a quad, 2 triangles, 4 verts -} -#endif - -// ------------------------------------------------------------------------------------------------ -/** CRC */ -// ------------------------------------------------------------------------------------------------ -void WaterRenderObjClass::crc( Xfer *xfer ) -{ - -} - -// ------------------------------------------------------------------------------------------------ -/** Xfer - * Version Info: - * 1: Initial version */ -// ------------------------------------------------------------------------------------------------ -void WaterRenderObjClass::xfer( Xfer *xfer ) -{ - - // version - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // grid cells x - Int cellsX = m_gridCellsX; - xfer->xferInt( &cellsX ); - if( cellsX != m_gridCellsX ) - { - - DEBUG_CRASH(( "WaterRenderObjClass::xfer - cells X mismatch" )); - throw SC_INVALID_DATA; - - } - - // grid cells Y - Int cellsY = m_gridCellsY; - xfer->xferInt( &cellsY ); - if( cellsY != m_gridCellsY ) - { - - DEBUG_CRASH(( "WaterRenderObjClass::xfer - cells Y mismatch" )); - throw SC_INVALID_DATA; - - } - - // xfer each of the mesh data points - for( UnsignedInt i = 0; i < m_meshDataSize; ++i ) - { - - // height - xfer->xferReal( &m_meshData[ i ].height ); - - // velocity - xfer->xferReal( &m_meshData[ i ].velocity ); - - // status - xfer->xferUnsignedByte( &m_meshData[ i ].status ); - - // preferred height - xfer->xferUnsignedByte( &m_meshData[ i ].preferredHeight ); - - } - -} - -// ------------------------------------------------------------------------------------------------ -/** Load post process */ -// ------------------------------------------------------------------------------------------------ -void WaterRenderObjClass::loadPostProcess( void ) -{ - -} - - diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp deleted file mode 100644 index 5c60664aae..0000000000 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp +++ /dev/null @@ -1,1309 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public 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: W3DWaterTracks.cpp //////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: W3DWaterTracks.cpp -// -// Created: Mark Wilczynski, July 2001 -// -// Desc: Draw waves and splash marks on water surface. System allows for -// some simple animation : dynamic uv coordinates, scaling, scrolling, -// and alpha. -//----------------------------------------------------------------------------- - -#include "W3DDevice/GameClient/HeightMap.h" -#include "W3DDevice/GameClient/W3DWaterTracks.h" -#include "W3DDevice/GameClient/W3DShaderManager.h" -#include "W3DDevice/GameClient/W3DShroud.h" -#include "GameClient/InGameUI.h" -#include "GameClient/Water.h" -#include "GameLogic/TerrainLogic.h" -#include "Common/FramePacer.h" -#include "Common/GlobalData.h" -#include "Common/UnicodeString.h" -#include "Common/file.h" -#include "Common/FileSystem.h" -#include "texture.h" -#include "colmath.h" -#include "coltest.h" -#include "rinfo.h" -#include "camera.h" -#include "assetmgr.h" -#include "WW3D2/dx8wrapper.h" - -//number of vertex pages allocated - allows double buffering of vertex updates. -//while one is being rendered, another is being updated. Improves HW parallelism. -#define WATER_VB_PAGES 1000 -#define WATER_STRIP_X 2 //vertex resolution of each strip -#define WATER_STRIP_Y 2 -#define SYNC_WAVES //all the waves are in sync - movement resets at same time. -//#define DEFAULT_FINAL_WAVE_WIDTH 28.0f -//#define DEFAULT_FINAL_WAVE_HEIGHT 18.0f -//#define DEFAULT_SECOND_WAVE_TIME_OFFSET 6267 //should always be half of totalMs - -WaterTracksRenderSystem *TheWaterTracksRenderSystem=NULL; ///< singleton for track drawing system. - -static Bool pauseWaves=FALSE; - -enum waveType CPP_11(: Int) -{ - WaveTypeFirst, - WaveTypePond=WaveTypeFirst, - WaveTypeOcean, - WaveTypeCloseOcean, //same as above but appears much closer to beach. - WaveTypeCloseOceanDouble, //same as above but waves much sloser together. - WaveTypeRadial, - WaveTypeLast = WaveTypeRadial, - WaveTypeStationary, - WaveTypeMax, -}; - -struct waveInfo -{ - Real m_finalWidth; //final width of of wave when it reaches beach. - Real m_finalHeight; //final height of wave after it stretched out on beach. - Real m_waveDistance; //distance away from beach where wave starts. - Real m_initialVelocity; - Int m_fadeMs; //time to fade out wave after it stops on shore. - Real m_initialWidthFraction; //fraction of m_finalWidth when wave first appears. - Real m_initialHeightWidthFraction; //fraction of initial width to use as the initial height. - Int m_timeToCompress; //time for back of wave to continue moving forward after front starts retreating. - Int m_secondWaveTimeOffset; //time for second wave to start. Should always be half of first wave's TotalMs. - const char *m_textureName; //name of texture to use on wave. - const char *m_waveTypeName; //name of this wave type. -}; - -waveInfo waveTypeInfo[WaveTypeMax]= -{ - {28.0f, 18.0f, 25.0f, 0.018f, 900, 0.01f, 0.18f, 1500, 0,"wave256.tga","Pond"}, //pond - {55.0f, 36.0f, 80.0f, 0.015f, 2000, 0.5f, 0.18f, 1000, 6267,"wave256.tga","Ocean"}, //ocean - {55.0f, 36.0f, 80.0f, 0.015f, 2000, 0.05f, 0.18f, 1000, 6267,"wave256.tga","Close Ocean"}, - {55.0f, 36.0f, 80.0f, 0.015f, 4000, 0.01f, 0.18f, 2000, 6267,"wave256.tga","Close Ocean Double"}, - {55.0f, 27.0f, 80.0f, 0.015f, 2000, 0.01f, 8.0f, 2000, 5367,"wave256.tga","Radial"}, -}; - -//============================================================================= -// WaterTracksObj::~WaterTracksObj -//============================================================================= -/** Destructor. Releases w3d assets. */ -//============================================================================= -WaterTracksObj::~WaterTracksObj(void) -{ - freeWaterTracksResources(); -} - -//============================================================================= -// WaterTracksObj::WaterTracksObj -//============================================================================= -/** Constructor. Just nulls out some variables. */ -//============================================================================= -WaterTracksObj::WaterTracksObj(void) -{ - m_stageZeroTexture=NULL; - m_bound=false; - m_initTimeOffset=0; -} - -//============================================================================= -// WaterTracksObj::Get_Obj_Space_Bounding_Sphere -//============================================================================= -/** WW3D method that returns object bounding sphere used in frustum culling*/ -//============================================================================= -void WaterTracksObj::Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const -{ /// @todo: Add code to cull track marks to screen by constantly updating bounding volumes - sphere=m_boundingSphere; -} - -//============================================================================= -// WaterTracksObj::Get_Obj_Space_Bounding_Box -//============================================================================= -/** WW3D method that returns object bounding box used in collision detection*/ -//============================================================================= -void WaterTracksObj::Get_Obj_Space_Bounding_Box(AABoxClass & box) const -{ - box=m_boundingBox; -} - -//============================================================================= -// WaterTracksObj::freeWaterTracksResources -//============================================================================= -/** Free any W3D resources associated with this object */ -//============================================================================= -Int WaterTracksObj::freeWaterTracksResources(void) -{ - REF_PTR_RELEASE(m_stageZeroTexture); - return 0; -} - -//============================================================================= -// WaterTracksObj::init -//============================================================================= -/** Setup size settings and allocate W3D texture -* The width/length define the size of the polygon quad which will contain -* the specified texture. - */ -//============================================================================= -void WaterTracksObj::init( Real width, Real length, const Vector2 &start, const Vector2 &end, const Char *texturename, Int waveTimeOffset) -{ - freeWaterTracksResources(); //free old resources used by this track - - //save original settings used to create this wave - m_initStartPos = start; - m_initEndPos = end; - m_initTimeOffset = waveTimeOffset; - - m_boundingSphere.Init(Vector3(0,0,0),400); - m_boundingBox.Center.Set(0.0f, 0.0f, 0.0f); - m_boundingBox.Extent.Set(400.0f, 400.0f, 1.0f); - m_x=WATER_STRIP_X; - m_y=WATER_STRIP_Y; - m_elapsedMs=m_initTimeOffset; - m_startPos=start; - m_perpDir=m_waveDir=end-start; - m_perpDir.Rotate(-1.57079632679f); //get vector perpendicular to wave motion. - m_perpDir.Normalize(); - - m_waveDir=m_perpDir; - m_waveDir.Rotate(PI/2); //get vector along wave travel direction. - //move back by width of wave so start point turns into maximum reach of wave. - //m_startPos -= m_waveDir*m_width; - //move back initial tip off of wave a couple units off the final position - //to give it some room to travel. Travel vector is stored in m_waveDir. - m_waveDistance = waveTypeInfo[m_type].m_waveDistance; //total distance traveled by wave front - - m_waveDir *= m_waveDistance; - m_startPos -= m_waveDir; //move start point down away from shoreline - - m_initialVelocity=waveTypeInfo[m_type].m_initialVelocity; //velocity per ms - m_totalMs = m_waveDistance/m_initialVelocity; //amount of time for wave to travel complete distance - - m_fadeMs = waveTypeInfo[m_type].m_fadeMs; //time for wave to fade out after it stops on beach - - m_waveInitialWidth=length * waveTypeInfo[m_type].m_initialWidthFraction;///Get_Texture(texturename); -} - -//============================================================================= -// WaterTracksObj::init -//============================================================================= -/** Setup size settings and allocate W3D texture -* Alternate version of init where: -* (start, end) define a vector perpendicular to wave travel. The length of this -* vector is used as the length of the wave segment. The line between start-end -* defines the maximum distance the wave will reach. - */ -//============================================================================= -void WaterTracksObj::init( Real width, const Vector2 &start, const Vector2 &end, const Char *texturename) -{ - freeWaterTracksResources(); //free old resources used by this track - m_boundingSphere.Init(Vector3(0,0,0),400); - m_boundingBox.Center.Set(0.0f, 0.0f, 0.0f); - m_boundingBox.Extent.Set(400.0f, 400.0f, 1.0f); - m_perpDir=end-start; - m_startPos=start + m_perpDir*0.5f; //move start point to middle - Real length=m_perpDir.Length(); - m_perpDir *= 1.0f/length; //normalize it. - m_waveDir=m_perpDir; - m_waveDir.Rotate(PI/2); //get vector along wave travel direction. - m_startPos -= m_waveDir*width; //move back by width of wave - m_waveDir *= 1.3f*MAP_XY_FACTOR; //travel 4 units - m_startPos -= m_waveDir; //move start point down away from shoreline - m_x=WATER_STRIP_X; - m_y=WATER_STRIP_Y; - m_elapsedMs=0; - m_initialVelocity=0.001f*MAP_XY_FACTOR; //velocity per ms - m_totalMs=m_waveDir.Length()/m_initialVelocity; - m_fadeMs = 3000; //time for wave to fade out after it stops on beach - - m_stageZeroTexture=WW3DAssetManager::Get_Instance()->Get_Texture(texturename); -} - -//============================================================================= -// WaterTracksObj::update -//============================================================================= -/** Update state of object - advance animations and other states. - */ -//============================================================================= -Int WaterTracksObj::update(Int msElapsed) -{ - return TRUE; //assume we had an update -} - -#define waveInitialV = 0.01f -#define waveAcceleration = -0.01f - -//============================================================================= -// WaterTracksObj::render -//============================================================================= -/** Draws the object in it's current state. - */ -//============================================================================= - -Int WaterTracksObj::render(DX8VertexBufferClass *vertexBuffer, Int batchStart) -{ - // TheSuperHackers @tweak The wave movement time step is now decoupled from the render update. - m_elapsedMs += TheFramePacer->getLogicTimeStepMilliseconds(); - - VertexFormatXYZDUV1 *vb; - Vector2 waveTailOrigin,waveFrontOrigin; - Real ooWaveDirLen=1.0f/m_waveDir.Length(); //one over length - Real waterHeight; - Real waveAlpha; - Real widthFrac; - Real heightFrac; - - if (batchStart < (WATER_VB_PAGES*WATER_STRIP_X*WATER_STRIP_Y-m_x*m_y)) - { //we have room in current VB, append new verts - if(vertexBuffer->Get_DX8_Vertex_Buffer()->Lock(batchStart*vertexBuffer->FVF_Info().Get_FVF_Size(),m_x*m_y*vertexBuffer->FVF_Info().Get_FVF_Size(),(unsigned char**)&vb,D3DLOCK_NOOVERWRITE) != D3D_OK) - return batchStart; - } - else - { //ran out of room in last VB, request a substitute VB. - if(vertexBuffer->Get_DX8_Vertex_Buffer()->Lock(0,m_x*m_y*vertexBuffer->FVF_Info().Get_FVF_Size(),(unsigned char**)&vb,D3DLOCK_DISCARD) != D3D_OK) - return batchStart; - batchStart=0; //reset start of page to first vertex - } - - //Adjust wave position in a non-linear way so that it slows down as it hits the target. Using 1/4 sine wave - //seems to work okay since it maxes out at 1.0 at our final position. - //Real timeFrac=(Real)m_elapsedMs/(Real)m_totalMs;//sinf(0.5f*3.14159f*(Real)m_elapsedMs/(Real)m_totalMs); - - //Real displacement=m_elapsedMs*waveInitialV+0.5*waveAcceleration*m_elapsed*m_elapsed; - - heightFrac=1.0f; - widthFrac = 1.0f; - - if (m_type == WaveTypeStationary) - { //stationary wave - waveFrontOrigin = m_startPos; - waveFrontOrigin -= m_perpDir*m_waveFinalWidth*0.5f; //offset to left edge of wave - waveTailOrigin = waveFrontOrigin - m_waveFinalHeight * ooWaveDirLen*m_waveDir; - waveAlpha = 0.0f; - - if (m_elapsedMs >= m_totalMs) - m_elapsedMs = 0; //done with effect*/ - if (m_elapsedMs > (m_timeToReachBeach + m_timeToStop -1000 + m_fadeMs)) - { //fading out - waveAlpha = m_elapsedMs-(m_timeToReachBeach + m_timeToStop - 1000 +m_fadeMs);//(m_totalMs-m_timeToRetreat -m_fadeMs - m_elapsedMs)/m_fadeMs; - waveAlpha = waveAlpha / m_timeToRetreat; - waveAlpha = 1.0f - waveAlpha; - if (waveAlpha < 0.0f) - waveAlpha = 0.0f; - } - else - if (m_elapsedMs > (m_timeToReachBeach + m_timeToStop - 1000)) - { //start fading up - - waveAlpha = m_elapsedMs-(m_timeToReachBeach + m_timeToStop - 1000);//(m_totalMs-m_timeToRetreat -m_fadeMs - m_elapsedMs)/m_fadeMs; - waveAlpha = waveAlpha / m_fadeMs; - if (waveAlpha > 1.0f) - waveAlpha = 1.0f; - } - } - else - { //moving wave - - //get coordinate of top left of wave strip - if (m_elapsedMs < m_timeToReachBeach) - { //wave has not reached beach yet so position only depends on velocity - waveAlpha = m_elapsedMs / m_timeToReachBeach; - widthFrac = waveAlpha; - widthFrac=(m_waveInitialWidth + widthFrac* (m_waveFinalWidth-m_waveInitialWidth))/m_waveFinalWidth; - - waveFrontOrigin = m_startPos + m_initialVelocity*m_elapsedMs*ooWaveDirLen*m_waveDir; - waveFrontOrigin -= m_perpDir*m_waveFinalWidth*0.5f*widthFrac; //offset to left edge of wave - //Tail of wave will be behind the front by fixed amount. - waveTailOrigin = waveFrontOrigin - m_waveInitialHeight * ooWaveDirLen*m_waveDir; - } - else //wave has reached beach and is decelerating - if (m_elapsedMs < m_totalMs) - { waveAlpha = 1.0f; - widthFrac = 1.0f; - //Get position of wave when it hit the beach - waveFrontOrigin = m_startPos + m_initialVelocity*m_timeToReachBeach*ooWaveDirLen*m_waveDir; - waveTailOrigin = waveFrontOrigin; //store position for calculating tail position - //Add movement after it hit the beach - Real elapsedMs=m_elapsedMs - m_timeToReachBeach; - waveFrontOrigin += (m_initialVelocity*elapsedMs+0.5f*m_frontSlowDownAcc*elapsedMs*elapsedMs)*ooWaveDirLen*m_waveDir; - waveFrontOrigin -= m_perpDir*m_waveFinalWidth*0.5f*widthFrac; //offset to left edge of wave - - Real timeSinceBacktrack = m_elapsedMs - m_timeToReachBeach - m_timeToStop; - if (timeSinceBacktrack < 0) - timeSinceBacktrack = 0; - waveAlpha = timeSinceBacktrack/m_fadeMs; - if (waveAlpha > 1.0f) - waveAlpha = 1.0f; - - waveAlpha = 1.0f - waveAlpha; - - //Get position of tail when front hits the beach. - waveTailOrigin -= m_waveInitialHeight * ooWaveDirLen*m_waveDir; - - if (m_elapsedMs > (m_timeToReachBeach+m_timeToStop+m_timeToCompress)) - { elapsedMs=elapsedMs; ///@todo: bug? - waveTailOrigin += (0.5f*m_backSlowDownAcc*(m_timeToStop+m_timeToCompress)*(m_timeToStop+m_timeToCompress))*ooWaveDirLen*m_waveDir; - //get time since wave should have stopped moving forward - Real newElapsed = m_elapsedMs - (m_timeToReachBeach+m_timeToStop+m_timeToCompress); - waveTailOrigin += (0.5f*m_frontSlowDownAcc*newElapsed*newElapsed)*ooWaveDirLen*m_waveDir; - } - else - // if (m_elapsedMs < (m_totalMs-m_timeToRetreat)) - //find position of tail including slowdown after it hit the beach - // waveTailOrigin += (m_initialVelocity*elapsedMs+0.5f*m_backSlowDownAcc*elapsedMs*elapsedMs)*ooWaveDirLen*m_waveDir; - waveTailOrigin += (0.5f*m_backSlowDownAcc*elapsedMs*elapsedMs)*ooWaveDirLen*m_waveDir; - - waveTailOrigin -= m_perpDir*m_waveFinalWidth*0.5f*widthFrac; //offset to left edge of wave - } - else - { m_elapsedMs = 0; - waveAlpha = m_elapsedMs / m_timeToReachBeach; - widthFrac = waveAlpha; - widthFrac=(m_waveInitialWidth + widthFrac* (m_waveFinalWidth-m_waveInitialWidth))/m_waveFinalWidth; - - waveFrontOrigin = m_startPos + m_initialVelocity*m_elapsedMs*ooWaveDirLen*m_waveDir; - waveFrontOrigin -= m_perpDir*m_waveFinalWidth*0.5f*widthFrac; //offset to left edge of wave - //Tail of wave will be behind the front by fixed amount. - waveTailOrigin = waveFrontOrigin - m_waveInitialHeight * ooWaveDirLen*m_waveDir; - } - } - - //First insert tail of wave: - Vector2 testPoint(waveTailOrigin); - TheTerrainLogic->isUnderwater(testPoint.X,testPoint.Y,&waterHeight); - vb->x= testPoint.X; - vb->y= testPoint.Y; - vb->z=waterHeight+1.5f; - vb->diffuse=(REAL_TO_INT(waveAlpha*255.0f)<<24) |0xffffff; - if (m_flipU) - vb->u1=1; - else - vb->u1=0; - vb->v1=0; - vb++; - testPoint.Set(waveTailOrigin + m_perpDir*m_waveFinalWidth*widthFrac); - vb->x= testPoint.X; - vb->y= testPoint.Y; - vb->z=waterHeight+1.5f; - vb->diffuse=(REAL_TO_INT(waveAlpha*255.0f)<<24) |0xffffff; - if (m_flipU) - vb->u1=0.0f; - else - vb->u1=1.0f; - vb->v1=0; - vb++; - //insert front of wave - testPoint.Set(waveFrontOrigin); - vb->x= testPoint.X; - vb->y= testPoint.Y; - vb->z=waterHeight+1.5f; - vb->diffuse=(REAL_TO_INT(waveAlpha*255.0f)<<24) |0xffffff; - if (m_flipU) - vb->u1=1; - else - vb->u1=0; - vb->v1=1.0f; - vb++; - testPoint.Set(waveFrontOrigin + m_perpDir*m_waveFinalWidth*widthFrac); - vb->x= testPoint.X; - vb->y= testPoint.Y; - vb->z=waterHeight+1.5f; - vb->diffuse=(REAL_TO_INT(waveAlpha*255.0f)<<24) |0xffffff; - if (m_flipU) - vb->u1=0; - else - vb->u1=1.0f; - vb->v1=1.0f; - vb++; - - vertexBuffer->Get_DX8_Vertex_Buffer()->Unlock(); - - Int idxCount=(m_y-1)*(m_x*2+2) - 2; //index count - - DX8Wrapper::Set_Index_Buffer(TheWaterTracksRenderSystem->m_indexBuffer,batchStart); - DX8Wrapper::Draw_Strip(0,idxCount-2,0,m_x*m_y); //there are always n-2 primitives for n index strip. - - return batchStart+m_x*m_y; //return new offset into unused area of vertex buffer -} - -//============================================================================= -//WaterTracksRenderSystem::bindTrack -//============================================================================= -/** Grab a track from the free store. If no free tracks exist, return NULL. - As long as a track is bound to an object (like a tank) it is ready to accept - updates with additional edges. Once it is unbound, it will expire and return - to the free store once all tracks have faded out. -*/ -//============================================================================= -WaterTracksObj *WaterTracksRenderSystem::bindTrack(waveType type) -{ - WaterTracksObj *mod,*nextmod,*prevmod; - - mod = m_freeModules; - if( mod ) - { - // take module off the free list - if( mod->m_nextSystem ) - mod->m_nextSystem->m_prevSystem = mod->m_prevSystem; - if( mod->m_prevSystem ) - mod->m_prevSystem->m_nextSystem = mod->m_nextSystem; - else - m_freeModules = mod->m_nextSystem; - - mod->m_type=type; - - // put module on the used list (sorted next to similar types) - nextmod=NULL,prevmod=NULL; - for( nextmod = m_usedModules; nextmod; prevmod=nextmod,nextmod = nextmod->m_nextSystem ) - { - if (nextmod->m_type==type) - { //found start of other shadows using same texture, insert new shadow here. - mod->m_nextSystem=nextmod; - mod->m_prevSystem=prevmod; - nextmod->m_prevSystem=mod; - if (prevmod) - { prevmod->m_nextSystem=mod; - } - else - m_usedModules=mod; - break; - } - } - - if (nextmod==NULL) - { //shadow with new texture. Add to top of list. - mod->m_nextSystem = m_usedModules; - if (m_usedModules) - m_usedModules->m_prevSystem=mod; - m_usedModules = mod; - } - - mod->m_bound=true; - } - - #ifdef SYNC_WAVES - nextmod=m_usedModules; - - while(nextmod) - { - nextmod->m_elapsedMs=nextmod->m_initTimeOffset; - nextmod=nextmod->m_nextSystem; - } - #endif - - return mod; -} - -//============================================================================= -//WaterTracksRenderSystem::unbindTrack -//============================================================================= -/** Called when an object (i.e Tank) will not lay down any more tracks and -doesn't need this object anymore. The track-laying object will be returned -to pool of available tracks as soon as any remaining track edges have faded out. -*/ -//============================================================================= -void WaterTracksRenderSystem::unbindTrack( WaterTracksObj *mod ) -{ - //this object should return to free store as soon as there is nothing - //left to render. - mod->m_bound=false; - releaseTrack(mod); -} - -//============================================================================= -//WaterTracksRenderSystem::releaseTrack -//============================================================================= -/** Returns a track laying object to free store to be used again later. -*/ -void WaterTracksRenderSystem::releaseTrack( WaterTracksObj *mod ) -{ - if (mod==NULL) - return; - - assert(mod->m_bound == false); - - // remove module from used list - if( mod->m_nextSystem ) - mod->m_nextSystem->m_prevSystem = mod->m_prevSystem; - if( mod->m_prevSystem ) - mod->m_prevSystem->m_nextSystem = mod->m_nextSystem; - else - m_usedModules = mod->m_nextSystem; - - // add module to free list - mod->m_prevSystem = NULL; - mod->m_nextSystem = m_freeModules; - if( m_freeModules ) - m_freeModules->m_prevSystem = mod; - m_freeModules = mod; - mod->freeWaterTracksResources(); -} - -//============================================================================= -// WaterTracksRenderSystem::WaterTracksRenderSystem -//============================================================================= -/** Constructor. Just nulls out some variables. */ -//============================================================================= -WaterTracksRenderSystem::WaterTracksRenderSystem() -{ - m_usedModules = NULL; - m_freeModules = NULL; - m_indexBuffer = NULL; - m_vertexMaterialClass = NULL; - m_vertexBuffer = NULL; - m_stripSizeX=WATER_STRIP_X; - m_stripSizeY=WATER_STRIP_Y; - m_batchStart=0; - TheWaterTracksRenderSystem = this; //only allow one instance of this object. -} - -//============================================================================= -// WaterTracksRenderSystem::~WaterTracksRenderSystem -//============================================================================= -/** Destructor. Free all pre-allocated track laying render objects*/ -//============================================================================= -WaterTracksRenderSystem::~WaterTracksRenderSystem( void ) -{ - - // free all data - shutdown(); - - m_vertexMaterialClass=NULL; - -} - -//============================================================================= -// WaterTracksRenderSystem::ReAcquireResources -//============================================================================= -/** (Re)allocates all W3D assets after a reset.. */ -//============================================================================= -void WaterTracksRenderSystem::ReAcquireResources(void) -{ - Int i,j,k; -// const Int numModules=16; ///@todo: Get a value out of gdf - - // just for paranoia's sake. - REF_PTR_RELEASE(m_indexBuffer); - REF_PTR_RELEASE(m_vertexBuffer); - - //Will need m_y-1 strips, each of length m_x*2. - //Will also need 2 extra indices to connect each strip to next one (except last strip) - //Total index buffer size = (m_y-1)*(m_x*2+2) - 2 (drop the extra 2 indices from last strip) - - Int idxCount=(m_stripSizeY-1)*(m_stripSizeX*2+2) - 2; - - m_indexBuffer=NEW_REF(DX8IndexBufferClass,(idxCount)); - - // Fill up the IB - { - DX8IndexBufferClass::WriteLockClass lockIdxBuffer(m_indexBuffer); - UnsignedShort *ib=lockIdxBuffer.Get_Index_Array(); - - for (i=0,j=0,k=0; im_waterPositionZ; - - ReAcquireResources(); - //go with a preset material for now. - m_vertexMaterialClass=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_DIFFUSE); - - //use a multi-texture shader: - m_shaderClass = ShaderClass::_PresetAlphaShader; - m_shaderClass.Set_Cull_Mode(ShaderClass::CULL_MODE_DISABLE); //water should be visible from both sides - - // we cannot initialize a system that is already initialized - if( m_freeModules || m_usedModules ) - { - - // system already online! - assert( 0 ); - return; - - } - - // allocate our modules for this system - for( i = 0; i < numModules; i++ ) - { - - mod = NEW WaterTracksObj; - - if( mod == NULL ) - { - - // unable to allocate modules needed - assert( 0 ); - return; - - } - - mod->m_prevSystem = NULL; - mod->m_nextSystem = m_freeModules; - if( m_freeModules ) - m_freeModules->m_prevSystem = mod; - m_freeModules = mod; - - } - -} - -void WaterTracksRenderSystem::reset(void) -{ - WaterTracksObj *nextMod,*mod; - - //release unbound tracks that may still be fading out - mod=m_usedModules; - - while(mod) - { - nextMod=mod->m_nextSystem; - mod->m_bound=false; - releaseTrack(mod); - - mod = nextMod; - } - - - // free all attached things and used modules - assert( m_usedModules == NULL ); -} - -//============================================================================= -// WaterTracksRenderSystem::shutdown -//============================================================================= -/** Shutdown and free all memory for this system */ -//============================================================================= -void WaterTracksRenderSystem::shutdown( void ) -{ - WaterTracksObj *nextMod,*mod; - - //release unbound tracks that may still be fading out - mod=m_usedModules; - - while(mod) - { - nextMod=mod->m_nextSystem; - - if (!mod->m_bound) - releaseTrack(mod); - - mod = nextMod; - } - - - // free all attached things and used modules - assert( m_usedModules == NULL ); - - // free all module storage - while( m_freeModules ) - { - - nextMod = m_freeModules->m_nextSystem; - delete m_freeModules; - m_freeModules = nextMod; - - } - - REF_PTR_RELEASE(m_indexBuffer); - REF_PTR_RELEASE(m_vertexMaterialClass); - REF_PTR_RELEASE(m_vertexBuffer); - -} - -//============================================================================= -// WaterTracksRenderSystem::update -//============================================================================= -/** Update the state of all active track marks - fade, expire, etc. */ -//============================================================================= -void WaterTracksRenderSystem::update() -{ - - static Int iLastTime=timeGetTime(); - WaterTracksObj *mod=m_usedModules,*nextMod; - - Int timeDiff = timeGetTime()-iLastTime; - iLastTime += timeDiff; - - //first update all the tracks - while( mod ) - { - nextMod = mod->m_nextSystem; - - if (!mod->m_bound || (!mod->update(timeDiff) && !mod->m_bound)) - { //object is not longer updating and is unbound so ok to release it. - releaseTrack(mod); - } - - mod = nextMod; - } -} - - -void TestWaterUpdate(void); -void setFPMode( void ); - -//============================================================================= -// WaterTracksRenderSystem::flush -//============================================================================= -/** Draw all active track marks for this frame */ -//============================================================================= -void WaterTracksRenderSystem::flush(RenderInfoClass & rinfo) -{ -/** @todo: Optimize system by drawing tracks as triangle strips and use dynamic vertex buffer access. -May also try rendering all tracks with one call to W3D/D3D by grouping them by texture. -Try improving the fit to vertical surfaces like cliffs. -*/ - Int diffuseLight; - - if (!TheGlobalData->m_showSoftWaterEdge || TheWaterTransparency->m_transparentWaterDepth ==0 ) - return; - - if (TheGlobalData->m_usingWaterTrackEditor) - TestWaterUpdate(); - - update(); //update positions of all the tracks - - rinfo.Camera.Apply(); - - if (!m_usedModules || ShaderClass::Is_Backface_Culling_Inverted()) - return; //don't render track marks in reflections. - - //According to Nvidia there's a D3D bug that happens if you don't start with a - //new dynamic VB each frame - so we force a DISCARD by overflowing the counter. - m_batchStart = 0xffff; - - // adjust shading for time of day. - Real shadeR, shadeG, shadeB; - shadeR = TheGlobalData->m_terrainAmbient[0].red; - shadeG = TheGlobalData->m_terrainAmbient[0].green; - shadeB = TheGlobalData->m_terrainAmbient[0].blue; - shadeR += TheGlobalData->m_terrainDiffuse[0].red/2; - shadeG += TheGlobalData->m_terrainDiffuse[0].green/2; - shadeB += TheGlobalData->m_terrainDiffuse[0].blue/2; - shadeR*=255.0f; - shadeG*=255.0f; - shadeB*=255.0f; - - diffuseLight=REAL_TO_INT(shadeB) | (REAL_TO_INT(shadeG) << 8) | (REAL_TO_INT(shadeR) << 16); - - Matrix3D tm(1); ///set to identity - DX8Wrapper::Set_Transform(D3DTS_WORLD,tm); //position the water surface - - DX8Wrapper::Set_Material(m_vertexMaterialClass); - DX8Wrapper::Set_Shader(m_shaderClass); - - DX8Wrapper::Set_Vertex_Buffer(m_vertexBuffer); - DX8Wrapper::Set_DX8_Render_State(D3DRS_ZBIAS,8); - //Force apply of render states so we can override them. - DX8Wrapper::Apply_Render_State_Changes(); - - if (TheTerrainRenderObject->getShroud()) - { - W3DShaderManager::setTexture(0,TheTerrainRenderObject->getShroud()->getShroudTexture()); - W3DShaderManager::setShader(W3DShaderManager::ST_SHROUD_TEXTURE, 1); - - //modulate with shroud texture - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLORARG1, D3DTA_TEXTURE ); //stage 1 texture - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLORARG2, D3DTA_CURRENT ); //previous stage texture - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLOROP, D3DTOP_MODULATE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAOP, D3DTOP_MODULATE ); - - //Shroud shader uses z-compare of EQUAL which wouldn't work on water because it doesn't - //write to the zbuffer. Change to LESSEQUAL. - DX8Wrapper::Set_DX8_Render_State(D3DRS_ZFUNC, D3DCMP_LESSEQUAL); - } - - Int LastTextureType=-1; - - WaterTracksObj *mod=m_usedModules; - - while( mod ) - { - if (LastTextureType != mod->m_type) - DX8Wrapper::Set_Texture(0,mod->m_stageZeroTexture); - - Int vertsRendered=mod->render(m_vertexBuffer,m_batchStart); - - m_batchStart = vertsRendered; //advance past vertices already in buffer - - mod = mod->m_nextSystem; - } - - DX8Wrapper::Set_DX8_Render_State(D3DRS_ZBIAS,0); - - if (TheTerrainRenderObject->getShroud()) - { //we used the shroud shader, so reset it. - DX8Wrapper::Set_DX8_Render_State(D3DRS_ZFUNC, D3DCMP_EQUAL); - W3DShaderManager::resetShader(W3DShaderManager::ST_SHROUD_TEXTURE); - } -} - -WaterTracksObj *WaterTracksRenderSystem::findTrack(Vector2 &start, Vector2 &end, waveType type) -{ - WaterTracksObj *mod=m_usedModules; - - while( mod ) - { - if (mod->m_initEndPos == end && - mod->m_initStartPos == start && - mod->m_type == type) - return mod; - mod = mod->m_nextSystem; - } - return NULL; -} -void WaterTracksRenderSystem::saveTracks(void) -{ - - if (!TheTerrainLogic) - return; - - AsciiString fileName=TheTerrainLogic->getSourceFilename(); - char path[256]; - - strlcpy(path, fileName.str(), ARRAY_SIZE(path)); - strlcat(path, ".wak", ARRAY_SIZE(path)); - - WaterTracksObj *umod; - Int trackCount=0; - - FILE *fp=fopen(path,"wb"); - - if (fp) - { - umod=m_usedModules; - while(umod) - { if (umod->m_initTimeOffset == 0) - { //only save the primary wave front, second layer is added automatically. - fwrite(&umod->m_initStartPos,sizeof(umod->m_startPos),1,fp); - fwrite(&umod->m_initEndPos,sizeof(umod->m_perpDir),1,fp); - fwrite(&umod->m_type,sizeof(umod->m_type),1,fp); - // fwrite(&umod->m_initTimeOffset,sizeof(umod->m_initTimeOffset),1,fp); - trackCount++; - } - umod=umod->m_nextSystem; - } - fwrite(&trackCount,sizeof(trackCount),1,fp); - fclose(fp); - } -} - -void WaterTracksRenderSystem::loadTracks(void) -{ - - if (!TheTerrainLogic) - return; - - AsciiString fileName=TheTerrainLogic->getSourceFilename(); - char path[256]; - - strlcpy(path, fileName.str(), ARRAY_SIZE(path)); - strlcat(path, ".wak", ARRAY_SIZE(path)); - - File *file = TheFileSystem->openFile(path, File::READ | File::BINARY); - WaterTracksObj *umod; - Int trackCount=0; - Int flipU=0; - Vector2 startPos,endPos; - waveType wtype; - - if (file) - { - file->seek(-4,File::END); - file->read(&trackCount,sizeof(trackCount)); - file->seek(0, File::START); - for (Int i=0; iread(&startPos,sizeof(startPos)); - file->read(&endPos,sizeof(endPos)); - file->read(&wtype,sizeof(wtype)); - //Check if this track already exists. - if (findTrack(startPos,endPos,wtype)) - { i++; - goto tryagain; - } - - umod=TheWaterTracksRenderSystem->bindTrack(wtype); - if (umod) - { //umod->init(1.5f*MAP_XY_FACTOR,Vector2(0,0),Vector2(1,1),"wave256.tga"); - flipU ^= 1; //toggle flip state - umod->init(waveTypeInfo[wtype].m_finalHeight,waveTypeInfo[wtype].m_finalWidth,startPos,endPos,waveTypeInfo[wtype].m_textureName,0); - umod->m_flipU=flipU; - - if (waveTypeInfo[wtype].m_secondWaveTimeOffset) //check if we need a second wave to follow - { - umod=TheWaterTracksRenderSystem->bindTrack(wtype); - if (umod) - { - umod->init(waveTypeInfo[wtype].m_finalHeight,waveTypeInfo[wtype].m_finalWidth,startPos,endPos,waveTypeInfo[wtype].m_textureName,waveTypeInfo[wtype].m_secondWaveTimeOffset); - umod->m_flipU = !flipU; - } - } - } - } - file->close(); - } - -#if 0 //Obsolete code used before there was another editor to place waves. - //Look for all waypoints that start with "waveStart_" - for (Waypoint *way = TheTerrainLogic->getFirstWaypoint(); way; way = way->getNext()) - { - if (way->getName().startsWith("waveStart_") && way->getNumLinks() == 1) - { - Waypoint *nextWay = way->getLink(0); - Coord3D startPos = *way->getLocation(); - Coord3D endPos = *nextWay->getLocation(); - - //initialize surface layer (1) - WaterTracksObj *umod=TheWaterTracksRenderSystem->bindTrack(1); - if (umod) - { - umod->init(DEFAULT_FINAL_WAVE_HEIGHT,DEFAULT_FINAL_WAVE_WIDTH,Vector2(startPos.x,startPos.y),Vector2(endPos.x,endPos.y),"wave1.tga",0); - } -/* - //initialize foam layer (0) - umod=TheWaterTracksRenderSystem->bindTrack(0); - if (umod) - { - umod->init(2.5f*MAP_XY_FACTOR,5.0f*MAP_XY_FACTOR,Vector2(startPos.x,startPos.y),Vector2(endPos.x,endPos.y),"wave2.tga"); -// umod->m_fadeMs += 1500; //take extra 500 ms to fade out wave. -// umod->m_retreatFrac = 1.0f; //don't move wave back after it hits final position. - }*/ - } - } -#endif -} - -/**@todo: this is a quick hack for adding/removing/testing breaking waves inside the client. -Will need to move this code to an external editor at some pont. */ -#include "GameClient/Display.h" - -extern HWND ApplicationHWnd; - -//TODO: Fix editor so it actually draws the wave segment instead of line while editing -//Could freeze all the water while editing? Or keep setting elapsed time on current segment. -//Have to make it so seamless merge of segments at final position. -static void TestWaterUpdate(void) -{ - static Int doInit=1; - static WaterTracksObj *track=NULL,*track2=NULL; - static Int trackEditMode=0; - static waveType currentWaveType = WaveTypeOcean; - POINT screenPoint; - POINT endPoint; - static POINT mouseAnchor; - static Int haveStart=0; - static Int haveEnd=0; - static Coord3D terrainPointStart,terrainPointEnd; - //flags to tell me when the user lets go of a key - static Int trackEditModeReset=1; - static Int addPointReset=1; - static Int deleteTrackReset=1; - static Int saveTracksReset=1; - static Int loadTracksReset=1; - static Int changeTypeReset=1; - - pauseWaves=FALSE; - - if (doInit) - { //create the system - doInit=0; - -// TheWaterTracksRenderSystem = NEW (WaterTracksRenderSystem); -// TheWaterTracksRenderSystem->init(); - - //create a dummy track -// track=TheWaterTracksRenderObjClassSystem->bindTrack(0); -// track->init(1.5f,8.0f,Vector2(147.0f,67.0f),Vector2(146.9f,68.6f),"wave2.tga"); - -// track=TheWaterTracksRenderObjClassSystem->bindTrack(0); -// track->init(1.5f,8.0f,Vector2(139.0f,66.0f),Vector2(138.8f,67.6f),"wave2.tga"); - } - - if (GetAsyncKeyState(VK_F5) & 0x8001) //check if F5 pressed since last call - { - if (trackEditModeReset) - { - if (trackEditMode) - { - UnicodeString string; - string.format(L"Leaving Water Track Edit Mode"); - TheInGameUI->message(string); - } - else - { - UnicodeString string; - string.format(L"Entering Water Track Edit Mode"); - TheInGameUI->message(string); - - string.format(L"Wave Type: %hs",waveTypeInfo[currentWaveType].m_waveTypeName); - TheInGameUI->message(string); - } - - trackEditMode ^= 1; //toggle editor on/off - - if (trackEditMode == 0) - { //editor was turned off, save changes - haveStart=0; - haveEnd=0; - } - trackEditModeReset=0; - } - } - else - trackEditModeReset=1; - - if (trackEditMode) - { //we are in wave edit mode - - if (GetCursorPos(&screenPoint)) //read mouse position - { - ScreenToClient( ApplicationHWnd, &screenPoint); - - if (GetAsyncKeyState(VK_F6) & 0x8001) - { - if (addPointReset) - { - if (!haveStart) - { mouseAnchor=screenPoint; - TheTacticalView->screenToTerrain( (ICoord2D *)&screenPoint, &terrainPointStart); - haveStart=1; - UnicodeString string; - string.format(L"Added Start"); - TheInGameUI->message(string); - } - else - { - endPoint=screenPoint; - TheTacticalView->screenToTerrain( (ICoord2D *)&screenPoint, &terrainPointEnd); - haveEnd=1; - //Have enough info to add a wave now - track=TheWaterTracksRenderSystem->bindTrack(currentWaveType); - if (track) - {// track->init(1.5f*MAP_XY_FACTOR,Vector2(terrainPointStart.x,terrainPointStart.y),Vector2(terrainPointEnd.x,terrainPointEnd.y),"wave256.tga"); - //Generate valid input for the 2 points - Vector2 startPoint(terrainPointStart.x,terrainPointStart.y); - Vector2 endPoint(terrainPointEnd.x,terrainPointEnd.y); - Vector2 midPoint = endPoint - startPoint; - Vector2 m_perpDir = midPoint; - m_perpDir.Rotate(1.57079632679f); //get vector perpendicular to wave motion. - m_perpDir.Normalize(); - midPoint = startPoint + (midPoint)*0.5f; - Vector2 dirMidPoint = midPoint + m_perpDir; - - track->init(waveTypeInfo[currentWaveType].m_finalHeight,waveTypeInfo[currentWaveType].m_finalWidth,Vector2(midPoint.X,midPoint.Y),Vector2(dirMidPoint.X,dirMidPoint.Y),waveTypeInfo[currentWaveType].m_textureName,0); - - if (waveTypeInfo[currentWaveType].m_secondWaveTimeOffset) - { - //Add a second track slightly behind this one - track2=TheWaterTracksRenderSystem->bindTrack(currentWaveType); - if (track2) - { - track2->init(waveTypeInfo[currentWaveType].m_finalHeight,waveTypeInfo[currentWaveType].m_finalWidth,Vector2(midPoint.X,midPoint.Y),Vector2(dirMidPoint.X,dirMidPoint.Y),waveTypeInfo[currentWaveType].m_textureName,waveTypeInfo[currentWaveType].m_secondWaveTimeOffset); - } - } - - UnicodeString string; - string.format(L"Added End"); - TheInGameUI->message(string); - } - haveStart=0; //reset for next segment - haveEnd=0; - } - addPointReset=0; - } - } - else - addPointReset=1; - - if (GetAsyncKeyState(VK_DELETE) & 0x8001) - { //delete last segment added - if (deleteTrackReset && track) - { deleteTrackReset=0; - TheWaterTracksRenderSystem->unbindTrack(track); - if (track2) - TheWaterTracksRenderSystem->unbindTrack(track2); - haveStart=0; //reset for next segment - haveEnd=0; - track=NULL; - track2=NULL; - } - } - else - deleteTrackReset=1; - - if (GetAsyncKeyState(VK_INSERT) & 0x8001) - { //change current wave type - if (changeTypeReset) - { changeTypeReset=0; - currentWaveType = (waveType)((Int)currentWaveType + 1); - if (currentWaveType > WaveTypeLast) - currentWaveType = WaveTypeFirst; - - UnicodeString string; - string.format(L"Wave Type: %hs",waveTypeInfo[currentWaveType].m_waveTypeName); - TheInGameUI->message(string); - } - } - else - changeTypeReset=1; - - if (GetAsyncKeyState(VK_F7) & 0x8001) - { //save all segments added - if (saveTracksReset) - { saveTracksReset=0; - TheWaterTracksRenderSystem->saveTracks(); - haveStart=0; //reset for next segment - haveEnd=0; - track=NULL; - track2=NULL; - UnicodeString string; - string.format(L"Saved Tracks"); - TheInGameUI->message(string); - } - } - else - saveTracksReset=1; - - if (GetAsyncKeyState(VK_F8) & 0x8001) - { //load tracks for map - if (loadTracksReset) - { loadTracksReset=0; - TheWaterTracksRenderSystem->reset(); - TheWaterTracksRenderSystem->loadTracks(); - haveStart=0; //reset for next segment - haveEnd=0; - track=NULL; - track2=NULL; - UnicodeString string; - string.format(L"Loaded Tracks"); - TheInGameUI->message(string); - } - } - else - saveTracksReset=1; - }; - - if (haveStart && !haveEnd) - { //draw a guide line -// View *tacticalView = TheDisplay->getFirstView(); -// tacticalView->worldToScreen( &m_moveHint[i].pos, &pos ); - - TheTacticalView->screenToTerrain( (ICoord2D *)&screenPoint, &terrainPointEnd); - //Check if point is within correct distance of start - Real xdiff=terrainPointEnd.x - terrainPointStart.x; - Real ydiff=terrainPointEnd.y - terrainPointStart.y; - if (sqrt (xdiff * xdiff + ydiff * ydiff) <= waveTypeInfo[currentWaveType].m_finalWidth) - { TheDisplay->drawLine(mouseAnchor.x, mouseAnchor.y, screenPoint.x, screenPoint.y,1,0xffccccff); - DX8Wrapper::Invalidate_Cached_Render_States(); - ShaderClass::Invalidate(); - } - - pauseWaves=TRUE; - -// char buffer[64]; -// sprintf(buffer,"\n%d,%d,%d,%d",mouseAnchor.x, mouseAnchor.y, screenPoint.x, screenPoint.y); -// OutputDebugString (buffer); - } - } -} diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvp deleted file mode 100644 index 6468dcd0df..0000000000 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvp +++ /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) 2001-2003 Electronic Arts Inc. // -;// // -;//////////////////////////////////////////////////////////////////////////////// - -; Waves pixel shader -; Kenny Mitchell April 2001 -; Modified July 2001 Mark Wilczynski - -; Declare pixel shader version 1.1 -ps.1.1 - -; Define t0 as a standard 3-vector from bumpmap -tex t0 - -; Perform EMBM to get a local normal bump reflection. -texbem t1, t0 ; compute new (u,v) values - -#ifndef DO_WATER_ALPHA_TEXTURE - -; result goes in output color multiplied by diffuse -mul r0, t1, v0 - -#else - -;alternate version which uses a third texture which provides per-pixel alpha. -; result goes in output color multiplied by diffuse -tex t2 ; get alpha texture -mul r0.rgb, t1, v0 -+mul r0.a, t2, v0 - -#endif - - - diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvv b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvv deleted file mode 100644 index c33486962f..0000000000 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvv +++ /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) 2001-2003 Electronic Arts Inc. // -;// // -;//////////////////////////////////////////////////////////////////////////////// - -; Waves vertex shader -; Kenny Mitchell April 2001 -; Modified July 2001 Mark Wilczynski - -#define CV_ZERO 0 -#define CV_ONE 1 - -#define CV_WORLDVIEWPROJ_0 2 -#define CV_WORLDVIEWPROJ_1 3 -#define CV_WORLDVIEWPROJ_2 4 -#define CV_WORLDVIEWPROJ_3 5 - -#define CV_TEXPROJ_0 6 -#define CV_TEXPROJ_1 7 -#define CV_TEXPROJ_2 8 -#define CV_TEXPROJ_3 9 -#define CV_PATCH_SCALE_OFFSET 10 - -#define V_POSITION v0 -#define V_DIFFUSE v1 -#define V_TEXTURE v2 -#define V_TEXTURE2 v3 - -vs.1.1 - -; Below is Kenny's new optimized version -; Transform position to clip space and output it -dp4 r0.x, V_POSITION, c[CV_WORLDVIEWPROJ_0] -dp4 r0.y, V_POSITION, c[CV_WORLDVIEWPROJ_1] -dp4 r0.z, V_POSITION, c[CV_WORLDVIEWPROJ_2] -dp4 r0.w, V_POSITION, c[CV_WORLDVIEWPROJ_3] - -mov oPos, r0 - -; get 1/w and multiply it onto x and y -rcp r1.w, r0.w -mul r1.xy, r0.xy, r1.w - -; scale/flip/offset tex coords to screen -mad oT1.xy, r1.xy, c[CV_TEXPROJ_0].xy,c[CV_TEXPROJ_0].zw - -mov oT0, V_TEXTURE -mov oD0, V_DIFFUSE - -#ifdef DO_WATER_ALPHA_TEXTURE -;generate uv coordinates for a third texture (alpha channel) -mad oT2.xy,v0.xz,c[CV_PATCH_SCALE_OFFSET].zw,c[CV_PATCH_SCALE_OFFSET].xy -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt b/Generals/Code/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt index 01148543c8..0a51c6d964 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt @@ -15,8 +15,8 @@ set(WW3D2_SRC #assetstatus.h #bitmaphandler.cpp #bitmaphandler.h - bmp2d.cpp - bmp2d.h + #bmp2d.cpp + #bmp2d.h boxrobj.cpp boxrobj.h #bwrender.cpp @@ -54,8 +54,8 @@ set(WW3D2_SRC #dx8polygonrenderer.h dx8renderer.cpp dx8renderer.h - dx8texman.cpp - dx8texman.h + #dx8texman.cpp + #dx8texman.h dx8vertexbuffer.cpp dx8vertexbuffer.h #dx8webbrowser.cpp @@ -104,8 +104,8 @@ set(WW3D2_SRC mapper.h #matinfo.cpp #matinfo.h - matpass.cpp - matpass.h + #matpass.cpp + #matpass.h matrixmapper.cpp matrixmapper.h mesh.cpp @@ -195,18 +195,18 @@ set(WW3D2_SRC #stripoptimizer.h #surfaceclass.cpp #surfaceclass.h - texproject.cpp - texproject.h + #texproject.cpp + #texproject.h #textdraw.cpp #textdraw.h - texture.cpp - texture.h - texturefilter.cpp - texturefilter.h - textureloader.cpp - textureloader.h - texturethumbnail.cpp - texturethumbnail.h + #texture.cpp + #texture.h + #texturefilter.cpp + #texturefilter.h + #textureloader.cpp + #textureloader.h + #texturethumbnail.cpp + #texturethumbnail.h vertmaterial.cpp vertmaterial.h #visrasterizer.cpp diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/bmp2d.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/bmp2d.cpp deleted file mode 100644 index 8f0ba147a0..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/bmp2d.cpp +++ /dev/null @@ -1,299 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program. If not, see . -*/ - -/*************************************************************************** - *** C O N F I 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/G * - * * - * $Archive:: /Commando/Code/ww3d2/bmp2d.cpp $* - * * - * $Org Author:: Jani_p $* - * * - * $Author:: Kenny_m $* - * * - * $Modtime:: 08/05/02 10:44a $* - * * - * $Revision:: 12 $* - * * - * 08/05/02 KM Texture class redesign - *-------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "bmp2d.h" -#include "pot.h" -#include "ww3d.h" -#include "texture.h" -#include "surfaceclass.h" -#include "assetmgr.h" -#include "textureloader.h" -#include "ww3dformat.h" - -Bitmap2DObjClass::Bitmap2DObjClass -( - const char *filename, - float screen_x, - float screen_y, - bool center, - bool additive, - bool colorizable, - int usable_width, - int usable_height, - bool ignore_alpha -) - : DynamicScreenMeshClass(2, 4) -{ - - int resw, resh, resbits; - bool windowed; - - // find the resolution (for centering and pixel to pixel translation) - WW3D::Get_Device_Resolution(resw, resh, resbits, windowed); - // This should be the correct way to do things - // but other code expects an aspect ratio of 1.0 - // Hector Yee 2/22/01 - // Set_Aspect(resh/(float)resw); - - - // load up the surfaces file name - TextureClass *tex = WW3DAssetManager::Get_Instance()->Get_Texture(filename, MIP_LEVELS_1); - if (!tex->Is_Initialized()) - TextureLoader::Request_Foreground_Loading(tex); - - SurfaceClass *surface = tex->Get_Surface_Level(0); - - if (!surface) { - surface = NEW_REF(SurfaceClass, (32, 32, Get_Valid_Texture_Format(WW3D_FORMAT_R8G8B8,true))); - } - - SurfaceClass::SurfaceDescription sd; - surface->Get_Description(sd); - - if (usable_width == -1) - usable_width = sd.Width; - if (usable_height == -1) - usable_height = sd.Height; - - // if we requested the image to be centered around a point adjust the - // coordinates accordingly. - if (center) { - screen_x -= ((float)usable_width / resw) / 2; - screen_y -= ((float)usable_height / resh) / 2; - } - - // The image will be broken down into square textures. The size of these - // textures will be the smallest POT (power of two) which is equal or - // greater than the smaller dimension of the image. Also, the pieces can - // never be larger than 256 texels because some rendering devices don't - // support textures larger than that. - int surf_w = usable_width; - int surf_h = usable_height; - int piece = Find_POT(MIN(surf_w, surf_h)); - piece = MIN(piece, 256); - - // now take the image in question and break it down into - // "piece"x"piece"-pixel polygons and calculate the number of textures - // based from those calculations. - int mw = (surf_w & (piece - 1)) ? (surf_w / piece)+1 : (surf_w /piece); - int mh = (surf_h & (piece - 1)) ? (surf_h / piece)+1 : (surf_h /piece); - - // for every square texture it takes four vertexes to express the two - // polygons. - Resize(mw * mh *2, mw * mh * 4); - - // Set shader to additive if requested, else alpha or opaque depending on - // whether the texture has an alpha channel. Sorting is always set so that - // sortbias can be used to determine occlusion between the various 2D - // elements. - ShaderClass shader; - - if (additive) { - shader = ShaderClass::_PresetAdditive2DShader; - } else { - if (ignore_alpha == false && Has_Alpha(sd.Format)) { - shader = ShaderClass::_PresetAlpha2DShader; - } else { - shader = ShaderClass::_PresetOpaque2DShader; - } - } - - Enable_Sort(); - - - // If we want to be able to colorize this bitmap later (by setting - // emissive color for the vertex material, or via a vertex emissive color - // array) we need to enable the primary gradient in the shader (it is - // disabled in the 2D presets), and set an appropriate vertex material. - if (colorizable) { - shader.Set_Primary_Gradient(ShaderClass::GRADIENT_MODULATE); - VertexMaterialClass *vertex_material = NEW_REF( VertexMaterialClass, ()); - vertex_material->Set_Ambient(0.0f, 0.0f, 0.0f); - vertex_material->Set_Diffuse(0.0f, 0.0f, 0.0f); - vertex_material->Set_Specular(0.0f, 0.0f, 0.0f); - vertex_material->Set_Emissive(1.0f, 1.0f, 1.0f); - Set_Vertex_Material(vertex_material, true); - vertex_material->Release_Ref(); - } - - // Set desired shader. - Set_Shader(shader); - - // loop through the rows and columns of the image and make valid - // textures from the pieces. - for (int lpy = 0, tlpy=0; lpy < mh; lpy++, tlpy += piece) { - for (int lpx = 0, tlpx = 0; lpx < mw; lpx++, tlpx += piece) { - - // figure the desired width and height of the texture (max "piece") - int iw = MIN(piece, usable_width - (tlpx)); - int ih = MIN(piece, usable_height - (tlpy)); - int pot = MAX(Find_POT(iw), Find_POT(ih)); - - // create the texture and turn MIP-mapping off. - SurfaceClass *piece_surface=NEW_REF(SurfaceClass,(pot,pot,sd.Format)); - piece_surface->Copy(0,0,tlpx,tlpy,pot,pot,surface); - TextureClass *piece_texture =NEW_REF(TextureClass,(piece_surface,MIP_LEVELS_1)); - piece_texture->Get_Filter().Set_U_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); - piece_texture->Get_Filter().Set_V_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); - REF_PTR_RELEASE(piece_surface); - - // calculate our actual texture coordinates based on the difference between - // the width and height of the texture and the width and height the font - // occupys. - float tw = (float)iw / (float)pot; - float th = (float)ih / (float)pot; - - // convert image width and image height to normalized values - float vw = (float)iw / (float)resw; - float vh = (float)ih / (float)resh; - - // figure out the screen space x and y positions of the object in question. - float x = screen_x + (((float)tlpx) / (float)resw); - float y = screen_y + (((float)tlpy) / (float)resh); - - Set_Texture(piece_texture); - Begin_Tri_Strip(); - Vertex( x, y, 0, 0, 0); - Vertex( x + vw, y, 0, tw, 0); - Vertex( x, y + vh, 0, 0, th); - Vertex( x + vw, y + vh, 0, tw, th); - End_Tri_Strip(); - - // release our reference to the texture - REF_PTR_RELEASE(piece_texture); - } - } - REF_PTR_RELEASE(tex); - REF_PTR_RELEASE(surface); - - Set_Dirty(); -} - -Bitmap2DObjClass::Bitmap2DObjClass -( - TextureClass *texture, - float screen_x, - float screen_y, - bool center, - bool additive, - bool colorizable, - bool ignore_alpha -) - : DynamicScreenMeshClass(2, 4) -{ - int resw, resh, resbits; - bool windowed; - - // find the resolution (for centering and pixel to pixel translation) - WW3D::Get_Device_Resolution(resw, resh, resbits, windowed); - // This should be the correct way to do things - // but other code expects an aspect ratio of 1.0 - // Hector Yee 2/22/01 - //Set_Aspect(resh/(float)resw); - - // Find the dimensions of the texture: -// SurfaceClass::SurfaceDescription sd; -// texture->Get_Level_Description(sd); - - if (!texture->Is_Initialized()) - TextureLoader::Request_Foreground_Loading(texture); - - // convert image width and image height to normalized values - 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. - if (center) { - screen_x -= vw / 2; - screen_y -= vh / 2; - } - - // Set shader to additive if requested, else alpha or opaque depending on whether the texture - // has an alpha channel. Sorting is never set - if you wish to sort these types of objects you - // should use static sort levels (note that static sort levels are not implemented for these - // objects yet, but it should be very simple to do). - ShaderClass shader; - - if (additive) { - shader = ShaderClass::_PresetAdditive2DShader; - } else { - if (ignore_alpha == false && Has_Alpha(texture->Get_Texture_Format())) { - shader = ShaderClass::_PresetAlpha2DShader; - } else { - shader = ShaderClass::_PresetOpaque2DShader; - } - } - Disable_Sort(); - - // If we want to be able to colorize this bitmap later (by setting - // emissive color for the vertex material, or via a vertex emissive color - // array) we need to enable the primary gradient in the shader (it is - // disabled in the 2D presets), and set an appropriate vertex material. - if (colorizable) { - shader.Set_Primary_Gradient(ShaderClass::GRADIENT_MODULATE); - VertexMaterialClass *vertex_material = NEW_REF( VertexMaterialClass, ()); - vertex_material->Set_Ambient(0.0f, 0.0f, 0.0f); - vertex_material->Set_Diffuse(0.0f, 0.0f, 0.0f); - vertex_material->Set_Specular(0.0f, 0.0f, 0.0f); - vertex_material->Set_Emissive(1.0f, 1.0f, 1.0f); - Set_Vertex_Material(vertex_material, true); - vertex_material->Release_Ref(); - } - - // Set desired shader. - Set_Shader(shader); - - // Set texture to requested texture: - Set_Texture(texture); - - Begin_Tri_Strip(); - Vertex( screen_x, screen_y, 0, 0, 0); - Vertex( screen_x + vw, screen_y, 0, 1.0, 0); - Vertex( screen_x, screen_y + vh, 0, 0, 1.0); - Vertex( screen_x + vw, screen_y + vh, 0, 1.0, 1.0); - End_Tri_Strip(); - - Set_Dirty(); -} - -RenderObjClass * Bitmap2DObjClass::Clone(void) const -{ - return NEW_REF( Bitmap2DObjClass, (*this)); -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/bmp2d.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/bmp2d.h deleted file mode 100644 index b09e595ecb..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/bmp2d.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 . -*/ - -/*************************************************************************** - *** C O N F I 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/G * - * * - * $Archive:: /Commando/Code/ww3d2/bmp2d.h $* - * * - * $Author:: Hector_y $* - * * - * $Modtime:: 2/21/01 1:31p $* - * * - * $Revision:: 3 $* - * * - *-------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#pragma once - -#include "dynamesh.h" - -class Bitmap2DObjClass : public DynamicScreenMeshClass -{ - public: - Bitmap2DObjClass(const char *filename, float norm_x, float norm_y, - bool center, bool additive, bool colorizable = false, int width = -1, int height = -1, bool ignore_alpha = false); - Bitmap2DObjClass(TextureClass *texture, float norm_x, float norm_y, - bool center, bool additive, bool colorizable = false, bool ignore_alpha = false); - Bitmap2DObjClass( const Bitmap2DObjClass & src) : DynamicScreenMeshClass(src) {} - - virtual RenderObjClass * Clone(void) const; - virtual int Class_ID(void) const { return CLASSID_BITMAP2D; } -}; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8texman.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8texman.cpp deleted file mode 100644 index 0d66a497ae..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8texman.cpp +++ /dev/null @@ -1,198 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : DX8 Texture Manager * - * * - * $Archive:: /Commando/Code/ww3d2/dx8texman.cpp $* - * * - * Original Author:: Hector Yee * - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 06/27/02 1:27p $* - * * - * $Revision:: 4 $* - * * - * 06/27/02 KM Texture class abstraction * - *---------------------------------------------------------------------------------------------* - * Functions: * - * DX8TextureManagerClass::Shutdown -- Shuts down the texture manager * - * DX8TextureManagerClass::Add -- Adds a texture to be managed * - * DX8TextureManagerClass::Remove -- Removes a texture from being managed * - * DX8TextureManagerClass::Release_Textures -- Releases the internal d3d texture * - * DX8TextureManagerClass::Recreate_Textures -- Reallocates lost textures * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -// This class manages textures that are in the default pool -// ensuring that they are released on device loss -// and created on device reset - -// Note: It does NOT addref to textures because it is called in the texture -// destructor - -#include "dx8texman.h" - -TextureTrackerList DX8TextureManagerClass::Managed_Textures; - - -/*********************************************************************************************** - * DX8TextureManagerClass::Shutdown -- Shuts down the texture manager * - * * - * * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * 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()) - { - TextureTrackerClass *track=Managed_Textures.Remove_Head(); - delete track; - } -} - -/*********************************************************************************************** - * DX8TextureManagerClass::Add -- Adds a texture to be managed * - * * - * * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/25/2001 hy : Created. * - * 5/16/2002 km : Added depth stencil texture tracking and abstraction * - *=============================================================================================*/ -void DX8TextureManagerClass::Add(TextureTrackerClass *track) -{ - // this function should only be called by the texture constructor - Managed_Textures.Add(track); -} - - -/*********************************************************************************************** - * DX8TextureManagerClass::Remove -- Removes a texture from being managed * - * * - * * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/25/2001 hy : Created. * - * 5/16/2002 km : Added depth stencil texture tracking and abstraction * - *=============================================================================================*/ -void DX8TextureManagerClass::Remove(TextureBaseClass *tex) -{ - // this function should only be called by the texture destructor - TextureTrackerListIterator it(&Managed_Textures); - - while (!it.Is_Done()) - { - TextureTrackerClass *track=it.Peek_Obj(); - if (track->Get_Texture()==tex) - { - it.Remove_Current_Object(); - delete track; - break; - } - it.Next(); - } -} - - -/*********************************************************************************************** - * DX8TextureManagerClass::Release_Textures -- Releases the internal d3d texture * - * * - * * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/25/2001 hy : Created. * - * 5/16/2002 km : Added depth stencil texture tracking and abstraction * - *=============================================================================================*/ -void DX8TextureManagerClass::Release_Textures() -{ - TextureTrackerListIterator it(&Managed_Textures); - - while (!it.Is_Done()) - { - TextureTrackerClass *track=it.Peek_Obj(); - track->Release(); - it.Next(); - } -} - - -/*********************************************************************************************** - * DX8TextureManagerClass::Recreate_Textures -- Reallocates lost textures * - * * - * * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/25/2001 hy : Created. * - * 5/16/2002 km : Added depth stencil texture tracking and abstraction * - *=============================================================================================*/ -void DX8TextureManagerClass::Recreate_Textures() -{ - TextureTrackerListIterator it(&Managed_Textures); - - while (!it.Is_Done()) - { - 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 deleted file mode 100644 index bc18832207..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8texman.h +++ /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 : DX8 Texture Manager * - * * - * $Archive:: /Commando/Code/ww3d2/dx8texman.h $* - * * - * Original Author:: Hector Yee * - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 06/27/02 1:27p $* - * * - * $Revision:: 4 $* - * * - * 06/27/02 KM Texture class abstraction * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#pragma once - -#include "always.h" -#include "texture.h" -#include "dx8wrapper.h" -#include "ww3dformat.h" -#include "dx8list.h" -#include "multilist.h" - -class DX8TextureManagerClass; - -class TextureTrackerClass : public MultiListObjectClass -{ -public: - TextureTrackerClass - ( - unsigned int w, - unsigned int h, - MipCountType count, - TextureBaseClass *tex - ) - : Width(w), - Height(h), - Mip_level_count(count), - Texture(tex) - { - } - - 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; - 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; -}; - -class DX8ZTextureTrackerClass : public TextureTrackerClass -{ -public: - DX8ZTextureTrackerClass - ( - unsigned int w, - unsigned int h, - WW3DZFormat zformat, - MipCountType count, - TextureBaseClass* tex - ) - : TextureTrackerClass(w,h,count,tex), ZFormat(zformat) - { - } - - virtual void Recreate() const - { - WWASSERT(Texture->Peek_D3D_Base_Texture()==NULL); - Texture->Poke_Texture - ( - DX8Wrapper::_Create_DX8_ZTexture - ( - Width, - Height, - ZFormat, - Mip_level_count, - D3DPOOL_DEFAULT - ) - ); - } - - -private: - WW3DZFormat ZFormat; -}; - - -class DX8TextureManagerClass -{ -public: - static void Shutdown(); - static void Add(TextureTrackerClass *track); - static void Remove(TextureBaseClass *tex); - static void Release_Textures(); - static void Recreate_Textures(); -private: - static TextureTrackerList Managed_Textures; -}; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/matpass.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/matpass.cpp deleted file mode 100644 index d7fc3aa660..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/matpass.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 : WW3d * - * * - * $Archive:: /Commando/Code/ww3d2/matpass.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 06/27/02 1:27p $* - * * - * $Revision:: 8 $* - * * - * 06/27/02 KM Changes to max texture stage caps * - *---------------------------------------------------------------------------------------------* - * Functions: * - * MaterialPassClass::MaterialPassClass -- Constructor * - * MaterialPassClass::~MaterialPassClass -- Destructor * - * MaterialPassClass::Install_Materials -- Plug our material settings into D3D * - * MaterialPassClass::Set_Texture -- Set texture to use * - * MaterialPassClass::Set_Shader -- Set the shader to use * - * MaterialPassClass::Set_Material -- set vertex material to use * - * MaterialPassClass::Get_Texture -- Get a pointer to the texture * - * MaterialPassClass::Get_Material -- get the vertex material * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "matpass.h" -#include "vertmaterial.h" -#include "shader.h" -#include "texture.h" -#include "statistics.h" -#include "dx8wrapper.h" - - -bool MaterialPassClass::EnablePerPolygonCulling = true; - - -/*********************************************************************************************** - * MaterialPassClass::MaterialPassClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/26/2001 gth : Created. * - *=============================================================================================*/ -MaterialPassClass::MaterialPassClass(void) : - Shader(0), - Material(NULL), - CullVolume(NULL), - EnableOnTranslucentMeshes(true) -{ - for (int i=0; iGet_Max_Textures_Per_Pass();++i) - { - DX8Wrapper::Set_Texture(i,Peek_Texture(i)); - } -} - - -/*********************************************************************************************** - * MaterialPassClass::Set_Texture -- Set texture to use * - * * - * INPUT: * - * tex - pointer to the texture for this material pass (or NULL) * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/9/99 gth : Created. * - *=============================================================================================*/ -void MaterialPassClass::Set_Texture(TextureClass * tex,int stage) -{ - WWASSERT(stage >= 0); - WWASSERT(stage < MAX_TEX_STAGES); - - REF_PTR_SET(Texture[stage],tex); -} - - -/*********************************************************************************************** - * MaterialPassClass::Set_Shader -- Set the shader to use * - * * - * INPUT: * - * shader - shader for this material pass * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/9/99 gth : Created. * - *=============================================================================================*/ -void MaterialPassClass::Set_Shader(ShaderClass shader) -{ - Shader = shader; - Shader.Enable_Fog ("MaterialPassClass"); -} - - -/*********************************************************************************************** - * MaterialPassClass::Set_Material -- set vertex material to use * - * * - * INPUT: * - * mat - pointer to the vertex material this material pass uses * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/9/99 gth : Created. * - *=============================================================================================*/ -void MaterialPassClass::Set_Material(VertexMaterialClass * mat) -{ - REF_PTR_SET(Material,mat); -} - - -/*********************************************************************************************** - * MaterialPassClass::Get_Texture -- Get a pointer to the texture * - * * - * INPUT: * - * * - * OUTPUT: * - * reference counted pointer to the texture this material pass is using * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/9/99 gth : Created. * - *=============================================================================================*/ -TextureClass * MaterialPassClass::Get_Texture(int stage) const -{ - WWASSERT(stage >= 0); - WWASSERT(stage < MAX_TEX_STAGES); - - if (Texture[stage]) { - Texture[stage]->Add_Ref(); - } - return Texture[stage]; -} - - -/*********************************************************************************************** - * MaterialPassClass::Get_Material -- get the vertex material * - * * - * INPUT: * - * * - * OUTPUT: * - * reference counted pointer to the vertex material being used by this material pass * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/9/99 gth : Created. * - *=============================================================================================*/ -VertexMaterialClass * MaterialPassClass::Get_Material(void) const -{ - if (Material) { - Material->Add_Ref(); - } - return Material; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/matpass.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/matpass.h deleted file mode 100644 index afa2226464..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/matpass.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 : ww3d * - * * - * $Archive:: /Commando/Code/ww3d2/matpass.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 06/27/02 1:27p $* - * * - * $Revision:: 6 $* - * * - * 06/27/02 KM Texture class abstraction * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#pragma once - -#include "always.h" -#include "shader.h" - -class TextureClass; -class VertexMaterialClass; -class MeshModelClass; -class OBBoxClass; - -/** -** MaterialPassClass -** -** This class wraps all of the data needed to describe an additional -** material pass for any object. The motivation for this class is to -** implement certain types of special effects. All data needed to -** apply the pass should be generated procedurally. Typically a -** vertex processor will be used to generate any needed u-v's or vertex -** colors. Alternatively, we could add the option to request to -** re-use the model's existing u-v's or vertex colors. -** -** -*/ -class MaterialPassClass : public RefCountClass -{ -public: - - MaterialPassClass(void); - ~MaterialPassClass(void); - - /// MW: Had to make this virtual so app can perform direct/custom D3D setup. - virtual void Install_Materials(void) const; - virtual void UnInstall_Materials(void) const { }; ///< reset/cleanup D3D states - - void Set_Texture(TextureClass * Texture,int stage = 0); - void Set_Shader(ShaderClass shader); - void Set_Material(VertexMaterialClass * mat); - - TextureClass * Get_Texture(int stage = 0) const; - VertexMaterialClass * Get_Material(void) const; - - TextureClass * Peek_Texture(int stage = 0) const; - ShaderClass Peek_Shader(void) const { return Shader; } - VertexMaterialClass * Peek_Material(void) const { return Material; } - - void Set_Cull_Volume(OBBoxClass * volume) { CullVolume = volume; } - OBBoxClass * Get_Cull_Volume(void) const { return CullVolume; } - - void Enable_On_Translucent_Meshes(bool onoff) { EnableOnTranslucentMeshes = onoff; } - bool Is_Enabled_On_Translucent_Meshes(void) { return EnableOnTranslucentMeshes; } - - static void Enable_Per_Polygon_Culling(bool onoff) { EnablePerPolygonCulling = onoff; } - static bool Is_Per_Polygon_Culling_Enabled(void) { return EnablePerPolygonCulling; } - -protected: - - enum { MAX_TEX_STAGES = 8 }; - - TextureClass * Texture[MAX_TEX_STAGES]; - ShaderClass Shader; - VertexMaterialClass * Material; - bool EnableOnTranslucentMeshes; - - OBBoxClass * CullVolume; - static bool EnablePerPolygonCulling; - -}; - - -inline TextureClass * MaterialPassClass::Peek_Texture(int stage) const -{ - WWASSERT(stage >= 0); - WWASSERT(stage < MAX_TEX_STAGES); - return Texture[stage]; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texproject.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texproject.cpp deleted file mode 100644 index 79ea6d9804..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texproject.cpp +++ /dev/null @@ -1,1389 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I 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/texproject.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Kenny Mitchell * - * * - * $Modtime:: 08/05/02 10:03a $* - * * - * $Revision:: 22 $* - * * - * 06/26/02 KM Matrix name change to avoid MAX conflicts * - * 06/27/02 KM Render to shadow buffer texture support * - * 08/05/02 KM Texture class redesign - *---------------------------------------------------------------------------------------------* - * Functions: * - * TexProjectClass::TexProjectClass -- Constructor * - * TexProjectClass::~TexProjectClass -- Destructor * - * TexProjectClass::Set_Texture_Size -- Set the size of texture to use * - * TexProjectClass::Get_Texture_Size -- Returns the stored texture size * - * TexProjectClass::Set_Flag -- Turn specified flag on or off * - * TexProjectClass::Get_Flag -- Get the current state of specified flag * - * TexProjectClass::Set_Intensity -- Set the intensity of this projector * - * TexProjectClass::Get_Intensity -- returns the current "desired" intensity * - * TexProjectClass::Set_Attenuation -- Set the attenuation factor * - * TexProjectClass::Get_Attenuation -- Returns the attenuation value * - * TexProjectClass::Enable_Attenuation -- Set the state of the ATTENUATE flag * - * TexProjectClass::Is_Attenuation_Enabled -- Get the state of the ATTENUATE flag * - * TexProjectClass::Is_Depth_Gradient_Enabled -- returns whether the depth gradient is enabl * - * TexProjectClass::Enable_Depth_Gradient -- enable/disable depth gradient * - * TexProjectClass::Init_Multiplicative -- Initialize this to be a multiplicative texture pr * - * TexProjectClass::Is_Intensity_Zero -- check if we can eliminate this projector * - * TexProjectClass::Init_Additive -- Set up the projector to be additive * - * TexProjectClass::Set_Perspective_Projection -- Set up a perspective projection * - * TexProjectClass::Set_Ortho_Projection -- Set up an orthographic projection * - * TexProjectClass::Set_Texture -- Set the texture to be projected * - * TexProjectClass::Get_Texture -- Returns the texture being projected * - * TexProjectClass::Peek_Texture -- Returns the texture being projected * - * TexProjectClass::Peek_Material_Pass -- Returns the material pass object * - * TexProjectClass::Compute_Perspective_Projection -- Set up a perspective projection of an * - * TexProjectClass::Compute_Perspective_Projection -- Set up a perspective projection of an * - * TexProjectClass::Compute_Ortho_Projection -- Automatic Orthographic projection * - * TexProjectClass::Compute_Ortho_Projection -- Automatic Orthographic projection * - * TexProjectClass::Compute_Texture -- Generates texture by rendering an object * - * TexProjectClass::Configure_Camera -- setup a camera to match this projector * - * TexProjectClass::Pre_Render_Update -- Prepare the projector for rendering * - * TexProjectClass::Update_WS_Bounding_Volume -- Recalculate the world-space bounding box * - * TexProjectClass::Get_Surface -- Returns pointer to the texture surface * - * TexProjectClass::Set_Render_Target -- Install a render target for this projector to use * - * TexProjectClass::Needs_Render_Target -- returns wheter this projector needs a render targ * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "texproject.h" -#include "vertmaterial.h" -#include "shader.h" -#include "texture.h" -#include "rendobj.h" -#include "rinfo.h" -#include "camera.h" -#include "matpass.h" -#include "bwrender.h" -#include "assetmgr.h" -#include "dx8wrapper.h" - - -// DEBUG DEBUG -#include "MPU.h" - -#define DEBUG_SHADOW_RENDERING 0 -//#define DEFAULT_TEXTURE_SIZE 64 - -const float INTENSITY_RATE_OF_CHANGE = 1.0f; // change in intensity per second - - -/* -** -** Shadow mapping: from pre-projected view coordinates back to world space -** then to shadow space -** -** (1) Vshadow = PShadow * Mwrld-shadow * Vwrld -** -** (2) Vview = Mwrld-camera * Vwrld -** -** Using (2) to solve for Vwrld in terms of Vview -** -1 -** (3) Mwrld-camera * Vview = Vwrld -** -** Substituting (3) into (1) -** -1 -** (4) Vshadow = Pshadow * Mwrld-shadow * Mwrld-camera * Vview -** -** --------------------------------------------------------------------------------- -** -** Shadow mapping: from pre-projected view space to world space, to shadow space, -** then projecting. -** -** (1) Vshadow = Mwrld-shadow * Vwrld -** -** (2) Vview = Mwrld-camera * Vwrld -** -** solving (2) for Vwrld: -** -1 -** (3) Mwrld-camera * Vview = Vwrld -** -** substitute into (1) -** -1 -** (4) Vshadow = Mwrld-shadow * Mwrld-camera * Vview -** -** project shadow -** -1 -** (5) Vproj-shadow = Pshadow * (Mwrld-shadow * Mwrld-camera ) * Vview -** -** aaah! same thing :-) -** -** --------------------------------------------------------------------------------- -** -** Shadow mapping: from pre-projected view coordinates back to obj space -** then to shadow space -** -** (1) Vshadow = PShadow * Mwrld-shadow * Mobj-wrld * Vobj -** -** (2) Vview = Mwrld-camera * Mobj-wrld * Vobj -** -1 -1 -** (3) Mobj-wrld * Mwrld-camera * Vview = Vobj -** -1 -1 -** (4) Vshadow = PShadow * Mwrld-shadow * Mobj-wrld * Mobj-wrld * Mwrld-camera * Vview -** -1 -** (5) Vshadow = PShadow * Mwrld-shadow * Mvrld-camera * Vview -** -** -** Ideas: -** - Use Texture Projectors to implement spot lights and stained glass windows -** - Attenuate texture projections with distance from the projector -** - Should be able to handle lots of pre-calculated static texture projectors. They -** should cull well and we can pre-generate the textures. -** -** Ideas maybe used in conjunction with texture projections: -** - Light volumes: the problem is when the volume is cliped it looks funny, we can -** fill in the clipped face of a non-translucent object by rendering the backfaces -** - Use the backface-fill to make the camera slicing through the commando look like -** its *really* slicing through the commando :-) -** - The back-face-fill trick might be able to use el-cheapo screen mapping! -** -*/ - - - -/*********************************************************************************************** - * TexProjectClass::TexProjectClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/4/00 gth : Created. * - *=============================================================================================*/ -TexProjectClass::TexProjectClass(void) : - Flags(DEFAULT_FLAGS), - DesiredIntensity(1.0f), - Intensity(1.0f), - Attenuation(1.0f), - MaterialPass(NULL), - Mapper1(NULL), - RenderTarget(NULL), - DepthStencilTarget(NULL), - HFov(90.0f), - VFov(90.0f), - XMin(-10.0f), - XMax(10.0f), - YMin(-10.0f), - YMax(10.0f), - ZNear(1.0f), - ZFar(1000.0f) -{ - // create a material pass class - MaterialPass = NEW_REF(MaterialPassClass,()); - MaterialPass->Set_Cull_Volume(&WorldBoundingVolume); - - // create a vertex material - VertexMaterialClass * vmtl = NEW_REF(VertexMaterialClass,()); - WWASSERT(vmtl != NULL); - - // Plug our parent's mapper into our vertex material - // the mapper for stage1 will be allocated as needed - vmtl->Set_Mapper(Mapper); - - MaterialPass->Set_Material(vmtl); - vmtl->Release_Ref(); - vmtl = NULL; - - // by default init our material pass to be multiplicative (shadow) - Init_Multiplicative(); -} - - -/*********************************************************************************************** - * TexProjectClass::~TexProjectClass -- Destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/4/00 gth : Created. * - *=============================================================================================*/ -TexProjectClass::~TexProjectClass(void) -{ - REF_PTR_RELEASE(Mapper1); - REF_PTR_RELEASE(MaterialPass); - REF_PTR_RELEASE(RenderTarget); - REF_PTR_RELEASE(DepthStencilTarget); -} - - -/*********************************************************************************************** - * TexProjectClass::Set_Texture_Size -- Set the size of texture to use * - * * - * This function stores the desired texture size in this TexProjectClass. Note that * - * this size is only used if you have the TexProjectClass generate a texture. * - * * - * INPUT: * - * size - dimension of the texture in pixels * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/4/00 gth : Created. * - *=============================================================================================*/ -void TexProjectClass::Set_Texture_Size(int size) -{ - WWASSERT(size > 0); - WWASSERT(size <= 512); - Flags &= ~SIZE_MASK; - Flags |= (size << SIZE_SHIFT); -} - - -/*********************************************************************************************** - * TexProjectClass::Get_Texture_Size -- Returns the stored texture size * - * * - * Returns the size stored in the flags variable. This can be different than the actual * - * texture's size if you manually installed a texture. This size is only used when * - * automatically generating a texture as is the case when creating shadows. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/4/00 gth : Created. * - *=============================================================================================*/ -int TexProjectClass::Get_Texture_Size(void) -{ - return (Flags & SIZE_MASK) >> SIZE_SHIFT; -} - - -/*********************************************************************************************** - * TexProjectClass::Set_Flag -- Turn specified flag on or off * - * * - * See the TexProjectClass header file for valid flags * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/4/00 gth : Created. * - *=============================================================================================*/ -void TexProjectClass::Set_Flag(uint32 flag,bool onoff) -{ - if (onoff) { - Flags |= flag; - } else { - Flags &= ~flag; - } -} - - -/*********************************************************************************************** - * TexProjectClass::Get_Flag -- Get the current state of specified flag * - * * - * See the TexProjectClass header file for valid flags * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/4/00 gth : Created. * - *=============================================================================================*/ -bool TexProjectClass::Get_Flag(uint32 flag) const -{ - return (Flags & flag) == flag; -} - - -/*********************************************************************************************** - * TexProjectClass::Set_Intensity -- Set the intensity of this projector * - * * - * The "intensity" is a value between 0 and 1. At 0, the projector will have no effect * - * At 1, the projector will be at its highest strength. The intensity will automatically * - * smoothly interpolate towards the value specified unless you use the immediate option. * - * * - * INPUT: * - * intensity - desired intensity, 0 <= intensity <= 1 * - * immediate - should the intensity be immediately set to the desired value? (default = false) * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/4/00 gth : Created. * - *=============================================================================================*/ -void TexProjectClass::Set_Intensity(float intensity,bool immediate) -{ - WWASSERT(intensity <= 1.0f); - WWASSERT(intensity >= 0.0f); - - DesiredIntensity = intensity; - if (immediate) { - Intensity = DesiredIntensity; - } -} - - -/*********************************************************************************************** - * TexProjectClass::Get_Intensity -- returns the current "desired" intensity * - * * - * This will return the last value that was sent into this object through Set_Intensity. * - * Note however that the actual intensity used in rendering may not have arrived at * - * that value yet. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/4/00 gth : Created. * - *=============================================================================================*/ -float TexProjectClass::Get_Intensity(void) -{ - return DesiredIntensity; -} - - -/*********************************************************************************************** - * TexProjectClass::Is_Intensity_Zero -- check if we can eliminate this projector * - * * - * Only returns true if the current intensity is zero AND the target intensity is zero * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/4/00 gth : Created. * - *=============================================================================================*/ -bool TexProjectClass::Is_Intensity_Zero(void) -{ - return ((Intensity == 0.0f) && (DesiredIntensity == 0.0f)); -} - - -/*********************************************************************************************** - * TexProjectClass::Set_Attenuation -- Set the attenuation factor * - * * - * Attenuation scales the intensity. I use attenuation to make shadows fade away as they * - * get farther away from the light source or from the viewer. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/4/00 gth : Created. * - *=============================================================================================*/ -void TexProjectClass::Set_Attenuation(float attenuation) -{ - WWASSERT(attenuation >= 0.0f); - WWASSERT(attenuation <= 1.0f); - Attenuation = attenuation; -} - - -/*********************************************************************************************** - * TexProjectClass::Get_Attenuation -- Returns the attenuation value * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/4/00 gth : Created. * - *=============================================================================================*/ -float TexProjectClass::Get_Attenuation(void) -{ - return Attenuation; -} - - -/*********************************************************************************************** - * TexProjectClass::Enable_Attenuation -- Set the state of the ATTENUATE flag * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/4/00 gth : Created. * - *=============================================================================================*/ -void TexProjectClass::Enable_Attenuation(bool onoff) -{ - Set_Flag(ATTENUATE,onoff); -} - - -/*********************************************************************************************** - * TexProjectClass::Is_Attenuation_Enabled -- Get the state of the ATTENUATE flag * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/4/00 gth : Created. * - *=============================================================================================*/ -bool TexProjectClass::Is_Attenuation_Enabled(void) -{ - return Get_Flag(ATTENUATE); -} - - -/*********************************************************************************************** - * TexProjectClass::Enable_Depth_Gradient -- enable/disable depth gradient * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/25/2000 gth : Created. * - *=============================================================================================*/ -void TexProjectClass::Enable_Depth_Gradient(bool onoff) -{ - Set_Flag(USE_DEPTH_GRADIENT,onoff); - - // re-setup the shader settings - if (Get_Flag(ADDITIVE)) { - Init_Additive(); - } else { - Init_Multiplicative(); - } -} - - -/*********************************************************************************************** - * TexProjectClass::Is_Depth_Gradient_Enabled -- returns whether the depth gradient is enabled * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/25/2000 gth : Created. * - *=============================================================================================*/ -bool TexProjectClass::Is_Depth_Gradient_Enabled(bool onoff) -{ - return Get_Flag(USE_DEPTH_GRADIENT); -} - -/*********************************************************************************************** - * TexProjectClass::Init_Multiplicative -- Initialize this to be a multiplicative texture proj * - * * - * Set up the internal materials so that the texture is multiplied with whatever it is * - * projected onto. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/4/00 gth : Created. * - *=============================================================================================*/ -void TexProjectClass::Init_Multiplicative(void) -{ - Set_Flag(ADDITIVE,false); - - /* - ** Set up the shader - */ - static ShaderClass mult_shader( SHADE_CNST( ShaderClass::PASS_LEQUAL, //depth_compare, - ShaderClass::DEPTH_WRITE_DISABLE, //depth_mask, - ShaderClass::COLOR_WRITE_ENABLE, //color_mask, - ShaderClass::SRCBLEND_ZERO, //src_blend, - ShaderClass::DSTBLEND_SRC_COLOR, //dst_blend, - ShaderClass::FOG_DISABLE, //fog, - ShaderClass::GRADIENT_ADD, //pri_grad, - ShaderClass::SECONDARY_GRADIENT_DISABLE, //sec_grad, - ShaderClass::TEXTURING_ENABLE, //texture, - - ShaderClass::ALPHATEST_DISABLE, //alpha_test, - ShaderClass::CULL_MODE_ENABLE, //cull mode - 0, //post_det_color, - 0) ); //post_det_alpha - - if (WW3DAssetManager::Get_Instance()->Get_Activate_Fog_On_Load()) { - mult_shader.Enable_Fog ("TexProjectClass"); - } - - if (Get_Flag(USE_DEPTH_GRADIENT)) { - - /* - ** enable multi-texturing - */ - mult_shader.Set_Post_Detail_Color_Func(ShaderClass::DETAILCOLOR_ADD); - - /* - ** plug the gradient texture into the second stage - */ - TextureClass * grad_tex = WW3DAssetManager::Get_Instance()->Get_Texture("MultProjectorGradient.tga"); - if (grad_tex) { - grad_tex->Get_Filter().Set_U_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); - grad_tex->Get_Filter().Set_V_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); - MaterialPass->Set_Texture(grad_tex,1); - grad_tex->Release_Ref(); - } else { - WWDEBUG_SAY(("Could not find texture: MultProjectorGradient.tga!")); - } - - } else { - - /* - ** disable multi-texturing - */ - mult_shader.Set_Post_Detail_Color_Func(ShaderClass::DETAILCOLOR_DISABLE); - - /* - ** remove the texture from the second stage - */ - MaterialPass->Set_Texture(NULL,1); - } - -#if (DEBUG_SHADOW_RENDERING) - // invert the shader so we can see what polygons it is hitting - mult_shader.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_ONE); - mult_shader.Set_Src_Blend_Func(ShaderClass::SRCBLEND_ONE); -#endif - - MaterialPass->Set_Shader(mult_shader); - - /* - ** Set up the Vertex Material parameters - */ - VertexMaterialClass * vmtl = MaterialPass->Peek_Material(); - vmtl->Set_Ambient(0,0,0); - vmtl->Set_Diffuse(0,0,0); - vmtl->Set_Specular(0,0,0); - vmtl->Set_Emissive(0.0f,0.0f,0.0f); - vmtl->Set_Opacity(1.0f); - vmtl->Set_Lighting(true); // I need the emissive value to scale the intensity of the shadow - - /* - ** Set up some mapper settings related to depth gradient - */ - if (Get_Flag(USE_DEPTH_GRADIENT)) { - if (Mapper1 == NULL) { - Mapper1 = NEW_REF(MatrixMapperClass,(1)); - } - Mapper1->Set_Type(MatrixMapperClass::DEPTH_GRADIENT); - vmtl->Set_Mapper(Mapper1,1); - } else { - vmtl->Set_Mapper(NULL,1); - } -} - - -/*********************************************************************************************** - * TexProjectClass::Init_Additive -- Set up the projector to be additive * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/11/00 gth : Created. * - *=============================================================================================*/ -void TexProjectClass::Init_Additive(void) -{ - Set_Flag(ADDITIVE,true); - - /* - ** Set up the shader - */ - static ShaderClass add_shader( SHADE_CNST( ShaderClass::PASS_LEQUAL, //depth_compare, - ShaderClass::DEPTH_WRITE_DISABLE, //depth_mask, - ShaderClass::COLOR_WRITE_ENABLE, //color_mask, - ShaderClass::SRCBLEND_ONE, //src_blend, - ShaderClass::DSTBLEND_ONE, //dst_blend, - ShaderClass::FOG_DISABLE, //fog, - ShaderClass::GRADIENT_MODULATE, //pri_grad, - ShaderClass::SECONDARY_GRADIENT_DISABLE, //sec_grad, - ShaderClass::TEXTURING_ENABLE, //texture, - ShaderClass::ALPHATEST_DISABLE, //alpha_test, - ShaderClass::CULL_MODE_ENABLE, //cullmode, - ShaderClass::DETAILCOLOR_DISABLE, //post_det_color, - ShaderClass::DETAILALPHA_DISABLE) ); //post_det_alpha - - if (WW3DAssetManager::Get_Instance()->Get_Activate_Fog_On_Load()) { - add_shader.Enable_Fog ("TexProjectClass"); - } - - /* - ** Additive projectors always use the normal gradient so they need multi-texturing - */ - add_shader.Set_Post_Detail_Color_Func(ShaderClass::DETAILCOLOR_SCALE); - - /* - ** plug in the gradient texture - */ - TextureClass * grad_tex = WW3DAssetManager::Get_Instance()->Get_Texture("AddProjectorGradient.tga"); - if (grad_tex) { - grad_tex->Get_Filter().Set_U_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); - grad_tex->Get_Filter().Set_V_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); - MaterialPass->Set_Texture(grad_tex,1); - grad_tex->Release_Ref(); - } else { - WWDEBUG_SAY(("Could not find texture: AddProjectorGradient.tga!")); - } - -#if (DEBUG_SHADOW_RENDERING) - // invert the shader so we can see what polygons it is hitting - add_shader.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_SRC_COLOR); - add_shader.Set_Src_Blend_Func(ShaderClass::SRCBLEND_ZERO); -#endif - - MaterialPass->Set_Shader(add_shader); - - /* - ** Set up the Vertex Material parameters - */ - VertexMaterialClass * vmtl = MaterialPass->Peek_Material(); - vmtl->Set_Ambient(0,0,0); - vmtl->Set_Diffuse(0,0,0); - vmtl->Set_Specular(0,0,0); - vmtl->Set_Emissive(1,1,1); - vmtl->Set_Opacity(1.0f); - vmtl->Set_Lighting(true); //need emissive to scale the intensity of the projector - - /* - ** Set up some mapper settings related to depth gradient - ** Additive texture projections always use the normal gradient - */ - if (Mapper1 == NULL) { - Mapper1 = NEW_REF(MatrixMapperClass,(1)); - } - Mapper1->Set_Type(MatrixMapperClass::NORMAL_GRADIENT); - vmtl->Set_Mapper(Mapper1,1); -} - - -/*********************************************************************************************** - * TexProjectClass::Set_Texture -- Set the texture to be projected * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/11/00 gth : Created. * - *=============================================================================================*/ -void TexProjectClass::Set_Texture(TextureClass * texture) -{ - if (texture != NULL) - { - 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); - } -} - - -/*********************************************************************************************** - * TexProjectClass::Get_Texture -- Returns the texture being projected * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * the pointer is ref-counted! make sure to keep track of your references * - * * - * HISTORY: * - * 1/11/00 gth : Created. * - *=============================================================================================*/ -TextureClass * TexProjectClass::Get_Texture(void) const -{ - return MaterialPass->Get_Texture(); -} - - -/*********************************************************************************************** - * TexProjectClass::Peek_Texture -- Returns the texture being projected * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/11/00 gth : Created. * - *=============================================================================================*/ -TextureClass * TexProjectClass::Peek_Texture(void) const -{ - return MaterialPass->Peek_Texture(); -} - - -/*********************************************************************************************** - * TexProjectClass::Peek_Material_Pass -- Returns the material pass object * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/11/00 gth : Created. * - *=============================================================================================*/ -MaterialPassClass * TexProjectClass::Peek_Material_Pass(void) -{ - return MaterialPass; -} - - -/*********************************************************************************************** - * TexProjectClass::Set_Perspective_Projection -- set up a perspective projection * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/27/00 gth : Created. * - *=============================================================================================*/ -void TexProjectClass::Set_Perspective_Projection(float hfov,float vfov,float znear,float zfar) -{ - HFov = hfov; - VFov = vfov; - ZNear = znear; - ZFar = zfar; - - ProjectorClass::Set_Perspective_Projection(hfov,vfov,znear,zfar); - Set_Flag(PERSPECTIVE,true); -} - - -/*********************************************************************************************** - * TexProjectClass::Set_Ortho_Projection -- set up an orthographic projection * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/27/00 gth : Created. * - *=============================================================================================*/ -void TexProjectClass::Set_Ortho_Projection(float xmin,float xmax,float ymin,float ymax,float znear,float zfar) -{ - XMin = xmin; - XMax = xmax; - YMin = ymin; - YMax = ymax; - ZNear = znear; - ZFar = zfar; - - ProjectorClass::Set_Ortho_Projection(xmin,xmax,ymin,ymax,znear,zfar); - Set_Flag(PERSPECTIVE,false); -} - -/*********************************************************************************************** - * TexProjectClass::Compute_Perspective_Projection -- Set up a perspective projection of an ob * - * * - * This function automates the process of generating the perspective parameters needed to * - * tightly bound the projection of an object. * - * * - * INPUT: * - * model - object which we are created a projection of * - * lightpos - positional light source * - * znear - distance to near clipping plane for the projection (if -1.0, will be generated) * - * zfar - distance to far clipping plane for the projection (if -1.0, will be generated) * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/11/00 gth : Created. * - *=============================================================================================*/ -bool TexProjectClass::Compute_Perspective_Projection -( - RenderObjClass * model, - const Vector3 & lightpos, - float znear, - float zfar -) -{ - if (model == NULL) { - WWDEBUG_SAY(("Attempting to generate projection for a NULL model")); - return false; - } - - AABoxClass box; - model->Get_Obj_Space_Bounding_Box(box); - const Matrix3D & tm = model->Get_Transform(); - - return Compute_Perspective_Projection(box,tm,lightpos,znear,zfar); -} - - -/*********************************************************************************************** - * TexProjectClass::Compute_Perspective_Projection -- Set up a perspective projection of an ob * - * * - * This function automates the process of generating the perspective parameters needed to * - * tightly bound the projection of an object. * - * * - * INPUT: * - * obj_box - object space bounding box of the object we are projecting * - * tm - transform of the object we are projecting * - * lightpos - positional light source * - * user_znear - distance to near clipping plane for the projection (if -1.0, will be generated)* - * user_zfar - distance to far clipping plane for the projection (if -1.0, will be generated) * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/11/00 gth : Created. * - *=============================================================================================*/ -bool TexProjectClass::Compute_Perspective_Projection -( - const AABoxClass & obj_box, - const Matrix3D & tm, - const Vector3 & lightpos, - float user_znear, - float user_zfar -) -{ - /* - ** Compute the center of the box in world-space - */ - Vector3 wrld_center; - Matrix3D::Transform_Vector(tm,obj_box.Center,&wrld_center); - - /* - ** Create a camera transform looking at the object. - ** Set this as our transform later in this routine. - */ - Matrix3D texture_tm,texture_tm_inv; - texture_tm.Look_At(lightpos,wrld_center,0.0f); - texture_tm.Get_Orthogonal_Inverse(texture_tm_inv); - - /* - ** Calculate the axis-aligned bounding box of the model in the camera's coordinate system. - */ - AABoxClass box = obj_box; - Matrix3D obj_to_world = tm; - Matrix3D obj_to_texture; - Matrix3D::Multiply(texture_tm_inv,obj_to_world,&obj_to_texture); - box.Transform(obj_to_texture); - - /* - ** If the box is behind the viewpoint or the viewpoint is inside the box - ** our FOV will be > 180 degrees. Have to give up - */ - if ((box.Center.Z > 0.0f) || (box.Extent.Z > WWMath::Fabs(box.Center.Z))) { - return false; - } - - /* - ** Compute the frustum parameters. Remember that our z coordinates are negative but the - ** projection code needs positive z distances. - */ - float znear = -box.Center.Z; //-(box.Center.Z + obj_box.Extent.Quick_Length()); - float zfar = -(box.Center.Z - obj_box.Extent.Quick_Length()) * 2.0f; - - if (user_znear != -1.0f) { - znear = box.Center.Z + user_znear; - } - if (user_zfar != -1.0f) { - zfar = box.Center.Z + user_zfar; - } - - float tan_hfov2 = WWMath::Fabs(box.Extent.X / (box.Center.Z + box.Extent.Z)); - float tan_vfov2 = WWMath::Fabs(box.Extent.Y / (box.Center.Z + box.Extent.Z)); - float hfov = 2.0f * WWMath::Atan(tan_hfov2); - float vfov = 2.0f * WWMath::Atan(tan_vfov2); - - /* - ** Plug in the results. - */ - Set_Perspective_Projection(hfov,vfov,znear,zfar); - Set_Transform(texture_tm); - return true; -} - - -/*********************************************************************************************** - * TexProjectClass::Compute_Ortho_Projection -- Automatic Orthographic projection * - * * - * Generates the orthographic projection parameters to tightly bound an object * - * * - * INPUT: * - * model - object which we are created a projection of * - * lightdir - directional light source * - * znear - distance to near clipping plane for the projection (if -1.0, will be generated) * - * zfar - distance to far clipping plane for the projection (if -1.0, will be generated) * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/11/00 gth : Created. * - *=============================================================================================*/ -bool TexProjectClass::Compute_Ortho_Projection -( - RenderObjClass * model, - const Vector3 & lightdir, - float znear, - float zfar -) -{ - if (model == NULL) { - WWDEBUG_SAY(("Attempting to generate projection for a NULL model")); - return false; - } - - AABoxClass box; - model->Get_Obj_Space_Bounding_Box(box); - const Matrix3D & tm = model->Get_Transform(); - - return Compute_Ortho_Projection(box,tm,lightdir,znear,zfar); -} - - -/*********************************************************************************************** - * TexProjectClass::Compute_Ortho_Projection -- Automatic Orthographic projection * - * * - * Generates the orthographic projection parameters to tightly bound an object * - * * - * INPUT: * - * obj_box - object space bounding box of the object we are projecting * - * tm - transform of the object we are projecting * - * lightdir - directional light * - * user_znear - distance to near clipping plane for the projection (if -1.0, will be generated)* - * user_zfar - distance to far clipping plane for the projection (if -1.0, will be generated) * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/11/00 gth : Created. * - *=============================================================================================*/ -bool TexProjectClass::Compute_Ortho_Projection -( - const AABoxClass & obj_box, - const Matrix3D & tm, - const Vector3 & lightdir, - float user_znear, - float user_zfar -) -{ - /* - ** Compute the center of the box in world-space - */ - AABoxClass wrldbox = obj_box; - wrldbox.Transform(tm); - - /* - ** Create a camera transform looking at the object. - ** Set this as our transform later in this routine. - */ - Vector3 camera_target = wrldbox.Center; - Vector3 camera_position = camera_target - 2.0f * wrldbox.Extent.Length() * lightdir; - - Matrix3D texture_tm,texture_tm_inv; - texture_tm.Look_At(camera_position,camera_target,0.0f); - texture_tm.Get_Orthogonal_Inverse(texture_tm_inv); - - /* - ** Calculate the axis-aligned bounding box of the model in the camera's coordinate system. - */ - AABoxClass box = obj_box; - Matrix3D obj_to_world = tm; - Matrix3D obj_to_texture; - Matrix3D::Multiply(texture_tm_inv,obj_to_world,&obj_to_texture); - box.Transform(obj_to_texture); - - /* - ** Expand the box to help with bounding box errors - */ - box.Extent *= 1.0f; - - /* - ** Compute the frustum parameters. Note that znear and zfar are supposed to - ** be positive distances for the projection code. - */ - float znear = -box.Center.Z; //-(box.Center.Z + obj_box.Extent.Quick_Length()); - float zfar = -(box.Center.Z - obj_box.Extent.Quick_Length()) * 2.0f; - - if (user_znear != -1.0f) { - znear = -box.Center.Z + user_znear; - } - if (user_zfar != -1.0f) { - zfar = -box.Center.Z + user_zfar; - } - - /* - ** All done! - */ - Set_Ortho_Projection( box.Center.X - box.Extent.X, - box.Center.X + box.Extent.X, - box.Center.Y - box.Extent.Y, - box.Center.Y + box.Extent.Y, - znear, - zfar ); - Set_Transform(texture_tm); - return true; -} - -/*********************************************************************************************** - * TexProjectClass::Compute_Texture -- Generates texture by rendering an object * - * * - * INPUT: * - * model - pointer to the render object to generate a shadow texture for * - * context - shadow render context which has been initialized to resolution * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/11/00 gth : Created. * - * 5/16/02 kjm : Added optional custom depth/stencil target * - *=============================================================================================*/ -bool TexProjectClass::Compute_Texture -( - RenderObjClass * model, - SpecialRenderInfoClass * context -) -{ - if ((model == NULL) || (context == NULL)) - { - return false; - } - /* - ** Render to texture - */ - TextureClass * rtarget=NULL; - ZTextureClass* ztarget=NULL; - - Peek_Render_Target(&rtarget,&ztarget); - - if (rtarget != NULL) - { - // set projector for render context KJM - context->Texture_Projector=this; - - /* - ** Set the render target - */ - DX8Wrapper::Set_Render_Target_With_Z (rtarget,ztarget); - - /* - ** Set up the camera - */ - Configure_Camera(context->Camera); - - /* - ** Render the object - */ - Vector3 color(0.0f,0.0f,0.0f); - if (Get_Flag(ADDITIVE) == false) { - color.Set(1.0f,1.0f,1.0f); - } - - bool zclear=ztarget!=NULL; - - bool snapshot=WW3D::Is_Snapshot_Activated(); - SNAPSHOT_SAY(("TexProjectCLass::Begin_Render()")); - WW3D::Begin_Render(true,zclear,color); // false to zclear as we don't have z-buffer - WW3D::Render(*model,*context); - SNAPSHOT_SAY(("TexProjectCLass::End_Render()")); - WW3D::End_Render(false); - WW3D::Activate_Snapshot(snapshot); // End_Render() ends the shapsnot, so restore the state - - DX8Wrapper::Set_Render_Target((IDirect3DSurface8 *)NULL); - - } - -#if 0 - - /* - ** Render the object with the BW Renderer into our color surface - */ - BWRenderClass bwr((unsigned char*)shadow_surface->getDataPtr(),tex_size); - bwr.Fill(0xff); - context->BWRenderer = &bwr; - model->Special_Render(*context); - context->BWRenderer = NULL; -#endif - return true; -} - - -/*********************************************************************************************** - * TexProjectClass::Needs_Render_Target -- returns wheter this projector needs a render target * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/17/2001 gth : Created. * - *=============================================================================================*/ -bool TexProjectClass::Needs_Render_Target(void) -{ - return Get_Flag(TEXTURE_DIRTY); -} - - -/*********************************************************************************************** - * TexProjectClass::Set_Render_Target -- Install a render target for this projector to use * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/16/2001 gth : Created. * - *=============================================================================================*/ -void TexProjectClass::Set_Render_Target -( - TextureClass* render_target, - ZTextureClass* zbuffer -) -{ - REF_PTR_SET(RenderTarget,render_target); - Set_Texture(RenderTarget); - REF_PTR_SET(DepthStencilTarget,zbuffer); -} - -/*********************************************************************************************** - * TexProjectClass::Peek_Render_Target -- Returns pointer to the render target if we have one * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/5/2001 gth : Created. * - * 5/16/2002 kjm : Added optional custom zbuffer * - *=============================================================================================*/ -TextureClass* TexProjectClass::Peek_Render_Target -( - TextureClass** rtarget, - ZTextureClass** ztarget -) -{ - // some uses of this function just want to know if a render target exists - if (rtarget==NULL) return RenderTarget; - - *rtarget=RenderTarget; - - // don't set if pointer isn't supplied - if (ztarget!=NULL) - *ztarget=DepthStencilTarget; - - return RenderTarget; -} - -/*********************************************************************************************** - * TexProjectClass::Configure_Camera -- set up a camera to match this projector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/11/00 gth : Created. * - *=============================================================================================*/ -void TexProjectClass::Configure_Camera(CameraClass & camera) -{ - camera.Set_Transform(Transform); - camera.Set_Clip_Planes(0.01f,ZFar); - - if (Get_Flag(PERSPECTIVE)) { - camera.Set_Projection_Type(CameraClass::PERSPECTIVE); - camera.Set_View_Plane(HFov,VFov); - - } else { - camera.Set_Projection_Type(CameraClass::ORTHO); - camera.Set_View_Plane(Vector2(XMin,YMin),Vector2(XMax,YMax)); - } - - // Set one-pixel borders to the texture to avoid "flooding" shadows... - float size=Get_Texture_Size(); - float inv_size=1.0f/size; - Vector2 vmin(1.0f*inv_size,1.0f*inv_size); - Vector2 vmax((size-1.0f)*inv_size,(size-1.0f)*inv_size); - camera.Set_Viewport(vmin,vmax); -} - - -/*********************************************************************************************** - * TexProjectClass::Pre_Render_Update -- Prepare the projector for rendering * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/11/00 gth : Created. * - *=============================================================================================*/ -void TexProjectClass::Pre_Render_Update(const Matrix3D & camera) -{ - /* - ** Mview-texture = PShadow * Mwrld-texture * Mcamera-vrld - */ - Matrix3D world_to_texture; - Matrix3D tmp; - Matrix4x4 view_to_texture; - - Transform.Get_Orthogonal_Inverse(world_to_texture); - Matrix3D::Multiply(world_to_texture,camera,&tmp); - Matrix4x4::Multiply(Projection,tmp,&view_to_texture); - - /* - ** update the current intensity by iterating it towards the desired intensity - */ - float intensity_delta = DesiredIntensity - Intensity; - float max_intensity_delta = INTENSITY_RATE_OF_CHANGE * WW3D::Get_Logic_Frame_Time_Seconds(); - - if (intensity_delta > max_intensity_delta) { - Intensity += max_intensity_delta; - } else if (intensity_delta < -max_intensity_delta) { - Intensity -= max_intensity_delta; - } else { - Intensity = DesiredIntensity; - } - - float actual_intensity = Intensity * Attenuation; - - /* - ** install the current intensity - */ - VertexMaterialClass * vmat = MaterialPass->Peek_Material(); - if (Get_Flag(ADDITIVE)) { - vmat->Set_Emissive(actual_intensity,actual_intensity,actual_intensity); - } else { - vmat->Set_Emissive(1.0f - actual_intensity,1.0f - actual_intensity,1.0f - actual_intensity); - } - - /* - ** update the mappers - */ - if (Get_Flag(PERSPECTIVE)) { - Mapper->Set_Type(MatrixMapperClass::PERSPECTIVE_PROJECTION); - } 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()); - } -} - - -/*********************************************************************************************** - * TexProjectClass::Update_WS_Bounding_Volume -- Recalculate the world-space bounding box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/11/00 gth : Created. * - *=============================================================================================*/ -void TexProjectClass::Update_WS_Bounding_Volume(void) -{ - ProjectorClass::Update_WS_Bounding_Volume(); - - /* - ** Tell our culling system that we've changed - */ - Vector3 extent; - WorldBoundingVolume.Compute_Axis_Aligned_Extent(&extent); - Set_Cull_Box(AABoxClass(WorldBoundingVolume.Center,extent)); -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texproject.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texproject.h deleted file mode 100644 index 0ad5aa9efd..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texproject.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 . -*/ - -/*********************************************************************************************** - *** C O N F I 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/texproject.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Kenny Mitchell * - * * - * $Modtime:: 06/26/02 4:04p $* - * * - * $Revision:: 8 $* - * * - * 06/27/02 KM Render to shadow buffer texture support * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#pragma once - -#include "always.h" -#include "matrix3d.h" -#include "matrix4.h" -#include "obbox.h" -#include "matpass.h" -#include "matrixmapper.h" -#include "cullsys.h" -#include "multilist.h" -#include "projector.h" - - -class SpecialRenderInfoClass; -class RenderObjClass; -class MaterialPassClass; -class SurfaceClass; - -class TextureClass; -class ZTextureClass; - - -/** -** TexProjectClass -** This class is used to project textures onto object in the world. It contains -** a pointer to the texture to be projected, a bounding volume for the projection, -** and a material pass which can perform the projection. -** -** Design Goals: -** - Texture Projectors should be easy to place in the world and move around. -** solution: Store the bounding volume and any other parameters in a coordinate -** system local to the projector. Update the world-space cache whenever needed. -** The automatically generated shadow texture projectors are a special case subset -** of the general texture projection code. For this reason, a local bounding -** volume will be stored and its world-space equivalent will be updated whenever -** needed. -** -** - Texture projectors need to be compatible with the culling systems. -** solution: inherit the Cullable interface. -** -** - Texture projectors need to be quickly pulled in and out of many lists during -** the rendering process. -** solution: list system similar to PhysListClass? I really need to templatize this. -** - done: MultiListClass! -** -** - Dynamic Texture projectors need to be updated in stages. Update/recompute only the -** bounding volume first, then defer computing the actual texture until it is -** determined that the volume falls into the frustum and is applied to at least one -** object. -** solution: Code the bounding volume/projection paramter generation separate from -** the texture generation code. A derived texture projection object. Let texture -** projectors know about the object they are projecting so that they can have that -** object rendered from the desired viewpoint. Need a 'Dirty' flag and a pointer to -** a 'parent' object. Perhaps separate this code into a ShadowProjectClass since shadows -** are the only case I can think of that need the ability to re-render their 'parent' -** object. Everything else should be a static texture-map either generated 'artistically' -** or generated off-line. -** -*/ -class TexProjectClass : public ProjectorClass, public CullableClass, public MultiListObjectClass -{ -public: - - TexProjectClass(void); - virtual ~TexProjectClass(void); - - /* - ** Material settings - */ - void Set_Texture_Size(int size); - int Get_Texture_Size(void); - void Init_Multiplicative(void); - void Init_Additive(void); - void Set_Intensity(float intensity,bool immediate = false); // 1.0 = on 100%, 0.0 = 'off' - float Get_Intensity(void); - bool Is_Intensity_Zero(void); - void Set_Attenuation(float attenuation); // 1.0 = on, 0.0 = off - float Get_Attenuation(void); - void Enable_Attenuation(bool onoff); - bool Is_Attenuation_Enabled(void); - MaterialPassClass * Peek_Material_Pass(void); - - /* - ** Options - */ - void Enable_Affect_Dynamic_Objects(bool onoff) { Set_Flag(AFFECT_DYNAMIC_OBJS,onoff); } - bool Is_Affect_Dynamic_Objects_Enabled(void) { return Get_Flag(AFFECT_DYNAMIC_OBJS); } - void Enable_Affect_Static_Objects(bool onoff) { Set_Flag(AFFECT_STATIC_OBJS,onoff); } - bool Is_Affect_Static_Objects_Enabled(void) { return Get_Flag(AFFECT_STATIC_OBJS); } - void Enable_Depth_Gradient(bool onoff); - bool Is_Depth_Gradient_Enabled(bool onoff); - - /* - ** Manual initialization of a TexProjectClass - ** 1 - call ProjectorClass::Set_Transform - ** 2 - call Set_Projection_Perspective -or- Set_Projection_Ortho - ** 3 - call Set_Texture. - */ - 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); - - void Set_Texture(TextureClass * texture); - TextureClass * Get_Texture(void) const; - TextureClass * Peek_Texture(void) const; - - - void Set_DepthStencilBuffer(ZTextureClass* ztex); - ZTextureClass* Get_DepthStencilBuffer() const; - ZTextureClass* Peek_DepthStencilBuffer() const; - - /* - ** Automatic initialization of a TexProjectClass. - ** First set up your projection parameters, give the projector a render target, then call Compute_Texture - */ - bool Compute_Perspective_Projection(RenderObjClass * obj,const Vector3 & lightpos,float znear=-1.0f,float zfar=-1.0f); - bool Compute_Perspective_Projection(const AABoxClass & obj_box,const Matrix3D & tm,const Vector3 & lightpos,float znear=-1.0f,float zfar=-1.0f); - - bool Compute_Ortho_Projection(RenderObjClass * obj,const Vector3 & lightdir,float znear=-1.0f,float zfar=-1.0f); - bool Compute_Ortho_Projection(const AABoxClass & obj_box,const Matrix3D & tm,const Vector3 & lightdir,float znear=-1.0f,float zfar=-1.0f); - - bool Needs_Render_Target(void); - void Set_Render_Target(TextureClass* render_target, ZTextureClass* ztarget=NULL); - TextureClass* Peek_Render_Target(TextureClass** rtarget=NULL, ZTextureClass** ztarget=NULL); - - bool Compute_Texture(RenderObjClass * model,SpecialRenderInfoClass * context); - - /* - ** Prep for rendering, called by the scene prior to usage. - */ - virtual void Pre_Render_Update(const Matrix3D & camera); - - /* - ** virtual interface for getting the pointer of the object that generated this shadow. - ** defaults to returning NULL. This is implemented by some derived classes and used by - ** the system to prevent a projection from being applied to the object that generated - ** the projection... - ** (gth) feels kludgy, this got a little messy when I moved this code into WW3D from WWPhys - */ - virtual void * Get_Projection_Object_ID(void) const { return NULL; } - -protected: - - void Set_Flag(uint32 flag,bool onoff); - bool Get_Flag(uint32 flag) const; - virtual void Update_WS_Bounding_Volume(void); - void Configure_Camera(CameraClass & camera); - - enum FlagsType - { - PERSPECTIVE = 0x00000001, // PERSPECTIVE or ORTHO - ADDITIVE = 0x00000002, // ADDITIVE or MULTIPLICATIVE - TEXTURE_DIRTY = 0x00000004, // used by derived DynTexProjectClass - VOLATILE = 0x00000008, // this is a volatile texture. - ATTENUATE = 0x00000010, // this projector should be attenuated based on distance to viewer - AFFECT_DYNAMIC_OBJS = 0x00000020, // this projector affects dynamic objects - AFFECT_STATIC_OBJS = 0x00000040, // this projector affects static objects - USE_DEPTH_GRADIENT = 0x00000080, // fade the projection as a function of depth - HAS_RENDER_TARGET = 0x00000100, // the texture we have can be a render target - SIZE_MASK = 0xFFF00000, // desired texture size stored in upper 3 nibbles - SIZE_SHIFT = 20, - - DEFAULT_FLAGS = ATTENUATE | AFFECT_DYNAMIC_OBJS | AFFECT_STATIC_OBJS - }; - - uint32 Flags; - - /* - ** Intensity Controls - */ - float DesiredIntensity; // last input desired intensity. - float Intensity; // basic shadow intensity. value between 0 and 1 - float Attenuation; // attenuation factor based on distance from camera. value between 0 and 1 - - /* - ** Material pass to be added to any object that intersects the volume - */ - MaterialPassClass * MaterialPass; - MatrixMapperClass * Mapper1; - TextureClass * RenderTarget; - ZTextureClass* DepthStencilTarget; - - /* - ** I have to remember all of these values so that I can properly initialize a CameraClass - ** when we do render-to-texture. Some day we will merge CameraClass and ProjectorClass. - */ - float HFov; // horizontal fov (for perspective mode) - float VFov; // vertical fov (for perspective mode) - float XMin; // left x clip plane (for ortho) - float XMax; // right x clip plane (for ortho) - float YMin; // bottom y clip plane (for ortho) - float YMax; // top y clip plane (for ortho) - float ZNear,ZFar; // z clip planes (for both modes) -}; - - -/* -** Texture Projector Lists -*/ -typedef RefMultiListClass TexProjListClass; -typedef RefMultiListIterator TexProjListIterator; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texture.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texture.cpp deleted file mode 100644 index cbd16fb276..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texture.cpp +++ /dev/null @@ -1,1908 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I 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/texture.cpp $* - * * - * $Org Author:: Steve_t $* - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 08/05/02 1:27p $* - * * - * $Revision:: 85 $* - * * - * 06/27/02 KM Texture class abstraction * - * 08/05/02 KM Texture class redesign (revisited) - *---------------------------------------------------------------------------------------------* - * Functions: * - * FileListTextureClass::Load_Frame_Surface -- Load source texture * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "texture.h" - -#include -#include -#include "dx8wrapper.h" -#include "TARGA.h" -#include -#include "w3d_file.h" -#include "assetmgr.h" -#include "formconv.h" -#include "textureloader.h" -#include "missingtexture.h" -#include "ffactory.h" -#include "dx8caps.h" -#include "dx8texman.h" -#include "meshmatdesc.h" -#include "texturethumbnail.h" -#include "wwprofile.h" - -const unsigned DEFAULT_INACTIVATION_TIME=20000; - -/* -** Definitions of static members: -*/ - -static unsigned unused_texture_id; - -// This throttles submissions to the background texture loading queue. -static unsigned TexturesAppliedPerFrame; -const unsigned MAX_TEXTURES_APPLIED_PER_FRAME=2; - - -/*! - * KM General base constructor for texture classes - */ -TextureBaseClass::TextureBaseClass -( - unsigned int width, - unsigned int height, - enum MipCountType mip_level_count, - enum PoolType pool, - bool rendertarget, - bool reducible -) -: MipLevelCount(mip_level_count), - D3DTexture(NULL), - Initialized(false), - Name(""), - FullPath(""), - texture_id(unused_texture_id++), - IsLightmap(false), - IsProcedural(false), - IsReducible(reducible), - IsCompressionAllowed(false), - InactivationTime(0), - ExtendedInactivationTime(0), - LastInactivationSyncTime(0), - LastAccessed(0), - Width(width), - Height(height), - Pool(pool), - Dirty(false), - TextureLoadTask(NULL), - ThumbnailLoadTask(NULL), - HSVShift(0.0f,0.0f,0.0f) -{ -} - - -//********************************************************************************************** -//! Base texture class destructor -/*! KJM -*/ -TextureBaseClass::~TextureBaseClass(void) -{ - delete TextureLoadTask; - TextureLoadTask=NULL; - delete ThumbnailLoadTask; - ThumbnailLoadTask=NULL; - - if (D3DTexture) - { - D3DTexture->Release(); - D3DTexture = NULL; - } - - DX8TextureManagerClass::Remove(this); -} - - - - -//********************************************************************************************** -//! Invalidate old unused textures -/*! -*/ -void TextureBaseClass::Invalidate_Old_Unused_Textures(unsigned invalidation_time_override) -{ - // (gth) If thumbnails are not enabled, then we don't run this code. - if (WW3D::Get_Thumbnail_Enabled() == false) { - return; - } - - // Zero the texture apply count in this function because this is called every frame...(this wasn't in E&B main branch KJM) - TexturesAppliedPerFrame=0; - - unsigned synctime=WW3D::Get_Sync_Time(); - HashTemplateIterator ite(WW3DAssetManager::Get_Instance()->Texture_Hash()); - // Loop through all the textures in the manager - - for (ite.First ();!ite.Is_Done();ite.Next ()) - { - TextureClass* tex=ite.Peek_Value(); - - // Consider invalidating if texture has been initialized and defines inactivation time - if (tex->Initialized && tex->InactivationTime) - { - unsigned age=synctime-tex->LastAccessed; - - if (invalidation_time_override) - { - if (age>invalidation_time_override) - { - tex->Invalidate(); - tex->LastInactivationSyncTime=synctime; - } - } - else - { - // Not used in the last n milliseconds? - if (age>(tex->InactivationTime+tex->ExtendedInactivationTime)) - { - tex->Invalidate(); - tex->LastInactivationSyncTime=synctime; - } - } - } - } -} - - - - - -//********************************************************************************************** -//! Invalidate this texture -/*! -*/ -void TextureBaseClass::Invalidate() -{ - if (TextureLoadTask) { - return; - } - if (ThumbnailLoadTask) { - return; - } - - // Don't invalidate procedural textures - if (IsProcedural) { - return; - } - - if (D3DTexture) - { - D3DTexture->Release(); - D3DTexture = NULL; - } - - Initialized=false; - - LastAccessed=WW3D::Get_Sync_Time(); -/* was battlefield version// If the texture has already been initialised we should exit now - if (Initialized) return; - - WWPROFILE(("TextureClass::Init()")); - - // If the texture has recently been inactivated, increase the inactivation time (this texture obviously - // should not have been inactivated yet). - - if (InactivationTime && LastInactivationSyncTime) { - if ((WW3D::Get_Sync_Time()-LastInactivationSyncTime)Release(); - D3DTexture = NULL; - } - - Initialized=false; - - LastAccessed=WW3D::Get_Sync_Time();*/ -} - -//********************************************************************************************** -//! Returns a pointer to the d3d texture -/*! -*/ -IDirect3DBaseTexture8 * TextureBaseClass::Peek_D3D_Base_Texture() const -{ - LastAccessed=WW3D::Get_Sync_Time(); - return D3DTexture; -} - -//********************************************************************************************** -//! Set the d3d texture pointer. Handles ref counts properly. -/*! -*/ -void TextureBaseClass::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(); - } -} - - -//********************************************************************************************** -//! Load locked surface -/*! -*/ -void TextureBaseClass::Load_Locked_Surface() -{ - WWPROFILE(("TextureClass::Load_Locked_Surface()")); - if (D3DTexture) D3DTexture->Release(); - D3DTexture=0; - TextureLoader::Request_Thumbnail(this); - Initialized=false; -} - - -//********************************************************************************************** -//! Is missing texture -/*! -*/ -bool TextureBaseClass::Is_Missing_Texture() -{ - bool flag = false; - IDirect3DBaseTexture8 *missing_texture = MissingTexture::_Get_Missing_Texture(); - - if (D3DTexture == missing_texture) - flag = true; - - if (missing_texture) - { - missing_texture->Release(); - } - - return flag; -} - - -//********************************************************************************************** -//! Set texture name -/*! -*/ -void TextureBaseClass::Set_Texture_Name(const char * name) -{ - Name=name; -} - - - - -//********************************************************************************************** -//! Get priority -/*! -*/ -unsigned int TextureBaseClass::Get_Priority(void) -{ - if (!D3DTexture) - { - WWASSERT_PRINT(0, "Get_Priority: D3DTexture is NULL!"); - return 0; - } - -#ifndef _XBOX - return D3DTexture->GetPriority(); -#else - return 0; -#endif -} - - -//********************************************************************************************** -//! Set priority -/*! -*/ -unsigned int TextureBaseClass::Set_Priority(unsigned int priority) -{ - if (!D3DTexture) - { - WWASSERT_PRINT(0, "Set_Priority: D3DTexture is NULL!"); - return 0; - } - -#ifndef _XBOX - return D3DTexture->SetPriority(priority); -#else - return 0; -#endif -} - - -//********************************************************************************************** -//! Get reduction mip levels -/*! -*/ -unsigned TextureBaseClass::Get_Reduction() const -{ - // don't reduce if the texture is too small already or - // has no mip map levels - if (MipLevelCount==MIP_LEVELS_1) return 0; - if (Width <= 32 || Height <= 32) return 0; - - int reduction=WW3D::Get_Texture_Reduction(); - - // 'large texture extra reduction' causes textures above 256x256 to be reduced one more step. - if (WW3D::Is_Large_Texture_Extra_Reduction_Enabled() && (Width > 256 || Height > 256)) { - reduction++; - } - if (MipLevelCount && reduction>MipLevelCount) { - reduction=MipLevelCount; - } - return reduction; -} - - - -//********************************************************************************************** -//! Apply NULL texture state -/*! -*/ -void TextureBaseClass::Apply_Null(unsigned int stage) -{ - // This function sets the render states for a "NULL" texture - DX8Wrapper::Set_DX8_Texture(stage, NULL); -} - -// ---------------------------------------------------------------------------- -// Setting HSV_Shift value is always relative to the original texture. This function invalidates the -// texture surface and causes the texture to be reloaded. For thumbnailable textures, the hue shifting -// is done in the background loading thread. -// ---------------------------------------------------------------------------- -void TextureBaseClass::Set_HSV_Shift(const Vector3 &hsv_shift) -{ - Invalidate(); - HSVShift=hsv_shift; -} - -//********************************************************************************************** -//! Get total locked surface size -/*! KM -*/ -int TextureBaseClass::_Get_Total_Locked_Surface_Size() -{ - int total_locked_surface_size=0; - - HashTemplateIterator ite(WW3DAssetManager::Get_Instance()->Texture_Hash()); - // Loop through all the textures in the manager - for (ite.First ();!ite.Is_Done();ite.Next ()) - { - // Get the current texture - TextureBaseClass* tex=ite.Peek_Value(); - if (!tex->Initialized) - { - total_locked_surface_size+=tex->Get_Texture_Memory_Usage(); - } - } - return total_locked_surface_size; -} - -//********************************************************************************************** -//! Get total texture size -/*! KM -*/ -int TextureBaseClass::_Get_Total_Texture_Size() -{ - int total_texture_size=0; - - HashTemplateIterator ite(WW3DAssetManager::Get_Instance()->Texture_Hash()); - // Loop through all the textures in the manager - for (ite.First ();!ite.Is_Done();ite.Next ()) - { - // Get the current texture - TextureBaseClass* tex=ite.Peek_Value(); - total_texture_size+=tex->Get_Texture_Memory_Usage(); - } - return total_texture_size; -} - -// ---------------------------------------------------------------------------- - - -//********************************************************************************************** -//! Get total lightmap texture size -/*! -*/ -int TextureBaseClass::_Get_Total_Lightmap_Texture_Size() -{ - int total_texture_size=0; - - HashTemplateIterator ite(WW3DAssetManager::Get_Instance()->Texture_Hash()); - // Loop through all the textures in the manager - for (ite.First ();!ite.Is_Done();ite.Next ()) - { - // Get the current texture - TextureBaseClass* tex=ite.Peek_Value(); - if (tex->Is_Lightmap()) - { - total_texture_size+=tex->Get_Texture_Memory_Usage(); - } - } - return total_texture_size; -} - - -//********************************************************************************************** -//! Get total procedural texture size -/*! -*/ -int TextureBaseClass::_Get_Total_Procedural_Texture_Size() -{ - int total_texture_size=0; - - HashTemplateIterator ite(WW3DAssetManager::Get_Instance()->Texture_Hash()); - // Loop through all the textures in the manager - for (ite.First ();!ite.Is_Done();ite.Next ()) - { - // Get the current texture - TextureBaseClass* tex=ite.Peek_Value(); - if (tex->Is_Procedural()) - { - total_texture_size+=tex->Get_Texture_Memory_Usage(); - } - } - return total_texture_size; -} - -//********************************************************************************************** -//! Get total texture count -/*! -*/ -int TextureBaseClass::_Get_Total_Texture_Count() -{ - int texture_count=0; - - HashTemplateIterator ite(WW3DAssetManager::Get_Instance()->Texture_Hash()); - // Loop through all the textures in the manager - for (ite.First ();!ite.Is_Done();ite.Next ()) - { - texture_count++; - } - - return texture_count; -} - -// ---------------------------------------------------------------------------- - - -//********************************************************************************************** -//! Get total light map texture count -/*! -*/ -int TextureBaseClass::_Get_Total_Lightmap_Texture_Count() -{ - int texture_count=0; - - HashTemplateIterator ite(WW3DAssetManager::Get_Instance()->Texture_Hash()); - // Loop through all the textures in the manager - for (ite.First ();!ite.Is_Done();ite.Next ()) - { - if (ite.Peek_Value()->Is_Lightmap()) - { - texture_count++; - } - } - - return texture_count; -} - -//********************************************************************************************** -//! Get total procedural texture count -/*! -*/ -int TextureBaseClass::_Get_Total_Procedural_Texture_Count() -{ - int texture_count=0; - - HashTemplateIterator ite(WW3DAssetManager::Get_Instance()->Texture_Hash()); - // Loop through all the textures in the manager - for (ite.First ();!ite.Is_Done();ite.Next ()) - { - if (ite.Peek_Value()->Is_Procedural()) - { - texture_count++; - } - } - - return texture_count; -} - - -//********************************************************************************************** -//! Get total locked surface count -/*! -*/ -int TextureBaseClass::_Get_Total_Locked_Surface_Count() -{ - int texture_count=0; - - HashTemplateIterator ite(WW3DAssetManager::Get_Instance()->Texture_Hash()); - // Loop through all the textures in the manager - for (ite.First ();!ite.Is_Done();ite.Next ()) - { - // Get the current texture - TextureBaseClass* tex=ite.Peek_Value(); - if (!tex->Initialized) - { - texture_count++; - } - } - - return texture_count; -} - -/************************************************************************* -** TextureClass -*************************************************************************/ -TextureClass::TextureClass -( - unsigned width, - unsigned height, - WW3DFormat format, - MipCountType mip_level_count, - PoolType pool, - bool rendertarget, - bool allow_reduction -) -: TextureBaseClass(width, height, mip_level_count, pool, rendertarget,allow_reduction), - Filter(mip_level_count), - TextureFormat(format) -{ - Initialized=true; - IsProcedural=true; - IsReducible=false; - - switch (format) - { - case WW3D_FORMAT_DXT1: - case WW3D_FORMAT_DXT2: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: - IsCompressionAllowed=true; - break; - default : break; - } - - D3DPOOL d3dpool=(D3DPOOL)0; - switch(pool) - { - case POOL_DEFAULT : d3dpool=D3DPOOL_DEFAULT; break; - case POOL_MANAGED : d3dpool=D3DPOOL_MANAGED; break; - case POOL_SYSTEMMEM : d3dpool=D3DPOOL_SYSTEMMEM; break; - default: WWASSERT(0); - } - - Poke_Texture - ( - DX8Wrapper::_Create_DX8_Texture - ( - width, - height, - format, - mip_level_count, - d3dpool, - rendertarget - ) - ); - - if (pool==POOL_DEFAULT) - { - Set_Dirty(); - DX8TextureTrackerClass *track=new DX8TextureTrackerClass - ( - width, - height, - format, - mip_level_count, - this, - rendertarget - ); - DX8TextureManagerClass::Add(track); - } - LastAccessed=WW3D::Get_Sync_Time(); -} - - - -// ---------------------------------------------------------------------------- -TextureClass::TextureClass -( - const char *name, - const char *full_path, - MipCountType mip_level_count, - WW3DFormat texture_format, - bool allow_compression, - bool allow_reduction -) -: TextureBaseClass(0, 0, mip_level_count), - Filter(mip_level_count), - TextureFormat(texture_format) -{ - IsCompressionAllowed=allow_compression; - InactivationTime=DEFAULT_INACTIVATION_TIME; // Default inactivation time 30 seconds - IsReducible=allow_reduction; - - switch (TextureFormat) - { - case WW3D_FORMAT_DXT1: - case WW3D_FORMAT_DXT2: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: - IsCompressionAllowed=true; - break; - case WW3D_FORMAT_U8V8: // Bumpmap - case WW3D_FORMAT_L6V5U5: // Bumpmap - case WW3D_FORMAT_X8L8V8U8: // Bumpmap - // If requesting bumpmap format that isn't available we'll just return the surface in whatever color - // format the texture file is in. (This is illegal case, the format support should always be queried - // before creating a bump texture!) - if (!DX8Wrapper::Is_Initted() || !DX8Wrapper::Get_Current_Caps()->Support_Texture_Format(TextureFormat)) - { - TextureFormat=WW3D_FORMAT_UNKNOWN; - } - // If bump format is valid, make sure compression is not allowed so that we don't even attempt to load - // from a compressed file (quality isn't good enough for bump map). Also disable mipmapping. - else - { - IsCompressionAllowed=false; - MipLevelCount=MIP_LEVELS_1; - Filter.Set_Mip_Mapping(TextureFilterClass::FILTER_TYPE_NONE); - } - break; - default: break; - } - - WWASSERT_PRINT(name && name[0], "TextureClass CTor: NULL or empty texture name"); - int len=strlen(name); - for (int i=0;iGet_Original_Texture_Width(); - Height=thumb->Get_Original_Texture_Height(); - if (MipLevelCount!=MIP_LEVELS_1) { - MipLevelCount=(MipCountType)thumb->Get_Original_Texture_Mip_Level_Count(); - } - } - - LastAccessed=WW3D::Get_Sync_Time(); - - // If the thumbnails are not enabled, init the texture at this point to avoid stalling when the - // mesh is rendered. - if (!WW3D::Get_Thumbnail_Enabled()) - { - if (TextureLoader::Is_DX8_Thread()) - { - Init(); - } - } -} - -// ---------------------------------------------------------------------------- -TextureClass::TextureClass -( - SurfaceClass *surface, - MipCountType mip_level_count -) -: TextureBaseClass(0,0,mip_level_count), - Filter(mip_level_count), - TextureFormat(surface->Get_Surface_Format()) -{ - IsProcedural=true; - Initialized=true; - IsReducible=false; - - SurfaceClass::SurfaceDescription sd; - surface->Get_Description(sd); - Width=sd.Width; - Height=sd.Height; - switch (sd.Format) - { - case WW3D_FORMAT_DXT1: - case WW3D_FORMAT_DXT2: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: - IsCompressionAllowed=true; - break; - default: break; - } - - Poke_Texture - ( - DX8Wrapper::_Create_DX8_Texture - ( - surface->Peek_D3D_Surface(), - mip_level_count - ) - ); - LastAccessed=WW3D::Get_Sync_Time(); -} - -// ---------------------------------------------------------------------------- -TextureClass::TextureClass(IDirect3DBaseTexture8* d3d_texture) -: TextureBaseClass - ( - 0, - 0, - ((MipCountType)d3d_texture->GetLevelCount()) - ), - Filter((MipCountType)d3d_texture->GetLevelCount()) -{ - Initialized=true; - IsProcedural=true; - IsReducible=false; - - Set_D3D_Base_Texture(d3d_texture); - IDirect3DSurface8* 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) - { - case WW3D_FORMAT_DXT1: - case WW3D_FORMAT_DXT2: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: - IsCompressionAllowed=true; - break; - default: break; - } - - LastAccessed=WW3D::Get_Sync_Time(); -} - -//********************************************************************************************** -//! Initialise the texture -/*! -*/ -void TextureClass::Init() -{ - // If the texture has already been initialised we should exit now - if (Initialized) return; - - WWPROFILE("TextureClass::Init"); - - // If the texture has recently been inactivated, increase the inactivation time (this texture obviously - // should not have been inactivated yet). - if (InactivationTime && LastInactivationSyncTime) - { - if ((WW3D::Get_Sync_Time()-LastInactivationSyncTime)Release(); - - Poke_Texture(d3d_texture);//TextureLoadTask->Peek_D3D_Texture(); - d3d_texture->AddRef(); - - if (initialized) Initialized=true; - if (disable_auto_invalidation) InactivationTime = 0; - - WWASSERT(d3d_texture); - IDirect3DSurface8* 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 (initialized) - { - TextureFormat=D3DFormat_To_WW3DFormat(d3d_desc.Format); - Width=d3d_desc.Width; - Height=d3d_desc.Height; - } - surface->Release(); - -} - - -//********************************************************************************************** -//! Apply texture states -/*! -*/ -void TextureClass::Apply(unsigned int stage) -{ - // Initialization needs to be done when texture is used if it hasn't been done before. - // XBOX always initializes textures at creation time. - if (!Initialized) - { - Init(); - - /* was in battlefield// Non-thumbnailed textures are always initialized when used - if (MipLevelCount==MIP_LEVELS_1) - { - } - // Thumbnailed textures have delayed initialization and a background loading system - else - { - // Limit the number of texture initializations per frame to reduce stuttering - if (TexturesAppliedPerFrameGetSurfaceLevel(level, &d3d_surface)); - SurfaceClass *surface = new SurfaceClass(d3d_surface); - d3d_surface->Release(); - - return surface; -} - -//********************************************************************************************** -//! Get surface description for a mip level -/*! -*/ -void TextureClass::Get_Level_Description( SurfaceClass::SurfaceDescription & desc, unsigned int level ) -{ - SurfaceClass * surf = Get_Surface_Level(level); - if (surf != NULL) { - surf->Get_Description(desc); - } - REF_PTR_RELEASE(surf); -} - -//********************************************************************************************** -//! Get D3D surface from mip level -/*! -*/ -IDirect3DSurface8 *TextureClass::Get_D3D_Surface_Level(unsigned int level) -{ - if (!Peek_D3D_Texture()) - { - WWASSERT_PRINT(0, "Get_D3D_Surface_Level: D3DTexture is NULL!"); - return 0; - } - - IDirect3DSurface8 *d3d_surface = NULL; - DX8_ErrorCode(Peek_D3D_Texture()->GetSurfaceLevel(level, &d3d_surface)); - return d3d_surface; -} - -//********************************************************************************************** -//! Get texture memory usage -/*! -*/ -unsigned TextureClass::Get_Texture_Memory_Usage() const -{ - int size=0; - if (!Peek_D3D_Texture()) return 0; - for (unsigned i=0;iGetLevelCount();++i) - { - D3DSURFACE_DESC desc; - DX8_ErrorCode(Peek_D3D_Texture()->GetLevelDesc(i,&desc)); - size+=desc.Size; - } - return size; -} - - -// Utility functions -TextureClass* Load_Texture(ChunkLoadClass & cload) -{ - // Assume failure - TextureClass *newtex = NULL; - - char name[256]; - if (cload.Open_Chunk () && (cload.Cur_Chunk_ID () == W3D_CHUNK_TEXTURE)) - { - - W3dTextureInfoStruct texinfo; - bool hastexinfo = false; - - /* - ** Read in the texture filename, and a possible texture info structure. - */ - while (cload.Open_Chunk()) { - switch (cload.Cur_Chunk_ID()) { - case W3D_CHUNK_TEXTURE_NAME: - cload.Read(&name,cload.Cur_Chunk_Length()); - break; - - case W3D_CHUNK_TEXTURE_INFO: - cload.Read(&texinfo,sizeof(W3dTextureInfoStruct)); - hastexinfo = true; - break; - }; - cload.Close_Chunk(); - } - cload.Close_Chunk(); - - /* - ** Get the texture from the asset manager - */ - if (hastexinfo) - { - - MipCountType mipcount; - - bool no_lod = ((texinfo.Attributes & W3DTEXTURE_NO_LOD) == W3DTEXTURE_NO_LOD); - - if (no_lod) - { - mipcount = MIP_LEVELS_1; - } - else - { - switch (texinfo.Attributes & W3DTEXTURE_MIP_LEVELS_MASK) { - - case W3DTEXTURE_MIP_LEVELS_ALL: - mipcount = MIP_LEVELS_ALL; - break; - - case W3DTEXTURE_MIP_LEVELS_2: - mipcount = MIP_LEVELS_2; - break; - - case W3DTEXTURE_MIP_LEVELS_3: - mipcount = MIP_LEVELS_3; - break; - - case W3DTEXTURE_MIP_LEVELS_4: - mipcount = MIP_LEVELS_4; - break; - - default: - WWASSERT (false); - mipcount = MIP_LEVELS_ALL; - break; - } - } - - WW3DFormat format=WW3D_FORMAT_UNKNOWN; - - switch (texinfo.Attributes & W3DTEXTURE_TYPE_MASK) - { - - case W3DTEXTURE_TYPE_COLORMAP: - // Do nothing. - break; - - case W3DTEXTURE_TYPE_BUMPMAP: - { - if (DX8Wrapper::Is_Initted() && DX8Wrapper::Get_Current_Caps()->Support_Bump_Envmap()) - { - // No mipmaps to bumpmap for now - mipcount=MIP_LEVELS_1; - - if (DX8Wrapper::Get_Current_Caps()->Support_Texture_Format(WW3D_FORMAT_U8V8)) format=WW3D_FORMAT_U8V8; - else if (DX8Wrapper::Get_Current_Caps()->Support_Texture_Format(WW3D_FORMAT_X8L8V8U8)) format=WW3D_FORMAT_X8L8V8U8; - else if (DX8Wrapper::Get_Current_Caps()->Support_Texture_Format(WW3D_FORMAT_L6V5U5)) format=WW3D_FORMAT_L6V5U5; - } - break; - } - - default: - WWASSERT (false); - break; - } - - newtex = WW3DAssetManager::Get_Instance()->Get_Texture (name, mipcount, format); - - if (no_lod) - { - newtex->Get_Filter().Set_Mip_Mapping(TextureFilterClass::FILTER_TYPE_NONE); - } - bool u_clamp = ((texinfo.Attributes & W3DTEXTURE_CLAMP_U) != 0); - newtex->Get_Filter().Set_U_Addr_Mode(u_clamp ? TextureFilterClass::TEXTURE_ADDRESS_CLAMP : TextureFilterClass::TEXTURE_ADDRESS_REPEAT); - bool v_clamp = ((texinfo.Attributes & W3DTEXTURE_CLAMP_V) != 0); - newtex->Get_Filter().Set_V_Addr_Mode(v_clamp ? TextureFilterClass::TEXTURE_ADDRESS_CLAMP : TextureFilterClass::TEXTURE_ADDRESS_REPEAT); - - } else - { - newtex = WW3DAssetManager::Get_Instance()->Get_Texture(name); - } - - WWASSERT(newtex); - } - - // Return a pointer to the new texture - return newtex; -} - -// Utility function used by Save_Texture -void setup_texture_attributes(TextureClass * tex, W3dTextureInfoStruct * texinfo) -{ - texinfo->Attributes = 0; - - if (tex->Get_Filter().Get_Mip_Mapping() == TextureFilterClass::FILTER_TYPE_NONE) texinfo->Attributes |= W3DTEXTURE_NO_LOD; - if (tex->Get_Filter().Get_U_Addr_Mode() == TextureFilterClass::TEXTURE_ADDRESS_CLAMP) texinfo->Attributes |= W3DTEXTURE_CLAMP_U; - if (tex->Get_Filter().Get_V_Addr_Mode() == TextureFilterClass::TEXTURE_ADDRESS_CLAMP) texinfo->Attributes |= W3DTEXTURE_CLAMP_V; -} - - -void Save_Texture(TextureClass * texture,ChunkSaveClass & csave) -{ - const char * filename; - W3dTextureInfoStruct texinfo; - memset(&texinfo,0,sizeof(texinfo)); - - filename = texture->Get_Full_Path(); - - setup_texture_attributes(texture, &texinfo); - - csave.Begin_Chunk(W3D_CHUNK_TEXTURE_NAME); - csave.Write(filename,strlen(filename)+1); - csave.End_Chunk(); - - if ((texinfo.Attributes != 0) || (texinfo.AnimType != 0) || (texinfo.FrameCount != 0)) { - csave.Begin_Chunk(W3D_CHUNK_TEXTURE_INFO); - csave.Write(&texinfo, sizeof(texinfo)); - csave.End_Chunk(); - } -} - - -/*! - * KJM depth stencil texture constructor - */ -ZTextureClass::ZTextureClass -( - unsigned width, - unsigned height, - WW3DZFormat zformat, - MipCountType mip_level_count, - PoolType pool -) -: TextureBaseClass(width,height, mip_level_count, pool), - DepthStencilTextureFormat(zformat) -{ - D3DPOOL d3dpool=(D3DPOOL)0; - switch (pool) - { - case POOL_DEFAULT: d3dpool=D3DPOOL_DEFAULT; break; - case POOL_MANAGED: d3dpool=D3DPOOL_MANAGED; break; - case POOL_SYSTEMMEM: d3dpool=D3DPOOL_SYSTEMMEM; break; - default: WWASSERT(0); - } - - Poke_Texture - ( - DX8Wrapper::_Create_DX8_ZTexture - ( - width, - height, - zformat, - mip_level_count, - d3dpool - ) - ); - - if (pool==POOL_DEFAULT) - { - Set_Dirty(); - DX8ZTextureTrackerClass *track=new DX8ZTextureTrackerClass - ( - width, - height, - zformat, - mip_level_count, - this - ); - DX8TextureManagerClass::Add(track); - } - Initialized=true; - IsProcedural=true; - IsReducible=false; - - LastAccessed=WW3D::Get_Sync_Time(); -} - - -//********************************************************************************************** -//! Apply depth stencil texture -/*! KM -*/ -void ZTextureClass::Apply(unsigned int stage) -{ - DX8Wrapper::Set_DX8_Texture(stage, Peek_D3D_Base_Texture()); -} - -//********************************************************************************************** -//! Apply new surface to texture -/*! KM -*/ -void ZTextureClass::Apply_New_Surface -( - IDirect3DBaseTexture8* d3d_texture, - bool initialized, - bool disable_auto_invalidation -) -{ - IDirect3DBaseTexture8* d3d_tex=Peek_D3D_Base_Texture(); - - if (d3d_tex) d3d_tex->Release(); - - Poke_Texture(d3d_texture);//TextureLoadTask->Peek_D3D_Texture(); - d3d_texture->AddRef(); - - if (initialized) Initialized=true; - if (disable_auto_invalidation) InactivationTime = 0; - - WWASSERT(Peek_D3D_Texture()); - IDirect3DSurface8* 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 (initialized) - { - DepthStencilTextureFormat=D3DFormat_To_WW3DZFormat(d3d_desc.Format); - Width=d3d_desc.Width; - Height=d3d_desc.Height; - } - surface->Release(); -} - -//********************************************************************************************** -//! Get D3D surface from mip level -/*! -*/ -IDirect3DSurface8* ZTextureClass::Get_D3D_Surface_Level(unsigned int level) -{ - if (!Peek_D3D_Texture()) - { - WWASSERT_PRINT(0, "Get_D3D_Surface_Level: D3DTexture is NULL!"); - return 0; - } - - IDirect3DSurface8 *d3d_surface = NULL; - DX8_ErrorCode(Peek_D3D_Texture()->GetSurfaceLevel(level, &d3d_surface)); - return d3d_surface; -} - -//********************************************************************************************** -//! Get texture memory usage -/*! -*/ -unsigned ZTextureClass::Get_Texture_Memory_Usage() const -{ - int size=0; - if (!Peek_D3D_Texture()) return 0; - for (unsigned i=0;iGetLevelCount();++i) - { - D3DSURFACE_DESC desc; - DX8_ErrorCode(Peek_D3D_Texture()->GetLevelDesc(i,&desc)); - size+=desc.Size; - } - return size; -} - - - -/************************************************************************* -** CubeTextureClass -*************************************************************************/ -CubeTextureClass::CubeTextureClass -( - unsigned width, - unsigned height, - WW3DFormat format, - MipCountType mip_level_count, - PoolType pool, - bool rendertarget, - bool allow_reduction -) -: TextureClass(width, height, format, mip_level_count, pool, rendertarget) -{ - Initialized=true; - IsProcedural=true; - IsReducible=false; - - switch (format) - { - case WW3D_FORMAT_DXT1: - case WW3D_FORMAT_DXT2: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: - IsCompressionAllowed=true; - break; - default : break; - } - - D3DPOOL d3dpool=(D3DPOOL)0; - switch(pool) - { - case POOL_DEFAULT : d3dpool=D3DPOOL_DEFAULT; break; - case POOL_MANAGED : d3dpool=D3DPOOL_MANAGED; break; - case POOL_SYSTEMMEM : d3dpool=D3DPOOL_SYSTEMMEM; break; - default: WWASSERT(0); - } - - Poke_Texture - ( - DX8Wrapper::_Create_DX8_Cube_Texture - ( - width, - height, - format, - mip_level_count, - d3dpool, - rendertarget - ) - ); - - if (pool==POOL_DEFAULT) - { - Set_Dirty(); - DX8TextureTrackerClass *track=new DX8TextureTrackerClass - ( - width, - height, - format, - mip_level_count, - this, - rendertarget - ); - DX8TextureManagerClass::Add(track); - } - LastAccessed=WW3D::Get_Sync_Time(); -} - - - -// ---------------------------------------------------------------------------- -CubeTextureClass::CubeTextureClass -( - const char *name, - const char *full_path, - MipCountType mip_level_count, - WW3DFormat texture_format, - bool allow_compression, - bool allow_reduction -) -: TextureClass(0,0,mip_level_count, POOL_MANAGED, false, texture_format) -{ - IsCompressionAllowed=allow_compression; - InactivationTime=DEFAULT_INACTIVATION_TIME; // Default inactivation time 30 seconds - - switch (TextureFormat) - { - case WW3D_FORMAT_DXT1: - case WW3D_FORMAT_DXT2: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: - IsCompressionAllowed=true; - break; - case WW3D_FORMAT_U8V8: // Bumpmap - case WW3D_FORMAT_L6V5U5: // Bumpmap - case WW3D_FORMAT_X8L8V8U8: // Bumpmap - // If requesting bumpmap format that isn't available we'll just return the surface in whatever color - // format the texture file is in. (This is illegal case, the format support should always be queried - // before creating a bump texture!) - if (!DX8Wrapper::Is_Initted() || !DX8Wrapper::Get_Current_Caps()->Support_Texture_Format(TextureFormat)) - { - TextureFormat=WW3D_FORMAT_UNKNOWN; - } - // If bump format is valid, make sure compression is not allowed so that we don't even attempt to load - // from a compressed file (quality isn't good enough for bump map). Also disable mipmapping. - else - { - IsCompressionAllowed=false; - MipLevelCount=MIP_LEVELS_1; - Filter.Set_Mip_Mapping(TextureFilterClass::FILTER_TYPE_NONE); - } - break; - default: break; - } - - WWASSERT_PRINT(name && name[0], "TextureClass CTor: NULL or empty texture name"); - int len=strlen(name); - for (int i=0;iGet_Original_Texture_Width(); - Height=thumb->Get_Original_Texture_Height(); - if (MipLevelCount!=MIP_LEVELS_1) { - MipLevelCount=(MipCountType)thumb->Get_Original_Texture_Mip_Level_Count(); - } - } - - LastAccessed=WW3D::Get_Sync_Time(); - - // If the thumbnails are not enabled, init the texture at this point to avoid stalling when the - // mesh is rendered. - if (!WW3D::Get_Thumbnail_Enabled()) - { - if (TextureLoader::Is_DX8_Thread()) - { - Init(); - } - } -} - -// don't know if these are needed -#if 0 -// ---------------------------------------------------------------------------- -CubeTextureClass::CubeTextureClass -( - SurfaceClass *surface, - MipCountType mip_level_count -) -: TextureClass(0,0,mip_level_count, POOL_MANAGED, false, surface->Get_Surface_Format()) -{ - IsProcedural=true; - Initialized=true; - IsReducible=false; - - SurfaceClass::SurfaceDescription sd; - surface->Get_Description(sd); - Width=sd.Width; - Height=sd.Height; - switch (sd.Format) - { - case WW3D_FORMAT_DXT1: - case WW3D_FORMAT_DXT2: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: - IsCompressionAllowed=true; - break; - default: break; - } - - Poke_Texture - ( - DX8Wrapper::_Create_DX8_Cube_Texture - ( - surface->Peek_D3D_Surface(), - mip_level_count - ) - ); - LastAccessed=WW3D::Get_Sync_Time(); -} - -// ---------------------------------------------------------------------------- -CubeTextureClass::CubeTextureClass(IDirect3DBaseTexture8* d3d_texture) -: TextureBaseClass - ( - 0, - 0, - ((MipCountType)d3d_texture->GetLevelCount()) - ), - Filter((MipCountType)d3d_texture->GetLevelCount()) -{ - Initialized=true; - IsProcedural=true; - IsReducible=false; - - Peek_Texture()->AddRef(); - IDirect3DSurface8* 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) - { - case WW3D_FORMAT_DXT1: - case WW3D_FORMAT_DXT2: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: - IsCompressionAllowed=true; - break; - default: break; - } - - LastAccessed=WW3D::Get_Sync_Time(); -} -#endif - -//********************************************************************************************** -//! Apply new surface to texture -/*! -*/ -void CubeTextureClass::Apply_New_Surface -( - IDirect3DBaseTexture8* d3d_texture, - bool initialized, - bool disable_auto_invalidation -) -{ - IDirect3DBaseTexture8* d3d_tex=Peek_D3D_Base_Texture(); - - if (d3d_tex) d3d_tex->Release(); - - Poke_Texture(d3d_texture);//TextureLoadTask->Peek_D3D_Texture(); - d3d_texture->AddRef(); - - if (initialized) Initialized=true; - if (disable_auto_invalidation) InactivationTime = 0; - - WWASSERT(d3d_texture); - D3DSURFACE_DESC d3d_desc; - ::ZeroMemory(&d3d_desc, sizeof(D3DSURFACE_DESC)); - DX8_ErrorCode(Peek_D3D_CubeTexture()->GetLevelDesc(0,&d3d_desc)); - - if (initialized) - { - TextureFormat=D3DFormat_To_WW3DFormat(d3d_desc.Format); - Width=d3d_desc.Width; - Height=d3d_desc.Height; - } -} - - -/************************************************************************* -** VolumeTextureClass -*************************************************************************/ -VolumeTextureClass::VolumeTextureClass -( - unsigned width, - unsigned height, - unsigned depth, - WW3DFormat format, - MipCountType mip_level_count, - PoolType pool, - bool rendertarget, - bool allow_reduction -) -: TextureClass(width, height, format, mip_level_count, pool, rendertarget), - Depth(depth) -{ - Initialized=true; - IsProcedural=true; - IsReducible=false; - - switch (format) - { - case WW3D_FORMAT_DXT1: - case WW3D_FORMAT_DXT2: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: - IsCompressionAllowed=true; - break; - default : break; - } - - D3DPOOL d3dpool=(D3DPOOL)0; - switch(pool) - { - case POOL_DEFAULT : d3dpool=D3DPOOL_DEFAULT; break; - case POOL_MANAGED : d3dpool=D3DPOOL_MANAGED; break; - case POOL_SYSTEMMEM : d3dpool=D3DPOOL_SYSTEMMEM; break; - default: WWASSERT(0); - } - - Poke_Texture - ( - DX8Wrapper::_Create_DX8_Volume_Texture - ( - width, - height, - depth, - format, - mip_level_count, - d3dpool - ) - ); - - if (pool==POOL_DEFAULT) - { - Set_Dirty(); - DX8TextureTrackerClass *track=new DX8TextureTrackerClass - ( - width, - height, - format, - mip_level_count, - this, - rendertarget - ); - DX8TextureManagerClass::Add(track); - } - LastAccessed=WW3D::Get_Sync_Time(); -} - - - -// ---------------------------------------------------------------------------- -VolumeTextureClass::VolumeTextureClass -( - const char *name, - const char *full_path, - MipCountType mip_level_count, - WW3DFormat texture_format, - bool allow_compression, - bool allow_reduction -) -: TextureClass(0,0,mip_level_count, POOL_MANAGED, false, texture_format), - Depth(0) -{ - IsCompressionAllowed=allow_compression; - InactivationTime=DEFAULT_INACTIVATION_TIME; // Default inactivation time 30 seconds - - switch (TextureFormat) - { - case WW3D_FORMAT_DXT1: - case WW3D_FORMAT_DXT2: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: - IsCompressionAllowed=true; - break; - case WW3D_FORMAT_U8V8: // Bumpmap - case WW3D_FORMAT_L6V5U5: // Bumpmap - case WW3D_FORMAT_X8L8V8U8: // Bumpmap - // If requesting bumpmap format that isn't available we'll just return the surface in whatever color - // format the texture file is in. (This is illegal case, the format support should always be queried - // before creating a bump texture!) - if (!DX8Wrapper::Is_Initted() || !DX8Wrapper::Get_Current_Caps()->Support_Texture_Format(TextureFormat)) - { - TextureFormat=WW3D_FORMAT_UNKNOWN; - } - // If bump format is valid, make sure compression is not allowed so that we don't even attempt to load - // from a compressed file (quality isn't good enough for bump map). Also disable mipmapping. - else - { - IsCompressionAllowed=false; - MipLevelCount=MIP_LEVELS_1; - Filter.Set_Mip_Mapping(TextureFilterClass::FILTER_TYPE_NONE); - } - break; - default: break; - } - - WWASSERT_PRINT(name && name[0], "TextureClass CTor: NULL or empty texture name"); - int len=strlen(name); - for (int i=0;iGet_Original_Texture_Width(); - Height=thumb->Get_Original_Texture_Height(); - if (MipLevelCount!=MIP_LEVELS_1) { - MipLevelCount=(MipCountType)thumb->Get_Original_Texture_Mip_Level_Count(); - } - } - - LastAccessed=WW3D::Get_Sync_Time(); - - // If the thumbnails are not enabled, init the texture at this point to avoid stalling when the - // mesh is rendered. - if (!WW3D::Get_Thumbnail_Enabled()) - { - if (TextureLoader::Is_DX8_Thread()) - { - Init(); - } - } -} - -// don't know if these are needed -#if 0 -// ---------------------------------------------------------------------------- -CubeTextureClass::CubeTextureClass -( - SurfaceClass *surface, - MipCountType mip_level_count -) -: TextureClass(0,0,mip_level_count, POOL_MANAGED, false, surface->Get_Surface_Format()) -{ - IsProcedural=true; - Initialized=true; - IsReducible=false; - - SurfaceClass::SurfaceDescription sd; - surface->Get_Description(sd); - Width=sd.Width; - Height=sd.Height; - switch (sd.Format) - { - case WW3D_FORMAT_DXT1: - case WW3D_FORMAT_DXT2: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: - IsCompressionAllowed=true; - break; - default: break; - } - - Poke_Texture - ( - DX8Wrapper::_Create_DX8_Cube_Texture - ( - surface->Peek_D3D_Surface(), - mip_level_count - ) - ); - LastAccessed=WW3D::Get_Sync_Time(); -} - -// ---------------------------------------------------------------------------- -CubeTextureClass::CubeTextureClass(IDirect3DBaseTexture8* d3d_texture) -: TextureBaseClass - ( - 0, - 0, - ((MipCountType)d3d_texture->GetLevelCount()) - ), - Filter((MipCountType)d3d_texture->GetLevelCount()) -{ - Initialized=true; - IsProcedural=true; - IsReducible=false; - - Peek_Texture()->AddRef(); - IDirect3DSurface8* 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) - { - case WW3D_FORMAT_DXT1: - case WW3D_FORMAT_DXT2: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: - IsCompressionAllowed=true; - break; - default: break; - } - - LastAccessed=WW3D::Get_Sync_Time(); -} -#endif - - - - -//********************************************************************************************** -//! Apply new surface to texture -/*! -*/ -void VolumeTextureClass::Apply_New_Surface -( - IDirect3DBaseTexture8* d3d_texture, - bool initialized, - bool disable_auto_invalidation -) -{ - IDirect3DBaseTexture8* d3d_tex=Peek_D3D_Base_Texture(); - - if (d3d_tex) d3d_tex->Release(); - - Poke_Texture(d3d_texture);//TextureLoadTask->Peek_D3D_Texture(); - d3d_texture->AddRef(); - - if (initialized) Initialized=true; - if (disable_auto_invalidation) InactivationTime = 0; - - WWASSERT(d3d_texture); - D3DVOLUME_DESC d3d_desc; - ::ZeroMemory(&d3d_desc, sizeof(D3DVOLUME_DESC)); - - DX8_ErrorCode(Peek_D3D_VolumeTexture()->GetLevelDesc(0,&d3d_desc)); - - if (initialized) - { - TextureFormat=D3DFormat_To_WW3DFormat(d3d_desc.Format); - Width=d3d_desc.Width; - Height=d3d_desc.Height; - Depth=d3d_desc.Depth; - } -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texture.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texture.h deleted file mode 100644 index 47eff85d7f..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texture.h +++ /dev/null @@ -1,475 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I 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/texture.h $* - * * - * $Org Author:: Jani_p $* - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 08/05/02 1:27p $* - * * - * $Revision:: 46 $* - * * - * 05/16/02 KM Base texture class to abstract major texture types, e.g. 3d, z, cube, etc. - * 06/27/02 KM Texture class abstraction * - * 08/05/02 KM Texture class redesign (revisited) - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#pragma once - -#include "always.h" -#include "chunkio.h" -#include "surfaceclass.h" -#include "ww3dformat.h" -#include "wwstring.h" -#include "vector3.h" -#include "texturefilter.h" - -struct IDirect3DBaseTexture8; -struct IDirect3DTexture8; -struct IDirect3DCubeTexture8; -struct IDirect3DVolumeTexture8; - -class DX8Wrapper; -class TextureLoader; -class LoaderThreadClass; -class TextureLoadTaskClass; -class CubeTextureClass; -class VolumeTextureClass; - -class TextureBaseClass : public RefCountClass -{ - friend class TextureLoader; - friend class LoaderThreadClass; - friend class DX8TextureTrackerClass; //(gth) so it can call Poke_Texture, - friend class DX8ZTextureTrackerClass; - -public: - - enum PoolType - { - POOL_DEFAULT=0, - POOL_MANAGED, - POOL_SYSTEMMEM - }; - - enum TexAssetType - { - TEX_REGULAR, - TEX_CUBEMAP, - TEX_VOLUME - }; - - // base constructor for derived classes - TextureBaseClass - ( - unsigned width, - unsigned height, - MipCountType mip_level_count=MIP_LEVELS_ALL, - PoolType pool=POOL_MANAGED, - bool rendertarget=false, - bool reducible=true - ); - - virtual ~TextureBaseClass(); - - virtual TexAssetType Get_Asset_Type() const=0; - - // Names - void Set_Texture_Name(const char * name); - void Set_Full_Path(const char * path) { FullPath = path; } - const StringClass& Get_Texture_Name(void) const { return Name; } - const StringClass& Get_Full_Path(void) const { if (FullPath.Is_Empty ()) return Name; return FullPath; } - - unsigned Get_ID() const { return texture_id; } // Each textrure has a unique id - - // The number of Mip levels in the texture - unsigned int Get_Mip_Level_Count(void) const - { - return MipLevelCount; - } - - // 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; - } - - // Time, after which the texture is invalidated if not used. Set to zero to indicate infinite. - // Time is in milliseconds. - void Set_Inactivation_Time(unsigned time) { InactivationTime=time; } - int Get_Inactivation_Time() const { return InactivationTime; } - - // Texture priority affects texture management and caching. - unsigned int Get_Priority(void); - unsigned int Set_Priority(unsigned int priority); // Returns previous priority - - // Debug utility functions for returning the texture memory usage - virtual unsigned Get_Texture_Memory_Usage() const=0; - - bool Is_Initialized() const { return Initialized; } - bool Is_Lightmap() const { return IsLightmap; } - bool Is_Procedural() const { return IsProcedural; } - bool Is_Reducible() const { return IsReducible; } //can texture be reduced in resolution for LOD purposes? - - static int _Get_Total_Locked_Surface_Size(); - static int _Get_Total_Texture_Size(); - static int _Get_Total_Lightmap_Texture_Size(); - static int _Get_Total_Procedural_Texture_Size(); - static int _Get_Total_Locked_Surface_Count(); - static int _Get_Total_Texture_Count(); - static int _Get_Total_Lightmap_Texture_Count(); - static int _Get_Total_Procedural_Texture_Count(); - - virtual void Init()=0; - - // This utility function processes the texture reduction (used during rendering) - void Invalidate(); - - // 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; }; - - void Set_HSV_Shift(const Vector3 &hsv_shift); - const Vector3& Get_HSV_Shift() { return HSVShift; } - - bool Is_Compression_Allowed() const { return IsCompressionAllowed; } - - unsigned Get_Reduction() const; - - // Background texture loader will call this when texture has been loaded - virtual void Apply_New_Surface(IDirect3DBaseTexture8* tex, bool initialized, bool disable_auto_invalidation = false)=0; // If the parameter is true, the texture will be flagged as initialised - - MipCountType MipLevelCount; - - // Inactivate textures that haven't been used in a while. Pass zero to use textures' - // own inactive times (default). In urgent need to free up texture memory, try - // calling with relatively small (just few seconds) time override to free up everything - // but the currently used textures. - static void Invalidate_Old_Unused_Textures(unsigned inactive_time_override); - - // Apply this texture's settings into D3D - virtual void Apply(unsigned int stage)=0; - - // Apply a Null texture's settings into D3D - static void Apply_Null(unsigned int stage); - - virtual TextureClass* As_TextureClass() { return NULL; } - virtual CubeTextureClass* As_CubeTextureClass() { return NULL; } - virtual VolumeTextureClass* As_VolumeTextureClass() { return NULL; } - - IDirect3DTexture8* Peek_D3D_Texture() const { return (IDirect3DTexture8*)Peek_D3D_Base_Texture(); } - IDirect3DVolumeTexture8* Peek_D3D_VolumeTexture() const { return (IDirect3DVolumeTexture8*)Peek_D3D_Base_Texture(); } - IDirect3DCubeTexture8* Peek_D3D_CubeTexture() const { return (IDirect3DCubeTexture8*)Peek_D3D_Base_Texture(); } - -protected: - - void Load_Locked_Surface(); - void Poke_Texture(IDirect3DBaseTexture8* tex) { D3DTexture = tex; } - - bool Initialized; - - // For debug purposes the texture sets this true if it is a lightmap texture - bool IsLightmap; - bool IsCompressionAllowed; - bool IsProcedural; - bool IsReducible; - - - unsigned InactivationTime; // In milliseconds - unsigned ExtendedInactivationTime; // This is set by the engine, if needed - unsigned LastInactivationSyncTime; - mutable unsigned LastAccessed; - - // If this is non-zero, the texture will have a hue shift done at the next init (this - // value should only be changed by Set_HSV_Shift() function, which also invalidates the - // texture). - Vector3 HSVShift; - - int Width; - int Height; - -private: - - // Direct3D texture object - IDirect3DBaseTexture8 *D3DTexture; - - // Name - StringClass Name; - StringClass FullPath; - - // Unique id - unsigned texture_id; - - // Support for self-managed textures - - PoolType Pool; - bool Dirty; - - friend class TextureLoadTaskClass; - friend class CubeTextureLoadTaskClass; - friend class VolumeTextureLoadTaskClass; - TextureLoadTaskClass* TextureLoadTask; - TextureLoadTaskClass* ThumbnailLoadTask; - -}; - - -/************************************************************************* -** TextureClass -** -** This is our regular texture class. For legacy reasons it contains some -** information beyond the D3D texture itself, such as texture addressing -** modes. -** -*************************************************************************/ -class TextureClass : public TextureBaseClass -{ - W3DMPO_GLUE(TextureClass) -// friend DX8Wrapper; - -public: - - // Create texture with desired height, width and format. - TextureClass - ( - unsigned width, - unsigned height, - WW3DFormat format, - MipCountType mip_level_count=MIP_LEVELS_ALL, - PoolType pool=POOL_MANAGED, - bool rendertarget=false, - bool allow_reduction=true - ); - - // Create texture from a file. If format is specified the texture is converted to that format. - // Note that the format must be supported by the current device and that a texture can't exist - // in the system with the same name in multiple formats. - TextureClass - ( - const char *name, - const char *full_path=NULL, - MipCountType mip_level_count=MIP_LEVELS_ALL, - WW3DFormat texture_format=WW3D_FORMAT_UNKNOWN, - bool allow_compression=true, - bool allow_reduction=true - ); - - // Create texture from a surface. - TextureClass - ( - SurfaceClass *surface, - MipCountType mip_level_count=MIP_LEVELS_ALL - ); - - TextureClass(IDirect3DBaseTexture8* d3d_texture); - - // defualt constructors for derived classes (cube & vol) - TextureClass - ( - unsigned width, - unsigned height, - MipCountType mip_level_count=MIP_LEVELS_ALL, - PoolType pool=POOL_MANAGED, - bool rendertarget=false, - WW3DFormat format=WW3D_FORMAT_UNKNOWN, - bool allow_reduction=true - ) - : TextureBaseClass(width,height,mip_level_count,pool,rendertarget,allow_reduction), TextureFormat(format), Filter(mip_level_count) { } - - virtual TexAssetType Get_Asset_Type() const { return TEX_REGULAR; } - - virtual void Init(); - - // Background texture loader will call this when texture has been loaded - virtual void Apply_New_Surface(IDirect3DBaseTexture8* tex, bool initialized, bool disable_auto_invalidation = false); // If the parameter is true, the texture will be flagged as initialised - - // Get the surface of one of the mipmap levels (defaults to highest-resolution one) - SurfaceClass *Get_Surface_Level(unsigned int level = 0); - IDirect3DSurface8 *Get_D3D_Surface_Level(unsigned int level = 0); - void Get_Level_Description( SurfaceClass::SurfaceDescription & desc, unsigned int level = 0 ); - - TextureFilterClass& Get_Filter() { return Filter; } - - WW3DFormat Get_Texture_Format() const { return TextureFormat; } - - virtual void Apply(unsigned int stage); - - virtual unsigned Get_Texture_Memory_Usage() const; - - virtual TextureClass* As_TextureClass() { return this; } - -protected: - - WW3DFormat TextureFormat; - - // legacy - TextureFilterClass Filter; -}; - -class ZTextureClass : public TextureBaseClass -{ -public: - // Create a z texture with desired height, width and format - ZTextureClass - ( - unsigned width, - unsigned height, - WW3DZFormat zformat, - MipCountType mip_level_count=MIP_LEVELS_ALL, - PoolType pool=POOL_MANAGED - ); - - WW3DZFormat Get_Texture_Format() const { return DepthStencilTextureFormat; } - - virtual TexAssetType Get_Asset_Type() const { return TEX_REGULAR; } - - virtual void Init() {} - - // Background texture loader will call this when texture has been loaded - virtual void Apply_New_Surface(IDirect3DBaseTexture8* tex, bool initialized, bool disable_auto_invalidation = false); // If the parameter is true, the texture will be flagged as initialised - - virtual void Apply(unsigned int stage); - - IDirect3DSurface8 *Get_D3D_Surface_Level(unsigned int level = 0); - virtual unsigned Get_Texture_Memory_Usage() const; - -private: - - WW3DZFormat DepthStencilTextureFormat; -}; - -class CubeTextureClass : public TextureClass -{ -public: - // Create texture with desired height, width and format. - CubeTextureClass - ( - unsigned width, - unsigned height, - WW3DFormat format, - MipCountType mip_level_count=MIP_LEVELS_ALL, - PoolType pool=POOL_MANAGED, - bool rendertarget=false, - bool allow_reduction=true - ); - - // Create texture from a file. If format is specified the texture is converted to that format. - // Note that the format must be supported by the current device and that a texture can't exist - // in the system with the same name in multiple formats. - CubeTextureClass - ( - const char *name, - const char *full_path=NULL, - MipCountType mip_level_count=MIP_LEVELS_ALL, - WW3DFormat texture_format=WW3D_FORMAT_UNKNOWN, - bool allow_compression=true, - bool allow_reduction=true - ); - - // Create texture from a surface. - CubeTextureClass - ( - SurfaceClass *surface, - MipCountType mip_level_count=MIP_LEVELS_ALL - ); - - CubeTextureClass(IDirect3DBaseTexture8* d3d_texture); - - virtual void Apply_New_Surface(IDirect3DBaseTexture8* tex, bool initialized, bool disable_auto_invalidation = false); // If the parameter is true, the texture will be flagged as initialised - - virtual TexAssetType Get_Asset_Type() const { return TEX_CUBEMAP; } - - virtual CubeTextureClass* As_CubeTextureClass() { return this; } - -}; - -class VolumeTextureClass : public TextureClass -{ -public: - // Create texture with desired height, width and format. - VolumeTextureClass - ( - unsigned width, - unsigned height, - unsigned depth, - WW3DFormat format, - MipCountType mip_level_count=MIP_LEVELS_ALL, - PoolType pool=POOL_MANAGED, - bool rendertarget=false, - bool allow_reduction=true - ); - - // Create texture from a file. If format is specified the texture is converted to that format. - // Note that the format must be supported by the current device and that a texture can't exist - // in the system with the same name in multiple formats. - VolumeTextureClass - ( - const char *name, - const char *full_path=NULL, - MipCountType mip_level_count=MIP_LEVELS_ALL, - WW3DFormat texture_format=WW3D_FORMAT_UNKNOWN, - bool allow_compression=true, - bool allow_reduction=true - ); - - // Create texture from a surface. - VolumeTextureClass - ( - SurfaceClass *surface, - MipCountType mip_level_count=MIP_LEVELS_ALL - ); - - VolumeTextureClass(IDirect3DBaseTexture8* d3d_texture); - - virtual void Apply_New_Surface(IDirect3DBaseTexture8* tex, bool initialized, bool disable_auto_invalidation = false); // If the parameter is true, the texture will be flagged as initialised - - virtual TexAssetType Get_Asset_Type() const { return TEX_VOLUME; } - - virtual VolumeTextureClass* As_VolumeTextureClass() { return this; } - -protected: - - int Depth; -}; - -// Utility functions for loading and saving texture descriptions from/to W3D files -TextureClass *Load_Texture(ChunkLoadClass & cload); -void Save_Texture(TextureClass * texture, ChunkSaveClass & csave); diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texturefilter.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texturefilter.cpp deleted file mode 100644 index 690faf2ef4..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texturefilter.cpp +++ /dev/null @@ -1,251 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I 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:: ww3d2/texturefilter.cpp $* - * * - * $Org Author:: Kenny Mitchell $* - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 08/05/02 1:27p $* - * * - * $Revision:: 1 $* - * * - * 08/05/02 KM Texture filter class abstraction * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "texturefilter.h" -#include "dx8wrapper.h" - -unsigned _MinTextureFilters[MAX_TEXTURE_STAGES][TextureFilterClass::FILTER_TYPE_COUNT]; -unsigned _MagTextureFilters[MAX_TEXTURE_STAGES][TextureFilterClass::FILTER_TYPE_COUNT]; -unsigned _MipMapFilters[MAX_TEXTURE_STAGES][TextureFilterClass::FILTER_TYPE_COUNT]; - -/************************************************************************* -** TextureFilterClass -*************************************************************************/ -TextureFilterClass::TextureFilterClass(MipCountType mip_level_count) -: TextureMinFilter(FILTER_TYPE_DEFAULT), - TextureMagFilter(FILTER_TYPE_DEFAULT), - UAddressMode(TEXTURE_ADDRESS_REPEAT), - VAddressMode(TEXTURE_ADDRESS_REPEAT) -{ - if (mip_level_count!=MIP_LEVELS_1) - { - MipMapFilter=FILTER_TYPE_DEFAULT; - } - else - { - MipMapFilter=FILTER_TYPE_NONE; - } -} - -//********************************************************************************************** -//! Apply filters (legacy) -/*! -*/ -void TextureFilterClass::Apply(unsigned int stage) -{ - DX8Wrapper::Set_DX8_Texture_Stage_State(stage,D3DTSS_MINFILTER,_MinTextureFilters[stage][TextureMinFilter]); - DX8Wrapper::Set_DX8_Texture_Stage_State(stage,D3DTSS_MAGFILTER,_MagTextureFilters[stage][TextureMagFilter]); - DX8Wrapper::Set_DX8_Texture_Stage_State(stage,D3DTSS_MIPFILTER,_MipMapFilters[stage][MipMapFilter]); - - switch (Get_U_Addr_Mode()) - { - case TEXTURE_ADDRESS_REPEAT: - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); - break; - - case TEXTURE_ADDRESS_CLAMP: - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP); - break; - } - - switch (Get_V_Addr_Mode()) - { - case TEXTURE_ADDRESS_REPEAT: - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); - break; - - case TEXTURE_ADDRESS_CLAMP: - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP); - break; - } -} - -//********************************************************************************************** -//! Init filters (legacy) -/*! -*/ -void TextureFilterClass::_Init_Filters(TextureFilterMode filter_type) -{ - const D3DCAPS8& dx8caps=DX8Wrapper::Get_Current_Caps()->Get_DX8_Caps(); - -#ifndef _XBOX - _MinTextureFilters[0][FILTER_TYPE_NONE]=D3DTEXF_POINT; - _MagTextureFilters[0][FILTER_TYPE_NONE]=D3DTEXF_POINT; - _MipMapFilters[0][FILTER_TYPE_NONE]=D3DTEXF_NONE; - - _MinTextureFilters[0][FILTER_TYPE_FAST]=D3DTEXF_LINEAR; - _MagTextureFilters[0][FILTER_TYPE_FAST]=D3DTEXF_LINEAR; - _MipMapFilters[0][FILTER_TYPE_FAST]=D3DTEXF_POINT; - - _MagTextureFilters[0][FILTER_TYPE_BEST]=D3DTEXF_POINT; - _MinTextureFilters[0][FILTER_TYPE_BEST]=D3DTEXF_POINT; - _MipMapFilters[0][FILTER_TYPE_BEST]=D3DTEXF_POINT; -#else - _MinTextureFilters[0][FILTER_TYPE_NONE]=D3DTEXF_ANISOTROPIC; - _MagTextureFilters[0][FILTER_TYPE_NONE]=D3DTEXF_ANISOTROPIC; - _MipMapFilters[0][FILTER_TYPE_NONE]=D3DTEXF_LINEAR; - - _MinTextureFilters[0][FILTER_TYPE_FAST]=D3DTEXF_ANISOTROPIC; - _MagTextureFilters[0][FILTER_TYPE_FAST]=D3DTEXF_ANISOTROPIC; - _MipMapFilters[0][FILTER_TYPE_FAST]=D3DTEXF_LINEAR; - - _MagTextureFilters[0][FILTER_TYPE_BEST]=D3DTEXF_ANISOTROPIC; - _MinTextureFilters[0][FILTER_TYPE_BEST]=D3DTEXF_ANISOTROPIC; - _MipMapFilters[0][FILTER_TYPE_BEST]=D3DTEXF_LINEAR; -#endif - -#ifndef _XBOX - if (dx8caps.TextureFilterCaps&D3DPTFILTERCAPS_MAGFLINEAR) _MagTextureFilters[0][FILTER_TYPE_BEST]=D3DTEXF_LINEAR; - if (dx8caps.TextureFilterCaps&D3DPTFILTERCAPS_MINFLINEAR) _MinTextureFilters[0][FILTER_TYPE_BEST]=D3DTEXF_LINEAR; - - // Set anisotropic filtering only if requested and available - if (filter_type==TEXTURE_FILTER_ANISOTROPIC) { - if (dx8caps.TextureFilterCaps&D3DPTFILTERCAPS_MAGFANISOTROPIC) _MagTextureFilters[0][FILTER_TYPE_BEST]=D3DTEXF_ANISOTROPIC; - if (dx8caps.TextureFilterCaps&D3DPTFILTERCAPS_MINFANISOTROPIC) _MinTextureFilters[0][FILTER_TYPE_BEST]=D3DTEXF_ANISOTROPIC; - } - - // Set linear mip filter only if requested trilinear or anisotropic, and linear available - if (filter_type==TEXTURE_FILTER_ANISOTROPIC || filter_type==TEXTURE_FILTER_TRILINEAR) { - if (dx8caps.TextureFilterCaps&D3DPTFILTERCAPS_MIPFLINEAR) _MipMapFilters[0][FILTER_TYPE_BEST]=D3DTEXF_LINEAR; - } -#endif - - // For stages above zero, set best filter to the same as the stage zero, except if anisotropic - int i=1; - 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:: ww3d2/texturefilter.h $* - * * - * $Org Author:: Kenny Mitchell $* - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 08/05/02 1:27p $* - * * - * $Revision:: 1 $* - * * - * 08/05/02 KM Texture filter class abstraction * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#pragma once - -#ifndef DX8_WRAPPER_H -//#include "dx8wrapper.h" -#endif - -enum MipCountType -{ - MIP_LEVELS_ALL=0, // generate all mipmap levels down to 1x1 size - MIP_LEVELS_1, // no mipmapping at all (just one mip level) - MIP_LEVELS_2, - MIP_LEVELS_3, - MIP_LEVELS_4, - MIP_LEVELS_5, - MIP_LEVELS_6, - MIP_LEVELS_7, - MIP_LEVELS_8, - MIP_LEVELS_10, - MIP_LEVELS_11, - MIP_LEVELS_12, - MIP_LEVELS_MAX // This isn't to be used (use MIP_LEVELS_ALL instead), it is just an enum for creating static tables etc. -}; - - -// NOTE: Since "texture wrapping" (NOT TEXTURE WRAP MODE - THIS IS -// SOMETHING ELSE) is a global state that affects all texture stages, -// and this class only affects its own stage, we will not worry about -// it for now. Later (probably when we implement world-oriented -// environment maps) we will consider where to put it. - -// This is legacy and should be phased out into wwshade shader states -// keeping as an abstracted class for now to support this transition later -class TextureFilterClass -{ -public: - - enum FilterType - { - FILTER_TYPE_NONE, - FILTER_TYPE_FAST, - FILTER_TYPE_BEST, - FILTER_TYPE_DEFAULT, - FILTER_TYPE_COUNT - }; - - enum TextureFilterMode - { - TEXTURE_FILTER_BILINEAR, - TEXTURE_FILTER_TRILINEAR, - TEXTURE_FILTER_ANISOTROPIC - }; - - enum TxtAddrMode - { - TEXTURE_ADDRESS_REPEAT=0, - TEXTURE_ADDRESS_CLAMP - }; - - TextureFilterClass(MipCountType mip_level_count=MIP_LEVELS_1); - - void Apply(unsigned int stage); - - // Filter and MIPmap settings: - FilterType Get_Min_Filter(void) const { return TextureMinFilter; } - FilterType Get_Mag_Filter(void) const { return TextureMagFilter; } - FilterType Get_Mip_Mapping(void) const { return MipMapFilter; } - void Set_Min_Filter(FilterType filter) { TextureMinFilter=filter; } - void Set_Mag_Filter(FilterType filter) { TextureMagFilter=filter; } - void Set_Mip_Mapping(FilterType mipmap); - - // Texture address mode - TxtAddrMode Get_U_Addr_Mode(void) const { return UAddressMode; } - TxtAddrMode Get_V_Addr_Mode(void) const { return VAddressMode; } - void Set_U_Addr_Mode(TxtAddrMode mode) { UAddressMode=mode; } - void Set_V_Addr_Mode(TxtAddrMode mode) { VAddressMode=mode; } - - // This needs to be called after device has been created - static void _Init_Filters(TextureFilterMode texture_filter); - - static void _Set_Default_Min_Filter(FilterType filter); - static void _Set_Default_Mag_Filter(FilterType filter); - static void _Set_Default_Mip_Filter(FilterType filter); - -private: - // State not contained in the Direct3D texture object: - FilterType TextureMinFilter; - FilterType TextureMagFilter; - FilterType MipMapFilter; - TxtAddrMode UAddressMode; - TxtAddrMode VAddressMode; -}; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/textureloader.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/textureloader.cpp deleted file mode 100644 index 48f060f10c..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/textureloader.cpp +++ /dev/null @@ -1,2819 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : DX8 Texture Manager * - * * - * $Archive:: /Commando/Code/ww3d2/textureloader.h $* - * * - * Original Author:: vss_sync * - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 08/05/02 10:03a $* - * * - * $Revision:: 3 $* - * * - * 06/27/02 KM Texture class abstraction * - * 08/05/02 KM Texture class redesign (revisited) - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "textureloader.h" -#include "mutex.h" -#include "thread.h" -#include "wwdebug.h" -#include "texture.h" -#include "ffactory.h" -#include "wwstring.h" -#include "bufffile.h" -#include "ww3d.h" -#include "assetmgr.h" -#include "dx8wrapper.h" -#include "dx8caps.h" -#include "missingtexture.h" -#include "TARGA.h" -#include -#include "wwmemlog.h" -#include "formconv.h" -#include "texturethumbnail.h" -#include "ddsfile.h" -#include "bitmaphandler.h" -#include "wwprofile.h" - -bool TextureLoader::TextureLoadSuspended; -int TextureLoader::TextureInactiveOverrideTime = 0; - -#define USE_MANAGED_TEXTURES - -//////////////////////////////////////////////////////////////////////////////// -// -// TextureLoadTaskListClass implementation -// -//////////////////////////////////////////////////////////////////////////////// - -TextureLoadTaskListClass::TextureLoadTaskListClass(void) -: Root() -{ - Root.Next = Root.Prev = &Root; -} - -void TextureLoadTaskListClass::Push_Front (TextureLoadTaskClass *task) -{ - // task should non-null and not on any list - WWASSERT(task != NULL && task->Next == NULL && task->Prev == NULL); - - // update inserted task to point to list - task->Next = Root.Next; - task->Prev = &Root; - task->List = this; - - // update list to point to inserted task - Root.Next->Prev = task; - Root.Next = task; -} - -void TextureLoadTaskListClass::Push_Back(TextureLoadTaskClass *task) -{ - // task should be non-null and not on any list - WWASSERT(task != NULL && task->Next == NULL && task->Prev == NULL); - - // update inserted task to point to list - task->Next = &Root; - task->Prev = Root.Prev; - task->List = this; - - // update list to point to inserted task - Root.Prev->Next = task; - Root.Prev = task; -} - -TextureLoadTaskClass *TextureLoadTaskListClass::Pop_Front(void) -{ - // exit early if list is empty - if (Is_Empty()) { - return 0; - } - - // otherwise, grab first task and remove it. - TextureLoadTaskClass *task = (TextureLoadTaskClass *)Root.Next; - Remove(task); - return task; - -} - -TextureLoadTaskClass *TextureLoadTaskListClass::Pop_Back(void) -{ - // exit early if list is empty - if (Is_Empty()) { - return 0; - } - - // otherwise, grab last task and remove it. - TextureLoadTaskClass *task = (TextureLoadTaskClass *)Root.Prev; - Remove(task); - return task; -} - -void TextureLoadTaskListClass::Remove(TextureLoadTaskClass *task) -{ - // exit early if task is not on this list. - if (task->List != this) { - return; - } - - // update list to skip task - task->Prev->Next = task->Next; - task->Next->Prev = task->Prev; - - // update task to no longer point at list - task->Prev = 0; - task->Next = 0; - task->List = 0; -} - - -//////////////////////////////////////////////////////////////////////////////// -// -// SynchronizedTextureLoadTaskListClass implementation -// -//////////////////////////////////////////////////////////////////////////////// - -SynchronizedTextureLoadTaskListClass::SynchronizedTextureLoadTaskListClass(void) -: TextureLoadTaskListClass(), - CriticalSection() -{ -} - -void SynchronizedTextureLoadTaskListClass::Push_Front(TextureLoadTaskClass *task) -{ - FastCriticalSectionClass::LockClass lock(CriticalSection); - TextureLoadTaskListClass::Push_Front(task); -} - -void SynchronizedTextureLoadTaskListClass::Push_Back(TextureLoadTaskClass *task) -{ - FastCriticalSectionClass::LockClass lock(CriticalSection); - TextureLoadTaskListClass::Push_Back(task); -} - -TextureLoadTaskClass *SynchronizedTextureLoadTaskListClass::Pop_Front(void) -{ - // this duplicates code inside base class, but saves us an unnecessary lock. - if (Is_Empty()) { - return 0; - } - - FastCriticalSectionClass::LockClass lock(CriticalSection); - return TextureLoadTaskListClass::Pop_Front(); - -} - -TextureLoadTaskClass *SynchronizedTextureLoadTaskListClass::Pop_Back(void) -{ - // this duplicates code inside base class, but saves us an unnecessary lock. - if (Is_Empty()) { - return 0; - } - - FastCriticalSectionClass::LockClass lock(CriticalSection); - return TextureLoadTaskListClass::Pop_Back(); -} - -void SynchronizedTextureLoadTaskListClass::Remove(TextureLoadTaskClass *task) -{ - FastCriticalSectionClass::LockClass lock(CriticalSection); - TextureLoadTaskListClass::Remove(task); -} - - -// Locks - -// To prevent deadlock, threads should acquire locks in the order in which -// they are defined below. No ordering is necessary for the task list locks, -// since one thread can never hold two at once. - -static FastCriticalSectionClass _ForegroundCriticalSection; -static FastCriticalSectionClass _BackgroundCriticalSection; - -// Lists - -static SynchronizedTextureLoadTaskListClass _ForegroundQueue; -static SynchronizedTextureLoadTaskListClass _BackgroundQueue; - -static TextureLoadTaskListClass _TexLoadFreeList; -static TextureLoadTaskListClass _CubeTexLoadFreeList; -static TextureLoadTaskListClass _VolTexLoadFreeList; - - -// The background texture loading thread. -static class LoaderThreadClass : public ThreadClass -{ -public: -#ifdef Exception_Handler - LoaderThreadClass(const char *thread_name = "Texture loader thread") : ThreadClass(thread_name, &Exception_Handler) {} -#else - LoaderThreadClass(const char *thread_name = "Texture loader thread") : ThreadClass(thread_name) {} -#endif - - void Thread_Function(); -} _TextureLoadThread; - - -// TODO: Legacy - remove this call! -IDirect3DTexture8* Load_Compressed_Texture( - const StringClass& filename, - unsigned reduction_factor, - MipCountType mip_level_count, - WW3DFormat dest_format) -{ - // If DDS file isn't available, use TGA file to convert to DDS. - - DDSFileClass dds_file(filename,reduction_factor); - if (!dds_file.Is_Available()) return NULL; - if (!dds_file.Load()) return NULL; - - unsigned width=dds_file.Get_Width(0); - unsigned height=dds_file.Get_Height(0); - unsigned mips=dds_file.Get_Mip_Level_Count(); - - // If format isn't defined get the nearest valid texture format to the compressed file format - // Note that the nearest valid format could be anything, even uncompressed. - if (dest_format==WW3D_FORMAT_UNKNOWN) dest_format=Get_Valid_Texture_Format(dds_file.Get_Format(),true); - - IDirect3DTexture8* d3d_texture = DX8Wrapper::_Create_DX8_Texture - ( - width, - height, - dest_format, - (MipCountType)mips - ); - - for (unsigned level=0;levelGetSurfaceLevel(level/*-reduction_factor*/,&d3d_surface)); - dds_file.Copy_Level_To_Surface(level,d3d_surface); - d3d_surface->Release(); - } - return d3d_texture; -} - -static bool Is_Format_Compressed(WW3DFormat texture_format,bool allow_compression) -{ - // Verify that the user isn't requesting compressed texture without hardware support - - bool compressed=false; - if (texture_format!=WW3D_FORMAT_UNKNOWN) { - if (!DX8Wrapper::Get_Current_Caps()->Support_DXTC() || !allow_compression) { - WWASSERT(texture_format!=WW3D_FORMAT_DXT1); - WWASSERT(texture_format!=WW3D_FORMAT_DXT2); - WWASSERT(texture_format!=WW3D_FORMAT_DXT3); - WWASSERT(texture_format!=WW3D_FORMAT_DXT4); - WWASSERT(texture_format!=WW3D_FORMAT_DXT5); - } - if (texture_format==WW3D_FORMAT_DXT1 || - texture_format==WW3D_FORMAT_DXT2 || - texture_format==WW3D_FORMAT_DXT3 || - texture_format==WW3D_FORMAT_DXT4 || - texture_format==WW3D_FORMAT_DXT5) { - compressed=true; - } - } - - // 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() && - allow_compression); - - return compressed; -} - - -//////////////////////////////////////////////////////////////////////////////// -// -// TextureLoader implementation -// -//////////////////////////////////////////////////////////////////////////////// - -void TextureLoader::Init() -{ - WWASSERT(!_TextureLoadThread.Is_Running()); - - ThumbnailManagerClass::Init(); - - _TextureLoadThread.Execute(); - _TextureLoadThread.Set_Priority(-4); - TextureInactiveOverrideTime = 0; -} - - -void TextureLoader::Deinit() -{ - FastCriticalSectionClass::LockClass lock(_BackgroundCriticalSection); - _TextureLoadThread.Stop(); - - ThumbnailManagerClass::Deinit(); - TextureLoadTaskClass::Delete_Free_Pool(); -} - - -bool TextureLoader::Is_DX8_Thread(void) -{ - return (ThreadClass::_Get_Current_Thread_ID() == DX8Wrapper::_Get_Main_Thread_ID()); -} - - -// ---------------------------------------------------------------------------- -// -// Modify given texture size to nearest valid size on current hardware. -// -// ---------------------------------------------------------------------------- - -void TextureLoader::Validate_Texture_Size -( - unsigned& width, - unsigned& height, - unsigned& depth -) -{ - const D3DCAPS8& dx8caps=DX8Wrapper::Get_Current_Caps()->Get_DX8_Caps(); - - unsigned poweroftwowidth = 1; - while (poweroftwowidth < width) - { - poweroftwowidth <<= 1; - } - - unsigned poweroftwoheight = 1; - while (poweroftwoheight < height) - { - poweroftwoheight <<= 1; - } - - unsigned poweroftwodepth = 1; - while (poweroftwodepth< depth) - { - poweroftwodepth <<= 1; - } - - if (poweroftwowidth>dx8caps.MaxTextureWidth) - { - poweroftwowidth=dx8caps.MaxTextureWidth; - } - if (poweroftwoheight>dx8caps.MaxTextureHeight) - { - poweroftwoheight=dx8caps.MaxTextureHeight; - } - if (poweroftwodepth>dx8caps.MaxVolumeExtent) - { - poweroftwodepth=dx8caps.MaxVolumeExtent; - } - - if (poweroftwowidth>poweroftwoheight) - { - while (poweroftwowidth/poweroftwoheight>8) - { - poweroftwoheight*=2; - } - } - else - { - while (poweroftwoheight/poweroftwowidth>8) - { - poweroftwowidth*=2; - } - } - - width=poweroftwowidth; - height=poweroftwoheight; - depth=poweroftwodepth; -} - -IDirect3DTexture8* TextureLoader::Load_Thumbnail(const StringClass& filename, const Vector3& hsv_shift)//,WW3DFormat texture_format) -{ - WWASSERT(Is_DX8_Thread()); - - ThumbnailClass* thumb=NULL; - thumb=ThumbnailManagerClass::Peek_Thumbnail_Instance_From_Any_Manager(filename); - - // If no thumb is found return a missing texture - if (!thumb) { - return MissingTexture::_Get_Missing_Texture(); - } - - WWASSERT(thumb->Get_Format()==WW3D_FORMAT_A4R4G4B4); - unsigned src_pitch=thumb->Get_Width()*2; // Thumbs are always 16 bits - WW3DFormat dest_format; - WW3DFormat texture_format=WW3D_FORMAT_UNKNOWN; - if (texture_format==WW3D_FORMAT_UNKNOWN) { - dest_format=Get_Valid_Texture_Format(WW3D_FORMAT_A4R4G4B4,false); // no compressed formats please - } - else { - dest_format=Get_Valid_Texture_Format(texture_format,false); // no compressed formats please - WWASSERT(dest_format==texture_format); - } - - IDirect3DTexture8* sysmem_texture = DX8Wrapper::_Create_DX8_Texture( - thumb->Get_Width(), - thumb->Get_Height(), - dest_format, - MIP_LEVELS_ALL, -#ifdef USE_MANAGED_TEXTURES - D3DPOOL_MANAGED); -#else - D3DPOOL_SYSTEMMEM); -#endif - - unsigned level=0; - D3DLOCKED_RECT locked_rects[12]={0}; - WWASSERT(sysmem_texture->GetLevelCount()<=12); - - // Lock all surfaces - for (level=0;levelGetLevelCount();++level) { - DX8_ErrorCode( - sysmem_texture->LockRect( - level, - &locked_rects[level], - NULL, - 0)); - } - - unsigned char* src_surface=thumb->Peek_Bitmap(); - WW3DFormat src_format=thumb->Get_Format(); - unsigned width=thumb->Get_Width(); - unsigned height=thumb->Get_Height(); - - Vector3 hsv=hsv_shift; - for (level=0;levelGetLevelCount()-1;++level) { - BitmapHandlerClass::Copy_Image_Generate_Mipmap( - width, - height, - (unsigned char*)locked_rects[level].pBits, - locked_rects[level].Pitch, - dest_format, - src_surface, - src_pitch, - src_format, - (unsigned char*)locked_rects[level+1].pBits, // mipmap - locked_rects[level+1].Pitch, - hsv); - hsv=Vector3(0.0f,0.0f,0.0f); // Only do the shift for the first level, as the mipmaps are based on it. - - src_format=dest_format; - src_surface=(unsigned char*)locked_rects[level].pBits; - src_pitch=locked_rects[level].Pitch; - width>>=1; - height>>=1; - } - - // Unlock all surfaces - for (level=0;levelGetLevelCount();++level) { - DX8_ErrorCode(sysmem_texture->UnlockRect(level)); - } -#ifdef USE_MANAGED_TEXTURES - return sysmem_texture; -#else - IDirect3DTexture8* d3d_texture = DX8Wrapper::_Create_DX8_Texture( - thumb->Get_Width(), - thumb->Get_Height(), - dest_format, - TextureBaseClass::MIP_LEVELS_ALL, - D3DPOOL_DEFAULT); - DX8CALL(UpdateTexture(sysmem_texture,d3d_texture)); - sysmem_texture->Release(); - - WWDEBUG_SAY(("Created non-managed texture (%s)",filename)); - return d3d_texture; -#endif -} - - -// ---------------------------------------------------------------------------- -// -// Load image to a surface. The function tries to create texture that matches -// targa format. If suitable format is not available, it selects closest matching -// format and performs color space conversion. -// -// ---------------------------------------------------------------------------- -IDirect3DSurface8* TextureLoader::Load_Surface_Immediate( - const StringClass& filename, - WW3DFormat texture_format, - bool allow_compression) -{ - WWASSERT(Is_DX8_Thread()); - - bool compressed=Is_Format_Compressed(texture_format,allow_compression); - - if (compressed) { - IDirect3DTexture8* comp_tex=Load_Compressed_Texture(filename,0,MIP_LEVELS_1,WW3D_FORMAT_UNKNOWN); - if (comp_tex) { - IDirect3DSurface8* d3d_surface=NULL; - DX8_ErrorCode(comp_tex->GetSurfaceLevel(0,&d3d_surface)); - comp_tex->Release(); - return d3d_surface; - } - } - - // Make sure the file can be opened. If not, return missing texture. - Targa targa; - if (TARGA_ERROR_HANDLER(targa.Open(filename, TGA_READMODE),filename)) return MissingTexture::_Create_Missing_Surface(); - - // DX8 uses image upside down compared to TGA - targa.Header.ImageDescriptor ^= TGAIDF_YORIGIN; - - WW3DFormat src_format,dest_format; - unsigned src_bpp=0; - Get_WW3D_Format(dest_format,src_format,src_bpp,targa); - - if (texture_format!=WW3D_FORMAT_UNKNOWN) { - dest_format=texture_format; - } - - // Destination size will be the next power of two square from the larger width and height... - unsigned width, height; - width=targa.Header.Width; - height=targa.Header.Height; - unsigned src_width=targa.Header.Width; - unsigned src_height=targa.Header.Height; - - // NOTE: We load the palette but we do not yet support paletted textures! - char palette[256*4]; - targa.SetPalette(palette); - if (TARGA_ERROR_HANDLER(targa.Load(filename, TGAF_IMAGE, false),filename)) return MissingTexture::_Create_Missing_Surface(); - - unsigned char* src_surface=(unsigned char*)targa.GetImage(); - - // No paletted destination format allowed - unsigned char* converted_surface=NULL; - if (src_format==WW3D_FORMAT_A1R5G5B5 || src_format==WW3D_FORMAT_R5G6B5 || src_format==WW3D_FORMAT_A4R4G4B4 || - src_format==WW3D_FORMAT_P8 || src_format==WW3D_FORMAT_L8 || src_width!=width || src_height!=height) { - converted_surface=W3DNEWARRAY unsigned char[width*height*4]; - dest_format=Get_Valid_Texture_Format(WW3D_FORMAT_A8R8G8B8,false); - BitmapHandlerClass::Copy_Image( - converted_surface, - width, - height, - width*4, - WW3D_FORMAT_A8R8G8B8,//dest_format, - src_surface, - src_width, - src_height, - src_width*src_bpp, - src_format, - (unsigned char*)targa.GetPalette(), - targa.Header.CMapDepth>>3, - false); - src_surface=converted_surface; - src_format=WW3D_FORMAT_A8R8G8B8;//dest_format; - src_width=width; - src_height=height; - src_bpp=Get_Bytes_Per_Pixel(src_format); - } - - unsigned src_pitch=src_width*src_bpp; - - IDirect3DSurface8* d3d_surface = DX8Wrapper::_Create_DX8_Surface(width,height,dest_format); - WWASSERT(d3d_surface); - D3DLOCKED_RECT locked_rect; - DX8_ErrorCode( - d3d_surface->LockRect( - &locked_rect, - NULL, - 0)); - - BitmapHandlerClass::Copy_Image( - (unsigned char*)locked_rect.pBits, - width, - height, - locked_rect.Pitch, - dest_format, - src_surface, - src_width, - src_height, - src_pitch, - src_format, - (unsigned char*)targa.GetPalette(), - targa.Header.CMapDepth>>3, - false); // No mipmap - - DX8_ErrorCode(d3d_surface->UnlockRect()); - - delete[] converted_surface; - - return d3d_surface; -} - - -void TextureLoader::Request_Thumbnail(TextureBaseClass *tc) -{ - // Grab the foreground lock. This prevents the foreground thread - // from retiring any tasks related to this texture. It also - // serializes calls to Request_Thumbnail from multiple threads. - FastCriticalSectionClass::LockClass lock(_ForegroundCriticalSection); - - // Has a Direct3D texture already been loaded? - if (tc->Peek_D3D_Base_Texture()) { - return; - } - - TextureLoadTaskClass *task = tc->ThumbnailLoadTask; - - if (Is_DX8_Thread()) { - // load the thumbnail immediately - TextureLoader::Load_Thumbnail(tc); - - // clear any pending thumbnail load - if (task) { - _ForegroundQueue.Remove(task); - task->Destroy(); - } - - } else { - TextureLoadTaskClass *load_task = tc->TextureLoadTask; - - // if texture is not already loading a thumbnail and there is no - // background load near completion. (a background load waiting - // to be applied will be ready at the same time as a queued thumbnail. - // Why do the extra work?) - if (!task && (!load_task || load_task->Get_State() < TextureLoadTaskClass::STATE_LOAD_MIPMAP)) { - - // create a thumbnail load task and add to foreground queue. - task = TextureLoadTaskClass::Create(tc, TextureLoadTaskClass::TASK_THUMBNAIL, TextureLoadTaskClass::PRIORITY_LOW); - _ForegroundQueue.Push_Back(task); - } - } -} - - -void TextureLoader::Request_Background_Loading(TextureBaseClass *tc) -{ - WWPROFILE(("TextureLoader::Request_Background_Loading()")); - // Grab the foreground lock. This prevents the foreground thread - // from retiring any tasks related to this texture. It also - // serializes calls to Request_Background_Loading from other - // threads. - FastCriticalSectionClass::LockClass foreground_lock(_ForegroundCriticalSection); - - // Has the texture already been loaded? - if (tc->Is_Initialized()) { - return; - } - - TextureLoadTaskClass *task = tc->TextureLoadTask; - - // if texture already has a load task, we don't need to create another one. - if (task) { - return; - } - - task = TextureLoadTaskClass::Create(tc, TextureLoadTaskClass::TASK_LOAD, TextureLoadTaskClass::PRIORITY_LOW); - - if (Is_DX8_Thread()) { - Begin_Load_And_Queue(task); - } else { - _ForegroundQueue.Push_Back(task); - } -} - - -void TextureLoader::Request_Foreground_Loading(TextureBaseClass *tc) -{ - WWPROFILE(("TextureLoader::Request_Foreground_Loading()")); - // Grab the foreground lock. This prevents the foreground thread - // from retiring the load tasks for this texture. It also - // serializes calls to Request_Foreground_Loading from other - // threads. - FastCriticalSectionClass::LockClass foreground_lock(_ForegroundCriticalSection); - - // Has the texture already been loaded? - if (tc->Is_Initialized()) { - return; - } - - TextureLoadTaskClass *task = tc->TextureLoadTask; - TextureLoadTaskClass *task_thumb = tc->ThumbnailLoadTask; - - if (Is_DX8_Thread()) { - - // since we're in the DX8 thread, we can load the entire - // texture right now. - - // if we have a thumbnail task waiting, kill it. - if (task_thumb) { - _ForegroundQueue.Remove(task_thumb); - task_thumb->Destroy(); - } - - if (task) { - // we need to remove the task from any queue, since we're going - // to finish it up right now. - - // halt background thread. After we're holding this lock, - // we know the background thread cannot begin loading - // mipmap levels for this texture. - FastCriticalSectionClass::LockClass background_lock(_BackgroundCriticalSection); - _ForegroundQueue.Remove(task); - _BackgroundQueue.Remove(task); - } else { - // Since the task manages all the state associated with loading - // a texture, we temporarily create one. - task = TextureLoadTaskClass::Create(tc, TextureLoadTaskClass::TASK_LOAD, TextureLoadTaskClass::PRIORITY_HIGH); - } - - // finish loading the task and destroy it. - task->Finish_Load(); - task->Destroy(); - - } else { - // we are not in the DX8 thread. We need to add a high-priority loading - // task to the foreground queue. - - // Grab the background lock. After we're holding this lock, we - // know the background thread cannot begin loading mipmap levels - // for this texture. - FastCriticalSectionClass::LockClass background_lock(_BackgroundCriticalSection); - - // if we have a thumbnail task, we should cancel it. Since we are not - // the foreground thread, we are not allowed to call Destroy(). Instead, - // leave it queued in the completed state so it will be destroyed by Update(). - if (task_thumb) { - task_thumb->Set_State(TextureLoadTaskClass::STATE_COMPLETE); - } - - if (task) { - // if a load task is waiting on the background queue, we need to - // move it to the foreground queue. - if (task->Get_List() == &_BackgroundQueue) { - - // remove task from list - _BackgroundQueue.Remove(task); - - // add to foreground queue. - _ForegroundQueue.Push_Back(task); - } - - // upgrade the task priority - task->Set_Priority(TextureLoadTaskClass::PRIORITY_HIGH); - - } else { - // allocate high priority load task - task = TextureLoadTaskClass::Create(tc, TextureLoadTaskClass::TASK_LOAD, TextureLoadTaskClass::PRIORITY_HIGH); - - // add to back of foreground queue. - _ForegroundQueue.Push_Back(task); - } - } -} - - -void TextureLoader::Flush_Pending_Load_Tasks(void) -{ - // This function can only be called from the main thread. - // (Only the main thread can make the DX8 calls necessary - // to complete texture loading. If we wanted to flush - // the pending tasks from another thread, we'd probably - // want to set a bool that is checked by Update(). - WWASSERT(Is_DX8_Thread()); - - for (;;) { - bool done = false; - - { - // we have no pending load tasks when both queues are empty - // and the background thread is not processing a texture. - - // Grab the background lock. Once we're holding it, we - // know that the background thread is not processing any - // textures. - - // NOTE: It's important that we do only hold on to the background - // lock while we check for completion. Otherwise, we will either - // violate the lock order when we call Update() (which grabs - // the foreground lock) or never give the background thread - // a chance to empty its queue. - FastCriticalSectionClass::LockClass background_lock(_BackgroundCriticalSection); - done = _BackgroundQueue.Is_Empty() && _ForegroundQueue.Is_Empty(); - } - - // exit loop if no entries in list - if (done) { - break; - } - - Update(); - ThreadClass::Switch_Thread(); - } -} - - -// Nework update macro for texture loader. -#pragma warning(disable:4201) // warning C4201: nonstandard extension used : nameless struct/union -#include -#define UPDATE_NETWORK \ - if (network_callback) { \ - unsigned long time2 = timeGetTime(); \ - if (time2 - time > 20) { \ - network_callback(); \ - time = time2; \ - } \ - } \ - - -void TextureLoader::Update(void (*network_callback)(void)) -{ - WWASSERT_PRINT(Is_DX8_Thread(), "TextureLoader::Update must be called from the main thread!"); - - if (TextureLoadSuspended) { - return; - } - - // grab foreground lock to prevent any other thread from - // modifying texture tasks. - FastCriticalSectionClass::LockClass lock(_ForegroundCriticalSection); - - unsigned long time = timeGetTime(); - - // while we have tasks on the foreground queue - while (TextureLoadTaskClass *task = _ForegroundQueue.Pop_Front()) { - UPDATE_NETWORK; - // dispatch to proper task handler - switch (task->Get_Type()) { - case TextureLoadTaskClass::TASK_THUMBNAIL: - Process_Foreground_Thumbnail(task); - break; - - case TextureLoadTaskClass::TASK_LOAD: - Process_Foreground_Load(task); - break; - } - } - - TextureBaseClass::Invalidate_Old_Unused_Textures(TextureInactiveOverrideTime); -} - -void TextureLoader::Suspend_Texture_Load() -{ - WWASSERT_PRINT(Is_DX8_Thread(),"TextureLoader::Suspend_Texture_Load must be called from the main thread!"); - TextureLoadSuspended=true; -} - -void TextureLoader::Continue_Texture_Load() -{ - WWASSERT_PRINT(Is_DX8_Thread(),"TextureLoader::Continue_Texture_Load must be called from the main thread!"); - TextureLoadSuspended=false; -} - -void TextureLoader::Process_Foreground_Thumbnail(TextureLoadTaskClass *task) -{ - switch (task->Get_State()) { - case TextureLoadTaskClass::STATE_NONE: - Load_Thumbnail(task->Peek_Texture()); - FALLTHROUGH; // NOTE: fall-through is intentional - - case TextureLoadTaskClass::STATE_COMPLETE: - task->Destroy(); - break; - } -} - - -void TextureLoader::Process_Foreground_Load(TextureLoadTaskClass *task) -{ - // Is high-priority task? - if (task->Get_Priority() == TextureLoadTaskClass::PRIORITY_HIGH) { - task->Finish_Load(); - task->Destroy(); - return; - } - - // otherwise, must be a low-priority task. - - switch (task->Get_State()) { - case TextureLoadTaskClass::STATE_NONE: - Begin_Load_And_Queue(task); - break; - - case TextureLoadTaskClass::STATE_LOAD_MIPMAP: - task->End_Load(); - task->Destroy(); - break; - } -} - - -void TextureLoader::Begin_Load_And_Queue(TextureLoadTaskClass *task) -{ - // should only be called from the DX8 thread. - WWASSERT(Is_DX8_Thread()); - - if (task->Begin_Load()) { - // add to front of background queue. This means the - // background load thread will service tasks in LIFO - // (last in, first out) order. - - // NOTE: this was how the old code did it, with a - // comment that mentioned good reasons for doing so, - // without actually listing the reasons. I suspect - // it has something to do with visually important textures, - // like those in the foreground, starting their load last. - _BackgroundQueue.Push_Front(task); - } else { - // unable to load. - task->Apply_Missing_Texture(); - task->Destroy(); - } -} - - -void TextureLoader::Load_Thumbnail(TextureBaseClass *tc) -{ - // All D3D operations must run from main thread - WWASSERT(Is_DX8_Thread()); - - // load thumbnail texture - IDirect3DTexture8 *d3d_texture = Load_Thumbnail(tc->Get_Full_Path(),tc->Get_HSV_Shift()); - - // apply thumbnail to texture - if (tc->Get_Asset_Type()==TextureBaseClass::TEX_REGULAR) - { - tc->Apply_New_Surface(d3d_texture, false); - } - - // release our reference to thumbnail texture - d3d_texture->Release(); - d3d_texture = 0; -} - - -void LoaderThreadClass::Thread_Function(void) -{ - while (running) { - // if there are no tasks on the background queue, no need to grab background lock. - if (!_BackgroundQueue.Is_Empty()) { - // Grab background load so other threads know we could be - // loading a texture. - FastCriticalSectionClass::LockClass lock(_BackgroundCriticalSection); - - // try to remove a task from the background queue. This could fail - // if another thread modified the queue between our test above and - // grabbing the lock. - TextureLoadTaskClass* task = _BackgroundQueue.Pop_Front(); - if (task) { - // verify task is in proper state for background processing. - WWASSERT(task->Get_Type() == TextureLoadTaskClass::TASK_LOAD); - WWASSERT(task->Get_State() == TextureLoadTaskClass::STATE_LOAD_BEGUN); - - // load mip map levels and return to foreground queue for final step. - task->Load(); - _ForegroundQueue.Push_Back(task); - } - } - - Switch_Thread(); - } -} - - -//////////////////////////////////////////////////////////////////////////////// -// -// TextureLoaderTaskClass implementation -// -//////////////////////////////////////////////////////////////////////////////// - -TextureLoadTaskClass::TextureLoadTaskClass() -: Texture (0), - D3DTexture (0), - Format (WW3D_FORMAT_UNKNOWN), - Width (0), - Height (0), - MipLevelCount (0), - Reduction (0), - Type (TASK_NONE), - Priority (PRIORITY_LOW), - State (STATE_NONE), - HSVShift (0.0f,0.0f,0.0f) -{ - // because texture load tasks are pooled, the constructor and destructor - // don't need to do much. The work of attaching a task to a texture is - // is done by Init() and Deinit(). - - for (int i = 0; i < MIP_LEVELS_MAX; ++i) { - LockedSurfacePtr[i] = NULL; - LockedSurfacePitch[i] = 0; - } -} - - -TextureLoadTaskClass::~TextureLoadTaskClass(void) -{ - Deinit(); -} - - -TextureLoadTaskClass *TextureLoadTaskClass::Create(TextureBaseClass *tc, TaskType type, PriorityType priority) -{ - // recycle or create a new texture load task with the given type - // and priority, then associate the texture with the task. - - // pull a load task from front of free list - TextureLoadTaskClass *task = NULL; - switch (tc->Get_Asset_Type()) - { - case TextureBaseClass::TEX_REGULAR : task=_TexLoadFreeList.Pop_Front(); break; - case TextureBaseClass::TEX_CUBEMAP : task=_CubeTexLoadFreeList.Pop_Front(); break; - case TextureBaseClass::TEX_VOLUME : task=_VolTexLoadFreeList.Pop_Front(); break; - default : WWASSERT(0); - }; - - // if no tasks on free list, allocate a new task - if (!task) - { - switch (tc->Get_Asset_Type()) - { - case TextureBaseClass::TEX_REGULAR : task=new TextureLoadTaskClass; break; - case TextureBaseClass::TEX_CUBEMAP : task=new CubeTextureLoadTaskClass; break; - case TextureBaseClass::TEX_VOLUME : task=new VolumeTextureLoadTaskClass; break; - default : WWASSERT(0); - } - } - task->Init(tc, type, priority); - return task; -} - - -void TextureLoadTaskClass::Destroy(void) -{ - // detach the task from its texture, and return to free pool. - Deinit(); - _TexLoadFreeList.Push_Front(this); -} - - -void TextureLoadTaskClass::Delete_Free_Pool(void) -{ - // (gth) We should probably just MEMPool these task objects... - while (TextureLoadTaskClass *task = _TexLoadFreeList.Pop_Front()) { - delete task; - } - while (TextureLoadTaskClass *task = _CubeTexLoadFreeList.Pop_Front()) { - delete task; - } - while (TextureLoadTaskClass *task = _VolTexLoadFreeList.Pop_Front()) { - delete task; - } -} - - -void TextureLoadTaskClass::Init(TextureBaseClass* tc, TaskType type, PriorityType priority) -{ - WWASSERT(tc); - - // NOTE: we must be in the main thread to avoid corrupting the texture's refcount. - WWASSERT(TextureLoader::Is_DX8_Thread()); - REF_PTR_SET(Texture, tc); - - // Make sure texture has a filename. - WWASSERT(!Texture->Get_Full_Path().Is_Empty()); - - Type = type; - Priority = priority; - State = STATE_NONE; - - D3DTexture = 0; - - TextureClass* tex=Texture->As_TextureClass(); - - if (tex) - { - Format = tex->Get_Texture_Format(); // don't assume format yet KM - } - else - { - Format = WW3D_FORMAT_UNKNOWN; - } - - Width = 0; - Height = 0; - MipLevelCount = Texture->MipLevelCount; - Reduction = Texture->Get_Reduction(); - HSVShift = Texture->Get_HSV_Shift(); - - - for (int i = 0; i < MIP_LEVELS_MAX; ++i) - { - LockedSurfacePtr[i] = NULL; - LockedSurfacePitch[i] = 0; - } - - switch (Type) - { - case TASK_THUMBNAIL: - WWASSERT(Texture->ThumbnailLoadTask == NULL); - Texture->ThumbnailLoadTask = this; - break; - - case TASK_LOAD: - WWASSERT(Texture->TextureLoadTask == NULL); - Texture->TextureLoadTask = this; - break; - } -} - - -void TextureLoadTaskClass::Deinit() -{ - // task should not be on any list when it is being detached from texture. - WWASSERT(Next == NULL); - WWASSERT(Prev == NULL); - - WWASSERT(D3DTexture == NULL); - - for (int i = 0; i < MIP_LEVELS_MAX; ++i) { - WWASSERT(LockedSurfacePtr[i] == NULL); - } - - if (Texture) { - switch (Type) { - case TASK_THUMBNAIL: - WWASSERT(Texture->ThumbnailLoadTask == this); - Texture->ThumbnailLoadTask = NULL; - break; - - case TASK_LOAD: - WWASSERT(Texture->TextureLoadTask == this); - Texture->TextureLoadTask = NULL; - break; - } - - // NOTE: we must be in main thread to avoid corrupting Texture's refcount. - WWASSERT(TextureLoader::Is_DX8_Thread()); - REF_PTR_RELEASE(Texture); - } -} - - -bool TextureLoadTaskClass::Begin_Load(void) -{ - WWASSERT(TextureLoader::Is_DX8_Thread()); - - bool loaded = false; - - // if allowed, begin a compressed load - if (Texture->Is_Compression_Allowed()) { - loaded = Begin_Compressed_Load(); - } - - // otherwise, begin an uncompressed load - if (!loaded) { - loaded = Begin_Uncompressed_Load(); - } - - // if not loaded, abort. - if (!loaded) { - return false; - } - - // lock surfaces in preparation for copy - Lock_Surfaces(); - - State = STATE_LOAD_BEGUN; - - return true; -} - - -// ---------------------------------------------------------------------------- -// -// Load mipmap levels to a pre-generated and locked texture object based on -// information in load task object. Try loading from a DDS file first and if -// that fails try a TGA. -// -// ---------------------------------------------------------------------------- -bool TextureLoadTaskClass::Load(void) -{ - WWMEMLOG(MEM_TEXTURE); - WWASSERT(Peek_D3D_Texture()); - - bool loaded = false; - - // if allowed, try to load compressed mipmaps - if (Texture->Is_Compression_Allowed()) { - loaded = Load_Compressed_Mipmap(); - } - - // otherwise, load uncompressed mipmaps - if (!loaded) { - loaded = Load_Uncompressed_Mipmap(); - } - - State = STATE_LOAD_MIPMAP; - - return loaded; -} - - -void TextureLoadTaskClass::End_Load(void) -{ - WWASSERT(TextureLoader::Is_DX8_Thread()); - - Unlock_Surfaces(); - Apply(true); - - State = STATE_LOAD_COMPLETE; -} - - -void TextureLoadTaskClass::Finish_Load(void) -{ - switch (State) { - // NOTE: fall-through below is intentional. - - case STATE_NONE: - if (!Begin_Load()) { - Apply_Missing_Texture(); - break; - } - FALLTHROUGH; - - case STATE_LOAD_BEGUN: - Load(); - FALLTHROUGH; - - case STATE_LOAD_MIPMAP: - End_Load(); - FALLTHROUGH; - - default: - break; - } -} - - -void TextureLoadTaskClass::Apply_Missing_Texture(void) -{ - WWASSERT(TextureLoader::Is_DX8_Thread()); - WWASSERT(!D3DTexture); - - D3DTexture = MissingTexture::_Get_Missing_Texture(); - Apply(true); -} - - -void TextureLoadTaskClass::Apply(bool initialize) -{ - WWASSERT(D3DTexture); - - // Verify that none of the mip levels are locked - for (unsigned i=0;iApply_New_Surface(D3DTexture, initialize); - - D3DTexture->Release(); - D3DTexture = NULL; -} - -static bool Get_Texture_Information -( - const char* filename, - unsigned& reduction, - unsigned& w, - unsigned& h, - unsigned& d, - WW3DFormat& format, - unsigned& mip_count, - bool compressed -) -{ - ThumbnailClass* thumb=ThumbnailManagerClass::Peek_Thumbnail_Instance_From_Any_Manager(filename); - - if (!thumb) - { - if (compressed) - { - DDSFileClass dds_file(filename, 0); - if (!dds_file.Is_Available()) return false; - - // Destination size will be the next power of two square from the larger width and height... - w = dds_file.Get_Width(0); - h = dds_file.Get_Height(0); - d = dds_file.Get_Depth(0); - format = dds_file.Get_Format(); - mip_count = dds_file.Get_Mip_Level_Count(); - //Figure out correct reduction - int reqReduction=WW3D::Get_Texture_Reduction(); //requested reduction - - if (reqReduction >= mip_count) - reqReduction=mip_count-1; //leave only the lowest level - - //Clamp reduction - int curReduction=0; - int curWidth=w; - int curHeight=h; - int minDim=WW3D::Get_Texture_Min_Dimension(); - - while (curReduction < reqReduction && curWidth > minDim && curHeight > minDim) - { curWidth >>=1; //keep dividing - curHeight >>=1; - curReduction++; - } - reduction=curReduction; - return true; - } - - Targa targa; - if (TARGA_ERROR_HANDLER(targa.Open(filename, TGA_READMODE), filename)) - { - return false; - } - - unsigned int bpp; - WW3DFormat dest_format; - Get_WW3D_Format(dest_format,format,bpp,targa); - - mip_count = 0; - - //Figure out how many mip levels this texture will occupy - for (int i=targa.Header.Width, j=targa.Header.Height; i > 0 && j > 0; i>>=1, j>>=1) - mip_count++; - - //Figure out correct reduction - int reqReduction=WW3D::Get_Texture_Reduction(); //requested reduction - - if (reqReduction >= mip_count) - reqReduction=mip_count-1; //leave only the lowest level - - //Clamp reduction - int curReduction=0; - int curWidth=targa.Header.Width; - int curHeight=targa.Header.Height; - int minDim=WW3D::Get_Texture_Min_Dimension(); - - while (curReduction < reqReduction && curWidth > minDim && curHeight > minDim) - { curWidth >>=1; //keep dividing - curHeight >>=1; - curReduction++; - } - reduction=curReduction; - - // Destination size will be the next power of two square from the larger width and height... - w = targa.Header.Width; - h = targa.Header.Height; - d = 1; - return true; - } - - if (compressed && - thumb->Get_Original_Texture_Format()!=WW3D_FORMAT_DXT1 && - thumb->Get_Original_Texture_Format()!=WW3D_FORMAT_DXT2 && - thumb->Get_Original_Texture_Format()!=WW3D_FORMAT_DXT3 && - thumb->Get_Original_Texture_Format()!=WW3D_FORMAT_DXT4 && - thumb->Get_Original_Texture_Format()!=WW3D_FORMAT_DXT5) { - return false; - } - - w=thumb->Get_Original_Texture_Width() >> reduction; - h=thumb->Get_Original_Texture_Height() >> reduction; - //d=thumb->Get_Original_Texture_Depth() >> reduction; // need to a volume texture support to thumbnails...maybe - mip_count=thumb->Get_Original_Texture_Mip_Level_Count(); - format=thumb->Get_Original_Texture_Format(); - return true; -} - - -bool TextureLoadTaskClass::Begin_Compressed_Load(void) -{ - unsigned orig_w,orig_h,orig_d,orig_mip_count,reduction; - WW3DFormat orig_format; - if (!Get_Texture_Information - ( - Texture->Get_Full_Path(), - reduction, - orig_w, - orig_h, - orig_d, - orig_format, - orig_mip_count, - true - ) - ) - { - return false; - } - - // Destination size will be the next power of two square from the larger width and height... - unsigned int width = orig_w; - unsigned int height = orig_h; - TextureLoader::Validate_Texture_Size(width, height,orig_d); - - // If the size doesn't match, try and see if texture reduction would help... (mainly for - // cases where loaded texture is larger than hardware limit) - if (width != orig_w || height != orig_h) - { - for (unsigned int i = 1; i < orig_mip_count; ++i) - { - unsigned w=orig_w>>i; - if (w<4) w=4; - unsigned h=orig_h>>i; - if (h<4) h=4; - unsigned tmp_w=w; - unsigned tmp_h=h; - - TextureLoader::Validate_Texture_Size(w,h,orig_d); - - if (w == tmp_w && h == tmp_h) - { - Reduction += i; - width = w; - height = h; - break; - } - } - } - - Width = width; - Height = height; - Format = Get_Valid_Texture_Format(orig_format, Texture->Is_Compression_Allowed()); - Reduction = reduction; - - - if (!Texture->Is_Reducible() || Texture->MipLevelCount == MIP_LEVELS_1) - Reduction = 0; //app doesn't want this texture to ever be reduced. - else - //Make sure we don't reduce below the level requested by the app - if (Texture->MipLevelCount != MIP_LEVELS_ALL && (Texture->MipLevelCount - Reduction) < 1) - Reduction = Texture->MipLevelCount - 1; - - //Another sanity check - if (Reduction >= orig_mip_count) - Reduction = 0; //should not be possible to get here, but check just in case. - - unsigned int mip_level_count = Get_Mip_Level_Count(); - int reducedWidth=Width; - int reducedHeight=Height; - - // If texture wants all mip levels, take as many as the file contains (not necessarily all) - // Otherwise take as many mip levels as the texture wants, not to exceed the count in file... - if (!mip_level_count) - { - reducedWidth >>= Reduction; - reducedHeight >>= Reduction; - mip_level_count = orig_mip_count-Reduction;//dds_file.Get_Mip_Level_Count(); - if (mip_level_count < 1) - mip_level_count = 1; //sanity check to make sure something gets loaded. - } - else - { - if (mip_level_count > orig_mip_count) - { //dds_file.Get_Mip_Level_Count()) { - mip_level_count = orig_mip_count;//dds_file.Get_Mip_Level_Count(); - } - - if (Reduction) - { reducedWidth >>= Reduction; - reducedHeight >>= Reduction; - mip_level_count -= Reduction; //reduced requested number by those removed. - } - } - - // Once more, verify that the mip level count is correct (in case it was changed here it might not - // match the size...well actually it doesn't have to match but it can't be bigger than the size) - unsigned int max_mip_level_count = 1; - unsigned int w = 4; - unsigned int h = 4; - - while (w < Width && h < Height) - { - w += w; - h += h; - max_mip_level_count++; - } - - if (mip_level_count > max_mip_level_count) - { - mip_level_count = max_mip_level_count; - } - - D3DTexture = DX8Wrapper::_Create_DX8_Texture - ( - reducedWidth, - reducedHeight, - Format, - (MipCountType)mip_level_count, -#ifdef USE_MANAGED_TEXTURES - D3DPOOL_MANAGED -#else - D3DPOOL_SYSTEMMEM -#endif - ); - - MipLevelCount = mip_level_count; - - return true; -} - -bool TextureLoadTaskClass::Begin_Uncompressed_Load(void) -{ - unsigned width,height,depth,orig_mip_count,reduction; - WW3DFormat orig_format; - if (!Get_Texture_Information - ( - Texture->Get_Full_Path(), - reduction, - width, - height, - depth, - orig_format, - orig_mip_count, - false - ) - ) - { - return false; - } - - WW3DFormat src_format=orig_format; - WW3DFormat dest_format=src_format; - dest_format=Get_Valid_Texture_Format(dest_format,false); // No compressed destination format if reading from targa... - - if ( src_format != WW3D_FORMAT_A8R8G8B8 - && src_format != WW3D_FORMAT_R8G8B8 - && src_format != WW3D_FORMAT_X8R8G8B8 ) - { - WWDEBUG_SAY(("Invalid TGA format used in %s - only 24 and 32 bit formats should be used!", Texture->Get_Full_Path().str())); - } - - // Destination size will be the next power of two square from the larger width and height... - unsigned ow = width; - unsigned oh = height; - TextureLoader::Validate_Texture_Size(width, height,depth); - if (width != ow || height != oh) - { - WWDEBUG_SAY(("Invalid texture size, scaling required. Texture: %s, size: %d x %d -> %d x %d", Texture->Get_Full_Path().str(), ow, oh, width, height)); - } - - Width = width; - Height = height; - Reduction = reduction; - - if (!Texture->Is_Reducible() || Texture->MipLevelCount == MIP_LEVELS_1) - Reduction = 0; //app doesn't want this texture to ever be reduced. - else - //Make sure we don't reduce below the level requested by the app - if (Texture->MipLevelCount != MIP_LEVELS_ALL && (Texture->MipLevelCount - Reduction) < 1) - Reduction = Texture->MipLevelCount - 1; - - //Another sanity check - if (Reduction >= orig_mip_count) - Reduction = 0; //should not be possible to get here, but check just in case. - - if (Format == WW3D_FORMAT_UNKNOWN) - { - Format=dest_format; - // Format = Get_Valid_Texture_Format(dest_format, false); validated above - } - else - { - Format = Get_Valid_Texture_Format(Format, false); - } - - int reducedWidth=Width; - int reducedHeight=Height; - int reducedMipCount=Texture->MipLevelCount; - - if (Reduction) - { //we don't care about specific levels so reduce them if needed. - reducedWidth >>= Reduction; - reducedHeight >>= Reduction; - if (reducedMipCount != MIP_LEVELS_ALL) - reducedMipCount -= Reduction; - } - - D3DTexture = DX8Wrapper::_Create_DX8_Texture - ( - reducedWidth, - reducedHeight, - Format, - (MipCountType)reducedMipCount, -#ifdef USE_MANAGED_TEXTURES - D3DPOOL_MANAGED -#else - D3DPOOL_SYSTEMMEM -#endif - ); - - return true; -} - -/* -bool TextureLoadTaskClass::Begin_Compressed_Load(void) -{ - DDSFileClass dds_file(Texture->Get_Full_Path(), Get_Reduction()); - if (!dds_file.Is_Available()) { - return false; - } - - // Destination size will be the next power of two square from the larger width and height... - unsigned int width = dds_file.Get_Width(0); - unsigned int height = dds_file.Get_Height(0); - TextureLoader::Validate_Texture_Size(width, height); - - // If the size doesn't match, try and see if texture reduction would help... (mainly for - // cases where loaded texture is larger than hardware limit) - if (width != dds_file.Get_Width(0) || height != dds_file.Get_Height(0)) { - for (unsigned int i = 1; i < dds_file.Get_Mip_Level_Count(); ++i) { - unsigned int w = dds_file.Get_Width(i); - unsigned int h = dds_file.Get_Height(i); - TextureLoader::Validate_Texture_Size(w,h); - - if (w == dds_file.Get_Width(i) && h == dds_file.Get_Height(i)) { - Reduction += i; - width = w; - height = h; - break; - } - } - } - - Width = width; - Height = height; - Format = Get_Valid_Texture_Format(dds_file.Get_Format(), Texture->Is_Compression_Allowed()); - - unsigned int mip_level_count = Get_Mip_Level_Count(); - - // If texture wants all mip levels, take as many as the file contains (not necessarily all) - // Otherwise take as many mip levels as the texture wants, not to exceed the count in file... - if (!mip_level_count) { - mip_level_count = dds_file.Get_Mip_Level_Count(); - } else if (mip_level_count > dds_file.Get_Mip_Level_Count()) { - mip_level_count = dds_file.Get_Mip_Level_Count(); - } - - // Once more, verify that the mip level count is correct (in case it was changed here it might not - // match the size...well actually it doesn't have to match but it can't be bigger than the size) - unsigned int max_mip_level_count = 1; - unsigned int w = 4; - unsigned int h = 4; - - while (w < Width && h < Height) { - w += w; - h += h; - max_mip_level_count++; - } - - if (mip_level_count > max_mip_level_count) { - mip_level_count = max_mip_level_count; - } - - D3DTexture = DX8Wrapper::_Create_DX8_Texture( - Width, - Height, - Format, - (TextureBaseClass::MipCountType)mip_level_count, -#ifdef USE_MANAGED_TEXTURES - D3DPOOL_MANAGED); -#else - D3DPOOL_SYSTEMMEM); -#endif - MipLevelCount = mip_level_count; - return true; -} - - -bool TextureLoadTaskClass::Begin_Uncompressed_Load(void) -{ - Targa targa; - if (TARGA_ERROR_HANDLER(targa.Open(Texture->Get_Full_Path(), TGA_READMODE), Texture->Get_Full_Path())) { - return false; - } - - unsigned int bpp; - WW3DFormat src_format, dest_format; - Get_WW3D_Format(dest_format,src_format,bpp,targa); - - if ( src_format != WW3D_FORMAT_A8R8G8B8 - && src_format != WW3D_FORMAT_R8G8B8 - && src_format != WW3D_FORMAT_X8R8G8B8) { - WWDEBUG_SAY(("Invalid TGA format used in %s - only 24 and 32 bit formats should be used!", Texture->Get_Full_Path())); - } - - // Destination size will be the next power of two square from the larger width and height... - unsigned width=targa.Header.Width, height=targa.Header.Height; - int ReductionFactor=Get_Reduction(); - int MipLevels=0; - - //Figure out how many mip levels this texture will occupy - for (int i=width, j=height; i > 0 && j > 0; i>>=1, j>>=1) - MipLevels++; - - //Adjust the reduction factor to keep textures above some minimum dimensions - if (MipLevels <= WW3D::Get_Texture_Min_Mip_Levels()) - ReductionFactor=0; - else - { int mipToDrop=MipLevels-WW3D::Get_Texture_Min_Mip_Levels(); - if (ReductionFactor >= mipToDrop) - ReductionFactor=mipToDrop; - } - - width=targa.Header.Width>>ReductionFactor; - height=targa.Header.Height>>ReductionFactor; - unsigned ow = width; - unsigned oh = height; - TextureLoader::Validate_Texture_Size(width, height); - if (width != ow || height != oh) { - WWDEBUG_SAY(("Invalid texture size, scaling required. Texture: %s, size: %d x %d -> %d x %d", Texture->Get_Full_Path(), ow, oh, width, height)); - } - - Width = width; - Height = height; - - // changed because format was being read from previous loading task?! KJM - Format=dest_format; - //if (Format == WW3D_FORMAT_UNKNOWN) { - // Format = Get_Valid_Texture_Format(dest_format, false); - //} else { - // Format = Get_Valid_Texture_Format(Format, false); - //} - - D3DTexture = DX8Wrapper::_Create_DX8_Texture - ( - Width, - Height, - Format, - Texture->MipLevelCount, -#ifdef USE_MANAGED_TEXTURES - D3DPOOL_MANAGED); -#else - D3DPOOL_SYSTEMMEM); -#endif - return true; -} -*/ - -void TextureLoadTaskClass::Lock_Surfaces(void) -{ - MipLevelCount = D3DTexture->GetLevelCount(); - - for (unsigned int i = 0; i < MipLevelCount; ++i) - { - D3DLOCKED_RECT locked_rect; - DX8_ErrorCode - ( - Peek_D3D_Texture()->LockRect - ( - i, - &locked_rect, - NULL, - 0 - ) - ); - LockedSurfacePtr[i] = (unsigned char *)locked_rect.pBits; - LockedSurfacePitch[i] = locked_rect.Pitch; - } -} - - -void TextureLoadTaskClass::Unlock_Surfaces(void) -{ - for (unsigned int i = 0; i < MipLevelCount; ++i) - { - if (LockedSurfacePtr[i]) - { - WWASSERT(ThreadClass::_Get_Current_Thread_ID() == DX8Wrapper::_Get_Main_Thread_ID()); - DX8_ErrorCode(Peek_D3D_Texture()->UnlockRect(i)); - } - LockedSurfacePtr[i] = NULL; - } - -#ifndef USE_MANAGED_TEXTURES - IDirect3DTexture8* tex = DX8Wrapper::_Create_DX8_Texture(Width, Height, Format, Texture->MipLevelCount,D3DPOOL_DEFAULT); - DX8CALL(UpdateTexture(Peek_D3D_Texture(),tex)); - Peek_D3D_Texture()->Release(); - D3DTexture=tex; - WWDEBUG_SAY(("Created non-managed texture (%s)",Texture->Get_Full_Path())); -#endif - -} - - -bool TextureLoadTaskClass::Load_Compressed_Mipmap(void) -{ - DDSFileClass dds_file(Texture->Get_Full_Path(), Get_Reduction()); - - // if we can't load from file, indicate rror. - if (!dds_file.Is_Available() || !dds_file.Load()) - { - return false; - } - - // regular 2d texture - unsigned int width = Get_Width(); - unsigned int height = Get_Height(); - - if (Reduction) - { for (unsigned int level = 0; level < Reduction; ++level) { - width >>= 1; - height >>= 1; - } - } - - for (unsigned int level = 0; level < Get_Mip_Level_Count(); ++level) - { - WWASSERT(width && height); - dds_file.Copy_Level_To_Surface - ( - level, - Get_Format(), - width, - height, - Get_Locked_Surface_Ptr(level), - Get_Locked_Surface_Pitch(level), - HSVShift - ); - - width >>= 1; - height >>= 1; - } - - return true; -} - - -bool TextureLoadTaskClass::Load_Uncompressed_Mipmap(void) -{ - if (!Get_Mip_Level_Count()) - { - return false; - } - - Targa targa; - if (TARGA_ERROR_HANDLER(targa.Open(Texture->Get_Full_Path(), TGA_READMODE), Texture->Get_Full_Path())) { - return false; - } - - // DX8 uses image upside down compared to TGA - targa.Header.ImageDescriptor ^= TGAIDF_YORIGIN; - - WW3DFormat src_format; - WW3DFormat dest_format; - unsigned int src_bpp = 0; - Get_WW3D_Format(dest_format,src_format,src_bpp,targa); - if (src_format==WW3D_FORMAT_UNKNOWN) return false; - - dest_format = Get_Format(); // Texture can be requested in different format than the most obvious from the TGA - - char palette[256*4]; - targa.SetPalette(palette); - - unsigned int src_width = targa.Header.Width; - unsigned int src_height = targa.Header.Height; - unsigned int width = Get_Width(); - unsigned int height = Get_Height(); - - // NOTE: We load the palette but we do not yet support paletted textures! - if (TARGA_ERROR_HANDLER(targa.Load(Texture->Get_Full_Path(), TGAF_IMAGE, false), Texture->Get_Full_Path())) { - return false; - } - - unsigned char * src_surface = (unsigned char*)targa.GetImage(); - unsigned char * converted_surface = NULL; - - // No paletted format allowed when generating mipmaps - Vector3 hsv_shift=HSVShift; - if ( src_format == WW3D_FORMAT_A1R5G5B5 - || src_format == WW3D_FORMAT_R5G6B5 - || src_format == WW3D_FORMAT_A4R4G4B4 - || src_format == WW3D_FORMAT_P8 - || src_format == WW3D_FORMAT_L8 - || src_width != width - || src_height != height) { - - converted_surface = new unsigned char[width*height*4]; - dest_format = Get_Valid_Texture_Format(WW3D_FORMAT_A8R8G8B8, false); - - BitmapHandlerClass::Copy_Image( - converted_surface, - width, - height, - width*4, - WW3D_FORMAT_A8R8G8B8, //dest_format, - src_surface, - src_width, - src_height, - src_width*src_bpp, - src_format, - (unsigned char*)targa.GetPalette(), - targa.Header.CMapDepth>>3, - false, - hsv_shift); - hsv_shift=Vector3(0.0f,0.0f,0.0f); - - src_surface = converted_surface; - src_format = WW3D_FORMAT_A8R8G8B8; //dest_format; - src_width = width; - src_height = height; - src_bpp = Get_Bytes_Per_Pixel(src_format); - } - - unsigned src_pitch = src_width * src_bpp; - - if (Reduction) - { //texture needs to be reduced so allocate storage for full-sized version. - unsigned char * destination_surface = new unsigned char[width*height*4]; - //generate upper mip-levels that will be dropped in final texture - for (unsigned int level = 0; level < Reduction; ++level) { - BitmapHandlerClass::Copy_Image( - (unsigned char *)destination_surface, - width, - height, - src_pitch, - Get_Format(), - src_surface, - src_width, - src_height, - src_pitch, - src_format, - NULL, - 0, - true, - hsv_shift); - - width >>= 1; - height >>= 1; - src_width >>= 1; - src_height >>= 1; - } - delete [] destination_surface; - } - - for (unsigned int level = 0; level < Get_Mip_Level_Count(); ++level) { - WWASSERT(Get_Locked_Surface_Ptr(level)); - BitmapHandlerClass::Copy_Image( - Get_Locked_Surface_Ptr(level), - width, - height, - Get_Locked_Surface_Pitch(level), - Get_Format(), - src_surface, - src_width, - src_height, - src_pitch, - src_format, - NULL, - 0, - true, - hsv_shift); - hsv_shift=Vector3(0.0f,0.0f,0.0f); - - width >>= 1; - height >>= 1; - src_width >>= 1; - src_height >>= 1; - - if (!width || !height || !src_width || !src_height) { - break; - } - } - - delete[] converted_surface; - - return true; -} - - -unsigned char * TextureLoadTaskClass::Get_Locked_Surface_Ptr(unsigned int level) -{ - WWASSERT(levelGet_Full_Path().Is_Empty()); - - Type = type; - Priority = priority; - State = STATE_NONE; - - D3DTexture = 0; - - CubeTextureClass* tex=Texture->As_CubeTextureClass(); - - if (tex) - { - Format = tex->Get_Texture_Format(); // don't assume format yet KM - } - else - { - Format = WW3D_FORMAT_UNKNOWN; - } - - Width = 0; - Height = 0; - MipLevelCount = Texture->MipLevelCount; - Reduction = Texture->Get_Reduction(); - HSVShift = Texture->Get_HSV_Shift(); - - - for (int f=0; f<6; f++) - { - for (int i = 0; i < MIP_LEVELS_MAX; ++i) - { - LockedCubeSurfacePtr[f][i] = NULL; - LockedCubeSurfacePitch[f][i] = 0; - } - } - - switch (Type) - { - case TASK_THUMBNAIL: - WWASSERT(Texture->ThumbnailLoadTask == NULL); - Texture->ThumbnailLoadTask = this; - break; - - case TASK_LOAD: - WWASSERT(Texture->TextureLoadTask == NULL); - Texture->TextureLoadTask = this; - break; - } -} - - -void CubeTextureLoadTaskClass::Deinit() -{ - // task should not be on any list when it is being detached from texture. - WWASSERT(Next == NULL); - WWASSERT(Prev == NULL); - - WWASSERT(D3DTexture == NULL); - - for (int f=0; f<6; f++) - { - for (int i = 0; i < MIP_LEVELS_MAX; ++i) - { - WWASSERT(LockedCubeSurfacePtr[f][i] == NULL); - } - } - - if (Texture) - { - switch (Type) - { - case TASK_THUMBNAIL: - WWASSERT(Texture->ThumbnailLoadTask == this); - Texture->ThumbnailLoadTask = NULL; - break; - - case TASK_LOAD: - WWASSERT(Texture->TextureLoadTask == this); - Texture->TextureLoadTask = NULL; - break; - } - - // NOTE: we must be in main thread to avoid corrupting Texture's refcount. - WWASSERT(TextureLoader::Is_DX8_Thread()); - REF_PTR_RELEASE(Texture); - } -} - -void CubeTextureLoadTaskClass::Lock_Surfaces(void) -{ - for (unsigned int f=0; f<6; f++) - { - for (unsigned int i=0; iLockRect - ( - (D3DCUBEMAP_FACES)f, - i, - &locked_rect, - NULL, - 0 - ) - ); - LockedCubeSurfacePtr[f][i] = (unsigned char *)locked_rect.pBits; - LockedCubeSurfacePitch[f][i]= locked_rect.Pitch; - } - } -} - -void CubeTextureLoadTaskClass::Unlock_Surfaces(void) -{ - for (unsigned int f=0; f<6; f++) - { - for (unsigned int i = 0; i < MipLevelCount; ++i) - { - if (LockedCubeSurfacePtr[f][i]) - { - WWASSERT(ThreadClass::_Get_Current_Thread_ID() == DX8Wrapper::_Get_Main_Thread_ID()); - DX8_ErrorCode - ( - Peek_D3D_Cube_Texture()->UnlockRect((D3DCUBEMAP_FACES)f,i) - ); - } - LockedCubeSurfacePtr[f][i] = NULL; - } - } - -#ifndef USE_MANAGED_TEXTURES - IDirect3DCubeTexture8* tex = DX8Wrapper::_Create_DX8_Cube_Texture - ( - Width, - Height, - Format, - Texture->MipLevelCount, - D3DPOOL_DEFAULT - ); - DX8CALL(UpdateTexture(Peek_D3D_Volume_Texture(),tex)); - Peek_D3D_Volume_Texture()->Release(); - D3DTexture=tex; - WWDEBUG_SAY(("Created non-managed texture (%s)",Texture->Get_Full_Path())); -#endif - -} - - - -bool CubeTextureLoadTaskClass::Begin_Compressed_Load() -{ - unsigned orig_w,orig_h,orig_d,orig_mip_count,reduction; - WW3DFormat orig_format; - if (!Get_Texture_Information - ( - Texture->Get_Full_Path(), - reduction, - orig_w, - orig_h, - orig_d, - orig_format, - orig_mip_count, - true - ) - ) - { - return false; - } - - // Destination size will be the next power of two square from the larger width and height... - unsigned int width = orig_w; - unsigned int height = orig_h; - TextureLoader::Validate_Texture_Size(width, height,orig_d); - - // If the size doesn't match, try and see if texture reduction would help... (mainly for - // cases where loaded texture is larger than hardware limit) - if (width != orig_w || height != orig_h) - { - for (unsigned int i = 1; i < orig_mip_count; ++i) - { - unsigned w=orig_w>>i; - if (w<4) w=4; - unsigned h=orig_h>>i; - if (h<4) h=4; - unsigned tmp_w=w; - unsigned tmp_h=h; - - TextureLoader::Validate_Texture_Size(w,h,orig_d); - - if (w == tmp_w && h == tmp_h) - { - Reduction += i; - width = w; - height = h; - break; - } - } - } - - Width = width; - Height = height; - Format = Get_Valid_Texture_Format(orig_format, Texture->Is_Compression_Allowed()); - - unsigned int mip_level_count = Get_Mip_Level_Count(); - - // If texture wants all mip levels, take as many as the file contains (not necessarily all) - // Otherwise take as many mip levels as the texture wants, not to exceed the count in file... - if (!mip_level_count) - { - mip_level_count = orig_mip_count;//dds_file.Get_Mip_Level_Count(); - } - else if (mip_level_count > orig_mip_count) - {//dds_file.Get_Mip_Level_Count()) { - mip_level_count = orig_mip_count;//dds_file.Get_Mip_Level_Count(); - } - - // Once more, verify that the mip level count is correct (in case it was changed here it might not - // match the size...well actually it doesn't have to match but it can't be bigger than the size) - unsigned int max_mip_level_count = 1; - unsigned int w = 4; - unsigned int h = 4; - - while (w < Width && h < Height) - { - w += w; - h += h; - max_mip_level_count++; - } - - if (mip_level_count > max_mip_level_count) - { - mip_level_count = max_mip_level_count; - } - - D3DTexture = DX8Wrapper::_Create_DX8_Cube_Texture - ( - Width, - Height, - Format, - (MipCountType)mip_level_count, -#ifdef USE_MANAGED_TEXTURES - D3DPOOL_MANAGED -#else - D3DPOOL_SYSTEMMEM -#endif - ); - - MipLevelCount = mip_level_count; - return true; -} - -bool CubeTextureLoadTaskClass::Begin_Uncompressed_Load(void) -{ - unsigned width,height,depth,orig_mip_count,reduction; - WW3DFormat orig_format; - if (!Get_Texture_Information - ( - Texture->Get_Full_Path(), - reduction, - width, - height, - depth, - orig_format, - orig_mip_count, - false - ) - ) - { - return false; - } - - WW3DFormat src_format=orig_format; - WW3DFormat dest_format=src_format; - dest_format=Get_Valid_Texture_Format(dest_format,false); // No compressed destination format if reading from targa... - - if ( src_format != WW3D_FORMAT_A8R8G8B8 - && src_format != WW3D_FORMAT_R8G8B8 - && src_format != WW3D_FORMAT_X8R8G8B8 ) - { - WWDEBUG_SAY(("Invalid TGA format used in %s - only 24 and 32 bit formats should be used!", Texture->Get_Full_Path().str())); - } - - // Destination size will be the next power of two square from the larger width and height... - unsigned ow = width; - unsigned oh = height; - TextureLoader::Validate_Texture_Size(width, height,depth); - if (width != ow || height != oh) - { - WWDEBUG_SAY(("Invalid texture size, scaling required. Texture: %s, size: %d x %d -> %d x %d", Texture->Get_Full_Path().str(), ow, oh, width, height)); - } - - Width = width; - Height = height; - - if (Format == WW3D_FORMAT_UNKNOWN) - { - Format=dest_format; - } - else - { - Format = Get_Valid_Texture_Format(Format, false); - } - - D3DTexture = DX8Wrapper::_Create_DX8_Cube_Texture - ( - Width, - Height, - Format, - Texture->MipLevelCount, -#ifdef USE_MANAGED_TEXTURES - D3DPOOL_MANAGED -#else - D3DPOOL_SYSTEMMEM -#endif - ); - - return true; -} - -bool CubeTextureLoadTaskClass::Load_Compressed_Mipmap(void) -{ - DDSFileClass dds_file(Texture->Get_Full_Path(), Get_Reduction()); - - // if we can't load from file, indicate rror. - if (!dds_file.Is_Available() || !dds_file.Load()) - { - return false; - } - - // load cube map faces - for (unsigned int face=0; face<6; face++) - { - unsigned int width = Get_Width(); - unsigned int height = Get_Height(); - - for (unsigned int level=0; level>=1; - height>>=1; - } - } - - return true; -} - -unsigned char* CubeTextureLoadTaskClass::Get_Locked_CubeMap_Surface_Pointer(unsigned int face, unsigned int level) -{ - WWASSERT(face<6 && levelGet_Full_Path().Is_Empty()); - - Type = type; - Priority = priority; - State = STATE_NONE; - - D3DTexture = 0; - - VolumeTextureClass* tex=Texture->As_VolumeTextureClass(); - - if (tex) - { - Format = tex->Get_Texture_Format(); // don't assume format yet KM - } - else - { - Format = WW3D_FORMAT_UNKNOWN; - } - - Width = 0; - Height = 0; - Depth = 0; - MipLevelCount = Texture->MipLevelCount; - Reduction = Texture->Get_Reduction(); - HSVShift = Texture->Get_HSV_Shift(); - - - for (int i = 0; i < MIP_LEVELS_MAX; ++i) - { - LockedSurfacePtr[i] = NULL; - LockedSurfacePitch[i] = 0; - LockedSurfaceSlicePitch[i] = 0; - } - - switch (Type) - { - case TASK_THUMBNAIL: - WWASSERT(Texture->ThumbnailLoadTask == NULL); - Texture->ThumbnailLoadTask = this; - break; - - case TASK_LOAD: - WWASSERT(Texture->TextureLoadTask == NULL); - Texture->TextureLoadTask = this; - break; - } -} - -void VolumeTextureLoadTaskClass::Lock_Surfaces() -{ - for (unsigned int i=0; iLockBox - ( - i, - &locked_box, - NULL, - 0 - ) - ); - LockedSurfacePtr[i] = (unsigned char *)locked_box.pBits; - LockedSurfacePitch[i] = locked_box.RowPitch; - LockedSurfaceSlicePitch[i] = locked_box.SlicePitch; - } -} - - -void VolumeTextureLoadTaskClass::Unlock_Surfaces() -{ - for (unsigned int i = 0; i < MipLevelCount; ++i) - { - if (LockedSurfacePtr[i]) - { - WWASSERT(ThreadClass::_Get_Current_Thread_ID() == DX8Wrapper::_Get_Main_Thread_ID()); - DX8_ErrorCode - ( - Peek_D3D_Volume_Texture()->UnlockBox(i) - ); - } - LockedSurfacePtr[i] = NULL; - } - -#ifndef USE_MANAGED_TEXTURES - IDirect3DTexture8* tex = DX8Wrapper::_Create_DX8_Volume_Texture(Width, Height, Depth, Format, Texture->MipLevelCount,D3DPOOL_DEFAULT); - DX8CALL(UpdateTexture(Peek_D3D_Volume_Texture(),tex)); - Peek_D3D_Volume_Texture()->Release(); - D3DTexture=tex; - WWDEBUG_SAY(("Created non-managed texture (%s)",Texture->Get_Full_Path())); -#endif - -} - - - -bool VolumeTextureLoadTaskClass::Begin_Compressed_Load() -{ - unsigned orig_w,orig_h,orig_d,orig_mip_count,reduction; - WW3DFormat orig_format; - if (!Get_Texture_Information - ( - Texture->Get_Full_Path(), - reduction, - orig_w, - orig_h, - orig_d, - orig_format, - orig_mip_count, - true - ) - ) - { - return false; - } - - // Destination size will be the next power of two square from the larger width and height... - unsigned int width = orig_w; - unsigned int height = orig_h; - unsigned int depth = orig_d; - TextureLoader::Validate_Texture_Size(width, height, depth); - - // If the size doesn't match, try and see if texture reduction would help... (mainly for - // cases where loaded texture is larger than hardware limit) - if (width != orig_w || height != orig_h || depth != orig_d) - { - for (unsigned int i = 1; i < orig_mip_count; ++i) - { - unsigned w=orig_w>>i; - if (w<4) w=4; - unsigned h=orig_h>>i; - if (h<4) h=4; - unsigned d=orig_d>>i; - if (d<1) d=1; - unsigned tmp_w=w; - unsigned tmp_h=h; - unsigned tmp_d=d; - - TextureLoader::Validate_Texture_Size(w,h,d); - - if (w == tmp_w && h == tmp_h && d== tmp_d) - { - Reduction += i; - width = w; - height = h; - depth = d; - break; - } - } - } - - Width = width; - Height = height; - Depth = depth; - Format = Get_Valid_Texture_Format(orig_format, Texture->Is_Compression_Allowed()); - - unsigned int mip_level_count = Get_Mip_Level_Count(); - - // If texture wants all mip levels, take as many as the file contains (not necessarily all) - // Otherwise take as many mip levels as the texture wants, not to exceed the count in file... - if (!mip_level_count) - { - mip_level_count = orig_mip_count;//dds_file.Get_Mip_Level_Count(); - } - else if (mip_level_count > orig_mip_count) - {//dds_file.Get_Mip_Level_Count()) { - mip_level_count = orig_mip_count;//dds_file.Get_Mip_Level_Count(); - } - - // Once more, verify that the mip level count is correct (in case it was changed here it might not - // match the size...well actually it doesn't have to match but it can't be bigger than the size) - unsigned int max_mip_level_count = 1; - unsigned int w = 4; - unsigned int h = 4; - - while (w < Width && h < Height) - { - w += w; - h += h; - max_mip_level_count++; - } - if (mip_level_count > max_mip_level_count) - { - mip_level_count = max_mip_level_count; - } - - D3DTexture = DX8Wrapper::_Create_DX8_Volume_Texture - ( - Width, - Height, - Depth, - Format, - (MipCountType)mip_level_count, -#ifdef USE_MANAGED_TEXTURES - D3DPOOL_MANAGED -#else - D3DPOOL_SYSTEMMEM -#endif - ); - - MipLevelCount = mip_level_count; - return true; -} - -bool VolumeTextureLoadTaskClass::Begin_Uncompressed_Load(void) -{ - unsigned width,height,depth,orig_mip_count,reduction; - WW3DFormat orig_format; - if (!Get_Texture_Information - ( - Texture->Get_Full_Path(), - reduction, - width, - height, - depth, - orig_format, - orig_mip_count, - false - ) - ) - { - return false; - } - - WW3DFormat src_format=orig_format; - WW3DFormat dest_format=src_format; - dest_format=Get_Valid_Texture_Format(dest_format,false); // No compressed destination format if reading from targa... - - if ( src_format != WW3D_FORMAT_A8R8G8B8 - && src_format != WW3D_FORMAT_R8G8B8 - && src_format != WW3D_FORMAT_X8R8G8B8 ) - { - WWDEBUG_SAY(("Invalid TGA format used in %s - only 24 and 32 bit formats should be used!", Texture->Get_Full_Path().str())); - } - - // Destination size will be the next power of two square from the larger width and height... - unsigned ow = width; - unsigned oh = height; - unsigned od = depth; - TextureLoader::Validate_Texture_Size(width, height, depth); - if (width != ow || height != oh || depth != od) - { - WWDEBUG_SAY(("Invalid texture size, scaling required. Texture: %s, size: %d x %d -> %d x %d", Texture->Get_Full_Path().str(), ow, oh, width, height)); - } - - Width = width; - Height = height; - Depth = depth; - - if (Format == WW3D_FORMAT_UNKNOWN) - { - Format=dest_format; - } - else - { - Format = Get_Valid_Texture_Format(Format, false); - } - - D3DTexture = DX8Wrapper::_Create_DX8_Volume_Texture - ( - Width, - Height, - Depth, - Format, - Texture->MipLevelCount, -#ifdef USE_MANAGED_TEXTURES - D3DPOOL_MANAGED -#else - D3DPOOL_SYSTEMMEM -#endif - ); - - return true; -} - -bool VolumeTextureLoadTaskClass::Load_Compressed_Mipmap(void) -{ - DDSFileClass dds_file(Texture->Get_Full_Path(), Get_Reduction()); - - // if we can't load from file, indicate rror. - if (!dds_file.Is_Available() || !dds_file.Load()) - { - return false; - } - - // load volume - unsigned int depth=dds_file.Get_Depth(0); - unsigned int width=Get_Width(); - unsigned int height=Get_Height(); - - WWASSERT(width && height && depth); - - for (unsigned int level=0; level>=1; - height>>=1; - depth>>=1; - } - - return true; -} - -unsigned char* VolumeTextureLoadTaskClass::Get_Locked_Volume_Pointer(unsigned int level) -{ - WWASSERT(level. -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : DX8 Texture Manager * - * * - * $Archive:: /Commando/Code/ww3d2/textureloader.h $* - * * - * Original Author:: vss_sync * - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 06/27/02 1:27p $* - * * - * $Revision:: 2 $* - * * - * 06/27/02 KM Texture class abstraction * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#pragma once - -#include "always.h" -#include "texture.h" - -class StringClass; -struct IDirect3DTexture8; -class TextureLoadTaskClass; - -class TextureLoader -{ -public: - static void Init(void); - static void Deinit(void); - - // Modify given texture size to nearest valid size on current hardware. - static void Validate_Texture_Size(unsigned& width, unsigned& height, unsigned& depth); - - static IDirect3DTexture8 * Load_Thumbnail( - const StringClass& filename,const Vector3& hsv_shift); -// WW3DFormat texture_format); // Pass WW3D_FORMAT_UNKNOWN if you don't care - - static IDirect3DSurface8 * Load_Surface_Immediate( - const StringClass& filename, - WW3DFormat surface_format, // Pass WW3D_FORMAT_UNKNOWN if you don't care - bool allow_compression); - - static void Request_Thumbnail(TextureBaseClass* tc); - - // Adds a loading task to the system. The task if processed in a separate - // thread as soon as possible. The task will appear in finished tasks list - // when it's been completed. The texture will be refreshed on the next - // update call after appearing to the finished tasks list. - static void Request_Background_Loading(TextureBaseClass* tc); - - // Textures can only be created and locked by the main thread so this function sends a request to the texture - // handling system to load the texture immediatelly next time it enters the main thread. If this function - // is called from the main thread the texture is loaded immediatelly. - static void Request_Foreground_Loading(TextureBaseClass* tc); - - static void Flush_Pending_Load_Tasks(void); - static void Update(void(*network_callback)(void) = NULL); - - // returns true if current thread of execution is allowed to make DX8 calls. - static bool Is_DX8_Thread(void); - - static void Suspend_Texture_Load(); - static void Continue_Texture_Load(); - - static void Set_Texture_Inactive_Override_Time(int time_ms) {TextureInactiveOverrideTime = time_ms;} - -private: - static void Process_Foreground_Load (TextureLoadTaskClass *task); - static void Process_Foreground_Thumbnail (TextureLoadTaskClass *task); - - static void Begin_Load_And_Queue (TextureLoadTaskClass *task); - static void Load_Thumbnail (TextureBaseClass *tc); - - static bool TextureLoadSuspended; - - // The time in ms before a texture is thrown out. - // The default is zero. The scripted movies set this to reduce texture stalls in movies. - static int TextureInactiveOverrideTime; -}; - -class TextureLoadTaskListNodeClass -{ - friend class TextureLoadTaskListClass; - - public: - TextureLoadTaskListNodeClass(void) : Next(0), Prev(0) { } - - TextureLoadTaskListClass *Get_List(void) { return List; } - - TextureLoadTaskListNodeClass *Next; - TextureLoadTaskListNodeClass *Prev; - TextureLoadTaskListClass * List; -}; - - -class TextureLoadTaskListClass -{ - // This class implements an unsynchronized, double-linked list of TextureLoadTaskClass - // objects, using an embedded list node. - - public: - TextureLoadTaskListClass(void); - - // Returns true if list is empty, false otherwise. - bool Is_Empty (void) const { return (Root.Next == &Root); } - - // Add a task to beginning of list - void Push_Front (TextureLoadTaskClass *task); - - // Add a task to end of list - void Push_Back (TextureLoadTaskClass *task); - - // Remove and return a task from beginning of list, or NULL if list is empty. - TextureLoadTaskClass * Pop_Front (void); - - // Remove and return a task from end of list, or NULL if list is empty - TextureLoadTaskClass * Pop_Back (void); - - // Remove specified task from list, if present - void Remove (TextureLoadTaskClass *task); - - private: - // This list is implemented using a sentinel node. - TextureLoadTaskListNodeClass Root; -}; - - -class SynchronizedTextureLoadTaskListClass : public TextureLoadTaskListClass -{ - // This class added thread-safety to the basic TextureLoadTaskListClass. - - public: - SynchronizedTextureLoadTaskListClass(void); - - // See comments above for description of member functions. - void Push_Front (TextureLoadTaskClass *task); - void Push_Back (TextureLoadTaskClass *task); - TextureLoadTaskClass * Pop_Front (void); - TextureLoadTaskClass * Pop_Back (void); - void Remove (TextureLoadTaskClass *task); - - private: - FastCriticalSectionClass CriticalSection; -}; - -/* -** (gth) The allocation system we're using for TextureLoadTaskClass has gotten a little -** complicated since Kenny added the new task types for Cube and Volume textures. The -** ::Destroy member is used to return a task to the pool now and must be over-ridden in -** each derived class to put the task back into the correct free list. -*/ - - -class TextureLoadTaskClass : public TextureLoadTaskListNodeClass -{ - public: - enum TaskType { - TASK_NONE, - TASK_THUMBNAIL, - TASK_LOAD, - }; - - enum PriorityType { - PRIORITY_LOW, - PRIORITY_HIGH, - }; - - enum StateType { - STATE_NONE, - - STATE_LOAD_BEGUN, - STATE_LOAD_MIPMAP, - STATE_LOAD_COMPLETE, - - STATE_COMPLETE, - }; - - - TextureLoadTaskClass(void); - ~TextureLoadTaskClass(void); - - static TextureLoadTaskClass * Create (TextureBaseClass *tc, TaskType type, PriorityType priority); - static void Delete_Free_Pool (void); - - virtual void Destroy (void); - virtual void Init (TextureBaseClass *tc, TaskType type, PriorityType priority); - virtual void Deinit (void); - - TaskType Get_Type (void) const { return Type; } - PriorityType Get_Priority (void) const { return Priority; } - StateType Get_State (void) const { return State; } - - WW3DFormat Get_Format (void) const { return Format; } - unsigned int Get_Width (void) const { return Width; } - unsigned int Get_Height (void) const { return Height; } - unsigned int Get_Mip_Level_Count (void) const { return MipLevelCount; } - unsigned int Get_Reduction (void) const { return Reduction; } - - unsigned char * Get_Locked_Surface_Ptr (unsigned int level); - unsigned int Get_Locked_Surface_Pitch(unsigned int level) const; - - TextureBaseClass * Peek_Texture (void) { return Texture; } - IDirect3DTexture8 * Peek_D3D_Texture (void) { return (IDirect3DTexture8*)D3DTexture; } - - void Set_Type (TaskType t) { Type = t; } - void Set_Priority (PriorityType p) { Priority = p; } - void Set_State (StateType s) { State = s; } - - bool Begin_Load (void); - bool Load (void); - void End_Load (void); - void Finish_Load (void); - void Apply_Missing_Texture (void); - - protected: - virtual bool Begin_Compressed_Load (void); - virtual bool Begin_Uncompressed_Load (void); - - virtual bool Load_Compressed_Mipmap (void); - virtual bool Load_Uncompressed_Mipmap(void); - - virtual void Lock_Surfaces (void); - virtual void Unlock_Surfaces (void); - - void Apply (bool initialize); - - TextureBaseClass* Texture; - IDirect3DBaseTexture8* D3DTexture; - WW3DFormat Format; - - unsigned int Width; - unsigned int Height; - unsigned int MipLevelCount; - unsigned int Reduction; - Vector3 HSVShift; - - unsigned char * LockedSurfacePtr[MIP_LEVELS_MAX]; - unsigned int LockedSurfacePitch[MIP_LEVELS_MAX]; - - TaskType Type; - PriorityType Priority; - StateType State; -}; - -class CubeTextureLoadTaskClass : public TextureLoadTaskClass -{ -public: - CubeTextureLoadTaskClass(); - - virtual void Destroy (void); - virtual void Init (TextureBaseClass *tc, TaskType type, PriorityType priority); - virtual void Deinit (void); - -protected: - virtual bool Begin_Compressed_Load (void); - virtual bool Begin_Uncompressed_Load (void); - - virtual bool Load_Compressed_Mipmap (void); -// virtual bool Load_Uncompressed_Mipmap(void); - - virtual void Lock_Surfaces (void); - virtual void Unlock_Surfaces (void); - -private: - unsigned char* Get_Locked_CubeMap_Surface_Pointer(unsigned int face, unsigned int level); - unsigned int Get_Locked_CubeMap_Surface_Pitch(unsigned int face, unsigned int level) const; - - IDirect3DCubeTexture8* Peek_D3D_Cube_Texture(void) { return (IDirect3DCubeTexture8*)D3DTexture; } - - unsigned char* LockedCubeSurfacePtr[6][MIP_LEVELS_MAX]; - unsigned int LockedCubeSurfacePitch[6][MIP_LEVELS_MAX]; -}; - -class VolumeTextureLoadTaskClass : public TextureLoadTaskClass -{ -public: - VolumeTextureLoadTaskClass(); - - virtual void Destroy (void); - virtual void Init (TextureBaseClass *tc, TaskType type, PriorityType priority); - -protected: - virtual bool Begin_Compressed_Load (void); - virtual bool Begin_Uncompressed_Load (void); - - virtual bool Load_Compressed_Mipmap (void); -// virtual bool Load_Uncompressed_Mipmap(void); - - virtual void Lock_Surfaces (void); - virtual void Unlock_Surfaces (void); - -private: - unsigned char* Get_Locked_Volume_Pointer(unsigned int level); - unsigned int Get_Locked_Volume_Row_Pitch(unsigned int level); - unsigned int Get_Locked_Volume_Slice_Pitch(unsigned int level); - - IDirect3DVolumeTexture8* Peek_D3D_Volume_Texture(void) { return (IDirect3DVolumeTexture8*)D3DTexture; } - - unsigned int LockedSurfaceSlicePitch[MIP_LEVELS_MAX]; - - unsigned int Depth; -}; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp deleted file mode 100644 index 24d385fbf2..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp +++ /dev/null @@ -1,410 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General 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 "texturethumbnail.h" -#include "hashtemplate.h" -#include "missingtexture.h" -#include "TARGA.h" -#include "ww3dformat.h" -#include "ddsfile.h" -#include "textureloader.h" -#include "bitmaphandler.h" -#include "ffactory.h" -#include "RAWFILE.h" -#include "wwprofile.h" -#include - -static DLListClass ThumbnailManagerList; -static ThumbnailManagerClass* GlobalThumbnailManager; -bool ThumbnailManagerClass::CreateThumbnailIfNotFound=false; - -static void Create_Hash_Name(StringClass& name, const StringClass& thumb_name) -{ - name=thumb_name; - int len=name.Get_Length(); - WWASSERT(!stricmp(&name[len-4],".tga") || !stricmp(&name[len-4],".dds")); - name[len-4]='\0'; - _strlwr(name.Peek_Buffer()); -} - - /* file_auto_ptr my_tga_file(_TheFileFactory,filename); - if (my_tga_file->Is_Available()) { - my_tga_file->Open(); - unsigned size=my_tga_file->Size(); - char* tga_memory=new char[size]; - my_tga_file->Read(tga_memory,size); - my_tga_file->Close(); - - StringClass pth("data\\"); - pth+=filename; - RawFileClass tmp_tga_file(pth); - tmp_tga_file.Create(); - tmp_tga_file.Write(tga_memory,size); - tmp_tga_file.Close(); - delete[] tga_memory; - - } -*/ - - -ThumbnailClass::ThumbnailClass( - ThumbnailManagerClass* manager, - const char* name, - unsigned char* bitmap, - unsigned w, - unsigned h, - unsigned original_w, - unsigned original_h, - unsigned original_mip_level_count, - WW3DFormat original_format, - bool allocated, - unsigned long date_time) - : - Manager(manager), - Name(name), - Bitmap(bitmap), - Allocated(allocated), - Width(w), - Height(h), - OriginalTextureWidth(original_w), - OriginalTextureHeight(original_h), - OriginalTextureMipLevelCount(original_mip_level_count), - OriginalTextureFormat(original_format), - DateTime(date_time) -{ - Manager->Insert_To_Hash(this); -} - -// ---------------------------------------------------------------------------- -// -// Load texture and generate mipmap levels if requested. The function tries -// to create texture that matches targa format. If suitable format is not -// available, it selects closest matching format and performs color space -// conversion. -// -// ---------------------------------------------------------------------------- - -ThumbnailClass::ThumbnailClass(ThumbnailManagerClass* manager, const StringClass& filename) - : - Manager(manager), - Bitmap(0), - Name(filename), - Allocated(false), - Width(0), - Height(0), - OriginalTextureWidth(0), - OriginalTextureHeight(0), - OriginalTextureMipLevelCount(0), - OriginalTextureFormat(WW3D_FORMAT_UNKNOWN), - DateTime(0) -{ - WWPROFILE(("ThumbnailClass::ThumbnailClass")); - unsigned reduction_factor=3; - - // First, try loading image from a DDS file - DDSFileClass dds_file(filename,reduction_factor); - if (dds_file.Is_Available() && dds_file.Load()) { - DateTime=dds_file.Get_Date_Time(); - - int len=Name.Get_Length(); - WWASSERT(len>4); - Name[len-3]='d'; - Name[len-2]='d'; - Name[len-1]='s'; - - unsigned level=0; - while (dds_file.Get_Width(level)>32 || dds_file.Get_Height(level)>32) { - if (level>=dds_file.Get_Mip_Level_Count()) break; - level++; - } - - OriginalTextureWidth=dds_file.Get_Full_Width(); - OriginalTextureHeight=dds_file.Get_Full_Height(); - OriginalTextureFormat=dds_file.Get_Format(); - OriginalTextureMipLevelCount=dds_file.Get_Mip_Level_Count(); - Width=dds_file.Get_Width(0); - Height=dds_file.Get_Height(0); - Bitmap=W3DNEWARRAY unsigned char[Width*Height*2]; - Allocated=true; - dds_file.Copy_Level_To_Surface( - 0, // Level - WW3D_FORMAT_A4R4G4B4, - Width, - Height, - Bitmap, - Width*2, - Vector3(0.0f,0.0f,0.0f));// We don't want to HSV-shift here - } - // If DDS file can't be used try loading from TGA - else { - // Make sure the file can be opened. If not, return missing texture. - Targa targa; - if (TARGA_ERROR_HANDLER(targa.Open(filename,TGA_READMODE),filename)) return; - - // DX8 uses image upside down compared to TGA - targa.Header.ImageDescriptor ^= TGAIDF_YORIGIN; - - WW3DFormat src_format,dest_format; - unsigned src_bpp=0; - Get_WW3D_Format(src_format,src_bpp,targa); - if (src_format==WW3D_FORMAT_UNKNOWN) { - WWDEBUG_SAY(("Unknown texture format for %s",filename.str())); - return; - } - - // Destination size will be the next power of two square from the larger width and height... - OriginalTextureWidth=targa.Header.Width; - OriginalTextureHeight=targa.Header.Height; - OriginalTextureFormat=src_format; - Width=targa.Header.Width>>reduction_factor; - Height=targa.Header.Height>>reduction_factor; - OriginalTextureMipLevelCount=1; - unsigned iw=1; - unsigned ih=1; - while (iw32 || Height>32) { - reduction_factor++; - Width>>=2; - Height>>=2; - } - - unsigned poweroftwowidth = 1; - while (poweroftwowidth < Width) { - poweroftwowidth <<= 1; - } - - unsigned poweroftwoheight = 1; - while (poweroftwoheight < Height) { - poweroftwoheight <<= 1; - } - - Width=poweroftwowidth; - Height=poweroftwoheight; - - unsigned src_width=targa.Header.Width; - unsigned src_height=targa.Header.Height; - - // NOTE: We load the palette but we do not yet support paletted textures! - char palette[256*4]; - targa.SetPalette(palette); - if (TARGA_ERROR_HANDLER(targa.Load(filename, TGAF_IMAGE, false),filename)) return; - - // Get time stamp from the tga file - { - file_auto_ptr my_tga_file(_TheFileFactory,filename); - WWASSERT(my_tga_file->Is_Available()); - my_tga_file->Open(); - DateTime=my_tga_file->Get_Date_Time(); - my_tga_file->Close(); - } - - unsigned char* src_surface=(unsigned char*)targa.GetImage(); - - int len=Name.Get_Length(); - WWASSERT(len>4); - Name[len-3]='t'; - Name[len-2]='g'; - Name[len-1]='a'; - - Bitmap=W3DNEWARRAY unsigned char[Width*Height*2]; - Allocated=true; - - dest_format=WW3D_FORMAT_A8R8G8B8; - BitmapHandlerClass::Copy_Image( - Bitmap, - Width, - Height, - Width*2, - WW3D_FORMAT_A4R4G4B4, - src_surface, - src_width, - src_height, - src_width*src_bpp, - src_format, - (unsigned char*)targa.GetPalette(), - targa.Header.CMapDepth>>3, - false); - } - - Manager->Insert_To_Hash(this); -} - -ThumbnailClass::~ThumbnailClass() -{ - if (Allocated) delete[] Bitmap; - Manager->Remove_From_Hash(this); -} - - -// ---------------------------------------------------------------------------- -ThumbnailManagerClass::ThumbnailManagerClass(const char* thumbnail_filename) - : - ThumbnailMemory(NULL), - ThumbnailFileName(thumbnail_filename), - PerTextureTimeStampUsed(false), - Changed(false), - DateTime(0) -{ -} - -// ---------------------------------------------------------------------------- -ThumbnailManagerClass::~ThumbnailManagerClass() -{ - HashTemplateIterator ite(ThumbnailHash); - ite.First(); - while (!ite.Is_Done()) { - ThumbnailClass* thumb=ite.Peek_Value(); - delete thumb; - ite.First(); - } - - delete[] ThumbnailMemory; - ThumbnailMemory=NULL; -} - -// ---------------------------------------------------------------------------- -ThumbnailManagerClass* ThumbnailManagerClass::Peek_Thumbnail_Manager(const char* thumbnail_filename) -{ - ThumbnailManagerClass* man=ThumbnailManagerList.Head(); - while (man) { - if (man->ThumbnailFileName==thumbnail_filename) return man; - man=man->Succ(); - } - if (GlobalThumbnailManager && - GlobalThumbnailManager->ThumbnailFileName==thumbnail_filename) return GlobalThumbnailManager; - return NULL; -} - -// ---------------------------------------------------------------------------- -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, - // so we'll do pure string compares here... - - // Must NOT add global manager with this function - WWASSERT(stricmp(thumbnail_filename,GLOBAL_THUMBNAIL_MANAGER_FILENAME)); - - ThumbnailManagerClass* man=Peek_Thumbnail_Manager(thumbnail_filename); - if (man) return; - - // Not found, create and add to the list. - man=new ThumbnailManagerClass(thumbnail_filename); - ThumbnailManagerList.Add_Tail(man); -} -// ---------------------------------------------------------------------------- -void ThumbnailManagerClass::Remove_Thumbnail_Manager(const char* thumbnail_filename) -{ - ThumbnailManagerClass* man=ThumbnailManagerList.Head(); - while (man) { - if (man->ThumbnailFileName==thumbnail_filename) { - delete man; - return; - } - man=man->Succ(); - } - if (GlobalThumbnailManager && - GlobalThumbnailManager->ThumbnailFileName==thumbnail_filename) { - delete GlobalThumbnailManager; - GlobalThumbnailManager=NULL; - } -} -// ---------------------------------------------------------------------------- -ThumbnailClass* ThumbnailManagerClass::Peek_Thumbnail_Instance(const StringClass& name) -{ - - return Get_From_Hash(name); -} - -ThumbnailClass* ThumbnailManagerClass::Peek_Thumbnail_Instance_From_Any_Manager(const StringClass& filename) -{ - WWPROFILE(("Peek_Thumbnail_Instance_From_Any_Manager")); - ThumbnailManagerClass* thumb_man=ThumbnailManagerList.Head(); - while (thumb_man) { - ThumbnailClass* thumb=thumb_man->Peek_Thumbnail_Instance(filename); - if (thumb) return thumb; - thumb_man=thumb_man->Succ(); - } - - if (GlobalThumbnailManager) { - ThumbnailClass* thumb=GlobalThumbnailManager->Peek_Thumbnail_Instance(filename); - if (thumb) return thumb; - } - -// If thumbnail is not found, see if we can find a texture. It is possible that the texture is outside of -// a mix file and didn't get included in any thumbnail database based on a mixfile. If so, we'll add it to -// our global thumbnail database. - if (Is_Thumbnail_Created_If_Not_Found()) { - if (GlobalThumbnailManager) { - ThumbnailClass* thumb=new ThumbnailClass(GlobalThumbnailManager,filename); - if (!thumb->Peek_Bitmap()) { - delete thumb; - thumb=NULL; - } - return thumb; - } - } - - return NULL; -} - - -void ThumbnailManagerClass::Insert_To_Hash(ThumbnailClass* thumb) -{ - Changed=true; - StringClass hash_name(0,true); - Create_Hash_Name(hash_name,thumb->Get_Name()); - ThumbnailHash.Insert(hash_name,thumb); -} - -ThumbnailClass* ThumbnailManagerClass::Get_From_Hash(const StringClass& name) -{ - StringClass hash_name(0,true); - Create_Hash_Name(hash_name,name); - return ThumbnailHash.Get(hash_name); -} - -void ThumbnailManagerClass::Remove_From_Hash(ThumbnailClass* thumb) -{ - Changed=true; - StringClass hash_name(0,true); - Create_Hash_Name(hash_name,thumb->Get_Name()); - ThumbnailHash.Remove(hash_name); -} - -void ThumbnailManagerClass::Init() -{ - WWASSERT(GlobalThumbnailManager == NULL); - GlobalThumbnailManager=new ThumbnailManagerClass(GLOBAL_THUMBNAIL_MANAGER_FILENAME); - GlobalThumbnailManager->Enable_Per_Texture_Time_Stamp(true); -} - -void ThumbnailManagerClass::Deinit() -{ - while (ThumbnailManagerClass* man=ThumbnailManagerList.Head()) { - delete man; - } - - delete GlobalThumbnailManager; - GlobalThumbnailManager=NULL; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.h deleted file mode 100644 index 4d740af636..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.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 . -*/ - -// 08/07/02 KM Texture class redesign (revisited) - -#pragma once - -#include "always.h" -#include "wwstring.h" -#include "hashtemplate.h" -#include "dllist.h" -#include "ww3dformat.h" - -#define GLOBAL_THUMBNAIL_MANAGER_FILENAME "global.th6" - -class ThumbnailManagerClass; - -// ---------------------------------------------------------------------------- - -class ThumbnailClass -{ - friend ThumbnailManagerClass; - - StringClass Name; - unsigned char* Bitmap; - unsigned Width; - unsigned Height; - unsigned OriginalTextureWidth; - unsigned OriginalTextureHeight; - unsigned OriginalTextureMipLevelCount; - WW3DFormat OriginalTextureFormat; - unsigned long DateTime; - bool Allocated; // if true, destructor will free the memory - ThumbnailManagerClass* Manager; - - ThumbnailClass( - ThumbnailManagerClass* manager, - const char* name, - unsigned char* bitmap, - unsigned w, - unsigned h, - unsigned original_w, - unsigned original_h, - unsigned original_mip_level_count, - WW3DFormat original_format, - bool allocated, - unsigned long date_time); - ThumbnailClass( - ThumbnailManagerClass* manager, - const StringClass& filename); - ~ThumbnailClass(); -public: - - unsigned char* Peek_Bitmap() { return Bitmap; } - WW3DFormat Get_Format() { return WW3D_FORMAT_A4R4G4B4; } - unsigned Get_Width() const { return Width; } - unsigned Get_Height() const { return Height; } - unsigned Get_Original_Texture_Width() const { return OriginalTextureWidth; } - unsigned Get_Original_Texture_Height() const { return OriginalTextureHeight; } - unsigned Get_Original_Texture_Mip_Level_Count() const { return OriginalTextureMipLevelCount; } - WW3DFormat Get_Original_Texture_Format() const { return OriginalTextureFormat; } - unsigned long Get_Date_Time() const { return DateTime; } - const StringClass& Get_Name() const { return Name; } - -}; - -// ---------------------------------------------------------------------------- - -class ThumbnailManagerClass : public DLNodeClass -{ - W3DMPO_GLUE(ThumbnailManagerClass); - - friend ThumbnailClass; - - static bool CreateThumbnailIfNotFound; - bool PerTextureTimeStampUsed; - StringClass ThumbnailFileName; - HashTemplateClass ThumbnailHash; - unsigned char* ThumbnailMemory; - bool Changed; - unsigned long DateTime; - - 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); - -public: - ThumbnailClass* Peek_Thumbnail_Instance(const StringClass& 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); - - static ThumbnailClass* Peek_Thumbnail_Instance_From_Any_Manager(const StringClass& name); - - static bool Is_Thumbnail_Created_If_Not_Found() { return CreateThumbnailIfNotFound; } - static void Create_Thumbnail_If_Not_Found(bool create) { CreateThumbnailIfNotFound=create; } - - bool Is_Per_Texture_Time_Stamp_Used() const { return PerTextureTimeStampUsed; } - void Enable_Per_Texture_Time_Stamp(bool enable) { PerTextureTimeStampUsed=enable; } - - static void Init(); - static void Deinit(); -}; - -// ---------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/CMakeLists.txt b/GeneralsMD/Code/GameEngine/CMakeLists.txt index b77b4292e5..065d37a8fb 100644 --- a/GeneralsMD/Code/GameEngine/CMakeLists.txt +++ b/GeneralsMD/Code/GameEngine/CMakeLists.txt @@ -225,7 +225,7 @@ set(GAMEENGINE_SRC Include/GameClient/TerrainVisual.h # Include/GameClient/VideoPlayer.h # Include/GameClient/View.h - Include/GameClient/Water.h +# Include/GameClient/Water.h Include/GameClient/WindowLayout.h # Include/GameClient/WindowVideoManager.h Include/GameClient/WindowXlat.h @@ -825,7 +825,7 @@ set(GAMEENGINE_SRC # Source/GameClient/VideoPlayer.cpp # Source/GameClient/VideoStream.cpp # Source/GameClient/View.cpp - Source/GameClient/Water.cpp +# Source/GameClient/Water.cpp Source/GameLogic/AI/AI.cpp Source/GameLogic/AI/AIDock.cpp Source/GameLogic/AI/AIGroup.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/CMakeLists.txt b/GeneralsMD/Code/GameEngineDevice/CMakeLists.txt index e1bb05cdb1..c96e1f0b27 100644 --- a/GeneralsMD/Code/GameEngineDevice/CMakeLists.txt +++ b/GeneralsMD/Code/GameEngineDevice/CMakeLists.txt @@ -13,7 +13,7 @@ set(GAMEENGINEDEVICE_SRC Include/W3DDevice/GameClient/Module/W3DDebrisDraw.h Include/W3DDevice/GameClient/Module/W3DDefaultDraw.h Include/W3DDevice/GameClient/Module/W3DDependencyModelDraw.h - Include/W3DDevice/GameClient/Module/W3DLaserDraw.h +# Include/W3DDevice/GameClient/Module/W3DLaserDraw.h Include/W3DDevice/GameClient/Module/W3DModelDraw.h Include/W3DDevice/GameClient/Module/W3DOverlordAircraftDraw.h Include/W3DDevice/GameClient/Module/W3DOverlordTankDraw.h @@ -73,8 +73,8 @@ set(GAMEENGINEDEVICE_SRC # Include/W3DDevice/GameClient/W3DVideoBuffer.h # Include/W3DDevice/GameClient/W3DView.h Include/W3DDevice/GameClient/W3DVolumetricShadow.h - Include/W3DDevice/GameClient/W3DWater.h - Include/W3DDevice/GameClient/W3DWaterTracks.h +# Include/W3DDevice/GameClient/W3DWater.h +# Include/W3DDevice/GameClient/W3DWaterTracks.h Include/W3DDevice/GameClient/W3DWaypointBuffer.h Include/W3DDevice/GameClient/W3DWebBrowser.h Include/W3DDevice/GameClient/WorldHeightMap.h @@ -102,7 +102,7 @@ set(GAMEENGINEDEVICE_SRC Source/W3DDevice/GameClient/Drawable/Draw/W3DDebrisDraw.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DDefaultDraw.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DDependencyModelDraw.cpp - Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp +# Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DOverlordAircraftDraw.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DOverlordTankDraw.cpp @@ -176,8 +176,8 @@ set(GAMEENGINEDEVICE_SRC # Source/W3DDevice/GameClient/W3DView.cpp Source/W3DDevice/GameClient/W3dWaypointBuffer.cpp Source/W3DDevice/GameClient/W3DWebBrowser.cpp - Source/W3DDevice/GameClient/Water/W3DWater.cpp - Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp +# Source/W3DDevice/GameClient/Water/W3DWater.cpp +# Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp Source/W3DDevice/GameClient/WorldHeightMap.cpp Source/W3DDevice/GameLogic/W3DGameLogic.cpp Source/W3DDevice/GameLogic/W3DGhostObject.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt index eb4e80cee0..13f5bc1ef6 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt +++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt @@ -15,8 +15,8 @@ set(WW3D2_SRC #assetstatus.h #bitmaphandler.cpp #bitmaphandler.h - bmp2d.cpp - bmp2d.h + #bmp2d.cpp + #bmp2d.h boxrobj.cpp boxrobj.h #bwrender.cpp @@ -56,8 +56,8 @@ set(WW3D2_SRC dx8renderer.h dx8rendererdebugger.cpp dx8rendererdebugger.h - dx8texman.cpp - dx8texman.h + #dx8texman.cpp + #dx8texman.h dx8vertexbuffer.cpp dx8vertexbuffer.h #dx8webbrowser.cpp @@ -108,8 +108,8 @@ set(WW3D2_SRC mapper.h #matinfo.cpp #matinfo.h - matpass.cpp - matpass.h + #matpass.cpp + #matpass.h matrixmapper.cpp matrixmapper.h mesh.cpp @@ -200,18 +200,18 @@ set(WW3D2_SRC #stripoptimizer.h #surfaceclass.cpp #surfaceclass.h - texproject.cpp - texproject.h + #texproject.cpp + #texproject.h #textdraw.cpp #textdraw.h - texture.cpp - texture.h - texturefilter.cpp - texturefilter.h - textureloader.cpp - textureloader.h - texturethumbnail.cpp - texturethumbnail.h + #texture.cpp + #texture.h + #texturefilter.cpp + #texturefilter.h + #textureloader.cpp + #textureloader.h + #texturethumbnail.cpp + #texturethumbnail.h vertmaterial.cpp vertmaterial.h #visrasterizer.cpp diff --git a/scripts/cpp/unify_move_files.py b/scripts/cpp/unify_move_files.py index 6d401ef28f..42ec8582a2 100644 --- a/scripts/cpp/unify_move_files.py +++ b/scripts/cpp/unify_move_files.py @@ -190,6 +190,34 @@ def main(): #unify_file(Game.ZEROHOUR, "GameEngineDevice/Include/W3DDevice/GameClient/W3DView.h", Game.CORE, "GameEngineDevice/Include/W3DDevice/GameClient/W3DView.h") #unify_file(Game.ZEROHOUR, "GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp", Game.CORE, "GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp") + #unify_file(Game.ZEROHOUR, "Libraries/Source/WWVegas/WW3D2/bmp2d.cpp", Game.CORE, "Libraries/Source/WWVegas/WW3D2/bmp2d.cpp") + #unify_file(Game.ZEROHOUR, "Libraries/Source/WWVegas/WW3D2/bmp2d.h", Game.CORE, "Libraries/Source/WWVegas/WW3D2/bmp2d.h") + #unify_file(Game.ZEROHOUR, "Libraries/Source/WWVegas/WW3D2/dx8texman.cpp", Game.CORE, "Libraries/Source/WWVegas/WW3D2/dx8texman.cpp") + #unify_file(Game.ZEROHOUR, "Libraries/Source/WWVegas/WW3D2/dx8texman.h", Game.CORE, "Libraries/Source/WWVegas/WW3D2/dx8texman.h") + #unify_file(Game.ZEROHOUR, "Libraries/Source/WWVegas/WW3D2/matpass.cpp", Game.CORE, "Libraries/Source/WWVegas/WW3D2/matpass.cpp") + #unify_file(Game.ZEROHOUR, "Libraries/Source/WWVegas/WW3D2/matpass.h", Game.CORE, "Libraries/Source/WWVegas/WW3D2/matpass.h") + #unify_file(Game.ZEROHOUR, "Libraries/Source/WWVegas/WW3D2/texproject.cpp", Game.CORE, "Libraries/Source/WWVegas/WW3D2/texproject.cpp") + #unify_file(Game.ZEROHOUR, "Libraries/Source/WWVegas/WW3D2/texproject.h", Game.CORE, "Libraries/Source/WWVegas/WW3D2/texproject.h") + #unify_file(Game.ZEROHOUR, "Libraries/Source/WWVegas/WW3D2/texture.cpp", Game.CORE, "Libraries/Source/WWVegas/WW3D2/texture.cpp") + #unify_file(Game.ZEROHOUR, "Libraries/Source/WWVegas/WW3D2/texture.h", Game.CORE, "Libraries/Source/WWVegas/WW3D2/texture.h") + #unify_file(Game.ZEROHOUR, "Libraries/Source/WWVegas/WW3D2/texturefilter.cpp", Game.CORE, "Libraries/Source/WWVegas/WW3D2/texturefilter.cpp") + #unify_file(Game.ZEROHOUR, "Libraries/Source/WWVegas/WW3D2/texturefilter.h", Game.CORE, "Libraries/Source/WWVegas/WW3D2/texturefilter.h") + #unify_file(Game.ZEROHOUR, "Libraries/Source/WWVegas/WW3D2/textureloader.cpp", Game.CORE, "Libraries/Source/WWVegas/WW3D2/textureloader.cpp") + #unify_file(Game.ZEROHOUR, "Libraries/Source/WWVegas/WW3D2/textureloader.h", Game.CORE, "Libraries/Source/WWVegas/WW3D2/textureloader.h") + #unify_file(Game.ZEROHOUR, "Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp", Game.CORE, "Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp") + #unify_file(Game.ZEROHOUR, "Libraries/Source/WWVegas/WW3D2/texturethumbnail.h", Game.CORE, "Libraries/Source/WWVegas/WW3D2/texturethumbnail.h") + + #unify_file(Game.ZEROHOUR, "GameEngine/Include/GameClient/Water.h", Game.CORE, "GameEngine/Include/GameClient/Water.h") + #unify_file(Game.ZEROHOUR, "GameEngine/Source/GameClient/Water.cpp", Game.CORE, "GameEngine/Source/GameClient/Water.cpp") + #unify_file(Game.ZEROHOUR, "GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DLaserDraw.h", Game.CORE, "GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DLaserDraw.h") + #unify_file(Game.ZEROHOUR, "GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h", Game.CORE, "GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h") + #unify_file(Game.ZEROHOUR, "GameEngineDevice/Include/W3DDevice/GameClient/W3DWaterTracks.h", Game.CORE, "GameEngineDevice/Include/W3DDevice/GameClient/W3DWaterTracks.h") + #unify_file(Game.ZEROHOUR, "GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp", Game.CORE, "GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp") + #unify_file(Game.ZEROHOUR, "GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp", Game.CORE, "GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp") + #unify_file(Game.ZEROHOUR, "GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp", Game.CORE, "GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp") + #unify_file(Game.ZEROHOUR, "GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvp", Game.CORE, "GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvp") + #unify_file(Game.ZEROHOUR, "GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvv", Game.CORE, "GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvv") + return From 334f56ac4b82f37849841ba57f0953e0746ddcc6 Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Sat, 13 Dec 2025 13:39:15 +0100 Subject: [PATCH 34/70] build(heightmap): Fix include paths in Zero Hour Height Map files (#1991) --- .../Include/W3DDevice/GameClient/BaseHeightMap.h | 2 +- .../Include/W3DDevice/GameClient/FlatHeightMap.h | 4 ++-- .../GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h | 4 ++-- .../Include/W3DDevice/GameClient/WorldHeightMap.h | 2 +- .../Source/W3DDevice/GameClient/BaseHeightMap.cpp | 1 + 5 files changed, 7 insertions(+), 6 deletions(-) diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h index 591fb04b03..9d3469a36b 100644 --- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h +++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h @@ -34,7 +34,7 @@ #include "vertmaterial.h" #include "Lib/BaseType.h" #include "Common/GameType.h" -#include "WorldHeightMap.h" +#include "W3DDevice/GameClient/WorldHeightMap.h" #define MAX_ENABLED_DYNAMIC_LIGHTS 20 typedef UnsignedByte HeightSampleType; //type of data to store in heightmap diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/FlatHeightMap.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/FlatHeightMap.h index cebe16170a..7cbea55a47 100644 --- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/FlatHeightMap.h +++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/FlatHeightMap.h @@ -34,8 +34,8 @@ #include "vertmaterial.h" #include "Lib/BaseType.h" #include "Common/GameType.h" -#include "WorldHeightMap.h" -#include "BaseHeightMap.h" +#include "W3DDevice/GameClient/WorldHeightMap.h" +#include "W3DDevice/GameClient/BaseHeightMap.h" class W3DTerrainBackground; /// Custom render object that draws the heightmap and handles intersection tests. diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h index 7491d7333b..4e35b06729 100644 --- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h +++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h @@ -34,8 +34,8 @@ #include "vertmaterial.h" #include "Lib/BaseType.h" #include "Common/GameType.h" -#include "WorldHeightMap.h" -#include "BaseHeightMap.h" +#include "W3DDevice/GameClient/WorldHeightMap.h" +#include "W3DDevice/GameClient/BaseHeightMap.h" #define VERTEX_BUFFER_TILE_LENGTH 32 //tiles of side length 32 (grid of 33x33 vertices). diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/WorldHeightMap.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/WorldHeightMap.h index 0b524afbc0..932edf2a7a 100644 --- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/WorldHeightMap.h +++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/WorldHeightMap.h @@ -33,7 +33,7 @@ #include "WWLib/refcount.h" #include "WWMath/vector3.h" #include "W3DDevice/GameClient/TileData.h" -#include "../../GameEngine/Include/Common/MapObject.h" +#include "Common/MapObject.h" #include "Common/STLTypedefs.h" typedef std::vector VecICoord2D; diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp index 7400b5673c..afb6045e68 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp @@ -57,6 +57,7 @@ #include #include "Common/GlobalData.h" #include "Common/PerfTimer.h" +#include "Common/Xfer.h" #include "GameClient/TerrainVisual.h" #include "GameClient/View.h" From 330ad2252ec6ee8f159e57f9b2c8c48932e679bf Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Sun, 14 Dec 2025 12:26:40 +0100 Subject: [PATCH 35/70] unify(heightmap): Merge Height Map related code and move Zero Hour's BaseHeightMap, FlatHeightMap, W3DPropDraw, W3DTreeDraw, W3DPropBuffer, W3DSnow, W3DTerrainBackground files to Core (#1991) --- Core/GameEngine/CMakeLists.txt | 4 +- .../GameEngine/Include/GameClient/Snow.h | 0 .../GameEngine/Source/GameClient/Snow.cpp | 0 Core/GameEngineDevice/CMakeLists.txt | 28 +- .../W3DDevice/GameClient/BaseHeightMap.h | 0 .../W3DDevice/GameClient/FlatHeightMap.h | 0 .../W3DDevice/GameClient/Module/W3DPropDraw.h | 0 .../W3DDevice/GameClient/Module/W3DTreeDraw.h | 0 .../W3DDevice/GameClient/W3DPropBuffer.h | 0 .../Include/W3DDevice/GameClient/W3DSnow.h | 0 .../GameClient/W3DTerrainBackground.h | 0 .../W3DDevice/GameClient/BaseHeightMap.cpp | 0 .../GameClient/Drawable/Draw/W3DPropDraw.cpp | 0 .../GameClient/Drawable/Draw/W3DTreeDraw.cpp | 0 .../W3DDevice/GameClient/FlatHeightMap.cpp | 0 .../W3DDevice/GameClient/W3DPropBuffer.cpp | 0 .../Source/W3DDevice/GameClient/W3DSnow.cpp | 0 .../GameClient/W3DTerrainBackground.cpp | 0 .../GameEngine/Include/Common/GlobalData.h | 1 + Generals/Code/GameEngine/Include/Common/INI.h | 1 + .../GameEngine/Include/Common/MapObject.h | 13 + .../GameEngine/Include/Common/ThingFactory.h | 4 +- .../Include/GameClient/TerrainVisual.h | 137 + .../Include/GameLogic/PartitionManager.h | 2 + .../GameEngine/Source/Common/GlobalData.cpp | 1 + .../Code/GameEngine/Source/Common/INI/INI.cpp | 1 + .../Source/Common/Thing/ThingFactory.cpp | 11 +- .../GameEngine/Source/GameClient/MapUtil.cpp | 2 +- .../GameClient/Terrain/TerrainVisual.cpp | 78 + .../GameLogic/Object/PartitionManager.cpp | 26 + .../GameLogic/ScriptEngine/ScriptActions.cpp | 6 +- .../Include/W3DDevice/GameClient/HeightMap.h | 256 +- .../Include/W3DDevice/GameClient/TerrainTex.h | 9 +- .../W3DDevice/GameClient/W3DBibBuffer.h | 2 +- .../W3DDevice/GameClient/W3DBridgeBuffer.h | 2 +- .../W3DDevice/GameClient/W3DRoadBuffer.h | 6 +- .../W3DDevice/GameClient/W3DTerrainVisual.h | 56 +- .../W3DDevice/GameClient/W3DTreeBuffer.h | 203 +- .../W3DDevice/GameClient/WorldHeightMap.h | 55 +- .../Source/W3DDevice/GameClient/HeightMap.cpp | 2584 ++--------------- .../W3DDevice/GameClient/TerrainTex.cpp | 206 +- .../W3DDevice/GameClient/W3DDisplay.cpp | 6 +- .../W3DDevice/GameClient/W3DRoadBuffer.cpp | 11 + .../W3DDevice/GameClient/W3DTerrainVisual.cpp | 511 +++- .../W3DDevice/GameClient/W3DTreeBuffer.cpp | 2029 ++++++++++--- .../W3DDevice/GameClient/WorldHeightMap.cpp | 450 ++- .../Code/Libraries/Include/Lib/BaseType.h | 56 +- .../Source/WWVegas/WW3D2/dx8caps.cpp | 1 + .../Libraries/Source/WWVegas/WW3D2/dx8caps.h | 2 + .../Libraries/Source/WWVegas/WW3D2/shader.cpp | 24 +- .../Libraries/Source/WWVegas/WW3D2/shader.h | 12 +- .../Tools/WorldBuilder/src/WorldBuilder.cpp | 2 + GeneralsMD/Code/GameEngine/CMakeLists.txt | 4 +- .../Include/GameClient/TerrainVisual.h | 12 - .../GameClient/Terrain/TerrainVisual.cpp | 5 - .../Code/GameEngineDevice/CMakeLists.txt | 28 +- .../W3DDevice/GameClient/W3DTerrainVisual.h | 16 - .../Source/W3DDevice/GameClient/HeightMap.cpp | 2 - .../W3DDevice/GameClient/TerrainTex.cpp | 2 +- .../W3DDevice/GameClient/W3DTerrainVisual.cpp | 44 +- .../W3DDevice/GameClient/WorldHeightMap.cpp | 18 - scripts/cpp/unify_move_files.py | 17 + 62 files changed, 3652 insertions(+), 3294 deletions(-) rename {GeneralsMD/Code => Core}/GameEngine/Include/GameClient/Snow.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Source/GameClient/Snow.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Include/W3DDevice/GameClient/FlatHeightMap.h (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DPropDraw.h (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DTreeDraw.h (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Include/W3DDevice/GameClient/W3DPropBuffer.h (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Include/W3DDevice/GameClient/W3DSnow.h (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainBackground.h (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DPropDraw.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DTreeDraw.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Source/W3DDevice/GameClient/FlatHeightMap.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Source/W3DDevice/GameClient/W3DPropBuffer.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Source/W3DDevice/GameClient/W3DSnow.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainBackground.cpp (100%) diff --git a/Core/GameEngine/CMakeLists.txt b/Core/GameEngine/CMakeLists.txt index e486efe32e..53a0bc08e6 100644 --- a/Core/GameEngine/CMakeLists.txt +++ b/Core/GameEngine/CMakeLists.txt @@ -224,7 +224,7 @@ set(GAMEENGINE_SRC # Include/GameClient/ShellHooks.h # Include/GameClient/ShellMenuScheme.h Include/GameClient/Smudge.h -# Include/GameClient/Snow.h + Include/GameClient/Snow.h # Include/GameClient/Statistics.h # Include/GameClient/TerrainRoads.h # Include/GameClient/TerrainVisual.h @@ -820,7 +820,7 @@ set(GAMEENGINE_SRC Source/GameClient/ParabolicEase.cpp # Source/GameClient/RadiusDecal.cpp # Source/GameClient/SelectionInfo.cpp -# Source/GameClient/Snow.cpp + Source/GameClient/Snow.cpp # Source/GameClient/Statistics.cpp # Source/GameClient/System/Anim2D.cpp # Source/GameClient/System/CampaignManager.cpp diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Snow.h b/Core/GameEngine/Include/GameClient/Snow.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/GameClient/Snow.h rename to Core/GameEngine/Include/GameClient/Snow.h diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Snow.cpp b/Core/GameEngine/Source/GameClient/Snow.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/GameClient/Snow.cpp rename to Core/GameEngine/Source/GameClient/Snow.cpp diff --git a/Core/GameEngineDevice/CMakeLists.txt b/Core/GameEngineDevice/CMakeLists.txt index 66dff03ecc..32bd6e6557 100644 --- a/Core/GameEngineDevice/CMakeLists.txt +++ b/Core/GameEngineDevice/CMakeLists.txt @@ -6,9 +6,9 @@ set(GAMEENGINEDEVICE_SRC # Include/W3DDevice/Common/W3DModuleFactory.h Include/W3DDevice/Common/W3DRadar.h # Include/W3DDevice/Common/W3DThingFactory.h -# Include/W3DDevice/GameClient/BaseHeightMap.h + Include/W3DDevice/GameClient/BaseHeightMap.h # Include/W3DDevice/GameClient/camerashakesystem.h -# Include/W3DDevice/GameClient/FlatHeightMap.h + Include/W3DDevice/GameClient/FlatHeightMap.h # Include/W3DDevice/GameClient/HeightMap.h # Include/W3DDevice/GameClient/Module/W3DDebrisDraw.h # Include/W3DDevice/GameClient/Module/W3DDefaultDraw.h @@ -20,14 +20,14 @@ set(GAMEENGINEDEVICE_SRC # Include/W3DDevice/GameClient/Module/W3DOverlordTruckDraw.h # Include/W3DDevice/GameClient/Module/W3DPoliceCarDraw.h # Include/W3DDevice/GameClient/Module/W3DProjectileStreamDraw.h -# Include/W3DDevice/GameClient/Module/W3DPropDraw.h + Include/W3DDevice/GameClient/Module/W3DPropDraw.h # Include/W3DDevice/GameClient/Module/W3DRopeDraw.h # Include/W3DDevice/GameClient/Module/W3DScienceModelDraw.h # Include/W3DDevice/GameClient/Module/W3DSupplyDraw.h # Include/W3DDevice/GameClient/Module/W3DTankDraw.h # Include/W3DDevice/GameClient/Module/W3DTankTruckDraw.h # Include/W3DDevice/GameClient/Module/W3DTracerDraw.h -# Include/W3DDevice/GameClient/Module/W3DTreeDraw.h + Include/W3DDevice/GameClient/Module/W3DTreeDraw.h # Include/W3DDevice/GameClient/Module/W3DTruckDraw.h # Include/W3DDevice/GameClient/TerrainTex.h # Include/W3DDevice/GameClient/TileData.h @@ -57,16 +57,16 @@ set(GAMEENGINEDEVICE_SRC # Include/W3DDevice/GameClient/W3DParticleSys.h # Include/W3DDevice/GameClient/W3DPoly.h # Include/W3DDevice/GameClient/W3DProjectedShadow.h -# Include/W3DDevice/GameClient/W3DPropBuffer.h + Include/W3DDevice/GameClient/W3DPropBuffer.h # Include/W3DDevice/GameClient/W3DRoadBuffer.h # Include/W3DDevice/GameClient/W3DScene.h Include/W3DDevice/GameClient/W3DShaderManager.h # Include/W3DDevice/GameClient/W3DShadow.h # Include/W3DDevice/GameClient/W3DShroud.h Include/W3DDevice/GameClient/W3DSmudge.h -# Include/W3DDevice/GameClient/W3DSnow.h + Include/W3DDevice/GameClient/W3DSnow.h # Include/W3DDevice/GameClient/W3DStatusCircle.h -# Include/W3DDevice/GameClient/W3DTerrainBackground.h + Include/W3DDevice/GameClient/W3DTerrainBackground.h # Include/W3DDevice/GameClient/W3DTerrainTracks.h # Include/W3DDevice/GameClient/W3DTerrainVisual.h # Include/W3DDevice/GameClient/W3DTreeBuffer.h @@ -97,7 +97,7 @@ set(GAMEENGINEDEVICE_SRC # Source/W3DDevice/Common/Thing/W3DModuleFactory.cpp # Source/W3DDevice/Common/Thing/W3DThingFactory.cpp # Source/W3DDevice/Common/W3DConvert.cpp -# Source/W3DDevice/GameClient/BaseHeightMap.cpp + Source/W3DDevice/GameClient/BaseHeightMap.cpp Source/W3DDevice/GameClient/CameraShakeSystem.cpp # Source/W3DDevice/GameClient/Drawable/Draw/W3DDebrisDraw.cpp # Source/W3DDevice/GameClient/Drawable/Draw/W3DDefaultDraw.cpp @@ -109,16 +109,16 @@ set(GAMEENGINEDEVICE_SRC # Source/W3DDevice/GameClient/Drawable/Draw/W3DOverlordTruckDraw.cpp # Source/W3DDevice/GameClient/Drawable/Draw/W3DPoliceCarDraw.cpp # Source/W3DDevice/GameClient/Drawable/Draw/W3DProjectileStreamDraw.cpp -# Source/W3DDevice/GameClient/Drawable/Draw/W3DPropDraw.cpp + Source/W3DDevice/GameClient/Drawable/Draw/W3DPropDraw.cpp # Source/W3DDevice/GameClient/Drawable/Draw/W3DRopeDraw.cpp # Source/W3DDevice/GameClient/Drawable/Draw/W3DScienceModelDraw.cpp # Source/W3DDevice/GameClient/Drawable/Draw/W3DSupplyDraw.cpp # Source/W3DDevice/GameClient/Drawable/Draw/W3DTankDraw.cpp # Source/W3DDevice/GameClient/Drawable/Draw/W3DTankTruckDraw.cpp # Source/W3DDevice/GameClient/Drawable/Draw/W3DTracerDraw.cpp -# Source/W3DDevice/GameClient/Drawable/Draw/W3DTreeDraw.cpp + Source/W3DDevice/GameClient/Drawable/Draw/W3DTreeDraw.cpp # Source/W3DDevice/GameClient/Drawable/Draw/W3DTruckDraw.cpp -# Source/W3DDevice/GameClient/FlatHeightMap.cpp + Source/W3DDevice/GameClient/FlatHeightMap.cpp # Source/W3DDevice/GameClient/GUI/Gadget/W3DCheckBox.cpp # Source/W3DDevice/GameClient/GUI/Gadget/W3DComboBox.cpp # Source/W3DDevice/GameClient/GUI/Gadget/W3DHorizontalSlider.cpp @@ -160,15 +160,15 @@ set(GAMEENGINEDEVICE_SRC # Source/W3DDevice/GameClient/W3DMouse.cpp # Source/W3DDevice/GameClient/W3DParticleSys.cpp # Source/W3DDevice/GameClient/W3DPoly.cpp -# Source/W3DDevice/GameClient/W3DPropBuffer.cpp + Source/W3DDevice/GameClient/W3DPropBuffer.cpp # Source/W3DDevice/GameClient/W3DRoadBuffer.cpp # Source/W3DDevice/GameClient/W3DScene.cpp Source/W3DDevice/GameClient/W3DShaderManager.cpp # Source/W3DDevice/GameClient/W3DShroud.cpp Source/W3DDevice/GameClient/W3DSmudge.cpp -# Source/W3DDevice/GameClient/W3DSnow.cpp + Source/W3DDevice/GameClient/W3DSnow.cpp # Source/W3DDevice/GameClient/W3DStatusCircle.cpp -# Source/W3DDevice/GameClient/W3DTerrainBackground.cpp + Source/W3DDevice/GameClient/W3DTerrainBackground.cpp # Source/W3DDevice/GameClient/W3DTerrainTracks.cpp # Source/W3DDevice/GameClient/W3DTerrainVisual.cpp # Source/W3DDevice/GameClient/W3DTreeBuffer.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h b/Core/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h rename to Core/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/FlatHeightMap.h b/Core/GameEngineDevice/Include/W3DDevice/GameClient/FlatHeightMap.h similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/FlatHeightMap.h rename to Core/GameEngineDevice/Include/W3DDevice/GameClient/FlatHeightMap.h diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DPropDraw.h b/Core/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DPropDraw.h similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DPropDraw.h rename to Core/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DPropDraw.h diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DTreeDraw.h b/Core/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DTreeDraw.h similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DTreeDraw.h rename to Core/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DTreeDraw.h diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DPropBuffer.h b/Core/GameEngineDevice/Include/W3DDevice/GameClient/W3DPropBuffer.h similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DPropBuffer.h rename to Core/GameEngineDevice/Include/W3DDevice/GameClient/W3DPropBuffer.h diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DSnow.h b/Core/GameEngineDevice/Include/W3DDevice/GameClient/W3DSnow.h similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DSnow.h rename to Core/GameEngineDevice/Include/W3DDevice/GameClient/W3DSnow.h diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainBackground.h b/Core/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainBackground.h similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainBackground.h rename to Core/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainBackground.h diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp rename to Core/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DPropDraw.cpp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DPropDraw.cpp similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DPropDraw.cpp rename to Core/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DPropDraw.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DTreeDraw.cpp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DTreeDraw.cpp similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DTreeDraw.cpp rename to Core/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DTreeDraw.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/FlatHeightMap.cpp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/FlatHeightMap.cpp similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/FlatHeightMap.cpp rename to Core/GameEngineDevice/Source/W3DDevice/GameClient/FlatHeightMap.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DPropBuffer.cpp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/W3DPropBuffer.cpp similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DPropBuffer.cpp rename to Core/GameEngineDevice/Source/W3DDevice/GameClient/W3DPropBuffer.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DSnow.cpp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/W3DSnow.cpp similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DSnow.cpp rename to Core/GameEngineDevice/Source/W3DDevice/GameClient/W3DSnow.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainBackground.cpp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainBackground.cpp similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainBackground.cpp rename to Core/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainBackground.cpp diff --git a/Generals/Code/GameEngine/Include/Common/GlobalData.h b/Generals/Code/GameEngine/Include/Common/GlobalData.h index 0e59219221..cb7c0d1dda 100644 --- a/Generals/Code/GameEngine/Include/Common/GlobalData.h +++ b/Generals/Code/GameEngine/Include/Common/GlobalData.h @@ -153,6 +153,7 @@ class GlobalData : public SubsystemInterface Int m_waterType; Bool m_showSoftWaterEdge; Bool m_usingWaterTrackEditor; + Bool m_isWorldBuilder; Int m_featherWater; diff --git a/Generals/Code/GameEngine/Include/Common/INI.h b/Generals/Code/GameEngine/Include/Common/INI.h index 869b4d1c20..0e48452dc5 100644 --- a/Generals/Code/GameEngine/Include/Common/INI.h +++ b/Generals/Code/GameEngine/Include/Common/INI.h @@ -204,6 +204,7 @@ class INI static void parseParticleSystemDefinition( INI *ini ); static void parseWaterSettingDefinition( INI *ini ); static void parseWaterTransparencyDefinition( INI *ini ); + static void parseWeatherDefinition( INI *ini ); static void parseMappedImageDefinition( INI *ini ); static void parseArmorDefinition( INI *ini ); static void parseDamageFXDefinition( INI *ini ); diff --git a/Generals/Code/GameEngine/Include/Common/MapObject.h b/Generals/Code/GameEngine/Include/Common/MapObject.h index 9b29e983ad..91ed1c3005 100644 --- a/Generals/Code/GameEngine/Include/Common/MapObject.h +++ b/Generals/Code/GameEngine/Include/Common/MapObject.h @@ -33,6 +33,19 @@ #include "Common/GameMemory.h" #include "GameClient/TerrainRoads.h" + + +class WorldHeightMapInterfaceClass +{ +public: + + virtual Int getBorderSize() = 0; + virtual Real getSeismicZVelocity(Int xIndex, Int yIndex) const = 0; + virtual void setSeismicZVelocity(Int xIndex, Int yIndex, Real value) = 0; + virtual Real getBilinearSampleSeismicZVelocity( Int x, Int y) = 0; + +}; + /** MapObject class Not ref counted. Do not store pointers to this class. */ class WorldHeightMap; diff --git a/Generals/Code/GameEngine/Include/Common/ThingFactory.h b/Generals/Code/GameEngine/Include/Common/ThingFactory.h index 4d4871aedb..c9469239c2 100644 --- a/Generals/Code/GameEngine/Include/Common/ThingFactory.h +++ b/Generals/Code/GameEngine/Include/Common/ThingFactory.h @@ -73,7 +73,7 @@ class ThingFactory : public SubsystemInterface get a template given template database name. return null if not found. note, this is now substantially faster (does a hash-table lookup) */ - const ThingTemplate *findTemplate( const AsciiString& name ) { return findTemplateInternal(name); } + const ThingTemplate *findTemplate( const AsciiString& name, Bool check = TRUE ) { return findTemplateInternal( name, check ); } /** get a template given ID. return null if not found. @@ -120,7 +120,7 @@ class ThingFactory : public SubsystemInterface NOTE: this is protected since it returns a NON-CONST template, and folks outside of the template system itself shouldn't get access... */ - ThingTemplate *findTemplateInternal( const AsciiString& name ); + ThingTemplate *findTemplateInternal( const AsciiString& name, Bool check = TRUE ); ThingTemplate *m_firstTemplate; ///< head of linked list UnsignedShort m_nextTemplateID; ///< next available ID for templates diff --git a/Generals/Code/GameEngine/Include/GameClient/TerrainVisual.h b/Generals/Code/GameEngine/Include/GameClient/TerrainVisual.h index a6cb48cb63..b89d384f75 100644 --- a/Generals/Code/GameEngine/Include/GameClient/TerrainVisual.h +++ b/Generals/Code/GameEngine/Include/GameClient/TerrainVisual.h @@ -31,6 +31,7 @@ #include "Common/Terrain.h" #include "Common/Snapshot.h" +#include "Common/MapObject.h" // FORWARD REFERENCES ///////////////////////////////////////////////////////////////////////////// class TerrainType; @@ -38,6 +39,119 @@ class WaterHandle; class Matrix3D; class Object; class Drawable; +class GeometryInfo; + + +class WorldHeightMap; +struct SeismicSimulationNode; +class SeismicSimulationFilterBase; + + +#define DEFAULT_SEISMIC_SIMULATION_MAGNITUDE (20.0f) +struct SeismicSimulationNode; // just a forward declaration folks, no cause for alarm +class SeismicSimulationFilterBase +{ +public: + enum SeismicSimStatusCode CPP_11(: Int) + { + SEISMIC_STATUS_INVALID, + SEISMIC_STATUS_ACTIVE, + SEISMIC_STATUS_ZERO_ENERGY, + }; + + virtual SeismicSimStatusCode filterCallback( WorldHeightMapInterfaceClass *heightMap, const SeismicSimulationNode *node ) = 0; + virtual Real applyGravityCallback( Real velocityIn ) = 0; +}; + +struct SeismicSimulationNode +{ + SeismicSimulationNode() + { + m_center.x = 0; + m_center.y = 0; + m_radius = 0; + m_region.lo.x = 0; + m_region.lo.y = 0; + m_region.hi.x = 0; + m_region.hi.y = 0; + m_clean = FALSE; + callbackFilter = NULL; + m_life = 0; + m_magnitude = DEFAULT_SEISMIC_SIMULATION_MAGNITUDE; + + } + SeismicSimulationNode( const SeismicSimulationNode &ssn ) + { + m_center.x = ssn.m_center.x; + m_center.y = ssn.m_center.y; + m_radius = ssn.m_radius; + m_region.lo.x = ssn.m_region.lo.x; + m_region.lo.y = ssn.m_region.lo.y; + m_region.hi.x = ssn.m_region.hi.x; + m_region.hi.y = ssn.m_region.hi.y; + m_clean = ssn.m_clean; + callbackFilter= ssn.callbackFilter; + m_life = ssn.m_life; + m_magnitude = ssn.m_magnitude; + + } + SeismicSimulationNode( const Coord3D* ctr, Real rad, Real mag, SeismicSimulationFilterBase *cbf = NULL ) + { + m_center.x = REAL_TO_INT_FLOOR(ctr->x/MAP_XY_FACTOR); + m_center.y = REAL_TO_INT_FLOOR(ctr->y/MAP_XY_FACTOR); + m_radius = (rad-1)/MAP_XY_FACTOR; + UnsignedInt regionSize = rad/MAP_XY_FACTOR; + m_region.lo.x = m_center.x - regionSize; + m_region.lo.y = m_center.y - regionSize; + m_region.hi.x = m_center.x + regionSize; + m_region.hi.y = m_center.y + regionSize; + m_clean = false; + callbackFilter= cbf; + m_life = 0; + m_magnitude = mag; + + } + + SeismicSimulationFilterBase::SeismicSimStatusCode handleFilterCallback( WorldHeightMapInterfaceClass *heightMap ) + { + if ( callbackFilter == NULL ) + return SeismicSimulationFilterBase::SEISMIC_STATUS_INVALID; + + ++m_life; + + return callbackFilter->filterCallback( heightMap, this ); + } + + Real applyGravity( Real velocityIn ) + { + DEBUG_ASSERTCRASH( callbackFilter, ("SeismicSimulationNode::applyGravity() has no callback filter!") ); + + if ( callbackFilter == NULL ) + return velocityIn;//oops, we have no callback! + + return callbackFilter->applyGravityCallback( velocityIn ); + + } + + IRegion2D m_region; + ICoord2D m_center; + Bool m_clean; + Real m_magnitude; + UnsignedInt m_radius; + UnsignedInt m_life; + + SeismicSimulationFilterBase *callbackFilter; + +}; +typedef std::list SeismicSimulationList; +typedef SeismicSimulationList::iterator SeismicSimulationListIt; + +class DomeStyleSeismicFilter : public SeismicSimulationFilterBase +{ + virtual SeismicSimStatusCode filterCallback( WorldHeightMapInterfaceClass *heightMap, const SeismicSimulationNode *node ); + virtual Real applyGravityCallback( Real velocityIn ); +}; + //------------------------------------------------------------------------------------------------- /** LOD values for terrain, keep this in sync with TerrainLODNames[] */ @@ -149,11 +263,34 @@ class TerrainVisual : public Snapshot, virtual void removeAllBibs(void)=0; virtual void removeBibHighlighting(void)=0; + virtual void removeTreesAndPropsForConstruction( + const Coord3D* pos, + const GeometryInfo& geom, + Real angle + ) = 0; + + virtual void addProp(const ThingTemplate *tt, const Coord3D *pos, Real angle) = 0; // // Modify height. // virtual void setRawMapHeight(const ICoord2D *gridPos, Int height)=0; + virtual Int getRawMapHeight(const ICoord2D *gridPos)=0; + + + //////////////////////////////////////////////////// + //////////////////////////////////////////////////// + //////////////////////////////////////////////////// +#ifdef DO_SEISMIC_SIMULATIONS + virtual void updateSeismicSimulations( void ) = 0; /// walk the SeismicSimulationList and, well, do it. + virtual void addSeismicSimulation( const SeismicSimulationNode& sim ) = 0; +#endif + virtual WorldHeightMap* getLogicHeightMap( void ) {return NULL;}; + virtual WorldHeightMap* getClientHeightMap( void ) {return NULL;}; + //////////////////////////////////////////////////// + //////////////////////////////////////////////////// + //////////////////////////////////////////////////// + /// Replace the skybox texture virtual void replaceSkyboxTextures(const AsciiString *oldTexName[NumSkyboxTextures], const AsciiString *newTexName[NumSkyboxTextures])=0; diff --git a/Generals/Code/GameEngine/Include/GameLogic/PartitionManager.h b/Generals/Code/GameEngine/Include/GameLogic/PartitionManager.h index 20c9146ac3..18e278bb71 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/PartitionManager.h +++ b/Generals/Code/GameEngine/Include/GameLogic/PartitionManager.h @@ -1479,6 +1479,8 @@ class PartitionManager : public SubsystemInterface, public Snapshot CellShroudStatus getShroudStatusForPlayer( Int playerIndex, Int x, Int y ) const; CellShroudStatus getShroudStatusForPlayer( Int playerIndex, const Coord3D *loc ) const; + ObjectShroudStatus getPropShroudStatusForPlayer(Int playerIndex, const Coord3D *loc ) const; + Real getGroundOrStructureHeight(Real posx, Real posy); void getMostValuableLocation( Int playerIndex, UnsignedInt whichPlayerTypes, ValueOrThreat valType, Coord3D *outLocation ); diff --git a/Generals/Code/GameEngine/Source/Common/GlobalData.cpp b/Generals/Code/GameEngine/Source/Common/GlobalData.cpp index 9bb81b3165..348374f57f 100644 --- a/Generals/Code/GameEngine/Source/Common/GlobalData.cpp +++ b/Generals/Code/GameEngine/Source/Common/GlobalData.cpp @@ -670,6 +670,7 @@ GlobalData::GlobalData() m_featherWater = FALSE; m_showSoftWaterEdge = TRUE; //display soft water edge m_usingWaterTrackEditor = FALSE; + m_isWorldBuilder = FALSE; m_showMetrics = false; diff --git a/Generals/Code/GameEngine/Source/Common/INI/INI.cpp b/Generals/Code/GameEngine/Source/Common/INI/INI.cpp index 8e39f00c65..51b8fc2e8a 100644 --- a/Generals/Code/GameEngine/Source/Common/INI/INI.cpp +++ b/Generals/Code/GameEngine/Source/Common/INI/INI.cpp @@ -127,6 +127,7 @@ static const BlockParse theTypeTable[] = { "Video", INI::parseVideoDefinition }, { "WaterSet", INI::parseWaterSettingDefinition }, { "WaterTransparency", INI::parseWaterTransparencyDefinition}, + { "Weather", INI::parseWeatherDefinition}, { "Weapon", INI::parseWeaponTemplateDefinition }, { "WebpageURL", INI::parseWebpageURLDefinition }, { "HeaderTemplate", INI::parseHeaderTemplateDefinition }, diff --git a/Generals/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp b/Generals/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp index 8c75ab0f3d..22db98ea19 100644 --- a/Generals/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp +++ b/Generals/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp @@ -134,7 +134,7 @@ ThingTemplate *ThingFactory::newTemplate( const AsciiString& name ) newTemplate = newInstance(ThingTemplate); // if the default template is present, get it and copy over any data to the new template - const ThingTemplate *defaultT = findTemplate( "DefaultThingTemplate" ); + const ThingTemplate *defaultT = findTemplate( "DefaultThingTemplate", FALSE ); if( defaultT ) { @@ -265,7 +265,7 @@ const ThingTemplate *ThingFactory::findByTemplateID( UnsignedShort id ) //------------------------------------------------------------------------------------------------- /** Return the template with the matching database name */ //------------------------------------------------------------------------------------------------- -ThingTemplate *ThingFactory::findTemplateInternal( const AsciiString& name ) +ThingTemplate *ThingFactory::findTemplateInternal( const AsciiString& name, Bool check ) { ThingTemplateHashMapIt tIt = m_templateHashMap.find(name); @@ -292,7 +292,10 @@ ThingTemplate *ThingFactory::findTemplateInternal( const AsciiString& name ) #endif - //DEBUG_LOG(("*** Object template %s not found",name.str())); + if( check && name.isNotEmpty() ) + { + DEBUG_CRASH( ("Failed to find thing template %s (case sensitive) This issue has a chance of crashing after you ignore it!", name.str() ) ); + } return NULL; } @@ -372,7 +375,7 @@ AsciiString TheThingTemplateBeingParsedName; #endif // find existing item if present - ThingTemplate *thingTemplate = TheThingFactory->findTemplateInternal( name ); + ThingTemplate *thingTemplate = TheThingFactory->findTemplateInternal( name, FALSE ); if( !thingTemplate ) { // no item is present, create a new one diff --git a/Generals/Code/GameEngine/Source/GameClient/MapUtil.cpp b/Generals/Code/GameEngine/Source/GameClient/MapUtil.cpp index 41fcbb2578..6f4e8abfed 100644 --- a/Generals/Code/GameEngine/Source/GameClient/MapUtil.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/MapUtil.cpp @@ -131,7 +131,7 @@ static Bool ParseObjectDataChunk(DataChunkInput &file, DataChunkInfo *info, void // create the map object pThisOne = newInstance( MapObject )( loc, name, angle, flags, &d, - TheThingFactory->findTemplate( name ) ); + TheThingFactory->findTemplate( name, FALSE ) ); //DEBUG_LOG(("obj %s owner %s",name.str(),d.getAsciiString(TheKey_originalOwner).str())); diff --git a/Generals/Code/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp b/Generals/Code/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp index 712769dde3..4220bb451e 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp @@ -128,3 +128,81 @@ void TerrainVisual::loadPostProcess( void ) { } + + +SeismicSimulationFilterBase::SeismicSimStatusCode DomeStyleSeismicFilter::filterCallback( WorldHeightMapInterfaceClass *heightMap, const SeismicSimulationNode *node ) +{ + + Int life = node->m_life; + + if ( heightMap == NULL ) + return SEISMIC_STATUS_INVALID; + + + if ( life == 0 ) + return SEISMIC_STATUS_ACTIVE; + if ( life < 15 ) + { + // ADD HEIGHT BECAUSE THE EXPLOSION IS PUSHING DIRT UP + + Real magnitude = node->m_magnitude; + + Real offsScalar = magnitude / (Real)life; // real-life, get it? + Int radius = node->m_radius; + Int border = heightMap->getBorderSize(); + Int centerX = node->m_center.x + border ; + Int centerY = node->m_center.y + border ; + + UnsignedInt workspaceWidth = radius*2; + Real *workspace = NEW Real[ sqr(workspaceWidth) ]; + Real *workspaceEnd = workspace + sqr(workspaceWidth); + + + for ( Real *t = workspace; t < workspaceEnd; ++t ) *t = 0.0f;// clear the workspace + + Int x, y; + for (x = 0; x < radius; ++x) + { + for (y = 0; y < radius; ++y) + { + + Real distance = sqrt( sqr(x) + sqr(y) );//Pythagoras + + if ( distance < radius ) + { + Real distScalar = cos( ( distance / radius * (PI/2) ) ); + Real height = (offsScalar * distScalar); + + workspace[ (radius + x) + workspaceWidth * (radius + y) ] = height + heightMap->getBilinearSampleSeismicZVelocity( centerX + x, centerY + y ) ;//kaleidoscope + + if ( x != 0 ) // non-zero test prevents cross-shaped double stamp + { + workspace[ (radius - x) + workspaceWidth * (radius + y) ] = height + heightMap->getBilinearSampleSeismicZVelocity( centerX - x, centerY + y ) ; + if ( y != 0 ) + workspace[ (radius - x) + workspaceWidth * (radius - y) ] = height + heightMap->getBilinearSampleSeismicZVelocity( centerX - x, centerY - y ) ; + } + if ( y != 0 ) + workspace[ (radius + x) + workspaceWidth * (radius - y) ] = height + heightMap->getBilinearSampleSeismicZVelocity( centerX + x, centerY - y ) ; + } + } + } + + // stuff the values from the workspace into the heightmap's velocities + for (x = 0; x < workspaceWidth; ++x) + for (y = 0; y < workspaceWidth; ++y) + heightMap->setSeismicZVelocity( centerX - radius + x, centerY - radius + y, MIN( 9.0f, workspace[ x + workspaceWidth * y ]) ); + + delete [] workspace; + + return SEISMIC_STATUS_ACTIVE; + } + else + return SEISMIC_STATUS_ZERO_ENERGY; +} + +Real DomeStyleSeismicFilter::applyGravityCallback( Real velocityIn ) +{ + Real velocityOut = velocityIn; + velocityOut -= 1.5f; + return velocityOut; +} diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp index b2c353701d..9986736965 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp @@ -3080,6 +3080,32 @@ CellShroudStatus PartitionManager::getShroudStatusForPlayer(Int playerIndex, con } +//----------------------------------------------------------------------------- +ObjectShroudStatus PartitionManager::getPropShroudStatusForPlayer(Int playerIndex, const Coord3D *loc ) const +{ + Int x, y; + + ThePartitionManager->worldToCell( loc->x - m_cellSize*0.5f, loc->y - m_cellSize*0.5f, &x, &y ); + + CellShroudStatus cellStat = getShroudStatusForPlayer( playerIndex, x, y ); + if (cellStat != getShroudStatusForPlayer( playerIndex, x+1, y )) { + return OBJECTSHROUD_PARTIAL_CLEAR; + } + if (cellStat != getShroudStatusForPlayer( playerIndex, x+1, y+1 )) { + return OBJECTSHROUD_PARTIAL_CLEAR; + } + if (cellStat != getShroudStatusForPlayer( playerIndex, x, y+1 )) { + return OBJECTSHROUD_PARTIAL_CLEAR; + } + if (cellStat == CELLSHROUD_SHROUDED) { + return OBJECTSHROUD_SHROUDED; + } + if (cellStat == CELLSHROUD_CLEAR) { + return OBJECTSHROUD_CLEAR; + } + return OBJECTSHROUD_FOGGED; +} + #ifdef FASTER_GCO diff --git a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp index e0242d431c..6680f09c8c 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp @@ -4923,7 +4923,7 @@ void ScriptActions::doMoveUnitTowardsNearest( const AsciiString& unitName, const return; } - const ThingTemplate *templ = TheThingFactory->findTemplate(objectType); + const ThingTemplate *templ = TheThingFactory->findTemplate(objectType, FALSE); if (!templ) { return; } @@ -4958,7 +4958,7 @@ void ScriptActions::doMoveTeamTowardsNearest( const AsciiString& teamName, const return; } - const ThingTemplate *templ = TheThingFactory->findTemplate(objectType); + const ThingTemplate *templ = TheThingFactory->findTemplate(objectType, FALSE); if (!templ) { return; } @@ -5447,7 +5447,7 @@ void ScriptActions::doTeamUseCommandButtonOnNearestObjectType( const AsciiString return; } - const ThingTemplate *thingTemplate = TheThingFactory->findTemplate(objectType); + const ThingTemplate *thingTemplate = TheThingFactory->findTemplate(objectType, FALSE); if (!thingTemplate) { return; } diff --git a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h index 4e0829dedd..d800fea6a3 100644 --- a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h +++ b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h @@ -34,63 +34,14 @@ #include "vertmaterial.h" #include "Lib/BaseType.h" #include "Common/GameType.h" -#include "WorldHeightMap.h" - -#define MAX_ENABLED_DYNAMIC_LIGHTS 20 -typedef UnsignedByte HeightSampleType; //type of data to store in heightmap -class W3DTreeBuffer; -class W3DBibBuffer; -class W3DRoadBuffer; -class W3DBridgeBuffer; -class W3DWaypointBuffer; -class W3DTerrainLogic; -class W3DCustomEdging; -class W3DAssetManager; -class SimpleSceneClass; -class W3DShroud; - -#define no_TIMING_TESTS 1 - -#define no_PRE_TRANSFORM_VERTEX // Don't do this, not a performance win. jba. - -#define no_USE_TREE_BUFFER ///@todoRe-enable this optimization later... jba. - -typedef struct { - Int minX, maxX; - Int minY, maxY; -} TBounds; +#include "W3DDevice/GameClient/WorldHeightMap.h" +#include "W3DDevice/GameClient/BaseHeightMap.h" #define VERTEX_BUFFER_TILE_LENGTH 32 //tiles of side length 32 (grid of 33x33 vertices). -class LightMapTerrainTextureClass; -class CloudMapTerrainTextureClass; -class W3DDynamicLight; - -#if 0 -#define USE_NORMALS 1 -#define VERTEX_FORMAT VertexFormatXYZNUV2 -#else -#define USE_DIFFUSE 1 -#define VERTEX_FORMAT VertexFormatXYZDUV2 -#define DX8_VERTEX_FORMAT DX8_FVF_XYZDUV2 -#endif - -#define DO_SCORCH 1 - -#define DO_ROADS 1 - -#define TEST_CUSTOM_EDGING 1 - // Adjust the triangles to make cliff sides most attractive. jba. #define FLIP_TRIANGLES 1 -#ifdef DO_SCORCH -typedef struct { - Vector3 location; - Real radius; - Int scorchType; -} TScorch; -#endif /// Custom render object that draws the heightmap and handles intersection tests. /** @@ -98,13 +49,16 @@ Custom W3D render object that's used to process the terrain. It handles virtually everything to do with the terrain, including: drawing, lighting, scorchmarks and intersection tests. */ -class HeightMapRenderObjClass : public RenderObjClass, public DX8_CleanupHook + + + +class HeightMapRenderObjClass : public BaseHeightMapRenderObjClass { public: HeightMapRenderObjClass(void); - ~HeightMapRenderObjClass(void); + virtual ~HeightMapRenderObjClass(void); // DX8_CleanupHook methods virtual void ReleaseResources(void); ///< Release all dx8 resources so the device can be reset. @@ -114,194 +68,40 @@ class HeightMapRenderObjClass : public RenderObjClass, public DX8_CleanupHook ///////////////////////////////////////////////////////////////////////////// // Render Object Interface (W3D methods) ///////////////////////////////////////////////////////////////////////////// - virtual RenderObjClass * Clone(void) const; - virtual int Class_ID(void) const; virtual void Render(RenderInfoClass & rinfo); - virtual bool Cast_Ray(RayCollisionTestClass & raytest); // This CANNOT be Bool, as it will not inherit properly if you make Bool == Int -///@todo: Add methods for collision detection with terrain -// 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 Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const; - virtual void Get_Obj_Space_Bounding_Box(AABoxClass & aabox) const; - - virtual void On_Frame_Update(void); - virtual void Notify_Added(SceneClass * scene); ///allocate resources needed to render heightmap - int initHeightData(Int width, Int height, WorldHeightMap *pMap, RefRenderObjListIterator *pLightsIterator); - Int freeMapResources(void); ///< free resources used to render heightmap - UnsignedByte getClipHeight(Int x, Int y) const - { - Int xextent = m_map->getXExtent() - 1; - Int yextent = m_map->getYExtent() - 1; - - if (x < 0) - x = 0; - else if (x > xextent) - x = xextent; - - if (y < 0) - y = 0; - else if (y > yextent) - y = yextent; - - return m_map->getDataPtr()[x + y*m_map->getXExtent()]; - } - void updateCenter(CameraClass *camera, RefRenderObjListIterator *pLightsIterator); - - /// Update the macro texture (pass 3). - void updateMacroTexture(AsciiString textureName); - void doTextures(Bool flag) {m_disableTextures = !flag;}; - /// Update the diffuse value from static light info for one vertex. - void doTheLight(VERTEX_FORMAT *vb, Vector3*light, Vector3*normal, RefRenderObjListIterator *pLightsIterator, UnsignedByte alpha); - void addScorch(Vector3 location, Real radius, Scorches type); - void addTree(Coord3D location, Real scale, Real angle, AsciiString name, Bool visibleInMirror); - void renderTrees(CameraClass * camera); ///< renders the tree buffer. - - /// Add a bib at location. - void addTerrainBib(Vector3 corners[4], ObjectID id, Bool highlight); - void addTerrainBibDrawable(Vector3 corners[4], DrawableID id, Bool highlight); - /// Remove a bib. - void removeTerrainBib(ObjectID id); - void removeTerrainBibDrawable(DrawableID id); - - /// Removes all bibs. - void removeAllTerrainBibs(void); - /// Remove all highlighting. - void removeTerrainBibHighlighting(void); - - void renderTerrainPass(CameraClass *pCamera); ///< renders additional terrain pass. - W3DShroud *getShroud() {return m_shroud;} - void updateShorelineTiles(Int minX, Int minY, Int maxX, Int maxY, WorldHeightMap *pMap); ///
m_showAsVisibleCliff; - - DX8IndexBufferClass *m_indexBuffer; /// VecICoord2D; @@ -88,7 +88,10 @@ class DataChunkInput; struct DataChunkInfo; class AlphaEdgeTextureClass; -class WorldHeightMap : public RefCountClass +#define NUM_ALPHA_TILES 12 + +class WorldHeightMap : public RefCountClass, + public WorldHeightMapInterfaceClass { friend class TerrainTextureClass; friend class AlphaTerrainTextureClass; @@ -115,10 +118,16 @@ class WorldHeightMap : public RefCountClass VecICoord2D m_boundaries; ///< the in-game boundaries Int m_dataSize; ///< size of m_data. UnsignedByte *m_data; ///< array of z(height) values in the height map. - UnsignedByte *m_cellFlipState; ///< array of bits to indicate the flip state of each cell. + + UnsignedByte *m_seismicUpdateFlag; ///< array of bits to prevent ovelapping physics-update regions from doubling effects on shared cells + UnsignedInt m_seismicUpdateWidth; ///< width of the array holding SeismicUpdateFlags + Real *m_seismicZVelocities; ///< how fast is the dirt rising/falling at this location + + UnsignedByte *m_cellFlipState; ///< array of bits to indicate the flip state of each cell. Int m_flipStateWidth; ///< with of the array holding cellFlipState UnsignedByte *m_cellCliffState; ///< array of bits to indicate the cliff state of each cell. + /// Texture indices. Short *m_tileNdxes; ///< matches m_Data, indexes into m_SourceTiles. Short *m_blendTileNdxes; ///< matches m_Data, indexes into m_blendedTiles. 0 means no blend info. @@ -171,11 +180,13 @@ class WorldHeightMap : public RefCountClass Int m_drawWidthX; Int m_drawHeightY; + /// Tiles that hold the alpha channel info. + static TileData *m_alphaTiles[NUM_ALPHA_TILES]; + + protected: TileData *getSourceTile(UnsignedInt ndx) { if (ndxm_width) m_drawWidthX = m_width;} void setDrawHeight(Int height) {m_drawHeightY = height; if (m_drawHeightY>m_height) m_drawHeightY = m_height;} - Int getBorderSize(void) {return m_borderSize;} + virtual Int getBorderSize(void) {return m_borderSize;} + Int getBorderSizeInline(void) const { return m_borderSize; } /// Get height with the offset that HeightMapRenderObjClass uses built in. UnsignedByte getDisplayHeight(Int x, Int y) { return m_data[x+m_drawOriginX+m_width*(y+m_drawOriginY)];} @@ -250,12 +262,21 @@ class WorldHeightMap : public RefCountClass TXTextureClass getTextureFromIndex( Int textureIndex ); public: // tile and texture info. + void setTextureLOD(Int lod); ///< set maximum lod level sent to the hardware. TextureClass *getTerrainTexture(void); //< generates if needed and returns the terrain texture TextureClass *getAlphaTerrainTexture(void); //< generates if needed and returns alpha terrain texture TextureClass *getEdgeTerrainTexture(void); //< generates if needed and returns blend edge texture /// UV mapping data for a cell to map into the terrain texture. Returns true if the textures had to be stretched for cliffs. Bool getUVData(Int xIndex, Int yIndex, float U[4], float V[4], Bool fullTile); Bool getFlipState(Int xIndex, Int yIndex) const; + ///Faster version of above function without all the safety checks - For people that do checks externally. + Bool getQuickFlipState(Int xIndex, Int yIndex) const + { + return m_cellFlipState[yIndex*m_flipStateWidth + (xIndex >> 3)] & (1<<(xIndex&0x7)); + } + + void setFlipState(Int xIndex, Int yIndex, Bool value); + void clearFlipStates(void); Bool getCliffState(Int xIndex, Int yIndex) const; Bool getExtraAlphaUVData(Int xIndex, Int yIndex, float U[4], float V[4], UnsignedByte alpha[4], Bool *flip, Bool *cliff); /// UV mapping data for a cell to map into the alpha terrain texture. @@ -264,11 +285,33 @@ class WorldHeightMap : public RefCountClass AsciiString getTerrainNameAt(Real x, Real y); Bool isCliffMappedTexture(Int xIndex, Int yIndex); + + Bool getSeismicUpdateFlag(Int xIndex, Int yIndex) const; + void setSeismicUpdateFlag(Int xIndex, Int yIndex, Bool value); + void clearSeismicUpdateFlags(void) ; + virtual Real getSeismicZVelocity(Int xIndex, Int yIndex) const; + virtual void setSeismicZVelocity(Int xIndex, Int yIndex, Real value); + void fillSeismicZVelocities( Real value ); + virtual Real getBilinearSampleSeismicZVelocity( Int x, Int y); + + + +public: // Flat tile texture info. + TerrainTextureClass *getFlatTexture(Int xCell, Int yCell, Int cellWidth, Int pixelsPerCell); //< generates and returns the terrain texture + + static void setupAlphaTiles(void); + UnsignedByte *getPointerToTileData(Int xIndex, Int yIndex, Int width); + Bool getRawTileData(Short tileNdx, Int width, UnsignedByte *buffer, Int bufLen); + UnsignedByte *getRGBAlphaDataForWidth(Int width, TBlendTileInfo *pBlend); + public: // modify height value void setRawHeight(Int xIndex, Int yIndex, UnsignedByte height) { Int ndx = (yIndex*m_width)+xIndex; if ((ndx>=0) && (ndx #include #include @@ -71,6 +73,7 @@ #include "W3DDevice/GameClient/W3DTerrainTracks.h" #include "W3DDevice/GameClient/W3DBibBuffer.h" #include "W3DDevice/GameClient/W3DTreeBuffer.h" +#include "W3DDevice/GameClient/W3DPropBuffer.h" #include "W3DDevice/GameClient/W3DRoadBuffer.h" #include "W3DDevice/GameClient/W3DBridgeBuffer.h" #include "W3DDevice/GameClient/W3DWaypointBuffer.h" @@ -92,6 +95,9 @@ #define no_OPTIMIZED_HEIGHTMAP_LIGHTING 01 // Doesn't work well. jba. +const Bool HALF_RES_MESH = false; + +HeightMapRenderObjClass *TheHeightMap = NULL; //----------------------------------------------------------------------------- // Private Data //----------------------------------------------------------------------------- @@ -101,35 +107,12 @@ static ShaderClass detailOpaqueShader(SC_DETAIL_BLEND); -//----------------------------------------------------------------------------- -// Global Functions & Data -//----------------------------------------------------------------------------- -/// The one-of for the terrain rendering object. -HeightMapRenderObjClass *TheTerrainRenderObject=NULL; - -/** Entry point so that trees can be drawn at the appropriate point in the rendering pipe for - transparent objects. */ -void DoTrees(RenderInfoClass & rinfo) -{ - if (TheTerrainRenderObject) { - TheTerrainRenderObject->renderTrees(&rinfo.Camera); - } -} - -void oversizeTheTerrain(Int amount) -{ - if (TheTerrainRenderObject) - { - TheTerrainRenderObject->oversizeTerrain(amount); - } -} - #define DEFAULT_MAX_FRAME_EXTRABLEND_TILES 256 //default number of terrain tiles rendered per call (must fit in one VB) #define DEFAULT_MAX_MAP_EXTRABLEND_TILES 2048 //default size of array allocated to hold all map extra blend tiles. #define DEFAULT_MAX_BATCH_SHORELINE_TILES 512 //maximum number of terrain tiles rendered per call (must fit in one VB) #define DEFAULT_MAX_MAP_SHORELINE_TILES 4096 //default size of array allocated to hold all map shoreline tiles. -#define ADJUST_FROM_INDEX_TO_REAL(k) ((k-m_map->getBorderSize())*MAP_XY_FACTOR) +#define ADJUST_FROM_INDEX_TO_REAL(k) ((k-m_map->getBorderSizeInline())*MAP_XY_FACTOR) inline Int IABS(Int x) { if (x>=0) return x; return -x;}; //----------------------------------------------------------------------------- @@ -137,15 +120,12 @@ inline Int IABS(Int x) { if (x>=0) return x; return -x;}; //----------------------------------------------------------------------------- //============================================================================= -// HeightMapRenderObjClass::freeMapResources +// HeightMapRenderObjClass::freeIndexVertexBuffers //============================================================================= /** Frees the w3d resources used to draw the terrain. */ //============================================================================= -Int HeightMapRenderObjClass::freeMapResources(void) +void HeightMapRenderObjClass::freeIndexVertexBuffers(void) { -#ifdef DO_SCORCH - freeScorchBuffers(); -#endif REF_PTR_RELEASE(m_indexBuffer); if (m_vertexBufferTiles) { for (int i=0; iRelease(); - delete[] m_xformedVertexBuffer; - m_xformedVertexBuffer = NULL; - } -#endif - REF_PTR_RELEASE(m_vertexMaterialClass); - REF_PTR_RELEASE(m_stageZeroTexture); - REF_PTR_RELEASE(m_stageOneTexture); - REF_PTR_RELEASE(m_stageTwoTexture); - REF_PTR_RELEASE(m_stageThreeTexture); - REF_PTR_RELEASE(m_destAlphaTexture); - REF_PTR_RELEASE(m_map); - return 0; } //============================================================================= -// HeightMapRenderObjClass::doTheLight +// HeightMapRenderObjClass::freeMapResources //============================================================================= -/** Calculates the diffuse lighting for a vertex in the terrain, taking all of the -static lights into account as well. It is possible to just use the normal in the -vertex and let D3D do the lighting, but it is slower to render, and can only -handle 4 lights at this point. */ +/** Frees the w3d resources used to draw the terrain. */ //============================================================================= -void HeightMapRenderObjClass::doTheLight(VERTEX_FORMAT *vb, Vector3*light, Vector3*normal, RefRenderObjListIterator *pLightsIterator, UnsignedByte alpha) +Int HeightMapRenderObjClass::freeMapResources(void) { -#ifdef USE_NORMALS - vb->nx = normal->X; - vb->ny = normal->Y; - vb->nz = normal->Z; -#else - Real shadeR, shadeG, shadeB; - Real shade; - shadeR = TheGlobalData->m_terrainAmbient[0].red; //only the first terrain light contributes to ambient - shadeG = TheGlobalData->m_terrainAmbient[0].green; - shadeB = TheGlobalData->m_terrainAmbient[0].blue; - - if (pLightsIterator) { - for (pLightsIterator->First(); !pLightsIterator->Is_Done(); pLightsIterator->Next()) - { - LightClass *pLight = (LightClass*)pLightsIterator->Peek_Obj(); - Vector3 lightDirection(vb->x, vb->y, vb->z); - Real factor = 1.0f; - switch(pLight->Get_Type()) { - case LightClass::POINT: - case LightClass::SPOT: { - Vector3 lightLoc = pLight->Get_Position(); - lightDirection -= lightLoc; - double range, midRange; - pLight->Get_Far_Attenuation_Range(midRange, range); - if (vb->x < lightLoc.X-range) continue; - if (vb->x > lightLoc.X+range) continue; - if (vb->y < lightLoc.Y-range) continue; - if (vb->y > lightLoc.Y+range) continue; - Real dist = lightDirection.Length(); - if (dist >= range) continue; - if (midRange < 0.1) continue; -#if 1 - factor = 1.0f - (dist - midRange) / (range - midRange); -#else - // f = 1.0 / (atten0 + d*atten1 + d*d/atten2); - if (fabs(range-midRange)<1e-5) { - // if the attenuation range is too small assume uniform with cutoff - factor = 1.0; - } else { - factor = 1.0f/(0.1+dist/midRange + 5.0f*dist*dist/(range*range)); - } -#endif - factor = WWMath::Clamp(factor,0.0f,1.0f); - } - break; - case LightClass::DIRECTIONAL: - lightDirection = pLight->Get_Transform().Get_Z_Vector(); - factor = 1.0; - break; - }; - lightDirection.Normalize(); - Vector3 lightRay(-lightDirection.X, -lightDirection.Y, -lightDirection.Z); - shade = Vector3::Dot_Product(lightRay, *normal); - shade *= factor; - Vector3 diffuse; - pLight->Get_Diffuse(&diffuse); - Vector3 ambient; - pLight->Get_Ambient(&ambient); - if (shade > 1.0) shade = 1.0; - if(shade < 0.0f) shade = 0.0f; - shadeR += shade*diffuse.X; - shadeG += shade*diffuse.Y; - shadeB += shade*diffuse.Z; - shadeR += factor*ambient.X; - shadeG += factor*ambient.Y; - shadeB += factor*ambient.Z; - - } - } - // Add in global diffuse value. - const RGBColor *terrainDiffuse; - for (Int lightIndex=0; lightIndex < TheGlobalData->m_numGlobalLights; lightIndex++) - { - shade = Vector3::Dot_Product(light[lightIndex], *normal); - if (shade > 1.0) shade = 1.0; - if(shade < 0.0f) shade = 0.0f; - terrainDiffuse=&TheGlobalData->m_terrainDiffuse[lightIndex]; - shadeR += shade*terrainDiffuse->red; - shadeG += shade*terrainDiffuse->green; - shadeB += shade*terrainDiffuse->blue; - } - - if (shadeR > 1.0) shadeR = 1.0; - if(shadeR < 0.0f) shadeR = 0.0f; - if (shadeG > 1.0) shadeG = 1.0; - if(shadeG < 0.0f) shadeG = 0.0f; - if (shadeB > 1.0) shadeB = 1.0; - if(shadeB < 0.0f) shadeB = 0.0f; + BaseHeightMapRenderObjClass::freeMapResources(); + freeIndexVertexBuffers(); - if (m_useDepthFade && vb->z <= TheGlobalData->m_waterPositionZ) - { //height is below water level - //reduce lighting values based on light fall off as it travels through water. - float depthScale = (1.4f - vb->z)/TheGlobalData->m_waterPositionZ; - shadeR *= 1.0f - depthScale * (1.0f-m_depthFade.X); - shadeG *= 1.0f - depthScale * (1.0f-m_depthFade.Y); - shadeB *= 1.0f - depthScale * (1.0f-m_depthFade.Z); - } - - shadeR*=255.0f; - shadeG*=255.0f; - shadeB*=255.0f; - vb->diffuse = REAL_TO_INT(shadeB) | (REAL_TO_INT(shadeG) << 8) | (REAL_TO_INT(shadeR) << 16) | ((Int)alpha << 24); -#endif + return 0; } + //============================================================================= // HeightMapRenderObjClass::doTheDynamicLight //============================================================================= @@ -448,7 +311,7 @@ Int HeightMapRenderObjClass::updateVB(DX8VertexBufferClass *pVB, char *data, Int Int vertsPerRow=(VERTEX_BUFFER_TILE_LENGTH)*4; //vertices per row of VB Int cellOffset = 1; - if (m_halfResMesh) { + if (HALF_RES_MESH) { cellOffset = 2; } @@ -469,7 +332,7 @@ Int HeightMapRenderObjClass::updateVB(DX8VertexBufferClass *pVB, char *data, Int for (j=y0; jgetDrawOrgY(); for (i=x0; igetUVData(getXWithOrigin(i),getYWithOrigin(j),U, V, m_halfResMesh); - pMap->getAlphaUVData(getXWithOrigin(i),getYWithOrigin(j), UA, VA, alpha, &flipForBlend, m_halfResMesh); + pMap->getUVData(getXWithOrigin(i),getYWithOrigin(j),U, V, HALF_RES_MESH); + pMap->getAlphaUVData(getXWithOrigin(i),getYWithOrigin(j), UA, VA, alpha, &flipForBlend, HALF_RES_MESH); } @@ -632,8 +495,8 @@ Int HeightMapRenderObjClass::updateVB(DX8VertexBufferClass *pVB, char *data, Int if (m_showImpassableAreas) { // Color impassable cells "red" DEBUG_ASSERTCRASH(PATHFIND_CELL_SIZE_F == MAP_XY_FACTOR, ("Pathfind must be terrain cell size, or this code needs reworking. John A.")); - Real borderHiX = (pMap->getXExtent()-2*pMap->getBorderSize())*MAP_XY_FACTOR; - Real borderHiY = (pMap->getYExtent()-2*pMap->getBorderSize())*MAP_XY_FACTOR; + Real borderHiX = (pMap->getXExtent()-2*pMap->getBorderSizeInline())*MAP_XY_FACTOR; + Real borderHiY = (pMap->getYExtent()-2*pMap->getBorderSizeInline())*MAP_XY_FACTOR; Bool border = pCurVertices[0].x == -MAP_XY_FACTOR || pCurVertices[0].y == -MAP_XY_FACTOR; Bool cliffMapped = pMap->isCliffMappedTexture(getXWithOrigin(i), getYWithOrigin(j)); if (pCurVertices[0].x == borderHiX) { @@ -720,10 +583,10 @@ Int HeightMapRenderObjClass::updateVBForLight(DX8VertexBufferClass *pVB, char *d for (j=y0; jgetDrawOrgY()-m_map->getBorderSize(); + Int yCoord = getYWithOrigin(j)+m_map->getDrawOrgY()-m_map->getBorderSizeInline(); Bool intersect = false; for (k=0; km_minY <= yCoord+1 && @@ -747,10 +610,10 @@ Int HeightMapRenderObjClass::updateVBForLight(DX8VertexBufferClass *pVB, char *d for (i=x0; igetDrawOrgX()-m_map->getBorderSize(); + Int xCoord = getXWithOrigin(i)+m_map->getDrawOrgX()-m_map->getBorderSizeInline(); Bool intersect = false; for (k=0; km_minX <= xCoord+1 && @@ -771,7 +634,7 @@ Int HeightMapRenderObjClass::updateVBForLight(DX8VertexBufferClass *pVB, char *d } // vb is the pointer to the vertex in the hardware dx8 vertex buffer. Int offset = (j-originY)*vertsPerRow+4*(i-originX); - if (m_halfResMesh) { + if (HALF_RES_MESH) { offset = (j-originY)*vertsPerRow/4+2*(i-originX); } vb = vBase + offset; //skip to correct row in vertex buffer @@ -876,7 +739,7 @@ Int HeightMapRenderObjClass::updateVBForLightOptimized(DX8VertexBufferClass *pVB Int quad_below_offset; Int quad_below_right_offset; - if (m_halfResMesh == false) { + if (HALF_RES_MESH == false) { // offset = (j-originY)*vertsPerRow+4*(i-originX); quad_right_offset = 4; quad_below_offset = vertsPerRow; @@ -895,10 +758,10 @@ Int HeightMapRenderObjClass::updateVBForLightOptimized(DX8VertexBufferClass *pVB // for (j=y0; jgetDrawOrgY()-m_map->getBorderSize(); + Int yCoord = getYWithOrigin(j)+m_map->getDrawOrgY()-m_map->getBorderSizeInline(); Bool intersect = false; for (k=0; km_minY <= yCoord+1 && @@ -922,10 +785,10 @@ Int HeightMapRenderObjClass::updateVBForLightOptimized(DX8VertexBufferClass *pVB for (i=x0; igetDrawOrgX()-m_map->getBorderSize(); + Int xCoord = getXWithOrigin(i)+m_map->getDrawOrgX()-m_map->getBorderSizeInline(); Bool intersect = false; for (k=0; km_minX <= xCoord+1 && @@ -946,7 +809,7 @@ Int HeightMapRenderObjClass::updateVBForLightOptimized(DX8VertexBufferClass *pVB } // vb is the pointer to the vertex in the hardware dx8 vertex buffer. Int offset = (j-originY)*vertsPerRow+4*(i-originX); - if (m_halfResMesh) { + if (HALF_RES_MESH) { offset = (j-originY)*vertsPerRow/4+2*(i-originX); } vb = vBase + offset; //skip to correct row in vertex buffer @@ -1145,7 +1008,12 @@ 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 RTS_DEBUG - DEBUG_ASSERTCRASH(x0>=0&&y0>=0 && x1=0, ("HeightMapRenderObjClass::UpdateBlock parameters extend beyond left edge.")); + DEBUG_ASSERTCRASH(y0>=0, ("HeightMapRenderObjClass::UpdateBlock parameters extend beyond bottom edge.")); + DEBUG_ASSERTCRASH(x1getDrawOrgX(); - yOffset = m_map->getDrawOrgY(); - } - - vmin.Set(x*VERTEX_BUFFER_TILE_LENGTH+xOffset,y*VERTEX_BUFFER_TILE_LENGTH+yOffset,m_minHeight); - vmax.Set((x+1)*VERTEX_BUFFER_TILE_LENGTH+xOffset,(y+1)*VERTEX_BUFFER_TILE_LENGTH+yOffset,m_maxHeight); - - aabox->Init_Min_Max(vmin,vmax); - return *aabox; -} - -#ifdef DO_SCORCH -//============================================================================= -// HeightMapRenderObjClass::drawScorches -//============================================================================= -/** Draws the scorch marks. */ -//============================================================================= -void HeightMapRenderObjClass::drawScorches(void) -{ - updateScorches(); - if (m_curNumScorchIndices == 0) { - return; - } - DX8Wrapper::Set_Index_Buffer(m_indexScorch,0); - DX8Wrapper::Set_Vertex_Buffer(m_vertexScorch); - - DX8Wrapper::Set_Texture(0,m_scorchTexture); - if (Is_Hidden() == 0) { - DX8Wrapper::Draw_Triangles( 0,m_curNumScorchIndices/3, 0, m_curNumScorchVertices); - } -} -#endif - //----------------------------------------------------------------------------- // Public Functions @@ -1248,36 +1070,8 @@ HeightMapRenderObjClass::~HeightMapRenderObjClass(void) { freeMapResources(); - delete m_treeBuffer; - m_treeBuffer = NULL; - - delete m_bibBuffer; - m_bibBuffer = NULL; - -#ifdef TEST_CUSTOM_EDGING - delete m_customEdging; - m_customEdging = NULL; -#endif - -#ifdef DO_ROADS - delete m_roadBuffer; - m_roadBuffer = NULL; -#endif - - delete m_bridgeBuffer; - m_bridgeBuffer = NULL; - - delete m_waypointBuffer; - m_waypointBuffer = NULL; - - delete m_shroud; - m_shroud = NULL; - delete [] m_extraBlendTilePositions; m_extraBlendTilePositions = NULL; - - delete [] m_shoreLineTilePositions; - m_shoreLineTilePositions = NULL; } //============================================================================= @@ -1285,91 +1079,23 @@ HeightMapRenderObjClass::~HeightMapRenderObjClass(void) //============================================================================= /** Constructor. Mostly nulls out the member variables. */ //============================================================================= -HeightMapRenderObjClass::HeightMapRenderObjClass(void) -{ - m_x=0; - m_y=0; - m_needFullUpdate = false; - m_showImpassableAreas = false; - m_originX = 0; - m_originY = 0; - m_updating = false; - //Set height to the maximum value that can be stored. - //We should refine this with actual value. - m_maxHeight=(pow(256.0, sizeof(HeightSampleType))-1.0)*MAP_HEIGHT_SCALE; - m_minHeight=0; - m_numExtraBlendTiles=0; - m_extraBlendTilePositions=NULL; - m_extraBlendTilePositionsSize=0; - m_shoreLineTilePositions=NULL; - m_numShoreLineTiles=0; - m_shoreLineTilePositionsSize=0; - m_currentMinWaterOpacity = -1.0f; - - m_numVertexBufferTiles=0; - m_indexBuffer=NULL; - m_vertexMaterialClass=NULL; -#ifdef PRE_TRANSFORM_VERTEX - m_xformedVertexBuffer = NULL; -#endif - m_stageZeroTexture=NULL; - m_stageOneTexture=NULL; - m_stageTwoTexture=NULL; - m_stageThreeTexture=NULL; - m_destAlphaTexture=NULL; - m_vertexBufferTiles=NULL; - m_vertexBufferBackup=NULL; - m_map=NULL; - m_depthFade.X = 0.0f; - m_depthFade.Y = 0.0f; - m_depthFade.Z = 0.0f; - m_useDepthFade = false; - m_disableTextures = false; - TheTerrainRenderObject = this; - - m_treeBuffer = NULL; - m_bibBuffer = NULL; -#ifdef TEST_CUSTOM_EDGING - m_customEdging = NULL; -#endif - m_bridgeBuffer = NULL; - m_waypointBuffer = NULL; -#ifdef DO_ROADS - m_roadBuffer = NULL; -#endif -#ifdef DO_SCORCH - m_vertexScorch = NULL; - m_indexScorch = NULL; - m_scorchTexture = NULL; - clearAllScorches(); - m_shroud = NULL; -#endif - m_bridgeBuffer = NEW W3DBridgeBuffer; - - if (TheGlobalData->m_headless) - return; - - m_treeBuffer = NEW W3DTreeBuffer; - - m_bibBuffer = NEW W3DBibBuffer; - - m_curImpassableSlope = 45.0f; // default to 45 degrees. - -#ifdef TEST_CUSTOM_EDGING - m_customEdging = NEW W3DCustomEdging; -#endif - m_waypointBuffer = NEW W3DWaypointBuffer; -#ifdef DO_ROADS - m_roadBuffer = NEW W3DRoadBuffer; -#endif - -#if defined(RTS_DEBUG) - if (TheGlobalData->m_shroudOn) - m_shroud = NEW W3DShroud; -#else - m_shroud = NEW W3DShroud; -#endif - DX8Wrapper::SetCleanupHook(this); +HeightMapRenderObjClass::HeightMapRenderObjClass(void): +m_extraBlendTilePositions(NULL), +m_numExtraBlendTiles(0), +m_numVisibleExtraBlendTiles(0), +m_extraBlendTilePositionsSize(0), +m_vertexBufferTiles(NULL), +m_vertexBufferBackup(NULL), +m_originX(0), +m_originY(0), +m_indexBuffer(NULL), +m_numVBTilesX(0), +m_numVBTilesY(0), +m_numVertexBufferTiles(0), +m_numBlockColumnsInLastVB(0), +m_numBlockRowsInLastVB(0) +{ + TheHeightMap = this; } @@ -1381,6 +1107,11 @@ adj < 0 decreases it one step, if adj==0, then just sets up for the current LOD //============================================================================= void HeightMapRenderObjClass::adjustTerrainLOD(Int adj) { + BaseHeightMapRenderObjClass::adjustTerrainLOD(adj); + + return; + +#if 0 if (adj>0 && TheGlobalData->m_terrainLODm_terrainLOD=(TerrainLOD)(TheGlobalData->m_terrainLOD+1); if (adj<0 && TheGlobalData->m_terrainLOD>TERRAIN_LOD_MIN) TheWritableGlobalData->m_terrainLOD=(TerrainLOD)(TheGlobalData->m_terrainLOD-1); @@ -1440,6 +1171,7 @@ void HeightMapRenderObjClass::adjustTerrainLOD(Int adj) TheTacticalView->setAngle(TheTacticalView->getAngle() + 1); TheTacticalView->setAngle(TheTacticalView->getAngle() - 1); } +#endif } //============================================================================= @@ -1449,47 +1181,7 @@ void HeightMapRenderObjClass::adjustTerrainLOD(Int adj) //============================================================================= void HeightMapRenderObjClass::ReleaseResources(void) { - if (m_treeBuffer) { - m_treeBuffer->freeTreeBuffers(); - } - if (m_bibBuffer) { - m_bibBuffer->freeBibBuffers(); - } -#ifdef TEST_CUSTOM_EDGING - if (m_customEdging) - m_customEdging ->freeEdgingBuffers(); -#endif - if (m_bridgeBuffer) { - m_bridgeBuffer->freeBridgeBuffers(); - } - - if( m_waypointBuffer ) - { - m_waypointBuffer->freeWaypointBuffers(); - } - // We need to save the map. - WorldHeightMap *pMap=NULL; - REF_PTR_SET(pMap, m_map); - freeMapResources(); - m_map = pMap; // ref_ptr_set has already incremented the ref count. - if (TheWaterRenderObj) - TheWaterRenderObj->ReleaseResources(); - if (TheTerrainTracksRenderObjClassSystem) - TheTerrainTracksRenderObjClassSystem->ReleaseResources(); - if (TheW3DShadowManager) - TheW3DShadowManager->ReleaseResources(); - if (m_shroud) - { m_shroud->reset(); - m_shroud->ReleaseResources(); - } - - //Release any resources that may be used by custom pixel/vertex shaders - W3DShaderManager::shutdown(); -#ifdef DO_ROADS - if (m_roadBuffer) { - m_roadBuffer->freeRoadBuffers(); - } -#endif + BaseHeightMapRenderObjClass::ReleaseResources(); } //============================================================================= @@ -1499,1678 +1191,199 @@ void HeightMapRenderObjClass::ReleaseResources(void) //============================================================================= void HeightMapRenderObjClass::ReAcquireResources(void) { - W3DShaderManager::init(); //reaquire resources which may be needed by custom shaders - - if (TheWaterRenderObj) - TheWaterRenderObj->ReAcquireResources(); - - if (TheTerrainTracksRenderObjClassSystem) - TheTerrainTracksRenderObjClassSystem->ReAcquireResources(); - - if (TheW3DShadowManager) - TheW3DShadowManager->ReAcquireResources(); - if (m_shroud) - m_shroud->ReAcquireResources(); - - Int x = m_x; - Int y = m_y; - - if (m_map) - { - this->initHeightData(x,y,m_map, NULL); - // Tell lights to update next time through. - m_needFullUpdate = true; - } - - if (m_treeBuffer) { - m_treeBuffer->allocateTreeBuffers(); - } - if (m_bibBuffer) { - m_bibBuffer->allocateBibBuffers(); - } -#ifdef TEST_CUSTOM_EDGING - if (m_customEdging) - m_customEdging ->allocateEdgingBuffers(); -#endif - if (m_bridgeBuffer) { - m_bridgeBuffer->allocateBridgeBuffers(); - } - - //Waypoint buffers are done dynamically. One line, one node (just rendered multiple times accessing other data). - //Internally creates it if needed. - -#ifdef DO_ROADS - if (m_roadBuffer) { - m_roadBuffer->allocateRoadBuffers(); - m_roadBuffer->loadRoads(); - } -#endif - - if (TheTacticalView) - { TheTacticalView->forceRedraw(); //force map to update itself for the current camera position. - //for some reason we need to do it twice otherwise we sometimes end up with a black map until - //the player moves. - TheTacticalView->forceRedraw(); - } + BaseHeightMapRenderObjClass::ReAcquireResources(); } //============================================================================= -// HeightMapRenderObjClass::updateMacroTexture +// HeightMapRenderObjClass::reset //============================================================================= /** Updates the macro noise/lightmap texture (pass 3) */ //============================================================================= -void HeightMapRenderObjClass::updateMacroTexture(AsciiString textureName) +void HeightMapRenderObjClass::reset(void) { - m_macroTextureName = textureName; - // Release texture. - REF_PTR_RELEASE(m_stageThreeTexture); - // Reallocate texture. - m_stageThreeTexture=NEW LightMapTerrainTextureClass(m_macroTextureName); + BaseHeightMapRenderObjClass::reset(); } //============================================================================= -// HeightMapRenderObjClass::reset +// HeightMapRenderObjClass::oversizeTerrain //============================================================================= -/** Updates the macro noise/lightmap texture (pass 3) */ +/** Sets the terrain oversize amount. */ //============================================================================= -void HeightMapRenderObjClass::reset(void) +void HeightMapRenderObjClass::oversizeTerrain(Int tilesToOversize) { - if (m_treeBuffer) { - m_treeBuffer->clearAllTrees(); - } - clearAllScorches(); -#ifdef TEST_CUSTOM_EDGING - if (m_customEdging) - m_customEdging ->clearAllEdging(); -#endif -#ifdef DO_ROADS - if (m_roadBuffer) { - m_roadBuffer->clearAllRoads(); - } -#endif - if (m_bridgeBuffer) { - m_bridgeBuffer->clearAllBridges(); + Int width = WorldHeightMap::NORMAL_DRAW_WIDTH; + Int height = WorldHeightMap::NORMAL_DRAW_HEIGHT; + if (tilesToOversize>0 && tilesToOversize<5) + { + width += 32*tilesToOversize; + height += 32*tilesToOversize; + if (width>m_map->getXExtent()) + width = m_map->getXExtent(); + if (height>m_map->getYExtent()) + height = m_map->getYExtent(); } + Int dx = width-m_map->getDrawWidth(); + Int dy = height-m_map->getDrawHeight(); + m_map->setDrawWidth(width); + m_map->setDrawHeight(height); + dx /= 2; + dy /= 2; + Int newOrgX = m_map->getDrawOrgX()-dx; + Int newOrgy = m_map->getDrawOrgY()-dy; + if (newOrgX<0) newOrgX=0; + if (newOrgy<0) newOrgy=0; + m_map->setDrawOrg(newOrgX,newOrgy); + m_originX = 0; + m_originY = 0; + if (m_shroud) + m_shroud->reset(); + //delete m_shroud; + //m_shroud = NULL; + initHeightData(m_map->getDrawWidth(), m_map->getDrawHeight(), m_map, NULL, FALSE); + m_needFullUpdate = true; +} - if (m_bibBuffer) { - m_bibBuffer->clearAllBibs(); - } - m_showAsVisibleCliff.clear(); - if (m_shroud) - { m_shroud->reset(); - m_shroud->setBorderShroudLevel((W3DShroudLevel)TheGlobalData->m_shroudAlpha); //assume border is always black at start. - } -} -/**@todo: Ray intersection needs to be optimized with some sort of grid-tracing -(ala line drawing). We should also try making the search in a front->back order -relative to the ray so we can early exit as soon as we have a hit. -* //============================================================================= -// HeightMapRenderObjClass::Cast_Ray +// HeightMapRenderObjClass::initHeightData //============================================================================= -/** Return intersection of a ray with the heightmap mesh. -This is a quick version that just checks every polygon inside -a 2D bounding rectangle of the ray projected onto the heightfield plane. -For most of our view-picking cases the ray in almost perpendicular to the -map plane so this is very quick (small bounding box). But it can become slow -for arbitrary rays such as those used in AI visbility checks.(2 units on -opposite corners of the map would check every polygon in the map). -*/ +/** Allocate a heightmap of x by y vertices and fill with initial height values. +Also allocates all rendering resources such as vertex buffers, index buffers, +shaders, and materials.*/ //============================================================================= -bool HeightMapRenderObjClass::Cast_Ray(RayCollisionTestClass & raytest) +Int HeightMapRenderObjClass::initHeightData(Int x, Int y, WorldHeightMap *pMap, RefRenderObjListIterator *pLightsIterator, Bool updateExtraPassTiles) { - TriClass tri; - Bool hit = false; - Int X,Y; - Vector3 normal,P0,P1,P2,P3; - - if (!m_map) - return false; //need valid pointer to heightmap samples -//HeightSampleType *pData = m_map->getDataPtr(); - //Clip ray to extents of heightfield - AABoxClass hbox; - LineSegClass lineseg,lineseg2; - CastResultStruct result; - Int StartCellX = 0; - Int EndCellX = 0; - Int StartCellY = 0; - Int EndCellY = 0; - const Int overhang = 2*VERTEX_BUFFER_TILE_LENGTH+m_map->getBorderSize(); // Allow picking past the edge for scrolling & objects. - Vector3 minPt(MAP_XY_FACTOR*(-overhang), MAP_XY_FACTOR*(-overhang), -MAP_XY_FACTOR); - Vector3 maxPt(MAP_XY_FACTOR*(m_map->getXExtent()+overhang), - MAP_XY_FACTOR*(m_map->getYExtent()+overhang), MAP_HEIGHT_SCALE*m_map->getMaxHeightValue()+MAP_XY_FACTOR); - MinMaxAABoxClass mmbox(minPt, maxPt); - hbox.Init(mmbox); - - lineseg=raytest.Ray; - - //Set initial ray endpoints - P0 = raytest.Ray.Get_P0(); - P1 = raytest.Ray.Get_P1(); - result.ComputeContactPoint=true; - - Int p; - for (p=0; p<3; p++) { - //find intersection point of ray and terrain bounding box - result.Reset(); - result.ComputeContactPoint=true; - if (CollisionMath::Collide(lineseg,hbox,&result)) - { //ray intersects terrain or starts inside the terrain. - if (!result.StartBad) //check if start point inside terrain - P0 = result.ContactPoint; //make intersection point the new start of the ray. - - //reverse direction of original ray and clip again to extent of - //heightmap - result.Fraction=1.0f; //reset the result - result.StartBad=false; - lineseg2.Set(lineseg.Get_P1(),lineseg.Get_P0()); //reverse line segment - if (CollisionMath::Collide(lineseg2,hbox,&result)) - { if (!result.StartBad) //check if end point inside terrain - P1 = result.ContactPoint; //make intersection point the new end pont of ray - } - } else { - if (p==0) return(false); - break; - } - - // Take the 2D bounding box of ray and check heights - // inside this box for intersection. - if (P0.X > P1.X) { //flip start/end points - StartCellX = REAL_TO_INT_FLOOR(P1.X/MAP_XY_FACTOR); - EndCellX = REAL_TO_INT_CEIL(P0.X/MAP_XY_FACTOR); - } else { - StartCellX = REAL_TO_INT_FLOOR(P0.X/MAP_XY_FACTOR); - EndCellX = REAL_TO_INT_CEIL(P1.X/MAP_XY_FACTOR); - } - if (P0.Y > P1.Y) { //flip start/end points - StartCellY = REAL_TO_INT_FLOOR(P1.Y/MAP_XY_FACTOR); - EndCellY = REAL_TO_INT_CEIL(P0.Y/MAP_XY_FACTOR); - } else { - StartCellY = REAL_TO_INT_FLOOR(P0.Y/MAP_XY_FACTOR); - EndCellY = REAL_TO_INT_CEIL(P1.Y/MAP_XY_FACTOR); - } - - Int i, j, minHt, maxHt; + BaseHeightMapRenderObjClass::initHeightData(x, y, pMap, pLightsIterator, updateExtraPassTiles); + Int i,j; +// Int vertsPerRow=x*2-2; +// Int vertsPerColumn=y*2-2; - minHt = m_map->getMaxHeightValue(); - maxHt = 0; + HeightSampleType *data = NULL; + if (pMap) { + data = pMap->getDataPtr(); + } - for (j=StartCellY; j<=EndCellY; j++) { - for (i=StartCellX; i<=EndCellX; i++) { - Short cur = getClipHeight(i+m_map->getBorderSize(),j+m_map->getBorderSize()); - if (curgetXExtent(); + Int m_mapDY=pMap->getYExtent(); + if (!m_extraBlendTilePositions) + { //Need to allocate memory + m_extraBlendTilePositions = NEW Int[DEFAULT_MAX_MAP_EXTRABLEND_TILES]; + m_extraBlendTilePositionsSize = DEFAULT_MAX_MAP_EXTRABLEND_TILES; } + + //Find list of all extra blend tiles used on map. These are tiles with 3 materials/textures + //over the same tile and require an extra render pass. + for (j=0; j<(m_mapDY-1); j++) + for (i=0; i<(m_mapDX-1); i++) + { + Real U[4],V[4]; + UnsignedByte alpha[4]; + Bool flipState,cliffState; + if (pMap->getExtraAlphaUVData(i,j,U,V,alpha,&flipState, &cliffState)) + { if (m_numExtraBlendTiles >= m_extraBlendTilePositionsSize) + { //no more room to store extra blend tiles so enlarge the buffer. + Int *tempPositions=NEW Int[m_extraBlendTilePositionsSize+512]; + memcpy(tempPositions, m_extraBlendTilePositions, m_extraBlendTilePositionsSize*sizeof(Int)); + delete [] m_extraBlendTilePositions; + //enlarge by more tiles to reduce memory trashing + m_extraBlendTilePositions = tempPositions; + m_extraBlendTilePositionsSize += 512; + } + //Pack x and y position into single integer since maps are limited in size + m_extraBlendTilePositions[m_numExtraBlendTiles]=i | (j <<16); + m_numExtraBlendTiles++; + } + } } - Vector3 minPt(MAP_XY_FACTOR*(StartCellX-1), MAP_XY_FACTOR*(StartCellY-1), MAP_HEIGHT_SCALE*(minHt-1)); - Vector3 maxPt(MAP_XY_FACTOR*(EndCellX+1), MAP_XY_FACTOR*(EndCellY+1), MAP_HEIGHT_SCALE*(maxHt+1)); - MinMaxAABoxClass mmbox(minPt, maxPt); - hbox.Init(mmbox); } - raytest.Result->ComputeContactPoint=true; //tell CollisionMath that we need point. - - // Adjust indexes into the bordered height map. - - StartCellX += m_map->getBorderSize(); - EndCellX += m_map->getBorderSize(); - StartCellY += m_map->getBorderSize(); - EndCellY += m_map->getBorderSize(); - - Int offset; - for (offset = 1; offset < 5; offset *= 3) { - for (Y=StartCellY-offset; Y<=EndCellY+offset; Y++) { - //if (Y<0) continue; - //if (Y>=m_map->getYExtent()-1) continue; - - for (X=StartCellX-offset; X<=EndCellX+offset; X++) { - //test the 2 triangles in this cell - // 3-----2 - // | /| - // | / | - // |/ | - // 0-----1 - - //bottom triangle first - P0.X=ADJUST_FROM_INDEX_TO_REAL(X); - P0.Y=ADJUST_FROM_INDEX_TO_REAL(Y); - P0.Z=MAP_HEIGHT_SCALE*(float)getClipHeight(X, Y); - - P1.X=ADJUST_FROM_INDEX_TO_REAL(X+1); - P1.Y=ADJUST_FROM_INDEX_TO_REAL(Y); - P1.Z=MAP_HEIGHT_SCALE*(float)getClipHeight(X+1, Y); - - P2.X=ADJUST_FROM_INDEX_TO_REAL(X+1); - P2.Y=ADJUST_FROM_INDEX_TO_REAL(Y+1); - P2.Z=MAP_HEIGHT_SCALE*(float)getClipHeight(X+1, Y+1); + m_originX = 0; + m_originY = 0; + m_needFullUpdate = true; - P3.X=ADJUST_FROM_INDEX_TO_REAL(X); - P3.Y=ADJUST_FROM_INDEX_TO_REAL(Y+1); - P3.Z=MAP_HEIGHT_SCALE*(float)getClipHeight(X, Y+1); + // If the size changed, we need to allocate. + Bool needToAllocate = (x != m_x || y != m_y); + // If the textures aren't allocated (usually because of a hardware reset) need to allocate. + if (m_stageOneTexture == NULL) { + needToAllocate = true; + } + if (data && needToAllocate && m_treeBuffer != NULL) + { //requested heightmap different from old one. + freeIndexVertexBuffers(); + //Create static index buffers. These will index the vertex buffers holding the map. + m_indexBuffer=NEW_REF(DX8IndexBufferClass,(VERTEX_BUFFER_TILE_LENGTH*VERTEX_BUFFER_TILE_LENGTH*2*3)); + // Fill up the IB + DX8IndexBufferClass::WriteLockClass lockIdxBuffer(m_indexBuffer); + UnsignedShort *ib=lockIdxBuffer.Get_Index_Array(); - tri.V[0] = &P0; - tri.V[1] = &P1; - tri.V[2] = &P2; + for (j=0; j<(VERTEX_BUFFER_TILE_LENGTH*VERTEX_BUFFER_TILE_LENGTH*4); j+=VERTEX_BUFFER_TILE_LENGTH*4) + { + for (i=j; i<(j+VERTEX_BUFFER_TILE_LENGTH*4); i+=4) //4 vertices per 2x2 block + { + ib[0]=i; + ib[1]=i+2; + ib[2]=i+3; - tri.N = &normal; + ib[3]=i; + ib[4]=i+1; + ib[5]=i+2; - tri.Compute_Normal(); + ib+=6; //skip the 6 indices we just filled + } + } - hit = hit || (Bool)CollisionMath::Collide(raytest.Ray, tri, raytest.Result); - - if (raytest.Result->StartBad) - return true; - - //top triangle - tri.V[0] = &P2; - tri.V[1] = &P3; - tri.V[2] = &P0; - - tri.N = &normal; - - tri.Compute_Normal(); - - hit = hit || (Bool)CollisionMath::Collide(raytest.Ray, tri, raytest.Result); - - if (hit) - raytest.Result->SurfaceType = SURFACE_TYPE_DEFAULT; ///@todo: WW3D uses this to return dirt, grass, etc. Do we need this? - } - // Don't break. It is possible to intersect 2 triangles, and the second is closer. if (hit) break; - } - // Don't break. It is possible to intersect 2 triangles, and the second is closer. if (hit) break; - } - return hit; -} - -//============================================================================= -// HeightMapRenderObjClass::getHeightMapHeight -//============================================================================= -/** return the height and normal of the triangle plane containing given location within heightmap. */ -//============================================================================= -Real HeightMapRenderObjClass::getHeightMapHeight(Real x, Real y, Coord3D* normal) const -{ - if (m_map == NULL) - { - if (normal) - { - // return a default normal pointing up - normal->x = 0.0f; - normal->y = 0.0f; - normal->z = 1.0f; - } - return 0; - } - - float height; - - // 3-----2 - // | /| - // | / | - // |/ | - // 0-----1 - //Find surrounding grid points - - const Real MAP_XY_FACTOR_INV = 1.0f / MAP_XY_FACTOR; - - float xdiv = x * MAP_XY_FACTOR_INV; - float ydiv = y * MAP_XY_FACTOR_INV; - - float ixf = floorf(xdiv); - float iyf = floorf(ydiv); - - float fx = xdiv - ixf; //get fraction - float fy = ydiv - iyf; //get fraction - - // since ixf & iyf are already floor'ed, we can use the fastest f->i conversion we have... - Int ix = REAL_TO_INT_FLOOR(ixf) + m_map->getBorderSize(); - Int iy = REAL_TO_INT_FLOOR(iyf) + m_map->getBorderSize(); - Int xExtent = m_map->getXExtent(); - - // Check for extent-3, not extent-1: we go into the next row/column of data for smoothed triangle points, so extent-1 - // goes off the end... - if (ix > (xExtent-3) || iy > (m_map->getYExtent()-3) || iy < 1 || ix < 1) - { - // sample point is not on the heightmap - if (normal) - { - // return a default normal pointing up - normal->x = 0.0f; - normal->y = 0.0f; - normal->z = 1.0f; - } - return getClipHeight(ix, iy) * MAP_HEIGHT_SCALE; - } - - const UnsignedByte* data = m_map->getDataPtr(); - int idx = ix + iy*xExtent; - float p0 = data[idx]; - float p2 = data[idx + xExtent + 1]; - if (fy > fx) // test if we are in the upper triangle - { - float p3 = data[idx + xExtent]; - height = (p3 + (1.0f-fy)*(p0-p3) + fx*(p2-p3)) * MAP_HEIGHT_SCALE; - } - else - { - // we are in the lower triangle - float p1 = data[idx + 1]; - height = (p1 + fy*(p2-p1) + (1.0f-fx)*(p0-p1)) * MAP_HEIGHT_SCALE; - } - if (normal) { - // 9 8 - // - //10 3-----2 7 - // | /| - // | / | - // |/ | - //11 0-----1 6 - // - // 4 5 - //Find surrounding grid points for smoothed normals. - int idx4 = ix + (iy-1)*xExtent; - int idx0 = ix + iy*xExtent; - int idx3 = ix + iy*xExtent+xExtent; - int idx9 = ix + (iy+2)*xExtent; - UnsignedByte d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11; - d0 = data[idx0]; - d1 = data[idx0+1]; - d2 = data[idx3+1]; - d3 = data[idx3]; - d4 = data[idx4]; - d5 = data[idx4+1]; - d6 = data[idx0+2]; - d7 = data[idx3+2]; - d8 = data[idx9+1]; - d9 = data[idx9]; - d10 = data[idx3-1]; - d11 = data[idx0-1]; - - Real deltaZ_X0 = d1-d11; - Real deltaZ_X1 = d6-d0; - Real deltaZ_X2 = d7-d3; - Real deltaZ_X3 = d6-d0; - - Real deltaZ_Y0 = d3-d4; - Real deltaZ_Y1 = d2-d5; - Real deltaZ_Y2 = d8-d1; - Real deltaZ_Y3 = d9-d0; - - // Interpolate to get the smoothed valued. - Real deltaZ_X_Left = deltaZ_X0*(1.0f-fx) + fx*deltaZ_X3; - Real deltaZ_X_Right = deltaZ_X1*(1.0f-fx) + fx*deltaZ_X2; - Real deltaZ_X = deltaZ_X_Left*(1.0-fy) + fy*deltaZ_X_Right; - - Real deltaZ_Y_Left = deltaZ_Y0*(1.0f-fx) + fx*deltaZ_Y3; - Real deltaZ_Y_Right = deltaZ_Y1*(1.0f-fx) + fx*deltaZ_Y2; - Real deltaZ_Y = deltaZ_Y_Left*(1.0-fy) + fy*deltaZ_Y_Right; - - - - Vector3 l2r, n2f, normalAtTexel; - l2r.Set(2*MAP_XY_FACTOR/MAP_HEIGHT_SCALE, 0, deltaZ_X); - n2f.Set(0, 2*MAP_XY_FACTOR/MAP_HEIGHT_SCALE, deltaZ_Y); - Vector3::Normalized_Cross_Product(l2r,n2f, &normalAtTexel); - normal->x = normalAtTexel.X; - normal->y = normalAtTexel.Y; - normal->z = normalAtTexel.Z; - - } - - - return height; -} - -//============================================================================= -Bool HeightMapRenderObjClass::isClearLineOfSight(const Coord3D& pos, const Coord3D& posOther) const -{ - if (m_map == NULL) - return false; // doh. should not happen. - -#define DO_BRESENHAM -#ifdef DO_BRESENHAM - - /* - this is WAY faster, though not quite as accurate... however, the inaccuracy - is pretty minimal, so we really should force other code to live with it. (srj) - */ - const Real MAP_XY_FACTOR_INV = 1.0f / MAP_XY_FACTOR; - - Int borderSize = m_map->getBorderSize(); - Int start_x = REAL_TO_INT_FLOOR(pos.x * MAP_XY_FACTOR_INV) + borderSize; - Int start_y = REAL_TO_INT_FLOOR(pos.y * MAP_XY_FACTOR_INV) + borderSize; - Int end_x = REAL_TO_INT_FLOOR(posOther.x * MAP_XY_FACTOR_INV) + borderSize; - Int end_y = REAL_TO_INT_FLOOR(posOther.y * MAP_XY_FACTOR_INV) + borderSize; - Int delta_x = abs(end_x - start_x); // The difference between the x's - Int delta_y = abs(end_y - start_y); // The difference between the y's - Int x = start_x; // Start x off at the first pixel - Int y = start_y; // Start y off at the first pixel - - Int xinc1, xinc2; - if (end_x >= start_x) // The x-values are increasing - { - xinc1 = 1; - xinc2 = 1; - } - else // The x-values are decreasing - { - xinc1 = -1; - xinc2 = -1; - } - - Int yinc1, yinc2; - if (end_y >= start_y) // The y-values are increasing - { - yinc1 = 1; - yinc2 = 1; - } - else // The y-values are decreasing - { - yinc1 = -1; - yinc2 = -1; - } - - Int den, num, numadd, numpixels; - - Bool checkY = true; - if (delta_x >= delta_y) // There is at least one x-value for every y-value - { - xinc1 = 0; // Don't change the x when numerator >= denominator - yinc2 = 0; // Don't change the y for every iteration - den = delta_x; - num = delta_x / 2; - numadd = delta_y; - numpixels = delta_x; // There are more x-values than y-values - } - else // There is at least one y-value for every x-value - { - checkY = false; - xinc2 = 0; // Don't change the x for every iteration - yinc1 = 0; // Don't change the y when numerator >= denominator - den = delta_y; - num = delta_y / 2; - numadd = delta_x; - numpixels = delta_y; // There are more y-values than x-values - } - - Real nsInv = 1.0f / numpixels; - Real z = pos.z; - Real dz = posOther.z - z; - Real zinc = dz * nsInv; - - Bool result = true; - const UnsignedByte* data = m_map->getDataPtr(); - Int xExtent = m_map->getXExtent(); - Int yExtent = m_map->getYExtent(); - for (Int curpixel = 0; curpixel < numpixels; curpixel++) - { - if (x < 0 || - y < 0 || - x >= xExtent-1 || - y >= yExtent-1) - { - // once we go off the map, we're done - break; - } - - Int idx = x + y*xExtent; - float height = data[idx]; - height = __max(height, data[idx + 1]); - height = __max(height, data[idx + xExtent]); - height = __max(height, data[idx + xExtent + 1]); - height *= MAP_HEIGHT_SCALE; - - // if terrainHeight > z, we can't see, so punt. - // add a little fudge to account for slop. - const Real LOS_FUDGE = 0.5f; - if (height > z + LOS_FUDGE) - { - result = false; - break; - } - - // we're above the max height of the terrain and still looking up, so we're done. - // (don't bother for reverse test, since that doesn't generally happen) - if (z >= getMaxHeight() && zinc > 0.0f) - { - break; - } - - z += zinc; - - // continue with the maintenance. - num += numadd; // Increase the numerator by the top of the fraction - if (num >= den) // Check if numerator >= denominator - { - num -= den; // Calculate the new numerator value - x += xinc1; // Change the x as appropriate - y += yinc1; // Change the y as appropriate - } - x += xinc2; // Change the x as appropriate - y += yinc2; // Change the y as appropriate - } - - return result; - -#else - - // walk a line from obj to objOther and - // find the highest point in between 'em. while - // we're doing this, also estimate the point on the - // line at the same x,y as the high-terrain-point. - - Real fx = pos.x; - Real fy = pos.y; - Real fz = pos.z; - Real fdx = posOther.x - fx; - Real fdy = posOther.y - fy; - Real fdz = posOther.z - fz; - - // What's the largest step size that will be accurate enough? - // Currently we use a step size of about 2 "feet", which - // seems acceptable accuracy. If performance here is inadequate, - // we can try increasing the step size, but be sure to retest - // accuracy. - Real len = ceilf(sqrtf(fdx*fdx + fdy*fdy)); - const Real STEP_LEN = 2.0f; - Int numSteps = REAL_TO_INT_CEIL(len / STEP_LEN); - if (numSteps < 1) numSteps = 1; - Real fnsInv = 1.0f / numSteps; - Real fxinc = fdx * fnsInv; - Real fyinc = fdy * fnsInv; - Real fzinc = fdz * fnsInv; - while (numSteps--) - { - Real terrainHeight = getHeightMapHeight( fx, fy, NULL ); - - // if terrainHeight > fz, we can't see, so punt. - // add a little fudge to account for slop. - const Real LOS_FUDGE = 0.5f; - if (terrainHeight > fz + LOS_FUDGE) - { - return false; - } - - // we're above the max height of the terrain and still looking up, so we're done. - // (don't bother for reverse test, since that doesn't generally happen) - if (fz >= getMaxHeight() && fzinc > 0.0f) - { - return true; - } - - fx += fxinc; - fy += fyinc; - fz += fzinc; - - } - - return true; -#endif -} - -//============================================================================= -// HeightMapRenderObjClass::getMaxCellHeight -//============================================================================= -/** Returns maximum height of the 4 corners containing the given point */ -//============================================================================= -Real HeightMapRenderObjClass::getMaxCellHeight(Real x, Real y) const -{ - float p0,p1,p2,p3; - float height; - - // 3-----2 - // | /| - // | / | - // |/ | - // 0-----1 - //Find surrounding grid points - - if (m_map == NULL) - { //sample point is not on the heightmap - return 0.0f; //return default height - } - Int offset = 1; - Int iX = x/MAP_XY_FACTOR; - Int iY = y/MAP_XY_FACTOR; - iX += m_map->getBorderSize(); - iY += m_map->getBorderSize(); - if (iX<0) iX = 0; - if (iY<0) iY = 0; - if (iX >= (m_map->getXExtent()-1)) { - iX = m_map->getXExtent()-2; - } - if (iY >= (m_map->getYExtent()-1)) { - iY = m_map->getYExtent()-2; - } - if (m_halfResMesh) { - offset = 2; - iX = (iX/2)*2; - iY = (iY/2)*2; - } - UnsignedByte *data = m_map->getDataPtr(); - p0=data[iX+iY*m_map->getXExtent()]*MAP_HEIGHT_SCALE; - p1=data[(iX+offset)+iY*m_map->getXExtent()]*MAP_HEIGHT_SCALE; - p2=data[(iX+offset)+(iY+offset)*m_map->getXExtent()]*MAP_HEIGHT_SCALE; - p3=data[iX+(iY+offset)*m_map->getXExtent()]*MAP_HEIGHT_SCALE; - - height=p0; - height=__max(height,p1); - height=__max(height,p2); - height=__max(height,p3); - - return height; -} - -//============================================================================= -// HeightMapRenderObjClass::isCliffCell -//============================================================================= -/** Returns true if the cell containing the point is a cliff cell */ -//============================================================================= -Bool HeightMapRenderObjClass::isCliffCell(Real x, Real y) -{ - - if (m_map == NULL) - { //sample point is not on the heightmap - return false; - } - Int iX = x/MAP_XY_FACTOR; - Int iY = y/MAP_XY_FACTOR; - iX += m_map->getBorderSize(); - iY += m_map->getBorderSize(); - if (iX<0) iX = 0; - if (iY<0) iY = 0; - if (iX >= (m_map->getXExtent()-1)) { - iX = m_map->getXExtent()-2; - } - if (iY >= (m_map->getYExtent()-1)) { - iY = m_map->getYExtent()-2; - } - return m_map->getCliffState(iX, iY); -} - -//============================================================================= -//============================================================================= -Bool HeightMapRenderObjClass::showAsVisibleCliff(Int xIndex, Int yIndex) const -{ - Int xSize = m_map->getXExtent(); - - return m_showAsVisibleCliff[xIndex + yIndex * xSize]; -} - -//============================================================================= -//============================================================================= -Bool HeightMapRenderObjClass::evaluateAsVisibleCliff(Int xIndex, Int yIndex, Real valuesGreaterThanRad) -{ - // This one never changes, so don't bother recomputing it. - static const Real distance[4] = - { - 0.0f, - 1.0 * MAP_XY_FACTOR, - sqrt(2.0f) * MAP_XY_FACTOR, - 1.0 * MAP_XY_FACTOR, - }; - - // Note: getHeight will protect us from going out of bounds by returning 0 if we give it - // a value outside of its bounds. - UnsignedByte bytes[4] = - { - m_map->getHeight(xIndex + 0, yIndex + 0), - m_map->getHeight(xIndex + 1, yIndex + 0), - m_map->getHeight(xIndex + 1, yIndex + 1), - m_map->getHeight(xIndex + 0, yIndex + 1), - }; - - Real heights[4] = - { - INT_TO_REAL(bytes[0]) * MAP_HEIGHT_SCALE, - INT_TO_REAL(bytes[1]) * MAP_HEIGHT_SCALE, - INT_TO_REAL(bytes[2]) * MAP_HEIGHT_SCALE, - INT_TO_REAL(bytes[3]) * MAP_HEIGHT_SCALE, - }; - - Bool anyImpassable = FALSE; - - for (Int i = 1; i < 4 && !anyImpassable; ++i) { - if (fabs((heights[i] - heights[0]) / distance[i]) > valuesGreaterThanRad) { - anyImpassable = TRUE; - } - } - - return anyImpassable; -} - -//============================================================================= -// HeightMapRenderObjClass::oversizeTerrain -//============================================================================= -/** Sets the terrain oversize amount. */ -//============================================================================= -void HeightMapRenderObjClass::oversizeTerrain(Int tilesToOversize) -{ - Int width = WorldHeightMap::NORMAL_DRAW_WIDTH; - Int height = WorldHeightMap::NORMAL_DRAW_HEIGHT; - if (tilesToOversize>0 && tilesToOversize<5) - { - width += 32*tilesToOversize; - height += 32*tilesToOversize; - if (width>m_map->getXExtent()) - width = m_map->getXExtent(); - if (height>m_map->getYExtent()) - height = m_map->getYExtent(); - } - Int dx = width-m_map->getDrawWidth(); - Int dy = height-m_map->getDrawHeight(); - m_map->setDrawWidth(width); - m_map->setDrawHeight(height); - dx /= 2; - dy /= 2; - Int newOrgX = m_map->getDrawOrgX()-dx; - Int newOrgy = m_map->getDrawOrgY()-dy; - if (newOrgX<0) newOrgX=0; - if (newOrgy<0) newOrgy=0; - m_map->setDrawOrg(newOrgX,newOrgy); - m_originX = 0; - m_originY = 0; - if (m_shroud) - m_shroud->reset(); - //delete m_shroud; - //m_shroud = NULL; - initHeightData(m_map->getDrawWidth(), m_map->getDrawHeight(), m_map, NULL); - m_needFullUpdate = true; -} - - - -//============================================================================= -// HeightMapRenderObjClass::Get_Obj_Space_Bounding_Sphere -//============================================================================= -/** WW3D method that returns object bounding sphere used in frustum culling*/ -//============================================================================= -void HeightMapRenderObjClass::Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const -{ - Vector3 ObjSpaceCenter((float)m_x*0.5f*MAP_XY_FACTOR,(float)m_y*0.5f*MAP_XY_FACTOR,(float)m_minHeight+(m_maxHeight-m_minHeight)*0.5f); - float length = ObjSpaceCenter.Length(); - - if (m_map) { - ObjSpaceCenter.X += m_map->getDrawOrgX()*MAP_XY_FACTOR; - ObjSpaceCenter.Y += m_map->getDrawOrgY()*MAP_XY_FACTOR; - } - sphere.Init(ObjSpaceCenter, length); -} - -//============================================================================= -// HeightMapRenderObjClass::Get_Obj_Space_Bounding_Box -//============================================================================= -/** WW3D method that returns object bounding box used in collision detection*/ -//============================================================================= -void HeightMapRenderObjClass::Get_Obj_Space_Bounding_Box(AABoxClass & box) const -{ - Vector3 minPt(0,0,m_minHeight); - Vector3 maxPt((float)m_x*MAP_XY_FACTOR,(float)m_y*MAP_XY_FACTOR,(float)m_maxHeight); - if (m_map) { - minPt.X += m_map->getDrawOrgX()*MAP_XY_FACTOR; - minPt.Y += m_map->getDrawOrgY()*MAP_XY_FACTOR; - maxPt.X += m_map->getDrawOrgX()*MAP_XY_FACTOR; - maxPt.Y += m_map->getDrawOrgY()*MAP_XY_FACTOR; - } - MinMaxAABoxClass minMaxBox(minPt, maxPt); - - box.Init(minMaxBox); -} - -//------------------------------------------------------------------------------------------------- -/** Get the 3D extent of the terrain visible through the camera. Return value - is false if no part of terrain is visible. This function returns a worse - case bounding volume based on lowest/highest points in entire terrain. It - does not optimize the volume to heights actually visible. Unlike some of - the other methods, this function is guaranteed not to miss any visible - polygons. The ignoreMaxHeight flag is used to return a box that uses the - camera position as the maximum height instead of the terrain - good for getting - a volume enclosing things that can float above terrain. - */ -//------------------------------------------------------------------------------------------------- -Bool HeightMapRenderObjClass::getMaximumVisibleBox(const FrustumClass &frustum, AABoxClass *box, Bool ignoreMaxHeight) -{ - //create a plane from the lowest point on the terrain - PlaneClass groundPlane(Vector3(0,0,1), m_minHeight); - - //clip each side of the view frustum to ground plane - float clipFraction; - Vector3 ClippedCorners[8]; - ClippedCorners[0]=frustum.Corners[0]; - for (Int i=0; i<4; i++) - { ClippedCorners[i]=frustum.Corners[i]; - if (groundPlane.Compute_Intersection(frustum.Corners[i],frustum.Corners[i+4],&clipFraction)) - { //edge intersects the terrain - ClippedCorners[i+4]=frustum.Corners[i]+(frustum.Corners[i+4]-frustum.Corners[i])*clipFraction; - } - else - ClippedCorners[i+4]=frustum.Corners[i+4]; - } - - if (box) - box->Init(ClippedCorners,8); - - return TRUE; -} - -//============================================================================= -// HeightMapRenderObjClass::Class_ID -//============================================================================= -/** returns the class id, so the scene can tell what kind of render object it has. */ -//============================================================================= -Int HeightMapRenderObjClass::Class_ID(void) const -{ - return RenderObjClass::CLASSID_TILEMAP; -} - -//============================================================================= -// HeightMapRenderObjClass::Clone -//============================================================================= -/** Not used, but required virtual method. */ -//============================================================================= -RenderObjClass * HeightMapRenderObjClass::Clone(void) const -{ - assert(false); - return NULL; -} - -//============================================================================= -// HeightMapRenderObjClass::loadRoadsAndBridges -//============================================================================= -/** Loads the roads from the map objects. */ -//============================================================================= -void HeightMapRenderObjClass::loadRoadsAndBridges(W3DTerrainLogic *pTerrainLogic, Bool saveGame) -{ - if (DX8Wrapper::_Get_D3D_Device8() && (DX8Wrapper::_Get_D3D_Device8()->TestCooperativeLevel()) != D3D_OK) - return; //device not ready to render anything - -#ifdef DO_ROADS - if (m_roadBuffer) { - m_roadBuffer->loadRoads(); - } -#endif - if (m_bridgeBuffer) { - m_bridgeBuffer->loadBridges(pTerrainLogic, saveGame); - } -} - -// ============================================================================ -// HeightMapRenderObjClass::worldBuilderUpdateBridgeTowers -// ============================================================================ -/** The worldbuilder has it's own method here to update the visual representation - * of the bridge towers */ -// ============================================================================ -void HeightMapRenderObjClass::worldBuilderUpdateBridgeTowers( W3DAssetManager *assetManager, - SimpleSceneClass *scene ) -{ - - if( m_bridgeBuffer ) - m_bridgeBuffer->worldBuilderUpdateBridgeTowers( assetManager, scene ); - -} - -void HeightMapRenderObjClass::setShoreLineDetail(void) -{ - if (!m_map) - return; - - Int m_mapDX=m_map->getXExtent(); - Int m_mapDY=m_map->getYExtent(); - - //Find all shoreline tiles so they can get extra alpha blend - updateShorelineTiles(0,0,m_mapDX-1,m_mapDY-1,m_map); -} - -/**Scan through our map and record all tiles which cross a water plane and are within visible depth under -water.*/ -void HeightMapRenderObjClass::updateShorelineTiles(Int minX, Int minY, Int maxX, Int maxY, WorldHeightMap *pMap) -{ - Int border = pMap->getBorderSize(); - - //Clamp region to valid terrain tiles - if (minX<0) - minX = 0; - if (minY<0) - minY = 0; - if (maxX > (pMap->getXExtent() - 1)) - maxX = (pMap->getXExtent() - 1); - if (maxY > (pMap->getYExtent() - 1)) - maxY = (pMap->getYExtent() - 1); - - if (!m_shoreLineTilePositions) - { //Need to allocate memory - m_shoreLineTilePositions = NEW shoreLineTileInfo[DEFAULT_MAX_MAP_SHORELINE_TILES]; - m_shoreLineTilePositionsSize = DEFAULT_MAX_MAP_SHORELINE_TILES; - } - - //Find list of all extra blend tiles used on map. These are tiles with 3 materials/textures - //over the same tile and require an extra render pass. - - //First remove any existing extra blend tiles within this partial region - Int j=0; - for (; j> 16; - if (x >= minX && x < maxX && - y >= minY && y < maxY) - { //this tile is inside region being updated so remove it by shifting tile array - memcpy(m_shoreLineTilePositions+j,m_shoreLineTilePositions+j+1,(m_numShoreLineTiles-1-j)*sizeof(shoreLineTileInfo)); - m_numShoreLineTiles--; - j--; //look at current tile again since it was removed. - } - } - - if (TheWaterTransparency->m_transparentWaterDepth == 0 || !TheGlobalData->m_showSoftWaterEdge) - return; - - Int waterSide; - Real waterZ0,waterZ1,waterZ2,waterZ3; - Real terrainZ0, terrainZ1, terrainZ2, terrainZ3; - //Figure out maximum depth of water before we reach the m_minWaterOpacity value. Depths greater than this don't need - //custom shoreline tiles because they will get their opacity from the default value stored in the frame buffer during - //a screen clear operation. - Real transparentDepth=TheWaterTransparency->m_transparentWaterDepth*TheWaterTransparency->m_minWaterOpacity; - Real depthScaleFactor = 1.0f/transparentDepth; - - for (j=minY; jgetWaterHeight((i-border)*MAP_XY_FACTOR,(j-border)*MAP_XY_FACTOR)) > ((terrainZ0=MAP_HEIGHT_SCALE*pMap->getHeight(i,j))); - waterSide |=((waterZ1=TheWaterRenderObj->getWaterHeight((i-border+1)*MAP_XY_FACTOR,(j-border)*MAP_XY_FACTOR)) > ((terrainZ1=MAP_HEIGHT_SCALE*pMap->getHeight(i+1,j)))) << 1; - waterSide |=((waterZ2=TheWaterRenderObj->getWaterHeight((i-border+1)*MAP_XY_FACTOR,(j-border+1)*MAP_XY_FACTOR)) > ((terrainZ2=MAP_HEIGHT_SCALE*pMap->getHeight(i+1,j+1)))) << 2; - waterSide |=((waterZ3=TheWaterRenderObj->getWaterHeight((i-border)*MAP_XY_FACTOR,(j-border+1)*MAP_XY_FACTOR)) > ((terrainZ3=MAP_HEIGHT_SCALE*pMap->getHeight(i,j+1)))) << 3; - - if (!waterSide || (waterZ0*waterZ1*waterZ2*waterZ3) <= 0) - continue; //all verts are on positive (surface) side of water so don't need blending. Or one of them is outside the water plane bounds (waterHeight <= 0!) - - //Check if mix of under/over water vertices or some vertices within depth fade region. - if (waterSide < 0xf || (waterZ0 - terrainZ0) < transparentDepth || - (waterZ1 - terrainZ1) < transparentDepth || (waterZ2 - terrainZ2) < transparentDepth - || (waterZ3 - terrainZ3) < transparentDepth) - { //add tile to set that needs shoreline blending. - if (m_numShoreLineTiles >= m_shoreLineTilePositionsSize) - { //no more room to store extra blend tiles so enlarge the buffer. - shoreLineTileInfo *tempPositions=NEW shoreLineTileInfo[m_shoreLineTilePositionsSize+512]; - memcpy(tempPositions, m_shoreLineTilePositions, m_shoreLineTilePositionsSize*sizeof(shoreLineTileInfo)); - delete [] m_shoreLineTilePositions; - //enlarge by more tiles to reduce memory trashing - m_shoreLineTilePositions = tempPositions; - m_shoreLineTilePositionsSize += 512; - } - //Pack x and y position into single integer since maps are limited in size - shoreLineTileInfo *shoreInfo=&m_shoreLineTilePositions[m_numShoreLineTiles]; - shoreInfo->m_xy=i | (j <<16); - shoreInfo->t0=(waterZ0 - terrainZ0)*depthScaleFactor; - shoreInfo->t1=(waterZ1 - terrainZ1)*depthScaleFactor; - shoreInfo->t2=(waterZ2 - terrainZ2)*depthScaleFactor; - shoreInfo->t3=(waterZ3 - terrainZ3)*depthScaleFactor; - m_numShoreLineTiles++; - } - } -} - -/** Generate a lookup table for arbitrary angled impassable area viewing. */ -void HeightMapRenderObjClass::updateViewImpassableAreas(Bool partial, Int minX, Int maxX, Int minY, Int maxY) -{ - Int xSize = m_map->getXExtent(); - Int ySize = m_map->getYExtent(); - if (m_showAsVisibleCliff.size() != xSize * ySize) { - m_showAsVisibleCliff.resize(xSize * ySize); - } - - if (!partial) { - minX = 0; - minY = 0; - maxX = xSize; - maxY = ySize; - } - - // save calculating the tangent over and over again. - Real tanImpassableRad = tan(m_curImpassableSlope / 360.f * 2 * PI); - for (Int j = minY; j < maxY; ++j) { - for (Int i = minX; i < maxX; ++i) { - m_showAsVisibleCliff[i + j * xSize] = evaluateAsVisibleCliff(i, j, tanImpassableRad); - } - } -} - -/** Generate a lookup table which can be used to generate an -alpha value from a given set of uv coordinates. Currently used -for smoothing water/terrain border*/ -void HeightMapRenderObjClass::initDestAlphaLUT(void) -{ - if (!m_destAlphaTexture) - return; - - SurfaceClass *surf=m_destAlphaTexture->Get_Surface_Level(); - - if (surf) - { - Int pitch; - UnsignedInt *pData=(UnsignedInt*)surf->Lock(&pitch); - - Int maxOpacity=(Int)(TheWaterTransparency->m_minWaterOpacity * 255.0f); - Int alpha; - - if (pData) - { - //Fill texture with alpha gradient - for (Int x=0; x<256; x++) - { - alpha = x; - if (alpha > maxOpacity) - alpha = maxOpacity; - *pData=(alpha<<24)|0x00ffffff; - pData++; - } - surf->Unlock(); - } - - m_destAlphaTexture->Get_Filter().Set_U_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); - m_destAlphaTexture->Get_Filter().Set_V_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); - REF_PTR_RELEASE(surf); - m_currentMinWaterOpacity = TheWaterTransparency->m_minWaterOpacity; - } -} - -//============================================================================= -// HeightMapRenderObjClass::initHeightData -//============================================================================= -/** Allocate a heightmap of x by y vertices and fill with initial height values. -Also allocates all rendering resources such as vertex buffers, index buffers, -shaders, and materials.*/ -//============================================================================= -Int HeightMapRenderObjClass::initHeightData(Int x, Int y, WorldHeightMap *pMap, RefRenderObjListIterator *pLightsIterator) -{ - Int i,j; -// Int vertsPerRow=x*2-2; -// Int vertsPerColumn=y*2-2; - - REF_PTR_SET(m_map,pMap); //update our heightmap pointer in case it changed since last call. - - if (m_shroud) - m_shroud->init(m_map,TheGlobalData->m_partitionCellSize,TheGlobalData->m_partitionCellSize); -#ifdef DO_ROADS - if (m_roadBuffer) - m_roadBuffer->setMap(m_map); -#endif - HeightSampleType *data = NULL; - if (pMap) { - data = pMap->getDataPtr(); - } - - m_numExtraBlendTiles = 0; - m_numShoreLineTiles = 0; - //Do some preprocessing on map to extract useful data - if (pMap) - { - //Find min/max values for all terrain heights, useful for rendering optimization - Int m_mapDX=pMap->getXExtent(); - Int m_mapDY=pMap->getYExtent(); - Int i, j, minHt, maxHt; - - minHt = pMap->getMaxHeightValue(); - maxHt = 0; - - for (j=0; jgetHeight(i,j); - if (curgetExtraAlphaUVData(i,j,U,V,alpha,&flipState, &cliffState)) - { if (m_numExtraBlendTiles >= m_extraBlendTilePositionsSize) - { //no more room to store extra blend tiles so enlarge the buffer. - Int *tempPositions=NEW Int[m_extraBlendTilePositionsSize+512]; - memcpy(tempPositions, m_extraBlendTilePositions, m_extraBlendTilePositionsSize*sizeof(Int)); - delete [] m_extraBlendTilePositions; - //enlarge by more tiles to reduce memory trashing - m_extraBlendTilePositions = tempPositions; - m_extraBlendTilePositionsSize += 512; - } - //Pack x and y position into single integer since maps are limited in size - m_extraBlendTilePositions[m_numExtraBlendTiles]=i | (j <<16); - m_numExtraBlendTiles++; - } - } - - //Find all shoreline tiles so they can get extra alpha blend - updateShorelineTiles(0,0,m_mapDX-1,m_mapDY-1,pMap); - if (TheWaterTransparency->m_minWaterOpacity != m_currentMinWaterOpacity) - initDestAlphaLUT(); - } - - Set_Force_Visible(TRUE); //terrain is always visible. - m_halfResMesh = TheGlobalData->m_useHalfHeightMap; - m_originX = 0; - m_originY = 0; - m_needFullUpdate = true; - - m_scorchesInBuffer = 0; - m_curNumScorchVertices=0; - m_curNumScorchIndices=0; - // If the size changed, we need to allocate. - Bool needToAllocate = (x != m_x || y != m_y); - // If the textures aren't allocated (usually because of a hardware reset) need to allocate. - if (m_stageOneTexture == NULL && m_treeBuffer) { - needToAllocate = true; - } - if (data && needToAllocate && m_treeBuffer != NULL) - { //requested heightmap different from old one. - //allocate a new one. - freeMapResources(); //free old data and ib/vb - REF_PTR_SET(m_map,pMap); //update our heightmap pointer in case it changed since last call. - m_stageTwoTexture=NEW CloudMapTerrainTextureClass; - m_stageThreeTexture=NEW LightMapTerrainTextureClass(m_macroTextureName); - m_destAlphaTexture=MSGNEW("TextureClass") TextureClass(256,1,WW3D_FORMAT_A8R8G8B8,MIP_LEVELS_1); - initDestAlphaLUT(); -#ifdef DO_SCORCH - allocateScorchBuffers(); -#endif - - //Create static index buffers. These will index the vertex buffers holding the map. - m_indexBuffer=NEW_REF(DX8IndexBufferClass,(VERTEX_BUFFER_TILE_LENGTH*VERTEX_BUFFER_TILE_LENGTH*2*3)); - - // Fill up the IB - DX8IndexBufferClass::WriteLockClass lockIdxBuffer(m_indexBuffer); - UnsignedShort *ib=lockIdxBuffer.Get_Index_Array(); - - for (j=0; j<(VERTEX_BUFFER_TILE_LENGTH*VERTEX_BUFFER_TILE_LENGTH*4); j+=VERTEX_BUFFER_TILE_LENGTH*4) - { - for (i=j; i<(j+VERTEX_BUFFER_TILE_LENGTH*4); i+=4) //4 vertices per 2x2 block - { - ib[0]=i; - ib[1]=i+2; - ib[2]=i+3; - - ib[3]=i; - ib[4]=i+1; - ib[5]=i+2; - - ib+=6; //skip the 6 indices we just filled - } - } - - //Get number of vertex buffers needed to hold current map - //First round dimensions to next multiple of VERTEX_BUFFER_TILE_LENGTH since that's our - //blocksize - m_numVBTilesX=1; - for (i=VERTEX_BUFFER_TILE_LENGTH+1; iGetCreationParameters(&parms); - Bool softwareVertexProcessing = 0!=(parms.BehaviorFlags&D3DCREATE_SOFTWARE_VERTEXPROCESSING); - if (m_xformedVertexBuffer == NULL && softwareVertexProcessing) { - m_xformedVertexBuffer = NEW IDirect3DVertexBuffer8*[m_numVertexBufferTiles]; - } -#endif - - for (i=0; iCreateVertexBuffer( - D3DXGetFVFVertexSize(D3DFVF_XYZRHW |D3DFVF_DIFFUSE|D3DFVF_TEX2)*numVertex, - D3DUSAGE_WRITEONLY|D3DUSAGE_DYNAMIC, - D3DFVF_XYZRHW |D3DFVF_DIFFUSE|D3DFVF_TEX2, - D3DPOOL_DEFAULT, - &m_xformedVertexBuffer[i]); - } -#endif - } - - //go with a preset material for now. -#ifdef USE_NORMALS - m_vertexMaterialClass= NEW VertexMaterialClass(); - m_vertexMaterialClass->Set_Shininess(0.0); - m_vertexMaterialClass->Set_Ambient(1,1,1); - m_vertexMaterialClass->Set_Diffuse(1,1,1); - m_vertexMaterialClass->Set_Specular(0,0,0); - m_vertexMaterialClass->Set_Opacity(0); - m_vertexMaterialClass->Set_Lighting(true); -#else - m_vertexMaterialClass=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_DIFFUSE); -#endif - - m_shaderClass = detailOpaqueShader; // ShaderClass::_PresetOpaqueShader; - } - - updateBlock(0,0,x-1,y-1,pMap,pLightsIterator); - - return 0; -} - -#ifdef DO_SCORCH -//============================================================================= -// HeightMapRenderObjClass::freeScorchBuffers -//============================================================================= -/** Frees the vertex buffers for scorches.*/ -//============================================================================= -void HeightMapRenderObjClass::freeScorchBuffers(void) -{ - REF_PTR_RELEASE(m_vertexScorch); - REF_PTR_RELEASE(m_indexScorch); - REF_PTR_RELEASE(m_scorchTexture); -} - -//============================================================================= -// HeightMapRenderObjClass::allocateScorchBuffers -//============================================================================= -/** Allocates the vertex buffer and texture for scorches.*/ -//============================================================================= -void HeightMapRenderObjClass::allocateScorchBuffers(void) -{ - m_vertexScorch=NEW_REF(DX8VertexBufferClass,(DX8_FVF_XYZDUV1,MAX_SCORCH_VERTEX,DX8VertexBufferClass::USAGE_DEFAULT)); - m_indexScorch=NEW_REF(DX8IndexBufferClass,(MAX_SCORCH_INDEX)); - m_scorchTexture=NEW ScorchTextureClass; - m_scorchesInBuffer = 0; // If we just allocated the buffers, we got no scorches in the buffer. - m_curNumScorchVertices=0; - m_curNumScorchIndices=0; -#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; - loc.X += 5*MAP_XY_FACTOR; - addScorch(loc, 3*MAP_XY_FACTOR, SCORCH_1); -#endif - -} - -//============================================================================= -// HeightMapRenderObjClass::updateScorches -//============================================================================= -/** Builds the vertex buffer data for drawing the scorches.*/ -//============================================================================= -void HeightMapRenderObjClass::updateScorches(void) -{ - if (m_scorchesInBuffer > 1) { - return; - } - if (!m_indexScorch || !m_vertexScorch) { - return; - } - m_curNumScorchVertices = 0; - m_curNumScorchIndices = 0; - DX8IndexBufferClass::WriteLockClass lockIdxBuffer(m_indexScorch); - UnsignedShort *ib=lockIdxBuffer.Get_Index_Array(); - UnsignedShort *curIb = ib; - - DX8VertexBufferClass::WriteLockClass lockVtxBuffer(m_vertexScorch); - VertexFormatXYZDUV1 *vb = (VertexFormatXYZDUV1*)lockVtxBuffer.Get_Vertex_Array(); - VertexFormatXYZDUV1 *curVb = vb; - - Int curScorch; - Real shadeR, shadeG, shadeB; - shadeR = TheGlobalData->m_terrainAmbient[0].red; - shadeG = TheGlobalData->m_terrainAmbient[0].green; - shadeB = TheGlobalData->m_terrainAmbient[0].blue; - shadeR += TheGlobalData->m_terrainDiffuse[0].red/2; - shadeG += TheGlobalData->m_terrainDiffuse[0].green/2; - shadeB += TheGlobalData->m_terrainDiffuse[0].blue/2; - shadeR*=255.0f; - shadeG*=255.0f; - shadeB*=255.0f; - Int diffuse=REAL_TO_INT(shadeB) | (REAL_TO_INT(shadeG) << 8) | (REAL_TO_INT(shadeR) << 16) | ((int)255 << 24); - m_scorchesInBuffer = 0; - for (curScorch=m_numScorches-1; curScorch>=0; curScorch--) { - m_scorchesInBuffer++; - Real radius = m_scorches[curScorch].radius; - Vector3 loc = m_scorches[curScorch].location; - Int type = m_scorches[curScorch].scorchType; - if (type<0) { - type = 0; - } - if (type >= SCORCH_MARKS_IN_TEXTURE) { - type = 0; - } - Real amtToFloat = 0; - if (m_halfResMesh) { - amtToFloat = MAP_HEIGHT_SCALE/8; - } - - Int minX = REAL_TO_INT_FLOOR((loc.X-radius)/MAP_XY_FACTOR); - Int minY = REAL_TO_INT_FLOOR((loc.Y-radius)/MAP_XY_FACTOR); - if (minX<-m_map->getBorderSize()) minX=-m_map->getBorderSize(); - if (minY<-m_map->getBorderSize()) minY=-m_map->getBorderSize(); - Int maxX = REAL_TO_INT_CEIL((loc.X+radius)/MAP_XY_FACTOR); - Int maxY = REAL_TO_INT_CEIL((loc.Y+radius)/MAP_XY_FACTOR); - maxX++; maxY++; - if (maxX > m_map->getXExtent()-m_map->getBorderSize()) { - maxX = m_map->getXExtent()-m_map->getBorderSize(); - } - if (maxY > m_map->getYExtent()-m_map->getBorderSize()) { - maxY = m_map->getYExtent()-m_map->getBorderSize(); - } - Int startVertex = m_curNumScorchVertices; - Int i, j; - for (j=minY; j= MAX_SCORCH_VERTEX) return; - curVb->diffuse = diffuse; - Real theZ; - theZ = amtToFloat+((float)getClipHeight(i+m_map->getBorderSize(),j+m_map->getBorderSize())*MAP_HEIGHT_SCALE); - if (m_halfResMesh) { - theZ = amtToFloat + this->getMaxCellHeight(i, j); - Real amt2 = amtToFloat + getMaxCellHeight(i-1, j-1); - if (amt2 > theZ) { - theZ = amt2; - } - } - // The scorchmarks are spaced out by 1.5 in the texture. - Real uOffset = (type%SCORCH_PER_ROW) * 1.5f; - Real vOffset = (type/SCORCH_PER_ROW) * 1.5f; - Real X = i*MAP_XY_FACTOR; - Real Y = j*MAP_XY_FACTOR; - curVb->u1 = (uOffset + 0.5f + (X - loc.X)/(2*radius)) / (SCORCH_PER_ROW+1); - curVb->v1 = (vOffset + 0.5f + (Y - loc.Y)/(2*radius)) / (SCORCH_PER_ROW+1); - curVb->x = X; - curVb->y = Y; - curVb->z = theZ; - curVb++; - m_curNumScorchVertices++; - } - } - Int yOffset = maxX-minX; - for (j=0; j MAX_SCORCH_INDEX) return; - Int xNdx = i+minX+m_map->getBorderSize(); - Int yNdx = j+minY+m_map->getBorderSize(); - Bool flipForBlend = m_map->getFlipState(xNdx, yNdx); -#if 0 - UnsignedByte alpha[4]; - float UA[4], VA[4]; - m_map->getAlphaUVData(xNdx, yNdx, UA, VA, alpha, &flipForBlend, false); -#endif - if (flipForBlend) { - *curIb++ = startVertex + j*yOffset + i+1; - *curIb++ = startVertex + j*yOffset + i+yOffset; - *curIb++ = startVertex + j*yOffset + i; - *curIb++ = startVertex + j*yOffset + i+1; - *curIb++ = startVertex + j*yOffset + i+1+yOffset; - *curIb++ = startVertex + j*yOffset + i+yOffset; - } - else - { - *curIb++ = startVertex + j*yOffset + i; - *curIb++ = startVertex + j*yOffset + i+1+yOffset; - *curIb++ = startVertex + j*yOffset + i+yOffset; - *curIb++ = startVertex + j*yOffset + i; - *curIb++ = startVertex + j*yOffset + i+1; - *curIb++ = startVertex + j*yOffset + i+1+yOffset; - } - m_curNumScorchIndices+=6; - } - } - } - -} - -#endif - -//============================================================================= -// HeightMapRenderObjClass::clearAllScorches -//============================================================================= -/** Removes all scorches. */ -//============================================================================= -void HeightMapRenderObjClass::clearAllScorches(void) -{ -#ifdef DO_SCORCH - m_numScorches=0; - m_scorchesInBuffer=0; -#endif -} - -//============================================================================= -// HeightMapRenderObjClass::addScorch -//============================================================================= -/** Adds a scorch mark. */ -//============================================================================= -void HeightMapRenderObjClass::addScorch(Vector3 location, Real radius, Scorches type) -{ -#ifdef DO_SCORCH - if (m_numScorches >= MAX_SCORCH_MARKS) { - Int i; - for (i=0; i= m_map->getXExtent()) - x=m_map->getXExtent()-1; - if (y >= m_map->getYExtent()) - y=m_map->getYExtent()-1; - if (m_halfResMesh) { - x&=0xffffffe; - y&=0xffffffe; - } - - if (m_map == NULL) { - return(0); - } - - Vector3 l2r,n2f,normalAtTexel; - Int vn0,un0,vp1,up1; - Int cellOffset = 1; - if (m_halfResMesh) { - cellOffset = 2; - } - - vn0 = y-cellOffset; - vp1 = y+cellOffset; - if (vp1 >= m_map->getYExtent()) - vp1=m_map->getYExtent()-1; - if (vn0<0) vn0 = 0; - un0 = x-cellOffset; - up1 = x+cellOffset; - if (un0 < 0) - un0=0; - if (up1 >= m_map->getXExtent()) - up1=m_map->getXExtent()-1; - - Vector3 lightRay[MAX_GLOBAL_LIGHTS]; - const Coord3D *lightPos; - - for (Int lightIndex=0; lightIndex < TheGlobalData->m_numGlobalLights; lightIndex++) - { - lightPos=&TheGlobalData->m_terrainLightPos[lightIndex]; - lightRay[lightIndex].Set(-lightPos->x,-lightPos->y, -lightPos->z); - } - //top-left sample - l2r.Set(2*MAP_XY_FACTOR,0,MAP_HEIGHT_SCALE*(m_map->getHeight(up1, y) - m_map->getHeight(un0, y))); - n2f.Set(0,2*MAP_XY_FACTOR,MAP_HEIGHT_SCALE*(m_map->getHeight(x, vp1) - m_map->getHeight(x, vn0))); - -#ifdef ALLOW_TEMPORARIES - normalAtTexel= Normalize(Vector3::Cross_Product(l2r,n2f)); -#else - Vector3::Normalized_Cross_Product(l2r,n2f, &normalAtTexel); -#endif + m_numBlockColumnsInLastVB=(x-1)%VERTEX_BUFFER_TILE_LENGTH; //right border within last VB + m_numBlockRowsInLastVB=(y-1)%VERTEX_BUFFER_TILE_LENGTH; //bottom border within last VB - VERTEX_FORMAT vertex; - vertex.x=ADJUST_FROM_INDEX_TO_REAL(x); - vertex.y=ADJUST_FROM_INDEX_TO_REAL(y); + m_numVertexBufferTiles=m_numVBTilesX*m_numVBTilesY; + m_x=x; + m_y=y; + m_vertexBufferTiles = NEW DX8VertexBufferClass*[m_numVertexBufferTiles]; + m_vertexBufferBackup = NEW char *[m_numVertexBufferTiles]; - vertex.z= ((float)m_map->getHeight(x,y))*MAP_HEIGHT_SCALE; - vertex.u1=0; - vertex.v1=0; - vertex.u2=1; - vertex.v2=1; + Int numVertex = VERTEX_BUFFER_TILE_LENGTH*2*VERTEX_BUFFER_TILE_LENGTH*2; - RTS3DScene *pMyScene = (RTS3DScene *)Scene; - if (pMyScene) { - RefRenderObjListIterator *it = pMyScene->createLightsIterator(); - doTheLight(&vertex, lightRay, &normalAtTexel, it, 1.0f); - if (it) { - pMyScene->destroyLightsIterator(it); - it = NULL; - } - } else { - doTheLight(&vertex, lightRay, &normalAtTexel, NULL, 1.0f); - } + for (i=0; igetDrawOrgY(); - Int yCoordMax = m_y+m_map->getDrawOrgY()-1; - Int xCoordMin = m_map->getDrawOrgX(); - Int xCoordMax = m_x+m_map->getDrawOrgX()-1; - if (x xCoordMax || y>yCoordMax) { - return(0); - } - if (x==xCoordMax) x--; - if (y==yCoordMax) y--; - x -= xCoordMin; - y -= yCoordMin; - - y += m_originY; - if (y<0) y+= m_y-1; - if (y> m_y-1) y-=m_y-1; - if (y<0) y = 0; - if (y>= m_y-1) y=m_y-1; - - x += m_originX; - if (x<0) x+= m_x-1; - if (x> m_x-1) x-=m_x-1; - if (x<0) x = 0; - if (x>= m_x-1) x=m_x-1; - i = 0; - while (x>VERTEX_BUFFER_TILE_LENGTH) { - i++; - x -= VERTEX_BUFFER_TILE_LENGTH; - } - if (x==VERTEX_BUFFER_TILE_LENGTH) x--; - j = 0; - while (y>VERTEX_BUFFER_TILE_LENGTH) { - j++; - y -= VERTEX_BUFFER_TILE_LENGTH; + //go with a preset material for now. } - if (y==VERTEX_BUFFER_TILE_LENGTH) y--; - char **pData = m_vertexBufferBackup+j*m_numVBTilesX+i; - Int vertsPerRow=(VERTEX_BUFFER_TILE_LENGTH)*4; //vertices per row of VB - - if (m_halfResMesh) { - x/=2; - y/=2; - vertsPerRow /= 2; - } + updateBlock(0,0,x-1,y-1,pMap,pLightsIterator); - VERTEX_FORMAT *vbMirror = ((VERTEX_FORMAT*)(*pData)) + (y)*vertsPerRow+4*(x); - if ( vbMirror[0].x==X && vbMirror[0].y==Y) { - return(vbMirror[0].diffuse); - } - if ( vbMirror[3].x==X && vbMirror[3].y==Y) { - return(vbMirror[3].diffuse); - } - if ( vbMirror[1].x==X && vbMirror[1].y==Y) { - return(vbMirror[1].diffuse); - } - if ( vbMirror[2].x==X && vbMirror[2].y==Y) { - return(vbMirror[2].diffuse); - } -#ifdef RTS_DEBUG - char buf[256]; - sprintf(buf, "(%f,%f) -> mirror (%f, %f)\n", X, Y, vbMirror->x, vbMirror->y); - ::OutputDebugString(buf); -#endif - return(vbMirror->diffuse); -#endif + return 0; } + //============================================================================= // HeightMapRenderObjClass::On_Frame_Update //============================================================================= @@ -3178,7 +1391,7 @@ Int HeightMapRenderObjClass::getStaticDiffuse(Int x, Int y) //============================================================================= void HeightMapRenderObjClass::On_Frame_Update(void) { - + BaseHeightMapRenderObjClass::On_Frame_Update(); Int i,j,k; DX8VertexBufferClass **pVB; Int originX,originY; @@ -3266,8 +1479,8 @@ void HeightMapRenderObjClass::On_Frame_Update(void) yMin = originY; yMax = originY+VERTEX_BUFFER_TILE_LENGTH; Bool intersect = false; - Int yCoordMin = getYWithOrigin(yMin)+m_map->getDrawOrgY()-m_map->getBorderSize(); - Int yCoordMax = getYWithOrigin(yMax-1)+m_map->getDrawOrgY()+1-m_map->getBorderSize(); + Int yCoordMin = getYWithOrigin(yMin)+m_map->getDrawOrgY()-m_map->getBorderSizeInline(); + Int yCoordMax = getYWithOrigin(yMax-1)+m_map->getDrawOrgY()+1-m_map->getBorderSizeInline(); if (yCoordMax>yCoordMin) { // no wrap occurred. for (k=0; kgetDrawOrgX()-m_map->getBorderSize(); - Int xCoordMax = getXWithOrigin(xMax-1)+m_map->getDrawOrgX()+1-m_map->getBorderSize(); + Int xCoordMin = getXWithOrigin(xMin)+m_map->getDrawOrgX()-m_map->getBorderSizeInline(); + Int xCoordMax = getXWithOrigin(xMax-1)+m_map->getDrawOrgX()+1-m_map->getBorderSizeInline(); if (xCoordMax>xCoordMin) { // no wrap occurred. for (k=0; kaddTree(location, scale, angle, name, visibleInMirror); -}; - -//============================================================================= -// HeightMapRenderObjClass::addTerrainBib -//============================================================================= -/** Adds a terrainBib to the bib buffer.*/ -//============================================================================= -void HeightMapRenderObjClass::addTerrainBib(Vector3 corners[4], - ObjectID id, Bool highlight) -{ - if (m_bibBuffer) - m_bibBuffer->addBib(corners, id, highlight); -}; - -//============================================================================= -// HeightMapRenderObjClass::addTerrainBib -//============================================================================= -/** Adds a terrainBib to the bib buffer.*/ -//============================================================================= -void HeightMapRenderObjClass::addTerrainBibDrawable(Vector3 corners[4], - DrawableID id, Bool highlight) -{ - if (m_bibBuffer) - m_bibBuffer->addBibDrawable(corners, id, highlight); -}; - -//============================================================================= -// HeightMapRenderObjClass::removeAllTerrainBibs -//============================================================================= -/** Removes all terrainBib highlighting from the bib buffer.*/ -//============================================================================= -void HeightMapRenderObjClass::removeTerrainBibHighlighting() -{ - if (m_bibBuffer) - m_bibBuffer->removeHighlighting( ); -}; - -//============================================================================= -// HeightMapRenderObjClass::removeAllTerrainBibs -//============================================================================= -/** Removes all terrainBibs from the bib buffer.*/ -//============================================================================= -void HeightMapRenderObjClass::removeAllTerrainBibs() -{ - if (m_bibBuffer) - m_bibBuffer->clearAllBibs( ); -}; - -//============================================================================= -// HeightMapRenderObjClass::removeTerrainBib -//============================================================================= -/** Removes a terrainBib from the bib buffer.*/ -//============================================================================= -void HeightMapRenderObjClass::removeTerrainBib(ObjectID id) -{ - if (m_bibBuffer) - m_bibBuffer->removeBib( id ); -}; - -//============================================================================= -// HeightMapRenderObjClass::removeTerrainBib -//============================================================================= -/** Removes a terrainBib from the bib buffer.*/ -//============================================================================= -void HeightMapRenderObjClass::removeTerrainBibDrawable(DrawableID id) -{ - if (m_bibBuffer) - m_bibBuffer->removeBibDrawable( id ); -}; - //============================================================================= // HeightMapRenderObjClass::staticLightingChanged //============================================================================= @@ -3443,40 +1577,9 @@ void HeightMapRenderObjClass::removeTerrainBibDrawable(DrawableID id) //============================================================================= void HeightMapRenderObjClass::staticLightingChanged( void ) { - // Cause the terrain to get updated with new lighting. - m_needFullUpdate = true; - - // Cause the scorches to get updated with new lighting. - m_scorchesInBuffer = 0; // If we just allocated the buffers, we got no scorches in the buffer. - m_curNumScorchVertices=0; - m_curNumScorchIndices=0; - -} - -//============================================================================= -// HeightMapRenderObjClass::setTimeOfDay -//============================================================================= -/** When the time of day changes, the lighting changes and we need to update. */ -//============================================================================= -void HeightMapRenderObjClass::setTimeOfDay( TimeOfDay tod ) -{ - staticLightingChanged(); -} - -//============================================================================= -// HeightMapRenderObjClass::Notify_Added -//============================================================================= -/** W3D render object method, we use it to add ourselves to tthe update -list, so On_Frame_Update gets called. */ -//============================================================================= -void HeightMapRenderObjClass::Notify_Added(SceneClass * scene) -{ - RenderObjClass::Notify_Added(scene); - scene->Register(this,SceneClass::ON_FRAME_UPDATE); + BaseHeightMapRenderObjClass::staticLightingChanged(); } - - #define CENTER_LIMIT 2 #define BIG_JUMP 16 #define WIDE_STEP 32 @@ -3490,7 +1593,7 @@ static Bool check(const FrustumClass & frustum, WorldHeightMap *pMap, Int x, Int return(true); } Int height = pMap->getHeight(x, y); - Vector3 loc((x-pMap->getBorderSize())*MAP_XY_FACTOR, (y-pMap->getBorderSize())*MAP_XY_FACTOR, height*MAP_HEIGHT_SCALE); + Vector3 loc((x-pMap->getBorderSizeInline())*MAP_XY_FACTOR, (y-pMap->getBorderSizeInline())*MAP_XY_FACTOR, height*MAP_HEIGHT_SCALE); if (CollisionMath::Overlap_Test(frustum,loc) == CollisionMath::INSIDE) { if (xvisMaxX) visMaxX=x; @@ -3558,6 +1661,9 @@ static void calcVis(const FrustumClass & frustum, WorldHeightMap *pMap, Int minX } + + + //============================================================================= // HeightMapRenderObjClass::updateCenter //============================================================================= @@ -3575,39 +1681,28 @@ void HeightMapRenderObjClass::updateCenter(CameraClass *camera , RefRenderObjLis if (m_updating) { return; } - if (m_vertexBufferTiles ==NULL) return; //did not initialize resources yet. - m_treeBuffer->doFullUpdate(); // Tell the trees to update for view change. - -#ifdef TEST_CUSTOM_EDGING - m_customEdging->doFullUpdate(); -#endif + BaseHeightMapRenderObjClass::updateCenter(camera, pLightsIterator); m_updating = true; - if (m_needFullUpdate) { + if (m_needFullUpdate) + { m_needFullUpdate = false; updateBlock(0, 0, m_x-1, m_y-1, m_map, pLightsIterator); -#ifdef DO_ROADS - if (m_roadBuffer) { - m_roadBuffer->updateLighting(); - } -#endif - m_bridgeBuffer->doFullUpdate(); - m_bridgeBuffer->updateCenter(camera, pLightsIterator); m_updating = false; return; } - m_bridgeBuffer->updateCenter(camera, pLightsIterator); - if (m_x >= m_map->getXExtent() && m_y >= m_map->getYExtent()) { + if (m_x >= m_map->getXExtent() && m_y >= m_map->getYExtent()) + { m_updating = false; return; // no need to center. } Int cellOffset = 1; - if (m_halfResMesh) { + if (HALF_RES_MESH) { cellOffset = 2; } // determine the ray corresponding to the camera and distance to projection plane @@ -3674,10 +1769,10 @@ void HeightMapRenderObjClass::updateCenter(CameraClass *camera , RefRenderObjLis minY /= MAP_XY_FACTOR; maxY /= MAP_XY_FACTOR; - minX += m_map->getBorderSize(); - maxX += m_map->getBorderSize(); - minY += m_map->getBorderSize(); - maxY += m_map->getBorderSize(); + minX += m_map->getBorderSizeInline(); + maxX += m_map->getBorderSizeInline(); + minY += m_map->getBorderSizeInline(); + maxY += m_map->getBorderSizeInline(); visMinX = m_map->getXExtent(); visMinY = m_map->getYExtent(); @@ -3715,7 +1810,7 @@ void HeightMapRenderObjClass::updateCenter(CameraClass *camera , RefRenderObjLis newOrgX = (visMaxX+visMinX)/2-m_x/2.0; newOrgY = (visMaxY+visMinY)/2-m_y/2.0; } - if (m_halfResMesh) { + if (HALF_RES_MESH) { newOrgX &= 0xFFFFFFFE; newOrgY &= 0xFFFFFFFE; } @@ -3971,7 +2066,7 @@ void HeightMapRenderObjClass::Render(RenderInfoClass & rinfo) count++; Int numPolys = VERTEX_BUFFER_TILE_LENGTH*VERTEX_BUFFER_TILE_LENGTH*2; Int numVertex = (VERTEX_BUFFER_TILE_LENGTH*2)*(VERTEX_BUFFER_TILE_LENGTH*2); - if (m_halfResMesh) { + if (HALF_RES_MESH) { numPolys /= 4; numVertex /= 4; } @@ -4012,15 +2107,15 @@ void HeightMapRenderObjClass::Render(RenderInfoClass & rinfo) if (TheGlobalData->m_use3WayTerrainBlends) renderExtraBlendTiles(); + Int yCoordMin = m_map->getDrawOrgY(); + Int yCoordMax = m_y+m_map->getDrawOrgY()-1; + Int xCoordMin = m_map->getDrawOrgX(); + Int xCoordMax = m_x+m_map->getDrawOrgX()-1; #ifdef TEST_CUSTOM_EDGING // Draw edging just before last pass. DX8Wrapper::Set_Texture(0,NULL); DX8Wrapper::Set_Texture(1,NULL); m_stageTwoTexture->restore(); - Int yCoordMin = m_map->getDrawOrgY(); - Int yCoordMax = m_y+m_map->getDrawOrgY()-1; - Int xCoordMin = m_map->getDrawOrgX(); - Int xCoordMax = m_x+m_map->getDrawOrgX()-1; m_customEdging->drawEdging(m_map, xCoordMin, xCoordMax, yCoordMin, yCoordMax, m_stageZeroTexture, doCloud?m_stageTwoTexture:NULL, TheGlobalData->m_useLightMap?m_stageThreeTexture:NULL); #endif @@ -4036,11 +2131,13 @@ void HeightMapRenderObjClass::Render(RenderInfoClass & rinfo) RTS3DScene *pMyScene = (RTS3DScene *)Scene; RefRenderObjListIterator pDynamicLightsIterator(pMyScene->getDynamicLights()); m_roadBuffer->drawRoads(&rinfo.Camera, doCloud?m_stageTwoTexture:NULL, TheGlobalData->m_useLightMap?m_stageThreeTexture:NULL, - m_disableTextures,xCoordMin-m_map->getBorderSize(), xCoordMax-m_map->getBorderSize(), yCoordMin-m_map->getBorderSize(), yCoordMax-m_map->getBorderSize(), &pDynamicLightsIterator); + m_disableTextures,xCoordMin-m_map->getBorderSizeInline(), xCoordMax-m_map->getBorderSizeInline(), yCoordMin-m_map->getBorderSizeInline(), yCoordMax-m_map->getBorderSizeInline(), &pDynamicLightsIterator); } } #endif - + if (m_propBuffer) { + m_propBuffer->drawProps(rinfo); + } #ifdef DO_SCORCH DX8Wrapper::Set_Texture(0,NULL); DX8Wrapper::Set_Texture(1,NULL); @@ -4057,7 +2154,7 @@ void HeightMapRenderObjClass::Render(RenderInfoClass & rinfo) ShaderClass::Invalidate(); DX8Wrapper::Apply_Render_State_Changes(); - m_bridgeBuffer->drawBridges(&rinfo.Camera, m_disableTextures, m_stageTwoTexture); + m_bridgeBuffer->drawBridges(&rinfo.Camera, m_disableTextures, doCloud?m_stageTwoTexture:NULL); if (TheTerrainTracksRenderObjClassSystem) TheTerrainTracksRenderObjClassSystem->flush(); @@ -4075,7 +2172,8 @@ void HeightMapRenderObjClass::Render(RenderInfoClass & rinfo) else m_bridgeBuffer->drawBridges(&rinfo.Camera, m_disableTextures, m_stageTwoTexture); - m_waypointBuffer->drawWaypoints(rinfo); + if ( m_waypointBuffer ) + m_waypointBuffer->drawWaypoints(rinfo); m_bibBuffer->renderBibs(); @@ -4088,147 +2186,7 @@ void HeightMapRenderObjClass::Render(RenderInfoClass & rinfo) } -/**Render parts of terrain that are along the coast line and have vertices directly under the -water plane. Applying a custom render to these polygons allows for a smoother land->water -transition*/ -void HeightMapRenderObjClass::renderShoreLines(CameraClass *pCamera) -{ - if (!TheGlobalData->m_showSoftWaterEdge || TheWaterTransparency->m_transparentWaterDepth==0 || m_numShoreLineTiles == 0) - return; - - //Check if video card is capable of using this effect - if (DX8Wrapper::getBackBufferFormat() != WW3D_FORMAT_A8R8G8B8) - return; //can't apply effect on cards without destination alpha - - Int vertexCount = 0; - Int indexCount = 0; - Int xExtent = m_map->getXExtent(); - Int border = m_map->getBorderSize(); - Int drawEdgeY=m_map->getDrawOrgY()+m_map->getDrawHeight()-1; - Int drawEdgeX=m_map->getDrawOrgX()+m_map->getDrawWidth()-1; - if (drawEdgeX > (m_map->getXExtent()-1)) - drawEdgeX = m_map->getXExtent()-1; - if (drawEdgeY > (m_map->getYExtent()-1)) - drawEdgeY = m_map->getYExtent()-1; - Int drawStartX=m_map->getDrawOrgX(); - Int drawStartY=m_map->getDrawOrgY(); - const UnsignedByte* data = m_map->getDataPtr(); - Int j=0; - - ShaderClass unlitShader=ShaderClass::_PresetOpaque2DShader; - unlitShader.Set_Depth_Compare(ShaderClass::PASS_LEQUAL); - DX8Wrapper::Set_Shader(unlitShader); - VertexMaterialClass *vmat=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_DIFFUSE); - DX8Wrapper::Set_Material(vmat); - REF_PTR_RELEASE(vmat); - DX8Wrapper::Set_Texture(0,m_destAlphaTexture); - DX8Wrapper::Set_Transform(D3DTS_WORLD,Matrix3D(1)); - //Enabled writes to destination alpha only - DX8Wrapper::Set_DX8_Render_State(D3DRS_COLORWRITEENABLE,D3DCOLORWRITEENABLE_ALPHA); - DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_TEXCOORDINDEX, 0); - - while (j != m_numShoreLineTiles) - { - { //Need to put this in another code block so vb/ib gets automatically locked/unlocked by destructors - DynamicVBAccessClass vb_access(BUFFER_TYPE_DYNAMIC_DX8,dynamic_fvf_type,DEFAULT_MAX_BATCH_SHORELINE_TILES*4); - DynamicIBAccessClass ib_access(BUFFER_TYPE_DYNAMIC_DX8,DEFAULT_MAX_BATCH_SHORELINE_TILES*6); - - DynamicVBAccessClass::WriteLockClass lock(&vb_access); - VertexFormatXYZNDUV2 *vb= lock.Get_Formatted_Vertex_Array(); - DynamicIBAccessClass::WriteLockClass lockib(&ib_access); - UnsignedShort *ib=lockib.Get_Index_Array(); - if (!ib || !vb) - { DX8Wrapper::Set_DX8_Render_State(D3DRS_COLORWRITEENABLE,D3DCOLORWRITEENABLE_BLUE|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_RED); - return; - } - - //Loop over visible terrain and extract all the tiles that need shoreline blend - for (; j= (DEFAULT_MAX_BATCH_SHORELINE_TILES*4)) - break; //no room in vertex buffer - - shoreLineTileInfo *shoreInfo=&m_shoreLineTilePositions[j]; - - Int x = shoreInfo->m_xy & 0xffff; - Int y = shoreInfo->m_xy >> 16; - - if (x >= drawStartX && x < drawEdgeX && y >= drawStartY && y < drawEdgeY) - { //this tile is inside visible region - - Int idx = x+y*xExtent; - - Real p0=data[idx]*MAP_HEIGHT_SCALE; - Real p1=data[idx+1]*MAP_HEIGHT_SCALE; - Real p2=data[idx + 1 + xExtent]*MAP_HEIGHT_SCALE; - Real p3=data[idx + xExtent]*MAP_HEIGHT_SCALE; - - vb->x=(x-border)*MAP_XY_FACTOR; - vb->y=(y-border)*MAP_XY_FACTOR; - vb->z=p0; - vb->u1=shoreInfo->t0; - vb->v1=0; - vb++; - - vb->x=(x+1-border)*MAP_XY_FACTOR; - vb->y=(y-border)*MAP_XY_FACTOR; - vb->z=p1; - vb->u1=shoreInfo->t1; - vb->v1=0; - vb++; - - vb->x=(x+1-border)*MAP_XY_FACTOR; - vb->y=(y+1-border)*MAP_XY_FACTOR; - vb->z=p2; - vb->u1=shoreInfo->t2; - vb->v1=0; - vb++; - - vb->x=(x-border)*MAP_XY_FACTOR; - vb->y=(y+1-border)*MAP_XY_FACTOR; - vb->z=p3; - vb->u1=shoreInfo->t3; - vb->v1=0; - vb++; - - if (m_map->getFlipState(x,y)) - { - ib[0]=1+vertexCount; - ib[1]=3+vertexCount; - ib[2]=0+vertexCount; - ib[3]=1+vertexCount; - ib[4]=2+vertexCount; - ib[5]=3+vertexCount; - } - else - { - ib[0]=0+vertexCount; - ib[1]=2+vertexCount; - ib[2]=3+vertexCount; - ib[3]=0+vertexCount; - ib[4]=1+vertexCount; - ib[5]=2+vertexCount; - } - ib += 6; - vertexCount +=4; - indexCount +=6; - } - } - - DX8Wrapper::Set_Index_Buffer(ib_access,0); - DX8Wrapper::Set_Vertex_Buffer(vb_access); - } - - if (indexCount > 0 && vertexCount > 0) - DX8Wrapper::Draw_Triangles( 0,indexCount/3, 0, vertexCount); //draw a quad, 2 triangles, 4 verts - vertexCount=0; - indexCount=0; - } - //Disable writes to destination alpha - DX8Wrapper::Set_DX8_Render_State(D3DRS_COLORWRITEENABLE,D3DCOLORWRITEENABLE_BLUE|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_RED); - ShaderClass::Invalidate(); -} ///Performs additional terrain rendering pass, blending in the black shroud texture. void HeightMapRenderObjClass::renderTerrainPass(CameraClass *pCamera) @@ -4246,7 +2204,7 @@ void HeightMapRenderObjClass::renderTerrainPass(CameraClass *pCamera) count++; Int numPolys = VERTEX_BUFFER_TILE_LENGTH*VERTEX_BUFFER_TILE_LENGTH*2; Int numVertex = (VERTEX_BUFFER_TILE_LENGTH*2)*(VERTEX_BUFFER_TILE_LENGTH*2); - if (m_halfResMesh) { + if (HALF_RES_MESH) { numPolys /= 4; numVertex /= 4; } @@ -4275,30 +2233,8 @@ void HeightMapRenderObjClass::renderTerrainPass(CameraClass *pCamera) } //============================================================================= -// HeightMapRenderObjClass::renderTrees -//============================================================================= -/** Renders (draws) the trees. Since the trees are transparent, this has to be -called after flush. */ +// HeightMapRenderObjClass::renderExtraBlendTiles //============================================================================= -void HeightMapRenderObjClass::renderTrees(CameraClass * camera) -{ -#ifdef EXTENDED_STATS - if (DX8Wrapper::stats.m_disableObjects) { - return; - } -#endif - if (m_map==NULL) return; - if (Scene==NULL) return; - if (m_treeBuffer) { - Matrix3D tm(Transform); - DX8Wrapper::Set_Transform(D3DTS_WORLD,tm); - DX8Wrapper::Set_Material(m_vertexMaterialClass); - RTS3DScene *pMyScene = (RTS3DScene *)Scene; - RefRenderObjListIterator pDynamicLightsIterator(pMyScene->getDynamicLights()); - m_treeBuffer->drawTrees(camera, &pDynamicLightsIterator); - } -} - /** Renders an additoinal terrain pass including only those tiles which have more than 2 textures blended together. Used primarily for corner cases where 3 different textures meet.*/ void HeightMapRenderObjClass::renderExtraBlendTiles(void) @@ -4306,9 +2242,11 @@ void HeightMapRenderObjClass::renderExtraBlendTiles(void) Int vertexCount = 0; Int indexCount = 0; Int xExtent = m_map->getXExtent(); - Int border = m_map->getBorderSize(); + Int border = m_map->getBorderSizeInline(); static Int maxBlendTiles = DEFAULT_MAX_FRAME_EXTRABLEND_TILES; + m_numVisibleExtraBlendTiles = 0; + if (!m_numExtraBlendTiles) return; //nothing to draw @@ -4366,33 +2304,53 @@ void HeightMapRenderObjClass::renderExtraBlendTiles(void) vb->x=(x-border)*MAP_XY_FACTOR; vb->y=(y-border)*MAP_XY_FACTOR; vb->z=p0; + vb->nx=0; + vb->ny=0; + vb->nz=0; vb->diffuse=(alpha[0]<<24)|(getStaticDiffuse(x,y) & 0x00ffffff); vb->u1=U[0]; vb->v1=V[0]; + vb->u2=0; + vb->v2=0; vb++; vb->x=(x+1-border)*MAP_XY_FACTOR; vb->y=(y-border)*MAP_XY_FACTOR; vb->z=p1; + vb->nx=0; + vb->ny=0; + vb->nz=0; vb->diffuse=(alpha[1]<<24)|(getStaticDiffuse(x+1,y) & 0x00ffffff); vb->u1=U[1]; vb->v1=V[1]; + vb->u2=0; + vb->v2=0; vb++; vb->x=(x+1-border)*MAP_XY_FACTOR; vb->y=(y+1-border)*MAP_XY_FACTOR; vb->z=p2; + vb->nx=0; + vb->ny=0; + vb->nz=0; vb->diffuse=(alpha[2]<<24)|(getStaticDiffuse(x+1,y+1) & 0x00ffffff); vb->u1=U[2]; vb->v1=V[2]; + vb->u2=0; + vb->v2=0; vb++; vb->x=(x-border)*MAP_XY_FACTOR; vb->y=(y+1-border)*MAP_XY_FACTOR; vb->z=p3; + vb->nx=0; + vb->ny=0; + vb->nz=0; vb->diffuse=(alpha[3]<<24)|(getStaticDiffuse(x,y+1) & 0x00ffffff); vb->u1=U[3]; vb->v1=V[3]; + vb->u2=0; + vb->v2=0; vb++; if (flipState) @@ -4444,6 +2402,7 @@ void HeightMapRenderObjClass::renderExtraBlendTiles(void) DX8Wrapper::Set_Texture(0,NULL); //debug mode which draws terrain tiles in white. if (Is_Hidden() == 0) { DX8Wrapper::Draw_Triangles( 0,indexCount/3, 0, vertexCount); //draw a quad, 2 triangles, 4 verts + m_numVisibleExtraBlendTiles += indexCount/6; } } else @@ -4474,18 +2433,13 @@ void HeightMapRenderObjClass::renderExtraBlendTiles(void) for (Int pass=0; pass < devicePasses; pass++) { W3DShaderManager::setShader(st, pass); - //Draw all this road type. if (Is_Hidden() == 0) { DX8Wrapper::Draw_Triangles( 0,indexCount/3, 0, vertexCount); //draw a quad, 2 triangles, 4 verts + m_numVisibleExtraBlendTiles += indexCount/6; } } W3DShaderManager::resetShader(st); } } } - -//============================================================================= -Bool HeightMapRenderObjClass::useCloud() -{ - return TheGlobalData->m_useCloudMap && TheGlobalData->m_timeOfDay != TIME_OF_DAY_NIGHT; -} +#endif diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp index 91c0d47eea..7b3e9ceb36 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp @@ -67,9 +67,21 @@ /** Constructor. Calls parent constructor to create a 16 bit per pixel D3D texture of the desired height and mip level. */ //============================================================================= -TerrainTextureClass::TerrainTextureClass(int height, MipCountType mipLevelCount) : +TerrainTextureClass::TerrainTextureClass(int height) : TextureClass(TEXTURE_WIDTH, height, - WW3D_FORMAT_A1R5G5B5, mipLevelCount ) + WW3D_FORMAT_A1R5G5B5, MIP_LEVELS_3 ) +{ +} + +//============================================================================= +// TerrainTextureClass::TerrainTextureClass +//============================================================================= +/** Constructor. Calls parent constructor to create a 16 bit per pixel D3D +texture of the desired height and mip level. */ +//============================================================================= +TerrainTextureClass::TerrainTextureClass(int height, int width) : + TextureClass(width, height, + WW3D_FORMAT_A1R5G5B5, MIP_LEVELS_ALL ) { } @@ -92,10 +104,7 @@ int TerrainTextureClass::update(WorldHeightMap *htMap) DX8_ErrorCode(surface_level->GetDesc(&surface_desc)); if (surface_desc.Width < TEXTURE_WIDTH) { surface_level->Release(); - if (surface_desc.Width == 256) { - return update256(htMap); - } - return false; + return 0; } DX8_ErrorCode(surface_level->LockRect(&locked_rect, NULL, 0)); @@ -347,15 +356,24 @@ int TerrainTextureClass::update(WorldHeightMap *htMap) return(surface_desc.Height); } #endif + +//============================================================================= +// TerrainTextureClass::setLOD //============================================================================= -// TerrainTextureClass::update256 +/** Sets the lod of the texture to be loaded into the video card. */ //============================================================================= -/** Sets the tile bitmap data into the texture. Handles the special case for voodoos - and the like where the max texture size is 256. The tiles are placed with 1 +void TerrainTextureClass::setLOD(Int LOD) +{ + if (Peek_D3D_Texture()) Peek_D3D_Texture()->SetLOD(LOD); +} +//============================================================================= +// TerrainTextureClass::update +//============================================================================= +/** Sets the tile bitmap data into the texture. The tiles are placed with 4 pixel borders around them, so that when the tiles are scaled and bilinearly interpolated, you don't get seams between the tiles. */ //============================================================================= -int TerrainTextureClass::update256(WorldHeightMap *htMap) +Bool TerrainTextureClass::updateFlat(WorldHeightMap *htMap, Int xCell, Int yCell, Int cellWidth, Int pixelsPerCell) { // D3DTexture is our texture; @@ -364,149 +382,53 @@ int TerrainTextureClass::update256(WorldHeightMap *htMap) D3DLOCKED_RECT locked_rect; DX8_ErrorCode(Peek_D3D_Texture()->GetSurfaceLevel(0, &surface_level)); DX8_ErrorCode(surface_level->GetDesc(&surface_desc)); - if (surface_desc.Width != 256) { - surface_level->Release(); - return surface_desc.Height; + DEBUG_ASSERTCRASH((Int)surface_desc.Width == cellWidth*pixelsPerCell, ("Bitmap too small.")); + DEBUG_ASSERTCRASH((Int)surface_desc.Height == cellWidth*pixelsPerCell, ("Bitmap too small.")); + if (surface_desc.Width != cellWidth*pixelsPerCell) { + return false; } DX8_ErrorCode(surface_level->LockRect(&locked_rect, NULL, 0)); - Int tilePixelExtent = TILE_PIXEL_EXTENT/4; // We are going from 1024 to 256, so need to divide all the constants by 4. - Int tileOffset = TILE_OFFSET/4; - Int tilesPerRow = surface_desc.Width/(2*tilePixelExtent+tileOffset); - tilesPerRow *= 2; - Int numRows = surface_desc.Height/(tilePixelExtent+tileOffset); -#ifdef RTS_DEBUG - assert(tilesPerRow*numRows >= htMap->m_numBitmapTiles); - assert((Int)surface_desc.Width >= tilePixelExtent*tilesPerRow); -#endif if (surface_desc.Format == D3DFMT_A1R5G5B5) { + + Int pixelBytes = 2; Int cellX, cellY; #if 0 - for (cellX = 0; cellX < surface_desc.Width; cellX++) { - for (cellY = 0; cellY < surface_desc.Height; cellY++) { - UnsignedByte *pBGR = ((UnsignedByte *)locked_rect.pBits)+(cellY*surface_desc.Width+cellX)*2; - *((Short*)pBGR) = (((255-2*cellY)>>3)<<10) + ((4*cellX)>>4); + UnsignedInt X, Y; + for (X = 0; X < surface_desc.Width; X++) { + for (Y = 0; Y < surface_desc.Height; Y++) { + UnsignedByte *pBGR = ((UnsignedByte *)locked_rect.pBits)+(Y*surface_desc.Width+X)*pixelBytes; + *((Short*)pBGR) = (((255-2*Y)>>3)<<10) + ((2*X)>>4); } } - numRows = 0; -#endif - Int pixelBytes = 2; - for (cellY = 0; cellY < numRows; cellY++) { - for (cellX = 0; cellX < tilesPerRow; cellX++) { - Int tileNdx = cellX/2 + (tilesPerRow/2)*(cellY/2); - tileNdx *=4; - if (cellX&1) tileNdx++; - if (!(cellY&1)) tileNdx += 2; -#if ADD_EXTRA_TILES // Fills in an extra 2 columns and 1 row of tiles if there is room. - if (!htMap->getSourceTile(tileNdx) && htMap->getSourceTile(tileNdx-4)) { - tileNdx -= 4; - } - if (!htMap->getSourceTile(tileNdx) && htMap->getSourceTile(tileNdx-8)) { - tileNdx -= 8; - } - if (!htMap->getSourceTile(tileNdx) && htMap->getSourceTile(tileNdx-2*tilesPerRow)) { - tileNdx -= 2*tilesPerRow; - } #endif - if (htMap->getSourceTile(tileNdx)) { - Int i,j; - for (j=0; jgetSourceTile(tileNdx)->getRGBDataForWidth(tilePixelExtent); - pBGR += (tilePixelExtent-1-j)*TILE_BYTES_PER_PIXEL*tilePixelExtent; // invert to match. - Int row = cellY*tilePixelExtent+j; - row += tileOffset/2; - row += tileOffset*(cellY/2); - UnsignedByte *pBGRX = ((UnsignedByte*)locked_rect.pBits) + - (row)*surface_desc.Width*pixelBytes; - - Int column = cellX*tilePixelExtent; - column += tileOffset*(cellX/2); - pBGRX += column*pixelBytes; - pBGRX += (tileOffset/2)*pixelBytes; - for (i=0; i>3)<<10) + ((pBGR[1]>>3)<<5) + (pBGR[0]>>3); - pBGRX +=pixelBytes; - pBGR +=TILE_BYTES_PER_PIXEL; - } - } - - } - } - - } - - for (cellY = 0; cellY < numRows; cellY++) { - for (cellX = 0; cellX < tilesPerRow; cellX++) { - // Duplicate 1 rows of pixels before and after. - Int j; - for (j=0; jgetPointerToTileData(xCell+cellX, yCell+cellY, pixelsPerCell); + if (pBGR == NULL) continue; // past end of defined terrain. [3/24/2003] + Int k, l; + for (k=pixelsPerCell-1; k>=0; k--) { + UnsignedByte *pBGRX = pBGRX_data + (pixelsPerCell*(cellWidth-cellY-1)+k)*surface_desc.Width*pixelBytes + + cellX*pixelsPerCell*pixelBytes; + for (l=0; l>3)<<10) + ((pBGR[1]>>3)<<5) + (pBGR[0]>>3); + pBGRX +=pixelBytes; + pBGR +=TILE_BYTES_PER_PIXEL; } } } } - for (cellY = 0; cellY < numRows; cellY++) { - Int rowBytes = surface_desc.Width*pixelBytes; - Int row = cellY*tilePixelExtent; - row += tileOffset/2; - row += tileOffset*(cellY/2); - if ( (cellY&1) == 0) { - UnsignedByte *pBGRX = ((UnsignedByte*)locked_rect.pBits) + - (row)*rowBytes; - row += 2*tilePixelExtent; - UnsignedByte *pBase = ((UnsignedByte*)locked_rect.pBits) + - (row)*rowBytes; - memcpy(pBGRX-rowBytes, pBase-rowBytes, rowBytes); - } else { - UnsignedByte *pBase = ((UnsignedByte*)locked_rect.pBits) + - (row-tilePixelExtent)*rowBytes; - row += tilePixelExtent; - UnsignedByte *pBGRX = ((UnsignedByte*)locked_rect.pBits) + - (row)*rowBytes; - memcpy(pBGRX, pBase, rowBytes); - } - } - } + surface_level->UnlockRect(); surface_level->Release(); 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. - return(surface_desc.Height*4); + return(surface_desc.Height); } - //============================================================================= // TerrainTextureClass::Apply //============================================================================= @@ -517,8 +439,7 @@ void TerrainTextureClass::Apply(unsigned int stage) { // Do the base apply. TextureClass::Apply(stage); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP); +#if 0 // obsolete [4/1/2003] if (TheGlobalData && (TheGlobalData->m_bilinearTerrainTex || TheGlobalData->m_trilinearTerrainTex)) { DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MINFILTER, D3DTEXF_LINEAR); DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MAGFILTER, D3DTEXF_LINEAR); @@ -533,6 +454,8 @@ void TerrainTextureClass::Apply(unsigned int stage) } // Now setup the texture pipeline. if (stage==0) { + DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP); + DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP); DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE ); DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); @@ -544,6 +467,7 @@ void TerrainTextureClass::Apply(unsigned int stage) DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE,false); } +#endif } /****************************************************************************** @@ -726,6 +650,10 @@ void AlphaTerrainTextureClass::Apply(unsigned int stage) LightMapTerrainTextureClass::LightMapTerrainTextureClass(AsciiString name, MipCountType mipLevelCount) : TextureClass(name.isEmpty()?"TSNoiseUrb.tga":name.str(),name.isEmpty()?"TSNoiseUrb.tga":name.str(), mipLevelCount ) { + Get_Filter().Set_Min_Filter(TextureFilterClass::FILTER_TYPE_BEST); + Get_Filter().Set_Mag_Filter(TextureFilterClass::FILTER_TYPE_BEST); + Get_Filter().Set_U_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_REPEAT); + Get_Filter().Set_V_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_REPEAT); } #define STRETCH_FACTOR ((float)(1/(63.0*MAP_XY_FACTOR/2))) /* covers 63/2 tiles */ @@ -746,8 +674,9 @@ yet another set of uv coordinates. //============================================================================= void LightMapTerrainTextureClass::Apply(unsigned int stage) { - // Do the base apply. TextureClass::Apply(stage); +#if 0 // obsolete [4/1/2003] + // Do the base apply. /* previous setup */ if (TheGlobalData && TheGlobalData->m_trilinearTerrainTex) { DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MIPFILTER, D3DTEXF_LINEAR); @@ -804,6 +733,7 @@ void LightMapTerrainTextureClass::Apply(unsigned int stage) DX8Wrapper::Set_DX8_Render_State(D3DRS_SRCBLEND,D3DBLEND_DESTCOLOR); DX8Wrapper::Set_DX8_Render_State(D3DRS_DESTBLEND,D3DBLEND_ZERO); } +#endif } @@ -915,6 +845,7 @@ void AlphaEdgeTextureClass::Apply(unsigned int stage) { // Do the base apply. TextureClass::Apply(stage); +#if 0 // obsolete [4/1/2003] if (TheGlobalData && (TheGlobalData->m_bilinearTerrainTex || TheGlobalData->m_trilinearTerrainTex)) { DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MINFILTER, D3DTEXF_LINEAR); @@ -964,6 +895,7 @@ void AlphaEdgeTextureClass::Apply(unsigned int stage) DX8Wrapper::Set_DX8_Render_State(D3DRS_DESTBLEND,D3DBLEND_ZERO); } +#endif } @@ -1013,6 +945,7 @@ void CloudMapTerrainTextureClass::Apply(unsigned int stage) // Do the base apply. TextureClass::Apply(stage); +#if 0 // obsolete /* previous setup */ if (TheGlobalData && TheGlobalData->m_trilinearTerrainTex) { DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MIPFILTER, D3DTEXF_LINEAR); @@ -1087,6 +1020,7 @@ void CloudMapTerrainTextureClass::Apply(unsigned int stage) DX8Wrapper::_Set_DX8_Transform(D3DTS_TEXTURE1, *((Matrix4x4*)&inv)); } +#endif } //============================================================================= @@ -1156,6 +1090,8 @@ void CloudMapTerrainTextureClass::restore(void) /// @todo - get "EXScorch01.tga" from not hard coded location. ScorchTextureClass::ScorchTextureClass(MipCountType mipLevelCount) : TextureClass("EXScorch01.tga","EXScorch01.tga", mipLevelCount ) +// Hack to disable texture reduction. +// TextureClass("EXScorch01.tga","EXScorch01.tga", mipLevelCount,WW3D_FORMAT_UNKNOWN,true,false) { } diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp index 88b25cd33a..0d79197c64 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp @@ -1161,8 +1161,10 @@ void W3DDisplay::gatherDebugStats( void ) s_sortedPolysSinceLastUpdate = 0; // terrain stats - unibuffer.format( L"3-Way Blends: %d, Shoreline Blends: %d", TheTerrainRenderObject->getNumExtraBlendTiles(), - TheTerrainRenderObject->getNumShoreLineTiles()); + unibuffer.format( L"3-Way Blends: %d/%d, Shoreline Blends: %d/%d", TheTerrainRenderObject->getNumExtraBlendTiles(TRUE), + TheTerrainRenderObject->getNumExtraBlendTiles(FALSE), + TheTerrainRenderObject->getNumShoreLineTiles(TRUE), + TheTerrainRenderObject->getNumShoreLineTiles(FALSE)); m_displayStrings[TerrainStats]->setText( unibuffer ); // misc debug info diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DRoadBuffer.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DRoadBuffer.cpp index 9b538a211e..b8d8db3d90 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DRoadBuffer.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DRoadBuffer.cpp @@ -3177,6 +3177,7 @@ void W3DRoadBuffer::loadRoads() insertCurveSegments(); insertCrossTypeJoins(); preloadRoadsInVertexAndIndexBuffers(); + m_updateBuffers = true; //ticks = ::GetTickCount() - ticks; //char buf[256]; //sprintf(buf, "%d road segs, %d milisec.\n", m_numRoads, ticks); @@ -3197,6 +3198,16 @@ void W3DRoadBuffer::updateLighting(void) } } +//============================================================================= +// W3DRoadBuffer::updateCenter +//============================================================================= +/** Sets the flag to reload the vertex buffer. */ +//============================================================================= +void W3DRoadBuffer::updateCenter(void) +{ + m_updateBuffers = true; +} + //============================================================================= // W3DRoadBuffer::drawRoads //============================================================================= diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp index 1119bea537..754be44e7e 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp @@ -38,8 +38,14 @@ #include "Common/WellKnownKeys.h" #include "Common/TerrainTypes.h" #include "Common/Xfer.h" +#include "Common/UnitTimings.h" //Contains the DO_UNIT_TIMINGS define jba. + #include "GameClient/Drawable.h" +#include "GameClient/ClientRandomValue.h" + #include "GameLogic/Object.h" +#include "GameLogic/GameLogic.h" + #include "W3DDevice/GameClient/W3DScene.h" #include "W3DDevice/GameClient/W3DTerrainVisual.h" #include "W3DDevice/GameClient/WorldHeightMap.h" @@ -49,23 +55,120 @@ #include "W3DDevice/GameClient/W3DTerrainTracks.h" #include "W3DDevice/GameClient/W3DShadow.h" #include "W3DDevice/GameClient/HeightMap.h" +#include "W3DDevice/GameClient/FlatHeightMap.h" +#include "W3DDevice/GameClient/W3DSmudge.h" +#include "W3DDevice/GameClient/Module/W3DModelDraw.h" #include "WW3D2/light.h" #include "WW3D2/rendobj.h" #include "WW3D2/coltype.h" #include "WW3D2/coltest.h" #include "WW3D2/assetmgr.h" -#include "Common/UnitTimings.h" //Contains the DO_UNIT_TIMINGS define jba. + + +class TestSeismicFilter : public SeismicSimulationFilterBase +{ + + virtual SeismicSimStatusCode filterCallback( WorldHeightMapInterfaceClass *heightMap, const SeismicSimulationNode *node ) + { + + + Int life = node->m_life; + + if ( heightMap == NULL ) + return SEISMIC_STATUS_INVALID; + + + if ( life == 0 ) + return SEISMIC_STATUS_ACTIVE; + if ( life < 15 ) + { + // ADD HEIGHT BECAUSE THE EXPLOSION IS PUSHING DIRT UP + + Real magnitude = node->m_magnitude; + + Real offsScalar = magnitude / (Real)life; // real-life, get it? + Int radius = node->m_radius; + Int border = heightMap->getBorderSize(); + Int centerX = node->m_center.x + border ; + Int centerY = node->m_center.y + border ; + + UnsignedInt workspaceWidth = radius*2; + Real *workspace = NEW Real[ sqr(workspaceWidth) ]; + Real *workspaceEnd = workspace + sqr(workspaceWidth); + + + for ( Real *t = workspace; t < workspaceEnd; ++t ) *t = 0.0f;// clear the workspace + + Int x = 0; + for (; x < radius; ++x) + { + for (Int y = 0; y < radius; ++y) + { + + Real distance = sqrt( sqr(x) + sqr(y) );//Pythagoras + + if ( distance < radius ) + { + Real distScalar = cos( ( distance / radius * (PI/2) ) ); + Real height = (offsScalar * distScalar); + + workspace[ (radius + x) + workspaceWidth * (radius + y) ] = height + heightMap->getBilinearSampleSeismicZVelocity( centerX + x, centerY + y ) ;//kaleidoscope + + if ( x != 0 ) // non-zero test prevents cross-shaped double stamp + { + workspace[ (radius - x) + workspaceWidth * (radius + y) ] = height + heightMap->getBilinearSampleSeismicZVelocity( centerX - x, centerY + y ) ; + if ( y != 0 ) + workspace[ (radius - x) + workspaceWidth * (radius - y) ] = height + heightMap->getBilinearSampleSeismicZVelocity( centerX - x, centerY - y ) ; + } + if ( y != 0 ) + workspace[ (radius + x) + workspaceWidth * (radius - y) ] = height + heightMap->getBilinearSampleSeismicZVelocity( centerX + x, centerY - y ) ; + } + } + } + + // stuff the values from the workspace into the heightmap's velocities + for (x = 0; x < workspaceWidth; ++x) + for (Int y = 0; y < workspaceWidth; ++y) + heightMap->setSeismicZVelocity( centerX - radius + x, centerY - radius + y, workspace[ x + workspaceWidth * y ] ); + + delete [] workspace; + + return SEISMIC_STATUS_ACTIVE; + } + else + return SEISMIC_STATUS_ZERO_ENERGY; + } + + virtual Real applyGravityCallback( Real velocityIn ) + { + Real velocityOut = velocityIn; + velocityOut -= 1.5f; + return velocityOut; + } + + +}; +static TestSeismicFilter testSeismicFilter; + + + + //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- W3DTerrainVisual::W3DTerrainVisual() { m_terrainRenderObject = NULL; - m_terrainHeightMap = NULL; m_waterRenderObject = NULL; TheWaterRenderObj = NULL; + m_logicHeightMap = NULL; + +#ifdef DO_SEISMIC_SIMULATIONS + m_clientHeightMap = NULL; +#endif + } //------------------------------------------------------------------------------------------------- @@ -83,10 +186,17 @@ W3DTerrainVisual::~W3DTerrainVisual() delete TheW3DShadowManager; TheW3DShadowManager=NULL; + delete TheSmudgeManager; + TheSmudgeManager=NULL; + REF_PTR_RELEASE( m_waterRenderObject ); TheWaterRenderObj=NULL; REF_PTR_RELEASE( m_terrainRenderObject ); - REF_PTR_RELEASE( m_terrainHeightMap ); + REF_PTR_RELEASE( m_logicHeightMap ); + +#ifdef DO_SEISMIC_SIMULATIONS + REF_PTR_RELEASE( m_clientHeightMap ); +#endif } //------------------------------------------------------------------------------------------------- @@ -117,6 +227,10 @@ void W3DTerrainVisual::init( void ) m_waterRenderObject->init(TheGlobalData->m_waterPositionZ, TheGlobalData->m_waterExtentX, TheGlobalData->m_waterExtentY, W3DDisplay::m_3DScene, (WaterRenderObjClass::WaterType)TheGlobalData->m_waterType); //create a water plane that's 128x128 units m_waterRenderObject->Set_Position(Vector3(TheGlobalData->m_waterPositionX,TheGlobalData->m_waterPositionY,TheGlobalData->m_waterPositionZ)); //place water in world + // create smudge rendering system. + TheSmudgeManager = NEW(W3DSmudgeManager); + TheSmudgeManager->init(); + #ifdef DO_UNIT_TIMINGS #pragma MESSAGE("********************* WARNING- Doing UNIT TIMINGS. ") #else @@ -156,6 +270,10 @@ void W3DTerrainVisual::init( void ) TheGlobalData->m_vertexWaterAttenuationRange[ waterSettingIndex ] ); m_isWaterGridRenderingEnabled = FALSE; +#ifdef DO_SEISMIC_SIMULATIONS + m_seismicSimulationList.clear(); +#endif + } //------------------------------------------------------------------------------------------------- @@ -172,6 +290,9 @@ void W3DTerrainVisual::reset( void ) if (TheW3DShadowManager) TheW3DShadowManager->Reset(); + if (TheSmudgeManager) + TheSmudgeManager->reset(); + if (TheTerrainTracksRenderObjClassSystem) TheTerrainTracksRenderObjClassSystem->Reset(); @@ -191,6 +312,10 @@ void W3DTerrainVisual::reset( void ) m_waterRenderObject->reset(); } +#ifdef DO_SEISMIC_SIMULATIONS + m_seismicSimulationList.clear(); +#endif + } //------------------------------------------------------------------------------------------------- @@ -202,12 +327,187 @@ void W3DTerrainVisual::update( void ) // extend TerrainVisual::update(); +#ifdef DO_SEISMIC_SIMULATIONS + handleSeismicSimulations(); +#endif // if we have a water render object, it has an update method if( m_waterRenderObject ) m_waterRenderObject->update(); } + +#ifdef DO_SEISMIC_SIMULATIONS + +void W3DTerrainVisual::addSeismicSimulation( const SeismicSimulationNode& sim ) +{ + // HERE WOULD BE A GREAT PLACE FOR AN IDIOT TEST: + // REJECT SIMULATION NODES THAT ARE OFF SCREEN!!!!!!!!!! + // HERE WOULD BE A GREAT PLACE FOR AN IDIOT TEST: + // REJECT SIMULATION NODES THAT ARE OFF SCREEN!!!!!!!!!! + + + m_seismicSimulationList.push_back( sim ); +} + + + +void W3DTerrainVisual::handleSeismicSimulations( void ) +{ + if ( ! m_clientHeightMap || ! m_logicHeightMap || ! m_terrainRenderObject ) + return; + + + if ( ! m_seismicSimulationList.empty() ) + { + SeismicSimulationListIt it = m_seismicSimulationList.begin(); + + + m_clientHeightMap->clearSeismicUpdateFlags(); + + + while ( it != m_seismicSimulationList.end() ) + { + SeismicSimulationNode *ssn = &*it; + + if ( ssn ) + { + SeismicSimulationFilterBase::SeismicSimStatusCode code = ssn->handleFilterCallback( m_clientHeightMap ); + DEBUG_ASSERTCRASH( code != SeismicSimulationFilterBase::SEISMIC_STATUS_INVALID, ("Trouble in the Seismic simulator.") ); + + switch ( code ) + { + case SeismicSimulationFilterBase::SEISMIC_STATUS_ACTIVE: + { + break; + } + case SeismicSimulationFilterBase::SEISMIC_STATUS_ZERO_ENERGY: + { + break; + } + } + + Int border = m_clientHeightMap->getBorderSizeInline(); + + // Now we apply some gravity to the dirt, so it falls back to its "original" height + UnsignedInt fallCount = 0; + for (Int x = border+ssn->m_region.lo.x; x < border+ssn->m_region.hi.x; ++x) + { + for (Int y = border+ssn->m_region.lo.y; y < border+ssn->m_region.hi.y; ++y) + { + if ( ! m_clientHeightMap->getSeismicUpdateFlag( x, y ) ) + { + UnsignedByte heightOfOriginal = m_logicHeightMap->getHeight( x, y ); // LOGIC, YES DEFINITELY THE LOGIC + + Real oldSpeed = m_clientHeightMap->getSeismicZVelocity( x, y ); + Real newSpeed = ssn->applyGravity( oldSpeed );// - 0.5f; + + m_clientHeightMap->setSeismicZVelocity( x, y, newSpeed ); + + Int heightToUse = m_clientHeightMap->getHeight( x, y ) + newSpeed ; + + + if (heightToUse <= heightOfOriginal) + { + heightToUse = heightOfOriginal; + m_clientHeightMap->setSeismicZVelocity( x, y, 0.0f ); //poof! the dirt hit ground level so stop "falling" + } + else + { + ++fallCount; + + if ( heightToUse > 255 ) + heightToUse = 255; + + } + m_clientHeightMap->setRawHeight( x, y, heightToUse ); + m_clientHeightMap->setSeismicUpdateFlag( x, y, TRUE ); + } + + } + } + + if ( fallCount == 0 ) + ssn->m_clean = TRUE; + + } + + ++it; + + } + } + +} + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +void W3DTerrainVisual::updateSeismicSimulations( void ) +{ + + if (m_logicHeightMap==NULL) + return; + + if (m_clientHeightMap==NULL) + return; + + if (m_terrainRenderObject==NULL) + return; + + if ( ! m_seismicSimulationList.empty() ) + { + SeismicSimulationListIt it = m_seismicSimulationList.begin(); + + // First we run through the list and do our business for each region + + while ( it != m_seismicSimulationList.end() ) + { + SeismicSimulationNode *hur = &*it; + if ( hur ) + { + Int border = m_clientHeightMap->getBorderSizeInline(); + + TheTerrainRenderObject->updateBlock( + hur->m_region.lo.x + border, + hur->m_region.lo.y + border, + hur->m_region.hi.x + border, + hur->m_region.hi.y + border, + m_clientHeightMap, + 0); + } + + ++it; + + } + // Then we check to see if these need to get erased from the list + it = m_seismicSimulationList.begin(); + while ( it != m_seismicSimulationList.end() ) + { + SeismicSimulationNode *hur = &*it; + if ( hur->m_clean ) + { + it = m_seismicSimulationList.erase( it ); + } + else + ++it; + + } + + } +} + + +#endif //#defined DO_SEISMIC_SIMULATIONS + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + + //------------------------------------------------------------------------------------------------- /** load method for W3D visual terrain */ //------------------------------------------------------------------------------------------------- @@ -251,10 +551,23 @@ Bool W3DTerrainVisual::load( AsciiString filename ) if( m_terrainRenderObject == NULL ) return FALSE; - REF_PTR_RELEASE( m_terrainHeightMap ); - ChunkInputStream *pStrm = &fileStrm; - // allocate new height map data to read from file - m_terrainHeightMap = NEW WorldHeightMap(pStrm); + + ChunkInputStream *pStrm = &fileStrm; + + // allocate new height map data to read from file + REF_PTR_RELEASE( m_logicHeightMap ); + m_logicHeightMap = NEW WorldHeightMap(pStrm); + +#ifdef DO_SEISMIC_SIMULATIONS + + fileStrm.close(); + fileStrm.open(filename); + pStrm = &fileStrm; + + REF_PTR_RELEASE( m_clientHeightMap ); + m_clientHeightMap = NEW WorldHeightMap( pStrm ); + +#endif // Add any lights loaded by map. MapObject *pMapObj = MapObject::getFirstMapObject(); @@ -291,10 +604,20 @@ Bool W3DTerrainVisual::load( AsciiString filename ) RefRenderObjListIterator *it = W3DDisplay::m_3DScene ? W3DDisplay::m_3DScene->createLightsIterator() : NULL; // apply the heightmap to the terrain render object - m_terrainRenderObject->initHeightData( m_terrainHeightMap->getDrawWidth(), - m_terrainHeightMap->getDrawHeight(), - m_terrainHeightMap, + +#ifdef DO_SEISMIC_SIMULATIONS + m_terrainRenderObject->initHeightData( m_clientHeightMap->getDrawWidth(), + m_clientHeightMap->getDrawHeight(), + m_clientHeightMap, it); +#else + m_terrainRenderObject->initHeightData( m_logicHeightMap->getDrawWidth(), + m_logicHeightMap->getDrawHeight(), + m_logicHeightMap, + it); +#endif + + if (it) { W3DDisplay::m_3DScene->destroyLightsIterator(it); it = NULL; @@ -320,6 +643,7 @@ Bool W3DTerrainVisual::load( AsciiString filename ) { W3DDisplay::m_3DScene->Add_Render_Object( m_waterRenderObject); m_waterRenderObject->enableWaterGrid(false); + m_waterRenderObject->updateMapOverrides(); } #endif @@ -405,8 +729,13 @@ Bool W3DTerrainVisual::intersectTerrain( Coord3D *rayStart, void W3DTerrainVisual::getTerrainColorAt( Real x, Real y, RGBColor *pColor ) { - if( m_terrainHeightMap ) - m_terrainHeightMap->getTerrainColorAt( x, y, pColor ); +#ifdef DO_SEISMIC_SIMULATIONS + if( m_clientHeightMap ) + m_clientHeightMap->getTerrainColorAt( x, y, pColor ); +#else + if( m_logicHeightMap ) + m_logicHeightMap->getTerrainColorAt( x, y, pColor ); +#endif } @@ -416,16 +745,21 @@ TerrainType *W3DTerrainVisual::getTerrainTile( Real x, Real y ) { TerrainType *tile = NULL; - if( m_terrainHeightMap ) +#ifdef DO_SEISMIC_SIMULATIONS + if( m_clientHeightMap ) { - AsciiString tileName = m_terrainHeightMap->getTerrainNameAt( x, y ); - + AsciiString tileName = m_clientHeightMap->getTerrainNameAt( x, y ); tile = TheTerrainTypes->findTerrain( tileName ); - } +#else + if( m_logicHeightMap ) + { + AsciiString tileName = m_logicHeightMap->getTerrainNameAt( x, y ); + tile = TheTerrainTypes->findTerrain( tileName ); + } +#endif return tile; - } // ------------------------------------------------------------------------------------------------ @@ -551,23 +885,59 @@ Bool W3DTerrainVisual::getWaterGridHeight( Real worldX, Real worldY, Real *heigh // ------------------------------------------------------------------------------------------------ void W3DTerrainVisual::setRawMapHeight(const ICoord2D *gridPos, Int height) { - if (m_terrainHeightMap) { - Int x = gridPos->x+m_terrainHeightMap->getBorderSize(); - Int y = gridPos->y+m_terrainHeightMap->getBorderSize(); - //if (m_terrainHeightMap->getHeight(x,y) != height) //ML changed to prevent scissoring with roads - if (m_terrainHeightMap->getHeight(x,y) > height) + // This method writes to the m_logicHeightMap member, + // since m_logicHeightMap is the true, golden standard to which m_clientHeightMap + // interpolates during or after its Seismic simulation displaces it.. + // THIS IS TRUE ONLY WHEN DO_SEISMIC_SIMULATIONS is defined M Lorenzen, 8/23/03 + + if (m_logicHeightMap) + { + Int x = gridPos->x+m_logicHeightMap->getBorderSizeInline(); + Int y = gridPos->y+m_logicHeightMap->getBorderSizeInline(); + //if (m_logicHeightMap->getHeight(x,y) != height) //ML changed to prevent scissoring with roads + if (m_logicHeightMap->getHeight(x,y) > height) { - m_terrainHeightMap->setRawHeight(x, y, height); - m_terrainRenderObject->staticLightingChanged(); + m_logicHeightMap->setRawHeight(x, y, height); + m_terrainRenderObject->staticLightingChanged(); // OOH! this could benefit from the new Seismic update code + + +#ifdef DO_SEISMIC_SIMULATIONS + if ( m_clientHeightMap ) + { + if ( height < m_clientHeightMap->getHeight( x,y ) ) + m_clientHeightMap->setRawHeight( x, y, height ); // if the client map is heigher than this height, it will fall down to it anyway! + } +#endif + } } } +// ------------------------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------------------------ +Int W3DTerrainVisual::getRawMapHeight(const ICoord2D *gridPos) +{ + if (m_logicHeightMap) + { + Int x = gridPos->x+m_logicHeightMap->getBorderSizeInline(); + Int y = gridPos->y+m_logicHeightMap->getBorderSizeInline(); + //if (m_logicHeightMap->getHeight(x,y) != height) //ML changed to prevent scissoring with roads + return m_logicHeightMap->getHeight(x,y) ; + } + return 0; + +} + // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ void W3DTerrainVisual::addFactionBibDrawable(Drawable *factionBuilding, Bool highlight, Real extra) { - if (m_terrainHeightMap) { +#ifdef DO_SEISMIC_SIMULATIONS + if (m_clientHeightMap) +#else + if (m_logicHeightMap) +#endif + { const Matrix3D * mtx = factionBuilding->getTransformMatrix(); Vector3 corners[4]; Coord3D pos; @@ -604,7 +974,12 @@ void W3DTerrainVisual::addFactionBibDrawable(Drawable *factionBuilding, Bool hig // ------------------------------------------------------------------------------------------------ void W3DTerrainVisual::addFactionBib(Object *factionBuilding, Bool highlight, Real extra) { - if (m_terrainHeightMap) { +#ifdef DO_SEISMIC_SIMULATIONS + if (m_clientHeightMap) +#else + if (m_logicHeightMap) +#endif + { const Matrix3D * mtx = factionBuilding->getTransformMatrix(); Vector3 corners[4]; Coord3D pos; @@ -641,7 +1016,7 @@ void W3DTerrainVisual::addFactionBib(Object *factionBuilding, Bool highlight, Re // ------------------------------------------------------------------------------------------------ void W3DTerrainVisual::removeFactionBibDrawable(Drawable *factionBuilding) { - if (m_terrainHeightMap) { + if (m_terrainRenderObject) { m_terrainRenderObject->removeTerrainBibDrawable(factionBuilding->getID()); } } @@ -650,7 +1025,7 @@ void W3DTerrainVisual::removeFactionBibDrawable(Drawable *factionBuilding) // ------------------------------------------------------------------------------------------------ void W3DTerrainVisual::removeFactionBib(Object *factionBuilding) { - if (m_terrainHeightMap) { + if (m_terrainRenderObject) { m_terrainRenderObject->removeTerrainBib(factionBuilding->getID()); } } @@ -659,7 +1034,7 @@ void W3DTerrainVisual::removeFactionBib(Object *factionBuilding) // ------------------------------------------------------------------------------------------------ void W3DTerrainVisual::removeAllBibs(void) { - if (m_terrainHeightMap) { + if (m_terrainRenderObject) { m_terrainRenderObject->removeAllTerrainBibs(); } } @@ -668,11 +1043,53 @@ void W3DTerrainVisual::removeAllBibs(void) // ------------------------------------------------------------------------------------------------ void W3DTerrainVisual::removeBibHighlighting(void) { - if (m_terrainHeightMap) { + if (m_terrainRenderObject) { m_terrainRenderObject->removeTerrainBibHighlighting(); } } +// ------------------------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------------------------ +void W3DTerrainVisual::removeTreesAndPropsForConstruction(const Coord3D* pos, + const GeometryInfo& geom, + Real angle) +{ + if (m_terrainRenderObject) { + m_terrainRenderObject->removeTreesAndPropsForConstruction(pos, geom, angle); + } +} + +// ------------------------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------------------------ +void W3DTerrainVisual::addProp(const ThingTemplate *tTemplate, const Coord3D *pos, Real angle) +{ + ModelConditionFlags state; + state.clear(); + if (TheGlobalData->m_weather == WEATHER_SNOWY) + { + state.set(MODELCONDITION_SNOW); + } + if (TheGlobalData->m_timeOfDay == TIME_OF_DAY_NIGHT) + { + state.set(MODELCONDITION_NIGHT); + } + AsciiString modelName; + Real scale = tTemplate->getAssetScale(); + const ModuleInfo& mi = tTemplate->getDrawModuleInfo(); + if (mi.getCount() > 0) + { + const ModuleData* mdd = mi.getNthData(0); + const W3DModelDrawModuleData* md = mdd ? mdd->getAsW3DModelDrawModuleData() : NULL; + if (md) + { + modelName = md->getBestModelNameForWB(state); + } + } + if (m_terrainRenderObject && modelName.isNotEmpty()) { + m_terrainRenderObject->addProp(1, *pos, angle, scale, modelName); + } +} + // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ void W3DTerrainVisual::setTerrainTracksDetail(void) @@ -726,13 +1143,20 @@ void W3DTerrainVisual::crc( Xfer *xfer ) // ------------------------------------------------------------------------------------------------ /** Xfer * Version Info: - * 1: Initial version */ + * 1: Initial version + * 2: Add height map heights. + * 3: Add client side trees & props. jba. (Added for Zero Hour) +*/ // ------------------------------------------------------------------------------------------------ void W3DTerrainVisual::xfer( Xfer *xfer ) { // version +#if RTS_GENERALS && RETAIL_COMPATIBLE_XFER_SAVE XferVersion currentVersion = 2; +#else + XferVersion currentVersion = 3; +#endif XferVersion version = currentVersion; xfer->xferVersion( &version, currentVersion ); @@ -786,8 +1210,8 @@ void W3DTerrainVisual::xfer( Xfer *xfer ) // Write out the terrain height data. if (version >= 2) { - UnsignedByte *data = m_terrainHeightMap->getDataPtr(); - Int len = m_terrainHeightMap->getXExtent()*m_terrainHeightMap->getYExtent(); + UnsignedByte *data = m_logicHeightMap->getDataPtr(); + Int len = m_logicHeightMap->getXExtent()*m_logicHeightMap->getYExtent(); Int xferLen = len; xfer->xferInt(&xferLen); if (len!=xferLen) { @@ -797,12 +1221,31 @@ void W3DTerrainVisual::xfer( Xfer *xfer ) } } xfer->xferUser(data, len); - if (xfer->getXferMode() == XFER_LOAD) { + if (xfer->getXferMode() == XFER_LOAD) + { // Update the display height map. m_terrainRenderObject->staticLightingChanged(); } } + if (version >= 3) { + xfer->xferSnapshot(m_terrainRenderObject); + } + + // XFER // + // X R // + // X R // + // XFER // + ///// /USE CLIENT HEIGHT MAPCLIENT HEIGHT MAP +// // /USE CLIENT HEIGHT MAPCLIENT HEIGHT MAP +// ////USE CLIENT HEIGHT MAPCLIENT HEIGHT MAP---------------------------- +// // /USE CLIENT HEIGHT MAPCLIENT HEIGHT MAP ^ + ///// /USE CLIENT HEIGHT MAPCLIENT HEIGHT MAP 0 + // XFER // + // X R // + // X R // + // XFER // + } // ------------------------------------------------------------------------------------------------ diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp index b609f4dde5..294e6db54a 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp @@ -42,6 +42,15 @@ // //----------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------ +/** Topple options */ +// ------------------------------------------------------------------------------------------------ +enum +{ + W3D_TOPPLE_OPTIONS_NONE = 0x00000000, + W3D_TOPPLE_OPTIONS_NO_BOUNCE = 0x00000001, ///< do not bounce when hit the ground + W3D_TOPPLE_OPTIONS_NO_FX = 0x00000002 ///< do not play any FX when hit the ground +}; //----------------------------------------------------------------------------- // Includes //----------------------------------------------------------------------------- @@ -49,29 +58,214 @@ #include #include +#include "Common/FramePacer.h" #include "Common/GameUtility.h" -#include "Common/GlobalData.h" +#include "Common/MapReaderWriterInfo.h" +#include "Common/FileSystem.h" +#include "Common/file.h" +#include "Common/PerfTimer.h" +#include "Common/Player.h" +#include "Common/PlayerList.h" +#include "GameLogic/ScriptEngine.h" +#include "GameLogic/GameLogic.h" +#include "GameLogic/Object.h" +#include "GameLogic/PartitionManager.h" #include "GameClient/ClientRandomValue.h" +#include "GameClient/FXList.h" #include "W3DDevice/GameClient/TerrainTex.h" #include "W3DDevice/GameClient/HeightMap.h" #include "W3DDevice/GameClient/W3DDynamicLight.h" +#include "W3DDevice/GameClient/Module/W3DTreeDraw.h" +#include "W3DDevice/GameClient/W3DShaderManager.h" +#include "W3DDevice/GameClient/W3DShadow.h" +#include "W3DDevice/GameClient/W3DShroud.h" +#include "W3DDevice/GameClient/W3DProjectedShadow.h" #include "WW3D2/camera.h" #include "WW3D2/dx8wrapper.h" #include "WW3D2/dx8renderer.h" +#include "WW3D2/matinfo.h" #include "WW3D2/mesh.h" #include "WW3D2/meshmdl.h" +#include "d3dx8tex.h" + + +// If TEST_AND_BLEND is defined, it will do an alpha test and blend. Otherwise just alpha test. jba. [5/30/2003] +#define dontTEST_AND_BLEND 1 + +#define USE_STATIC 1 + +#define END_OF_PARTITION (-1) + +#define DELETED_TREE_TYPE (-2) + +/****************************************************************************** + W3DTreeTextureClass +******************************************************************************/ +//----------------------------------------------------------------------------- +// Public Functions +//----------------------------------------------------------------------------- + +//============================================================================= +// W3DTreeBuffer::W3DTreeTextureClass::W3DTreeTextureClass +//============================================================================= +/** Constructor. Calls parent constructor to create a 16 bit per pixel D3D +texture of the desired height and mip level. */ +//============================================================================= +W3DTreeBuffer::W3DTreeTextureClass::W3DTreeTextureClass(unsigned width, unsigned height) : + TextureClass(width, height, + WW3D_FORMAT_A8R8G8B8, MIP_LEVELS_ALL ) +{ +} + +//============================================================================= +// W3DTreeBuffer::W3DTreeTextureClass::update +//============================================================================= +/** Sets the tile bitmap data into the texture. The tiles are placed with 4 + pixel borders around them, so that when the tiles are scaled and bilinearly + interpolated, you don't get seams between the tiles. */ +//============================================================================= +int W3DTreeBuffer::W3DTreeTextureClass::update(W3DTreeBuffer *buffer) +{ + + //Set to clamp. + Get_Filter().Set_U_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); + Get_Filter().Set_V_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); + + IDirect3DSurface8 *surface_level; + D3DSURFACE_DESC surface_desc; + D3DLOCKED_RECT locked_rect; + DX8_ErrorCode(Peek_D3D_Texture()->GetSurfaceLevel(0, &surface_level)); + DX8_ErrorCode(surface_level->GetDesc(&surface_desc)); + + DX8_ErrorCode(surface_level->LockRect(&locked_rect, NULL, 0)); + + Int tilePixelExtent = TILE_PIXEL_EXTENT; +// Int numRows = surface_desc.Height/(tilePixelExtent+TILE_OFFSET); +#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 + if (surface_desc.Format == D3DFMT_A8R8G8B8) { + Int tileNdx; + Int pixelBytes = 4; +#if 0 // Fill unused texture for debug display. + UnsignedInt cellX, cellY; + for (cellX = 0; cellX < surface_desc.Width; cellX++) { + for (cellY = 0; cellY < surface_desc.Height; cellY++) { + UnsignedByte *pBGR = ((UnsignedByte *)locked_rect.pBits)+(cellY*surface_desc.Width+cellX)*pixelBytes; + //*((Short*)pBGR) = 0x8000 + (((255-2*cellY)>>3)<<10) + ((4*cellX)>>4); + *((Int*)pBGR) = 0xFF000000 | ( (((255-cellY))<<16) + ((cellX)) ); + + } + } +#endif + for (tileNdx=0; tileNdx < buffer->getNumTiles(); tileNdx++) { + TileData *pTile = buffer->getSourceTile(tileNdx); + if (!pTile) continue; + ICoord2D position = pTile->m_tileLocationInTexture; + if (position.x<0) { + continue; + } + Int i,j; + for (j=0; jgetRGBDataForWidth(tilePixelExtent); + pBGR += (tilePixelExtent-(1+j))*TILE_BYTES_PER_PIXEL*tilePixelExtent; // invert to match. + Int row = position.y+j; + UnsignedByte *pBGRA = ((UnsignedByte*)locked_rect.pBits) + + (row)*surface_desc.Width*pixelBytes; + + Int column = position.x; + pBGRA += column*pixelBytes; + for (i=0; i>3)<<10) + ((pBGR[1]>>3)<<5) + (pBGR[0]>>3); + *((Int *)pBGRA) = (pBGR[3]<<24) + (pBGR[2]<<16) + (pBGR[1]<<8) + (pBGR[0]); + pBGRA +=pixelBytes; + pBGR +=TILE_BYTES_PER_PIXEL; + } + } + } + + } + DX8_ErrorCode(surface_level->UnlockRect()); + surface_level->Release(); + DX8_ErrorCode(D3DXFilterTexture(Peek_D3D_Texture(), NULL, (UINT)0, D3DX_FILTER_BOX)); + if (WW3D::Get_Texture_Reduction()) { + DX8_ErrorCode(Peek_D3D_Texture()->SetLOD((DWORD)WW3D::Get_Texture_Reduction())); + } + return(surface_desc.Height); +} + +//============================================================================= +// W3DTreeBuffer::W3DTreeTextureClass::setLOD +//============================================================================= +/** Sets the lod of the texture to be loaded into the video card. */ +//============================================================================= +void W3DTreeBuffer::W3DTreeTextureClass::setLOD(Int LOD) const +{ + if (Peek_D3D_Texture()) { + DX8_ErrorCode(Peek_D3D_Texture()->SetLOD((DWORD)LOD)); + } +} +//============================================================================= +// W3DTreeBuffer::W3DTreeTextureClass::Apply +//============================================================================= +/** Sets the texture as the current D3D texture, and does some custom setup +(standard D3D setup, but beyond the scope of W3D). */ +//============================================================================= +void W3DTreeBuffer::W3DTreeTextureClass::Apply(unsigned int stage) +{ + // Do the base apply. + TextureClass::Apply(stage); +} //----------------------------------------------------------------------------- // Private Data //----------------------------------------------------------------------------- + +#ifdef TEST_AND_BLEND // A W3D shader that does alpha, texturing, tests zbuffer, doesn't update zbuffer. -#define SC_ALPHA_DETAIL ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_DISABLE, ShaderClass::COLOR_WRITE_ENABLE, ShaderClass::SRCBLEND_SRC_ALPHA, \ +#define SC_ALPHA_DETAIL ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_ENABLE, ShaderClass::COLOR_WRITE_ENABLE, ShaderClass::SRCBLEND_SRC_ALPHA, \ ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE, ShaderClass::SECONDARY_GRADIENT_DISABLE, ShaderClass::TEXTURING_ENABLE, \ - ShaderClass::ALPHATEST_DISABLE, ShaderClass::CULL_MODE_DISABLE, \ + ShaderClass::ALPHATEST_ENABLE, ShaderClass::CULL_MODE_ENABLE, \ + ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE) ) + +#define SC_ALPHA_DETAIL_2X ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_ENABLE, ShaderClass::COLOR_WRITE_ENABLE, ShaderClass::SRCBLEND_SRC_ALPHA, \ + ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE2X, ShaderClass::SECONDARY_GRADIENT_DISABLE, ShaderClass::TEXTURING_ENABLE, \ + ShaderClass::ALPHATEST_ENABLE, ShaderClass::CULL_MODE_ENABLE, \ + ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE) ) + +#else +#define SC_ALPHA_DETAIL ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_ENABLE, ShaderClass::COLOR_WRITE_ENABLE, ShaderClass::SRCBLEND_ONE, \ + ShaderClass::DSTBLEND_ZERO, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE, ShaderClass::SECONDARY_GRADIENT_DISABLE, ShaderClass::TEXTURING_ENABLE, \ + ShaderClass::ALPHATEST_ENABLE, ShaderClass::CULL_MODE_DISABLE, \ + ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE) ) + +#define SC_ALPHA_DETAIL_2X ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_ENABLE, ShaderClass::COLOR_WRITE_ENABLE, ShaderClass::SRCBLEND_ONE, \ + ShaderClass::DSTBLEND_ZERO, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE2X, ShaderClass::SECONDARY_GRADIENT_DISABLE, ShaderClass::TEXTURING_ENABLE, \ + ShaderClass::ALPHATEST_ENABLE, ShaderClass::CULL_MODE_ENABLE, \ + ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE) ) +#endif +static ShaderClass detailAlphaShader(SC_ALPHA_DETAIL); +static ShaderClass detailAlphaShader2X(SC_ALPHA_DETAIL_2X); + + +/* +#define SC_ALPHA_DETAIL ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_ENABLE, ShaderClass::COLOR_WRITE_ENABLE, ShaderClass::SRCBLEND_ONE, \ + ShaderClass::DSTBLEND_ZERO, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE, ShaderClass::SECONDARY_GRADIENT_DISABLE, ShaderClass::TEXTURING_ENABLE, \ + ShaderClass::ALPHATEST_ENABLE, ShaderClass::CULL_MODE_DISABLE, \ ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE) ) static ShaderClass detailAlphaShader(SC_ALPHA_DETAIL); +*/ + +/* +#define SC_ALPHA_DETAIL ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_DISABLE, ShaderClass::COLOR_WRITE_ENABLE, ShaderClass::SRCBLEND_SRC_ALPHA, \ + ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE, ShaderClass::SECONDARY_GRADIENT_DISABLE, ShaderClass::TEXTURING_ENABLE, \ + ShaderClass::ALPHATEST_ENABLE, ShaderClass::CULL_MODE_ENABLE, \ + ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE) ) +static ShaderClass detailAlphaShader(SC_ALPHA_DETAIL); +*/ /* #define SC_ALPHA_MIRROR ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_DISABLE, ShaderClass::COLOR_WRITE_ENABLE, ShaderClass::SRCBLEND_SRC_ALPHA, \ @@ -99,11 +293,10 @@ ShaderClass ShaderClass::_PresetAlpha2DShader(SC_ALPHA_2D); /** Culls the trees, marking the visible flag. If a tree becomes visible, it sets it's sortKey */ //============================================================================= -void W3DTreeBuffer::cull(CameraClass * camera) +void W3DTreeBuffer::cull(const CameraClass * camera) { Int curTree; - m_anythingChanged = false; // Calulate the vector direction that the camera is looking at. Matrix3D camera_matrix = camera->Get_Transform(); float zmod = -1; @@ -115,7 +308,7 @@ void W3DTreeBuffer::cull(CameraClass * camera) for (curTree=0; curTreeCull_Sphere(m_trees[curTree].bounds); - if (visible!=m_trees[curTree].visible) { + if (visible != m_trees[curTree].visible) { m_trees[curTree].visible=visible; m_anythingChanged = true; if (visible) { @@ -131,30 +324,57 @@ void W3DTreeBuffer::cull(CameraClass * camera) } m_updateAllKeys = false; } - //============================================================================= // W3DTreeBuffer::cullMirror //============================================================================= /** Culls the trees, marking the visible flag for the mirror view. Unlike cull(), doesn't update anything except the visible flag. */ //============================================================================= -void W3DTreeBuffer::cullMirror(CameraClass * camera) +Int W3DTreeBuffer::getPartitionBucket(const Coord3D &pos) const { - Int curTree; - m_anythingChanged = false; - for (curTree=0; curTreem_bounds.hi.x) x = m_bounds.hi.x; + if (y>m_bounds.hi.y) y = m_bounds.hi.y; + Int xIndex = REAL_TO_INT_FLOOR ( (x/(m_bounds.hi.x-m_bounds.lo.x)) * (PARTITION_WIDTH_HEIGHT-0.1f) ); + Int yIndex = REAL_TO_INT_FLOOR ( (y/(m_bounds.hi.y-m_bounds.lo.y)) * (PARTITION_WIDTH_HEIGHT-0.1f) ); + DEBUG_ASSERTCRASH(xIndex>=0 && yIndex>=0 && xIndexCull_Sphere(m_trees[curTree].bounds); - m_trees[curTree].visible=visible; + m_curSwayOffset[i] = 0; + m_curSwayFactor[i] = GameClientRandomValueReal(1.0f-delta, 1.0f+delta); } + m_curSwayVersion = info.m_breezeVersion; } +#if 0 // sort is not used, and messes up the order jba. [6/6/2003] //============================================================================= // W3DTreeBuffer::sort //============================================================================= @@ -191,80 +411,274 @@ void W3DTreeBuffer::sort(Int numIterations) m_anythingChanged = true; } } +#endif + +/********** GDIFileStream2 class ****************************/ +class GDIFileStream2 : public InputStream +{ +protected: + File* m_file; +public: + GDIFileStream2():m_file(NULL) {}; + GDIFileStream2(File* pFile):m_file(pFile) {}; + virtual Int read(void *pData, Int numBytes) { + return(m_file?m_file->read(pData, numBytes):0); + }; +}; + +//============================================================================= +// W3DTreeBuffer::updateTexture +//============================================================================= +/** Creates a new texture. */ +//============================================================================= +void W3DTreeBuffer::updateTexture(void) +{ + + const Int MAX_TEX_WIDTH = 2048; + + Int i, j; + Int maxHeight = 0; + const Int maxTilesPerRow = MAX_TEX_WIDTH/(TILE_PIXEL_EXTENT); + + REF_PTR_RELEASE(m_treeTexture); + + Bool availableGrid[maxTilesPerRow][maxTilesPerRow]; + Int row, column; + for (row=0; rowm_textureName.str() ); + theFile = TheFileSystem->openFile( texturePath, File::READ|File::BINARY); + if (theFile==NULL) { + sprintf( texturePath, "%s%s", TGA_DIR_PATH, m_treeTypes[i].m_data->m_textureName.str() ); + theFile = TheFileSystem->openFile( texturePath, File::READ|File::BINARY); + } + if (theFile != NULL) { + GDIFileStream2 theStream(theFile); + InputStream *pStr = &theStream; + Bool halfTile; + Int numTiles = WorldHeightMap::countTiles(pStr, &halfTile); + Int width; + for (width = 10; width >= 1; width--) { + if (numTiles >= width*width) { + numTiles = width*width; + break; + } + } + Bool texFound = false; + for (j=0; jm_textureName.compareNoCase(m_treeTypes[i].m_data->m_textureName)==0) { + m_treeTypes[i].m_firstTile = 0; + m_treeTypes[i].m_tileWidth = width; + m_treeTypes[i].m_numTiles = 0; + texFound = true; + break; + } + } + if (texFound) { + theFile->close(); + continue; + } + if (m_numTiles+numTiles<=MAX_TILES) { + theFile->seek(0, File::START); + m_treeTypes[i].m_firstTile = m_numTiles; + m_treeTypes[i].m_tileWidth = width; + m_treeTypes[i].m_numTiles = numTiles; + m_treeTypes[i].m_halfTile = halfTile; + WorldHeightMap::readTiles(pStr, m_sourceTiles+m_treeTypes[i].m_firstTile, width); + m_numTiles += numTiles; + } else { + m_treeTypes[i].m_firstTile = 0; + m_treeTypes[i].m_tileWidth = 0; + m_treeTypes[i].m_numTiles = 0; + } + theFile->close(); + } else { + DEBUG_CRASH(("Could not find texture %s", m_treeTypes[i].m_data->m_textureName.str())); + m_treeTypes[i].m_firstTile = 0; + m_treeTypes[i].m_tileWidth = 0; + m_treeTypes[i].m_numTiles = 0; + } + } + + Int tmpWidth = 8; + while (tmpWidth*tmpWidthMAX_TEX_WIDTH) { + m_textureWidth = 64; + m_textureHeight = 64; + if (m_treeTexture==NULL) { + m_treeTexture = new TextureClass("missing.tga"); + } + DEBUG_CRASH(("Too many trees in a scene.")); + return; + } + + for (i=0; im_tileLocationInTexture.x = -1; + m_sourceTiles[i]->m_tileLocationInTexture.y = -1; + } + } + + /* put the tree tiles into the texture */ + Int texClass; + Int tileWidth; + for (tileWidth = tilesPerRow; tileWidth>0; tileWidth--) { + for (texClass=0; texClassm_textureName.compareNoCase(m_treeTypes[texClass].m_data->m_textureName)==0) { + m_treeTypes[texClass].m_textureOrigin.x = m_treeTypes[i].m_textureOrigin.x; + m_treeTypes[texClass].m_textureOrigin.y = m_treeTypes[i].m_textureOrigin.y; + texFound = true; + break; + } + } + if (texFound) { + continue; + } + + // Find an available block of space. + Bool found = false; + for (row=0; row<(tilesPerRow-width)+1 && !found; row++) { + for (column=0; column<(tilesPerRow-width)+1 && !found; column++) { + if (availableGrid[row][column]) { + Bool open = true; + for (i=0; im_tileLocationInTexture.x = x; + m_sourceTiles[baseNdx]->m_tileLocationInTexture.y = y; + } + } + } + } + DEBUG_ASSERTCRASH(maxHeight<=m_textureWidth, ("Bad max height.")); + W3DTreeTextureClass *tex = new W3DTreeTextureClass((DWORD)m_textureWidth, (DWORD)m_textureWidth); + m_textureHeight = tex->update(this); + + m_treeTexture = tex; + + for (i=0; isetLOD(lod); +} //============================================================================= // W3DTreeBuffer::doLighting //============================================================================= /** Calculates the diffuse lighting as affected by dynamic lighting. */ //============================================================================= -Int W3DTreeBuffer::doLighting(Vector3 *loc, Real r, Real g, Real b, SphereClass &bounds, RefRenderObjListIterator *pDynamicLightsIterator) +UnsignedInt W3DTreeBuffer::doLighting(const Vector3 *normal, + const GlobalData::TerrainLighting *objectLighting, + const Vector3 *emissive, UnsignedInt vertDiffuse, Real scale) const { - if (pDynamicLightsIterator == NULL) { - return(REAL_TO_INT(b) | (REAL_TO_INT(g) << 8) | (REAL_TO_INT(r) << 16) | (255 << 24)); - } + Real shadeR, shadeG, shadeB; - shadeR = r; - shadeG = g; - shadeB = b; - Bool didLight = false; - for (pDynamicLightsIterator->First(); !pDynamicLightsIterator->Is_Done(); pDynamicLightsIterator->Next()) - { - W3DDynamicLight *pLight = (W3DDynamicLight*)pDynamicLightsIterator->Peek_Obj(); - if (!pLight->isEnabled()) { - continue; // he is turned off. - } - if (CollisionMath::Overlap_Test(bounds, pLight->Get_Bounding_Sphere()) == CollisionMath::OUTSIDE) { - continue; // this tree is outside of the light's influence. - } - Vector3 lightDirection = *loc; - Real factor; - switch(pLight->Get_Type()) { - case LightClass::POINT: - case LightClass::SPOT: { - Vector3 lightLoc = pLight->Get_Position(); - lightDirection -= lightLoc; - double range, midRange; - pLight->Get_Far_Attenuation_Range(midRange, range); - Real dist = lightDirection.Length(); - if (dist >= range) continue; - if (midRange < 0.1) continue; - factor = 1.0f - (dist - midRange) / (range - midRange); - factor = WWMath::Clamp(factor,0.0f,1.0f); - } - break; - case LightClass::DIRECTIONAL: - pLight->Get_Spot_Direction(lightDirection); - factor = 1.0; - break; - }; - Real shade = 0.5f * factor; // Assume adjustment for diffuse. - Vector3 vDiffuse; - pLight->Get_Diffuse(&vDiffuse); - Vector3 ambient; - pLight->Get_Ambient(&ambient); + Real shade; + shadeR = objectLighting[0].ambient.red+emissive->X; //only the first light contributes to ambient + shadeG = objectLighting[0].ambient.green+emissive->Y; + shadeB = objectLighting[0].ambient.blue+emissive->Z; + + Int i; + for (i=0; i 1.0) shade = 1.0; if(shade < 0.0f) shade = 0.0f; - shadeR += shade*vDiffuse.X; - shadeG += shade*vDiffuse.Y; - shadeB += shade*vDiffuse.Z; - shadeR += factor*ambient.X; - shadeG += factor*ambient.Y; - shadeB += factor*ambient.Z; - didLight = true; - } - if (!didLight) { - return(REAL_TO_INT(b) | (REAL_TO_INT(g) << 8) | (REAL_TO_INT(r) << 16) | (255 << 24)); + shadeR += shade*objectLighting[i].diffuse.red; + shadeG += shade*objectLighting[i].diffuse.green; + shadeB += shade*objectLighting[i].diffuse.blue; } + + shadeR *= scale; + shadeG *= scale; + shadeB *= scale; + if (shadeR > 1.0) shadeR = 1.0; if(shadeR < 0.0f) shadeR = 0.0f; if (shadeG > 1.0) shadeG = 1.0; if(shadeG < 0.0f) shadeG = 0.0f; if (shadeB > 1.0) shadeB = 1.0; if(shadeB < 0.0f) shadeB = 0.0f; + + if (vertDiffuse!=0xFFFFFFFF) { + shade = vertDiffuse&0xff; //blue; + shadeB *= shade/255.0f; + shade = (vertDiffuse>>8)&0xFF; // green; + shadeG *= shade/255.0f; + shade = (vertDiffuse>>16)&0xFF; // red; + shadeR *= shade/255.0f; + } + shadeR*=255.0f; shadeG*=255.0f; shadeB*=255.0f; - return(REAL_TO_INT(shadeB) | (REAL_TO_INT(shadeG) << 8) | (REAL_TO_INT(shadeR) << 16) | (255 << 24)); + const Real alpha = 255.0; + return REAL_TO_UNSIGNEDINT(shadeB) | (REAL_TO_INT(shadeG) << 8) | (REAL_TO_INT(shadeR) << 16) | ((Int)alpha << 24); + } //============================================================================= @@ -274,296 +688,426 @@ Int W3DTreeBuffer::doLighting(Vector3 *loc, Real r, Real g, Real b, SphereClass //============================================================================= void W3DTreeBuffer::loadTreesInVertexAndIndexBuffers(RefRenderObjListIterator *pDynamicLightsIterator) { - if (!m_indexTree || !m_vertexTree || !m_initialized) { + if (!m_indexTree[0] || !m_vertexTree[0] || !m_initialized) { return; } if (!m_anythingChanged) { - //return; - } - m_curNumTreeVertices = 0; - m_curNumTreeIndices = 0; - VertexFormatXYZDUV1 *vb; - UnsignedShort *ib; - // Lock the buffers. - DX8IndexBufferClass::WriteLockClass lockIdxBuffer(m_indexTree); - DX8VertexBufferClass::WriteLockClass lockVtxBuffer(m_vertexTree); - vb=(VertexFormatXYZDUV1*)lockVtxBuffer.Get_Vertex_Array(); - ib = lockIdxBuffer.Get_Index_Array(); - // Add to the index buffer & vertex buffer. - Vector2 lookAtVector(m_cameraLookAtVector.X, m_cameraLookAtVector.Y); - lookAtVector.Normalize(); - // We draw from back to front, so we put the indexes in the buffer - // from back to front. - UnsignedShort *curIb = ib+MAX_TREE_INDEX; - - VertexFormatXYZDUV1 *curVb = vb; + return; + } - Int curTree; + if (m_shadow == NULL && TheW3DProjectedShadowManager) { + Shadow::ShadowTypeInfo shadowInfo; + shadowInfo.m_ShadowName[0] = 0; + shadowInfo.allowUpdates=FALSE; //shadow image will never update + shadowInfo.allowWorldAlign=TRUE; //shadow image will wrap around world objects + shadowInfo.m_type = (ShadowType)SHADOW_DECAL; + shadowInfo.m_sizeX=20; + shadowInfo.m_sizeY=20; + shadowInfo.m_offsetX=0; + shadowInfo.m_offsetY=0; + m_shadow = TheW3DProjectedShadowManager->createDecalShadow(&shadowInfo); + } - // Calculate a static lighting value to use for all the trees. - Real shadeR, shadeG, shadeB; - shadeR = TheGlobalData->m_terrainAmbient[0].red; - shadeG = TheGlobalData->m_terrainAmbient[0].green; - shadeB = TheGlobalData->m_terrainAmbient[0].blue; - shadeR += TheGlobalData->m_terrainDiffuse[0].red; - shadeG += TheGlobalData->m_terrainDiffuse[0].green; - shadeB += TheGlobalData->m_terrainDiffuse[0].blue; - if (shadeR>1.0f) shadeR=1.0f; - if (shadeG>1.0f) shadeG=1.0f; - if (shadeB>1.0f) shadeB=1.0f; - shadeR*=255.0f; - shadeG*=255.0f; - shadeB*=255.0f; + m_anythingChanged = false; + Int curTree=0; + Int bNdx; + const GlobalData::TerrainLighting *objectLighting = TheGlobalData->m_terrainObjectsLighting[TheGlobalData->m_timeOfDay]; + for (bNdx=0; bNdx= m_numTrees) { + break; + } + VertexFormatXYZNDUV1 *vb; + UnsignedShort *ib; + // Lock the buffers. + #ifdef USE_STATIC + DX8IndexBufferClass::WriteLockClass lockIdxBuffer(m_indexTree[bNdx], 0); + DX8VertexBufferClass::WriteLockClass lockVtxBuffer(m_vertexTree[bNdx], 0); + #else + DX8IndexBufferClass::WriteLockClass lockIdxBuffer(m_indexTree[bNdx], D3DLOCK_DISCARD); + DX8VertexBufferClass::WriteLockClass lockVtxBuffer(m_vertexTree[bNdx], D3DLOCK_DISCARD); + #endif + vb=(VertexFormatXYZNDUV1*)lockVtxBuffer.Get_Vertex_Array(); + ib = lockIdxBuffer.Get_Index_Array(); + // Add to the index buffer & vertex buffer. + Vector2 lookAtVector(m_cameraLookAtVector.X, m_cameraLookAtVector.Y); + lookAtVector.Normalize(); + // We draw from back to front, so we put the indexes in the buffer + // from back to front. + UnsignedShort *curIb = ib; - for (curTree=0; curTreeFirst(); !pDynamicLightsIterator->Is_Done(); pDynamicLightsIterator->Next()) - { - W3DDynamicLight *pLight = (W3DDynamicLight*)pDynamicLightsIterator->Peek_Obj(); - if (!pLight->isEnabled()) { - continue; // he is turned off. + + + for ( ;curTreeGet_Bounding_Sphere()) == CollisionMath::OUTSIDE) { - continue; // this tree is outside of the light's influence. + if (!m_trees[curTree].visible) continue; + Real scale = m_trees[curTree].scale; + Vector3 loc = m_trees[curTree].location; + Real theSin = m_trees[curTree].sin; + Real theCos = m_trees[curTree].cos; + if (type<0 || m_treeTypes[type].m_mesh == 0) { + continue; } - doVertexLighting = true; - } -#endif - Int diffuse = 0; - if (!doVertexLighting) { - diffuse = doLighting(&loc, shadeR, shadeG, shadeB, m_trees[curTree].bounds, NULL); - } + Bool doVertexLighting = true; + + #if 0 // no dynamic lighting. + for (pDynamicLightsIterator->First(); !pDynamicLightsIterator->Is_Done(); pDynamicLightsIterator->Next()) + { + W3DDynamicLight *pLight = (W3DDynamicLight*)pDynamicLightsIterator->Peek_Obj(); + if (!pLight->isEnabled()) { + continue; // he is turned off. + } + if (CollisionMath::Overlap_Test(m_trees[curTree].bounds, pLight->Get_Bounding_Sphere()) == CollisionMath::OUTSIDE) { + continue; // this tree is outside of the light's influence. + } + doVertexLighting = true; + } + #endif + Vector3 emissive(0.0f,0.0f,0.0f); + MaterialInfoClass * matInfo = m_treeTypes[type].m_mesh->Get_Material_Info(); + if (matInfo) { + VertexMaterialClass *vertMat = matInfo->Peek_Vertex_Material(0); + if (vertMat) { + vertMat->Get_Emissive(&emissive); + } + } + REF_PTR_RELEASE(matInfo); - Real typeOffset = type*0.5; - Int startVertex = m_curNumTreeVertices; - Int i, j; - Int numVertex = m_typeMesh[type]->Peek_Model()->Get_Vertex_Count(); - Vector3 *pVert = m_typeMesh[type]->Peek_Model()->Get_Vertex_Array(); - // If we happen to have too many trees, stop. - if (m_curNumTreeVertices+numVertex+2>= MAX_TREE_VERTEX) { - break; - } - Int numIndex = m_typeMesh[type]->Get_Model()->Get_Polygon_Count(); - const Vector3i *pPoly = m_typeMesh[type]->Get_Model()->Get_Polygon_Array(); - if (m_curNumTreeIndices+3*numIndex+6 >= MAX_TREE_INDEX) { - break; - } - const Vector2*uvs=m_typeMesh[type]->Get_Model()->Get_UV_Array_By_Index(0); + Int startVertex = m_curNumTreeVertices[bNdx]; + m_trees[curTree].firstIndex = startVertex; + m_trees[curTree].bufferNdx = bNdx; + Int i; + Int numVertex = m_treeTypes[type].m_mesh->Peek_Model()->Get_Vertex_Count(); + Vector3 *pVert = m_treeTypes[type].m_mesh->Peek_Model()->Get_Vertex_Array(); - // If we are doing reduced resolution terrain, do reduced - // poly trees. - Bool doPanel = (TheGlobalData->m_useHalfHeightMap || TheGlobalData->m_stretchTerrain); - if (doPanel) { - if (m_trees[curTree].rotates) { - theSin = -lookAtVector.X; - theCos = lookAtVector.Y; + + // If we happen to have too many trees, stop. + if (m_curNumTreeVertices[bNdx]+numVertex+2>= MAX_TREE_VERTEX) { + break; } - // panel start is index offset, there are 3 index per triangle. - if (m_trees[curTree].panelStart/3 + 2 > numIndex) { - continue; // not enought polygons for the offset. jba. + Int numIndex = m_treeTypes[type].m_mesh->Peek_Model()->Get_Polygon_Count(); + const TriIndex *pPoly = m_treeTypes[type].m_mesh->Peek_Model()->Get_Polygon_Array(); + if (m_curNumTreeIndices[bNdx]+3*numIndex+6 >= MAX_TREE_INDEX) { + break; } - for (j=0; j<6; j++) { - i = ((Int *)pPoly)[j+m_trees[curTree].panelStart]; - if (m_curNumTreeVertices >= MAX_TREE_VERTEX) - break; - // Update the uv values. The W3D models each have their own texture, and - // we use one texture with all images in one, so we have to change the uvs to - // match. - Real U, V; - if (type==SHRUB) { - // shrub texture is tucked in the corner - U = ((512-64)+uvs[i].U*64.0f)/512.0f; - V = ((256-64)+uvs[i].V*64.0f)/256.0f; - } else if (type==FENCE) { - U = uvs[i].U*0.5f; - V = 1.0f + uvs[i].V; - } else { - U = typeOffset+uvs[i].U*0.5f; - V = uvs[i].V; + const Vector2*uvs=m_treeTypes[type].m_mesh->Peek_Model()->Get_UV_Array_By_Index(0); + + const Vector3*normals = m_treeTypes[type].m_mesh->Peek_Model()->Get_Vertex_Normal_Array(); + const unsigned *vecDiffuse = m_treeTypes[type].m_mesh->Peek_Model()->Get_Color_Array(0, false); + + Int diffuse = 0; + if (normals == NULL) { + doVertexLighting = false; + Vector3 normal(0.0f,0.0f,1.0f); + diffuse = doLighting(&normal, objectLighting, &emissive, 0xFFFFFFFF, 1.0f); + } + /* + * + // If we are doing reduced resolution terrain, do reduced + // poly trees. + Bool doPanel = (TheGlobalData->m_useHalfHeightMap || TheGlobalData->m_stretchTerrain); + + if (doPanel) { + if (m_trees[curTree].rotates) { + theSin = -lookAtVector.X; + theCos = lookAtVector.Y; } - curVb->u1 = U; - curVb->v1 = V/2.0; - Vector3 vLoc; - vLoc.X = pVert[i].X*scale*theCos - pVert[i].Z*scale*theSin; - vLoc.Y = pVert[i].Z*scale*theCos + pVert[i].X*scale*theSin; + // panel start is index offset, there are 3 index per triangle. + if (m_trees[curTree].panelStart/3 + 2 > numIndex) { + continue; // not enought polygons for the offset. jba. + } + for (j=0; j<6; j++) { + i = ((Int *)pPoly)[j+m_trees[curTree].panelStart]; + if (m_curNumTreeVertices >= MAX_TREE_VERTEX) + break; - vLoc.X += loc.X; - vLoc.Y += loc.Y; - vLoc.Z = loc.Z + pVert[i].Y*scale; // In W3D z is up, in 3dMax y is up. + // Update the uv values. The W3D models each have their own texture, and + // we use one texture with all images in one, so we have to change the uvs to + // match. + Real U, V; + if (type==SHRUB) { + // shrub texture is tucked in the corner + U = ((512-64)+uvs[i].U*64.0f)/512.0f; + V = ((256-64)+uvs[i].V*64.0f)/256.0f; + } else if (type==FENCE) { + U = uvs[i].U*0.5f; + V = 1.0f + uvs[i].V; + } else { + U = typeOffset+uvs[i].U*0.5f; + V = uvs[i].V; + } - curVb->x = vLoc.X; - curVb->y = vLoc.Y; - curVb->z = vLoc.Z; - if (doVertexLighting) { - curVb->diffuse = doLighting(&vLoc, shadeR, shadeG, shadeB, m_trees[curTree].bounds, pDynamicLightsIterator); - } else { - curVb->diffuse = diffuse; + curVb->u1 = U; + curVb->v1 = V/2.0; + Vector3 vLoc; + vLoc.X = pVert[i].X*scale*theCos - pVert[i].Y*scale*theSin; + vLoc.Y = pVert[i].Y*scale*theCos + pVert[i].X*scale*theSin; + + vLoc.X += loc.X; + vLoc.Y += loc.Y; + vLoc.Z = loc.Z + pVert[i].Z*scale; + + curVb->x = vLoc.X; + curVb->y = vLoc.Y; + curVb->z = vLoc.Z; + if (doVertexLighting) { + curVb->diffuse = doLighting(&vLoc, shadeR, shadeG, shadeB, m_trees[curTree].bounds, pDynamicLightsIterator); + } else { + curVb->diffuse = diffuse; + } + curVb++; + m_curNumTreeVertices++; } - curVb++; - m_curNumTreeVertices++; - } - for (i=0; i<6; i++) { - if (m_curNumTreeIndices+4 > MAX_TREE_INDEX) - break; - curIb--; - *curIb = startVertex + i; - m_curNumTreeIndices++; + for (i=0; i<6; i++) { + if (m_curNumTreeIndices+4 > MAX_TREE_INDEX) + break; + curIb--; + *curIb = startVertex + i; + m_curNumTreeIndices++; + } + } else { + */ + Real Uscale = m_treeTypes[type].m_tileWidth * (Real)TILE_PIXEL_EXTENT / (Real)m_textureWidth; + Real Vscale = m_treeTypes[type].m_tileWidth * (Real)TILE_PIXEL_EXTENT / (Real)m_textureHeight; + Real UOffset = m_treeTypes[type].m_textureOrigin.x/(Real)m_textureWidth; + Real VOffset = m_treeTypes[type].m_textureOrigin.y/(Real)m_textureHeight; + if (m_treeTypes[type].m_halfTile) { + Uscale *= 0.5f; + Vscale *= 0.5f; + VOffset += (TILE_PIXEL_EXTENT/2) / (Real)m_textureHeight; } - } else { for (i=0; i= MAX_TREE_VERTEX) + if (m_curNumTreeVertices[bNdx] >= MAX_TREE_VERTEX) break; // Update the uv values. The W3D models each have their own texture, and // we use one texture with all images in one, so we have to change the uvs to // match. Real U, V; - if (type==SHRUB) { - // shrub texture is tucked in the corner - U = ((512-64)+uvs[i].U*64.0f)/512.0f; - V = ((256-64)+uvs[i].V*64.0f)/256.0f; - } else if (type==FENCE) { - U = uvs[i].U*0.5f; - V = 1.0f + uvs[i].V; + U = uvs[i].U; + V = uvs[i].V; + + if (U>1.0f) U=1.0f; + if (U<0.0f) U=0.0f; + if (V>1.0f) V=1.0f; + if (V<0.0f) V=0.0f; + + curVb->u1 = U*Uscale + UOffset; + curVb->v1 = V*Vscale + VOffset; + Real x = pVert[i].X; + Real y = pVert[i].Y; + + + Vector3 vLoc; + x += m_treeTypes[type].m_offset.X; + y += m_treeTypes[type].m_offset.Y; + vLoc.X = x*scale*theCos - y*scale*theSin; + vLoc.Y = y*scale*theCos + x*scale*theSin; + vLoc.Z = pVert[i].Z*scale; + vLoc.Z += m_treeTypes[type].m_offset.Z; + + if (m_trees[curTree].m_toppleState != TOPPLE_UPRIGHT) { + Matrix3D::Transform_Vector(m_trees[curTree].m_mtx, vLoc, &vLoc); } else { - U = typeOffset+uvs[i].U*0.5f; - V = uvs[i].V; + if (m_trees[curTree].pushAside>0.0f) { + vLoc.X += pVert[i].Z * m_trees[curTree].pushAside * m_trees[curTree].pushAsideCos * m_treeTypes[type].m_data->m_maxOutwardMovement; + vLoc.Y += pVert[i].Z * m_trees[curTree].pushAside * m_trees[curTree].pushAsideSin* m_treeTypes[type].m_data->m_maxOutwardMovement; + } + vLoc.X += loc.X; + vLoc.Y += loc.Y; + vLoc.Z += loc.Z; } - curVb->u1 = U; - curVb->v1 = V/2.0; - Vector3 vLoc; - vLoc.X = pVert[i].X*scale*theCos - pVert[i].Z*scale*theSin; - vLoc.Y = pVert[i].Z*scale*theCos + pVert[i].X*scale*theSin; - vLoc.X += loc.X; - vLoc.Y += loc.Y; - vLoc.Z = loc.Z + pVert[i].Y*scale; // In W3D z is up, in 3dMax y is up. curVb->x = vLoc.X; curVb->y = vLoc.Y; curVb->z = vLoc.Z; + curVb->nx = m_trees[curTree].swayType; + curVb->ny = 1.0f - m_treeTypes[type].m_data->m_darkening*m_trees[curTree].pushAside; + curVb->nz = loc.Z; if (doVertexLighting) { - curVb->diffuse = doLighting(&vLoc, shadeR, shadeG, shadeB, m_trees[curTree].bounds, pDynamicLightsIterator); + Vector3 normal(0.0f, 0.0f, 1.0f); + if (normals) { + normal.X = normals[i].X*theCos - normals[i].Y*theSin; + normal.Y = normals[i].Y*theCos + normals[i].X*theSin; + normal.Z = normals[i].Z; + } + UnsignedInt vertexDiffuse; + if (vecDiffuse) { + vertexDiffuse = vecDiffuse[i]; + } else { + vertexDiffuse = 0xffffffff; + } + curVb->diffuse = doLighting(&normal, objectLighting, &emissive, + vertexDiffuse, 1.0f); } else { curVb->diffuse = diffuse; } curVb++; - m_curNumTreeVertices++; + m_curNumTreeVertices[bNdx]++; } for (i=0; i MAX_TREE_INDEX) + if (m_curNumTreeIndices[bNdx]+4 > MAX_TREE_INDEX) break; - curIb-=3; *curIb++ = startVertex + pPoly[i].I; *curIb++ = startVertex + pPoly[i].J; *curIb++ = startVertex + pPoly[i].K; - curIb-=3; - m_curNumTreeIndices+=3; + m_curNumTreeIndices[bNdx]+=3; } } } - m_curTreeIndexOffset = curIb - ib; -} - -//----------------------------------------------------------------------------- -// Public Functions -//----------------------------------------------------------------------------- +} //============================================================================= -// W3DTreeBuffer::~W3DTreeBuffer +// W3DTreeBuffer::updateVertexBuffer //============================================================================= -/** Destructor. Releases w3d assets. */ +/** Updates the push aside offset in vertex buffer. */ //============================================================================= -W3DTreeBuffer::~W3DTreeBuffer(void) +void W3DTreeBuffer::updateVertexBuffer(void) { - freeTreeBuffers(); - REF_PTR_RELEASE(m_treeTexture); - Int i; - for (i=0; iGet_Filter().Set_U_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); - m_treeTexture->Get_Filter().Set_V_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); - for (i=0; iCreate_Render_Obj("ALPINETREE.TREE 1" ); - break; - case 1: - m_typeMesh[i] = (MeshClass*)WW3DAssetManager::Get_Instance()->Create_Render_Obj("DECIDUOUS.TREE 1" ); - break; - case 2: - m_typeMesh[i] = (MeshClass*)WW3DAssetManager::Get_Instance()->Create_Render_Obj("SHRUB.TREE 1" ); - break; - case 3: - m_typeMesh[i] = (MeshClass*)WW3DAssetManager::Get_Instance()->Create_Render_Obj("FENCE.PLANE09" ); - break; + Int curTree; + for (curTree=0; curTreePeek_Model()->Get_Vertex_Count(); + Vector3 *pVert = m_treeTypes[type].m_mesh->Peek_Model()->Get_Vertex_Array(); + + for (i=0; i0.0f) { + vLoc.X += pVert[i].Z * m_trees[curTree].pushAside * m_trees[curTree].pushAsideCos * m_treeTypes[type].m_data->m_maxOutwardMovement; + vLoc.Y += pVert[i].Z * m_trees[curTree].pushAside * m_trees[curTree].pushAsideSin* m_treeTypes[type].m_data->m_maxOutwardMovement; + } + vLoc.X += loc.X; + vLoc.Y += loc.Y; + vLoc.Z += loc.Z; + } + + curVb->x = vLoc.X; + curVb->y = vLoc.Y; + curVb->z = vLoc.Z; + curVb->ny = 1.0f - m_treeTypes[type].m_data->m_darkening*m_trees[curTree].pushAside; + curVb++; + } } - if (m_typeMesh[i] == NULL) continue; - Int numVertex = m_typeMesh[i]->Peek_Model()->Get_Vertex_Count(); - Vector3 *pVert = m_typeMesh[i]->Peek_Model()->Get_Vertex_Array(); + } +} + +//----------------------------------------------------------------------------- +// Public Functions +//----------------------------------------------------------------------------- - const Matrix3D xfm = m_typeMesh[i]->Get_Transform(); - SphereClass bounds(pVert, numVertex); - // Model is in y up format, so swap y and z. - Real tmp; - tmp = bounds.Center.Y; - bounds.Center.Y = bounds.Center.Z; - bounds.Center.Z = tmp; - m_typeBounds[i] = bounds; +//============================================================================= +// W3DTreeBuffer::~W3DTreeBuffer +//============================================================================= +/** Destructor. Releases w3d assets. */ +//============================================================================= +W3DTreeBuffer::~W3DTreeBuffer(void) +{ + freeTreeBuffers(); + REF_PTR_RELEASE(m_treeTexture); + Int i; + for (i=0; iDeletePixelShader(m_dwTreePixelShader); + m_dwTreePixelShader = 0; + + if (m_dwTreeVertexShader) + DX8Wrapper::_Get_D3D_Device8()->DeleteVertexShader(m_dwTreeVertexShader); + m_dwTreeVertexShader = 0; +} + +//============================================================================= +// W3DTreeBuffer::unitMoved +//============================================================================= +/** Check to see if a unit collided with a tree/grass/bush. */ +//============================================================================= +void W3DTreeBuffer::unitMoved(Object *unit) +{ + if (unit->isKindOf(KINDOF_IMMOBILE)) { + // This is the initial positioning of the object, and we don't care. jba. [6/5/2003] + return; + } + Real radius = unit->getGeometryInfo().getMajorRadius(); + if (unit->getGeometryInfo().getGeomType()==GEOMETRY_BOX) { + if (radius>unit->getGeometryInfo().getMinorRadius()) { + radius = unit->getGeometryInfo().getMinorRadius(); + } + } + // Value to assume for the tree radius. +#define TREE_RADIUS_APPROX 7.0f + radius += TREE_RADIUS_APPROX; + + Coord3D pos = *unit->getPosition(); + Real x = pos.x-radius; + Real y = pos.y-radius; + if (xm_bounds.hi.x) x = m_bounds.hi.x; + if (y>m_bounds.hi.y) y = m_bounds.hi.y; + Int xIndex = REAL_TO_INT_FLOOR ( (x/(m_bounds.hi.x-m_bounds.lo.x)) * (PARTITION_WIDTH_HEIGHT-0.1f) ); + Int yIndex = REAL_TO_INT_FLOOR ( (y/(m_bounds.hi.y-m_bounds.lo.y)) * (PARTITION_WIDTH_HEIGHT-0.1f) ); + DEBUG_ASSERTCRASH(xIndex>=0 && yIndex>=0 && xIndexm_bounds.hi.x) x = m_bounds.hi.x; + if (y>m_bounds.hi.y) y = m_bounds.hi.y; + Int xMax = REAL_TO_INT_CEIL ( (x/(m_bounds.hi.x-m_bounds.lo.x)) * (PARTITION_WIDTH_HEIGHT-0.1f) ); + Int yMax = REAL_TO_INT_CEIL ( (y/(m_bounds.hi.y-m_bounds.lo.y)) * (PARTITION_WIDTH_HEIGHT-0.1f) ); + DEBUG_ASSERTCRASH(xMax>=0 && yMax>=0 && xMax<=PARTITION_WIDTH_HEIGHT && yMax<=PARTITION_WIDTH_HEIGHT, ("Invalid range.")); + Int i, j; + for (i=xIndex; i=m_numTrees) { + DEBUG_CRASH(("Invalid index.")); + break; + } + if (m_trees[treeNdx].treeType<0) { + treeNdx = m_trees[treeNdx].nextInPartition; + continue; // Tree is deleted. [7/11/2003] + } + Coord3D delta; + delta.set(m_trees[treeNdx].location.X, m_trees[treeNdx].location.Y, m_trees[treeNdx].location.Z ); + delta.sub(&pos); + if (radius*radius>delta.lengthSqr()) { + bool canTopple = unit->getCrusherLevel() > 1; + if (canTopple && m_treeTypes[m_trees[treeNdx].treeType].m_data->m_doTopple) { + // Give a vector with direction to thing. + Coord3D toppleVector; + toppleVector.set(m_trees[treeNdx].location.X, m_trees[treeNdx].location.Y, 0); + toppleVector.x -= unit->getPosition()->x; + toppleVector.y -= unit->getPosition()->y; + applyTopplingForce(m_trees+treeNdx, &toppleVector, 0, W3D_TOPPLE_OPTIONS_NONE); + } else if (m_treeTypes[m_trees[treeNdx].treeType].m_data->m_framesToMoveOutward>1) { + pushAsideTree(m_trees[treeNdx].drawableID, &pos, unit->getUnitDirectionVector2D(), unit->getID()); + } + } + treeNdx = m_trees[treeNdx].nextInPartition; + } + } + } + + } //============================================================================= @@ -585,10 +1219,39 @@ void W3DTreeBuffer::freeTreeBuffers(void) //============================================================================= void W3DTreeBuffer::allocateTreeBuffers(void) { - m_vertexTree=NEW_REF(DX8VertexBufferClass,(DX8_FVF_XYZDUV1,MAX_TREE_VERTEX+4,DX8VertexBufferClass::USAGE_DYNAMIC)); - m_indexTree=NEW_REF(DX8IndexBufferClass,(2*MAX_TREE_INDEX+4, DX8IndexBufferClass::USAGE_DYNAMIC)); - m_curNumTreeVertices=0; - m_curNumTreeIndices=0; + Int i; + for (i=0; igeomCollidesWithGeom( pos, geom, angle, &treePos, info, 0.0f)) { + // remove it [7/11/2003] + m_trees[i].treeType = DELETED_TREE_TYPE; + m_anythingChanged = true; + } + } +} + + +//============================================================================= +// W3DTreeBuffer::addTreeTypes +//============================================================================= +/** Adds a type of tree (model & texture). */ +//============================================================================= +Int W3DTreeBuffer::addTreeType(const W3DTreeDrawModuleData *data) +{ + if (m_numTreeTypes>=MAX_TYPES) { + DEBUG_CRASH(("Too many kinds of trees in map. Reduce kinds of trees, or raise tree limit. jba.")); + return 0; + } + m_needToUpdateTexture = true; + + m_treeTypes[m_numTreeTypes].m_mesh = NULL; + + RenderObjClass *robj=WW3DAssetManager::Get_Instance()->Create_Render_Obj(data->m_modelName.str()); + + if (robj==NULL) { + DEBUG_CRASH(("Unable to find model for tree %s", data->m_modelName.str())); + return 0; + } + AABoxClass box; + + robj->Get_Obj_Space_Bounding_Box(box); + Vector3 offset(0,0,0); + if (robj->Class_ID() == RenderObjClass::CLASSID_HLOD) { + RenderObjClass *hlod = robj; + robj = hlod->Get_Sub_Object(0); + const Matrix3D xfm = robj->Get_Bone_Transform(0); + xfm.Get_Translation(&offset); + REF_PTR_RELEASE(hlod); + } + + if (robj->Class_ID() == RenderObjClass::CLASSID_MESH) + m_treeTypes[m_numTreeTypes].m_mesh = (MeshClass*)robj; + + if (m_treeTypes[m_numTreeTypes].m_mesh==NULL) { + DEBUG_CRASH(("Tree %s is not simple mesh. Tell artist to re-export. Don't Ignore!!!", data->m_modelName.str())); + return 0; + } + + Int numVertex = m_treeTypes[m_numTreeTypes].m_mesh->Peek_Model()->Get_Vertex_Count(); + Vector3 *pVert = m_treeTypes[m_numTreeTypes].m_mesh->Peek_Model()->Get_Vertex_Array(); + + const Matrix3D xfm = m_treeTypes[m_numTreeTypes].m_mesh->Get_Transform(); + SphereClass bounds(pVert, numVertex); + bounds.Center += offset; + m_treeTypes[m_numTreeTypes].m_bounds = bounds; + m_treeTypes[m_numTreeTypes].m_textureOrigin.x = 0; + m_treeTypes[m_numTreeTypes].m_textureOrigin.y = 0; + m_treeTypes[m_numTreeTypes].m_data = data; + m_treeTypes[m_numTreeTypes].m_offset = offset; + m_treeTypes[m_numTreeTypes].m_shadowSize = (box.Extent.X + box.Extent.Y); // Average extent * 2. jba. + m_treeTypes[m_numTreeTypes].m_doShadow = data->m_doShadow; + m_numTreeTypes++; + return m_numTreeTypes-1; } //============================================================================= @@ -607,53 +1386,140 @@ void W3DTreeBuffer::clearAllTrees(void) /** Adds a tree. Name is the W3D model name, supported models are ALPINE, DECIDUOUS and SHRUB. */ //============================================================================= -void W3DTreeBuffer::addTree(Coord3D loc, Real scale, Real angle, AsciiString name, Bool mirrorVisible) +void W3DTreeBuffer::addTree(DrawableID id, Coord3D location, Real scale, Real angle, + Real randomScaleAmount, const W3DTreeDrawModuleData *data) { if (m_numTrees >= MAX_TREES) { return; } - if (!m_initialized) { return; } - - TTreeType treeType = ALPINE_TREE; - if (!name.compare("DECIDUOUS")) { - treeType = DECIDUOUS_TREE; - } else if (!name.compare("SHRUB")) { - treeType = SHRUB; - } else if (!name.compare("FENCE")) { - treeType = FENCE; + Int treeType = DELETED_TREE_TYPE; + Int i; + for (i=0; im_modelName.compareNoCase(data->m_modelName)==0 && + m_treeTypes[i].m_data->m_textureName.compareNoCase(data->m_textureName)==0) { + treeType = i; + break; + } + } + if (treeType<0) { + treeType = addTreeType(data); + if (treeType<0) { + return; + } + m_needToUpdateTexture = true; } - m_trees[m_numTrees].panelStart = 0; - Real randomScale = GameClientRandomValueReal( 0.7f, 1.3f ); - if (treeType == FENCE) { + if (data->m_framesToMoveOutward > 2 || data->m_doTopple) { // Fences don't randomly scale & orient - m_trees[m_numTrees].sin = WWMath::Sin(angle); - m_trees[m_numTrees].scale = scale; - m_trees[m_numTrees].cos = WWMath::Cos(angle); - m_trees[m_numTrees].rotates = false; - m_trees[m_numTrees].panelStart = 48; + Short bucket = getPartitionBucket(location); + m_trees[m_numTrees].nextInPartition = m_areaPartition[bucket]; + m_areaPartition[bucket] = m_numTrees; } else { + m_trees[m_numTrees].nextInPartition = END_OF_PARTITION; + } + + Real randomScale = GameClientRandomValueReal( 1.0f - randomScaleAmount, 1.0f+ randomScaleAmount ); + m_trees[m_numTrees].sin = WWMath::Sin(angle); + m_trees[m_numTrees].cos = WWMath::Cos(angle); + if (randomScaleAmount>0.0f) { // Randomizes the scale and orientation of trees. - m_trees[m_numTrees].sin = GameClientRandomValueReal( -1.0f, 1.0f ); m_trees[m_numTrees].scale = scale*randomScale; - m_trees[m_numTrees].cos = WWMath::Sqrt(1.0 - m_trees[m_numTrees].sin*m_trees[m_numTrees].sin); - m_trees[m_numTrees].rotates = true; + } else { + // Don't randomly scale & orient + m_trees[m_numTrees].scale = scale; } - m_trees[m_numTrees].location = Vector3(loc.x, loc.y, loc.z); + m_trees[m_numTrees].location = Vector3(location.x, location.y, location.z); m_trees[m_numTrees].treeType = treeType; // Translate the bounding sphere of the model. - m_trees[m_numTrees].bounds = m_typeBounds[treeType]; - m_trees[m_numTrees].bounds.Center *= scale; - m_trees[m_numTrees].bounds.Radius *= scale; + m_trees[m_numTrees].bounds = m_treeTypes[treeType].m_bounds; + m_trees[m_numTrees].bounds.Center *= m_trees[m_numTrees].scale; + m_trees[m_numTrees].bounds.Radius *= m_trees[m_numTrees].scale; m_trees[m_numTrees].bounds.Center += m_trees[m_numTrees].location; // Initially set it invisible. cull will update it's visiblity flag. m_trees[m_numTrees].visible = false; - m_trees[m_numTrees].mirrorVisible = mirrorVisible; + m_trees[m_numTrees].drawableID = id; + + m_trees[m_numTrees].firstIndex = 0; + m_trees[m_numTrees].bufferNdx = -1; + + m_trees[m_numTrees].swayType = GameClientRandomValue(1, MAX_SWAY_TYPES); + m_trees[m_numTrees].pushAside = 0; + m_trees[m_numTrees].lastFrameUpdated = 0; + m_trees[m_numTrees].pushAsideSource = INVALID_ID; + m_trees[m_numTrees].pushAsideDelta = 0; + m_trees[m_numTrees].pushAsideCos = 1; + m_trees[m_numTrees].pushAsideSin = 1; + m_trees[m_numTrees].m_toppleState = TOPPLE_UPRIGHT; m_numTrees++; } +//============================================================================= +// W3DTreeBuffer::updateTreePosition +//============================================================================= +/** Updates a tree's position */ +//============================================================================= +Bool W3DTreeBuffer::updateTreePosition(DrawableID id, Coord3D location, Real angle) +{ + Int i; + for (i=0; igetFrame(); + if(m_trees[i].pushAsideSource == pusherID) { + if (m_trees[i].lastFrameUpdated - lastFrame < 3) + return; // already pushing. [5/28/2003] + } + + if(m_trees[i].pushAside != 0.0f) { + return; // already pushing. [5/28/2003] + } + m_trees[i].pushAsideSource = pusherID; + Coord3D delta; + delta.set(m_trees[i].location.X, m_trees[i].location.Y, m_trees[i].location.Z); + delta.sub(pusherPos); + + if (pusherDirection->x*delta.y - pusherDirection->y*delta.x > 0.0f) { + m_trees[i].pushAsideCos = -pusherDirection->y; + m_trees[i].pushAsideSin = pusherDirection->x; + } else { + m_trees[i].pushAsideCos = pusherDirection->y; + m_trees[i].pushAsideSin = -pusherDirection->x; + } + m_anyPushChanged = true; + m_trees[i].pushAsideDelta = 1.0f/(Real)m_treeTypes[m_trees[i].treeType].m_data->m_framesToMoveOutward; + } + } +} + +DECLARE_PERF_TIMER(Tree_Render) //============================================================================= // W3DTreeBuffer::drawTrees @@ -662,32 +1528,513 @@ void W3DTreeBuffer::addTree(Coord3D loc, Real scale, Real angle, AsciiString nam //============================================================================= void W3DTreeBuffer::drawTrees(CameraClass * camera, RefRenderObjListIterator *pDynamicLightsIterator) { + USE_PERF_TIMER(Tree_Render) if (!m_isTerrainPass) { return; } + + // if breeze changes, always process the full update, even if not visible, + // so that things offscreen won't 'pop' when first viewed + const BreezeInfo& info = TheScriptEngine->getBreezeInfo(); + if (info.m_breezeVersion != m_curSwayVersion) + { + updateSway(info); + } + + // TheSuperHackers @tweak The tree sway, topple and sink time steps are now decoupled from the render update. + const Real timeScale = TheFramePacer->getActualLogicTimeScaleOverFpsRatio(); + Vector3 swayFactor[MAX_SWAY_TYPES]; + Int i; + for (i=0; i NUM_SWAY_ENTRIES-1) { + m_curSwayOffset[i] -= NUM_SWAY_ENTRIES-1; + } + Int minOffset = REAL_TO_INT_FLOOR(m_curSwayOffset[i]); + if (minOffset>=0 && minOffset+1m_useShadowDecals) { + for (curTree=0; curTreesetSize(m_treeTypes[type].m_shadowSize, m_treeTypes[type].m_shadowSize); + m_shadow->setPosition(m_trees[curTree].location.X, m_trees[curTree].location.Y, m_trees[curTree].location.Z); + TheW3DProjectedShadowManager->queueDecal(m_shadow); + } + TheW3DProjectedShadowManager->flushDecals(m_shadow->getTexture(0), SHADOW_DECAL); + } + + // Update pushed aside and toppling trees. + for (curTree=0; curTreem_killWhenToppled) { + if (m_trees[curTree].m_sinkFramesLeft <= 0.0f) { + m_trees[curTree].treeType = DELETED_TREE_TYPE; // delete it. [7/11/2003] + m_anythingChanged = true; // need to regenerate trees. [7/11/2003] + } + const Real sinkDistancePerFrame = moduleData->m_sinkDistance / moduleData->m_sinkFrames; + m_trees[curTree].m_sinkFramesLeft -= timeScale; + m_trees[curTree].location.Z -= sinkDistancePerFrame * timeScale; + m_trees[curTree].m_mtx.Set_Translation(m_trees[curTree].location); + } + } else if (m_trees[curTree].pushAsideDelta!=0.0f) { + m_trees[curTree].pushAside += m_trees[curTree].pushAsideDelta; + if (m_trees[curTree].pushAside>=1.0f) { + m_trees[curTree].pushAsideDelta = -1.0f/(Real)moduleData->m_framesToMoveInward; + } else if (m_trees[curTree].pushAside<=0.0f) { + m_trees[curTree].pushAsideDelta = 0.0f; + m_trees[curTree].pushAside = 0.0f; + } + } + } + + if (m_anythingChanged) { + loadTreesInVertexAndIndexBuffers(pDynamicLightsIterator); + m_anythingChanged = false; + } else if (m_anyPushChanged) { + m_anyPushChanged = false; + updateVertexBuffer(); } + +//#define DEBUG_TEXTURE 1 +#ifdef DEBUG_TEXTURE // Draw the combined texture for debugging. jba. [4/21/2003] // Setup the vertex buffer, shader & texture. - DX8Wrapper::Set_Index_Buffer(m_indexTree,0); - DX8Wrapper::Set_Vertex_Buffer(m_vertexTree); DX8Wrapper::Set_Shader(detailAlphaShader); DX8Wrapper::Set_Texture(0,m_treeTexture); + DynamicIBAccessClass ib_access(BUFFER_TYPE_DYNAMIC_DX8, 6); + //draw an infinite sky plane + DynamicVBAccessClass vb_access(BUFFER_TYPE_DYNAMIC_DX8, DX8_FVF_XYZNDUV2, 4); + { + DynamicIBAccessClass::WriteLockClass ibLock(&ib_access); + UnsignedShort *ndx = ibLock.Get_Index_Array(); + + if (ndx) { + ndx[0] = 0; + ndx[1] = 1; + ndx[2] = 2; + ndx[3] = 1; + ndx[4] = 3; + ndx[5] = 2; + } + DynamicVBAccessClass::WriteLockClass lock(&vb_access); + VertexFormatXYZNDUV2* verts=lock.Get_Formatted_Vertex_Array(); + if(verts) + { + Real width = 300; + Real origin = 40; + verts[0].x=origin; + verts[0].y=origin; + verts[0].z=15; + verts[0].u1=0; + verts[0].v1=0; + verts[0].diffuse=0xffffffff; + + verts[1].x=origin+width; + verts[1].y=origin; + verts[1].z=15; + verts[1].u1=1; + verts[1].v1=0; + verts[1].diffuse=0xffffffff; + + verts[2].x=origin; + verts[2].y=origin+width; + verts[2].z=15; + verts[2].u1=0; + verts[2].v1=1; + verts[2].diffuse=0xffffffff; + + verts[3].x=origin+width; + verts[3].y=origin+width; + verts[3].z=15; + verts[3].u1=1; + verts[3].v1=1; + verts[3].diffuse=0xffffffff; + } + } + + DX8Wrapper::Set_Index_Buffer(ib_access,0); + DX8Wrapper::Set_Vertex_Buffer(vb_access); + + Matrix3D tm(1); + DX8Wrapper::Set_Transform(D3DTS_WORLD,tm); + + DX8Wrapper::Draw_Triangles( 0,2, 0, 4); //draw a quad, 2 triangles, 4 verts +#endif + + + if (m_curNumTreeIndices[0] == 0) { + return; + } + DX8Wrapper::Set_Shader(detailAlphaShader); + + DX8Wrapper::Set_Texture(0,m_treeTexture); + DX8Wrapper::Set_Texture(1,NULL); + DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_TEXCOORDINDEX, 0); + DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_TEXCOORDINDEX, 1); // Draw all the trees. - DX8Wrapper::Draw_Triangles( m_curTreeIndexOffset, m_curNumTreeIndices/3, 0, m_curNumTreeVertices); + DX8Wrapper::Apply_Render_State_Changes(); + W3DShaderManager::setShroudTex(1); + DX8Wrapper::Apply_Render_State_Changes(); + + if (m_dwTreeVertexShader) { + D3DXMATRIX matProj, matView, matWorld; + DX8Wrapper::_Get_DX8_Transform(D3DTS_WORLD, *(Matrix4x4*)&matWorld); + DX8Wrapper::_Get_DX8_Transform(D3DTS_VIEW, *(Matrix4x4*)&matView); + DX8Wrapper::_Get_DX8_Transform(D3DTS_PROJECTION, *(Matrix4x4*)&matProj); + D3DXMATRIX mat; + D3DXMatrixMultiply( &mat, &matView, &matProj ); + D3DXMatrixMultiply( &mat, &matWorld, &mat ); + D3DXMatrixTranspose( &mat, &mat ); + + // c4 - Composite World-View-Projection Matrix + DX8Wrapper::_Get_D3D_Device8()->SetVertexShaderConstant( 4, &mat, 4 ); + Vector4 noSway(0,0,0,0); + DX8Wrapper::_Get_D3D_Device8()->SetVertexShaderConstant( 8, &noSway, 1 ); + + // c8 - c8+MAX_SWAY_TYPES - the sway amount. + for (i=0; iSetVertexShaderConstant( 9+i, &sway4, 1 ); + } + + W3DShroud *shroud; + if ((shroud=TheTerrainRenderObject->getShroud()) != 0) { + // Setup shroud texture info [6/6/2003] + float xoffset = 0; + float yoffset = 0; + Real width=shroud->getCellWidth(); + Real height=shroud->getCellHeight(); + + xoffset = -(float)shroud->getDrawOriginX() + width; + yoffset = -(float)shroud->getDrawOriginY() + height; + Vector4 offset(xoffset, yoffset, 0, 0); + DX8Wrapper::_Get_D3D_Device8()->SetVertexShaderConstant( 32, &offset, 1 ); + width = 1.0f/(width*shroud->getTextureWidth()); + height = 1.0f/(height*shroud->getTextureHeight()); + offset.Set(width, height, 1, 1); + DX8Wrapper::_Get_D3D_Device8()->SetVertexShaderConstant( 33, &offset, 1 ); + + } else { + Vector4 offset(0,0,0,0); + DX8Wrapper::_Get_D3D_Device8()->SetVertexShaderConstant( 32, &offset, 1 ); + DX8Wrapper::_Get_D3D_Device8()->SetVertexShaderConstant( 33, &offset, 1 ); + } + + DX8Wrapper::Set_Vertex_Shader(m_dwTreeVertexShader); +#if 0 + DX8Wrapper::Set_Pixel_Shader(m_dwTreePixelShader); + // a.c. 6/16 - allow switching between normal and 2X mode for terrain + Real mulTwoX = 0.5f; + if(TheGlobalData && TheGlobalData->m_useOverbright) + mulTwoX = 1.0f; + DX8Wrapper::_Get_D3D_Device8()->SetPixelShaderConstant(1, D3DXVECTOR4(mulTwoX, mulTwoX, mulTwoX, mulTwoX), 1); +#endif + + } else { + DX8Wrapper::Set_Vertex_Shader(DX8_FVF_XYZNDUV1); + } + + + Int bNdx; + for (bNdx=0;bNdxSetVertexShader(m_dwTreeVertexShader); + DX8Wrapper::_Get_D3D_Device8()->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 0); + DX8Wrapper::_Get_D3D_Device8()->SetTextureStageState(1, D3DTSS_TEXCOORDINDEX, 1); + DX8Wrapper::_Get_D3D_Device8()->SetTextureStageState(1, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE); + } + DX8Wrapper::Draw_Triangles( 0, m_curNumTreeIndices[bNdx]/3, 0, m_curNumTreeVertices[bNdx]); + } + + DX8Wrapper::Set_Vertex_Shader(DX8_FVF_XYZNDUV1); + DX8Wrapper::Set_Pixel_Shader(NULL); + DX8Wrapper::Invalidate_Cached_Render_States(); //code above mucks around with W3D states so make sure we reset + +} + +//------------------------------------------------------------------------------------------------- +///< Start the toppling process by giving a force vector +//------------------------------------------------------------------------------------------------- +void W3DTreeBuffer::applyTopplingForce( TTree *tree, const Coord3D* toppleDirection, Real toppleSpeed, + UnsignedInt options ) +{ + if (tree->m_toppleState != TOPPLE_UPRIGHT) { + return; + } + const W3DTreeDrawModuleData* d = m_treeTypes[tree->treeType].m_data; + // Having a low toppleSpeed is BAD. In particular, if the toppleSpeed is exactly 0, the + // tree will stay upright forever, frozen in place (because the sway update is dead) + // but never dying + if ( toppleSpeed < d->m_minimumToppleSpeed ) + { + toppleSpeed = d->m_minimumToppleSpeed; + } + + tree->m_toppleDirection = *toppleDirection; + tree->m_toppleDirection.normalize(); + tree->m_angularAccumulation = 0; + + tree->m_angularVelocity = toppleSpeed * d->m_initialVelocityPercent; + tree->m_angularAcceleration = toppleSpeed * d->m_initialAccelPercent; + tree->m_toppleState = TOPPLE_FALLING; + tree->m_options = options; + Coord3D pos; + pos.set(tree->location.X, tree->location.Y, tree->location.Z); + FXList::doFXPos(d->m_toppleFX, &pos); + m_anyPushChanged = true; + tree->m_mtx.Make_Identity(); + tree->m_mtx.Set_Translation(tree->location); + +} + +// this is our "bounce" limit -- slightly less that 90 degrees, to account for slop. +static const Real ANGULAR_LIMIT = PI/2 - PI/64; + +//------------------------------------------------------------------------------------------------- +///< Keep track of rotational fall distance, bounce and/or stop when needed. +//------------------------------------------------------------------------------------------------- +void W3DTreeBuffer::updateTopplingTree(TTree *tree, Real timeScale) +{ + //DLOG(Debug::Format("updating W3DTreeBuffer %08lx\n",this)); + DEBUG_ASSERTCRASH(tree->m_toppleState != TOPPLE_UPRIGHT, ("hmm, we should be sleeping here")); + if ( (tree->m_toppleState == TOPPLE_UPRIGHT) || (tree->m_toppleState == TOPPLE_DOWN) ) + return; + + const W3DTreeDrawModuleData* d = m_treeTypes[tree->treeType].m_data; + const Int localPlayerIndex = rts::getObservedOrLocalPlayerIndex_Safe(); + Coord3D pos; + pos.set(tree->location.X, tree->location.Y, tree->location.Z); + ObjectShroudStatus ss = ThePartitionManager->getPropShroudStatusForPlayer(localPlayerIndex, &pos); + if (ss==OBJECTSHROUD_FOGGED) { + // Don't update fogged trees. [8/11/2003] + tree->m_toppleState = TOPPLE_FOGGED; + return; + } else if (tree->m_toppleState == TOPPLE_FOGGED) { + // was fogged, now isn't. + tree->m_angularVelocity = 0; + tree->m_toppleState = TOPPLE_DOWN; + tree->m_mtx.In_Place_Pre_Rotate_X(-ANGULAR_LIMIT * tree->m_toppleDirection.y); + tree->m_mtx.In_Place_Pre_Rotate_Y(ANGULAR_LIMIT * tree->m_toppleDirection.x); + if (d->m_killWhenToppled) { + // If got killed in the fog, just remove. jba [8/11/2003] + tree->m_sinkFramesLeft = 0.0f; + } + return; + } + const Real VELOCITY_BOUNCE_LIMIT = 0.01f; // if the velocity after a bounce will be this or lower, just stop at zero + const Real VELOCITY_BOUNCE_SOUND_LIMIT = 0.03f; // and if this low, then skip the bounce sound + + Real curVelToUse = tree->m_angularVelocity * timeScale; + if (tree->m_angularAccumulation + curVelToUse > ANGULAR_LIMIT) + curVelToUse = ANGULAR_LIMIT - tree->m_angularAccumulation; + + tree->m_mtx.In_Place_Pre_Rotate_X(-curVelToUse * tree->m_toppleDirection.y); + tree->m_mtx.In_Place_Pre_Rotate_Y(curVelToUse * tree->m_toppleDirection.x); + + tree->m_angularAccumulation += curVelToUse; + if ((tree->m_angularAccumulation >= ANGULAR_LIMIT) && (tree->m_angularVelocity > 0)) + { + // Hit so either bounce or stop if too little remaining velocity. + tree->m_angularVelocity *= -d->m_bounceVelocityPercent; + + if( BitIsSet( tree->m_options, W3D_TOPPLE_OPTIONS_NO_BOUNCE ) == TRUE || + fabs(tree->m_angularVelocity) < VELOCITY_BOUNCE_LIMIT ) + { + // too slow, just stop + tree->m_angularVelocity = 0; + tree->m_toppleState = TOPPLE_DOWN; + if (d->m_killWhenToppled) { + tree->m_sinkFramesLeft = d->m_sinkFrames; + } + } + else if( fabs(tree->m_angularVelocity) >= VELOCITY_BOUNCE_SOUND_LIMIT ) + { + // fast enough bounce to warrant the bounce fx + if( BitIsSet( tree->m_options, W3D_TOPPLE_OPTIONS_NO_FX ) == FALSE ) { + Vector3 loc(0, 0, 3*TREE_RADIUS_APPROX); // Kinda towards the top of the tree. jba. [7/11/2003] + Vector3 xloc; + tree->m_mtx.Transform_Vector(tree->m_mtx, loc, &xloc); + Coord3D pos; + pos.set(xloc.X, xloc.Y, xloc.Z); + FXList::doFXPos(d->m_bounceFX, &pos); + } + } + } + else + { + tree->m_angularVelocity += tree->m_angularAcceleration * timeScale; + } + +} + +// ------------------------------------------------------------------------------------------------ +/** CRC */ +// ------------------------------------------------------------------------------------------------ +void W3DTreeBuffer::crc( Xfer *xfer ) +{ + // empty. jba [8/11/2003] } +// ------------------------------------------------------------------------------------------------ +/** Xfer + * Version Info: + * 1: Initial version */ +// ------------------------------------------------------------------------------------------------ +void W3DTreeBuffer::xfer( Xfer *xfer ) +{ + + // version +#if RETAIL_COMPATIBLE_XFER_SAVE + XferVersion currentVersion = 1; +#else + XferVersion currentVersion = 2; +#endif + XferVersion version = currentVersion; + xfer->xferVersion( &version, currentVersion ); + + Int i; + Int numTrees = m_numTrees; + xfer->xferInt(&numTrees); + if (xfer->getXferMode() == XFER_LOAD) { + m_numTrees = 0; + for (i=0; igetXferMode() != XFER_LOAD) { + tree = m_trees[i]; + treeType = m_trees[i].treeType; + if (treeType != DELETED_TREE_TYPE) { + modelName = m_treeTypes[treeType].m_data->m_modelName; + modelTexture = m_treeTypes[treeType].m_data->m_textureName; + } + } + xfer->xferAsciiString(&modelName); + xfer->xferAsciiString(&modelTexture); + if (xfer->getXferMode() == XFER_LOAD) { + Int j; + for (j=0; jm_modelName.compareNoCase(modelName)==0 && + m_treeTypes[j].m_data->m_textureName.compareNoCase(modelTexture)==0) { + treeType = j; + break; + } + } + } + + xfer->xferReal(&tree.location.X); + xfer->xferReal(&tree.location.Y); + xfer->xferReal(&tree.location.Z); + + xfer->xferReal(&tree.scale); ///< Scale at location. + xfer->xferReal(&tree.sin); ///< Sine of the rotation angle at location. + xfer->xferReal(&tree.cos); ///< Cosine of the rotation angle at location. + + xfer->xferDrawableID(&tree.drawableID); ///< Drawable this tree corresponds to. + + // Topple parameters. [7/7/2003] + xfer->xferReal(&tree.m_angularVelocity); ///< Velocity in degrees per frame (or is it radians per frame?) + xfer->xferReal(&tree.m_angularAcceleration); ///< Acceleration angularVelocity is increasing + xfer->xferCoord3D(&tree.m_toppleDirection); ///< Z-less direction we are toppling + xfer->xferUser(&tree.m_toppleState, sizeof(tree.m_toppleState)); ///< Stage this module is in. + xfer->xferReal(&tree.m_angularAccumulation); ///< How much have I rotated so I know when to bounce. + xfer->xferUnsignedInt(&tree.m_options); ///< topple options + xfer->xferMatrix3D(&tree.m_mtx); + + if (version <= 1) + { + UnsignedInt sinkFramesLeft = (UnsignedInt)tree.m_sinkFramesLeft; + xfer->xferUnsignedInt(&sinkFramesLeft); ///< Toppled trees sink into the terrain & disappear, how many frames left. + tree.m_sinkFramesLeft = (Real)sinkFramesLeft; + } + else + { + xfer->xferReal(&tree.m_sinkFramesLeft); ///< Toppled trees sink into the terrain & disappear, how many frames left. + } + + if (xfer->getXferMode() == XFER_LOAD && treeType != DELETED_TREE_TYPE && treeType < m_numTreeTypes) { + Coord3D pos; + pos.set(tree.location.X, tree.location.Y, tree.location.Z); + Real angle = 0; + addTree(tree.drawableID, pos, tree.scale, angle, 0, m_treeTypes[treeType].m_data); + if (m_numTrees) { + TTree *curTree = &m_trees[m_numTrees-1]; + curTree->m_angularAcceleration = tree.m_angularAcceleration; + curTree->m_angularVelocity = tree.m_angularVelocity; + curTree->m_toppleDirection = tree.m_toppleDirection; + curTree->m_toppleState = tree.m_toppleState; + curTree->m_options = tree.m_options; + curTree->m_mtx = tree.m_mtx; + curTree->m_sinkFramesLeft = tree.m_sinkFramesLeft; + } + } + } + +} + +// ------------------------------------------------------------------------------------------------ +/** Load post process */ +// ------------------------------------------------------------------------------------------------ +void W3DTreeBuffer::loadPostProcess( void ) +{ + // empty. jba [8/11/2003] +} + + + diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp index 38eb63b462..b8211abbcc 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp @@ -53,6 +53,7 @@ #include "Common/file.h" + #define K_OBSOLETE_HEIGHT_MAP_VERSION 8 #define PATHFIND_CLIFF_SLOPE_LIMIT_F 9.8f @@ -95,14 +96,10 @@ MapObject::MapObject(Coord3D loc, AsciiString name, Real angle, Int flags, const m_renderObj = NULL; m_shadowObj = NULL; m_runtimeFlags = 0; - + // Note - do NOT set TheKey_objectSelectable on creation - allow it to follow the .ini value unless specified by user action. jba. [3/20/2003] if (props) { m_properties = *props; - if (thingTemplate && !props->known(TheKey_objectSelectable, Dict::DICT_BOOL)) { - Bool selectable = thingTemplate->isKindOf(KINDOF_SELECTABLE); - m_properties.setBool(TheKey_objectSelectable, selectable); - } } else { @@ -113,12 +110,6 @@ MapObject::MapObject(Coord3D loc, AsciiString name, Real angle, Int flags, const m_properties.setBool(TheKey_objectPowered, true); m_properties.setBool(TheKey_objectRecruitableAI, true); m_properties.setBool(TheKey_objectTargetable, false ); - - Bool selectable = false; - if (thingTemplate) { - selectable = thingTemplate->isKindOf(KINDOF_SELECTABLE); - } - m_properties.setBool(TheKey_objectSelectable, selectable); } for( Int i = 0; i < BRIDGE_MAX_TOWERS; ++i ) @@ -375,6 +366,7 @@ const ThingTemplate *MapObject::getThingTemplate( void ) const /* ********* WorldHeightMap class ****************************/ +TileData *WorldHeightMap::m_alphaTiles[NUM_ALPHA_TILES]={0,0,0,0,0,0,0,0,0,0,0,0}; // // WorldHeightMap destructor . @@ -399,6 +391,12 @@ WorldHeightMap::~WorldHeightMap(void) delete[](m_cellFlipState); m_cellFlipState = NULL; + delete[](m_seismicUpdateFlag); + m_seismicUpdateFlag = NULL; + + delete[](m_seismicZVelocities); + m_seismicZVelocities = NULL; + delete[](m_cellCliffState); m_cellCliffState = NULL; @@ -407,6 +405,9 @@ WorldHeightMap::~WorldHeightMap(void) REF_PTR_RELEASE(m_sourceTiles[i]); REF_PTR_RELEASE(m_edgeTiles[i]); } + for (i=0; ivalidateSides(); + setupAlphaTiles(); } #ifdef EVAL_TILING_MODES @@ -467,7 +469,7 @@ static Bool ParseFunkyTilingDataChunk(DataChunkInput &file, DataChunkInfo *info, * */ WorldHeightMap::WorldHeightMap(ChunkInputStream *pStrm, Bool logicalDataOnly): - m_width(0), m_height(0), m_dataSize(0), m_data(NULL), m_cellFlipState(NULL), + m_width(0), m_height(0), m_dataSize(0), m_data(NULL), m_cellFlipState(NULL), m_seismicUpdateFlag(NULL), m_seismicZVelocities(NULL), m_drawOriginX(0), m_cellCliffState(NULL), m_drawOriginY(0), m_numTextureClasses(0), m_drawWidthX(NORMAL_DRAW_WIDTH), m_drawHeightY(NORMAL_DRAW_HEIGHT), @@ -510,6 +512,7 @@ WorldHeightMap::WorldHeightMap(ChunkInputStream *pStrm, Bool logicalDataOnly): file.registerParser( "GlobalLighting", AsciiString::TheEmptyString, ParseLightingDataChunk ); } if (!file.parse(this)) { + throw(ERROR_CORRUPT_FILE_FORMAT); } // patch bad maps. @@ -538,6 +541,7 @@ WorldHeightMap::WorldHeightMap(ChunkInputStream *pStrm, Bool logicalDataOnly): } TheSidesList->validateSides(); + setupAlphaTiles(); } /** Optimized version of method to get triangle flip state of a terrain cell. Use this @@ -552,6 +556,145 @@ Bool WorldHeightMap::getFlipState(Int xIndex, Int yIndex) const return m_cellFlipState[yIndex*m_flipStateWidth + (xIndex >> 3)] & (1<<(xIndex&0x7)); } +/** Sets the value of the flip state bit. +*/ +void WorldHeightMap::setFlipState(Int xIndex, Int yIndex, Bool value) +{ + if (xIndex<0 || yIndex<0) return ; + if (yIndex>=m_height) return ; + if (xIndex>=m_width) return ; + if (!m_cellFlipState) return ; + UnsignedByte *curVal = &m_cellFlipState[yIndex*m_flipStateWidth + (xIndex >> 3)]; + if (value) { + *curVal |= (1<<(xIndex&0x7)); + } else { + *curVal &= ~(1<<(xIndex&0x7)); + } +} + +/** Clears all flip state bits. +*/ +void WorldHeightMap::clearFlipStates(void) { + if (m_cellFlipState) { + memset(m_cellFlipState,0,m_flipStateWidth*m_height); //clear all flags + } +} + +//////////////////////////////////////////////////////////////////////////////m_SeismicUpdateFlag +Bool WorldHeightMap::getSeismicUpdateFlag(Int xIndex, Int yIndex) const +{ + if (xIndex<0 || yIndex<0) return false; + if (yIndex>=m_height) return false; + if (xIndex>=m_width) return false; + if (!m_seismicUpdateFlag) return false; + return m_seismicUpdateFlag[yIndex*m_seismicUpdateWidth + (xIndex >> 3)] & (1<<(xIndex&0x7)); +} +void WorldHeightMap::setSeismicUpdateFlag(Int xIndex, Int yIndex, Bool value) +{ + if (xIndex<0 || yIndex<0) return ; + if (yIndex>=m_height) return ; + if (xIndex>=m_width) return ; + if (!m_seismicUpdateFlag) return ; + UnsignedByte *curVal = &m_seismicUpdateFlag[yIndex*m_seismicUpdateWidth + (xIndex >> 3)]; + if (value) { + *curVal |= (1<<(xIndex&0x7)); + } else { + *curVal &= ~(1<<(xIndex&0x7)); + } +} +void WorldHeightMap::clearSeismicUpdateFlags(void) +{ + if (m_seismicUpdateFlag) { + memset(m_seismicUpdateFlag,0,m_seismicUpdateWidth*m_height); //clear all flags + } +} + +///////////////////////////////////////////////m_SeismicZVelocities +Real WorldHeightMap::getSeismicZVelocity(Int xIndex, Int yIndex) const +{ + if (xIndex<0 || yIndex<0) return false; + if (yIndex>=m_height) return false; + if (xIndex>=m_width) return false; + if (!m_seismicZVelocities) return false; + return m_seismicZVelocities[yIndex*m_width + xIndex]; +} +void WorldHeightMap::setSeismicZVelocity(Int xIndex, Int yIndex, Real value) +{ + if (xIndex<0 || yIndex<0) return ; + if (yIndex>=m_height) return ; + if (xIndex>=m_width) return ; + if (!m_seismicZVelocities) return ; + m_seismicZVelocities[yIndex*m_width + xIndex] = value; +} +void WorldHeightMap::fillSeismicZVelocities( Real value ) +{ + if (!m_seismicZVelocities) return ; + for (Int idx = 0; idx < m_width*m_height; ++idx) + m_seismicZVelocities[idx] = value; +} + +Real WorldHeightMap::getBilinearSampleSeismicZVelocity( Int x, Int y) +{ + if ( x < 0 || y < 0 ) return 0; + if ( y >= m_height ) return 0; + if ( x >= m_width ) return 0; + if (!m_seismicZVelocities) return 0; + + Real collector = 0.0f; + Real divisor = 0.0f; + + collector += m_seismicZVelocities[ y * m_width + x ]; + ++divisor; + + if ( y > 0 ) + { + collector += m_seismicZVelocities[ (y-1) * m_width + x ];//bottom + ++divisor; + + if( x > 0 ) + { + collector += m_seismicZVelocities[ (y-1) * m_width + (x-1) ];//lower left + ++divisor; + } + if ( x < m_width-1 ) + { + collector += m_seismicZVelocities[ (y-1) * m_width + (x+1) ];//lower right + ++divisor; + } + } + if ( y < m_height-1 ) + { + collector += m_seismicZVelocities[ (y+1) * m_width + x ];//top + ++divisor; + + if( x > 0 ) + { + collector += m_seismicZVelocities[ (y+1) * m_width + (x-1) ];//upper left + ++divisor; + } + if ( x < m_width-1 ) + { + collector += m_seismicZVelocities[ (y+1) * m_width + (x+1) ];//upper right + ++divisor; + } + } + if( x > 0 ) + { + collector += m_seismicZVelocities[ y * m_width + (x-1) ];//left + ++divisor; + } + if ( x < m_width-1 ) + { + collector += m_seismicZVelocities[ y * m_width + (x+1) ];//right + ++divisor; + } + + collector /= divisor; + + return collector; + +} + /** Get whether the cell is a cliff cell (impassable to ground vehicles). */ Bool WorldHeightMap::getCliffState(Int xIndex, Int yIndex) const @@ -739,6 +882,16 @@ Bool WorldHeightMap::ParseHeightMapData(DataChunkInput &file, DataChunkInfo *inf if (m_dataSize <= 0 || (m_dataSize != (m_width*m_height))) { throw ERROR_CORRUPT_FILE_FORMAT ; } + + Int numBytesX = (m_width+7)/8; //how many bytes to fit all bitflags + Int numBytesY = m_height; + m_seismicUpdateWidth=numBytesX; + m_seismicUpdateFlag = MSGNEW("WorldHeightMap::ParseHeightMapData _ m_seismicUpdateFlag allocated") UnsignedByte[numBytesX*numBytesY]; + clearSeismicUpdateFlags(); + m_seismicZVelocities = MSGNEW("WorldHeightMap_ParseHeightMapData _ zvelocities allocated") Real[m_dataSize]; + fillSeismicZVelocities( 0 ); + + file.readArrayOfBytes((char *)m_data, m_dataSize); // Resize me. if (info->version == K_HEIGHT_MAP_VERSION_1) { @@ -884,6 +1037,7 @@ void WorldHeightMap::readTexClass(TXTextureClass *texClass, TileData **tileData) */ Bool WorldHeightMap::ParseBlendTileData(DataChunkInput &file, DataChunkInfo *info, void *userData) { + int i, j; Int len = file.readInt(); if (m_dataSize != len) { throw ERROR_CORRUPT_FILE_FORMAT ; @@ -895,7 +1049,7 @@ Bool WorldHeightMap::ParseBlendTileData(DataChunkInput &file, DataChunkInfo *inf // Note - we have one less cell than the width & height. But for paranoia, allocate // extra row. jba. // - Int numBytesX = (m_width+1)/8; //how many bytes to fit all bitflags + Int numBytesX = (m_width+7)/8; //how many bytes to fit all bitflags Int numBytesY = m_height; m_flipStateWidth=numBytesX; @@ -918,7 +1072,18 @@ Bool WorldHeightMap::ParseBlendTileData(DataChunkInput &file, DataChunkInfo *inf file.readArrayOfBytes((char*)m_cliffInfoNdxes, m_dataSize*sizeof(Short)); } if (info->version >= K_BLEND_TILE_VERSION_7) { - file.readArrayOfBytes((char*)m_cellCliffState, m_height*m_flipStateWidth); + if (info->version==K_BLEND_TILE_VERSION_7) { + Int byteWidth = (m_width+1)/8; // previous incorrect length that got used to save the file. jba. [4/3/2003] + UnsignedByte *data = new UnsignedByte[m_height*byteWidth]; + file.readArrayOfBytes((char*)data, m_height*byteWidth); + for (j=0; j file loading here - int i; m_numTextureClasses = file.readInt(); DEBUG_ASSERTCRASH(m_numTextureClasses>0 && m_numTextureClasses<200, ("Unlikely m_numTextureClasses.")); for (i=0; ifindTemplate( name ) ); + TheThingFactory->findTemplate( name, FALSE ) ); //DEBUG_LOG(("obj %s owner %s",name.str(),d.getAsciiString(TheKey_originalOwner).str())); @@ -1138,9 +1302,12 @@ typedef struct { /// Count how many tiles come in from a targa file. -Int WorldHeightMap::countTiles(InputStream *pStr) +Int WorldHeightMap::countTiles(InputStream *pStr, Bool *halfTile) { TTargaHeader hdr; + if (halfTile) { + *halfTile = false; + } Int len = pStr->read(&hdr,sizeof(hdr)); if (len!=sizeof(hdr)) return(0); Int tileWidth = hdr.imageWidth/TILE_PIXEL_EXTENT; @@ -1170,6 +1337,10 @@ Int WorldHeightMap::countTiles(InputStream *pStr) if (tileWidth>=3 && tileHeight >=3) return(9); if (tileWidth>=2 && tileHeight >=2) return(4); if (tileWidth>=1 && tileHeight >=1) return(1); + if (halfTile && hdr.imageHeight==TILE_PIXEL_EXTENT/2 && hdr.imageWidth==TILE_PIXEL_EXTENT/2) { + *halfTile = true; + return 1; + } return(0); } /*Break down a .tga file into a collection of tiles. numRows * numRows total tiles.*/ @@ -1180,6 +1351,13 @@ Bool WorldHeightMap::readTiles(InputStream *pStr, TileData **tiles, Int numRows) Int tileWidth = hdr.imageWidth/TILE_PIXEL_EXTENT; Int tileHeight = hdr.imageHeight/TILE_PIXEL_EXTENT; + if (hdr.imageHeight==TILE_PIXEL_EXTENT/2) { + tileHeight = 1; + } + if (hdr.imageWidth==TILE_PIXEL_EXTENT/2) { + tileWidth = 1; + } + if (tileWidthread(&flag, 1); - repeatCount = flag&0x7f; - repeatCount++; - if (flag&0x80) { - running = true; + UnsignedByte r, g, b, a; + if (row < hdr.imageHeight) { + if (compressed && repeatCount==0) { + UnsignedByte flag; + pStr->read(&flag, 1); + repeatCount = flag&0x7f; + repeatCount++; + if (flag&0x80) { + running = true; + pStr->read(buf, bytesPerPixel); + } else { + running = false; + } + } + if (compressed) repeatCount--; + if (!running) { pStr->read(buf, bytesPerPixel); + } + r = buf[2]; g = buf[1]; b = buf[0]; + if (bytesPerPixel==4) { + a = buf[3]; } else { - running = false; + a = 255;// solid alpha. } - } - if (compressed) repeatCount--; - if (!running) { - pStr->read(buf, bytesPerPixel); + } else { + r = g = b = a = 0; } if (column >= (numRows*TILE_PIXEL_EXTENT)) continue; - r = buf[2]; g = buf[1]; b = buf[0]; - int tileNdx = (column/TILE_PIXEL_EXTENT) + numRows*(row/TILE_PIXEL_EXTENT); int pixelNdx = (column%TILE_PIXEL_EXTENT) + TILE_PIXEL_EXTENT*(row%TILE_PIXEL_EXTENT); @@ -1232,7 +1418,7 @@ Bool WorldHeightMap::readTiles(InputStream *pStr, TileData **tiles, Int numRows) *pixel++ = b; *pixel++ = g; *pixel++ = r; - *pixel = 0xFF; // solid alpha. + *pixel = a; } DEBUG_ASSERTCRASH(repeatCount==0, ("Invalid tga.")); @@ -1938,6 +2124,12 @@ void WorldHeightMap::getAlphaUVData(Int xIndex, Int yIndex, float U[4], float V[ #endif } +void WorldHeightMap::setTextureLOD(Int lod) +{ + if (m_terrainTex) + m_terrainTex->setLOD(lod); +} + TextureClass *WorldHeightMap::getTerrainTexture(void) { if (m_terrainTex == NULL) { @@ -2001,6 +2193,25 @@ TextureClass *WorldHeightMap::getEdgeTerrainTexture(void) return m_alphaEdgeTex; } +TerrainTextureClass *WorldHeightMap::getFlatTexture(Int xCell, Int yCell, Int cellWidth, Int pixelsPerCell) +{ + if (WW3D::Get_Texture_Reduction()) { + if (WW3D::Get_Texture_Reduction()>1) { + pixelsPerCell /= 4; + } else { + pixelsPerCell /= 2; + } + } + Int pow2Height = 1; + while (pow2HeightupdateFlat(this, xCell, yCell, cellWidth, pixelsPerCell); + return newTexture; +} + + Bool WorldHeightMap::setDrawOrg(Int xOrg, Int yOrg) { Int newX, newY; @@ -2161,3 +2372,174 @@ AsciiString WorldHeightMap::getTerrainNameAt(Real x, Real y) } +static UnsignedByte s_buffer[DATA_LEN_BYTES]; +static UnsignedByte s_blendBuffer[DATA_LEN_BYTES]; + +UnsignedByte * WorldHeightMap::getPointerToTileData(Int xIndex, Int yIndex, Int width) +{ + Int ndx = (yIndex*m_width)+xIndex; + if (yIndex<0 || xIndex<0 || xIndex>=m_width || yIndex>=m_height) { + return NULL; + } + if (ndx<0 || ndx>=m_dataSize) { + return NULL; + } + TBlendTileInfo *pBlend = NULL; + Short tileNdx = m_tileNdxes[ndx]; + if (getRawTileData(tileNdx, width, s_buffer, DATA_LEN_BYTES)) { + Short blendTileNdx = m_blendTileNdxes[ndx]; + if (blendTileNdx>0 && blendTileNdx < NUM_BLEND_TILES) { + pBlend = &m_blendedTiles[blendTileNdx]; + if (getRawTileData(pBlend->blendNdx, width, s_blendBuffer, DATA_LEN_BYTES)) { + UnsignedByte *pAlpha = getRGBAlphaDataForWidth(width, pBlend); + pAlpha += 3; // skip over the rgb to the a. + Int i, limit; + limit = width*width; + UnsignedByte *pBlendData = s_blendBuffer; + UnsignedByte *pDestData = s_buffer; + for (i=0; ihoriz) { + alphaTileNdx = K_HORIZ; + } else if (pBlend->vert) { + alphaTileNdx = K_VERT; + } else if (pBlend->rightDiagonal) { + alphaTileNdx = K_RDIAG; + if (pBlend->longDiagonal) alphaTileNdx=K_LRDIAG; + } else if (pBlend->leftDiagonal) { + alphaTileNdx = K_LDIAG; + if (pBlend->longDiagonal) alphaTileNdx=K_LLDIAG; + } + if (pBlend->inverted) { + alphaTileNdx += K_INV; + } + return m_alphaTiles[alphaTileNdx]->getRGBDataForWidth(width); +} + +void WorldHeightMap::setupAlphaTiles(void) +{ + TBlendTileInfo blendInfo; + if (m_alphaTiles[0] != NULL) return; + Int k; + for (k=0; k=K_INV) { + blendInfo.inverted = true; + baseK -= K_INV; + } + switch(baseK) { + case K_HORIZ : blendInfo.horiz = true; break; + case K_VERT : blendInfo.vert = true; break; + case K_LDIAG : blendInfo.leftDiagonal = true; break; + case K_RDIAG : blendInfo.rightDiagonal = true; break; + case K_LLDIAG : blendInfo.leftDiagonal = true; blendInfo.longDiagonal = true; break; + case K_LRDIAG : blendInfo.rightDiagonal = true; blendInfo.longDiagonal = true; break; + } + m_alphaTiles[k] = new TileData; + TileData *pTile = m_alphaTiles[k]; + + Int i, j; + UnsignedByte *pDest = pTile->getDataPtr(); + for (j=0; j 255) alpha = 255; + if (alpha<0) alpha = 0; + alpha = 255-alpha; + + pDest += 3; // skip blue, green & red bytes. + *pDest = alpha; // alpha. + //*pDest = 255; + pDest++; + } + } + pTile->updateMips(); + } +} + + +Bool WorldHeightMap::getRawTileData(Short tileNdx, Int width, + UnsignedByte *buffer, Int bufLen) +{ + TileData *pSrc = NULL; + if (tileNdx/4 < NUM_SOURCE_TILES) { + pSrc = m_sourceTiles[tileNdx/4]; + } + if (bufLen < (width*width*TILE_BYTES_PER_PIXEL)) { + return(false); + } + if (pSrc && pSrc->hasRGBDataForWidth(2*width)) { + Int j; + UnsignedByte *pSrcData = pSrc->getRGBDataForWidth(2*width); + Int xOffset=0; + Int yOffset=0; + if (tileNdx & 1) xOffset = width; + if (tileNdx & 2) yOffset = width; + for (j=0; j> 23; + int mask = exp < 127 ? 0 : 0xff800000; + exp -= 127; + mask >>= exp & 31; + x &= mask; + return *(float *)&x; +#endif +} + +// same here, fast floor function +__forceinline float fast_float_floor(float f) +{ + static unsigned almost1=(126<<23)|0x7fffff; + if (*(unsigned *)&f &0x80000000) + f-=*(float *)&almost1; + return fast_float_trunc(f); +} + +// same here, fast ceil function +__forceinline float fast_float_ceil(float f) +{ + static unsigned almost1=(126<<23)|0x7fffff; + if ( (*(unsigned *)&f &0x80000000)==0) + f+=*(float *)&almost1; + return fast_float_trunc(f); +} + //------------------------------------------------------------------------------------------------- #define REAL_TO_INT(x) ((Int)(x)) #define REAL_TO_UNSIGNEDINT(x) ((UnsignedInt)(x)) @@ -100,14 +146,18 @@ __forceinline long fast_float2long_round(float f) #define REAL_TO_BYTE(x) ((Byte)(x)) #define REAL_TO_UNSIGNEDBYTE(x) ((UnsignedByte)(x)) #define REAL_TO_CHAR(x) ((Char)(x)) -#define DOUBLE_TO_REAL(x) ((Real) (x)) -#define DOUBLE_TO_INT(x) ((Int) (x)) -#define INT_TO_REAL(x) ((Real) (x)) +#define DOUBLE_TO_REAL(x) ((Real)(x)) +#define DOUBLE_TO_INT(x) ((Int)(x)) +#define INT_TO_REAL(x) ((Real)(x)) // once we've ceiled/floored, trunc and round are identical, and currently, round is faster... (srj) #define REAL_TO_INT_CEIL(x) (fast_float2long_round(ceilf(x))) #define REAL_TO_INT_FLOOR(x) (fast_float2long_round(floorf(x))) +#define FAST_REAL_TRUNC(x) fast_float_trunc(x) +#define FAST_REAL_CEIL(x) fast_float_ceil(x) +#define FAST_REAL_FLOOR(x) fast_float_floor(x) + //-------------------------------------------------------------------- // Derived type definitions //-------------------------------------------------------------------- diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.cpp index 38477273fe..4b151ba765 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.cpp @@ -535,6 +535,7 @@ void DX8Caps::Compute_Caps(WW3DFormat display_format, const D3DADAPTER_IDENTIFIE } supportGamma=((swVPCaps.Caps2&D3DCAPS2_FULLSCREENGAMMA)==D3DCAPS2_FULLSCREENGAMMA); + SupportPointSprites = (caps.MaxPointSize > 1.0f); MaxTexturesPerPass=MAX_TEXTURE_STAGES; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.h index b988cf269a..69a793ae81 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.h @@ -215,6 +215,7 @@ class DX8Caps bool Support_Bump_Envmap() const { return SupportBumpEnvmap; } bool Support_Bump_Envmap_Luminance() const { return SupportBumpEnvmapLuminance; } bool Support_Dot3() const { return SupportDot3; } + bool Support_PointSprites() const { return SupportPointSprites; } int Get_Max_Textures_Per_Pass() const { return MaxTexturesPerPass; } // ------------------------------------------------------------------------- @@ -275,6 +276,7 @@ class DX8Caps bool SupportRenderToTextureFormat[WW3D_FORMAT_COUNT]; bool SupportDepthStencilFormat[WW3D_ZFORMAT_COUNT]; bool SupportDot3; + bool SupportPointSprites; int MaxTexturesPerPass; int VertexShaderVersion; int PixelShaderVersion; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/shader.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/shader.cpp index db5caf2559..809a7d2660 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/shader.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/shader.cpp @@ -615,17 +615,17 @@ void ShaderClass::Apply() } break; - // Bump map is a hack currently as we only have two stages in use! - case ShaderClass::GRADIENT_DOTPRODUCT3: - if(TextureOpCaps & D3DTEXOPCAPS_DOTPRODUCT3) - { - PricOp = D3DTOP_DOTPRODUCT3; - PricArg1 = D3DTA_TEXTURE; - PricArg2 = D3DTA_DIFFUSE; - PriaOp = D3DTOP_DISABLE; - PriaArg1 = D3DTA_TEXTURE; - PriaArg2 = D3DTA_CURRENT; - } + case ShaderClass::GRADIENT_MODULATE2X: + //Modulate Alpha + if(!(TextureOpCaps & D3DTOP_MODULATE2X)) + PricOp = D3DTOP_MODULATE; + else + PricOp = D3DTOP_MODULATE2X; + PricArg1 = D3DTA_TEXTURE; + PricArg2 = D3DTA_DIFFUSE; + PriaOp = D3DTOP_MODULATE; + PriaArg1 = D3DTA_TEXTURE; + PriaArg2 = D3DTA_DIFFUSE; break; } } @@ -999,7 +999,7 @@ const StringClass& ShaderClass::Get_Description(StringClass& str) const case GRADIENT_ADD: str+="GRADIENT_ADD | "; break; case GRADIENT_BUMPENVMAP: str+="GRADIENT_BUMPENVMAP | "; break; case GRADIENT_BUMPENVMAPLUMINANCE: str+="GRADIENT_BUMPENVMAPLUMINANCE | "; break; - case GRADIENT_DOTPRODUCT3: str+="GRADIENT_DOTPRODUCT3 | "; break; + case GRADIENT_MODULATE2X: str+="GRADIENT_MODULATE2X | "; break; } switch (Get_Secondary_Gradient()) { diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/shader.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/shader.h index 3d7141f5a9..e3c1d7ec01 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/shader.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/shader.h @@ -166,12 +166,12 @@ class ShaderClass enum PriGradientType { - GRADIENT_DISABLE=0, // 000 disable primary gradient (same as OpenGL 'decal' texture blend) - GRADIENT_MODULATE, // 001 modulate fragment ARGB by gradient ARGB (default) - GRADIENT_ADD, // 010 add gradient RGB to fragment RGB, copy gradient A to fragment A - GRADIENT_BUMPENVMAP, // 011 - GRADIENT_BUMPENVMAPLUMINANCE, // 100 - GRADIENT_DOTPRODUCT3, // 101 + GRADIENT_DISABLE=0, // 000 disable primary gradient (same as OpenGL 'decal' texture blend) + GRADIENT_MODULATE, // 001 modulate fragment ARGB by gradient ARGB (default) + GRADIENT_ADD, // 010 add gradient RGB to fragment RGB, copy gradient A to fragment A + GRADIENT_BUMPENVMAP, // 011 environment-mapped bump mapping + GRADIENT_BUMPENVMAPLUMINANCE, // 100 environment-mapped bump mapping with luminance control + GRADIENT_MODULATE2X, // 101 modulate fragment ARGB by gradient ARGB and multiply RGB by 2 }; enum SecGradientType diff --git a/Generals/Code/Tools/WorldBuilder/src/WorldBuilder.cpp b/Generals/Code/Tools/WorldBuilder/src/WorldBuilder.cpp index 9603cd1ec8..aa8be4c583 100644 --- a/Generals/Code/Tools/WorldBuilder/src/WorldBuilder.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/WorldBuilder.cpp @@ -413,6 +413,8 @@ BOOL CWorldBuilderApp::InitInstance() TheWritableGlobalData->m_shroudOn = FALSE; #endif + TheWritableGlobalData->m_isWorldBuilder = TRUE; + // Change the registry key under which our settings are stored. // TODO: You should modify this string to be something appropriate // such as the name of your company or organization. diff --git a/GeneralsMD/Code/GameEngine/CMakeLists.txt b/GeneralsMD/Code/GameEngine/CMakeLists.txt index 065d37a8fb..f2d8f8e005 100644 --- a/GeneralsMD/Code/GameEngine/CMakeLists.txt +++ b/GeneralsMD/Code/GameEngine/CMakeLists.txt @@ -219,7 +219,7 @@ set(GAMEENGINE_SRC Include/GameClient/ShellHooks.h Include/GameClient/ShellMenuScheme.h # Include/GameClient/Smudge.h - Include/GameClient/Snow.h +# Include/GameClient/Snow.h Include/GameClient/Statistics.h Include/GameClient/TerrainRoads.h Include/GameClient/TerrainVisual.h @@ -810,7 +810,7 @@ set(GAMEENGINE_SRC # Source/GameClient/ParabolicEase.cpp Source/GameClient/RadiusDecal.cpp Source/GameClient/SelectionInfo.cpp - Source/GameClient/Snow.cpp +# Source/GameClient/Snow.cpp Source/GameClient/Statistics.cpp Source/GameClient/System/Anim2D.cpp Source/GameClient/System/CampaignManager.cpp diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/TerrainVisual.h b/GeneralsMD/Code/GameEngine/Include/GameClient/TerrainVisual.h index 5fd50282f4..8463ff83ab 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/TerrainVisual.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/TerrainVisual.h @@ -47,8 +47,6 @@ struct SeismicSimulationNode; class SeismicSimulationFilterBase; - - #define DEFAULT_SEISMIC_SIMULATION_MAGNITUDE (20.0f) struct SeismicSimulationNode; // just a forward declaration folks, no cause for alarm class SeismicSimulationFilterBase @@ -65,10 +63,6 @@ class SeismicSimulationFilterBase virtual Real applyGravityCallback( Real velocityIn ) = 0; }; - - - - struct SeismicSimulationNode { SeismicSimulationNode() @@ -159,11 +153,6 @@ class DomeStyleSeismicFilter : public SeismicSimulationFilterBase }; - - - - - //------------------------------------------------------------------------------------------------- /** LOD values for terrain, keep this in sync with TerrainLODNames[] */ //------------------------------------------------------------------------------------------------- @@ -303,7 +292,6 @@ class TerrainVisual : public Snapshot, //////////////////////////////////////////////////// - /// Replace the skybox texture virtual void replaceSkyboxTextures(const AsciiString *oldTexName[NumSkyboxTextures], const AsciiString *newTexName[NumSkyboxTextures])=0; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp index fd2aff3e4a..7b200f35d8 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp @@ -130,11 +130,6 @@ void TerrainVisual::loadPostProcess( void ) } - - - - - SeismicSimulationFilterBase::SeismicSimStatusCode DomeStyleSeismicFilter::filterCallback( WorldHeightMapInterfaceClass *heightMap, const SeismicSimulationNode *node ) { diff --git a/GeneralsMD/Code/GameEngineDevice/CMakeLists.txt b/GeneralsMD/Code/GameEngineDevice/CMakeLists.txt index c96e1f0b27..34aceb1817 100644 --- a/GeneralsMD/Code/GameEngineDevice/CMakeLists.txt +++ b/GeneralsMD/Code/GameEngineDevice/CMakeLists.txt @@ -6,9 +6,9 @@ set(GAMEENGINEDEVICE_SRC Include/W3DDevice/Common/W3DModuleFactory.h # Include/W3DDevice/Common/W3DRadar.h Include/W3DDevice/Common/W3DThingFactory.h - Include/W3DDevice/GameClient/BaseHeightMap.h +# Include/W3DDevice/GameClient/BaseHeightMap.h # Include/W3DDevice/GameClient/camerashakesystem.h - Include/W3DDevice/GameClient/FlatHeightMap.h +# Include/W3DDevice/GameClient/FlatHeightMap.h Include/W3DDevice/GameClient/HeightMap.h Include/W3DDevice/GameClient/Module/W3DDebrisDraw.h Include/W3DDevice/GameClient/Module/W3DDefaultDraw.h @@ -20,14 +20,14 @@ set(GAMEENGINEDEVICE_SRC Include/W3DDevice/GameClient/Module/W3DOverlordTruckDraw.h Include/W3DDevice/GameClient/Module/W3DPoliceCarDraw.h Include/W3DDevice/GameClient/Module/W3DProjectileStreamDraw.h - Include/W3DDevice/GameClient/Module/W3DPropDraw.h +# Include/W3DDevice/GameClient/Module/W3DPropDraw.h Include/W3DDevice/GameClient/Module/W3DRopeDraw.h Include/W3DDevice/GameClient/Module/W3DScienceModelDraw.h Include/W3DDevice/GameClient/Module/W3DSupplyDraw.h Include/W3DDevice/GameClient/Module/W3DTankDraw.h Include/W3DDevice/GameClient/Module/W3DTankTruckDraw.h Include/W3DDevice/GameClient/Module/W3DTracerDraw.h - Include/W3DDevice/GameClient/Module/W3DTreeDraw.h +# Include/W3DDevice/GameClient/Module/W3DTreeDraw.h Include/W3DDevice/GameClient/Module/W3DTruckDraw.h Include/W3DDevice/GameClient/TerrainTex.h Include/W3DDevice/GameClient/TileData.h @@ -57,16 +57,16 @@ set(GAMEENGINEDEVICE_SRC Include/W3DDevice/GameClient/W3DParticleSys.h Include/W3DDevice/GameClient/W3DPoly.h Include/W3DDevice/GameClient/W3DProjectedShadow.h - Include/W3DDevice/GameClient/W3DPropBuffer.h +# Include/W3DDevice/GameClient/W3DPropBuffer.h Include/W3DDevice/GameClient/W3DRoadBuffer.h Include/W3DDevice/GameClient/W3DScene.h # Include/W3DDevice/GameClient/W3DShaderManager.h Include/W3DDevice/GameClient/W3DShadow.h Include/W3DDevice/GameClient/W3DShroud.h # Include/W3DDevice/GameClient/W3DSmudge.h - Include/W3DDevice/GameClient/W3DSnow.h +# Include/W3DDevice/GameClient/W3DSnow.h Include/W3DDevice/GameClient/W3DStatusCircle.h - Include/W3DDevice/GameClient/W3DTerrainBackground.h +# Include/W3DDevice/GameClient/W3DTerrainBackground.h Include/W3DDevice/GameClient/W3DTerrainTracks.h Include/W3DDevice/GameClient/W3DTerrainVisual.h Include/W3DDevice/GameClient/W3DTreeBuffer.h @@ -97,7 +97,7 @@ set(GAMEENGINEDEVICE_SRC Source/W3DDevice/Common/Thing/W3DModuleFactory.cpp Source/W3DDevice/Common/Thing/W3DThingFactory.cpp Source/W3DDevice/Common/W3DConvert.cpp - Source/W3DDevice/GameClient/BaseHeightMap.cpp +# Source/W3DDevice/GameClient/BaseHeightMap.cpp # Source/W3DDevice/GameClient/camerashakesystem.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DDebrisDraw.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DDefaultDraw.cpp @@ -109,16 +109,16 @@ set(GAMEENGINEDEVICE_SRC Source/W3DDevice/GameClient/Drawable/Draw/W3DOverlordTruckDraw.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DPoliceCarDraw.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DProjectileStreamDraw.cpp - Source/W3DDevice/GameClient/Drawable/Draw/W3DPropDraw.cpp +# Source/W3DDevice/GameClient/Drawable/Draw/W3DPropDraw.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DRopeDraw.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DScienceModelDraw.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DSupplyDraw.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DTankDraw.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DTankTruckDraw.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DTracerDraw.cpp - Source/W3DDevice/GameClient/Drawable/Draw/W3DTreeDraw.cpp +# Source/W3DDevice/GameClient/Drawable/Draw/W3DTreeDraw.cpp Source/W3DDevice/GameClient/Drawable/Draw/W3DTruckDraw.cpp - Source/W3DDevice/GameClient/FlatHeightMap.cpp +# Source/W3DDevice/GameClient/FlatHeightMap.cpp Source/W3DDevice/GameClient/GUI/Gadget/W3DCheckBox.cpp Source/W3DDevice/GameClient/GUI/Gadget/W3DComboBox.cpp Source/W3DDevice/GameClient/GUI/Gadget/W3DHorizontalSlider.cpp @@ -160,15 +160,15 @@ set(GAMEENGINEDEVICE_SRC Source/W3DDevice/GameClient/W3DMouse.cpp Source/W3DDevice/GameClient/W3DParticleSys.cpp Source/W3DDevice/GameClient/W3DPoly.cpp - Source/W3DDevice/GameClient/W3DPropBuffer.cpp +# Source/W3DDevice/GameClient/W3DPropBuffer.cpp Source/W3DDevice/GameClient/W3DRoadBuffer.cpp Source/W3DDevice/GameClient/W3DScene.cpp # Source/W3DDevice/GameClient/W3DShaderManager.cpp Source/W3DDevice/GameClient/W3DShroud.cpp # Source/W3DDevice/GameClient/W3DSmudge.cpp - Source/W3DDevice/GameClient/W3DSnow.cpp +# Source/W3DDevice/GameClient/W3DSnow.cpp Source/W3DDevice/GameClient/W3DStatusCircle.cpp - Source/W3DDevice/GameClient/W3DTerrainBackground.cpp +# Source/W3DDevice/GameClient/W3DTerrainBackground.cpp Source/W3DDevice/GameClient/W3DTerrainTracks.cpp Source/W3DDevice/GameClient/W3DTerrainVisual.cpp Source/W3DDevice/GameClient/W3DTreeBuffer.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainVisual.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainVisual.h index 35046b9a59..56f80c570e 100644 --- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainVisual.h +++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainVisual.h @@ -38,12 +38,6 @@ class WaterHandle; class BaseHeightMapRenderObjClass; class WorldHeightMap; - - - - - - //------------------------------------------------------------------------------------------------- /** W3D impelmentation of visual terrain details singleton */ //------------------------------------------------------------------------------------------------- @@ -150,9 +144,6 @@ class W3DTerrainVisual : public TerrainVisual //////////////////////////////////////////////////// //////////////////////////////////////////////////// - - - protected: // snapshot methods @@ -160,8 +151,6 @@ class W3DTerrainVisual : public TerrainVisual virtual void xfer( Xfer *xfer ); virtual void loadPostProcess( void ); - - #ifdef DO_SEISMIC_SIMULATIONS //////////////////////////////////////////////////// //////////////////////////////////////////////////// @@ -175,8 +164,6 @@ class W3DTerrainVisual : public TerrainVisual //////////////////////////////////////////////////// #endif - - BaseHeightMapRenderObjClass *m_terrainRenderObject; ///< W3D render object for terrain WaterRenderObjClass *m_waterRenderObject; ///< W3D render object for water plane @@ -191,7 +178,4 @@ class W3DTerrainVisual : public TerrainVisual AsciiString m_currentSkyboxTexNames[NumSkyboxTextures]; ///GetSurfaceLevel(0, &surface_level)); DX8_ErrorCode(surface_level->GetDesc(&surface_desc)); if (surface_desc.Width < TEXTURE_WIDTH) { + surface_level->Release(); return 0; } @@ -944,7 +945,6 @@ void CloudMapTerrainTextureClass::Apply(unsigned int stage) // Do the base apply. TextureClass::Apply(stage); - return; #if 0 // obsolete /* previous setup */ if (TheGlobalData && TheGlobalData->m_trilinearTerrainTex) { diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp index d1e770c2f0..77935049c5 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp @@ -169,16 +169,6 @@ W3DTerrainVisual::W3DTerrainVisual() m_clientHeightMap = NULL; #endif - - - - - - - - - - } //------------------------------------------------------------------------------------------------- @@ -344,7 +334,6 @@ void W3DTerrainVisual::update( void ) if( m_waterRenderObject ) m_waterRenderObject->update(); - } @@ -448,10 +437,6 @@ void W3DTerrainVisual::handleSeismicSimulations( void ) } } - - - - } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -573,9 +558,6 @@ Bool W3DTerrainVisual::load( AsciiString filename ) REF_PTR_RELEASE( m_logicHeightMap ); m_logicHeightMap = NEW WorldHeightMap(pStrm); - - - #ifdef DO_SEISMIC_SIMULATIONS fileStrm.close(); @@ -587,13 +569,6 @@ Bool W3DTerrainVisual::load( AsciiString filename ) #endif - - - - - - - // Add any lights loaded by map. MapObject *pMapObj = MapObject::getFirstMapObject(); while (pMapObj) @@ -656,7 +631,7 @@ Bool W3DTerrainVisual::load( AsciiString filename ) if (W3DDisplay::m_3DScene != NULL) { W3DDebugIcons *icons = NEW W3DDebugIcons; - W3DDisplay::m_3DScene->Add_Render_Object( icons ); + W3DDisplay::m_3DScene->Add_Render_Object( icons ); icons->Release_Ref(); // belongs to scene. } #endif @@ -770,7 +745,6 @@ TerrainType *W3DTerrainVisual::getTerrainTile( Real x, Real y ) { TerrainType *tile = NULL; - #ifdef DO_SEISMIC_SIMULATIONS if( m_clientHeightMap ) { @@ -785,11 +759,7 @@ TerrainType *W3DTerrainVisual::getTerrainTile( Real x, Real y ) } #endif - - - return tile; - } // ------------------------------------------------------------------------------------------------ @@ -1175,14 +1145,18 @@ void W3DTerrainVisual::crc( Xfer *xfer ) * Version Info: * 1: Initial version * 2: Add height map heights. - * 3: Add client side trees & props. jba. + * 3: Add client side trees & props. jba. (Added for Zero Hour) */ // ------------------------------------------------------------------------------------------------ void W3DTerrainVisual::xfer( Xfer *xfer ) { // version +#if RTS_GENERALS && RETAIL_COMPATIBLE_XFER_SAVE + XferVersion currentVersion = 2; +#else XferVersion currentVersion = 3; +#endif XferVersion version = currentVersion; xfer->xferVersion( &version, currentVersion ); @@ -1258,8 +1232,6 @@ void W3DTerrainVisual::xfer( Xfer *xfer ) xfer->xferSnapshot(m_terrainRenderObject); } - - // XFER // // X R // // X R // @@ -1274,10 +1246,6 @@ void W3DTerrainVisual::xfer( Xfer *xfer ) // X R // // XFER // - - - - } // ------------------------------------------------------------------------------------------------ diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp index 6fe0998491..52384dfed5 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp @@ -580,9 +580,6 @@ void WorldHeightMap::clearFlipStates(void) { } } - - - //////////////////////////////////////////////////////////////////////////////m_SeismicUpdateFlag Bool WorldHeightMap::getSeismicUpdateFlag(Int xIndex, Int yIndex) const { @@ -698,21 +695,6 @@ Real WorldHeightMap::getBilinearSampleSeismicZVelocity( Int x, Int y) } - - - - - - - - - - - - - - - /** Get whether the cell is a cliff cell (impassable to ground vehicles). */ Bool WorldHeightMap::getCliffState(Int xIndex, Int yIndex) const diff --git a/scripts/cpp/unify_move_files.py b/scripts/cpp/unify_move_files.py index 42ec8582a2..5440afa4cd 100644 --- a/scripts/cpp/unify_move_files.py +++ b/scripts/cpp/unify_move_files.py @@ -218,6 +218,23 @@ def main(): #unify_file(Game.ZEROHOUR, "GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvp", Game.CORE, "GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvp") #unify_file(Game.ZEROHOUR, "GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvv", Game.CORE, "GameEngineDevice/Source/W3DDevice/GameClient/Water/wave.nvv") + #unify_move_file(Game.ZEROHOUR, "GameEngine/Include/GameClient/Snow.h", Game.CORE, "GameEngine/Include/GameClient/Snow.h") + #unify_move_file(Game.ZEROHOUR, "GameEngine/Source/GameClient/Snow.cpp", Game.CORE, "GameEngine/Source/GameClient/Snow.cpp") + #unify_move_file(Game.ZEROHOUR, "GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h", Game.CORE, "GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h") + #unify_move_file(Game.ZEROHOUR, "GameEngineDevice/Include/W3DDevice/GameClient/FlatHeightMap.h", Game.CORE, "GameEngineDevice/Include/W3DDevice/GameClient/FlatHeightMap.h") + #unify_move_file(Game.ZEROHOUR, "GameEngineDevice/Include/W3DDevice/GameClient/W3DPropBuffer.h", Game.CORE, "GameEngineDevice/Include/W3DDevice/GameClient/W3DPropBuffer.h") + #unify_move_file(Game.ZEROHOUR, "GameEngineDevice/Include/W3DDevice/GameClient/W3DSnow.h", Game.CORE, "GameEngineDevice/Include/W3DDevice/GameClient/W3DSnow.h") + #unify_move_file(Game.ZEROHOUR, "GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainBackground.h", Game.CORE, "GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainBackground.h") + #unify_move_file(Game.ZEROHOUR, "GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DPropDraw.h", Game.CORE, "GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DPropDraw.h") + #unify_move_file(Game.ZEROHOUR, "GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DTreeDraw.h", Game.CORE, "GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DTreeDraw.h") + #unify_move_file(Game.ZEROHOUR, "GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp", Game.CORE, "GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp") + #unify_move_file(Game.ZEROHOUR, "GameEngineDevice/Source/W3DDevice/GameClient/FlatHeightMap.cpp", Game.CORE, "GameEngineDevice/Source/W3DDevice/GameClient/FlatHeightMap.cpp") + #unify_move_file(Game.ZEROHOUR, "GameEngineDevice/Source/W3DDevice/GameClient/W3DPropBuffer.cpp", Game.CORE, "GameEngineDevice/Source/W3DDevice/GameClient/W3DPropBuffer.cpp") + #unify_move_file(Game.ZEROHOUR, "GameEngineDevice/Source/W3DDevice/GameClient/W3DSnow.cpp", Game.CORE, "GameEngineDevice/Source/W3DDevice/GameClient/W3DSnow.cpp") + #unify_move_file(Game.ZEROHOUR, "GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainBackground.cpp", Game.CORE, "GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainBackground.cpp") + #unify_move_file(Game.ZEROHOUR, "GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DPropDraw.cpp", Game.CORE, "GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DPropDraw.cpp") + #unify_move_file(Game.ZEROHOUR, "GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DTreeDraw.cpp", Game.CORE, "GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DTreeDraw.cpp") + return From ce4e5957d90d9caa199cdf3a1ef5940fc219d187 Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Sun, 14 Dec 2025 13:41:43 +0100 Subject: [PATCH 36/70] unify(heightmap): Move Height Map and Terrain related files to Core (#1991) --- Core/GameEngine/CMakeLists.txt | 14 +- .../GameEngine/Include/Common/MapObject.h | 0 .../GameEngine/Include/GameClient/MapUtil.h | 0 .../Include/GameClient/TerrainRoads.h | 0 .../Include/GameClient/TerrainVisual.h | 0 .../GameEngine/Source/GameClient/MapUtil.cpp | 0 .../GameClient/Terrain/TerrainRoads.cpp | 0 .../GameClient/Terrain/TerrainVisual.cpp | 0 Core/GameEngineDevice/CMakeLists.txt | 28 +- .../Include/W3DDevice/GameClient/HeightMap.h | 0 .../Include/W3DDevice/GameClient/TerrainTex.h | 0 .../Include/W3DDevice/GameClient/TileData.h | 0 .../W3DDevice/GameClient/W3DTerrainTracks.h | 0 .../W3DDevice/GameClient/W3DTerrainVisual.h | 0 .../W3DDevice/GameClient/W3DTreeBuffer.h | 0 .../W3DDevice/GameClient/WorldHeightMap.h | 0 .../Source/W3DDevice/GameClient/HeightMap.cpp | 0 .../W3DDevice/GameClient/TerrainTex.cpp | 0 .../Source/W3DDevice/GameClient/TileData.cpp | 0 .../W3DDevice/GameClient/W3DTerrainTracks.cpp | 0 .../W3DDevice/GameClient/W3DTerrainVisual.cpp | 0 .../W3DDevice/GameClient/W3DTreeBuffer.cpp | 0 .../W3DDevice/GameClient/WorldHeightMap.cpp | 0 Generals/Code/GameEngine/CMakeLists.txt | 14 +- .../GameEngine/Include/Common/MapObject.h | 182 -- .../GameEngine/Include/GameClient/MapUtil.h | 150 - .../Include/GameClient/TerrainRoads.h | 229 -- .../Include/GameClient/TerrainVisual.h | 310 -- .../GameEngine/Source/GameClient/MapUtil.cpp | 1348 --------- .../GameClient/Terrain/TerrainRoads.cpp | 458 --- .../GameClient/Terrain/TerrainVisual.cpp | 208 -- Generals/Code/GameEngineDevice/CMakeLists.txt | 28 +- .../Include/W3DDevice/GameClient/HeightMap.h | 119 - .../Include/W3DDevice/GameClient/TerrainTex.h | 143 - .../Include/W3DDevice/GameClient/TileData.h | 101 - .../W3DDevice/GameClient/W3DTerrainTracks.h | 155 - .../W3DDevice/GameClient/W3DTerrainVisual.h | 181 -- .../W3DDevice/GameClient/W3DTreeBuffer.h | 283 -- .../W3DDevice/GameClient/WorldHeightMap.h | 319 --- .../Source/W3DDevice/GameClient/HeightMap.cpp | 2445 ---------------- .../W3DDevice/GameClient/TerrainTex.cpp | 1142 -------- .../Source/W3DDevice/GameClient/TileData.cpp | 107 - .../W3DDevice/GameClient/W3DTerrainTracks.cpp | 974 ------- .../W3DDevice/GameClient/W3DTerrainVisual.cpp | 1261 -------- .../W3DDevice/GameClient/W3DTreeBuffer.cpp | 2040 ------------- .../W3DDevice/GameClient/WorldHeightMap.cpp | 2545 ----------------- GeneralsMD/Code/GameEngine/CMakeLists.txt | 14 +- .../Code/GameEngineDevice/CMakeLists.txt | 28 +- scripts/cpp/unify_move_files.py | 22 + 49 files changed, 85 insertions(+), 14763 deletions(-) rename {GeneralsMD/Code => Core}/GameEngine/Include/Common/MapObject.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Include/GameClient/MapUtil.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Include/GameClient/TerrainRoads.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Include/GameClient/TerrainVisual.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Source/GameClient/MapUtil.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngine/Source/GameClient/Terrain/TerrainRoads.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Include/W3DDevice/GameClient/TerrainTex.h (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Include/W3DDevice/GameClient/TileData.h (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainTracks.h (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainVisual.h (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Include/W3DDevice/GameClient/W3DTreeBuffer.h (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Include/W3DDevice/GameClient/WorldHeightMap.h (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Source/W3DDevice/GameClient/TileData.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainTracks.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp (100%) delete mode 100644 Generals/Code/GameEngine/Include/Common/MapObject.h delete mode 100644 Generals/Code/GameEngine/Include/GameClient/MapUtil.h delete mode 100644 Generals/Code/GameEngine/Include/GameClient/TerrainRoads.h delete mode 100644 Generals/Code/GameEngine/Include/GameClient/TerrainVisual.h delete mode 100644 Generals/Code/GameEngine/Source/GameClient/MapUtil.cpp delete mode 100644 Generals/Code/GameEngine/Source/GameClient/Terrain/TerrainRoads.cpp delete mode 100644 Generals/Code/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp delete mode 100644 Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h delete mode 100644 Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/TerrainTex.h delete mode 100644 Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/TileData.h delete mode 100644 Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainTracks.h delete mode 100644 Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainVisual.h delete mode 100644 Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTreeBuffer.h delete mode 100644 Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/WorldHeightMap.h delete mode 100644 Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp delete mode 100644 Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp delete mode 100644 Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/TileData.cpp delete mode 100644 Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainTracks.cpp delete mode 100644 Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp delete mode 100644 Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp delete mode 100644 Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp diff --git a/Core/GameEngine/CMakeLists.txt b/Core/GameEngine/CMakeLists.txt index 53a0bc08e6..cd3cb89e9e 100644 --- a/Core/GameEngine/CMakeLists.txt +++ b/Core/GameEngine/CMakeLists.txt @@ -69,7 +69,7 @@ set(GAMEENGINE_SRC # Include/Common/List.h Include/Common/LocalFile.h Include/Common/LocalFileSystem.h -# Include/Common/MapObject.h + Include/Common/MapObject.h # Include/Common/MapReaderWriterInfo.h # Include/Common/MessageStream.h Include/Common/MiniDumper.h @@ -204,7 +204,7 @@ set(GAMEENGINE_SRC # Include/GameClient/Line2D.h # Include/GameClient/LoadScreen.h # Include/GameClient/LookAtXlat.h -# Include/GameClient/MapUtil.h + Include/GameClient/MapUtil.h # Include/GameClient/MessageBox.h # Include/GameClient/MetaEvent.h # Include/GameClient/Module/AnimatedParticleSysBoneClientUpdate.h @@ -226,8 +226,8 @@ set(GAMEENGINE_SRC Include/GameClient/Smudge.h Include/GameClient/Snow.h # Include/GameClient/Statistics.h -# Include/GameClient/TerrainRoads.h -# Include/GameClient/TerrainVisual.h + Include/GameClient/TerrainRoads.h + Include/GameClient/TerrainVisual.h Include/GameClient/VideoPlayer.h Include/GameClient/View.h Include/GameClient/Water.h @@ -807,7 +807,7 @@ set(GAMEENGINE_SRC # Source/GameClient/Input/Mouse.cpp # Source/GameClient/LanguageFilter.cpp # Source/GameClient/Line2D.cpp -# Source/GameClient/MapUtil.cpp + Source/GameClient/MapUtil.cpp # Source/GameClient/MessageStream/CommandXlat.cpp # Source/GameClient/MessageStream/GUICommandTranslator.cpp # Source/GameClient/MessageStream/HintSpy.cpp @@ -830,8 +830,8 @@ set(GAMEENGINE_SRC # 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/Terrain/TerrainRoads.cpp + Source/GameClient/Terrain/TerrainVisual.cpp Source/GameClient/VideoPlayer.cpp Source/GameClient/VideoStream.cpp Source/GameClient/View.cpp diff --git a/GeneralsMD/Code/GameEngine/Include/Common/MapObject.h b/Core/GameEngine/Include/Common/MapObject.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/Common/MapObject.h rename to Core/GameEngine/Include/Common/MapObject.h diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/MapUtil.h b/Core/GameEngine/Include/GameClient/MapUtil.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/GameClient/MapUtil.h rename to Core/GameEngine/Include/GameClient/MapUtil.h diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/TerrainRoads.h b/Core/GameEngine/Include/GameClient/TerrainRoads.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/GameClient/TerrainRoads.h rename to Core/GameEngine/Include/GameClient/TerrainRoads.h diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/TerrainVisual.h b/Core/GameEngine/Include/GameClient/TerrainVisual.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/GameClient/TerrainVisual.h rename to Core/GameEngine/Include/GameClient/TerrainVisual.h diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MapUtil.cpp b/Core/GameEngine/Source/GameClient/MapUtil.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/GameClient/MapUtil.cpp rename to Core/GameEngine/Source/GameClient/MapUtil.cpp diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Terrain/TerrainRoads.cpp b/Core/GameEngine/Source/GameClient/Terrain/TerrainRoads.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/GameClient/Terrain/TerrainRoads.cpp rename to Core/GameEngine/Source/GameClient/Terrain/TerrainRoads.cpp diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp b/Core/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp rename to Core/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp diff --git a/Core/GameEngineDevice/CMakeLists.txt b/Core/GameEngineDevice/CMakeLists.txt index 32bd6e6557..7ebd9b0294 100644 --- a/Core/GameEngineDevice/CMakeLists.txt +++ b/Core/GameEngineDevice/CMakeLists.txt @@ -9,7 +9,7 @@ set(GAMEENGINEDEVICE_SRC Include/W3DDevice/GameClient/BaseHeightMap.h # Include/W3DDevice/GameClient/camerashakesystem.h Include/W3DDevice/GameClient/FlatHeightMap.h -# Include/W3DDevice/GameClient/HeightMap.h + Include/W3DDevice/GameClient/HeightMap.h # Include/W3DDevice/GameClient/Module/W3DDebrisDraw.h # Include/W3DDevice/GameClient/Module/W3DDefaultDraw.h # Include/W3DDevice/GameClient/Module/W3DDependencyModelDraw.h @@ -29,8 +29,8 @@ set(GAMEENGINEDEVICE_SRC # Include/W3DDevice/GameClient/Module/W3DTracerDraw.h Include/W3DDevice/GameClient/Module/W3DTreeDraw.h # Include/W3DDevice/GameClient/Module/W3DTruckDraw.h -# Include/W3DDevice/GameClient/TerrainTex.h -# Include/W3DDevice/GameClient/TileData.h + Include/W3DDevice/GameClient/TerrainTex.h + Include/W3DDevice/GameClient/TileData.h # Include/W3DDevice/GameClient/W3DAssetManager.h # Include/W3DDevice/GameClient/W3DAssetManagerExposed.h # Include/W3DDevice/GameClient/W3DBibBuffer.h @@ -67,9 +67,9 @@ set(GAMEENGINEDEVICE_SRC Include/W3DDevice/GameClient/W3DSnow.h # Include/W3DDevice/GameClient/W3DStatusCircle.h Include/W3DDevice/GameClient/W3DTerrainBackground.h -# Include/W3DDevice/GameClient/W3DTerrainTracks.h -# Include/W3DDevice/GameClient/W3DTerrainVisual.h -# Include/W3DDevice/GameClient/W3DTreeBuffer.h + Include/W3DDevice/GameClient/W3DTerrainTracks.h + Include/W3DDevice/GameClient/W3DTerrainVisual.h + Include/W3DDevice/GameClient/W3DTreeBuffer.h Include/W3DDevice/GameClient/W3DVideoBuffer.h Include/W3DDevice/GameClient/W3DView.h # Include/W3DDevice/GameClient/W3DVolumetricShadow.h @@ -77,7 +77,7 @@ set(GAMEENGINEDEVICE_SRC Include/W3DDevice/GameClient/W3DWaterTracks.h # Include/W3DDevice/GameClient/W3DWaypointBuffer.h # Include/W3DDevice/GameClient/W3DWebBrowser.h -# Include/W3DDevice/GameClient/WorldHeightMap.h + Include/W3DDevice/GameClient/WorldHeightMap.h # Include/W3DDevice/GameLogic/W3DGameLogic.h # Include/W3DDevice/GameLogic/W3DGhostObject.h # Include/W3DDevice/GameLogic/W3DTerrainLogic.h @@ -136,13 +136,13 @@ set(GAMEENGINEDEVICE_SRC # Source/W3DDevice/GameClient/GUI/W3DGameFont.cpp # Source/W3DDevice/GameClient/GUI/W3DGameWindow.cpp # Source/W3DDevice/GameClient/GUI/W3DGameWindowManager.cpp -# Source/W3DDevice/GameClient/HeightMap.cpp + Source/W3DDevice/GameClient/HeightMap.cpp # Source/W3DDevice/GameClient/Shadow/W3DBufferManager.cpp # Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp # Source/W3DDevice/GameClient/Shadow/W3DShadow.cpp # Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp -# Source/W3DDevice/GameClient/TerrainTex.cpp -# Source/W3DDevice/GameClient/TileData.cpp + Source/W3DDevice/GameClient/TerrainTex.cpp + Source/W3DDevice/GameClient/TileData.cpp # Source/W3DDevice/GameClient/W3DAssetManager.cpp # Source/W3DDevice/GameClient/W3DAssetManagerExposed.cpp # Source/W3DDevice/GameClient/W3DBibBuffer.cpp @@ -169,16 +169,16 @@ set(GAMEENGINEDEVICE_SRC Source/W3DDevice/GameClient/W3DSnow.cpp # Source/W3DDevice/GameClient/W3DStatusCircle.cpp Source/W3DDevice/GameClient/W3DTerrainBackground.cpp -# Source/W3DDevice/GameClient/W3DTerrainTracks.cpp -# Source/W3DDevice/GameClient/W3DTerrainVisual.cpp -# Source/W3DDevice/GameClient/W3DTreeBuffer.cpp + Source/W3DDevice/GameClient/W3DTerrainTracks.cpp + Source/W3DDevice/GameClient/W3DTerrainVisual.cpp + Source/W3DDevice/GameClient/W3DTreeBuffer.cpp Source/W3DDevice/GameClient/W3DVideoBuffer.cpp Source/W3DDevice/GameClient/W3DView.cpp # Source/W3DDevice/GameClient/W3dWaypointBuffer.cpp # Source/W3DDevice/GameClient/W3DWebBrowser.cpp Source/W3DDevice/GameClient/Water/W3DWater.cpp Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp -# Source/W3DDevice/GameClient/WorldHeightMap.cpp + Source/W3DDevice/GameClient/WorldHeightMap.cpp # Source/W3DDevice/GameLogic/W3DGameLogic.cpp # Source/W3DDevice/GameLogic/W3DGhostObject.cpp # Source/W3DDevice/GameLogic/W3DTerrainLogic.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h b/Core/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h rename to Core/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/TerrainTex.h b/Core/GameEngineDevice/Include/W3DDevice/GameClient/TerrainTex.h similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/TerrainTex.h rename to Core/GameEngineDevice/Include/W3DDevice/GameClient/TerrainTex.h diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/TileData.h b/Core/GameEngineDevice/Include/W3DDevice/GameClient/TileData.h similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/TileData.h rename to Core/GameEngineDevice/Include/W3DDevice/GameClient/TileData.h diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainTracks.h b/Core/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainTracks.h similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainTracks.h rename to Core/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainTracks.h diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainVisual.h b/Core/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainVisual.h similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainVisual.h rename to Core/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainVisual.h diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTreeBuffer.h b/Core/GameEngineDevice/Include/W3DDevice/GameClient/W3DTreeBuffer.h similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTreeBuffer.h rename to Core/GameEngineDevice/Include/W3DDevice/GameClient/W3DTreeBuffer.h diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/WorldHeightMap.h b/Core/GameEngineDevice/Include/W3DDevice/GameClient/WorldHeightMap.h similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/WorldHeightMap.h rename to Core/GameEngineDevice/Include/W3DDevice/GameClient/WorldHeightMap.h diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp rename to Core/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp rename to Core/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/TileData.cpp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/TileData.cpp similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/TileData.cpp rename to Core/GameEngineDevice/Source/W3DDevice/GameClient/TileData.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainTracks.cpp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainTracks.cpp similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainTracks.cpp rename to Core/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainTracks.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp rename to Core/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp rename to Core/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp similarity index 100% rename from GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp rename to Core/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp diff --git a/Generals/Code/GameEngine/CMakeLists.txt b/Generals/Code/GameEngine/CMakeLists.txt index 357a3a48b6..9553884b67 100644 --- a/Generals/Code/GameEngine/CMakeLists.txt +++ b/Generals/Code/GameEngine/CMakeLists.txt @@ -62,7 +62,7 @@ set(GAMEENGINE_SRC Include/Common/List.h # Include/Common/LocalFile.h # Include/Common/LocalFileSystem.h - Include/Common/MapObject.h +# Include/Common/MapObject.h Include/Common/MapReaderWriterInfo.h Include/Common/MessageStream.h Include/Common/MiniLog.h @@ -192,7 +192,7 @@ set(GAMEENGINE_SRC Include/GameClient/Line2D.h Include/GameClient/LoadScreen.h Include/GameClient/LookAtXlat.h - Include/GameClient/MapUtil.h +# Include/GameClient/MapUtil.h Include/GameClient/MessageBox.h Include/GameClient/MetaEvent.h Include/GameClient/Module/AnimatedParticleSysBoneClientUpdate.h @@ -211,8 +211,8 @@ set(GAMEENGINE_SRC Include/GameClient/ShellHooks.h Include/GameClient/ShellMenuScheme.h Include/GameClient/Statistics.h - Include/GameClient/TerrainRoads.h - Include/GameClient/TerrainVisual.h +# Include/GameClient/TerrainRoads.h +# Include/GameClient/TerrainVisual.h # Include/GameClient/VideoPlayer.h # Include/GameClient/View.h # Include/GameClient/Water.h @@ -753,7 +753,7 @@ set(GAMEENGINE_SRC Source/GameClient/Input/Mouse.cpp Source/GameClient/LanguageFilter.cpp Source/GameClient/Line2D.cpp - Source/GameClient/MapUtil.cpp +# Source/GameClient/MapUtil.cpp Source/GameClient/MessageStream/CommandXlat.cpp Source/GameClient/MessageStream/GUICommandTranslator.cpp Source/GameClient/MessageStream/HintSpy.cpp @@ -773,8 +773,8 @@ set(GAMEENGINE_SRC Source/GameClient/System/Image.cpp Source/GameClient/System/ParticleSys.cpp Source/GameClient/System/RayEffect.cpp - Source/GameClient/Terrain/TerrainRoads.cpp - Source/GameClient/Terrain/TerrainVisual.cpp +# Source/GameClient/Terrain/TerrainRoads.cpp +# Source/GameClient/Terrain/TerrainVisual.cpp # Source/GameClient/VideoPlayer.cpp # Source/GameClient/View.cpp # Source/GameClient/Water.cpp diff --git a/Generals/Code/GameEngine/Include/Common/MapObject.h b/Generals/Code/GameEngine/Include/Common/MapObject.h deleted file mode 100644 index 91ed1c3005..0000000000 --- a/Generals/Code/GameEngine/Include/Common/MapObject.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) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - - -// MapObject.h -// Class to encapsulate height map. -// Author: John Ahlquist, April 2001 - -#pragma once - -#include "Common/Dict.h" -#include "Common/GameMemory.h" -#include "GameClient/TerrainRoads.h" - - - -class WorldHeightMapInterfaceClass -{ -public: - - virtual Int getBorderSize() = 0; - virtual Real getSeismicZVelocity(Int xIndex, Int yIndex) const = 0; - virtual void setSeismicZVelocity(Int xIndex, Int yIndex, Real value) = 0; - virtual Real getBilinearSampleSeismicZVelocity( Int x, Int y) = 0; - -}; - -/** MapObject class -Not ref counted. Do not store pointers to this class. */ -class WorldHeightMap; -class RenderObjClass; -class ThingTemplate; -class Shadow; -enum WaypointID CPP_11(: Int); - -#define MAP_XY_FACTOR (10.0f) //How wide and tall each height map square is in world space. -#define MAP_HEIGHT_SCALE (MAP_XY_FACTOR/16.0f) //divide all map heights by 8. - -// m_flags bit values. -enum { - FLAG_DRAWS_IN_MIRROR = 0x00000001, ///< If set, draws in water mirror. - FLAG_ROAD_POINT1 = 0x00000002, ///< If set, is the first point in a road segment. - FLAG_ROAD_POINT2 = 0x00000004, ///< If set, is the second point in a road segment. - FLAG_ROAD_FLAGS = (FLAG_ROAD_POINT1|FLAG_ROAD_POINT2), ///< If nonzero, object is a road piece. - FLAG_ROAD_CORNER_ANGLED = 0x00000008, ///< If set, the road corner is angled rather than curved. - FLAG_BRIDGE_POINT1 = 0x00000010, ///< If set, is the first point in a bridge. - FLAG_BRIDGE_POINT2 = 0x00000020, ///< If set, is the second point in a bridge. - FLAG_BRIDGE_FLAGS = (FLAG_BRIDGE_POINT1|FLAG_BRIDGE_POINT2), ///< If nonzero, object is a bridge piece. - FLAG_ROAD_CORNER_TIGHT = 0x00000040, - FLAG_ROAD_JOIN = 0x00000080, ///< If set, this road end does a generic alpha join. - FLAG_DONT_RENDER = 0x00000100 ///< If set, do not render this object. Only WB pays attention to this. (Right now, anyways) -}; - -class MapObject : public MemoryPoolObject -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(MapObject, "MapObject") - -// friend doesn't play well with MPO -- srj -// friend class WorldHeightMap; -// friend class WorldHeightMapEdit; -// friend class AddObjectUndoable; -// friend class DeleteInfo; - - enum - { - MO_SELECTED = 0x01, - MO_LIGHT = 0x02, - MO_WAYPOINT = 0x04, - MO_SCORCH = 0x08 - }; - - // This data is currently written out into the map data file. - Coord3D m_location; ///< Location of the center of the object. - AsciiString m_objectName; ///< The object name. - const ThingTemplate* m_thingTemplate; ///< thing template for map object - Real m_angle; ///< positive x is 0 degrees, angle is counterclockwise in degrees. - MapObject* m_nextMapObject; ///< linked list. - Int m_flags; ///< Bit flags. - Dict m_properties; ///< general property sheet. - // This data is runtime data that is used by the worldbuider editor, but - // not saved in the map file. - Int m_color; ///< Display color. - RenderObjClass* m_renderObj; ///< object that renders in the 3d scene. - Shadow* m_shadowObj; ///< object that renders shadow in the 3d scene. - RenderObjClass* m_bridgeTowers[ BRIDGE_MAX_TOWERS ]; ///< for bridge towers - Int m_runtimeFlags; - -public: - static MapObject *TheMapObjectListPtr; - static Dict TheWorldDict; - -public: - MapObject(Coord3D loc, AsciiString name, Real angle, Int flags, const Dict* props, - const ThingTemplate *thingTemplate ); - //~MapObject(void); ///< Note that deleting the head of a list deletes all linked objects in the list. - -public: - - Dict *getProperties() { return &m_properties; } ///< return the object's property sheet. - - void setNextMap(MapObject *nextMap) {m_nextMapObject = nextMap;} ///< Link the next map object. - const Coord3D *getLocation(void) const {return &m_location;} ///< Get the center point. - Real getAngle(void) const {return m_angle;} ///< Get the angle. - Int getColor(void) const {return m_color;} ///< Gets whatever ui color we set. - void setColor(Int color) {m_color=color;} ///< Sets the ui color. - AsciiString getName(void) const {return m_objectName;} ///< Gets the object name - void setName(AsciiString name); ///< Sets the object name - void setThingTemplate( const ThingTemplate* thing ); ///< set template - const ThingTemplate *getThingTemplate( void ) const; - MapObject *getNext(void) const {return m_nextMapObject;} ///< Next map object in the list. Not a copy, don't delete it. - MapObject *duplicate(void); ///< Allocates a copy. Caller is responsible for delete-ing this when done with it. - - void setAngle(Real angle) {m_angle = normalizeAngle(angle);} - void setLocation(Coord3D *pLoc) {m_location = *pLoc;} - void setFlag(Int flag) {m_flags |= flag;} - void clearFlag(Int flag) {m_flags &= (~flag);} - Bool getFlag(Int flag) const {return (m_flags&flag)?true:false;} - Int getFlags(void) const {return (m_flags);} - - Bool isSelected(void) const {return (m_runtimeFlags & MO_SELECTED) != 0;} - void setSelected(Bool sel) { if (sel) m_runtimeFlags |= MO_SELECTED; else m_runtimeFlags &= ~MO_SELECTED; } - - Bool isLight(void) const {return (m_runtimeFlags & MO_LIGHT) != 0;} - Bool isWaypoint(void) const {return (m_runtimeFlags & MO_WAYPOINT) != 0;} - Bool isScorch(void) const {return (m_runtimeFlags & MO_SCORCH) != 0;} - - void setIsLight() {m_runtimeFlags |= MO_LIGHT;} - void setIsWaypoint() { m_runtimeFlags |= MO_WAYPOINT; } - void setIsScorch() { m_runtimeFlags |= MO_SCORCH; } - - void setRenderObj(RenderObjClass *pObj); - RenderObjClass *getRenderObj(void) const {return m_renderObj;} - void setShadowObj(Shadow *pObj) {m_shadowObj=pObj;} - Shadow *getShadowObj(void) const {return m_shadowObj;} - - RenderObjClass* getBridgeRenderObject( BridgeTowerType type ); - void setBridgeRenderObject( BridgeTowerType type, RenderObjClass* renderObj ); - - WaypointID getWaypointID(); - AsciiString getWaypointName(); - void setWaypointID(Int i); - void setWaypointName(AsciiString n); - - // calling validate will call verifyValidTeam and verifyValidUniqueID. - void validate(void); - - // verifyValidTeam will either place the map object on an approrpriate team, or leave the - // current team (if it is valid) - void verifyValidTeam(void); - - // verifyValidUniqueID will ensure that this unit isn't sharing a number with another unit. - void verifyValidUniqueID(void); - - // The fast version doesn't attempt to verify uniqueness. It goes - static void fastAssignAllUniqueIDs(void); - - - static MapObject *getFirstMapObject(void) { return TheMapObjectListPtr; } - static Dict* getWorldDict() { return &TheWorldDict; } - static Int countMapObjectsWithOwner(const AsciiString& n); -}; diff --git a/Generals/Code/GameEngine/Include/GameClient/MapUtil.h b/Generals/Code/GameEngine/Include/GameClient/MapUtil.h deleted file mode 100644 index 5db7a1ede1..0000000000 --- a/Generals/Code/GameEngine/Include/GameClient/MapUtil.h +++ /dev/null @@ -1,150 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public 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: MapUtil.h ///////////////////////////////////////////////////////// -// Author: Matt Campbell, December 2001 -// Description: Map utility/convenience routines -//////////////////////////////////////////////////////////////////////////// - -#pragma once - -#include "Common/AsciiString.h" -#include "Common/UnicodeString.h" - -#include "Common/STLTypedefs.h" - -class GameWindow; -class AsciiString; -struct Coord3D; -struct FileInfo; -class Image; -class DataChunkInput; -struct DataChunkInfo; -// This matches the windows timestamp. -enum { SUPPLY_TECH_SIZE = 15}; -typedef std::list ICoord2DList; - -class TechAndSupplyImages -{ -public: - ICoord2DList m_techPosList; - ICoord2DList m_supplyPosList; -}; - -struct WinTimeStamp -{ - UnsignedInt m_lowTimeStamp; - UnsignedInt m_highTimeStamp; -}; - - -class WaypointMap : public std::map -{ -public: - void update( void ); ///< returns the number of multiplayer start spots found - Int m_numStartSpots; -}; - -typedef std::list Coord3DList; - -class MapMetaData -{ -public: - UnicodeString m_displayName; - AsciiString m_nameLookupTag; - Region3D m_extent; - Int m_numPlayers; - - Bool m_isMultiplayer; - Bool m_isOfficial; - Bool m_doesExist; ///< Flag to indicate whether the map physically exists. Should be true. - UnsignedInt m_filesize; - UnsignedInt m_CRC; - - WinTimeStamp m_timestamp; - - WaypointMap m_waypoints; - Coord3DList m_supplyPositions; - Coord3DList m_techPositions; - AsciiString m_fileName; -}; - -// TheSuperHackers @performance xezon 02/11/2025 Simplifies and improves the implementation of MapCache -// to prevent expensive reoccurring redundant map cache reads. - -class MapCache : public std::map -{ - typedef std::set MapNameSet; - -public: - MapCache() - : m_doCreateStandardMapCacheINI(TRUE) - , m_doLoadStandardMapCacheINI(TRUE) - , m_doLoadUserMapCacheINI(TRUE) - {} - - void updateCache( void ); - - AsciiString getMapDir() const; - AsciiString getUserMapDir() const; - AsciiString getMapExtension() const; - - const MapMetaData *findMap(AsciiString mapName); - - // allow us to create a set of shippable maps to be in mapcache.ini. For use with -buildMapCache. - void addShippingMap(AsciiString mapName) { mapName.toLower(); m_allowedMaps.insert(mapName); } - -private: - void prepareUnseenMaps(const AsciiString &mapDir); - Bool clearUnseenMaps(const AsciiString &mapDir); - void loadMapsFromMapCacheINI(const AsciiString &mapDir); - Bool loadMapsFromDisk(const AsciiString &mapDir, Bool isOfficial, Bool filterByAllowedMaps = FALSE); // returns true if we needed to (re)parse a map - Bool addMap(const AsciiString &mapDir, const AsciiString &fname, const AsciiString &lowerFname, FileInfo &fileInfo, Bool isOfficial); ///< returns true if it had to (re)parse the map - void writeCacheINI(const AsciiString &mapDir); - - static const char *const m_mapCacheName; - - MapNameSet m_allowedMaps; - Bool m_doCreateStandardMapCacheINI; - Bool m_doLoadStandardMapCacheINI; - Bool m_doLoadUserMapCacheINI; -}; - -extern MapCache *TheMapCache; -extern TechAndSupplyImages TheSupplyAndTechImageLocations; - -// TheSuperHackers @refactor xezon 28/11/2025 Refactors the map list population implementation -// by breaking it into smaller pieces to make it more maintainable. - -Int populateMapListbox( GameWindow *listbox, Bool useSystemMaps, Bool isMultiplayer, AsciiString mapToSelect = AsciiString::TheEmptyString ); /// Read a list of maps from the run directory and fill in the listbox. Return the selected index -Int populateMapListboxNoReset( GameWindow *listbox, Bool useSystemMaps, Bool isMultiplayer, AsciiString mapToSelect = AsciiString::TheEmptyString ); /// Read a list of maps from the run directory and fill in the listbox. Return the selected index -Bool isValidMap( AsciiString mapName, Bool isMultiplayer ); /// Validate a map -Image *getMapPreviewImage( AsciiString mapName ); -AsciiString getDefaultMap( Bool isMultiplayer ); /// Find a valid map -AsciiString getDefaultOfficialMap(); -Bool isOfficialMap( AsciiString mapName ); -Bool parseMapPreviewChunk(DataChunkInput &file, DataChunkInfo *info, void *userData); -void findDrawPositions( Int startX, Int startY, Int width, Int height, Region3D extent, - ICoord2D *ul, ICoord2D *lr ); -Bool WouldMapTransfer( const AsciiString& mapName ); diff --git a/Generals/Code/GameEngine/Include/GameClient/TerrainRoads.h b/Generals/Code/GameEngine/Include/GameClient/TerrainRoads.h deleted file mode 100644 index 72fa329122..0000000000 --- a/Generals/Code/GameEngine/Include/GameClient/TerrainRoads.h +++ /dev/null @@ -1,229 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public 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: TerrainRoads.h /////////////////////////////////////////////////////////////////////////// -// Author: Colin Day, December 2001 -// Desc: Terrain road descriptions -/////////////////////////////////////////////////////////////////////////////////////////////////// - -#pragma once - -// INCLUDES /////////////////////////////////////////////////////////////////////////////////////// -#include "Common/GameMemory.h" -#include "Common/SubsystemInterface.h" - -#include "GameLogic/Module/BodyModule.h" - - -// FORWARD DECLARATIONS /////////////////////////////////////////////////////////////////////////// -struct FieldParse; -class AsciiString; - -// ------------------------------------------------------------------------------------------------ -/** Bridges have 4 towers around it that the player can attack or use to repair the bridge */ -// ------------------------------------------------------------------------------------------------ -enum BridgeTowerType CPP_11(: Int) -{ - BRIDGE_TOWER_FROM_LEFT = 0, - BRIDGE_TOWER_FROM_RIGHT, - BRIDGE_TOWER_TO_LEFT, - BRIDGE_TOWER_TO_RIGHT, - - BRIDGE_MAX_TOWERS -}; - -// ------------------------------------------------------------------------------------------------ -enum { MAX_BRIDGE_BODY_FX = 3 }; - -//------------------------------------------------------------------------------------------------- -/** Terrain road description, good for roads and bridges */ -//------------------------------------------------------------------------------------------------- -class TerrainRoadType : public MemoryPoolObject -{ - - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( TerrainRoadType, "TerrainRoadType" ) - -public: - - TerrainRoadType( void ); - // destructor prototypes defined by memory pool object - - AsciiString getName( void ) { return m_name; } - AsciiString getTexture( void ) { return m_texture; } - Bool isBridge( void ) { return m_isBridge; } - UnsignedInt getID( void ) { return m_id; } - - Real getRoadWidth( void ) { return m_roadWidth; } - Real getRoadWidthInTexture( void ) { return m_roadWidthInTexture; } - - Real getBridgeScale( void ) { return m_bridgeScale; } - AsciiString getScaffoldObjectName( void ) { return m_scaffoldObjectName; } - AsciiString getScaffoldSupportObjectName( void ) { return m_scaffoldSupportObjectName; } - RGBColor getRadarColor( void ) { return m_radarColor; } - AsciiString getBridgeModel( void ) { return m_bridgeModelName; } - AsciiString getBridgeModelNameDamaged( void ) { return m_bridgeModelNameDamaged; } - AsciiString getBridgeModelNameReallyDamaged( void ) { return m_bridgeModelNameReallyDamaged; } - AsciiString getBridgeModelNameBroken( void ) { return m_bridgeModelNameBroken; } - AsciiString getTextureDamaged( void ) { return m_textureDamaged; } - AsciiString getTextureReallyDamaged( void ) { return m_textureReallyDamaged; } - AsciiString getTextureBroken( void ) { return m_textureBroken; } - AsciiString getTowerObjectName( BridgeTowerType tower ) { return m_towerObjectName[ tower ]; } - AsciiString getDamageToSoundString( BodyDamageType state ) { return m_damageToSoundString[ state ]; } - AsciiString getDamageToOCLString( BodyDamageType state, Int index ) { return m_damageToOCLString[ state ][ index ]; } - AsciiString getDamageToFXString( BodyDamageType state, Int index ) { return m_damageToFXString[ state ][ index ]; } - AsciiString getRepairedToSoundString( BodyDamageType state ) { return m_repairedToSoundString[ state ]; } - AsciiString getRepairedToOCLString( BodyDamageType state, Int index ) { return m_repairedToOCLString[ state ][ index ]; } - AsciiString getRepairedToFXString( BodyDamageType state, Int index ) { return m_repairedToFXString[ state ][ index ]; } - Real getTransitionEffectsHeight( void ) { return m_transitionEffectsHeight; } - Int getNumFXPerType( void ) { return m_numFXPerType; } - - // friend access methods to be used by the road collection only! - void friend_setName( AsciiString name ) { m_name = name; } - void friend_setTexture( AsciiString texture ) { m_texture = texture; } - void friend_setBridge( Bool isBridge ) { m_isBridge = isBridge; } - void friend_setID( UnsignedInt id ) { m_id = id; } - void friend_setNext( TerrainRoadType *next ) { m_next = next; } - TerrainRoadType *friend_getNext( void ) { return m_next; } - void friend_setRoadWidth( Real width ) { m_roadWidth = width; } - void friend_setRoadWidthInTexture( Real width ) { m_roadWidthInTexture = width; } - void friend_setBridgeScale( Real scale ) { m_bridgeScale = scale; } - void friend_setScaffoldObjectName( AsciiString name ) { m_scaffoldObjectName = name; } - void friend_setScaffoldSupportObjectName( AsciiString name ) { m_scaffoldSupportObjectName = name; } - void friend_setBridgeModelName( AsciiString name ) { m_bridgeModelName = name; } - void friend_setBridgeModelNameDamaged( AsciiString name ) { m_bridgeModelNameDamaged = name; } - void friend_setBridgeModelNameReallyDamaged( AsciiString name ) { m_bridgeModelNameReallyDamaged = name; } - void friend_setBridgeModelNameBroken( AsciiString name ) { m_bridgeModelNameBroken = name; } - void friend_setTextureDamaged( AsciiString texture ) { m_textureDamaged = texture; } - void friend_setTextureReallyDamaged( AsciiString texture ) { m_textureReallyDamaged = texture; } - void friend_setTextureBroken( AsciiString texture ) { m_textureBroken = texture; } - void friend_setTowerObjectName( BridgeTowerType tower, AsciiString name ) { m_towerObjectName[ tower ] = name; } - void friend_setDamageToSoundString( BodyDamageType state, AsciiString s ) { m_damageToSoundString[ state ] = s; } - void friend_setDamageToOCLString( BodyDamageType state, Int index, AsciiString s ) { m_damageToOCLString[ state ][ index ] = s; } - void friend_setDamageToFXString( BodyDamageType state, Int index, AsciiString s ) { m_damageToFXString[ state ][ index ] = s; } - void friend_setRepairedToSoundString( BodyDamageType state, AsciiString s ) { m_repairedToSoundString[ state ] = s; } - void friend_setRepairedToOCLString( BodyDamageType state, Int index, AsciiString s ) { m_repairedToOCLString[ state ][ index ] = s; } - void friend_setRepairedToFXString( BodyDamageType state, Int index, AsciiString s ) { m_repairedToFXString[ state ][ index ] = s; } - void friend_setTransitionEffectsHeight( Real height ) { m_transitionEffectsHeight = height; } - void friend_setNumFXPerType( Int num ) { m_numFXPerType = num; } - - /// get the parsing table for INI - const FieldParse *getRoadFieldParse( void ) { return m_terrainRoadFieldParseTable; } - const FieldParse *getBridgeFieldParse( void ) { return m_terrainBridgeFieldParseTable; } - -protected: - - AsciiString m_name; ///< entry name - Bool m_isBridge; ///< true if entry is for a bridge - UnsignedInt m_id; ///< unique id - TerrainRoadType *m_next; ///< next in road list - - // for parsing from INI - static const FieldParse m_terrainRoadFieldParseTable[]; ///< the parse table for INI definition - static const FieldParse m_terrainBridgeFieldParseTable[]; ///< the parse table for INI definition - static void parseTransitionToOCL( INI *ini, void *instance, void *store, const void *userData ); - static void parseTransitionToFX( INI *ini, void *instance, void *store, const void *userData ); - - // - // *note* I would union the road and bridge data, but unions can't have a copy - // constructor such as the AsciiString does - // - - // road data - Real m_roadWidth; ///< width of road - Real m_roadWidthInTexture; ///< width of road in the texture - - // bridge data - Real m_bridgeScale; ///< scale for bridge - - AsciiString m_scaffoldObjectName; ///< scaffold object name - AsciiString m_scaffoldSupportObjectName; ///< scaffold support object name - - RGBColor m_radarColor; ///< color for this bridge on the radar - - AsciiString m_bridgeModelName; ///< model name for bridge - AsciiString m_texture; ///< texture filename - - AsciiString m_bridgeModelNameDamaged; ///< model name for bridge - AsciiString m_textureDamaged; ///< model name for bridge - - AsciiString m_bridgeModelNameReallyDamaged; ///< model name for bridge - AsciiString m_textureReallyDamaged; ///< model name for bridge - - AsciiString m_bridgeModelNameBroken; ///< model name for bridge - AsciiString m_textureBroken; ///< model name for bridge - - AsciiString m_towerObjectName[ BRIDGE_MAX_TOWERS ]; ///< object names for the targetable towers on the bridge - - // - // the following strings are for repair/damage transition events, what sounds to - // play and a collection of OCL and FX lists to play over the bridge area - // - AsciiString m_damageToSoundString[ BODYDAMAGETYPE_COUNT ]; - AsciiString m_damageToOCLString[ BODYDAMAGETYPE_COUNT ][ MAX_BRIDGE_BODY_FX ]; - AsciiString m_damageToFXString[ BODYDAMAGETYPE_COUNT ][ MAX_BRIDGE_BODY_FX ]; - AsciiString m_repairedToSoundString[ BODYDAMAGETYPE_COUNT ]; - AsciiString m_repairedToOCLString[ BODYDAMAGETYPE_COUNT ][ MAX_BRIDGE_BODY_FX ]; - AsciiString m_repairedToFXString[ BODYDAMAGETYPE_COUNT ][ MAX_BRIDGE_BODY_FX ]; - Real m_transitionEffectsHeight; - Int m_numFXPerType; ///< for *each* fx/ocl we will make this many of them on the bridge area - -}; - -//------------------------------------------------------------------------------------------------- -/** Collection of all roads and bridges */ -//------------------------------------------------------------------------------------------------- -class TerrainRoadCollection : public SubsystemInterface -{ - -public: - - TerrainRoadCollection( void ); - ~TerrainRoadCollection( void ); - - void init() { } - void reset() { } - void update() { } - - TerrainRoadType *findRoad( AsciiString name ); ///< find road with matching name - TerrainRoadType *newRoad( AsciiString name ); ///< allocate new road, assing name, and link to list - TerrainRoadType *firstRoad( void ) { return m_roadList; } ///< return first road - TerrainRoadType *nextRoad( TerrainRoadType *road ); ///< get next road - - TerrainRoadType *findBridge( AsciiString name ); ///< find bridge with matching name - TerrainRoadType *newBridge( AsciiString name ); ///< allocate new bridge, assign name, and link - TerrainRoadType *firstBridge( void ) { return m_bridgeList; } ///< return first bridge - TerrainRoadType *nextBridge( TerrainRoadType *bridge ); ///< get next bridge - - TerrainRoadType *findRoadOrBridge( AsciiString name ); ///< search roads and bridges - -protected: - - TerrainRoadType *m_roadList; ///< list of available roads - TerrainRoadType *m_bridgeList; ///< list of available bridges - static UnsignedInt m_idCounter; ///< unique id counter when allocating roads/bridges - -}; - -// EXTERNAL //////////////////////////////////////////////////////////////////////////////////////// -extern TerrainRoadCollection *TheTerrainRoads; diff --git a/Generals/Code/GameEngine/Include/GameClient/TerrainVisual.h b/Generals/Code/GameEngine/Include/GameClient/TerrainVisual.h deleted file mode 100644 index b89d384f75..0000000000 --- a/Generals/Code/GameEngine/Include/GameClient/TerrainVisual.h +++ /dev/null @@ -1,310 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public 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: TerrainVisual.h ////////////////////////////////////////////////////////////////////////// -// Interface for visual representation of terrain on the client -// Author: Colin Day, April 2001 -/////////////////////////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#include "Common/Terrain.h" -#include "Common/Snapshot.h" -#include "Common/MapObject.h" - -// FORWARD REFERENCES ///////////////////////////////////////////////////////////////////////////// -class TerrainType; -class WaterHandle; -class Matrix3D; -class Object; -class Drawable; -class GeometryInfo; - - -class WorldHeightMap; -struct SeismicSimulationNode; -class SeismicSimulationFilterBase; - - -#define DEFAULT_SEISMIC_SIMULATION_MAGNITUDE (20.0f) -struct SeismicSimulationNode; // just a forward declaration folks, no cause for alarm -class SeismicSimulationFilterBase -{ -public: - enum SeismicSimStatusCode CPP_11(: Int) - { - SEISMIC_STATUS_INVALID, - SEISMIC_STATUS_ACTIVE, - SEISMIC_STATUS_ZERO_ENERGY, - }; - - virtual SeismicSimStatusCode filterCallback( WorldHeightMapInterfaceClass *heightMap, const SeismicSimulationNode *node ) = 0; - virtual Real applyGravityCallback( Real velocityIn ) = 0; -}; - -struct SeismicSimulationNode -{ - SeismicSimulationNode() - { - m_center.x = 0; - m_center.y = 0; - m_radius = 0; - m_region.lo.x = 0; - m_region.lo.y = 0; - m_region.hi.x = 0; - m_region.hi.y = 0; - m_clean = FALSE; - callbackFilter = NULL; - m_life = 0; - m_magnitude = DEFAULT_SEISMIC_SIMULATION_MAGNITUDE; - - } - SeismicSimulationNode( const SeismicSimulationNode &ssn ) - { - m_center.x = ssn.m_center.x; - m_center.y = ssn.m_center.y; - m_radius = ssn.m_radius; - m_region.lo.x = ssn.m_region.lo.x; - m_region.lo.y = ssn.m_region.lo.y; - m_region.hi.x = ssn.m_region.hi.x; - m_region.hi.y = ssn.m_region.hi.y; - m_clean = ssn.m_clean; - callbackFilter= ssn.callbackFilter; - m_life = ssn.m_life; - m_magnitude = ssn.m_magnitude; - - } - SeismicSimulationNode( const Coord3D* ctr, Real rad, Real mag, SeismicSimulationFilterBase *cbf = NULL ) - { - m_center.x = REAL_TO_INT_FLOOR(ctr->x/MAP_XY_FACTOR); - m_center.y = REAL_TO_INT_FLOOR(ctr->y/MAP_XY_FACTOR); - m_radius = (rad-1)/MAP_XY_FACTOR; - UnsignedInt regionSize = rad/MAP_XY_FACTOR; - m_region.lo.x = m_center.x - regionSize; - m_region.lo.y = m_center.y - regionSize; - m_region.hi.x = m_center.x + regionSize; - m_region.hi.y = m_center.y + regionSize; - m_clean = false; - callbackFilter= cbf; - m_life = 0; - m_magnitude = mag; - - } - - SeismicSimulationFilterBase::SeismicSimStatusCode handleFilterCallback( WorldHeightMapInterfaceClass *heightMap ) - { - if ( callbackFilter == NULL ) - return SeismicSimulationFilterBase::SEISMIC_STATUS_INVALID; - - ++m_life; - - return callbackFilter->filterCallback( heightMap, this ); - } - - Real applyGravity( Real velocityIn ) - { - DEBUG_ASSERTCRASH( callbackFilter, ("SeismicSimulationNode::applyGravity() has no callback filter!") ); - - if ( callbackFilter == NULL ) - return velocityIn;//oops, we have no callback! - - return callbackFilter->applyGravityCallback( velocityIn ); - - } - - IRegion2D m_region; - ICoord2D m_center; - Bool m_clean; - Real m_magnitude; - UnsignedInt m_radius; - UnsignedInt m_life; - - SeismicSimulationFilterBase *callbackFilter; - -}; -typedef std::list SeismicSimulationList; -typedef SeismicSimulationList::iterator SeismicSimulationListIt; - -class DomeStyleSeismicFilter : public SeismicSimulationFilterBase -{ - virtual SeismicSimStatusCode filterCallback( WorldHeightMapInterfaceClass *heightMap, const SeismicSimulationNode *node ); - virtual Real applyGravityCallback( Real velocityIn ); -}; - - -//------------------------------------------------------------------------------------------------- -/** LOD values for terrain, keep this in sync with TerrainLODNames[] */ -//------------------------------------------------------------------------------------------------- -typedef enum _TerrainLOD CPP_11(: Int) -{ - TERRAIN_LOD_INVALID, - TERRAIN_LOD_MIN, // note that this is less than max - TERRAIN_LOD_STRETCH_NO_CLOUDS, - TERRAIN_LOD_HALF_CLOUDS, - TERRAIN_LOD_NO_CLOUDS, - TERRAIN_LOD_STRETCH_CLOUDS, - TERRAIN_LOD_NO_WATER, - TERRAIN_LOD_MAX, // note that this is larger than min - TERRAIN_LOD_AUTOMATIC, - TERRAIN_LOD_DISABLE, - - TERRAIN_LOD_NUM_TYPES - -} TerrainLOD; -#ifdef DEFINE_TERRAIN_LOD_NAMES -static const char *const TerrainLODNames[] = -{ - "NONE", - "MIN", - "STRETCH_NO_CLOUDS", - "HALF_CLOUDS", - "NO_CLOUDS", - "STRETCH_CLOUDS", - "NO_WATER", - "MAX", - "AUTOMATIC", - "DISABLE", - - NULL -}; -static_assert(ARRAY_SIZE(TerrainLODNames) == TERRAIN_LOD_NUM_TYPES + 1, "Incorrect array size"); -#endif // end DEFINE_TERRAIN_LOD_NAMES - -//------------------------------------------------------------------------------------------------- -/** Device independent implementation for visual terrain */ -//------------------------------------------------------------------------------------------------- -class TerrainVisual : public Snapshot, - public SubsystemInterface -{ - -public: - - enum {NumSkyboxTextures = 5}; - - TerrainVisual(); - virtual ~TerrainVisual(); - - virtual void init( void ); - virtual void reset( void ); - virtual void update( void ); - - virtual Bool load( AsciiString filename ); - - /// get color of texture on the terrain at location specified - virtual void getTerrainColorAt( Real x, Real y, RGBColor *pColor ) = 0; - - /// get the terrain tile type at the world location in the (x,y) plane ignoring Z - virtual TerrainType *getTerrainTile( Real x, Real y ) = 0; - - /** intersect the ray with the terrain, if a hit occurs TRUE is returned - and the result point on the terrain is returned in "result" */ - virtual Bool intersectTerrain( Coord3D *rayStart, - Coord3D *rayEnd, - Coord3D *result ) { return FALSE; } - - // - // water methods - // - virtual void enableWaterGrid( Bool enable ) = 0; - /// set min/max height values allowed in water grid pointed to by waterTable - virtual void setWaterGridHeightClamps( const WaterHandle *waterTable, Real minZ, Real maxZ ) = 0; - /// adjust fallof parameters for grid change method - virtual void setWaterAttenuationFactors( const WaterHandle *waterTable, Real a, Real b, Real c, Real range ) = 0; - /// set the water table position and orientation in world space - virtual void setWaterTransform( const WaterHandle *waterTable, Real angle, Real x, Real y, Real z ) = 0; - virtual void setWaterTransform( const Matrix3D *transform ) = 0; - /// get water transform parameters - virtual void getWaterTransform( const WaterHandle *waterTable, Matrix3D *transform ) = 0; - /// water grid resolution spacing - virtual void setWaterGridResolution( const WaterHandle *waterTable, Real gridCellsX, Real gridCellsY, Real cellSize ) = 0; - virtual void getWaterGridResolution( const WaterHandle *waterTable, Real *gridCellsX, Real *gridCellsY, Real *cellSize ) = 0; - /// adjust the water grid in world coords by the delta - virtual void changeWaterHeight( Real x, Real y, Real delta ) = 0; - /// adjust the velocity at a water grid point corresponding to the world x,y - virtual void addWaterVelocity( Real worldX, Real worldY, Real velocity, Real preferredHeight ) = 0; - /// get height of water grid at specified position - virtual Bool getWaterGridHeight( Real worldX, Real worldY, Real *height) = 0; - - /// set detail of terrain tracks. - virtual void setTerrainTracksDetail(void)=0; - virtual void setShoreLineDetail(void)=0; - - /// Add a bib for an object at location. - virtual void addFactionBib(Object *factionBuilding, Bool highlight, Real extra = 0)=0; - /// Remove a bib. - virtual void removeFactionBib(Object *factionBuilding)=0; - - /// Add a bib for a drawable at location. - virtual void addFactionBibDrawable(Drawable *factionBuilding, Bool highlight, Real extra = 0)=0; - /// Remove a bib. - virtual void removeFactionBibDrawable(Drawable *factionBuilding)=0; - - virtual void removeAllBibs(void)=0; - virtual void removeBibHighlighting(void)=0; - - virtual void removeTreesAndPropsForConstruction( - const Coord3D* pos, - const GeometryInfo& geom, - Real angle - ) = 0; - - virtual void addProp(const ThingTemplate *tt, const Coord3D *pos, Real angle) = 0; - - // - // Modify height. - // - virtual void setRawMapHeight(const ICoord2D *gridPos, Int height)=0; - virtual Int getRawMapHeight(const ICoord2D *gridPos)=0; - - - //////////////////////////////////////////////////// - //////////////////////////////////////////////////// - //////////////////////////////////////////////////// -#ifdef DO_SEISMIC_SIMULATIONS - virtual void updateSeismicSimulations( void ) = 0; /// walk the SeismicSimulationList and, well, do it. - virtual void addSeismicSimulation( const SeismicSimulationNode& sim ) = 0; -#endif - virtual WorldHeightMap* getLogicHeightMap( void ) {return NULL;}; - virtual WorldHeightMap* getClientHeightMap( void ) {return NULL;}; - //////////////////////////////////////////////////// - //////////////////////////////////////////////////// - //////////////////////////////////////////////////// - - - /// Replace the skybox texture - virtual void replaceSkyboxTextures(const AsciiString *oldTexName[NumSkyboxTextures], const AsciiString *newTexName[NumSkyboxTextures])=0; - -protected: - - // snapshot methods - virtual void crc( Xfer *xfer ); - virtual void xfer( Xfer *xfer ); - virtual void loadPostProcess( void ); - - AsciiString m_filenameString; ///< file with terrain data - -}; - -// EXTERNALS ////////////////////////////////////////////////////////////////////////////////////// -extern TerrainVisual *TheTerrainVisual; ///< singleton extern diff --git a/Generals/Code/GameEngine/Source/GameClient/MapUtil.cpp b/Generals/Code/GameEngine/Source/GameClient/MapUtil.cpp deleted file mode 100644 index 6f4e8abfed..0000000000 --- a/Generals/Code/GameEngine/Source/GameClient/MapUtil.cpp +++ /dev/null @@ -1,1348 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public 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: MapUtil.cpp ////////////////////////////////////////////////////////////////////////////// -// Author: Matt Campbell, December 2001 -// Description: Map utility/convenience routines -/////////////////////////////////////////////////////////////////////////////////////////////////// - -// INCLUDES /////////////////////////////////////////////////////////////////////////////////////// -#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine - -#include "Common/crc.h" -#include "Common/FileSystem.h" -#include "Common/LocalFileSystem.h" -#include "Common/file.h" -#include "Common/GlobalData.h" -#include "Common/GameState.h" -#include "Common/GameEngine.h" -#include "Common/NameKeyGenerator.h" -#include "Common/DataChunk.h" -#include "Common/MapReaderWriterInfo.h" -#include "Common/MessageStream.h" -#include "Common/WellKnownKeys.h" -#include "Common/INI.h" -#include "Common/QuotedPrintable.h" -#include "Common/SkirmishBattleHonors.h" -#include "Common/ThingFactory.h" -#include "Common/ThingTemplate.h" -#include "Common/MapObject.h" -#include "GameClient/GameText.h" -#include "GameClient/WindowLayout.h" -#include "GameClient/Gadget.h" -#include "GameClient/Image.h" -#include "GameClient/Shell.h" -#include "GameClient/GameWindowManager.h" -#include "GameClient/GadgetListBox.h" -#include "GameClient/MapUtil.h" -#include "GameLogic/GameLogic.h" -#include "GameLogic/FPUControl.h" -#include "GameNetwork/GameInfo.h" -#include "GameNetwork/NetworkDefs.h" - - -//------------------------------------------------------------------------------- -// PRIVATE DATA /////////////////////////////////////////////////////////////////////////////////// -static const char *mapExtension = ".map"; - -static Int m_width = 0; ///< Height map width. -static Int m_height = 0; ///< Height map height (y size of array). -static Int m_borderSize = 0; ///< Non-playable border area. -static std::vector m_boundaries; ///< All the boundaries we use for the map -static Int m_dataSize = 0; ///< size of m_data. -static UnsignedByte *m_data = 0; ///< array of z(height) values in the height map. -static Dict worldDict = 0; - -static WaypointMap *m_waypoints = 0; -static Coord3DList m_supplyPositions; -static Coord3DList m_techPositions; - -static Int m_mapDX = 0; -static Int m_mapDY = 0; - -static UnsignedInt calcCRC( AsciiString fname ) -{ - CRC theCRC; - theCRC.clear(); - - File *fp = TheFileSystem->openFile(fname.str(), File::READ); - if( !fp ) - { - DEBUG_CRASH(("Couldn't open '%s'", fname.str())); - return 0; - } - - UnsignedByte buf[4096]; - Int num; - while ( (num=fp->read(buf, 4096)) > 0 ) - { - theCRC.computeCRC(buf, num); - } - - fp->close(); - fp = NULL; - - return theCRC.get(); -} - -static Bool ParseObjectDataChunk(DataChunkInput &file, DataChunkInfo *info, void *userData) -{ - Bool readDict = info->version >= K_OBJECTS_VERSION_2; - - Coord3D loc; - loc.x = file.readReal(); - loc.y = file.readReal(); - loc.z = file.readReal(); - if (info->version <= K_OBJECTS_VERSION_2) - { - loc.z = 0; - } - - Real angle = file.readReal(); - Int flags = file.readInt(); - AsciiString name = file.readAsciiString(); - Dict d; - if (readDict) - { - d = file.readDict(); - } - MapObject *pThisOne; - - // create the map object - pThisOne = newInstance( MapObject )( loc, name, angle, flags, &d, - TheThingFactory->findTemplate( name, FALSE ) ); - -//DEBUG_LOG(("obj %s owner %s",name.str(),d.getAsciiString(TheKey_originalOwner).str())); - - if (pThisOne->getProperties()->getType(TheKey_waypointID) == Dict::DICT_INT) - { - pThisOne->setIsWaypoint(); - - // grab useful info - (*m_waypoints)[pThisOne->getWaypointName()] = loc; - } - else if (pThisOne->getThingTemplate() && pThisOne->getThingTemplate()->isKindOf(KINDOF_TECH_BUILDING)) - { - m_techPositions.push_back(loc); - } - else if (pThisOne->getThingTemplate() && pThisOne->getThingTemplate()->isKindOf(KINDOF_SUPPLY_SOURCE_ON_PREVIEW)) - { - m_supplyPositions.push_back(loc); - } - - deleteInstance(pThisOne); - return TRUE; -} - -static Bool ParseObjectsDataChunk(DataChunkInput &file, DataChunkInfo *info, void *userData) -{ - file.m_currentObject = NULL; - file.registerParser( "Object", info->label, ParseObjectDataChunk ); - return (file.parse(userData)); -} - -static Bool ParseWorldDictDataChunk(DataChunkInput &file, DataChunkInfo *info, void *userData) -{ - worldDict = file.readDict(); - return true; -} - -static Bool ParseSizeOnly(DataChunkInput &file, DataChunkInfo *info, void *userData) -{ - m_width = file.readInt(); - m_height = file.readInt(); - if (info->version >= K_HEIGHT_MAP_VERSION_3) { - m_borderSize = file.readInt(); - } else { - m_borderSize = 0; - } - - if (info->version >= K_HEIGHT_MAP_VERSION_4) { - Int numBorders = file.readInt(); - m_boundaries.resize(numBorders); - for (int i = 0; i < numBorders; ++i) { - m_boundaries[i].x = file.readInt(); - m_boundaries[i].y = file.readInt(); - } - } - return true; - - m_dataSize = file.readInt(); - m_data = NEW UnsignedByte[m_dataSize]; // pool[]ify - if (m_dataSize <= 0 || (m_dataSize != (m_width*m_height))) { - throw ERROR_CORRUPT_FILE_FORMAT ; - } - file.readArrayOfBytes((char *)m_data, m_dataSize); - // Resize me. - if (info->version == K_HEIGHT_MAP_VERSION_1) { - Int newWidth = (m_width+1)/2; - Int newHeight = (m_height+1)/2; - Int i, j; - for (i=0; ilo.x = 0.0f; - - extent->lo.y = 0.0f; - - // Note - m_mapDX & Y are the number of height map grids wide, so we have to - // multiply by the grid width. - extent->hi.x = m_mapDX*MAP_XY_FACTOR; - extent->hi.y = m_mapDY*MAP_XY_FACTOR; - - extent->lo.z = 0; - extent->hi.z = 0; -} - -//------------------------------------------------------------------------------- - -void WaypointMap::update( void ) -{ - if (!m_waypoints) - { - m_numStartSpots = 1; - return; - } - - this->clear(); - - AsciiString startingCamName = TheNameKeyGenerator->keyToName(TheKey_InitialCameraPosition); - WaypointMap::const_iterator it; - - it = m_waypoints->find(startingCamName); - if (it != m_waypoints->end()) - { - (*this)[startingCamName] = it->second; - } - - m_numStartSpots = 0; - for (Int i=0; ifind(startingCamName); - if (it != m_waypoints->end()) - { - (*this)[startingCamName] = it->second; - ++m_numStartSpots; - } - else - { - break; - } - } - - m_numStartSpots = max(1, m_numStartSpots); -} - -const char *const MapCache::m_mapCacheName = "MapCache.ini"; - -AsciiString MapCache::getMapDir() const -{ - return "Maps"; -} - -AsciiString MapCache::getUserMapDir() const -{ - AsciiString tmp = TheGlobalData->getPath_UserData(); - tmp.concat(getMapDir()); - return tmp; -} - -AsciiString MapCache::getMapExtension() const -{ - return "map"; -} - -void MapCache::writeCacheINI( const AsciiString &mapDir ) -{ - AsciiString filepath = mapDir; - filepath.concat('\\'); - - TheFileSystem->createDirectory(mapDir); - - filepath.concat(m_mapCacheName); - FILE *fp = fopen(filepath.str(), "w"); - DEBUG_ASSERTCRASH(fp != NULL, ("Failed to create %s", filepath.str())); - if (fp == NULL) { - return; - } - - fprintf(fp, "; FILE: %s /////////////////////////////////////////////////////////////\n", filepath.str()); - fprintf(fp, "; This INI file is auto-generated - do not modify\n"); - fprintf(fp, "; /////////////////////////////////////////////////////////////////////////////\n"); - - MapCache::iterator it = begin(); - for (; it != end(); ++it) - { - if (it->first.startsWithNoCase(mapDir.str())) - { - const MapMetaData &md = it->second; - fprintf(fp, "\nMapCache %s\n", AsciiStringToQuotedPrintable(it->first.str()).str()); - fprintf(fp, " fileSize = %u\n", md.m_filesize); - fprintf(fp, " fileCRC = %u\n", md.m_CRC); - fprintf(fp, " timestampLo = %d\n", md.m_timestamp.m_lowTimeStamp); - fprintf(fp, " timestampHi = %d\n", md.m_timestamp.m_highTimeStamp); - fprintf(fp, " isOfficial = %s\n", (md.m_isOfficial)?"yes":"no"); - - fprintf(fp, " isMultiplayer = %s\n", (md.m_isMultiplayer)?"yes":"no"); - fprintf(fp, " numPlayers = %d\n", md.m_numPlayers); - - fprintf(fp, " extentMin = X:%2.2f Y:%2.2f Z:%2.2f\n", md.m_extent.lo.x, md.m_extent.lo.y, md.m_extent.lo.z); - fprintf(fp, " extentMax = X:%2.2f Y:%2.2f Z:%2.2f\n", md.m_extent.hi.x, md.m_extent.hi.y, md.m_extent.hi.z); - -// BAD AND NOW UNUSED: the mapcache.ini should not contain localized data... using the lookup tag instead -#if RTS_GENERALS - fprintf(fp, " displayName = %s\n", UnicodeStringToQuotedPrintable(md.m_displayName).str()); -#else - fprintf(fp, " nameLookupTag = %s\n", md.m_nameLookupTag.str()); -#endif - - Coord3D pos; - WaypointMap::const_iterator itw = md.m_waypoints.begin(); - for (; itw != md.m_waypoints.end(); ++itw) - { - pos = itw->second; - fprintf(fp, " %s = X:%2.2f Y:%2.2f Z:%2.2f\n", itw->first.str(), pos.x, pos.y, pos.z); - } - Coord3DList::const_iterator itc3d = md.m_techPositions.begin(); - for (; itc3d != md.m_techPositions.end(); ++itc3d) - { - pos = *itc3d; - fprintf(fp, " techPosition = X:%2.2f Y:%2.2f Z:%2.2f\n", pos.x, pos.y, pos.z); - } - - itc3d = md.m_supplyPositions.begin(); - for (; itc3d != md.m_supplyPositions.end(); ++itc3d) - { - pos = *itc3d; - fprintf(fp, " supplyPosition = X:%2.2f Y:%2.2f Z:%2.2f\n", pos.x, pos.y, pos.z); - } - fprintf(fp, "END\n\n"); - } - else - { - //DEBUG_LOG(("%s does not start %s", mapDir.str(), it->first.str())); - } - } - - fclose(fp); -} - -void MapCache::updateCache( void ) -{ - setFPMode(); - - const AsciiString mapDir = getMapDir(); - const AsciiString userMapDir = getUserMapDir(); - - // Create the standard map cache if required. Is only relevant for Mod developers. - // TheSuperHackers @tweak This step is done before loading any other map caches to not poison the cached state. - if (m_doCreateStandardMapCacheINI) - { -#if defined(RTS_DEBUG) - // only create the map cache file if "Maps" folder exists - const Bool buildMapCache = TheLocalFileSystem->doesFileExist(mapDir.str()); -#else - const Bool buildMapCache = TheGlobalData->m_buildMapCache; -#endif - if (buildMapCache) - { - const Bool isOfficial = TRUE; - const Bool filterByAllowedMaps = !m_allowedMaps.empty(); - - if (loadMapsFromDisk(mapDir, isOfficial, filterByAllowedMaps)) - { - writeCacheINI(mapDir); - } - } - m_doCreateStandardMapCacheINI = FALSE; - } - - // Load user map cache first. - if (m_doLoadUserMapCacheINI) - { - loadMapsFromMapCacheINI(userMapDir); - m_doLoadUserMapCacheINI = FALSE; - } - - // Load user maps from disk and update any discrepancies from the map cache. - if (loadMapsFromDisk(userMapDir, FALSE)) - { - writeCacheINI(userMapDir); - m_doLoadStandardMapCacheINI = TRUE; - } - - // Load standard maps from map cache last. - // This overwrites matching user maps to prevent munkees getting rowdy :) - if (m_doLoadStandardMapCacheINI) - { - loadMapsFromMapCacheINI(mapDir); - m_doLoadStandardMapCacheINI = FALSE; - } -} - -void MapCache::prepareUnseenMaps( const AsciiString &mapDir ) -{ - MapCache::iterator it = begin(); - for (; it != end(); ++it) - { - const AsciiString &mapName = it->first; - - if (mapName.startsWithNoCase(mapDir.str())) - { - it->second.m_doesExist = FALSE; - } - } -} - -Bool MapCache::clearUnseenMaps( const AsciiString &mapDir ) -{ - Bool erasedSomething = FALSE; - - MapCache::iterator it = begin(); - while (it != end()) - { - MapCache::iterator next = it; - ++next; - - const AsciiString &mapName = it->first; - const MapMetaData &mapData = it->second; - - if (mapName.startsWithNoCase(mapDir.str()) && !mapData.m_doesExist) - { - erase(it); - erasedSomething = TRUE; - } - - it = next; - } - - return erasedSomething; -} - -void MapCache::loadMapsFromMapCacheINI( const AsciiString &mapDir ) -{ - INI ini; - AsciiString fname; - fname.format("%s\\%s", mapDir.str(), m_mapCacheName); - - if (TheFileSystem->doesFileExist(fname.str())) - { - ini.load( fname, INI_LOAD_OVERWRITE, NULL ); - } -} - -Bool MapCache::loadMapsFromDisk( const AsciiString &mapDir, Bool isOfficial, Bool filterByAllowedMaps ) -{ - prepareUnseenMaps(mapDir); - - FilenameList filepathList; - FilenameListIter filepathIt; - AsciiString toplevelPattern; - toplevelPattern.format("%s\\", mapDir.str()); - Bool mapListChanged = FALSE; - AsciiString filenamepattern; - filenamepattern.format("*.%s", getMapExtension().str()); - - TheFileSystem->getFileListInDirectory(toplevelPattern, filenamepattern, filepathList, TRUE); - - filepathIt = filepathList.begin(); - - for (; filepathIt != filepathList.end(); ++filepathIt) - { - FileInfo fileInfo; - AsciiString filepathLower = *filepathIt; - filepathLower.toLower(); - - const char *szFilenameLower = filepathLower.reverseFind('\\'); - if (!szFilenameLower) - { - DEBUG_CRASH(("Couldn't find \\ in map name!")); - continue; - } - - AsciiString endingStr; - AsciiString filenameLower = szFilenameLower+1; - filenameLower.truncateBy(strlen(mapExtension)); - - if (filterByAllowedMaps && m_allowedMaps.find(filenameLower) == m_allowedMaps.end()) - { - DEBUG_CRASH(("Map '%s' has been filtered out", filenameLower.str())); - continue; - } - - endingStr.format("%s\\%s%s", filenameLower.str(), filenameLower.str(), mapExtension); - - if (!filepathLower.endsWithNoCase(endingStr.str())) - { - DEBUG_CRASH(("Found map '%s' in wrong spot (%s)", filenameLower.str(), filepathLower.str())); - continue; - } - - if (!TheFileSystem->getFileInfo(*filepathIt, &fileInfo)) - { - DEBUG_CRASH(("Could not get file info for map %s", filepathIt->str())); - continue; - } - - mapListChanged |= addMap(mapDir, *filepathIt, filepathLower, fileInfo, isOfficial); - } - - if (clearUnseenMaps(mapDir)) - { - mapListChanged = TRUE; - } - - return mapListChanged; -} - -Bool MapCache::addMap( - const AsciiString &mapDir, - const AsciiString &fname, - const AsciiString &lowerFname, - FileInfo &fileInfo, - Bool isOfficial) -{ - MapCache::iterator it = find(lowerFname); - if (it != end()) - { - // Found the map in our cache. Check to see if it has changed. - const MapMetaData& md = it->second; - - if (md.m_filesize == fileInfo.sizeLow && md.m_CRC != 0) - { - // Force a lookup so that we don't display the English localization in all builds. - if (md.m_nameLookupTag.isEmpty()) - { - // unofficial maps or maps without names - AsciiString tempdisplayname; - tempdisplayname = fname.reverseFind('\\') + 1; - (*this)[lowerFname].m_displayName.translate(tempdisplayname); - if (md.m_numPlayers >= 2) - { - UnicodeString extension; - extension.format(L" (%d)", md.m_numPlayers); - (*this)[lowerFname].m_displayName.concat(extension); - } - } - else - { - // official maps with name tags - (*this)[lowerFname].m_displayName = TheGameText->fetch(md.m_nameLookupTag); - if (md.m_numPlayers >= 2) - { - UnicodeString extension; - extension.format(L" (%d)", md.m_numPlayers); - (*this)[lowerFname].m_displayName.concat(extension); - } - } - - it->second.m_doesExist = TRUE; - -// DEBUG_LOG(("MapCache::addMap - found match for map %s", lowerFname.str())); - return FALSE; // OK, it checks out. - } - DEBUG_LOG(("%s didn't match file in MapCache", fname.str())); - DEBUG_LOG(("size: %d / %d", fileInfo.sizeLow, md.m_filesize)); - DEBUG_LOG(("time1: %d / %d", fileInfo.timestampHigh, md.m_timestamp.m_highTimeStamp)); - DEBUG_LOG(("time2: %d / %d", fileInfo.timestampLow, md.m_timestamp.m_lowTimeStamp)); -// DEBUG_LOG(("size: %d / %d", filesize, md.m_filesize)); -// DEBUG_LOG(("time1: %d / %d", timestamp.m_highTimeStamp, md.m_timestamp.m_highTimeStamp)); -// DEBUG_LOG(("time2: %d / %d", timestamp.m_lowTimeStamp, md.m_timestamp.m_lowTimeStamp)); - } - - DEBUG_LOG(("MapCache::addMap(): caching '%s' because '%s' was not found", fname.str(), lowerFname.str())); - - loadMap(fname); // Just load for querying the data, since we aren't playing this map. - - // The map is now loaded. Pick out what we need. - MapMetaData md; - md.m_fileName = lowerFname; - md.m_filesize = fileInfo.sizeLow; - md.m_isOfficial = isOfficial; - md.m_doesExist = TRUE; - md.m_waypoints.update(); - md.m_numPlayers = md.m_waypoints.m_numStartSpots; - md.m_isMultiplayer = (md.m_numPlayers >= 2); - md.m_timestamp.m_highTimeStamp = fileInfo.timestampHigh; - md.m_timestamp.m_lowTimeStamp = fileInfo.timestampLow; - md.m_supplyPositions = m_supplyPositions; - md.m_techPositions = m_techPositions; - md.m_CRC = calcCRC(fname); - - Bool exists = false; - AsciiString nameLookupTag = worldDict.getAsciiString(TheKey_mapName, &exists); - md.m_nameLookupTag = nameLookupTag; - - if (!exists || nameLookupTag.isEmpty()) - { - DEBUG_LOG(("Missing TheKey_mapName!")); - AsciiString tempdisplayname; - tempdisplayname = fname.reverseFind('\\') + 1; - md.m_displayName.translate(tempdisplayname); - if (md.m_numPlayers >= 2) - { - UnicodeString extension; - extension.format(L" (%d)", md.m_numPlayers); - md.m_displayName.concat(extension); - } - TheGameText->reset(); - } - else - { - AsciiString stringFileName; - stringFileName.format("%s\\%s", mapDir.str(), fname.str()); - stringFileName.truncateBy(4); - stringFileName.concat("\\map.str"); - TheGameText->initMapStringFile(stringFileName); - md.m_displayName = TheGameText->fetch(nameLookupTag); - if (md.m_numPlayers >= 2) - { - UnicodeString extension; - extension.format(L" (%d)", md.m_numPlayers); - md.m_displayName.concat(extension); - } - DEBUG_LOG(("Map name is now '%ls'", md.m_displayName.str())); - TheGameText->reset(); - } - - getExtent(&(md.m_extent)); - - (*this)[lowerFname] = md; - - DEBUG_LOG((" filesize = %d bytes", md.m_filesize)); - DEBUG_LOG((" displayName = %ls", md.m_displayName.str())); - DEBUG_LOG((" CRC = %X", md.m_CRC)); - DEBUG_LOG((" timestamp = %d", md.m_timestamp)); - DEBUG_LOG((" isOfficial = %s", (md.m_isOfficial)?"yes":"no")); - - DEBUG_LOG((" isMultiplayer = %s", (md.m_isMultiplayer)?"yes":"no")); - DEBUG_LOG((" numPlayers = %d", md.m_numPlayers)); - - DEBUG_LOG((" extent = (%2.2f,%2.2f) -> (%2.2f,%2.2f)", - md.m_extent.lo.x, md.m_extent.lo.y, - md.m_extent.hi.x, md.m_extent.hi.y)); - - Coord3D pos; - WaypointMap::iterator itw = md.m_waypoints.begin(); - for (; itw != md.m_waypoints.end(); ++itw) - { - pos = itw->second; - DEBUG_LOG((" waypoint %s: (%2.2f,%2.2f)", itw->first.str(), pos.x, pos.y)); - } - - resetMap(); - - return TRUE; -} - -MapCache *TheMapCache = NULL; - -// PUBLIC FUNCTIONS ////////////////////////////////////////////////////////////////////////////// - -Bool WouldMapTransfer( const AsciiString& mapName ) -{ - return mapName.startsWithNoCase(TheMapCache->getUserMapDir()); -} - -//------------------------------------------------------------------------------------------------- -typedef std::set > MapNameList; -typedef std::map MapDisplayToFileNameList; - -static void buildMapListForNumPlayers(MapNameList &outMapNames, MapDisplayToFileNameList &outFileNames, Int numPlayers) -{ - MapCache::iterator it = TheMapCache->begin(); - - for (; it != TheMapCache->end(); ++it) - { - const MapMetaData &mapData = it->second; - if (mapData.m_numPlayers == numPlayers) - { - outMapNames.insert(it->second.m_displayName); - outFileNames[it->second.m_displayName] = it->first; - } - } -} - -//------------------------------------------------------------------------------------------------- -struct MapListBoxData -{ - MapListBoxData() - : listbox(NULL) - , numLength(0) - , numColumns(0) - , w(10) - , h(10) - , color(GameMakeColor(255, 255, 255, 255)) - , battleHonors(NULL) - , easyImage(NULL) - , mediumImage(NULL) - , brutalImage(NULL) - , maxBrutalImage(NULL) - , mapToSelect() - , selectionIndex(0) // always select *something* - , isMultiplayer(false) - { - } - - GameWindow *listbox; - Int numLength; - Int numColumns; - Int w; - Int h; - Color color; - const SkirmishBattleHonors *battleHonors; - const Image *easyImage; - const Image *mediumImage; - const Image *brutalImage; - const Image *maxBrutalImage; - AsciiString mapToSelect; - Int selectionIndex; - Bool isMultiplayer; -}; - -//------------------------------------------------------------------------------------------------- -static Bool addMapToMapListbox( - MapListBoxData& lbData, - const AsciiString& mapDir, - const AsciiString& mapName, - const MapMetaData& mapMetaData) -{ - const Bool mapOk = mapName.startsWithNoCase(mapDir.str()) && lbData.isMultiplayer == mapMetaData.m_isMultiplayer && !mapMetaData.m_displayName.isEmpty(); - - if (mapOk) - { - UnicodeString mapDisplayName; - /// @todo: mapDisplayName = TheGameText->fetch(mapMetaData.m_displayName.str()); - mapDisplayName = mapMetaData.m_displayName; - - Int index = -1; - Int imageItemData = -1; - if (lbData.numColumns > 1 && mapMetaData.m_isMultiplayer) - { - const Int numEasy = lbData.battleHonors->getEnduranceMedal(mapName.str(), SLOT_EASY_AI); - const Int numMedium = lbData.battleHonors->getEnduranceMedal(mapName.str(), SLOT_MED_AI); - const Int numBrutal = lbData.battleHonors->getEnduranceMedal(mapName.str(), SLOT_BRUTAL_AI); - if (numBrutal) - { - const Int maxBrutalSlots = mapMetaData.m_numPlayers - 1; - if (lbData.maxBrutalImage != NULL && numBrutal == maxBrutalSlots) - { - index = GadgetListBoxAddEntryImage( lbData.listbox, lbData.maxBrutalImage, index, 0, lbData.w, lbData.h, TRUE); - imageItemData = 4; - } - else - { - index = GadgetListBoxAddEntryImage( lbData.listbox, lbData.brutalImage, index, 0, lbData.w, lbData.h, TRUE); - imageItemData = 3; - } - } - else if (numMedium) - { - imageItemData = 2; - index = GadgetListBoxAddEntryImage( lbData.listbox, lbData.mediumImage, index, 0, lbData.w, lbData.h, TRUE); - } - else if (numEasy) - { - imageItemData = 1; - index = GadgetListBoxAddEntryImage( lbData.listbox, lbData.easyImage, index, 0, lbData.w, lbData.h, TRUE); - } - else - { - imageItemData = 0; - index = GadgetListBoxAddEntryImage( lbData.listbox, NULL, index, 0, lbData.w, lbData.h, TRUE); - } - } - - index = GadgetListBoxAddEntryText( lbData.listbox, mapDisplayName, lbData.color, index, lbData.numColumns-1 ); - DEBUG_ASSERTCRASH(index >= 0, ("Expects valid index")); - - if (mapName == lbData.mapToSelect) - { - lbData.selectionIndex = index; - } - - // now set the char* as the item data. this works because the map cache isn't being - // modified while a map listbox is up. - GadgetListBoxSetItemData( lbData.listbox, (void *)(mapName.str()), index ); - - if (lbData.numColumns > 1) - { - GadgetListBoxSetItemData( lbData.listbox, (void *)imageItemData, index, 1 ); - } - - // TheSuperHackers @performance Now stops processing when the list is full. - if (index == lbData.numLength - 1) - { - return false; - } - } - - return true; -} - -//------------------------------------------------------------------------------------------------- -static Bool addMapCollectionToMapListbox( - MapListBoxData& lbData, - const AsciiString& mapDir, - const MapNameList& mapNames, - const MapDisplayToFileNameList& fileNames) -{ - MapNameList::const_iterator mapNameIt = mapNames.begin(); - - for (; mapNameIt != mapNames.end(); ++mapNameIt) - { - MapDisplayToFileNameList::const_iterator fileNameIt = fileNames.find(*mapNameIt); - DEBUG_ASSERTCRASH(fileNameIt != fileNames.end(), ("Map '%s' not found in file names map", mapNameIt->str())); - - const AsciiString& asciiMapName = fileNameIt->second; - -#if RTS_ZEROHOUR - //Patch 1.03 -- Purposely filter out these broken maps that exist in Generals. - if( !asciiMapName.compare( "maps\\armored fury\\armored fury.map" ) || - !asciiMapName.compare( "maps\\scorched earth\\scorched earth.map" ) ) - { - continue; - } -#endif - - MapCache::iterator mapCacheIt = TheMapCache->find(asciiMapName); - DEBUG_ASSERTCRASH(mapCacheIt != TheMapCache->end(), ("Map '%s' not found in map cache.", mapNameIt->str())); - /* - if (it != TheMapCache->end()) - { - DEBUG_LOG(("populateMapListbox(): looking at %s (displayName = %ls), mp = %d (== %d?) mapDir=%s (ok=%d)", - it->first.str(), it->second.m_displayName.str(), it->second.m_isMultiplayer, isMultiplayer, - mapDir.str(), it->first.startsWith(mapDir.str()))); - } - */ - - const Bool ok = addMapToMapListbox(lbData, mapDir, mapCacheIt->first, mapCacheIt->second); - - if (!ok) - return false; - } - - return true; -} - -//------------------------------------------------------------------------------------------------- -/** Load the listbox with all the map files available to play */ -//------------------------------------------------------------------------------------------------- -Int populateMapListboxNoReset( GameWindow *listbox, Bool useSystemMaps, Bool isMultiplayer, AsciiString mapToSelect ) -{ - if(!TheMapCache) - return -1; - - if (!listbox) - return -1; - - MapListBoxData lbData; - lbData.listbox = listbox; - lbData.numLength = GadgetListBoxGetListLength( listbox ); - lbData.numColumns = GadgetListBoxGetNumColumns( listbox ); - lbData.mapToSelect = mapToSelect; - lbData.isMultiplayer = isMultiplayer; - - if (lbData.numColumns > 1) - { - lbData.easyImage = TheMappedImageCollection->findImageByName("Star-Bronze"); - lbData.mediumImage = TheMappedImageCollection->findImageByName("Star-Silver"); - lbData.brutalImage = TheMappedImageCollection->findImageByName("Star-Gold"); - lbData.maxBrutalImage = TheMappedImageCollection->findImageByName("RedYell_Star"); - lbData.battleHonors = new SkirmishBattleHonors; - - lbData.w = lbData.brutalImage ? lbData.brutalImage->getImageWidth() : 10; - lbData.w = min(GadgetListBoxGetColumnWidth(listbox, 0), lbData.w); - lbData.h = lbData.w; - } - - AsciiString mapDir; - if (useSystemMaps) - { - mapDir = TheMapCache->getMapDir(); - } - else - { - mapDir = TheGlobalData->getPath_UserData(); - mapDir.concat(TheMapCache->getMapDir()); - } - mapDir.toLower(); - - MapNameList mapNames; - MapDisplayToFileNameList fileNames; - Int curNumPlayersInMap = 1; - - for (; curNumPlayersInMap <= MAX_SLOTS; ++curNumPlayersInMap) - { - buildMapListForNumPlayers(mapNames, fileNames, curNumPlayersInMap); - - const Bool ok = addMapCollectionToMapListbox(lbData, mapDir, mapNames, fileNames); - - mapNames.clear(); - fileNames.clear(); - - if (!ok) - break; - } - - delete lbData.battleHonors; - lbData.battleHonors = NULL; - - GadgetListBoxSetSelected(listbox, &lbData.selectionIndex, 1); - - if (lbData.selectionIndex >= 0) - { - Int topIndex = GadgetListBoxGetTopVisibleEntry(listbox); - Int bottomIndex = GadgetListBoxGetBottomVisibleEntry(listbox); - Int rowsOnScreen = bottomIndex - topIndex; - - if (lbData.selectionIndex >= bottomIndex) - { - Int newTop = max( 0, lbData.selectionIndex - max( 1, rowsOnScreen / 2 ) ); - //The trouble is that rowsOnScreen/2 can be zero if bottom is 1 and top is zero - GadgetListBoxSetTopVisibleEntry( listbox, newTop ); - } - } - - return lbData.selectionIndex; -} - -//------------------------------------------------------------------------------------------------- -/** Load the listbox with all the map files available to play */ -//------------------------------------------------------------------------------------------------- -Int populateMapListbox( GameWindow *listbox, Bool useSystemMaps, Bool isMultiplayer, AsciiString mapToSelect ) -{ - if(!TheMapCache) - return -1; - - if (!listbox) - return -1; - - // reset the listbox content - GadgetListBoxReset( listbox ); - - return populateMapListboxNoReset( listbox, useSystemMaps, isMultiplayer, mapToSelect ); -} - - - -//------------------------------------------------------------------------------------------------- -/** Validate a map */ -//------------------------------------------------------------------------------------------------- -Bool isValidMap( AsciiString mapName, Bool isMultiplayer ) -{ - if(!TheMapCache || mapName.isEmpty()) - return FALSE; - TheMapCache->updateCache(); - - mapName.toLower(); - MapCache::iterator it = TheMapCache->find(mapName); - if (it != TheMapCache->end()) - { - if (isMultiplayer == it->second.m_isMultiplayer) - { - return TRUE; - } - } - - return FALSE; -} - -//------------------------------------------------------------------------------------------------- -/** Find a valid map */ -//------------------------------------------------------------------------------------------------- -AsciiString getDefaultMap( Bool isMultiplayer ) -{ - if(!TheMapCache) - return AsciiString::TheEmptyString; - TheMapCache->updateCache(); - - MapCache::iterator it = TheMapCache->begin(); - for (; it != TheMapCache->end(); ++it) - { - if (isMultiplayer == it->second.m_isMultiplayer) - { - return it->first; - } - } - - return AsciiString::TheEmptyString; -} - - -AsciiString getDefaultOfficialMap() -{ - if(!TheMapCache) - return AsciiString::TheEmptyString; - TheMapCache->updateCache(); - - MapCache::iterator it = TheMapCache->begin(); - for (; it != TheMapCache->end(); ++it) - { - if (it->second.m_isMultiplayer && it->second.m_isOfficial) - { - return it->first; - } - } - return AsciiString::TheEmptyString; -} - - -Bool isOfficialMap( AsciiString mapName ) -{ - if(!TheMapCache || mapName.isEmpty()) - return FALSE; - TheMapCache->updateCache(); - mapName.toLower(); - MapCache::iterator it = TheMapCache->find(mapName); - if (it != TheMapCache->end()) - return it->second.m_isOfficial; - return FALSE; -} - - -const MapMetaData *MapCache::findMap(AsciiString mapName) -{ - mapName.toLower(); - MapCache::iterator it = find(mapName); - if (it == end()) - return NULL; - return &(it->second); -} - -// ------------------------------------------------------------------------------------------------ -/** Embed the pristine map into the xfer stream */ -// ------------------------------------------------------------------------------------------------ -static void copyFromBigToDir( const AsciiString& infile, const AsciiString& outfile ) -{ - // open the map file - - File *file = TheFileSystem->openFile( infile.str(), File::READ | File::BINARY ); - if( file == NULL ) - { - DEBUG_CRASH(( "copyFromBigToDir - Error opening source file '%s'", infile.str() )); - throw SC_INVALID_DATA; - } - - // how big is the map file - Int fileSize = file->seek( 0, File::END ); - - - // rewind to beginning of file - file->seek( 0, File::START ); - - // allocate buffer big enough to hold the entire map file - char *buffer = NEW char[ fileSize ]; - if( buffer == NULL ) - { - DEBUG_CRASH(( "copyFromBigToDir - Unable to allocate buffer for file '%s'", infile.str() )); - throw SC_INVALID_DATA; - } - - // copy the file to the buffer - if( file->read( buffer, fileSize ) < fileSize ) - { - DEBUG_CRASH(( "copyFromBigToDir - Error reading from file '%s'", infile.str() )); - throw SC_INVALID_DATA; - } - // close the BIG file - file->close(); - - File *filenew = TheFileSystem->openFile( outfile.str(), File::WRITE | File::CREATE | File::BINARY ); - - if( !filenew || filenew->write(buffer, fileSize) < fileSize) - { - DEBUG_CRASH(( "copyFromBigToDir - Error writing to file '%s'", outfile.str() )); - throw SC_INVALID_DATA; - } - - filenew->close(); - - // delete the buffer - delete [] buffer; -} - -Image *getMapPreviewImage( AsciiString mapName ) -{ - if(!TheGlobalData) - return NULL; - DEBUG_LOG(("%s Map Name", mapName.str())); - AsciiString tgaName = mapName; - AsciiString name; - AsciiString tempName; - tgaName.truncateBy(4); // ".map" - name = tgaName; - tgaName.concat(".tga"); - - AsciiString portableName = TheGameState->realMapPathToPortableMapPath(name); - tempName.set(AsciiString::TheEmptyString); - for(Int i = 0; i < portableName.getLength(); ++i) - { - char c = portableName.getCharAt(i); - if (c == '\\' || c == ':') - tempName.concat('_'); - else - tempName.concat(c); - } - - name = tempName; - name.concat(".tga"); - - - // copy file over - // copy source tgaName, to name - - Image *image = (Image *)TheMappedImageCollection->findImageByName(tempName); - if(!image) - { - - if(!TheFileSystem->doesFileExist(tgaName.str())) - return NULL; - AsciiString mapPreviewDir; - mapPreviewDir.format(MAP_PREVIEW_DIR_PATH, TheGlobalData->getPath_UserData().str()); - TheFileSystem->createDirectory(mapPreviewDir); - - mapPreviewDir.concat(name); - - Bool success = false; - try - { - copyFromBigToDir(tgaName, mapPreviewDir); - success = true; - } - catch (...) - { - success = false; // no rethrow - } - - if (success) - { - image = newInstance(Image); - image->setName(tempName); - //image->setFullPath("mission.tga"); - image->setFilename(name); - image->setStatus(IMAGE_STATUS_NONE); - Region2D uv; - uv.hi.x = 1.0f; - uv.hi.y = 1.0f; - uv.lo.x = 0.0f; - uv.lo.y = 0.0f; - image->setUV(&uv); - image->setTextureHeight(128); - image->setTextureWidth(128); - TheMappedImageCollection->addImage(image); - } - else - { - image = NULL; - } - } - - return image; - - - -/* - // sanity - if( mapName.isEmpty() ) - return NULL; - Region2D uv; - mapPreviewImage = TheMappedImageCollection->findImageByName("MapPreview"); - if(mapPreviewImage) - deleteInstance(mapPreviewImage); - - mapPreviewImage = TheMappedImageCollection->newImage(); - mapPreviewImage->setName("MapPreview"); - mapPreviewImage->setStatus(IMAGE_STATUS_RAW_TEXTURE); -// allocate our terrain texture - TextureClass * texture = new TextureClass( size.x, size.y, - WW3D_FORMAT_X8R8G8B8, MIP_LEVELS_1 ); - uv.lo.x = 0.0f; - uv.lo.y = 1.0f; - uv.hi.x = 1.0f; - uv.hi.y = 0.0f; - mapPreviewImage->setStatus( IMAGE_STATUS_RAW_TEXTURE ); - mapPreviewImage->setRawTextureData( texture ); - mapPreviewImage->setUV( &uv ); - mapPreviewImage->setTextureWidth( size.x ); - mapPreviewImage->setTextureHeight( size.y ); - mapPreviewImage->setImageSize( &size ); - - - CachedFileInputStream theInputStream; - if (theInputStream.open(AsciiString(mapName.str()))) - { - ChunkInputStream *pStrm = &theInputStream; - pStrm->absoluteSeek(0); - DataChunkInput file( pStrm ); - if (file.isValidFileType()) { // Backwards compatible files aren't valid data chunk files. - // Read the waypoints. - file.registerParser( "MapPreview", AsciiString::TheEmptyString, parseMapPreviewChunk ); - if (!file.parse(NULL)) { - DEBUG_ASSERTCRASH(false,("Unable to read MapPreview info.")); - deleteInstance(mapPreviewImage); - return NULL; - } - } - theInputStream.close(); - } - else - { - deleteInstance(mapPreviewImage); - return NULL; - } - - - return mapPreviewImage; - -*/ - return NULL; -} - -Bool parseMapPreviewChunk(DataChunkInput &file, DataChunkInfo *info, void *userData) -{ -/* - ICoord2D size; - - SurfaceClass *surface; - size.x = file.readInt(); - size.y = file.readInt(); - - - surface = (TextureClass *)mapPreviewImage->getRawTextureData()->Get_Surface_Level(); - //texture->Get_Surface_Level(); - - DEBUG_LOG(("BeginMapPreviewInfo")); - UnsignedInt *buffer = new UnsignedInt[size.x * size.y]; - Int x,y; - for (y=0; yDrawPixel( x, y, file.readInt() ); - buffer[y + x] = file.readInt(); - DEBUG_LOG(("x:%d, y:%d, %X", x, y, buffer[y + x])); - } - } - mapPreviewImage->setRawTextureData(buffer); - DEBUG_ASSERTCRASH(file.atEndOfChunk(), ("Unexpected data left over.")); - DEBUG_LOG(("EndMapPreviewInfo")); - REF_PTR_RELEASE(surface); - return true; -*/ - return FALSE; -} - -void findDrawPositions( Int startX, Int startY, Int width, Int height, Region3D extent, - ICoord2D *ul, ICoord2D *lr ) -{ - - Real ratioWidth; - Real ratioHeight; - Coord2D radar; - ratioWidth = extent.width()/(width * 1.0f); - ratioHeight = extent.height()/(height* 1.0f); - - if( ratioWidth >= ratioHeight) - { - radar.x = extent.width() / ratioWidth; - radar.y = extent.height()/ ratioWidth; - ul->x = 0; - ul->y = (height - radar.y) / 2.0f; - lr->x = radar.x; - lr->y = height - ul->y; - } - else - { - radar.x = extent.width() / ratioHeight; - radar.y = extent.height()/ ratioHeight; - ul->x = (width - radar.x ) / 2.0f; - ul->y = 0; - lr->x = width - ul->x; - lr->y = radar.y; - } - - // make them pixel positions - ul->x += startX; - ul->y += startY; - lr->x += startX; - lr->y += startY; - -} - diff --git a/Generals/Code/GameEngine/Source/GameClient/Terrain/TerrainRoads.cpp b/Generals/Code/GameEngine/Source/GameClient/Terrain/TerrainRoads.cpp deleted file mode 100644 index 03f3054a91..0000000000 --- a/Generals/Code/GameEngine/Source/GameClient/Terrain/TerrainRoads.cpp +++ /dev/null @@ -1,458 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public 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: TerrainRoads.cpp ///////////////////////////////////////////////////////////////////////// -// Author: Colin Day, December 2001 -// Desc: Terrain road/bridge descriptions -/////////////////////////////////////////////////////////////////////////////////////////////////// - -// INCLDUES /////////////////////////////////////////////////////////////////////////////////////// -#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine - -#define DEFINE_BODYDAMAGETYPE_NAMES -#include "Common/INI.h" -#include "GameClient/TerrainRoads.h" - -// PUBLIC DATA //////////////////////////////////////////////////////////////////////////////////// -TerrainRoadCollection *TheTerrainRoads = NULL; - -// PRIVATE DATA /////////////////////////////////////////////////////////////////////////////////// -UnsignedInt TerrainRoadCollection::m_idCounter = 0; - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -const FieldParse TerrainRoadType::m_terrainRoadFieldParseTable[] = -{ - - { "Texture", INI::parseAsciiString, NULL, offsetof( TerrainRoadType, m_texture ) }, - { "RoadWidth", INI::parseReal, NULL, offsetof( TerrainRoadType, m_roadWidth ) }, - { "RoadWidthInTexture", INI::parseReal, NULL, offsetof( TerrainRoadType, m_roadWidthInTexture ) }, - - { NULL, NULL, NULL, 0 }, - -}; - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -const FieldParse TerrainRoadType::m_terrainBridgeFieldParseTable[] = -{ - - { "BridgeScale", INI::parseReal, NULL, offsetof( TerrainRoadType, m_bridgeScale ) }, - { "ScaffoldObjectName", INI::parseAsciiString, NULL, offsetof( TerrainRoadType, m_scaffoldObjectName ) }, - { "ScaffoldSupportObjectName", INI::parseAsciiString, NULL, offsetof( TerrainRoadType, m_scaffoldSupportObjectName ) }, - { "RadarColor", INI::parseRGBColor, NULL, offsetof( TerrainRoadType, m_radarColor ) }, - - { "TransitionEffectsHeight", INI::parseReal, NULL, offsetof( TerrainRoadType, m_transitionEffectsHeight ) }, - { "NumFXPerType", INI::parseInt, NULL, offsetof( TerrainRoadType, m_numFXPerType ) }, - - { "BridgeModelName", INI::parseAsciiString, NULL, offsetof( TerrainRoadType, m_bridgeModelName ) }, - { "Texture", INI::parseAsciiString, NULL, offsetof( TerrainRoadType, m_texture ) }, - { "BridgeModelNameDamaged", INI::parseAsciiString, NULL, offsetof( TerrainRoadType, m_bridgeModelNameDamaged ) }, - { "TextureDamaged", INI::parseAsciiString, NULL, offsetof( TerrainRoadType, m_textureDamaged ) }, - { "BridgeModelNameReallyDamaged", INI::parseAsciiString, NULL, offsetof( TerrainRoadType, m_bridgeModelNameReallyDamaged ) }, - { "TextureReallyDamaged", INI::parseAsciiString, NULL, offsetof( TerrainRoadType, m_textureReallyDamaged ) }, - { "BridgeModelNameBroken", INI::parseAsciiString, NULL, offsetof( TerrainRoadType, m_bridgeModelNameBroken ) }, - { "TextureBroken", INI::parseAsciiString, NULL, offsetof( TerrainRoadType, m_textureBroken ) }, - - { "TowerObjectNameFromLeft", INI::parseAsciiString, NULL, offsetof( TerrainRoadType, m_towerObjectName[ BRIDGE_TOWER_FROM_LEFT ] ) }, - { "TowerObjectNameFromRight", INI::parseAsciiString, NULL, offsetof( TerrainRoadType, m_towerObjectName[ BRIDGE_TOWER_FROM_RIGHT ] ) }, - { "TowerObjectNameToLeft", INI::parseAsciiString, NULL, offsetof( TerrainRoadType, m_towerObjectName[ BRIDGE_TOWER_TO_LEFT ] ) }, - { "TowerObjectNameToRight", INI::parseAsciiString, NULL, offsetof( TerrainRoadType, m_towerObjectName[ BRIDGE_TOWER_TO_RIGHT ] ) }, - - { "DamagedToSound", INI::parseAsciiString, NULL, offsetof( TerrainRoadType, m_damageToSoundString[ BODY_DAMAGED ] ) }, - { "RepairedToSound", INI::parseAsciiString, NULL, offsetof( TerrainRoadType, m_repairedToSoundString[ BODY_DAMAGED ] ) }, - { "TransitionToOCL", parseTransitionToOCL, NULL, NULL }, - { "TransitionToFX", parseTransitionToFX, NULL, NULL }, - - - { NULL, NULL, NULL, 0 }, - -}; - -// ------------------------------------------------------------------------------------------------ -/** In the form of - * Label = Transition: ToState: EffectNum: OCL: */ -// ------------------------------------------------------------------------------------------------ -/*static*/ void TerrainRoadType::parseTransitionToOCL( INI *ini, - void *instance, - void *store, - const void *userData ) -{ - const char *token; - TerrainRoadType *theInstance = (TerrainRoadType *)instance; - - // which transition is this - Bool damageTransition; - token = ini->getNextSubToken( "Transition" ); - if( stricmp( token, "Damage" ) == 0 ) - damageTransition = TRUE; - else if( stricmp( token, "Repair" ) == 0 ) - damageTransition = FALSE; - else - { - - DEBUG_CRASH(( "Expected Damage/Repair transition keyword" )); - throw INI_INVALID_DATA; - - } - - // get body damage state - token = ini->getNextSubToken( "ToState" ); - BodyDamageType state = (BodyDamageType)ini->scanIndexList( token, TheBodyDamageTypeNames ); - - // get effect num - token = ini->getNextSubToken( "EffectNum" ); - Int effectNum = ini->scanInt( token ); - - // make effectNum zero based - --effectNum; - - // sanity check effect num - if( effectNum < 0 || effectNum >= MAX_BRIDGE_BODY_FX ) - { - - DEBUG_CRASH(( "Effect number max on bridge transitions is '%d'", MAX_BRIDGE_BODY_FX )); - throw INI_INVALID_DATA; - - } - - // read the string - token = ini->getNextSubToken( "OCL" ); - if( damageTransition ) - theInstance->friend_setDamageToOCLString( state, effectNum, AsciiString( token ) ); - else - theInstance->friend_setRepairedToOCLString( state, effectNum, AsciiString( token ) ); - -} - -// ------------------------------------------------------------------------------------------------ -/** In the form of - * Label = Transition: ToState: EffectNum: FX: */ -// ------------------------------------------------------------------------------------------------ -/*static*/ void TerrainRoadType::parseTransitionToFX( INI *ini, - void *instance, - void *store, - const void *userData ) -{ - const char *token; - TerrainRoadType *theInstance = (TerrainRoadType *)instance; - - // which transition is this - Bool damageTransition; - token = ini->getNextSubToken( "Transition" ); - if( stricmp( token, "Damage" ) == 0 ) - damageTransition = TRUE; - else if( stricmp( token, "Repair" ) == 0 ) - damageTransition = FALSE; - else - { - - DEBUG_CRASH(( "Expected Damage/Repair transition keyword" )); - throw INI_INVALID_DATA; - - } - - // get body damage state - token = ini->getNextSubToken( "ToState" ); - BodyDamageType state = (BodyDamageType)ini->scanIndexList( token, TheBodyDamageTypeNames ); - - // get effect num - token = ini->getNextSubToken( "EffectNum" ); - Int effectNum = ini->scanInt( token ); - - // make effectNum zero based - --effectNum; - - // sanity check effect num - if( effectNum < 0 || effectNum >= MAX_BRIDGE_BODY_FX ) - { - - DEBUG_CRASH(( "Effect number max on bridge transitions is '%d'", MAX_BRIDGE_BODY_FX )); - throw INI_INVALID_DATA; - - } - - // read the string - token = ini->getNextSubToken( "FX" ); - if( damageTransition ) - theInstance->friend_setDamageToFXString( state, effectNum, AsciiString( token ) ); - else - theInstance->friend_setRepairedToFXString( state, effectNum, AsciiString( token ) ); - -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -TerrainRoadType::TerrainRoadType( void ) -{ - - m_isBridge = FALSE; - m_id = 0; - m_next = NULL; - m_roadWidth = 0.0f; - m_roadWidthInTexture = 0.0f; - m_bridgeScale = 1.0f; - m_radarColor.red = 0.0f; - m_radarColor.green = 0.0f; - m_radarColor.blue = 0.0f; - m_transitionEffectsHeight = 0.0f; - m_numFXPerType = 0; - -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -TerrainRoadType::~TerrainRoadType( void ) -{ - -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////////////////// - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -TerrainRoadCollection::TerrainRoadCollection( void ) -{ - - m_roadList = NULL; - m_bridgeList = NULL; - - m_idCounter = 1; ///< MUST start this at 1. - -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -TerrainRoadCollection::~TerrainRoadCollection( void ) -{ - TerrainRoadType *temp; - - // delete all roads in the list - while( m_roadList ) - { - - // get next road - temp = m_roadList->friend_getNext(); - - // delete this road - deleteInstance(m_roadList); - - // set the new head of the list - m_roadList = temp; - - } - - // delete all bridges in the list - while( m_bridgeList ) - { - - // get next bridge - temp = m_bridgeList->friend_getNext(); - - // delete this bridge - deleteInstance(m_bridgeList); - - // set the new head of the list - m_bridgeList = temp; - - } - -} - -//------------------------------------------------------------------------------------------------- -/** Find road with matching name */ -//------------------------------------------------------------------------------------------------- -TerrainRoadType *TerrainRoadCollection::findRoad( AsciiString name ) -{ - TerrainRoadType *road; - - for( road = m_roadList; road; road = nextRoad( road ) ) - { - - if( road->getName() == name ) - return road; - - } - - // not found - return NULL; - -} - -//------------------------------------------------------------------------------------------------- -/** Find bridge with matching name */ -//------------------------------------------------------------------------------------------------- -TerrainRoadType *TerrainRoadCollection::findBridge( AsciiString name ) -{ - TerrainRoadType *bridge; - - for( bridge = m_bridgeList; bridge; bridge = nextBridge( bridge ) ) - { - - if( bridge->getName() == name ) - return bridge; - - } - - // not found - return NULL; - -} - -//------------------------------------------------------------------------------------------------- -/** Search the roads AND bridge lists for the name */ -//------------------------------------------------------------------------------------------------- -TerrainRoadType *TerrainRoadCollection::findRoadOrBridge( AsciiString name ) -{ - TerrainRoadType *road = findRoad( name ); - - if( road ) - return road; - else - return findBridge( name ); - -} - -//------------------------------------------------------------------------------------------------- -/** Allocate a new road, set the name, and link to the road list */ -//------------------------------------------------------------------------------------------------- -TerrainRoadType *TerrainRoadCollection::newRoad( AsciiString name ) -{ - TerrainRoadType *road = newInstance(TerrainRoadType); - - // assign the name - road->friend_setName( name ); - - // assign unique id - road->friend_setID( m_idCounter++ ); - - // is not a bridge - road->friend_setBridge( FALSE ); - - // set defaults from the default road - TerrainRoadType *defaultRoad = findRoad( "DefaultRoad" ); - if( defaultRoad ) - { - - road->friend_setTexture( defaultRoad->getTexture() ); - road->friend_setRoadWidth( defaultRoad->getRoadWidth() ); - road->friend_setRoadWidthInTexture( defaultRoad->getRoadWidthInTexture() ); - - } - - // link to list - road->friend_setNext( m_roadList ); - m_roadList = road; - - // return the new road - return road; - -} - -//------------------------------------------------------------------------------------------------- -/** Allocate a new bridge */ -//------------------------------------------------------------------------------------------------- -TerrainRoadType *TerrainRoadCollection::newBridge( AsciiString name ) -{ - TerrainRoadType *bridge = newInstance(TerrainRoadType); - - // assign the name - bridge->friend_setName( name ); - - // assign unique id - bridge->friend_setID( m_idCounter++ ); - - // is a bridge - bridge->friend_setBridge( TRUE ); - - // set defaults from the default bridge - TerrainRoadType *defaultBridge = findBridge( "DefaultBridge" ); - if( defaultBridge ) - { - - bridge->friend_setTexture( defaultBridge->getTexture() ); - bridge->friend_setBridgeScale( defaultBridge->getBridgeScale() ); - bridge->friend_setBridgeModelName( defaultBridge->getBridgeModel() ); - bridge->friend_setBridgeModelNameDamaged( defaultBridge->getBridgeModelNameDamaged() ); - bridge->friend_setBridgeModelNameReallyDamaged( defaultBridge->getBridgeModelNameReallyDamaged() ); - bridge->friend_setBridgeModelNameBroken( defaultBridge->getBridgeModelNameBroken() ); - bridge->friend_setTextureDamaged( defaultBridge->getTextureDamaged() ); - bridge->friend_setTextureReallyDamaged( defaultBridge->getTextureReallyDamaged() ); - bridge->friend_setTextureBroken( defaultBridge->getTextureBroken() ); - - bridge->friend_setTransitionEffectsHeight( defaultBridge->getTransitionEffectsHeight() ); - bridge->friend_setNumFXPerType( defaultBridge->getNumFXPerType() ); - for( Int state = BODY_PRISTINE; state < BODYDAMAGETYPE_COUNT; state++ ) - { - - bridge->friend_setDamageToSoundString( (BodyDamageType)state, bridge->getDamageToSoundString( (BodyDamageType)state ) ); - bridge->friend_setRepairedToSoundString( (BodyDamageType)state, bridge->getRepairedToSoundString( (BodyDamageType)state ) ); - - for( Int i = 0; i < MAX_BRIDGE_BODY_FX; i++ ) - { - - bridge->friend_setDamageToOCLString( (BodyDamageType)state, i, bridge->getDamageToOCLString( (BodyDamageType)state, i ) ); - bridge->friend_setDamageToFXString( (BodyDamageType)state, i, bridge->getDamageToOCLString( (BodyDamageType)state, i ) ); - bridge->friend_setRepairedToOCLString( (BodyDamageType)state, i, bridge->getDamageToOCLString( (BodyDamageType)state, i ) ); - bridge->friend_setRepairedToFXString( (BodyDamageType)state, i, bridge->getDamageToOCLString( (BodyDamageType)state, i ) ); - - } - - } - - } - - // link to list - bridge->friend_setNext( m_bridgeList ); - m_bridgeList = bridge; - - // return the new bridge - return bridge; - -} - -//------------------------------------------------------------------------------------------------- -/** Return next road in list */ -//------------------------------------------------------------------------------------------------- -TerrainRoadType *TerrainRoadCollection::nextRoad( TerrainRoadType *road ) -{ - - DEBUG_ASSERTCRASH( road->isBridge() == FALSE, ("nextRoad: road not a road") ); - return road->friend_getNext(); - -} - -//------------------------------------------------------------------------------------------------- -/** Return next bridge in list */ -//------------------------------------------------------------------------------------------------- -TerrainRoadType *TerrainRoadCollection::nextBridge( TerrainRoadType *bridge ) -{ - - DEBUG_ASSERTCRASH( bridge->isBridge() == TRUE, ("nextBridge, bridge is not a bridge") ); - return bridge->friend_getNext(); - -} - diff --git a/Generals/Code/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp b/Generals/Code/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp deleted file mode 100644 index 4220bb451e..0000000000 --- a/Generals/Code/GameEngine/Source/GameClient/Terrain/TerrainVisual.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) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: TerrainVisual.cpp //////////////////////////////////////////////////////////////////////// -// Interface for visual representation of terrain on the client -// Author: Colin Day, April 2001 -/////////////////////////////////////////////////////////////////////////////////////////////////// - -#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine -#include "Common/Xfer.h" -#include "GameClient/TerrainVisual.h" - - - - - -// GLOBALS //////////////////////////////////////////////////////////////////////////////////////// -TerrainVisual *TheTerrainVisual = NULL; - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// DEFINITIONS -/////////////////////////////////////////////////////////////////////////////////////////////////// - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -TerrainVisual::TerrainVisual() -{ - -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -TerrainVisual::~TerrainVisual() -{ - -} - -//------------------------------------------------------------------------------------------------- -/** initialize the device independent functionality of the visual terrain */ -//------------------------------------------------------------------------------------------------- -void TerrainVisual::init( void ) -{ - -} - -//------------------------------------------------------------------------------------------------- -/** Reset */ -//------------------------------------------------------------------------------------------------- -void TerrainVisual::reset( void ) -{ - - m_filenameString.clear(); - -} - -//------------------------------------------------------------------------------------------------- -/** Update */ -//------------------------------------------------------------------------------------------------- -void TerrainVisual::update( void ) -{ - // All the interesting stuff happens in load. jba. -} - -//------------------------------------------------------------------------------------------------- -/** device independent implementation for common terrain visual systems */ -//------------------------------------------------------------------------------------------------- -Bool TerrainVisual::load( AsciiString filename ) -{ - - // save the filename - if (filename.isEmpty()) - return FALSE; - - m_filenameString = filename; - - return TRUE; // success - -} - -// ------------------------------------------------------------------------------------------------ -/** CRC */ -// ------------------------------------------------------------------------------------------------ -void TerrainVisual::crc( Xfer *xfer ) -{ - -} - -// ------------------------------------------------------------------------------------------------ -/** Xfer - * Version Info: - * 1: Initial version */ -// ------------------------------------------------------------------------------------------------ -void TerrainVisual::xfer( Xfer *xfer ) -{ - - // version - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - -} - -// ------------------------------------------------------------------------------------------------ -/** Load post process */ -// ------------------------------------------------------------------------------------------------ -void TerrainVisual::loadPostProcess( void ) -{ - -} - - -SeismicSimulationFilterBase::SeismicSimStatusCode DomeStyleSeismicFilter::filterCallback( WorldHeightMapInterfaceClass *heightMap, const SeismicSimulationNode *node ) -{ - - Int life = node->m_life; - - if ( heightMap == NULL ) - return SEISMIC_STATUS_INVALID; - - - if ( life == 0 ) - return SEISMIC_STATUS_ACTIVE; - if ( life < 15 ) - { - // ADD HEIGHT BECAUSE THE EXPLOSION IS PUSHING DIRT UP - - Real magnitude = node->m_magnitude; - - Real offsScalar = magnitude / (Real)life; // real-life, get it? - Int radius = node->m_radius; - Int border = heightMap->getBorderSize(); - Int centerX = node->m_center.x + border ; - Int centerY = node->m_center.y + border ; - - UnsignedInt workspaceWidth = radius*2; - Real *workspace = NEW Real[ sqr(workspaceWidth) ]; - Real *workspaceEnd = workspace + sqr(workspaceWidth); - - - for ( Real *t = workspace; t < workspaceEnd; ++t ) *t = 0.0f;// clear the workspace - - Int x, y; - for (x = 0; x < radius; ++x) - { - for (y = 0; y < radius; ++y) - { - - Real distance = sqrt( sqr(x) + sqr(y) );//Pythagoras - - if ( distance < radius ) - { - Real distScalar = cos( ( distance / radius * (PI/2) ) ); - Real height = (offsScalar * distScalar); - - workspace[ (radius + x) + workspaceWidth * (radius + y) ] = height + heightMap->getBilinearSampleSeismicZVelocity( centerX + x, centerY + y ) ;//kaleidoscope - - if ( x != 0 ) // non-zero test prevents cross-shaped double stamp - { - workspace[ (radius - x) + workspaceWidth * (radius + y) ] = height + heightMap->getBilinearSampleSeismicZVelocity( centerX - x, centerY + y ) ; - if ( y != 0 ) - workspace[ (radius - x) + workspaceWidth * (radius - y) ] = height + heightMap->getBilinearSampleSeismicZVelocity( centerX - x, centerY - y ) ; - } - if ( y != 0 ) - workspace[ (radius + x) + workspaceWidth * (radius - y) ] = height + heightMap->getBilinearSampleSeismicZVelocity( centerX + x, centerY - y ) ; - } - } - } - - // stuff the values from the workspace into the heightmap's velocities - for (x = 0; x < workspaceWidth; ++x) - for (y = 0; y < workspaceWidth; ++y) - heightMap->setSeismicZVelocity( centerX - radius + x, centerY - radius + y, MIN( 9.0f, workspace[ x + workspaceWidth * y ]) ); - - delete [] workspace; - - return SEISMIC_STATUS_ACTIVE; - } - else - return SEISMIC_STATUS_ZERO_ENERGY; -} - -Real DomeStyleSeismicFilter::applyGravityCallback( Real velocityIn ) -{ - Real velocityOut = velocityIn; - velocityOut -= 1.5f; - return velocityOut; -} diff --git a/Generals/Code/GameEngineDevice/CMakeLists.txt b/Generals/Code/GameEngineDevice/CMakeLists.txt index 37a9ed2334..ab3d8f1d62 100644 --- a/Generals/Code/GameEngineDevice/CMakeLists.txt +++ b/Generals/Code/GameEngineDevice/CMakeLists.txt @@ -6,7 +6,7 @@ set(GAMEENGINEDEVICE_SRC Include/W3DDevice/Common/W3DModuleFactory.h # Include/W3DDevice/Common/W3DRadar.h Include/W3DDevice/Common/W3DThingFactory.h - Include/W3DDevice/GameClient/HeightMap.h +# Include/W3DDevice/GameClient/HeightMap.h Include/W3DDevice/GameClient/Module/W3DDebrisDraw.h Include/W3DDevice/GameClient/Module/W3DDefaultDraw.h Include/W3DDevice/GameClient/Module/W3DDependencyModelDraw.h @@ -22,8 +22,8 @@ set(GAMEENGINEDEVICE_SRC Include/W3DDevice/GameClient/Module/W3DTankTruckDraw.h Include/W3DDevice/GameClient/Module/W3DTracerDraw.h Include/W3DDevice/GameClient/Module/W3DTruckDraw.h - Include/W3DDevice/GameClient/TerrainTex.h - Include/W3DDevice/GameClient/TileData.h +# Include/W3DDevice/GameClient/TerrainTex.h +# Include/W3DDevice/GameClient/TileData.h Include/W3DDevice/GameClient/W3DAssetManager.h Include/W3DDevice/GameClient/W3DAssetManagerExposed.h Include/W3DDevice/GameClient/W3DBibBuffer.h @@ -56,9 +56,9 @@ set(GAMEENGINEDEVICE_SRC Include/W3DDevice/GameClient/W3DShadow.h Include/W3DDevice/GameClient/W3DShroud.h Include/W3DDevice/GameClient/W3DStatusCircle.h - Include/W3DDevice/GameClient/W3DTerrainTracks.h - Include/W3DDevice/GameClient/W3DTerrainVisual.h - Include/W3DDevice/GameClient/W3DTreeBuffer.h +# Include/W3DDevice/GameClient/W3DTerrainTracks.h +# Include/W3DDevice/GameClient/W3DTerrainVisual.h +# Include/W3DDevice/GameClient/W3DTreeBuffer.h # Include/W3DDevice/GameClient/W3DVideoBuffer.h # Include/W3DDevice/GameClient/W3DView.h Include/W3DDevice/GameClient/W3DVolumetricShadow.h @@ -66,7 +66,7 @@ set(GAMEENGINEDEVICE_SRC # Include/W3DDevice/GameClient/W3DWaterTracks.h Include/W3DDevice/GameClient/W3DWaypointBuffer.h Include/W3DDevice/GameClient/W3DWebBrowser.h - Include/W3DDevice/GameClient/WorldHeightMap.h +# Include/W3DDevice/GameClient/WorldHeightMap.h Include/W3DDevice/GameLogic/W3DGameLogic.h Include/W3DDevice/GameLogic/W3DGhostObject.h Include/W3DDevice/GameLogic/W3DTerrainLogic.h @@ -117,7 +117,7 @@ set(GAMEENGINEDEVICE_SRC Source/W3DDevice/GameClient/GUI/W3DGameFont.cpp Source/W3DDevice/GameClient/GUI/W3DGameWindow.cpp Source/W3DDevice/GameClient/GUI/W3DGameWindowManager.cpp - Source/W3DDevice/GameClient/HeightMap.cpp +# Source/W3DDevice/GameClient/HeightMap.cpp Source/W3DDevice/GameClient/Shaders/invmonochrome.nvp Source/W3DDevice/GameClient/Shaders/monochrome.nvp Source/W3DDevice/GameClient/Shaders/motionblur.nvp @@ -130,8 +130,8 @@ set(GAMEENGINEDEVICE_SRC Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp Source/W3DDevice/GameClient/Shadow/W3DShadow.cpp Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp - Source/W3DDevice/GameClient/TerrainTex.cpp - Source/W3DDevice/GameClient/TileData.cpp +# Source/W3DDevice/GameClient/TerrainTex.cpp +# Source/W3DDevice/GameClient/TileData.cpp Source/W3DDevice/GameClient/W3DAssetManager.cpp Source/W3DDevice/GameClient/W3DAssetManagerExposed.cpp Source/W3DDevice/GameClient/W3DBibBuffer.cpp @@ -154,9 +154,9 @@ set(GAMEENGINEDEVICE_SRC # Source/W3DDevice/GameClient/W3DShaderManager.cpp Source/W3DDevice/GameClient/W3DShroud.cpp Source/W3DDevice/GameClient/W3DStatusCircle.cpp - Source/W3DDevice/GameClient/W3DTerrainTracks.cpp - Source/W3DDevice/GameClient/W3DTerrainVisual.cpp - Source/W3DDevice/GameClient/W3DTreeBuffer.cpp +# Source/W3DDevice/GameClient/W3DTerrainTracks.cpp +# Source/W3DDevice/GameClient/W3DTerrainVisual.cpp +# Source/W3DDevice/GameClient/W3DTreeBuffer.cpp # Source/W3DDevice/GameClient/W3DVideoBuffer.cpp # Source/W3DDevice/GameClient/W3DView.cpp Source/W3DDevice/GameClient/W3dWaypointBuffer.cpp @@ -165,7 +165,7 @@ set(GAMEENGINEDEVICE_SRC # Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp # Source/W3DDevice/GameClient/Water/wave.nvp # Source/W3DDevice/GameClient/Water/wave.nvv - Source/W3DDevice/GameClient/WorldHeightMap.cpp +# Source/W3DDevice/GameClient/WorldHeightMap.cpp Source/W3DDevice/GameLogic/W3DGameLogic.cpp Source/W3DDevice/GameLogic/W3DGhostObject.cpp Source/W3DDevice/GameLogic/W3DTerrainLogic.cpp diff --git a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h deleted file mode 100644 index d800fea6a3..0000000000 --- a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.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) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#include "always.h" -#include "rendobj.h" -#include "w3d_file.h" -#include "dx8vertexbuffer.h" -#include "dx8indexbuffer.h" -#include "dx8wrapper.h" -#include "shader.h" -#include "vertmaterial.h" -#include "Lib/BaseType.h" -#include "Common/GameType.h" -#include "W3DDevice/GameClient/WorldHeightMap.h" -#include "W3DDevice/GameClient/BaseHeightMap.h" - -#define VERTEX_BUFFER_TILE_LENGTH 32 //tiles of side length 32 (grid of 33x33 vertices). - -// Adjust the triangles to make cliff sides most attractive. jba. -#define FLIP_TRIANGLES 1 - - -/// Custom render object that draws the heightmap and handles intersection tests. -/** -Custom W3D render object that's used to process the terrain. It handles -virtually everything to do with the terrain, including: drawing, lighting, -scorchmarks and intersection tests. -*/ - - - -class HeightMapRenderObjClass : public BaseHeightMapRenderObjClass -{ - -public: - - HeightMapRenderObjClass(void); - virtual ~HeightMapRenderObjClass(void); - - // DX8_CleanupHook methods - virtual void ReleaseResources(void); ///< Release all dx8 resources so the device can be reset. - virtual void ReAcquireResources(void); ///< Reacquire all resources after device reset. - - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface (W3D methods) - ///////////////////////////////////////////////////////////////////////////// - virtual void Render(RenderInfoClass & rinfo); - virtual void On_Frame_Update(void); - - ///allocate resources needed to render heightmap - virtual int initHeightData(Int width, Int height, WorldHeightMap *pMap, RefRenderObjListIterator *pLightsIterator, Bool updateExtraPassTiles=TRUE); - virtual Int freeMapResources(void); ///< free resources used to render heightmap - virtual void updateCenter(CameraClass *camera, RefRenderObjListIterator *pLightsIterator); - - virtual void staticLightingChanged(void); - virtual void adjustTerrainLOD(Int adj); - virtual void reset(void); - virtual void doPartialUpdate(const IRegion2D &partialRange, WorldHeightMap *htMap, RefRenderObjListIterator *pLightsIterator); - - virtual void oversizeTerrain(Int tilesToOversize); - - virtual int updateBlock(Int x0, Int y0, Int x1, Int y1, WorldHeightMap *pMap, RefRenderObjListIterator *pLightsIterator); - -protected: - Int *m_extraBlendTilePositions; ///. -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// TerrainTex.h -// Class to generate texture for terrain. -// Author: John Ahlquist, April 2001 - -#pragma once - -//#define DO_8STAGE_TERRAIN_PASS //optimized terrain rendering for Nvidia based cards - -#include "WW3D2/texture.h" -#include "WWMath/matrix3d.h" -#include "Common/AsciiString.h" - -class WorldHeightMap; -#define TILE_OFFSET 8 -/** *********************************************************************** -** TerrainTextureClass -***************************************************************************/ -class TerrainTextureClass : public TextureClass -{ - W3DMPO_GLUE(TerrainTextureClass) -protected: - virtual void Apply(unsigned int stage); - -public: - /// Create texture for a height map. - TerrainTextureClass(int height); - - /// Create texture for a height map. - TerrainTextureClass(int height, int width); - - // just use default destructor. ~TerrainTextureClass(void); -public: - int update(WorldHeightMap *htMap); ///< Sets the pixels, and returns the actual height of the texture. - Bool updateFlat(WorldHeightMap *htMap, Int xCell, Int yCell, Int cellWidth, Int pixelsPerCell); ///< Sets the pixels. - void setLOD(Int LOD); -}; - - -class AlphaTerrainTextureClass : public TextureClass -{ - W3DMPO_GLUE(AlphaTerrainTextureClass) -protected: - virtual void Apply(unsigned int stage); -public: - // Create texture for a height map. - AlphaTerrainTextureClass(TextureClass *pBaseTex ); - - // just use default destructor. ~TerrainTextureClass(void); - -}; - -/** *********************************************************************** -** AlphaEdgeTextureClass -***************************************************************************/ -class AlphaEdgeTextureClass : public TextureClass -{ - W3DMPO_GLUE(AlphaEdgeTextureClass) -protected: - virtual void Apply(unsigned int stage); - int update256(WorldHeightMap *htMap);///< Sets the pixels, and returns the actual height of the texture. - -public: - /// Create texture for a height map. - AlphaEdgeTextureClass(int height, MipCountType mipLevelCount = MIP_LEVELS_3 ); - - // just use default destructor. ~TerrainTextureClass(void); -public: - int update(WorldHeightMap *htMap); ///< Sets the pixels, and returns the actual height of the texture. - -}; - -class LightMapTerrainTextureClass : public TextureClass -{ - W3DMPO_GLUE(LightMapTerrainTextureClass) -protected: - virtual void Apply(unsigned int stage); - -public: - // Create texture from a height map. - LightMapTerrainTextureClass( AsciiString name, MipCountType mipLevelCount = MIP_LEVELS_ALL ); - - // just use default destructor. -}; - -class ScorchTextureClass : public TextureClass -{ - W3DMPO_GLUE(ScorchTextureClass) -protected: - virtual void Apply(unsigned int stage); - -public: - // Create texture. - ScorchTextureClass( MipCountType mipLevelCount = MIP_LEVELS_3 ); - - // just use default destructor. ~ScorchTextureClass(void); -}; - -class CloudMapTerrainTextureClass : public TextureClass -{ - W3DMPO_GLUE(CloudMapTerrainTextureClass) -protected: - virtual void Apply(unsigned int stage); - -protected: - float m_xSlidePerSecond ; ///< How far the clouds move per second. - float m_ySlidePerSecond ; ///< How far the clouds move per second. - int m_curTick; - float m_xOffset; - float m_yOffset; - - -public: - // Create texture from a height map. - CloudMapTerrainTextureClass( MipCountType mipLevelCount = MIP_LEVELS_ALL ); - - // just use default destructor. ~TerrainTextureClass(void); - - void restore(void); -}; diff --git a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/TileData.h b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/TileData.h deleted file mode 100644 index 8eb350f2ae..0000000000 --- a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/TileData.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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// TileData.h -// Class to hold 1 tile's data. -// Author: John Ahlquist, April 2001 - -#pragma once - -#include "Lib/BaseType.h" -#include "WWLib/refcount.h" -#include "Common/AsciiString.h" - -typedef struct { - Int blendNdx; - UnsignedByte horiz; - UnsignedByte vert; - UnsignedByte rightDiagonal; - UnsignedByte leftDiagonal; - UnsignedByte inverted; - UnsignedByte longDiagonal; - Int customBlendEdgeClass; // Class of texture for a blend edge. -1 means use alpha. -} TBlendTileInfo; - -#define INVERTED_MASK 0x1 //AND this with TBlendTileInfo.inverted to get actual inverted state -#define FLIPPED_MASK 0x2 //AND this with TBlendTileInfo.inverted to get forced flip state (for horizontal/vertical flips). -#define TILE_PIXEL_EXTENT 64 -#define TILE_BYTES_PER_PIXEL 4 -#define DATA_LEN_BYTES TILE_PIXEL_EXTENT*TILE_PIXEL_EXTENT*TILE_BYTES_PER_PIXEL -#define DATA_LEN_PIXELS TILE_PIXEL_EXTENT*TILE_PIXEL_EXTENT -#define TILE_PIXEL_EXTENT_MIP1 32 -#define TILE_PIXEL_EXTENT_MIP2 16 -#define TILE_PIXEL_EXTENT_MIP3 8 -#define TILE_PIXEL_EXTENT_MIP4 4 -#define TILE_PIXEL_EXTENT_MIP5 2 -#define TILE_PIXEL_EXTENT_MIP6 1 -#define TEXTURE_WIDTH 2048 // was 1024 jba - -/** This class holds the bitmap data from the .tga texture files. It is used to -create the D3D texture in the game and 3d windows, and to create DIB data for the -2d window. */ -class TileData : public RefCountClass -{ -protected: - - // data is bgrabgrabgra to be compatible with windows blt. jba. - // Also, first byte is lower left pixel, not upper left pixel. - // so 0,0 is lower left, not upper left. - UnsignedByte m_tileData[DATA_LEN_BYTES]; - /// Mipped down copies of the tile data. - UnsignedByte m_tileDataMip32[TILE_PIXEL_EXTENT_MIP1*TILE_PIXEL_EXTENT_MIP1*TILE_BYTES_PER_PIXEL]; - UnsignedByte m_tileDataMip16[TILE_PIXEL_EXTENT_MIP2*TILE_PIXEL_EXTENT_MIP2*TILE_BYTES_PER_PIXEL]; - UnsignedByte m_tileDataMip8[TILE_PIXEL_EXTENT_MIP3*TILE_PIXEL_EXTENT_MIP3*TILE_BYTES_PER_PIXEL]; - UnsignedByte m_tileDataMip4[TILE_PIXEL_EXTENT_MIP4*TILE_PIXEL_EXTENT_MIP4*TILE_BYTES_PER_PIXEL]; - UnsignedByte m_tileDataMip2[TILE_PIXEL_EXTENT_MIP5*TILE_PIXEL_EXTENT_MIP5*TILE_BYTES_PER_PIXEL]; - UnsignedByte m_tileDataMip1[TILE_PIXEL_EXTENT_MIP6*TILE_PIXEL_EXTENT_MIP6*TILE_BYTES_PER_PIXEL]; - -public: - ICoord2D m_tileLocationInTexture; - - -protected: - /** doMip - generates the next mip level mipping pHiRes down to pLoRes. - pLoRes is 1/2 the width of pHiRes, and both are square. */ - static void doMip(UnsignedByte *pHiRes, Int hiRow, UnsignedByte *pLoRes); - - - -public: - TileData(void); - -public: - UnsignedByte *getDataPtr(void) {return(m_tileData);}; - static Int dataLen(void) {return(DATA_LEN_BYTES);}; - - void updateMips(void); - - Bool hasRGBDataForWidth(Int width); - UnsignedByte *getRGBDataForWidth(Int width); -}; diff --git a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainTracks.h b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainTracks.h deleted file mode 100644 index 345b61ad24..0000000000 --- a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainTracks.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) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#include "always.h" -#include "rendobj.h" -#include "w3d_file.h" -#include "dx8vertexbuffer.h" -#include "dx8indexbuffer.h" -#include "shader.h" -#include "vertmaterial.h" -#include "Lib/BaseType.h" - -#define MAX_TRACK_EDGE_COUNT 100 //maximum number of edges or divisions in track mark -#define MAX_TRACK_OPAQUE_EDGE 25 //linear fade of edges will begin at this edge -#define FADE_TIME_FRAMES 300000 // 300 seconds at 30 fps - time to fade out an edge and remove it from the system. - -class TerrainTracksRenderObjClassSystem; -class Drawable; - -/// Custom render object that draws tracks on the terrain. -/** -This render object handles drawing tracks left by objects moving on the terrain. -*/ -class TerrainTracksRenderObjClass : public W3DMPO, public RenderObjClass -{ - W3DMPO_GLUE(TerrainTracksRenderObjClass) - - friend class TerrainTracksRenderObjClassSystem; - -public: - - TerrainTracksRenderObjClass(void); - ~TerrainTracksRenderObjClass(void); - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface (W3D methods) - ///////////////////////////////////////////////////////////////////////////// - virtual RenderObjClass * Clone(void) const; - virtual int Class_ID(void) const; - virtual void Render(RenderInfoClass & rinfo); - virtual void Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const; - virtual void Get_Obj_Space_Bounding_Box(AABoxClass & aabox) const; - - Int freeTerrainTracksResources(void); ///. -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: W3DTerrainVisual.h /////////////////////////////////////////////////////////////////////// -// W3D implementation details for visual aspects of terrain -// Author: Colin Day, April 2001 -/////////////////////////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#include "GameClient/TerrainVisual.h" -#include "W3DDevice/GameClient/W3DWater.h" - -// FORWARD REFERENCES ///////////////////////////////////////////////////////////////////////////// -class Matrix3D; -class WaterHandle; -class BaseHeightMapRenderObjClass; -class WorldHeightMap; - -//------------------------------------------------------------------------------------------------- -/** W3D impelmentation of visual terrain details singleton */ -//------------------------------------------------------------------------------------------------- -class W3DTerrainVisual : public TerrainVisual -{ - -public: - - W3DTerrainVisual(); - virtual ~W3DTerrainVisual(); - - virtual void init( void ); - virtual void reset( void ); - virtual void update( void ); - - virtual Bool load( AsciiString filename ); - - void getTerrainColorAt( Real x, Real y, RGBColor *pColor ); - - /// get the terrain tile type at the world location in the (x,y) plane ignoring Z - TerrainType *getTerrainTile( Real x, Real y ); - - /** intersect the ray with the terrain, if a hit occurs TRUE is returned - and the result point on the terrain is returned in "result" */ - virtual Bool intersectTerrain( Coord3D *rayStart, Coord3D *rayEnd, Coord3D *result ); - - // - // water methods - // - /// enable/disable the water grid - virtual void enableWaterGrid( Bool enable ); - /// set min/max height values allowed in water grid pointed to by waterTable - virtual void setWaterGridHeightClamps( const WaterHandle *waterTable, Real minZ, Real maxZ ); - /// adjust fallof parameters for grid change method - virtual void setWaterAttenuationFactors( const WaterHandle *waterTable, - Real a, Real b, Real c, Real range ); - /// set the water table position and orientation in world space - virtual void setWaterTransform( const WaterHandle *waterTable, - Real angle, Real x, Real y, Real z ); - virtual void setWaterTransform( const Matrix3D *transform ); - virtual void getWaterTransform( const WaterHandle *waterTable, Matrix3D *transform ); - /// water grid resolution spacing - virtual void setWaterGridResolution( const WaterHandle *waterTable, - Real gridCellsX, Real gridCellsY, Real cellSize ); - virtual void getWaterGridResolution( const WaterHandle *waterTable, - Real *gridCellsX, Real *gridCellsY, Real *cellSize ); - /// adjust the water grid in world coords by the delta - virtual void changeWaterHeight( Real x, Real y, Real delta ); - /// adjust the velocity at a water grid point corresponding to the world x,y - virtual void addWaterVelocity( Real worldX, Real worldY, - Real velocity, Real preferredHeight ); - virtual Bool getWaterGridHeight( Real worldX, Real worldY, Real *height); - - virtual void setTerrainTracksDetail(void); - virtual void setShoreLineDetail(void); - - /// Add a bib at location. - void addFactionBib(Object *factionBuilding, Bool highlight, Real extra = 0); - /// Remove a bib. - void removeFactionBib(Object *factionBuilding); - - /// Add a bib at location. - void addFactionBibDrawable(Drawable *factionBuilding, Bool highlight, Real extra = 0); - /// Remove a bib. - void removeFactionBibDrawable(Drawable *factionBuilding); - - virtual void removeAllBibs(void); - virtual void removeBibHighlighting(void); - - virtual void addProp(const ThingTemplate *tt, const Coord3D *pos, Real angle); - - virtual void removeTreesAndPropsForConstruction( - const Coord3D* pos, - const GeometryInfo& geom, - Real angle - ); - - - // - // Modify height. - // - virtual void setRawMapHeight(const ICoord2D *gridPos, Int height); - virtual Int getRawMapHeight(const ICoord2D *gridPos); - - /// Replace the skybox texture - virtual void replaceSkyboxTextures(const AsciiString *oldTexName[NumSkyboxTextures], const AsciiString *newTexName[NumSkyboxTextures]); - - //////////////////////////////////////////////////// - //////////////////////////////////////////////////// - //////////////////////////////////////////////////// -#ifdef DO_SEISMIC_SIMULATIONS - virtual void addSeismicSimulation( const SeismicSimulationNode& sim ); -#endif - WorldHeightMap* getLogicHeightMap( void ) {return m_logicHeightMap;}; - WorldHeightMap* getClientHeightMap( void ) - { -#ifdef DO_SEISMIC_SIMULATIONS - return m_clientHeightMap; -#else - return m_logicHeightMap; -#endif - } - //////////////////////////////////////////////////// - //////////////////////////////////////////////////// - //////////////////////////////////////////////////// - -protected: - - // snapshot methods - virtual void crc( Xfer *xfer ); - virtual void xfer( Xfer *xfer ); - virtual void loadPostProcess( void ); - -#ifdef DO_SEISMIC_SIMULATIONS - //////////////////////////////////////////////////// - //////////////////////////////////////////////////// - //////////////////////////////////////////////////// - virtual void handleSeismicSimulations( void ); - SeismicSimulationList m_seismicSimulationList; - virtual void updateSeismicSimulations( void ); /// walk the SeismicSimulationList and, well, do it. - - //////////////////////////////////////////////////// - //////////////////////////////////////////////////// - //////////////////////////////////////////////////// -#endif - - BaseHeightMapRenderObjClass *m_terrainRenderObject; ///< W3D render object for terrain - WaterRenderObjClass *m_waterRenderObject; ///< W3D render object for water plane - - WorldHeightMap *m_logicHeightMap; ///< height map used for render obj building - -#ifdef DO_SEISMIC_SIMULATIONS - WorldHeightMap *m_clientHeightMap; ///< this is a workspace for animating the terrain elevations -#endif - - Bool m_isWaterGridRenderingEnabled; - - AsciiString m_currentSkyboxTexNames[NumSkyboxTextures]; ///. -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: W3DTreeBuffer.h ////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: W3DTreeBuffer.h -// -// Created: John Ahlquist, May 2001 -// -// Desc: Draw buffer to handle all the trees in a scene. -// -//----------------------------------------------------------------------------- - -#pragma once - -//----------------------------------------------------------------------------- -// Includes -//----------------------------------------------------------------------------- -#include "always.h" -#include "rendobj.h" -#include "w3d_file.h" -#include "texture.h" -#include "dx8vertexbuffer.h" -#include "dx8indexbuffer.h" -#include "shader.h" -#include "vertmaterial.h" -#include "Lib/BaseType.h" -#include "Common/GameType.h" -#include "Common/AsciiString.h" -#include "Common/GlobalData.h" - -//----------------------------------------------------------------------------- -// Forward References -//----------------------------------------------------------------------------- -class MeshClass; -class W3DTreeBuffer; -class TileData; -class W3DTreeDrawModuleData; -struct BreezeInfo; -class GeometryInfo; -class W3DProjectedShadow; - -//----------------------------------------------------------------------------- -// Type Defines -//----------------------------------------------------------------------------- - -enum W3DToppleState CPP_11(: Int) -{ - TOPPLE_UPRIGHT = 0, - TOPPLE_FALLING, - TOPPLE_FOGGED, - TOPPLE_SHROUDED, // unused - TOPPLE_DOWN -}; -/// The individual data for a tree. -typedef struct { - Vector3 location; ///< Drawing location - Real scale; ///< Scale at location. - Real sin; ///< Sine of the rotation angle at location. - Real cos; ///< Cosine of the rotation angle at location. - Int treeType; ///< Type of tree. - Bool visible; ///< Visible flag, updated each frame. - SphereClass bounds; ///< Bounding sphere for culling to set the visible flag. - Real sortKey; ///< Sort key, essentially the distance along the look at vector. - DrawableID drawableID; ///< Drawable this tree corresponds to. - - Real pushAside; - Real pushAsideDelta; - Real pushAsideSin; ///< Sine of the rotation angle at location. - Real pushAsideCos; ///< Cosine of the rotation angle at location. - ObjectID pushAsideSource; ///< Unit that is pushing us aside. - - UnsignedInt lastFrameUpdated; ///< Last frame push aside was updated. - - Int nextInPartition; - - Int swayType; ///< Which sway array entry we are using. - - Int firstIndex; ///< First index in the vertex buffer for this tree. - Int bufferNdx; ///< Which vertex buffer this is in. - - // Topple parameters. [7/7/2003] - Real m_angularVelocity; ///< Velocity in degrees per frame (or is it radians per frame?) - Real m_angularAcceleration; ///< Acceleration angularVelocity is increasing - Coord3D m_toppleDirection; ///< Z-less direction we are toppling - W3DToppleState m_toppleState; ///< Stage this module is in. - Real m_angularAccumulation; ///< How much have I rotated so I know when to bounce. - UnsignedInt m_options; ///< topple options - Matrix3D m_mtx; - Real m_sinkFramesLeft; ///< Toppled trees sink into the terrain & disappear, how many frames left. - -} TTree; - -/// The individual data for a tree type. -typedef struct { - MeshClass * m_mesh; ///< Mesh for this kind of tree. - SphereClass m_bounds; ///< Bounding boxes for the base tree models. - const W3DTreeDrawModuleData *m_data; - ICoord2D m_textureOrigin; ///< Texture origin in the mega texture. - Int m_numTiles; ///< Number of tex tiles. - Int m_firstTile;///< First texture tile. - Int m_tileWidth;///< Width in tiles of texture; - Bool m_halfTile; ///< Tiles are 64x64 pixels, half tile supports a 32x32 bit texture. Have to adjust the uv values. - Vector3 m_offset; - Real m_shadowSize; ///< Shadow radius. - Bool m_doShadow; ///< Draw shadow. - -} TTreeType; - -// -// W3DTreeBuffer: Draw buffer for the trees. -// -// -class W3DTreeBuffer : public Snapshot -{ -//friend class BaseHeightMapRenderObjClass; - - //----------------------------------------------------------------------------- - // W3DTreeTextureClass - //----------------------------------------------------------------------------- - class W3DTreeTextureClass : public TextureClass - { - W3DMPO_GLUE(W3DTreeTextureClass) - protected: - virtual void Apply(unsigned int stage); - - public: - /// Create texture. - W3DTreeTextureClass(unsigned width, unsigned height); - - // just use default destructor. ~TerrainTextureClass(void); - public: - int update(W3DTreeBuffer *buffer); ///< Sets the pixels, and returns the actual height of the texture. - void setLOD(Int LOD) const; - }; - -public: - - W3DTreeBuffer(void); - ~W3DTreeBuffer(void); - /// Add a tree at location. Name is the w3d model name. - void addTree(DrawableID id, Coord3D location, Real scale, Real angle, - Real randomScaleAmount, const W3DTreeDrawModuleData *data); - /// Notify that an object moved, so check for collisions. - void unitMoved(Object *unit); - /// Add a type of tree. Name is the w3d model name. - Int addTreeType(const W3DTreeDrawModuleData *data); - /// Updates a tree's location. - Bool updateTreePosition(DrawableID id, Coord3D location, Real angle); - void pushAsideTree( DrawableID id, const Coord3D *pusherPos, - const Coord3D *pusherDirection, ObjectID pusherID ); - /// Remove a tree. - void removeTree(DrawableID id); - /// Remove trees that would be under a building. - void removeTreesForConstruction( - const Coord3D* pos, - const GeometryInfo& geom, - Real angle - ); - - void setTextureLOD(Int lod); ///. -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - - -// WorldHeightMap.h -// Class to encapsulate height map. -// Author: John Ahlquist, April 2001 - -#pragma once - -#include "Lib/BaseType.h" -#include "WWLib/refcount.h" -#include "WWMath/vector3.h" -#include "W3DDevice/GameClient/TileData.h" -#include "Common/MapObject.h" - -#include "Common/STLTypedefs.h" -typedef std::vector VecICoord2D; - - -/** MapObject class -Not ref counted. Do not store pointers to this class. */ - -#define K_MIN_HEIGHT 0 -#define K_MAX_HEIGHT 255 - -#define NUM_SOURCE_TILES 1024 -#define NUM_BLEND_TILES 16192 -#define NUM_CLIFF_INFO 32384 -#define FLAG_VAL 0x7ADA0000 - -// For backwards compatiblity. -#define TEX_PATH_LEN 256 - - -/// Struct in memory. -typedef struct { - Int globalTextureClass; - Int firstTile; - Int numTiles; - Int width; - Int isBlendEdgeTile; ///< True if the texture contains blend edges. - AsciiString name; - ICoord2D positionInTexture; -} TXTextureClass; - -typedef enum {POS_X, POS_Y, NEG_X, NEG_Y} TVDirection; -/// Struct in memory. -typedef struct { - Real u0, v0; // Upper left uv - Real u1, v1; // Lower left uv - Real u2, v2; // Lower right uv - Real u3, v3; // Upper right uv - Bool flip; - Bool mutant; // Mutant mapping needed to get this to fit. - Short tileIndex; // Tile texture. -} TCliffInfo; - -#define NUM_TEXTURE_CLASSES 256 - - -class TextureClass; -class ChunkInputStream; -class InputStream; -class OutputStream; -class DataChunkInput; -struct DataChunkInfo; -class AlphaEdgeTextureClass; - -#define NUM_ALPHA_TILES 12 - -class WorldHeightMap : public RefCountClass, - public WorldHeightMapInterfaceClass -{ - friend class TerrainTextureClass; - friend class AlphaTerrainTextureClass; - friend class W3DCustomEdging; - friend class AlphaEdgeTextureClass; - -#define NO_EVAL_TILING_MODES - -public: -#ifdef EVAL_TILING_MODES - enum {TILE_4x4, TILE_6x6, TILE_8x8} m_tileMode; -#endif - enum { - NORMAL_DRAW_WIDTH = 129, - NORMAL_DRAW_HEIGHT = 129, - STRETCH_DRAW_WIDTH = 65, - STRETCH_DRAW_HEIGHT = 65 - }; - -protected: - Int m_width; ///< Height map width. - Int m_height; ///< Height map height (y size of array). - Int m_borderSize; ///< Non-playable border area. - VecICoord2D m_boundaries; ///< the in-game boundaries - Int m_dataSize; ///< size of m_data. - UnsignedByte *m_data; ///< array of z(height) values in the height map. - - UnsignedByte *m_seismicUpdateFlag; ///< array of bits to prevent ovelapping physics-update regions from doubling effects on shared cells - UnsignedInt m_seismicUpdateWidth; ///< width of the array holding SeismicUpdateFlags - Real *m_seismicZVelocities; ///< how fast is the dirt rising/falling at this location - - UnsignedByte *m_cellFlipState; ///< array of bits to indicate the flip state of each cell. - Int m_flipStateWidth; ///< with of the array holding cellFlipState - UnsignedByte *m_cellCliffState; ///< array of bits to indicate the cliff state of each cell. - - - /// Texture indices. - Short *m_tileNdxes; ///< matches m_Data, indexes into m_SourceTiles. - Short *m_blendTileNdxes; ///< matches m_Data, indexes into m_blendedTiles. 0 means no blend info. - Short *m_cliffInfoNdxes; ///< matches m_Data, indexes into m_cliffInfo. 0 means no cliff info. - Short *m_extraBlendTileNdxes; ///< matches m_Data, indexes into m_extraBlendedTiles. 0 means no blend info. - - - Int m_numBitmapTiles; // Number of tiles initialized from bitmaps in m_SourceTiles. - Int m_numEdgeTiles; // Number of tiles initialized from bitmaps in m_SourceTiles. - Int m_numBlendedTiles; // Number of blended tiles created from bitmap tiles. - - TileData *m_sourceTiles[NUM_SOURCE_TILES]; ///< Tiles for m_textureClasses - TileData *m_edgeTiles[NUM_SOURCE_TILES]; ///< Tiles for m_textureClasses - - TBlendTileInfo m_blendedTiles[NUM_BLEND_TILES]; - TBlendTileInfo m_extraBlendedTiles[NUM_BLEND_TILES]; - - TCliffInfo m_cliffInfo[NUM_CLIFF_INFO]; - Int m_numCliffInfo; ///< Number of cliffInfo's used in m_cliffInfo. - - // Texture classes. There is one texture class for each bitmap read in. - // A class may have more than one tile. For example, if the grass bitmap is - // 128x128, it creates 4 64x64 tiles, so the grass texture class will have 4 tiles. - int m_numTextureClasses; - TXTextureClass m_textureClasses[NUM_TEXTURE_CLASSES]; - - // Edge Texture classes. There is one texture class for each bitmap read in. - // An edge class will normally have 4 tiles. - int m_numEdgeTextureClasses; - TXTextureClass m_edgeTextureClasses[NUM_TEXTURE_CLASSES]; - - /** The actual texture used to render the 3d mesh. Note that it is - basically m_SourceTiles laid out in rows, so by itself it is not useful. - Use GetUVData to get the mapping info for height cells to map into the - texture. */ - TerrainTextureClass *m_terrainTex; - Int m_terrainTexHeight; /// Height of m_terrainTex allocated. - /** The texture that contains the alpha edge tiles that get blended on - top of the base texture. getAlphaUVData does the mapping. */ - AlphaTerrainTextureClass *m_alphaTerrainTex; - Int m_alphaTexHeight; /// Height of m_alphaTerrainTex allocated. - - /** The texture that contains custom blend edge tiles. */ - AlphaEdgeTextureClass *m_alphaEdgeTex; - Int m_alphaEdgeHeight; /// Height of m_alphaEdgeTex allocated. - - /// Drawing info - re the part of the map that is being drawn. - Int m_drawOriginX; - Int m_drawOriginY; - Int m_drawWidthX; - Int m_drawHeightY; - - /// Tiles that hold the alpha channel info. - static TileData *m_alphaTiles[NUM_ALPHA_TILES]; - - -protected: - TileData *getSourceTile(UnsignedInt ndx) { if (ndxm_width) m_drawWidthX = m_width;} - void setDrawHeight(Int height) {m_drawHeightY = height; if (m_drawHeightY>m_height) m_drawHeightY = m_height;} - virtual Int getBorderSize(void) {return m_borderSize;} - Int getBorderSizeInline(void) const { return m_borderSize; } - /// Get height with the offset that HeightMapRenderObjClass uses built in. - UnsignedByte getDisplayHeight(Int x, Int y) { return m_data[x+m_drawOriginX+m_width*(y+m_drawOriginY)];} - - /// Get height in normal coordinates. - UnsignedByte getHeight(Int xIndex, Int yIndex) - { - Int ndx = (yIndex*m_width)+xIndex; - if ((ndx>=0) && (ndx> 3)] & (1<<(xIndex&0x7)); - } - - void setFlipState(Int xIndex, Int yIndex, Bool value); - void clearFlipStates(void); - Bool getCliffState(Int xIndex, Int yIndex) const; - Bool getExtraAlphaUVData(Int xIndex, Int yIndex, float U[4], float V[4], UnsignedByte alpha[4], Bool *flip, Bool *cliff); - /// UV mapping data for a cell to map into the alpha terrain texture. - void getAlphaUVData(Int xIndex, Int yIndex, float U[4], float V[4], UnsignedByte alpha[4], Bool *flip, Bool fullTile); - void getTerrainColorAt(Real x, Real y, RGBColor *pColor); - AsciiString getTerrainNameAt(Real x, Real y); - Bool isCliffMappedTexture(Int xIndex, Int yIndex); - - - Bool getSeismicUpdateFlag(Int xIndex, Int yIndex) const; - void setSeismicUpdateFlag(Int xIndex, Int yIndex, Bool value); - void clearSeismicUpdateFlags(void) ; - virtual Real getSeismicZVelocity(Int xIndex, Int yIndex) const; - virtual void setSeismicZVelocity(Int xIndex, Int yIndex, Real value); - void fillSeismicZVelocities( Real value ); - virtual Real getBilinearSampleSeismicZVelocity( Int x, Int y); - - - -public: // Flat tile texture info. - TerrainTextureClass *getFlatTexture(Int xCell, Int yCell, Int cellWidth, Int pixelsPerCell); //< generates and returns the terrain texture - - static void setupAlphaTiles(void); - UnsignedByte *getPointerToTileData(Int xIndex, Int yIndex, Int width); - Bool getRawTileData(Short tileNdx, Int width, UnsignedByte *buffer, Int bufLen); - UnsignedByte *getRGBAlphaDataForWidth(Int width, TBlendTileInfo *pBlend); - -public: // modify height value - void setRawHeight(Int xIndex, Int yIndex, UnsignedByte height) { - Int ndx = (yIndex*m_width)+xIndex; - if ((ndx>=0) && (ndx. -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: Heightmap.cpp //////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: Heightmap.cpp -// -// Created: Mark W., John Ahlquist, April/May 2001 -// -// Desc: Draw the terrain and scorchmarks in a scene. -// -//----------------------------------------------------------------------------- - -//----------------------------------------------------------------------------- -// Includes -//----------------------------------------------------------------------------- -#include "W3DDevice/GameClient/HeightMap.h" - -#ifndef USE_FLAT_HEIGHT_MAP // Flat height map uses flattened textures. jba. [3/20/2003] - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "Common/GlobalData.h" -#include "Common/PerfTimer.h" - -#include "GameClient/TerrainVisual.h" -#include "GameClient/View.h" -#include "GameClient/Water.h" - -#include "GameLogic/AIPathfind.h" -#include "GameLogic/TerrainLogic.h" -#include "W3DDevice/GameClient/TerrainTex.h" -#include "W3DDevice/GameClient/W3DDynamicLight.h" -#include "W3DDevice/GameClient/W3DScene.h" -#include "W3DDevice/GameClient/W3DTerrainTracks.h" -#include "W3DDevice/GameClient/W3DBibBuffer.h" -#include "W3DDevice/GameClient/W3DTreeBuffer.h" -#include "W3DDevice/GameClient/W3DPropBuffer.h" -#include "W3DDevice/GameClient/W3DRoadBuffer.h" -#include "W3DDevice/GameClient/W3DBridgeBuffer.h" -#include "W3DDevice/GameClient/W3DWaypointBuffer.h" -#include "W3DDevice/GameClient/W3DCustomEdging.h" -#include "W3DDevice/GameClient/WorldHeightMap.h" -#include "W3DDevice/GameClient/W3DShaderManager.h" -#include "W3DDevice/GameClient/W3DShadow.h" -#include "W3DDevice/GameClient/W3DWater.h" -#include "W3DDevice/GameClient/W3DShroud.h" -#include "WW3D2/dx8wrapper.h" -#include "WW3D2/light.h" -#include "WW3D2/scene.h" -#include "W3DDevice/GameClient/W3DPoly.h" -#include "W3DDevice/GameClient/W3DCustomScene.h" - -#include "Common/UnitTimings.h" //Contains the DO_UNIT_TIMINGS define jba. - - -#define no_OPTIMIZED_HEIGHTMAP_LIGHTING 01 -// Doesn't work well. jba. - -const Bool HALF_RES_MESH = false; - -HeightMapRenderObjClass *TheHeightMap = NULL; -//----------------------------------------------------------------------------- -// Private Data -//----------------------------------------------------------------------------- -#define SC_DETAIL_BLEND ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_ENABLE, ShaderClass::COLOR_WRITE_ENABLE, ShaderClass::SRCBLEND_ONE, \ - ShaderClass::DSTBLEND_ZERO, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE, ShaderClass::SECONDARY_GRADIENT_DISABLE, ShaderClass::TEXTURING_ENABLE, \ - ShaderClass::ALPHATEST_DISABLE, ShaderClass::CULL_MODE_ENABLE, ShaderClass::DETAILCOLOR_SCALE, ShaderClass::DETAILALPHA_DISABLE) ) - -static ShaderClass detailOpaqueShader(SC_DETAIL_BLEND); - -#define DEFAULT_MAX_FRAME_EXTRABLEND_TILES 256 //default number of terrain tiles rendered per call (must fit in one VB) -#define DEFAULT_MAX_MAP_EXTRABLEND_TILES 2048 //default size of array allocated to hold all map extra blend tiles. -#define DEFAULT_MAX_BATCH_SHORELINE_TILES 512 //maximum number of terrain tiles rendered per call (must fit in one VB) -#define DEFAULT_MAX_MAP_SHORELINE_TILES 4096 //default size of array allocated to hold all map shoreline tiles. - -#define ADJUST_FROM_INDEX_TO_REAL(k) ((k-m_map->getBorderSizeInline())*MAP_XY_FACTOR) -inline Int IABS(Int x) { if (x>=0) return x; return -x;}; - -//----------------------------------------------------------------------------- -// Private Functions -//----------------------------------------------------------------------------- - -//============================================================================= -// HeightMapRenderObjClass::freeIndexVertexBuffers -//============================================================================= -/** Frees the w3d resources used to draw the terrain. */ -//============================================================================= -void HeightMapRenderObjClass::freeIndexVertexBuffers(void) -{ - REF_PTR_RELEASE(m_indexBuffer); - if (m_vertexBufferTiles) { - for (int i=0; idiffuse; -#ifdef RTS_DEBUG - //vbMirror->diffuse += 30; // Shows which vertexes are geting touched by dynamic light. debug only. -#endif - - // (gth) avoiding the extra divides (compiler unfortunately didn't do this automatically...) - const float oo255 = (1.0f/255.0f); - shadeR = ((diffuse>>16)&0x00FF) * oo255; - shadeG = ((diffuse>>8)&0x00FF) * oo255; - shadeB = (diffuse&0x00FF) * oo255; - - Int alpha = (diffuse>>24)&0x00FF; - Int k; - for (k=0; kisEnabled()) { - continue; // he is turned off. - } - Vector3 lightDirection(vbMirror->x, vbMirror->y, vbMirror->z); - Real factor = 1.0f; - switch(pLight->Get_Type()) { - case LightClass::POINT: - case LightClass::SPOT: { - Vector3 lightLoc = pLight->Get_Position(); - lightDirection -= lightLoc; - double range, midRange; - pLight->Get_Far_Attenuation_Range(midRange, range); - Real dist = lightDirection.Length(); - if (dist >= range) continue; - if (midRange < 0.1) continue; - factor = 1.0f - (dist - midRange) / (range - midRange); - factor = WWMath::Clamp(factor,0.0f,1.0f); - - // (gth) normalize here since we have the length - lightDirection /= dist; - } - break; - case LightClass::DIRECTIONAL: - pLight->Get_Spot_Direction(lightDirection); - factor = 1.0; - break; - }; - - // (gth) unneeded due to above normalization - //lightDirection.Normalize(); - - Vector3 lightRay(-lightDirection.X, -lightDirection.Y, -lightDirection.Z); - Real shade = Vector3::Dot_Product(lightRay, *normal); - shade *= factor; - Vector3 diffuse; - pLight->Get_Diffuse(&diffuse); - Vector3 ambient; - pLight->Get_Ambient(&ambient); - if (shade > 1.0) shade = 1.0; - if(shade < 0.0f) shade = 0.0f; - shadeR += shade*diffuse.X; - shadeG += shade*diffuse.Y; - shadeB += shade*diffuse.Z; - shadeR += factor*ambient.X; - shadeG += factor*ambient.Y; - shadeB += factor*ambient.Z; - - } - if (shadeR > 1.0) shadeR = 1.0; - if(shadeR < 0.0f) shadeR = 0.0f; - if (shadeG > 1.0) shadeG = 1.0; - if(shadeG < 0.0f) shadeG = 0.0f; - if (shadeB > 1.0) shadeB = 1.0; - if(shadeB < 0.0f) shadeB = 0.0f; - shadeR*=255.0f; - shadeG*=255.0f; - shadeB*=255.0f; - -// (gth) faster float to int conversion, return the result so we can re-use it. -// vb->diffuse=REAL_TO_INT(shadeB) | (REAL_TO_INT(shadeG) << 8) | (REAL_TO_INT(shadeR) << 16) | ((int)alpha << 24); - UnsignedInt light_val = WWMath::Float_To_Int_Chop(shadeB) | (WWMath::Float_To_Int_Chop(shadeG) << 8) | (WWMath::Float_To_Int_Chop(shadeR) << 16) | ((int)alpha << 24); - vb->diffuse = light_val; - return light_val; - -#endif -} - -//============================================================================= -// HeightMapRenderObjClass::getXWithOrigin -//============================================================================= -/** Gets the x index that corresponds to the data. For example, if the columns -are shifted by 3, index 3 is actually the first row of polygons, or 0. Yes it -is confusing, but it makes sliding the map 10x faster. */ -//============================================================================= -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 RTS_DEBUG - DEBUG_ASSERTCRASH (x>=0, ("X out of range.")); - DEBUG_ASSERTCRASH (x= m_x-1) x=m_x-1; - return x; -} - -//============================================================================= -// HeightMapRenderObjClass::getYWithOrigin -//============================================================================= -/** Gets the y index that corresponds to the data. For example, if the rows -are shifted by 3, index 3 is actually the first row of polygons, or 0. Yes it -is confusing, but it makes sliding the map 10x faster. */ -//============================================================================= -Int HeightMapRenderObjClass::getYWithOrigin(Int y) -{ - y -= m_originY; - if (y<0) y+= m_y-1; - if (y>= m_y-1) y-=m_y-1; -#ifdef RTS_DEBUG - DEBUG_ASSERTCRASH (y>=0, ("Y out of range.")); - DEBUG_ASSERTCRASH (y= m_y-1) y=m_y-1; - return y; -} - -//============================================================================= -// HeightMapRenderObjClass::updateVB -//============================================================================= -/** Update a rectangular block of the given Vertex Buffer. -data is expected to be an array same dimensions as current heightmap -mapped into this VB. -*/ -//============================================================================= -Int HeightMapRenderObjClass::updateVB(DX8VertexBufferClass *pVB, char *data, Int x0, Int y0, Int x1, Int y1, Int originX, Int originY, WorldHeightMap *pMap, RefRenderObjListIterator *pLightsIterator) -{ - Int i,j; - Vector3 lightRay[MAX_GLOBAL_LIGHTS]; - const Coord3D *lightPos; - Int xCoord, yCoord; - Int vn0,un0,vp1,up1; - Vector3 l2r,n2f,normalAtTexel; - Int vertsPerRow=(VERTEX_BUFFER_TILE_LENGTH)*4; //vertices per row of VB - - Int cellOffset = 1; - if (HALF_RES_MESH) { - cellOffset = 2; - } - - REF_PTR_SET(m_map, pMap); //update our heightmap pointer in case it changed since last call. - if (m_vertexBufferTiles && pMap) - { -#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 - - DX8VertexBufferClass::WriteLockClass lockVtxBuffer(pVB); - VERTEX_FORMAT *vbHardware = (VERTEX_FORMAT*)lockVtxBuffer.Get_Vertex_Array(); - VERTEX_FORMAT *vBase = (VERTEX_FORMAT*)data; - // Note that we are building the vertex buffer data in the memory buffer, data. - // At the bottom, we will copy the final vertex data for one cell into the - // hardware vertex buffer. - - for (j=y0; jgetDrawOrgY()) - vn0=-pMap->getDrawOrgY(); - vp1 = getYWithOrigin(j+cellOffset)+cellOffset; - if (vp1 >= pMap->getYExtent()-pMap->getDrawOrgY()) - vp1=pMap->getYExtent()-pMap->getDrawOrgY()-1; - - yCoord = getYWithOrigin(j)+pMap->getDrawOrgY(); - for (i=x0; igetDrawOrgX()) - un0=-pMap->getDrawOrgX(); - up1 = getXWithOrigin(i+cellOffset)+cellOffset; - if (up1 >= pMap->getXExtent()-pMap->getDrawOrgX()) - up1=pMap->getXExtent()-pMap->getDrawOrgX()-1; - xCoord = getXWithOrigin(i)+pMap->getDrawOrgX(); - - //update the 4 vertices in this block - float U[4], V[4]; - UnsignedByte alpha[4]; - float UA[4], VA[4]; - Bool flipForBlend = false; // True if the blend needs the triangles flipped. - - if (pMap) { - pMap->getUVData(getXWithOrigin(i),getYWithOrigin(j),U, V, HALF_RES_MESH); - pMap->getAlphaUVData(getXWithOrigin(i),getYWithOrigin(j), UA, VA, alpha, &flipForBlend, HALF_RES_MESH); - } - - - for (Int lightIndex=0; lightIndex < TheGlobalData->m_numGlobalLights; lightIndex++) - { - lightPos=&TheGlobalData->m_terrainLightPos[lightIndex]; - lightRay[lightIndex].Set(-lightPos->x,-lightPos->y, -lightPos->z); - } - - //top-left sample - l2r.Set(2*MAP_XY_FACTOR,0,MAP_HEIGHT_SCALE*(pMap->getDisplayHeight(getXWithOrigin(i)+cellOffset, getYWithOrigin(j)) - pMap->getDisplayHeight(un0, getYWithOrigin(j)))); - n2f.Set(0,2*MAP_XY_FACTOR,MAP_HEIGHT_SCALE*(pMap->getDisplayHeight(getXWithOrigin(i), (getYWithOrigin(j)+cellOffset)) - pMap->getDisplayHeight(getXWithOrigin(i), vn0))); - -#ifdef ALLOW_TEMPORARIES - normalAtTexel= Normalize(Vector3::Cross_Product(l2r,n2f)); -#else - Vector3::Normalized_Cross_Product(l2r, n2f, &normalAtTexel); -#endif - - vb->x=xCoord; - vb->y=yCoord; - vb->z= ((float)pMap->getDisplayHeight(getXWithOrigin(i), getYWithOrigin(j)))*MAP_HEIGHT_SCALE; - vb->x = ADJUST_FROM_INDEX_TO_REAL(vb->x); - vb->y = ADJUST_FROM_INDEX_TO_REAL(vb->y); - vb->u1=U[0]; - vb->v1=V[0]; - vb->u2=UA[0]; - vb->v2=VA[0]; - doTheLight(vb, lightRay, &normalAtTexel, pLightsIterator, alpha[0]); - vb++; - - //top-right sample - l2r.Set(2*MAP_XY_FACTOR,0,MAP_HEIGHT_SCALE*(pMap->getDisplayHeight(up1 , getYWithOrigin(j) ) - pMap->getDisplayHeight(getXWithOrigin(i) , getYWithOrigin(j) ))); - n2f.Set(0,2*MAP_XY_FACTOR,MAP_HEIGHT_SCALE*(pMap->getDisplayHeight(getXWithOrigin(i)+cellOffset , (getYWithOrigin(j)+cellOffset) ) - pMap->getDisplayHeight(getXWithOrigin(i)+cellOffset , vn0 ))); - -#ifdef ALLOW_TEMPORARIES - normalAtTexel= Normalize(Vector3::Cross_Product(l2r,n2f)); -#else - Vector3::Normalized_Cross_Product(l2r, n2f, &normalAtTexel); -#endif - - vb->x=xCoord+cellOffset; - vb->y=yCoord; - vb->z= ((float)pMap->getDisplayHeight(getXWithOrigin(i)+cellOffset, getYWithOrigin(j)))*MAP_HEIGHT_SCALE; - vb->x = ADJUST_FROM_INDEX_TO_REAL(vb->x); - vb->y = ADJUST_FROM_INDEX_TO_REAL(vb->y); - vb->u1=U[1]; - vb->v1=V[1]; - vb->u2=UA[1]; - vb->v2=VA[1]; - doTheLight(vb, lightRay, &normalAtTexel, pLightsIterator, alpha[1]); - vb++; - - //bottom-right sample - l2r.Set(2*MAP_XY_FACTOR,0,MAP_HEIGHT_SCALE*(pMap->getDisplayHeight(up1 , (getYWithOrigin(j)+cellOffset) ) - pMap->getDisplayHeight(getXWithOrigin(i) , (getYWithOrigin(j)+cellOffset) ))); - n2f.Set(0,2*MAP_XY_FACTOR,MAP_HEIGHT_SCALE*(pMap->getDisplayHeight(getXWithOrigin(i)+cellOffset , vp1 ) - pMap->getDisplayHeight(getXWithOrigin(i)+cellOffset , getYWithOrigin(j) ))); - -#ifdef ALLOW_TEMPORARIES - normalAtTexel= Normalize(Vector3::Cross_Product(l2r,n2f)); -#else - Vector3::Normalized_Cross_Product(l2r, n2f, &normalAtTexel); -#endif - - vb->x=xCoord+cellOffset; - if (yCoord + 1 == pMap->getDrawOrgY() + m_y - 1) { - vb->y=yCoord+1; - } else { - vb->y=yCoord+cellOffset; - } - vb->z= ((float)pMap->getDisplayHeight(getXWithOrigin(i)+cellOffset, getYWithOrigin(j)+cellOffset))*MAP_HEIGHT_SCALE; - vb->x = ADJUST_FROM_INDEX_TO_REAL(vb->x); - vb->y = ADJUST_FROM_INDEX_TO_REAL(vb->y); - vb->u1=U[2]; - vb->v1=V[2]; - vb->u2=UA[2]; - vb->v2=VA[2]; - doTheLight(vb, lightRay, &normalAtTexel, pLightsIterator, alpha[2]); - vb++; - - //bottom-left sample - l2r.Set(2*MAP_XY_FACTOR,0,MAP_HEIGHT_SCALE*(pMap->getDisplayHeight(getXWithOrigin(i)+cellOffset , (getYWithOrigin(j)+cellOffset) ) - pMap->getDisplayHeight(un0 , (getYWithOrigin(j)+cellOffset) ))); - n2f.Set(0,2*MAP_XY_FACTOR,MAP_HEIGHT_SCALE*(pMap->getDisplayHeight(getXWithOrigin(i) , vp1 ) - pMap->getDisplayHeight(getXWithOrigin(i) , getYWithOrigin(j) ))); - -#ifdef ALLOW_TEMPORARIES - normalAtTexel= Normalize(Vector3::Cross_Product(l2r,n2f)); -#else - Vector3::Normalized_Cross_Product(l2r, n2f, &normalAtTexel); -#endif - - if (xCoord == pMap->getDrawOrgX()) { - vb->x=xCoord; - //if (vb->x < 0) vb->x = 0; - } else { - vb->x=xCoord; - } - if (yCoord + 1 == pMap->getDrawOrgY() + m_y - 1) { - vb->y=yCoord+1; - } else { - vb->y=yCoord+cellOffset; - } - vb->z= ((float)pMap->getDisplayHeight(getXWithOrigin(i), getYWithOrigin(j)+cellOffset))*MAP_HEIGHT_SCALE; - vb->x = ADJUST_FROM_INDEX_TO_REAL(vb->x); - vb->y = ADJUST_FROM_INDEX_TO_REAL(vb->y); - vb->u1=U[3]; - vb->v1=V[3]; - vb->u2=UA[3]; - vb->v2=VA[3]; - doTheLight(vb, lightRay, &normalAtTexel, pLightsIterator, alpha[3]); - vb++; - - VERTEX_FORMAT *pCurVertices = vb-4; -#ifdef FLIP_TRIANGLES // jba - reduces "diamonding" in some cases, not others. Better cliffs, though. - VERTEX_FORMAT tmpVertex; - if (flipForBlend) { - tmpVertex = pCurVertices[0]; - pCurVertices[0] = pCurVertices[1]; - pCurVertices[1] = pCurVertices[2]; - pCurVertices[2] = pCurVertices[3]; - pCurVertices[3] = tmpVertex; - } -#endif - - if (m_showImpassableAreas) { - // Color impassable cells "red" - DEBUG_ASSERTCRASH(PATHFIND_CELL_SIZE_F == MAP_XY_FACTOR, ("Pathfind must be terrain cell size, or this code needs reworking. John A.")); - Real borderHiX = (pMap->getXExtent()-2*pMap->getBorderSizeInline())*MAP_XY_FACTOR; - Real borderHiY = (pMap->getYExtent()-2*pMap->getBorderSizeInline())*MAP_XY_FACTOR; - Bool border = pCurVertices[0].x == -MAP_XY_FACTOR || pCurVertices[0].y == -MAP_XY_FACTOR; - Bool cliffMapped = pMap->isCliffMappedTexture(getXWithOrigin(i), getYWithOrigin(j)); - if (pCurVertices[0].x == borderHiX) { - border = true; - } - if (pCurVertices[0].y == borderHiY) { - border = true; - } - Bool isCliff = pMap->getCliffState(getXWithOrigin(i)+pMap->getDrawOrgX(), getYWithOrigin(j)+pMap->getDrawOrgY()) - || showAsVisibleCliff(getXWithOrigin(i) + pMap->getDrawOrgX(), getYWithOrigin(j)+pMap->getDrawOrgY()); - - if ( isCliff || border || cliffMapped) { - Int cellX, cellY; - for (cellX=0; cellX<2; cellX++) { - for (cellY=0; cellY<2; cellY++) { - Int vertex = cellX+2*cellY; - if (border) { - Bool doBorder = false; - if (pCurVertices[vertex].y >= 0 && pCurVertices[vertex].y <= borderHiY) { - if (pCurVertices[vertex].x == 0 || pCurVertices[vertex].x == borderHiX) { - doBorder = true; - } - } - if (pCurVertices[vertex].x >= 0 && pCurVertices[vertex].x <= borderHiX) { - if (pCurVertices[vertex].y == 0 || pCurVertices[vertex].y == borderHiY) { - doBorder = true; - } - } - if (doBorder) { - pCurVertices[vertex].diffuse &= 0xFF0000ff; // blue with alpha. - } - } else if (isCliff) { - pCurVertices[vertex].diffuse &= 0xFFFF0000; // red with alpha. - } - if (cliffMapped && vertex==0) { - pCurVertices[vertex].diffuse &= 0xFF000000; // Black. - pCurVertices[vertex].diffuse |= 0xff00; // Add green. - } - } - } - } - } - - // Note - We have been building the vertex buffer in the memory location. - // Now copy the set of vertices into the hardware buffer. - // We don't copy the whole vertex buffer because we often update only - // a couple of rows and its a lot faster to just copy the ones that change. - Int offset = pCurVertices - vBase; - memcpy(vbHardware+offset, pCurVertices, 4*sizeof(VERTEX_FORMAT)); - } - } - return 0; //success. - } - return -1; -} - -//============================================================================= -// HeightMapRenderObjClass::updateVBForLight -//============================================================================= -/** Update the dynamic lighting values only in a rectangular block of the given Vertex Buffer. -The vertex locations and texture coords are unchanged. -*/ -Int HeightMapRenderObjClass::updateVBForLight(DX8VertexBufferClass *pVB, char *data, Int x0, Int y0, Int x1, Int y1, Int originX, Int originY, W3DDynamicLight *pLights[], Int numLights) -{ - -#if (OPTIMIZED_HEIGHTMAP_LIGHTING) // (gth) if optimizations are enabled, jump over to the "optimized" version of this function. - return updateVBForLightOptimized( pVB, data, x0, y0, x1, y1, originX, originY, pLights, numLights ); -#endif - - Int i,j,k; - Int vn0,un0,vp1,up1; - Vector3 l2r,n2f,normalAtTexel; - Int vertsPerRow=(VERTEX_BUFFER_TILE_LENGTH)*4; //vertices per row of VB - - if (m_vertexBufferTiles && m_map) - { -#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 - - DX8VertexBufferClass::WriteLockClass lockVtxBuffer(pVB); - VERTEX_FORMAT *vBase = (VERTEX_FORMAT*)lockVtxBuffer.Get_Vertex_Array(); - VERTEX_FORMAT *vb; - - for (j=y0; jgetDrawOrgY()-m_map->getBorderSizeInline(); - Bool intersect = false; - for (k=0; km_minY <= yCoord+1 && - pLights[k]->m_maxY >= yCoord) { - intersect = true; - } - if (pLights[k]->m_prevMinY <= yCoord+1 && - pLights[k]->m_prevMaxY >= yCoord) { - intersect = true; - } - } - if (!intersect) { - continue; - } - vn0 = getYWithOrigin(j)-1; - if (vn0 < -m_map->getDrawOrgY()) - vn0=-m_map->getDrawOrgY(); - vp1 = getYWithOrigin(j+1)+1; - if (vp1 >= m_map->getYExtent()-m_map->getDrawOrgY()) - vp1=m_map->getYExtent()-m_map->getDrawOrgY()-1; - - for (i=x0; igetDrawOrgX()-m_map->getBorderSizeInline(); - Bool intersect = false; - for (k=0; km_minX <= xCoord+1 && - pLights[k]->m_maxX >= xCoord && - pLights[k]->m_minY <= yCoord+1 && - pLights[k]->m_maxY >= yCoord) { - intersect = true; - } - if (pLights[k]->m_prevMinX <= xCoord+1 && - pLights[k]->m_prevMaxX >= xCoord && - pLights[k]->m_prevMinY <= yCoord+1 && - pLights[k]->m_prevMaxY >= yCoord) { - intersect = true; - } - } - if (!intersect) { - continue; - } - // vb is the pointer to the vertex in the hardware dx8 vertex buffer. - Int offset = (j-originY)*vertsPerRow+4*(i-originX); - if (HALF_RES_MESH) { - offset = (j-originY)*vertsPerRow/4+2*(i-originX); - } - vb = vBase + offset; //skip to correct row in vertex buffer - // vbMirror is the pointer to the vertex in our memory based copy. - // The important point is that we can read out of our copy to get the original - // diffuse color, and xyz location. It is VERY SLOW to read out of the - // hardware vertex buffer, possibly worse... jba. - VERTEX_FORMAT *vbMirror = ((VERTEX_FORMAT*)data) + offset; - un0 = getXWithOrigin(i)-1; - if (un0 < -m_map->getDrawOrgX()) - un0=-m_map->getDrawOrgX(); - up1 = getXWithOrigin(i+1)+1; - if (up1 >= m_map->getXExtent()-m_map->getDrawOrgX()) - up1=m_map->getXExtent()-m_map->getDrawOrgX()-1; - - Vector3 lightRay(0,0,0); - - //top-left sample - l2r.Set(2*MAP_XY_FACTOR,0,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(getXWithOrigin(i)+1, getYWithOrigin(j)) - m_map->getDisplayHeight(un0, getYWithOrigin(j)))); - n2f.Set(0,2*MAP_XY_FACTOR,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(getXWithOrigin(i), (getYWithOrigin(j)+1)) - m_map->getDisplayHeight(getXWithOrigin(i), vn0))); - -#ifdef ALLOW_TEMPORARIES - normalAtTexel= Normalize(Vector3::Cross_Product(l2r,n2f)); -#else - Vector3::Normalized_Cross_Product(l2r, n2f, &normalAtTexel); -#endif - - doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, pLights, numLights); - vb++; vbMirror++; - - //top-right sample - l2r.Set(2*MAP_XY_FACTOR,0,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(up1 , getYWithOrigin(j) ) - m_map->getDisplayHeight(getXWithOrigin(i) , getYWithOrigin(j) ))); - n2f.Set(0,2*MAP_XY_FACTOR,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(getXWithOrigin(i)+1 , (getYWithOrigin(j)+1) ) - m_map->getDisplayHeight(getXWithOrigin(i)+1 , vn0 ))); - -#ifdef ALLOW_TEMPORARIES - normalAtTexel= Normalize(Vector3::Cross_Product(l2r,n2f)); -#else - Vector3::Normalized_Cross_Product(l2r, n2f, &normalAtTexel); -#endif - - doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, pLights, numLights); - vb++; vbMirror++; - - //bottom-right sample - l2r.Set(2*MAP_XY_FACTOR,0,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(up1 , (getYWithOrigin(j)+1) ) - m_map->getDisplayHeight(getXWithOrigin(i) , (getYWithOrigin(j)+1) ))); - n2f.Set(0,2*MAP_XY_FACTOR,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(getXWithOrigin(i)+1 , vp1 ) - m_map->getDisplayHeight(getXWithOrigin(i)+1 , getYWithOrigin(j) ))); - -#ifdef ALLOW_TEMPORARIES - normalAtTexel= Normalize(Vector3::Cross_Product(l2r,n2f)); -#else - Vector3::Normalized_Cross_Product(l2r, n2f, &normalAtTexel); -#endif - - doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, pLights, numLights); - vb++; vbMirror++; - - //bottom-left sample - l2r.Set(2*MAP_XY_FACTOR,0,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(getXWithOrigin(i)+1 , (getYWithOrigin(j)+1) ) - m_map->getDisplayHeight(un0 , (getYWithOrigin(j)+1) ))); - n2f.Set(0,2*MAP_XY_FACTOR,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(getXWithOrigin(i) , vp1 ) - m_map->getDisplayHeight(getXWithOrigin(i) , getYWithOrigin(j) ))); - -#ifdef ALLOW_TEMPORARIES - normalAtTexel= Normalize(Vector3::Cross_Product(l2r,n2f)); -#else - Vector3::Normalized_Cross_Product(l2r, n2f, &normalAtTexel); -#endif - - doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, pLights, numLights); - vb++; vbMirror++; - } - } - return 0; //success. - } - return -1; -} - - -Int HeightMapRenderObjClass::updateVBForLightOptimized(DX8VertexBufferClass *pVB, char *data, Int x0, Int y0, Int x1, Int y1, Int originX, Int originY, W3DDynamicLight *pLights[], Int numLights) -{ - Int i,j,k; - Int vn0,un0,vp1,up1; - Vector3 l2r,n2f,normalAtTexel; - Int vertsPerRow=(VERTEX_BUFFER_TILE_LENGTH)*4; //vertices per row of VB - - if (m_vertexBufferTiles && m_map) - { -#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 - - DX8VertexBufferClass::WriteLockClass lockVtxBuffer(pVB); - VERTEX_FORMAT *vBase = (VERTEX_FORMAT*)lockVtxBuffer.Get_Vertex_Array(); - VERTEX_FORMAT *vb; - - // - // (gth) the optimization in this function is to take advantage of verts in the same - // x,y position who have already computed their lighting. To do this, we need to set up - // some offsets in the vertex buffer. I've computed these offsets to be consistent with - // the formula's that Generals is using but in the case of the "half-res-mesh" I'm not - // sure things are correct... - // - Int quad_right_offset; - Int quad_below_offset; - Int quad_below_right_offset; - - if (HALF_RES_MESH == false) { - // offset = (j-originY)*vertsPerRow+4*(i-originX); - quad_right_offset = 4; - quad_below_offset = vertsPerRow; - quad_below_right_offset = vertsPerRow + 4; - - } else { - // offset = (j-originY)*vertsPerRow/4+2*(i-originX); - quad_right_offset = 2; - quad_below_offset = vertsPerRow/4; - quad_below_right_offset = vertsPerRow/4 + 2; - } - - // - // i,j loop over the quads affected by the light. Each quad has its *own* 4 vertices. This - // means that for any vertex position on the map, there are actually 4 copies of the vertex. - // - for (j=y0; jgetDrawOrgY()-m_map->getBorderSizeInline(); - Bool intersect = false; - for (k=0; km_minY <= yCoord+1 && - pLights[k]->m_maxY >= yCoord) { - intersect = true; - } - if (pLights[k]->m_prevMinY <= yCoord+1 && - pLights[k]->m_prevMaxY >= yCoord) { - intersect = true; - } - } - if (!intersect) { - continue; - } - vn0 = getYWithOrigin(j)-1; - if (vn0 < -m_map->getDrawOrgY()) - vn0=-m_map->getDrawOrgY(); - vp1 = getYWithOrigin(j+1)+1; - if (vp1 >= m_map->getYExtent()-m_map->getDrawOrgY()) - vp1=m_map->getYExtent()-m_map->getDrawOrgY()-1; - - for (i=x0; igetDrawOrgX()-m_map->getBorderSizeInline(); - Bool intersect = false; - for (k=0; km_minX <= xCoord+1 && - pLights[k]->m_maxX >= xCoord && - pLights[k]->m_minY <= yCoord+1 && - pLights[k]->m_maxY >= yCoord) { - intersect = true; - } - if (pLights[k]->m_prevMinX <= xCoord+1 && - pLights[k]->m_prevMaxX >= xCoord && - pLights[k]->m_prevMinY <= yCoord+1 && - pLights[k]->m_prevMaxY >= yCoord) { - intersect = true; - } - } - if (!intersect) { - continue; - } - // vb is the pointer to the vertex in the hardware dx8 vertex buffer. - Int offset = (j-originY)*vertsPerRow+4*(i-originX); - if (HALF_RES_MESH) { - offset = (j-originY)*vertsPerRow/4+2*(i-originX); - } - vb = vBase + offset; //skip to correct row in vertex buffer - // vbMirror is the pointer to the vertex in our memory based copy. - // The important point is that we can read out of our copy to get the original - // diffuse color, and xyz location. It is VERY SLOW to read out of the - // hardware vertex buffer, possibly worse... jba. - VERTEX_FORMAT *vbMirror = ((VERTEX_FORMAT*)data) + offset; - VERTEX_FORMAT *vbaseMirror = ((VERTEX_FORMAT*)data); - un0 = getXWithOrigin(i)-1; - if (un0 < -m_map->getDrawOrgX()) - un0=-m_map->getDrawOrgX(); - up1 = getXWithOrigin(i+1)+1; - if (up1 >= m_map->getXExtent()-m_map->getDrawOrgX()) - up1=m_map->getXExtent()-m_map->getDrawOrgX()-1; - - Vector3 lightRay(0,0,0); - - // - // (gth) Following the set of rules below lets us take advantage of lighting values that have - // been previously computed. The idea is to copy them ahead to future quads that will need them - // and then not compute them when we get to those quads. This also avoids having to read-back - // from the vertex buffer but we do jump around in memory... probably bad anyway, maybe we should - // compute into a temporary buffer and copy all at once... - // - unsigned long light_copy; - - // top-left sample -> only compute when i==0 and j==0 - if ((i==x0) && (j==y0)) { - l2r.Set(2*MAP_XY_FACTOR,0,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(getXWithOrigin(i)+1, getYWithOrigin(j)) - m_map->getDisplayHeight(un0, getYWithOrigin(j)))); - n2f.Set(0,2*MAP_XY_FACTOR,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(getXWithOrigin(i), (getYWithOrigin(j)+1)) - m_map->getDisplayHeight(getXWithOrigin(i), vn0))); - Vector3::Normalized_Cross_Product(l2r, n2f, &normalAtTexel); - doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, pLights, numLights); - } - vb++; vbMirror++; - - //top-right sample -> compute when j==0, then copy to (right,0) - if (j==y0) { - l2r.Set(2*MAP_XY_FACTOR,0,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(up1 , getYWithOrigin(j) ) - m_map->getDisplayHeight(getXWithOrigin(i) , getYWithOrigin(j) ))); - n2f.Set(0,2*MAP_XY_FACTOR,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(getXWithOrigin(i)+1 , (getYWithOrigin(j)+1) ) - m_map->getDisplayHeight(getXWithOrigin(i)+1 , vn0 ))); - Vector3::Normalized_Cross_Product(l2r, n2f, &normalAtTexel); - light_copy = doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, pLights, numLights); - - if (i < x1-1) { - // copy light to (right,0) - (vBase + offset + quad_right_offset)->diffuse = (light_copy&0x00FFFFFF) | ((vbaseMirror + offset + quad_right_offset)->diffuse&0xff000000) ; - } - } - vb++; vbMirror++; - - //bottom-right sample -> always compute, then copy to (right,3), (down,1), (down+right,0) - l2r.Set(2*MAP_XY_FACTOR,0,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(up1 , (getYWithOrigin(j)+1) ) - m_map->getDisplayHeight(getXWithOrigin(i) , (getYWithOrigin(j)+1) ))); - n2f.Set(0,2*MAP_XY_FACTOR,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(getXWithOrigin(i)+1 , vp1 ) - m_map->getDisplayHeight(getXWithOrigin(i)+1 , getYWithOrigin(j) ))); - Vector3::Normalized_Cross_Product(l2r, n2f, &normalAtTexel); - light_copy = doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, pLights, numLights); - - if (i < x1-1) { - // copy light to (right,3) - //(vBase + offset + quad_right_offset + 3)->diffuse = light_copy; - (vBase + offset + quad_right_offset + 3)->diffuse = (light_copy&0x00FFFFFF) | ((vbaseMirror + offset + quad_right_offset + 3)->diffuse&0xff000000) ; - } - if (j < y1-1) { - // copy light to (down,1) - //(vBase + offset + quad_below_offset + 1)->diffuse = light_copy; - (vBase + offset + quad_right_offset + 1)->diffuse = (light_copy&0x00FFFFFF) | ((vbaseMirror + offset + quad_right_offset + 1)->diffuse&0xff000000) ; - } - if ((i < x1-1) && (j < y1-1)) { - // copy light to (right+down,0) - //(vBase + offset + quad_below_right_offset)->diffuse = light_copy; - (vBase + offset + quad_right_offset)->diffuse = (light_copy&0x00FFFFFF) | ((vbaseMirror + offset + quad_right_offset)->diffuse&0xff000000) ; - } - vb++; vbMirror++; - - //bottom-left sample -> compute when i==0, otherwise copy from (left,2) - if (i==x0) { - l2r.Set(2*MAP_XY_FACTOR,0,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(getXWithOrigin(i)+1 , (getYWithOrigin(j)+1) ) - m_map->getDisplayHeight(un0 , (getYWithOrigin(j)+1) ))); - n2f.Set(0,2*MAP_XY_FACTOR,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(getXWithOrigin(i) , vp1 ) - m_map->getDisplayHeight(getXWithOrigin(i) , getYWithOrigin(j) ))); - Vector3::Normalized_Cross_Product(l2r, n2f, &normalAtTexel); - light_copy = doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, pLights, numLights); - - if (j < y1-1) { - // copy light to (down,0) - //(vBase + offset + quad_below_offset)->diffuse = light_copy; - (vBase + offset + quad_below_offset)->diffuse = (light_copy&0x00FFFFFF) | ((vbaseMirror + offset + quad_below_offset)->diffuse&0xff000000) ; - } - } - vb++; vbMirror++; - } - } - return 0; //success. - } - return -1; -} - - - -//============================================================================= -// HeightMapRenderObjClass::doPartialUpdate -//============================================================================= -/** Updates a partial block of vertices from [x0,y0 to x1,y1] -The coordinates in partialRange are map cell coordinates, relative to the entire map. -The vertex coordinates and texture coordinates, as well as static lighting are updated. -*/ -void HeightMapRenderObjClass::doPartialUpdate(const IRegion2D &partialRange, WorldHeightMap *htMap, RefRenderObjListIterator *pLightsIterator) -{ - // Adjust range into the current drawn map range. - Int minX = partialRange.lo.x - htMap->getDrawOrgX(); - Int maxX = partialRange.hi.x - htMap->getDrawOrgX(); - Int minY = partialRange.lo.y - htMap->getDrawOrgY(); - Int maxY = partialRange.hi.y - htMap->getDrawOrgY(); - if (minX<0) minX = 0; - if (minY<0) minY = 0; - if (maxX > m_x-1) maxX = m_x-1; - if (maxY > m_y-1) maxY = m_y-1; - if (maxX < minX) return; - if (maxY < minY) return; - if (m_originX == 0 && m_originY == 0) { - // simple case. - updateBlock(minX, minY, maxX, maxY, - htMap, pLightsIterator); - } - else - { - minY = minY+m_originY; - maxY = maxY+m_originY; - - if (minY> m_y-1) { - minY -= m_y-1; - maxY -= m_y-1; - } - if (maxY > m_y-1) { - maxY -= m_y-1; - updateBlock(0, minY, m_x-1, m_y-1, htMap, pLightsIterator); - updateBlock(0, 0, m_x-1, maxY, htMap, pLightsIterator); - } else { - updateBlock(0, minY, m_x-1, maxY, htMap, pLightsIterator); - } - } - - if (!m_extraBlendTilePositions) - { //Need to allocate memory - m_extraBlendTilePositions = NEW Int[DEFAULT_MAX_MAP_EXTRABLEND_TILES]; - m_extraBlendTilePositionsSize = DEFAULT_MAX_MAP_EXTRABLEND_TILES; - } - - //Find list of all extra blend tiles used on map. These are tiles with 3 materials/textures - //over the same tile and require an extra render pass. - - Int i, j; - //First remove any existing extra blend tiles within this partial region - for (j=0; j> 16; - if (x >= partialRange.lo.x && x < partialRange.hi.x && - y >= partialRange.lo.y && y < partialRange.hi.y) - { //this tile is inside region being updated so remove it by shifting tile array - memcpy(m_extraBlendTilePositions+j,m_extraBlendTilePositions+j+1,(m_numExtraBlendTiles-1-j)*sizeof(Int)); - m_numExtraBlendTiles--; - j--; //need to look at index j again because this tile was removed - } - } - - for (j=partialRange.lo.y; jgetExtraAlphaUVData(i,j,U,V,alpha,&flipState, &cliffState)) - { if (m_numExtraBlendTiles >= m_extraBlendTilePositionsSize) - { //no more room to store extra blend tiles so enlarge the buffer. - Int *tempPositions=NEW Int[m_extraBlendTilePositionsSize+512]; - memcpy(tempPositions, m_extraBlendTilePositions, m_extraBlendTilePositionsSize*sizeof(Int)); - delete [] m_extraBlendTilePositions; - //enlarge by more tiles to reduce memory trashing - m_extraBlendTilePositions = tempPositions; - m_extraBlendTilePositionsSize += 512; - } - //Pack x and y position into single integer since maps are limited in size - m_extraBlendTilePositions[m_numExtraBlendTiles]=i | (j <<16); - m_numExtraBlendTiles++; - } - } - updateShorelineTiles(partialRange.lo.x,partialRange.lo.y,partialRange.hi.x,partialRange.hi.y,htMap); - - updateViewImpassableAreas(TRUE, minX, maxX, minY, maxY); -} - -//============================================================================= -// HeightMapRenderObjClass::updateBlock -//============================================================================= -/** Updates a block of vertices from [x0,y0 to x1,y1] -The vertex coordinates and texture coordinates, as well as static lighting are updated. -*/ -Int HeightMapRenderObjClass::updateBlock(Int x0, Int y0, Int x1, Int y1, WorldHeightMap *pMap, RefRenderObjListIterator *pLightsIterator) -{ -#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(x1getTerrainTexture()); - REF_PTR_SET(m_stageOneTexture, pMap->getAlphaTerrainTexture()); - } - - Int i,j; - DX8VertexBufferClass **pVB; - Int originX,originY; - //step through each vertex buffer that needs updating - for (j=0; jyMin) yMin = y0; - yMax = originY+VERTEX_BUFFER_TILE_LENGTH; - if (y1= yMax) { - continue; - } - for (i=0; ix1) xMax = x1; - if (xMin >= xMax) { - continue; - } - pVB=m_vertexBufferTiles+j*m_numVBTilesX+i; //point to correct row/column of vertex buffers - char **pData = m_vertexBufferBackup+j*m_numVBTilesX+i; - updateVB(*pVB, *pData, xMin, yMin, xMax, yMax, originX, originY, pMap, pLightsIterator); - } - } - - return 0; -} - - -//----------------------------------------------------------------------------- -// Public Functions -//----------------------------------------------------------------------------- - -//============================================================================= -// HeightMapRenderObjClass::~HeightMapRenderObjClass -//============================================================================= -/** Destructor. Releases w3d assets. */ -//============================================================================= -HeightMapRenderObjClass::~HeightMapRenderObjClass(void) -{ - freeMapResources(); - - delete [] m_extraBlendTilePositions; - m_extraBlendTilePositions = NULL; -} - -//============================================================================= -// HeightMapRenderObjClass::HeightMapRenderObjClass -//============================================================================= -/** Constructor. Mostly nulls out the member variables. */ -//============================================================================= -HeightMapRenderObjClass::HeightMapRenderObjClass(void): -m_extraBlendTilePositions(NULL), -m_numExtraBlendTiles(0), -m_numVisibleExtraBlendTiles(0), -m_extraBlendTilePositionsSize(0), -m_vertexBufferTiles(NULL), -m_vertexBufferBackup(NULL), -m_originX(0), -m_originY(0), -m_indexBuffer(NULL), -m_numVBTilesX(0), -m_numVBTilesY(0), -m_numVertexBufferTiles(0), -m_numBlockColumnsInLastVB(0), -m_numBlockRowsInLastVB(0) -{ - TheHeightMap = this; -} - - -//============================================================================= -// HeightMapRenderObjClass::adjustTerrainLOD -//============================================================================= -/** Adjust the terrain Level Of Detail. If adj > 0 , increases LOD 1 step, if -adj < 0 decreases it one step, if adj==0, then just sets up for the current LOD */ -//============================================================================= -void HeightMapRenderObjClass::adjustTerrainLOD(Int adj) -{ - BaseHeightMapRenderObjClass::adjustTerrainLOD(adj); - - return; - -#if 0 - if (adj>0 && TheGlobalData->m_terrainLODm_terrainLOD=(TerrainLOD)(TheGlobalData->m_terrainLOD+1); - if (adj<0 && TheGlobalData->m_terrainLOD>TERRAIN_LOD_MIN) TheWritableGlobalData->m_terrainLOD=(TerrainLOD)(TheGlobalData->m_terrainLOD-1); - - switch (TheGlobalData->m_terrainLOD) { - case TERRAIN_LOD_MIN: TheWritableGlobalData->m_useCloudMap = false; - TheWritableGlobalData->m_useLightMap = false ; - TheWritableGlobalData->m_useWaterPlane = false; - TheWritableGlobalData->m_stretchTerrain = false; - TheWritableGlobalData->m_useHalfHeightMap = true; - break; - case TERRAIN_LOD_HALF_CLOUDS: TheWritableGlobalData->m_useCloudMap = true; - TheWritableGlobalData->m_useLightMap = true; - TheWritableGlobalData->m_useWaterPlane = false; - TheWritableGlobalData->m_stretchTerrain = false; - TheWritableGlobalData->m_useHalfHeightMap = true; - break; - case TERRAIN_LOD_STRETCH_NO_CLOUDS: TheWritableGlobalData->m_useCloudMap = false; - TheWritableGlobalData->m_useLightMap = false; - TheWritableGlobalData->m_useWaterPlane = false; - TheWritableGlobalData->m_stretchTerrain = true; - TheWritableGlobalData->m_useHalfHeightMap = false; - break; - case TERRAIN_LOD_STRETCH_CLOUDS: TheWritableGlobalData->m_useCloudMap = true; - TheWritableGlobalData->m_useLightMap = true; - TheWritableGlobalData->m_useWaterPlane = false; - TheWritableGlobalData->m_stretchTerrain = true; - TheWritableGlobalData->m_useHalfHeightMap = false; - break; - case TERRAIN_LOD_NO_CLOUDS: TheWritableGlobalData->m_useCloudMap = false; - TheWritableGlobalData->m_useLightMap = false; - TheWritableGlobalData->m_useWaterPlane = false; - TheWritableGlobalData->m_stretchTerrain = false; - TheWritableGlobalData->m_useHalfHeightMap = false; - break; - default: - case TERRAIN_LOD_NO_WATER: TheWritableGlobalData->m_useCloudMap = true; - TheWritableGlobalData->m_useLightMap = true; - TheWritableGlobalData->m_useWaterPlane = false; - TheWritableGlobalData->m_stretchTerrain = false; - TheWritableGlobalData->m_useHalfHeightMap = false; - break; - case TERRAIN_LOD_MAX: TheWritableGlobalData->m_useCloudMap = true; - TheWritableGlobalData->m_useLightMap = true; - TheWritableGlobalData->m_useWaterPlane = true; - TheWritableGlobalData->m_stretchTerrain = false; - TheWritableGlobalData->m_useHalfHeightMap = false; - break; - } - if (m_map==NULL) return; - m_map->setDrawOrg(m_map->getDrawOrgX(), m_map->getDrawOrgX()); - if (m_shroud) - m_shroud->reset(); //need reset here since initHeightData will load new shroud. - this->initHeightData(m_map->getDrawWidth(), - m_map->getDrawHeight(), m_map, NULL); - staticLightingChanged(); - if (TheTacticalView) { - TheTacticalView->setAngle(TheTacticalView->getAngle() + 1); - TheTacticalView->setAngle(TheTacticalView->getAngle() - 1); - } -#endif -} - -//============================================================================= -// HeightMapRenderObjClass::ReleaseResources -//============================================================================= -/** Releases all w3d assets, to prepare for Reset device call. */ -//============================================================================= -void HeightMapRenderObjClass::ReleaseResources(void) -{ - BaseHeightMapRenderObjClass::ReleaseResources(); -} - -//============================================================================= -// HeightMapRenderObjClass::ReAcquireResources -//============================================================================= -/** Reallocates all W3D assets after a reset.. */ -//============================================================================= -void HeightMapRenderObjClass::ReAcquireResources(void) -{ - BaseHeightMapRenderObjClass::ReAcquireResources(); -} - -//============================================================================= -// HeightMapRenderObjClass::reset -//============================================================================= -/** Updates the macro noise/lightmap texture (pass 3) */ -//============================================================================= -void HeightMapRenderObjClass::reset(void) -{ - BaseHeightMapRenderObjClass::reset(); -} - -//============================================================================= -// HeightMapRenderObjClass::oversizeTerrain -//============================================================================= -/** Sets the terrain oversize amount. */ -//============================================================================= -void HeightMapRenderObjClass::oversizeTerrain(Int tilesToOversize) -{ - Int width = WorldHeightMap::NORMAL_DRAW_WIDTH; - Int height = WorldHeightMap::NORMAL_DRAW_HEIGHT; - if (tilesToOversize>0 && tilesToOversize<5) - { - width += 32*tilesToOversize; - height += 32*tilesToOversize; - if (width>m_map->getXExtent()) - width = m_map->getXExtent(); - if (height>m_map->getYExtent()) - height = m_map->getYExtent(); - } - Int dx = width-m_map->getDrawWidth(); - Int dy = height-m_map->getDrawHeight(); - m_map->setDrawWidth(width); - m_map->setDrawHeight(height); - dx /= 2; - dy /= 2; - Int newOrgX = m_map->getDrawOrgX()-dx; - Int newOrgy = m_map->getDrawOrgY()-dy; - if (newOrgX<0) newOrgX=0; - if (newOrgy<0) newOrgy=0; - m_map->setDrawOrg(newOrgX,newOrgy); - m_originX = 0; - m_originY = 0; - if (m_shroud) - m_shroud->reset(); - //delete m_shroud; - //m_shroud = NULL; - initHeightData(m_map->getDrawWidth(), m_map->getDrawHeight(), m_map, NULL, FALSE); - m_needFullUpdate = true; -} - - - - -//============================================================================= -// HeightMapRenderObjClass::initHeightData -//============================================================================= -/** Allocate a heightmap of x by y vertices and fill with initial height values. -Also allocates all rendering resources such as vertex buffers, index buffers, -shaders, and materials.*/ -//============================================================================= -Int HeightMapRenderObjClass::initHeightData(Int x, Int y, WorldHeightMap *pMap, RefRenderObjListIterator *pLightsIterator, Bool updateExtraPassTiles) -{ - BaseHeightMapRenderObjClass::initHeightData(x, y, pMap, pLightsIterator, updateExtraPassTiles); - Int i,j; -// Int vertsPerRow=x*2-2; -// Int vertsPerColumn=y*2-2; - - HeightSampleType *data = NULL; - if (pMap) { - data = pMap->getDataPtr(); - } - - if (updateExtraPassTiles) - { - m_numExtraBlendTiles = 0; - //Do some preprocessing on map to extract useful data - if (pMap) - { - Int m_mapDX=pMap->getXExtent(); - Int m_mapDY=pMap->getYExtent(); - if (!m_extraBlendTilePositions) - { //Need to allocate memory - m_extraBlendTilePositions = NEW Int[DEFAULT_MAX_MAP_EXTRABLEND_TILES]; - m_extraBlendTilePositionsSize = DEFAULT_MAX_MAP_EXTRABLEND_TILES; - } - - //Find list of all extra blend tiles used on map. These are tiles with 3 materials/textures - //over the same tile and require an extra render pass. - for (j=0; j<(m_mapDY-1); j++) - for (i=0; i<(m_mapDX-1); i++) - { - Real U[4],V[4]; - UnsignedByte alpha[4]; - Bool flipState,cliffState; - if (pMap->getExtraAlphaUVData(i,j,U,V,alpha,&flipState, &cliffState)) - { if (m_numExtraBlendTiles >= m_extraBlendTilePositionsSize) - { //no more room to store extra blend tiles so enlarge the buffer. - Int *tempPositions=NEW Int[m_extraBlendTilePositionsSize+512]; - memcpy(tempPositions, m_extraBlendTilePositions, m_extraBlendTilePositionsSize*sizeof(Int)); - delete [] m_extraBlendTilePositions; - //enlarge by more tiles to reduce memory trashing - m_extraBlendTilePositions = tempPositions; - m_extraBlendTilePositionsSize += 512; - } - //Pack x and y position into single integer since maps are limited in size - m_extraBlendTilePositions[m_numExtraBlendTiles]=i | (j <<16); - m_numExtraBlendTiles++; - } - } - } - } - - m_originX = 0; - m_originY = 0; - m_needFullUpdate = true; - - // If the size changed, we need to allocate. - Bool needToAllocate = (x != m_x || y != m_y); - // If the textures aren't allocated (usually because of a hardware reset) need to allocate. - if (m_stageOneTexture == NULL) { - needToAllocate = true; - } - if (data && needToAllocate && m_treeBuffer != NULL) - { //requested heightmap different from old one. - freeIndexVertexBuffers(); - //Create static index buffers. These will index the vertex buffers holding the map. - m_indexBuffer=NEW_REF(DX8IndexBufferClass,(VERTEX_BUFFER_TILE_LENGTH*VERTEX_BUFFER_TILE_LENGTH*2*3)); - - // Fill up the IB - DX8IndexBufferClass::WriteLockClass lockIdxBuffer(m_indexBuffer); - UnsignedShort *ib=lockIdxBuffer.Get_Index_Array(); - - for (j=0; j<(VERTEX_BUFFER_TILE_LENGTH*VERTEX_BUFFER_TILE_LENGTH*4); j+=VERTEX_BUFFER_TILE_LENGTH*4) - { - for (i=j; i<(j+VERTEX_BUFFER_TILE_LENGTH*4); i+=4) //4 vertices per 2x2 block - { - ib[0]=i; - ib[1]=i+2; - ib[2]=i+3; - - ib[3]=i; - ib[4]=i+1; - ib[5]=i+2; - - ib+=6; //skip the 6 indices we just filled - } - } - - //Get number of vertex buffers needed to hold current map - //First round dimensions to next multiple of VERTEX_BUFFER_TILE_LENGTH since that's our - //blocksize - m_numVBTilesX=1; - for (i=VERTEX_BUFFER_TILE_LENGTH+1; igetDynamicLights()); - if (m_map == NULL) { - return; - } - -#ifdef DO_UNIT_TIMINGS -#pragma MESSAGE("*** WARNING *** DOING DO_UNIT_TIMINGS!!!!") - return; -#endif - -#ifdef EXTENDED_STATS - if (DX8Wrapper::stats.m_disableTerrain) { - return; - } -#endif - - Int numDynaLights=0; - W3DDynamicLight *enabledLights[MAX_ENABLED_DYNAMIC_LIGHTS]; - - Int yCoordMin = m_map->getDrawOrgY(); - Int yCoordMax = m_y+m_map->getDrawOrgY(); - Int xCoordMin = m_map->getDrawOrgX(); - Int xCoordMax = m_x+m_map->getDrawOrgX(); - - for (pDynamicLightsIterator.First(); !pDynamicLightsIterator.Is_Done(); pDynamicLightsIterator.Next()) - { - W3DDynamicLight *pLight = (W3DDynamicLight*)pDynamicLightsIterator.Peek_Obj(); - pLight->m_processMe = false; - if (pLight->m_enabled || pLight->m_priorEnable) { - Real range = pLight->Get_Attenuation_Range(); - if (pLight->m_priorEnable) { - pLight->m_prevMinX = pLight->m_minX; - pLight->m_prevMinY = pLight->m_minY; - pLight->m_prevMaxX = pLight->m_maxX; - pLight->m_prevMaxY = pLight->m_maxY; - } - Vector3 pos = pLight->Get_Position(); - pLight->m_minX = (pos.X-range)/MAP_XY_FACTOR; - pLight->m_maxX = (pos.X+range)/MAP_XY_FACTOR+1.0f; - pLight->m_minY = (pos.Y-range)/MAP_XY_FACTOR; - pLight->m_maxY = (pos.Y+range)/MAP_XY_FACTOR+1.0f; - if (!pLight->m_priorEnable) { - pLight->m_prevMinX = pLight->m_minX; - pLight->m_prevMinY = pLight->m_minY; - pLight->m_prevMaxX = pLight->m_maxX; - pLight->m_prevMaxY = pLight->m_maxY; - } - - if (pLight->m_minX < xCoordMax && - pLight->m_minY < yCoordMax && - pLight->m_maxX > xCoordMin && - pLight->m_maxY > yCoordMin) { - pLight->m_processMe = TRUE; - } else if (pLight->m_prevMinX < xCoordMax && - pLight->m_prevMinY < yCoordMax && - pLight->m_prevMaxX > xCoordMin && - pLight->m_prevMaxY > yCoordMin) { - pLight->m_processMe = TRUE; - } else { - pLight->m_processMe = false; - } - if (pLight->m_processMe) { - enabledLights[numDynaLights] = pLight; - numDynaLights++; - if (numDynaLights == MAX_ENABLED_DYNAMIC_LIGHTS) { - break; - } - } - } - pLight->m_priorEnable = pLight->m_enabled; - } - if (numDynaLights > 0) { - //step through each vertex buffer that needs updating - for (j=0; jgetDrawOrgY()-m_map->getBorderSizeInline(); - Int yCoordMax = getYWithOrigin(yMax-1)+m_map->getDrawOrgY()+1-m_map->getBorderSizeInline(); - if (yCoordMax>yCoordMin) { - // no wrap occurred. - for (k=0; km_minY < yCoordMax && - enabledLights[k]->m_maxY > yCoordMin) { - intersect = true; - break; - } - if (enabledLights[k]->m_prevMinY < yCoordMax && - enabledLights[k]->m_prevMaxY > yCoordMin) { - intersect = true; - break; - } - } - } else { - // wrap occurred, so we are outside of this range. - int tmp=yCoordMin; - yCoordMin = yCoordMax; - yCoordMax = tmp; - for (k=0; km_minY <= yCoordMin || - enabledLights[k]->m_maxY >= yCoordMax) { - intersect = true; - break; - } - if (enabledLights[k]->m_prevMinY <= yCoordMin || - enabledLights[k]->m_prevMaxY >= yCoordMax) { - intersect = true; - break; - } - } - } - if (!intersect) { - continue; - } - - for (i=0; igetDrawOrgX()-m_map->getBorderSizeInline(); - Int xCoordMax = getXWithOrigin(xMax-1)+m_map->getDrawOrgX()+1-m_map->getBorderSizeInline(); - if (xCoordMax>xCoordMin) { - // no wrap occurred. - for (k=0; km_minX < xCoordMax && - enabledLights[k]->m_maxX > xCoordMin) { - intersect = true; - break; - } - if (enabledLights[k]->m_prevMinX < xCoordMax && - enabledLights[k]->m_prevMaxX > xCoordMin) { - intersect = true; - break; - } - } - } else { - // wrap occurred, so we are outside of this range. - int tmp=xCoordMin; - xCoordMin = xCoordMax; - xCoordMax = tmp; - for (k=0; km_minX <= xCoordMin || - enabledLights[k]->m_maxX >= xCoordMax) { - intersect = true; - break; - } - if (enabledLights[k]->m_prevMinX <= xCoordMin || - enabledLights[k]->m_prevMaxX >= xCoordMax) { - intersect = true; - break; - } - } - } - if (!intersect) { - continue; - } - pVB=m_vertexBufferTiles+j*m_numVBTilesX+i; //point to correct row/column of vertex buffers - char **pData = m_vertexBufferBackup+j*m_numVBTilesX+i; - updateVBForLight(*pVB, *pData, xMin, yMin, xMax, yMax, originX,originY, enabledLights, numDynaLights); - } - } - } -} - -//============================================================================= -// HeightMapRenderObjClass::staticLightingChanged -//============================================================================= -/** Notification that all lighting needs to be recalculated. */ -//============================================================================= -void HeightMapRenderObjClass::staticLightingChanged( void ) -{ - BaseHeightMapRenderObjClass::staticLightingChanged(); -} - -#define CENTER_LIMIT 2 -#define BIG_JUMP 16 -#define WIDE_STEP 32 - -static Int visMinX, visMinY, visMaxX, visMaxY; -static Bool check(const FrustumClass & frustum, WorldHeightMap *pMap, Int x, Int y) -{ - if (x<0 || y<0) return(false); - if (x>= pMap->getXExtent() || y>= pMap->getYExtent()) return(false); - if (x >= visMinX && y >= visMinY && x <=visMaxX && y <= visMaxY) { - return(true); - } - Int height = pMap->getHeight(x, y); - Vector3 loc((x-pMap->getBorderSizeInline())*MAP_XY_FACTOR, (y-pMap->getBorderSizeInline())*MAP_XY_FACTOR, height*MAP_HEIGHT_SCALE); - if (CollisionMath::Overlap_Test(frustum,loc) == CollisionMath::INSIDE) { - if (xvisMaxX) visMaxX=x; - if (yvisMaxY) visMaxY=y; - return(true); - } - return(false); -} - -static void calcVis(const FrustumClass & frustum, WorldHeightMap *pMap, Int minX, Int minY, Int maxX, Int maxY, Int limit) -{ - if (maxX-minX<2) return; - if (maxY-minY<2) return; - if (minX >=visMinX && minY >= visMinY && maxX <=visMaxX && maxY <= visMaxY) { - return; - } - Int midX = (minX+maxX)/2; - Int midY = (minY+maxY)/2; - Bool recurse1 = maxX-minX>=limit; - Bool recurse2 = recurse1; - Bool recurse3 = recurse1; - Bool recurse4 = recurse1; - /* boxes are: - - 1 2 - - - 3 4 */ - - if (check(frustum, pMap, midX, maxY)) { - recurse1=true; - recurse2=true; - } - if (check(frustum, pMap, midX, minY)) { - recurse3=true; - recurse4=true; - } - if (check(frustum, pMap, midX, midY)) { - recurse1=true; - recurse2=true; - recurse3=true; - recurse4=true; - } - if (check(frustum, pMap, minX, midY)) { - recurse1=true; - recurse3=true; - } - if (check(frustum, pMap, maxX, midY)) { - recurse2=true; - recurse4=true; - } - if (recurse1) { - calcVis(frustum, pMap, minX, midY, midX, maxY, limit); - } - if (recurse2) { - calcVis(frustum, pMap, midX, midY, maxX, maxY, limit); - } - if (recurse3) { - calcVis(frustum, pMap, minX, minY, midX, midY, limit); - } - if (recurse4) { - calcVis(frustum, pMap, midX, minY, maxX, midY, limit); - } -} - - - - - -//============================================================================= -// HeightMapRenderObjClass::updateCenter -//============================================================================= -/** Updates the positioning of the drawn portion of the height map in the -heightmap. As the view slides around, this determines what is the actually -rendered portion of the terrain. Only a 96x96 section is rendered at any time, -even though maps can be up to 1024x1024. This function determines which subset -is rendered. */ -//============================================================================= -void HeightMapRenderObjClass::updateCenter(CameraClass *camera , RefRenderObjListIterator *pLightsIterator) -{ - if (m_map==NULL) { - return; - } - if (m_updating) { - return; - } - if (m_vertexBufferTiles ==NULL) - return; //did not initialize resources yet. - - BaseHeightMapRenderObjClass::updateCenter(camera, pLightsIterator); - - m_updating = true; - if (m_needFullUpdate) - { - m_needFullUpdate = false; - updateBlock(0, 0, m_x-1, m_y-1, m_map, pLightsIterator); - m_updating = false; - return; - } - - if (m_x >= m_map->getXExtent() && m_y >= m_map->getYExtent()) - { - m_updating = false; - return; // no need to center. - } - - Int cellOffset = 1; - if (HALF_RES_MESH) { - cellOffset = 2; - } - // determine the ray corresponding to the camera and distance to projection plane - Matrix3D camera_matrix = camera->Get_Transform(); - - Vector3 camera_location = camera->Get_Position(); - - Vector3 rayLocation; - Vector3 rayDirection; - Vector3 rayDirectionPt; - // the projected ray has the same origin as the camera - rayLocation = camera_location; - // determine the location of the screen coordinate in camera-model space - const ViewportClass &viewport = camera->Get_Viewport(); - Int i, j, minHt; - - Real intersectionZ; - minHt = m_map->getMaxHeightValue(); - for (i=0; igetDisplayHeight(i,j); - if (curGet_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 minX = 200000; - float maxX = -minX; - float minY = 200000; - float maxY = -minY; - for (i=0; i<2; i++) { - for (j=0; j<2; j++) { - float xmod = (-i + 0.5 + viewport.Min.X) * zmod * xscale;// / aspect; - float ymod = (j - 0.5 - viewport.Min.Y) * zmod * yscale;// * aspect; - - // 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(); - rayDirectionPt = rayLocation+rayDirection; - - x = Vector3::Find_X_At_Z(intersectionZ, rayLocation, rayDirectionPt); - y = Vector3::Find_Y_At_Z(intersectionZ, rayLocation, rayDirectionPt); - if (xmaxX) maxX = x; - if (ymaxY) maxY = y; - } - } - - // convert back to cell indexes. - minX /= MAP_XY_FACTOR; - maxX /= MAP_XY_FACTOR; - minY /= MAP_XY_FACTOR; - maxY /= MAP_XY_FACTOR; - - minX += m_map->getBorderSizeInline(); - maxX += m_map->getBorderSizeInline(); - minY += m_map->getBorderSizeInline(); - maxY += m_map->getBorderSizeInline(); - - visMinX = m_map->getXExtent(); - visMinY = m_map->getYExtent(); - visMaxX = 0; - visMaxY = 0; - - ///< @todo find out why values go out of range - if (minX<0) minX=0; - if (minY<0) minY=0; - if (maxX > visMinX) maxX = visMinX; - if (maxY > visMinY) maxY = visMinY; - - const FrustumClass & frustum = camera->Get_Frustum(); - Int limit = (maxX-minX)/2; - if (limit > WIDE_STEP/2) { - limit=WIDE_STEP/2; - } - calcVis(frustum, m_map, minX-WIDE_STEP/2, minY-WIDE_STEP/2, maxX+WIDE_STEP/2, maxY+WIDE_STEP/2, limit); - - if (m_map) { - Int newOrgX; - if (visMaxX-visMinX > m_x) { - newOrgX = (maxX+minX)/2-m_x/2.0; - } else { - newOrgX = (visMaxX+visMinX)/2-m_x/2.0; - } - - Int newOrgY; - if (visMaxY - visMinY > m_y) { - newOrgY = visMinY+1; - } else { - newOrgY = (visMaxY+visMinY)/2-m_y/2.0; - } - if (TheTacticalView->getFieldOfView() != 0) { - newOrgX = (visMaxX+visMinX)/2-m_x/2.0; - newOrgY = (visMaxY+visMinY)/2-m_y/2.0; - } - if (HALF_RES_MESH) { - newOrgX &= 0xFFFFFFFE; - newOrgY &= 0xFFFFFFFE; - } - Int deltaX = newOrgX - m_map->getDrawOrgX(); - Int deltaY = newOrgY - m_map->getDrawOrgY(); - if (IABS(deltaX) > m_x/2 || IABS(deltaY)>m_x/2) { - m_map->setDrawOrg(newOrgX, newOrgY); - m_originY = 0; - m_originX = 0; - updateBlock(0, 0, m_x-1, m_y-1, m_map, pLightsIterator); - m_updating = false; - return; - } - - if (abs(deltaX)>CENTER_LIMIT || abs(deltaY)>CENTER_LIMIT) { - if (abs(deltaY) >= CENTER_LIMIT) { - if (m_map->setDrawOrg(m_map->getDrawOrgX(), newOrgY)) { - Int minY = 0; - Int maxY = 0; - deltaY -= newOrgY - m_map->getDrawOrgY(); - m_originY += deltaY; - if (m_originY >= m_y-1) m_originY -= m_y-1; - if (deltaY<0) { - minY = m_originY; - maxY = m_originY-deltaY; - } else { - minY = m_originY - deltaY; - maxY = m_originY; - } - minY-=cellOffset; - if (m_originY < 0) m_originY += m_y-1; - if (minY<0) { - minY += m_y-1; - if (minY<0) minY = 0; - updateBlock(0, minY, m_x-1, m_y-1, m_map, pLightsIterator); - updateBlock(0, 0, m_x-1, maxY, m_map, pLightsIterator); - } else { - updateBlock(0, minY, m_x-1, maxY, m_map, pLightsIterator); - } - } - // It is much more efficient to update a cople of columns one frame, and then - // a couple of rows. So if we aren't "jumping" to a new view, and have done X - // recently, return. - if (abs(deltaX) < BIG_JUMP && !m_doXNextTime) { - m_updating = false; - m_doXNextTime = true; - return; // Only do the y this frame. Do x next frame. jba. - } - } - if (abs(deltaX) > CENTER_LIMIT) { - m_doXNextTime = false; - newOrgX = m_map->getDrawOrgX() + deltaX; - if (m_map->setDrawOrg(newOrgX, m_map->getDrawOrgY())) { - Int minX = 0; - Int maxX = 0; - deltaX -= newOrgX - m_map->getDrawOrgX(); - m_originX += deltaX; - if (m_originX >= m_x-1) m_originX -= m_x-1; - if (deltaX<0) { - minX = m_originX; - maxX = m_originX-deltaX; - } else { - minX = m_originX - deltaX; - maxX = m_originX; - } - minX-=cellOffset; - maxX+=cellOffset; - if (m_originX < 0) m_originX += m_x-1; - if (minX<0) { - minX += m_x-1; - if (minX<0) minX = 0; - updateBlock(minX,0,m_x-1, m_y-1, m_map, pLightsIterator); - updateBlock(0,0,maxX, m_y-1, m_map, pLightsIterator); - } else { - updateBlock(minX,0,maxX, m_y-1, m_map, pLightsIterator); - } - } - } - } - } - m_updating = false; -} - -//============================================================================= -// HeightMapRenderObjClass::Render -//============================================================================= -/** Renders (draws) the terrain. */ -//============================================================================= -//DECLARE_PERF_TIMER(Terrain_Render) - -void HeightMapRenderObjClass::Render(RenderInfoClass & rinfo) -{ - //USE_PERF_TIMER(Terrain_Render) - - Int i,j,devicePasses; - W3DShaderManager::ShaderTypes st; - const Bool doCloud = useCloud(); - - if (doCloud) - { - // TheSuperHackers @tweak Updates the cloud movement before applying it to the world. - // Is now decoupled from logic step. - W3DShaderManager::updateCloud(); - } - - Matrix3D tm(Transform); -#if 0 // There is some weirdness sometimes with the dx8 static buffers. - // This usually fixes terrain flashing. jba. - static Int delay = 1; - delay --; - if (delay<1) { - delay = 1; - static Int ndx = -1; - ndx++; - if (ndx>=m_numVertexBufferTiles) { - ndx = 0; - } - DX8VertexBufferClass::WriteLockClass lockVtxBuffer(m_vertexBufferTiles[ndx]); - VERTEX_FORMAT *vb = (VERTEX_FORMAT*)lockVtxBuffer.Get_Vertex_Array(); - vb = 0; - } -#endif - // If there are trees, tell them to draw at the transparent time to draw. - if (m_treeBuffer) { - m_treeBuffer->setIsTerrain(); - } - - -#ifdef DO_UNIT_TIMINGS -#pragma MESSAGE("*** WARNING *** DOING DO_UNIT_TIMINGS!!!!") - return; -#endif - -#ifdef EXTENDED_STATS - if (DX8Wrapper::stats.m_disableTerrain) { - return; - } -#endif - - DX8Wrapper::Set_Light_Environment(rinfo.light_environment); - - // Force shaders to update. - m_stageTwoTexture->restore(); - DX8Wrapper::Set_Texture(0,NULL); - DX8Wrapper::Set_Texture(1,NULL); - ShaderClass::Invalidate(); - - // tm.Scale(ObjSpaceExtent); - DX8Wrapper::Set_Transform(D3DTS_WORLD,tm); - - //Apply the shader and material - - DX8Wrapper::Set_Index_Buffer(m_indexBuffer,0); - - Bool doMultiPassWireFrame=FALSE; - - if (((RTS3DScene *)rinfo.Camera.Get_User_Data())->getCustomPassMode() == SCENE_PASS_ALPHA_MASK || - ((SceneClass *)rinfo.Camera.Get_User_Data())->Get_Extra_Pass_Polygon_Mode() == SceneClass::EXTRA_PASS_CLEAR_LINE) - { - if (WW3D::Is_Texturing_Enabled()) - { //first pass where we just fill the z-buffer - - devicePasses=1; //one pass solid, next in wireframe. - doMultiPassWireFrame=TRUE; - - if (rinfo.Additional_Pass_Count()) - { - rinfo.Peek_Additional_Pass(0)->Install_Materials(); - renderTerrainPass(&rinfo.Camera); - rinfo.Peek_Additional_Pass(0)->UnInstall_Materials(); - return; - } - } - else - { //wireframe pass - //Set to vertex diffuse lighting - DX8Wrapper::Set_Material(m_vertexMaterialClass); - //Set shader to non-textured solid color from vertex - DX8Wrapper::Set_Shader(ShaderClass::_PresetOpaqueSolidShader); - devicePasses=1; //one pass solid, next in wireframe. - DX8Wrapper::Apply_Render_State_Changes(); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG2, D3DTA_TFACTOR ); - DX8Wrapper::Set_DX8_Render_State(D3DRS_TEXTUREFACTOR,0xff808080); - doMultiPassWireFrame=TRUE; - renderTerrainPass(&rinfo.Camera); - DX8Wrapper::Set_DX8_Render_State(D3DRS_TEXTUREFACTOR,0xff008000); - return; - } - } - else - { - DX8Wrapper::Set_Material(m_vertexMaterialClass); - DX8Wrapper::Set_Shader(m_shaderClass); - - st=W3DShaderManager::ST_TERRAIN_BASE; //set default shader - - //set correct shader based on current settings - if (!ShaderClass::Is_Backface_Culling_Inverted()) - { //not reflection pass - if (TheGlobalData->m_useLightMap && doCloud) - { st=W3DShaderManager::ST_TERRAIN_BASE_NOISE12; - } - else - if (TheGlobalData->m_useLightMap) - { //lightmap only - st=W3DShaderManager::ST_TERRAIN_BASE_NOISE2; - } - else - if (doCloud) - { //cloudmap only - st=W3DShaderManager::ST_TERRAIN_BASE_NOISE1; - } - } - else - { //reflection pass, just do base texture - st=W3DShaderManager::ST_TERRAIN_BASE; - } - - //Find number of passes required to render current shader - devicePasses=W3DShaderManager::getShaderPasses(st); - - if (m_disableTextures) - devicePasses=1; //force to 1 lighting-only pass - - //Specify all textures that this shader may need. - W3DShaderManager::setTexture(0,m_stageZeroTexture); - W3DShaderManager::setTexture(1,m_stageZeroTexture); - W3DShaderManager::setTexture(2,m_stageTwoTexture); //cloud - W3DShaderManager::setTexture(3,m_stageThreeTexture);//noise - //Disable writes to destination alpha channel (if there is one) - if (DX8Wrapper::getBackBufferFormat() == WW3D_FORMAT_A8R8G8B8) - DX8Wrapper::Set_DX8_Render_State(D3DRS_COLORWRITEENABLE,D3DCOLORWRITEENABLE_BLUE|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_RED); - } - - Int pass; - for (pass=0; passProcessVertices(0, 0, numVertex, m_xformedVertexBuffer[j*m_numVBTilesX+i], 0); - ::OutputDebugString("did process vertex\n"); - } - if (m_xformedVertexBuffer) { - // Note - m_xformedVertexBuffer should only be used for non T&L hardware. jba. - DX8Wrapper::Apply_Render_State_Changes(); - DX8Wrapper::_Get_D3D_Device8()->SetStreamSource( - 0, - m_xformedVertexBuffer[j*m_numVBTilesX+i], - D3DXGetFVFVertexSize(D3DFVF_XYZRHW |D3DFVF_DIFFUSE|D3DFVF_TEX2)); - DX8Wrapper::_Get_D3D_Device8()->SetVertexShader(D3DFVF_XYZRHW |D3DFVF_DIFFUSE|D3DFVF_TEX2); - } -#endif - if (Is_Hidden() == 0) { - DX8Wrapper::Draw_Triangles( 0,numPolys, 0, numVertex); - } - - } - } - - if (!doMultiPassWireFrame) - { - if (pass) //shader was applied at least once? - W3DShaderManager::resetShader(st); - - //Draw feathered shorelines - renderShoreLines(&rinfo.Camera); - - //Do additional pass over any tiles that have 3 textures blended together. - if (TheGlobalData->m_use3WayTerrainBlends) - renderExtraBlendTiles(); - - Int yCoordMin = m_map->getDrawOrgY(); - Int yCoordMax = m_y+m_map->getDrawOrgY()-1; - Int xCoordMin = m_map->getDrawOrgX(); - Int xCoordMax = m_x+m_map->getDrawOrgX()-1; - #ifdef TEST_CUSTOM_EDGING - // Draw edging just before last pass. - DX8Wrapper::Set_Texture(0,NULL); - DX8Wrapper::Set_Texture(1,NULL); - m_stageTwoTexture->restore(); - m_customEdging->drawEdging(m_map, xCoordMin, xCoordMax, yCoordMin, yCoordMax, - m_stageZeroTexture, doCloud?m_stageTwoTexture:NULL, TheGlobalData->m_useLightMap?m_stageThreeTexture:NULL); - #endif - #ifdef DO_ROADS - DX8Wrapper::Set_Texture(0,NULL); - DX8Wrapper::Set_Texture(1,NULL); - m_stageTwoTexture->restore(); - - ShaderClass::Invalidate(); - if (!ShaderClass::Is_Backface_Culling_Inverted()) { - DX8Wrapper::Set_Material(m_vertexMaterialClass); - if (Scene) { - RTS3DScene *pMyScene = (RTS3DScene *)Scene; - RefRenderObjListIterator pDynamicLightsIterator(pMyScene->getDynamicLights()); - m_roadBuffer->drawRoads(&rinfo.Camera, doCloud?m_stageTwoTexture:NULL, TheGlobalData->m_useLightMap?m_stageThreeTexture:NULL, - m_disableTextures,xCoordMin-m_map->getBorderSizeInline(), xCoordMax-m_map->getBorderSizeInline(), yCoordMin-m_map->getBorderSizeInline(), yCoordMax-m_map->getBorderSizeInline(), &pDynamicLightsIterator); - } - } - #endif - if (m_propBuffer) { - m_propBuffer->drawProps(rinfo); - } - #ifdef DO_SCORCH - DX8Wrapper::Set_Texture(0,NULL); - DX8Wrapper::Set_Texture(1,NULL); - m_stageTwoTexture->restore(); - - ShaderClass::Invalidate(); - if (!ShaderClass::Is_Backface_Culling_Inverted()) { - drawScorches(); - } - #endif - DX8Wrapper::Set_Texture(0,NULL); - DX8Wrapper::Set_Texture(1,NULL); - m_stageTwoTexture->restore(); - ShaderClass::Invalidate(); - DX8Wrapper::Apply_Render_State_Changes(); - - m_bridgeBuffer->drawBridges(&rinfo.Camera, m_disableTextures, doCloud?m_stageTwoTexture:NULL); - - if (TheTerrainTracksRenderObjClassSystem) - TheTerrainTracksRenderObjClassSystem->flush(); - - if (m_shroud && rinfo.Additional_Pass_Count()) - { - rinfo.Peek_Additional_Pass(0)->Install_Materials(); - renderTerrainPass(&rinfo.Camera); - rinfo.Peek_Additional_Pass(0)->UnInstall_Materials(); - } - - ShaderClass::Invalidate(); - DX8Wrapper::Apply_Render_State_Changes(); - } - else - m_bridgeBuffer->drawBridges(&rinfo.Camera, m_disableTextures, m_stageTwoTexture); - - if ( m_waypointBuffer ) - m_waypointBuffer->drawWaypoints(rinfo); - - m_bibBuffer->renderBibs(); - - // We do some custom blending, so tell the shader class to reset everything. - DX8Wrapper::Set_Texture(0,NULL); - DX8Wrapper::Set_Texture(1,NULL); - m_stageTwoTexture->restore(); - ShaderClass::Invalidate(); - DX8Wrapper::Set_Material(NULL); - -} - - - -///Performs additional terrain rendering pass, blending in the black shroud texture. -void HeightMapRenderObjClass::renderTerrainPass(CameraClass *pCamera) -{ - DX8Wrapper::Set_Transform(D3DTS_WORLD,Matrix3D(1)); - - //Apply the shader and material - - DX8Wrapper::Set_Index_Buffer(m_indexBuffer,0); - - for (Int j=0; jProcessVertices(0, 0, numVertex, m_xformedVertexBuffer[j*m_numVBTilesX+i], 0); - ::OutputDebugString("did process vertex\n"); - } - if (m_xformedVertexBuffer) { - // Note - m_xformedVertexBuffer should only be used for non T&L hardware. jba. - DX8Wrapper::Apply_Render_State_Changes(); - DX8Wrapper::_Get_D3D_Device8()->SetStreamSource( - 0, - m_xformedVertexBuffer[j*m_numVBTilesX+i], - D3DXGetFVFVertexSize(D3DFVF_XYZRHW |D3DFVF_DIFFUSE|D3DFVF_TEX2)); - DX8Wrapper::_Get_D3D_Device8()->SetVertexShader(D3DFVF_XYZRHW |D3DFVF_DIFFUSE|D3DFVF_TEX2); - } -#endif - if (Is_Hidden() == 0) { - DX8Wrapper::Draw_Triangles( 0,numPolys, 0, numVertex); - } - } -} - -//============================================================================= -// HeightMapRenderObjClass::renderExtraBlendTiles -//============================================================================= -/** Renders an additoinal terrain pass including only those tiles which have more than 2 textures -blended together. Used primarily for corner cases where 3 different textures meet.*/ -void HeightMapRenderObjClass::renderExtraBlendTiles(void) -{ - Int vertexCount = 0; - Int indexCount = 0; - Int xExtent = m_map->getXExtent(); - Int border = m_map->getBorderSizeInline(); - static Int maxBlendTiles = DEFAULT_MAX_FRAME_EXTRABLEND_TILES; - - m_numVisibleExtraBlendTiles = 0; - - if (!m_numExtraBlendTiles) - return; //nothing to draw - - if (maxBlendTiles > 10000) //we can only fit about 10000 tiles into a single VB. - maxBlendTiles = 10000; - - DynamicVBAccessClass vb_access(BUFFER_TYPE_DYNAMIC_DX8,DX8_FVF_XYZNDUV2,maxBlendTiles*4); - DynamicIBAccessClass ib_access(BUFFER_TYPE_DYNAMIC_DX8,maxBlendTiles*6); - { - - DynamicVBAccessClass::WriteLockClass lock(&vb_access); - VertexFormatXYZNDUV2* vb= lock.Get_Formatted_Vertex_Array(); - DynamicIBAccessClass::WriteLockClass lockib(&ib_access); - UnsignedShort *ib=lockib.Get_Index_Array(); - - if (!vb || !ib) return; - - const UnsignedByte* data = m_map->getDataPtr(); - - //Loop over visible terrain and extract all the tiles that need extra blend - Int drawEdgeY=m_map->getDrawOrgY()+m_map->getDrawHeight()-1; - Int drawEdgeX=m_map->getDrawOrgX()+m_map->getDrawWidth()-1; - if (drawEdgeX > (m_map->getXExtent()-1)) - drawEdgeX = m_map->getXExtent()-1; - if (drawEdgeY > (m_map->getYExtent()-1)) - drawEdgeY = m_map->getYExtent()-1; - Int drawStartX=m_map->getDrawOrgX(); - Int drawStartY=m_map->getDrawOrgY(); - - for (Int j=0; j= (maxBlendTiles*4)) - break; //no room in vertex buffer - - Real U[4],V[4]; - UnsignedByte alpha[4]; - Bool flipState,cliffState; - Int x = m_extraBlendTilePositions[j] & 0xffff; - Int y = m_extraBlendTilePositions[j] >> 16; - - if (x >= drawStartX && x < drawEdgeX && - y >= drawStartY && y < drawEdgeY && - m_map->getExtraAlphaUVData(x,y,U,V,alpha,&flipState, &cliffState)) - { //this tile is inside visible region and has 3rd blend layer. - - Int idx = x+y*xExtent; - - Real p0=data[idx]*MAP_HEIGHT_SCALE; - Real p1=data[idx+1]*MAP_HEIGHT_SCALE; - Real p2=data[idx + 1 + xExtent]*MAP_HEIGHT_SCALE; - Real p3=data[idx + xExtent]*MAP_HEIGHT_SCALE; - if (cliffState && abs(p0-p2) > abs(p1-p3)) //cliffs sometimes force a flip - flipState = TRUE; - - vb->x=(x-border)*MAP_XY_FACTOR; - vb->y=(y-border)*MAP_XY_FACTOR; - vb->z=p0; - vb->nx=0; - vb->ny=0; - vb->nz=0; - vb->diffuse=(alpha[0]<<24)|(getStaticDiffuse(x,y) & 0x00ffffff); - vb->u1=U[0]; - vb->v1=V[0]; - vb->u2=0; - vb->v2=0; - vb++; - - vb->x=(x+1-border)*MAP_XY_FACTOR; - vb->y=(y-border)*MAP_XY_FACTOR; - vb->z=p1; - vb->nx=0; - vb->ny=0; - vb->nz=0; - vb->diffuse=(alpha[1]<<24)|(getStaticDiffuse(x+1,y) & 0x00ffffff); - vb->u1=U[1]; - vb->v1=V[1]; - vb->u2=0; - vb->v2=0; - vb++; - - vb->x=(x+1-border)*MAP_XY_FACTOR; - vb->y=(y+1-border)*MAP_XY_FACTOR; - vb->z=p2; - vb->nx=0; - vb->ny=0; - vb->nz=0; - vb->diffuse=(alpha[2]<<24)|(getStaticDiffuse(x+1,y+1) & 0x00ffffff); - vb->u1=U[2]; - vb->v1=V[2]; - vb->u2=0; - vb->v2=0; - vb++; - - vb->x=(x-border)*MAP_XY_FACTOR; - vb->y=(y+1-border)*MAP_XY_FACTOR; - vb->z=p3; - vb->nx=0; - vb->ny=0; - vb->nz=0; - vb->diffuse=(alpha[3]<<24)|(getStaticDiffuse(x,y+1) & 0x00ffffff); - vb->u1=U[3]; - vb->v1=V[3]; - vb->u2=0; - vb->v2=0; - vb++; - - if (flipState) - { - ib[0]=1+vertexCount; - ib[1]=3+vertexCount; - ib[2]=0+vertexCount; - ib[3]=1+vertexCount; - ib[4]=2+vertexCount; - ib[5]=3+vertexCount; - } - else - { - ib[0]=0+vertexCount; - ib[1]=2+vertexCount; - ib[2]=3+vertexCount; - ib[3]=0+vertexCount; - ib[4]=1+vertexCount; - ib[5]=2+vertexCount; - } - ib += 6; - vertexCount +=4; - indexCount +=6; - } - } - } - - if (vertexCount) - { - //Check if we couldn't fit all blend tiles into vertex buffer so we can enlarge it for next frame. - if (vertexCount == (maxBlendTiles*4)) - maxBlendTiles += 16; //enlarge by 16 to reduce trashing. - - ShaderClass::Invalidate(); //invalidate to force shader to reset since we directly changed states - DX8Wrapper::Set_Index_Buffer(ib_access,0); - DX8Wrapper::Set_Vertex_Buffer(vb_access); - VertexMaterialClass *vmat=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_DIFFUSE); - DX8Wrapper::Set_Material(vmat); - REF_PTR_RELEASE(vmat); - ShaderClass shader=ShaderClass::_PresetOpaqueShader; - shader.Set_Depth_Mask(ShaderClass::DEPTH_WRITE_DISABLE); //disable writes to z - DX8Wrapper::Set_Shader(shader); - - if (TheGlobalData->m_use3WayTerrainBlends == 2) - { - shader.Set_Primary_Gradient(ShaderClass::GRADIENT_DISABLE); //disable lighting. - shader.Set_Texturing(ShaderClass::TEXTURING_DISABLE); //disable texturing. - DX8Wrapper::Set_Shader(shader); - DX8Wrapper::Set_Texture(0,NULL); //debug mode which draws terrain tiles in white. - if (Is_Hidden() == 0) { - DX8Wrapper::Draw_Triangles( 0,indexCount/3, 0, vertexCount); //draw a quad, 2 triangles, 4 verts - m_numVisibleExtraBlendTiles += indexCount/6; - } - } - else - { - W3DShaderManager::setTexture(0,m_stageOneTexture); - W3DShaderManager::setTexture(1,m_stageTwoTexture); //cloud - W3DShaderManager::setTexture(2,m_stageThreeTexture); //noise/lightmap - - W3DShaderManager::ShaderTypes st = W3DShaderManager::ST_ROAD_BASE; - - const Bool doCloud = useCloud(); - - if (TheGlobalData->m_useLightMap && doCloud) - { - st = W3DShaderManager::ST_ROAD_BASE_NOISE12; - } - else if (TheGlobalData->m_useLightMap) - { //lightmap only - st = W3DShaderManager::ST_ROAD_BASE_NOISE2; - } - else if (doCloud) - { //cloudmap only - st = W3DShaderManager::ST_ROAD_BASE_NOISE1; - } - - Int devicePasses=W3DShaderManager::getShaderPasses(st); - - for (Int pass=0; pass < devicePasses; pass++) - { - W3DShaderManager::setShader(st, pass); - if (Is_Hidden() == 0) { - DX8Wrapper::Draw_Triangles( 0,indexCount/3, 0, vertexCount); //draw a quad, 2 triangles, 4 verts - m_numVisibleExtraBlendTiles += indexCount/6; - } - } - W3DShaderManager::resetShader(st); - } - } -} -#endif diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp deleted file mode 100644 index 7b3e9ceb36..0000000000 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp +++ /dev/null @@ -1,1142 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public 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: TerrainTex.cpp //////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: TerrainTex.cpp -// -// Created: John Ahlquist, April 2001 -// -// Desc: TextureClass overrides to perform custom texturing for the terrain. -// -//----------------------------------------------------------------------------- - -//----------------------------------------------------------------------------- -// Includes -//----------------------------------------------------------------------------- -#include - -#include "W3DDevice/GameClient/TerrainTex.h" -#include "W3DDevice/GameClient/WorldHeightMap.h" -#include "W3DDevice/GameClient/TileData.h" -#include "Common/GlobalData.h" -#include "WW3D2/dx8wrapper.h" -#include "d3dx8tex.h" - -/****************************************************************************** - TerrainTextureClass -******************************************************************************/ -//----------------------------------------------------------------------------- -// Public Functions -//----------------------------------------------------------------------------- - -//============================================================================= -// TerrainTextureClass::TerrainTextureClass -//============================================================================= -/** Constructor. Calls parent constructor to create a 16 bit per pixel D3D -texture of the desired height and mip level. */ -//============================================================================= -TerrainTextureClass::TerrainTextureClass(int height) : - TextureClass(TEXTURE_WIDTH, height, - WW3D_FORMAT_A1R5G5B5, MIP_LEVELS_3 ) -{ -} - -//============================================================================= -// TerrainTextureClass::TerrainTextureClass -//============================================================================= -/** Constructor. Calls parent constructor to create a 16 bit per pixel D3D -texture of the desired height and mip level. */ -//============================================================================= -TerrainTextureClass::TerrainTextureClass(int height, int width) : - TextureClass(width, height, - WW3D_FORMAT_A1R5G5B5, MIP_LEVELS_ALL ) -{ -} - - -//============================================================================= -// TerrainTextureClass::update -//============================================================================= -/** Sets the tile bitmap data into the texture. The tiles are placed with 4 - pixel borders around them, so that when the tiles are scaled and bilinearly - interpolated, you don't get seams between the tiles. */ -//============================================================================= -int TerrainTextureClass::update(WorldHeightMap *htMap) -{ - // D3DTexture is our texture; - - IDirect3DSurface8 *surface_level; - D3DSURFACE_DESC surface_desc; - D3DLOCKED_RECT locked_rect; - 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(); - return 0; - } - - DX8_ErrorCode(surface_level->LockRect(&locked_rect, NULL, 0)); - - Int tilePixelExtent = TILE_PIXEL_EXTENT; - Int tilesPerRow = surface_desc.Width/(2*TILE_PIXEL_EXTENT+TILE_OFFSET); - tilesPerRow *= 2; -// Int numRows = surface_desc.Height/(tilePixelExtent+TILE_OFFSET); -#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 - if (surface_desc.Format == D3DFMT_A1R5G5B5) { -#if 0 - UnsignedInt cellX, cellY; - for (cellX = 0; cellX < surface_desc.Width; cellX++) { - for (cellY = 0; cellY < surface_desc.Height; cellY++) { - UnsignedByte *pBGR = ((UnsignedByte *)locked_rect.pBits)+(cellY*surface_desc.Width+cellX)*2; - *((Short*)pBGR) = (((255-2*cellY)>>3)<<10) + ((4*cellX)>>4); - } - } -#endif - Int tileNdx; - Int pixelBytes = 2; - for (tileNdx=0; tileNdx < htMap->m_numBitmapTiles; tileNdx++) { - TileData *pTile = htMap->getSourceTile(tileNdx); - if (!pTile) continue; - ICoord2D position = pTile->m_tileLocationInTexture; - if (position.x<=0) continue; // all real tile offsets start at 2. jba. - - Int i,j; - for (j=0; jgetRGBDataForWidth(tilePixelExtent); - pBGR += (tilePixelExtent-1-j)*TILE_BYTES_PER_PIXEL*tilePixelExtent; // invert to match. - Int row = position.y+j; - UnsignedByte *pBGRX = ((UnsignedByte*)locked_rect.pBits) + - (row)*surface_desc.Width*pixelBytes; - - Int column = position.x; - pBGRX += column*pixelBytes; - for (i=0; i>3)<<10) + ((pBGR[1]>>3)<<5) + (pBGR[0]>>3); - pBGRX +=pixelBytes; - pBGR +=TILE_BYTES_PER_PIXEL; - } - } - } - // Now draw the 4 pixel border around each tile class. - Int texClass; - for (texClass=0; texClassm_numTextureClasses; texClass++) { - Int width = htMap->m_textureClasses[texClass].width; - ICoord2D origin = htMap->m_textureClasses[texClass].positionInTexture; - if (origin.x<=0) continue; - width *= TILE_PIXEL_EXTENT; - // Duplicate 4 columns of pixels before and after. - Int j; - for (j=0; jUnlockRect(); - surface_level->Release(); - DX8_ErrorCode(D3DXFilterTexture(Peek_D3D_Texture(), NULL, 0, D3DX_FILTER_BOX)); - if (WW3D::Get_Texture_Reduction()) { - Peek_D3D_Texture()->SetLOD(WW3D::Get_Texture_Reduction()); - } - return(surface_desc.Height); -} - -#if 0 // old version. -//============================================================================= -// TerrainTextureClass::update -//============================================================================= -/** Sets the tile bitmap data into the texture. The tiles are placed with 4 - pixel borders around them, so that when the tiles are scaled and bilinearly - interpolated, you don't get seams between the tiles. */ -//============================================================================= -int TerrainTextureClass::update(WorldHeightMap *htMap) -{ - // D3DTexture is our texture; - - IDirect3DSurface8 *surface_level; - D3DSURFACE_DESC surface_desc; - D3DLOCKED_RECT locked_rect; - DX8_ErrorCode(D3DTexture->GetSurfaceLevel(0, &surface_level)); - DX8_ErrorCode(surface_level->GetDesc(&surface_desc)); - if (surface_desc.Width < TEXTURE_WIDTH) { - surface_level->Release(); - if (surface_desc.Width == 256) { - return update256(htMap); - } - return false; - } - - DX8_ErrorCode(surface_level->LockRect(&locked_rect, NULL, 0)); - - Int tilePixelExtent = TILE_PIXEL_EXTENT; - Int tilesPerRow = surface_desc.Width/(2*TILE_PIXEL_EXTENT+TILE_OFFSET); - tilesPerRow *= 2; - Int numRows = surface_desc.Height/(tilePixelExtent+TILE_OFFSET); -#ifdef RTS_DEBUG - assert(tilesPerRow*numRows >= htMap->m_numBitmapTiles); - assert((Int)surface_desc.Width >= tilePixelExtent*tilesPerRow); -#endif - if (surface_desc.Format == D3DFMT_A1R5G5B5) { - Int cellX, cellY; -#if 0 - for (cellX = 0; cellX < surface_desc.Width; cellX++) { - for (cellY = 0; cellY < surface_desc.Height; cellY++) { - UnsignedByte *pBGR = ((UnsignedByte *)locked_rect.pBits)+(cellY*surface_desc.Width+cellX)*2; - *((Short*)pBGR) = (((255-2*cellY)>>3)<<10) + ((4*cellX)>>4); - } - } -#endif - Int pixelBytes = 2; - for (cellY = 0; cellY < numRows; cellY++) { - for (cellX = 0; cellX < tilesPerRow; cellX++) { - Int tileNdx = cellX/2 + (tilesPerRow/2)*(cellY/2); - tileNdx *=4; - if (cellX&1) tileNdx++; - if (!(cellY&1)) tileNdx += 2; -#define ADD_EXTRA_TILES 1 -#if ADD_EXTRA_TILES // Fills in an extra 2 columns and 1 row of tiles if there is room. - if (!htMap->getSourceTile(tileNdx) && htMap->getSourceTile(tileNdx-4)) { - tileNdx -= 4; - } - if (!htMap->getSourceTile(tileNdx) && htMap->getSourceTile(tileNdx-8)) { - tileNdx -= 8; - } - if (!htMap->getSourceTile(tileNdx) && htMap->getSourceTile(tileNdx-2*tilesPerRow)) { - tileNdx -= 2*tilesPerRow; - } -#endif - if (htMap->getSourceTile(tileNdx)) { - Int i,j; - for (j=0; jgetSourceTile(tileNdx)->getRGBDataForWidth(tilePixelExtent); - pBGR += (tilePixelExtent-1-j)*TILE_BYTES_PER_PIXEL*tilePixelExtent; // invert to match. - Int row = cellY*tilePixelExtent+j; - row += TILE_OFFSET/2; - row += TILE_OFFSET*(cellY/2); - UnsignedByte *pBGRX = ((UnsignedByte*)locked_rect.pBits) + - (row)*surface_desc.Width*pixelBytes; - - Int column = cellX*tilePixelExtent; - column += TILE_OFFSET*(cellX/2); - pBGRX += column*pixelBytes; - pBGRX += (TILE_OFFSET/2)*pixelBytes; - for (i=0; i>3)<<10) + ((pBGR[1]>>3)<<5) + (pBGR[0]>>3); - pBGRX +=pixelBytes; - pBGR +=TILE_BYTES_PER_PIXEL; - } - } - - } - } - - } - - - for (cellY = 0; cellY < numRows; cellY++) { - for (cellX = 0; cellX < tilesPerRow; cellX++) { - // Duplicate 4 rows of pixels before and after. - Int j; - for (j=0; jUnlockRect(); - surface_level->Release(); - DX8_ErrorCode(D3DXFilterTexture(D3DTexture, NULL, 0, D3DX_FILTER_BOX)); - return(surface_desc.Height); -} -#endif - -//============================================================================= -// TerrainTextureClass::setLOD -//============================================================================= -/** Sets the lod of the texture to be loaded into the video card. */ -//============================================================================= -void TerrainTextureClass::setLOD(Int LOD) -{ - if (Peek_D3D_Texture()) Peek_D3D_Texture()->SetLOD(LOD); -} -//============================================================================= -// TerrainTextureClass::update -//============================================================================= -/** Sets the tile bitmap data into the texture. The tiles are placed with 4 - pixel borders around them, so that when the tiles are scaled and bilinearly - interpolated, you don't get seams between the tiles. */ -//============================================================================= -Bool TerrainTextureClass::updateFlat(WorldHeightMap *htMap, Int xCell, Int yCell, Int cellWidth, Int pixelsPerCell) -{ - // D3DTexture is our texture; - - IDirect3DSurface8 *surface_level; - D3DSURFACE_DESC surface_desc; - D3DLOCKED_RECT locked_rect; - DX8_ErrorCode(Peek_D3D_Texture()->GetSurfaceLevel(0, &surface_level)); - DX8_ErrorCode(surface_level->GetDesc(&surface_desc)); - DEBUG_ASSERTCRASH((Int)surface_desc.Width == cellWidth*pixelsPerCell, ("Bitmap too small.")); - DEBUG_ASSERTCRASH((Int)surface_desc.Height == cellWidth*pixelsPerCell, ("Bitmap too small.")); - if (surface_desc.Width != cellWidth*pixelsPerCell) { - return false; - } - - DX8_ErrorCode(surface_level->LockRect(&locked_rect, NULL, 0)); - - - if (surface_desc.Format == D3DFMT_A1R5G5B5) { - - Int pixelBytes = 2; - Int cellX, cellY; -#if 0 - UnsignedInt X, Y; - for (X = 0; X < surface_desc.Width; X++) { - for (Y = 0; Y < surface_desc.Height; Y++) { - UnsignedByte *pBGR = ((UnsignedByte *)locked_rect.pBits)+(Y*surface_desc.Width+X)*pixelBytes; - *((Short*)pBGR) = (((255-2*Y)>>3)<<10) + ((2*X)>>4); - } - } -#endif - for (cellX = 0; cellX < cellWidth; cellX++) { - for (cellY = 0; cellY < cellWidth; cellY++) { - UnsignedByte *pBGRX_data = ((UnsignedByte*)locked_rect.pBits); - UnsignedByte *pBGR = htMap->getPointerToTileData(xCell+cellX, yCell+cellY, pixelsPerCell); - if (pBGR == NULL) continue; // past end of defined terrain. [3/24/2003] - Int k, l; - for (k=pixelsPerCell-1; k>=0; k--) { - UnsignedByte *pBGRX = pBGRX_data + (pixelsPerCell*(cellWidth-cellY-1)+k)*surface_desc.Width*pixelBytes + - cellX*pixelsPerCell*pixelBytes; - for (l=0; l>3)<<10) + ((pBGR[1]>>3)<<5) + (pBGR[0]>>3); - pBGRX +=pixelBytes; - pBGR +=TILE_BYTES_PER_PIXEL; - } - } - } - } - } - - surface_level->UnlockRect(); - surface_level->Release(); - DX8_ErrorCode(D3DXFilterTexture(Peek_D3D_Texture(), NULL, 0, D3DX_FILTER_BOX)); - return(surface_desc.Height); -} - -//============================================================================= -// TerrainTextureClass::Apply -//============================================================================= -/** Sets the texture as the current D3D texture, and does some custom setup -(standard D3D setup, but beyond the scope of W3D). */ -//============================================================================= -void TerrainTextureClass::Apply(unsigned int stage) -{ - // Do the base apply. - TextureClass::Apply(stage); -#if 0 // obsolete [4/1/2003] - if (TheGlobalData && (TheGlobalData->m_bilinearTerrainTex || TheGlobalData->m_trilinearTerrainTex)) { - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MINFILTER, D3DTEXF_LINEAR); - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MAGFILTER, D3DTEXF_LINEAR); - } else { - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MINFILTER, D3DTEXF_POINT); - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MAGFILTER, D3DTEXF_POINT); - } - if (TheGlobalData && TheGlobalData->m_trilinearTerrainTex) { - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MIPFILTER, D3DTEXF_LINEAR); - } else { - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MIPFILTER, D3DTEXF_POINT); - } - // Now setup the texture pipeline. - if (stage==0) { - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); - - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLOROP, D3DTOP_DISABLE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_TEXCOORDINDEX, 0 ); - DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE,false); - - } -#endif -} - -/****************************************************************************** - AlphaTerrainTextureClass -******************************************************************************/ -//----------------------------------------------------------------------------- -// Public Functions -//----------------------------------------------------------------------------- - -//============================================================================= -// AlphaTerrainTextureClass::AlphaTerrainTextureClass -//============================================================================= -/** Constructor. Calls parent constructor to creat a throw away 8x8 texture, -then uses the base texture's D3D texture. This way the base tiles pass, drawn -using TerrainTextureClass shares the same texture with the blended edges pass, -saving lots of texture memory, and preventing seams between blended tiles. */ -//============================================================================= -AlphaTerrainTextureClass::AlphaTerrainTextureClass( TextureClass *pBaseTex ): - TextureClass(8, 8, - WW3D_FORMAT_A1R5G5B5, MIP_LEVELS_1 ) -{ - // Attach the base texture's d3d texture. - IDirect3DTexture8 * d3d_tex = pBaseTex->Peek_D3D_Texture(); - Set_D3D_Base_Texture(d3d_tex); -} - - -//============================================================================= -// AlphaTerrainTextureClass::Apply -//============================================================================= -/** Sets the texture as the current D3D texture, and does some custom setup. -This may be applied in either single pass, as the second texture in the pipe, -or multipass. If stage==0, we are doing multipass and we set up the pipe -for a single texture. If stage==1, then we are doing a single pass, and we -set up the pipe so that we blend onto the base texture in stage 0. -(standard D3D setup, but beyond the scope of W3D). */ -//============================================================================= -void AlphaTerrainTextureClass::Apply(unsigned int stage) -{ - // Do the base apply. - TextureClass::Apply(stage); - - // Set the bilinear or trilinear filtering. - if (TheGlobalData && (TheGlobalData->m_bilinearTerrainTex || TheGlobalData->m_trilinearTerrainTex)) { - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MINFILTER, D3DTEXF_LINEAR); - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MAGFILTER, D3DTEXF_LINEAR); - } else { - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MINFILTER, D3DTEXF_POINT); - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MAGFILTER, D3DTEXF_POINT); - } - if (TheGlobalData && TheGlobalData->m_trilinearTerrainTex) { - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MIPFILTER, D3DTEXF_LINEAR); - } else { - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MIPFILTER, D3DTEXF_POINT); - } - // Since we are using multiple distinct tiles, the textures doesn't wrap, so clamp it. - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP); - // Now setup the texture pipeline. - if (stage==0) { - // Modulate the diffuse color with the texture as lighting comes from diffuse. - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_TEXCOORDINDEX, 1 ); - // Blend the result using the alpha. (came from diffuse mod texture) - DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE,true); - DX8Wrapper::Set_DX8_Render_State(D3DRS_SRCBLEND,D3DBLEND_SRCALPHA); - DX8Wrapper::Set_DX8_Render_State(D3DRS_DESTBLEND,D3DBLEND_INVSRCALPHA); - // Disable stage 2. - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLOROP, D3DTOP_DISABLE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); - } else if (stage==1) { - - if (TheGlobalData && !TheGlobalData->m_multiPassTerrain) - { - ///@todo: Remove 8-Stage Nvidia hack after drivers are fixed. - //This method is a backdoor specific to Nvidia based cards. It will fail on - //other hardware. Allows single pass blend of 2 textures and post modulate diffuse. - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLOROP, D3DTOP_MODULATE); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_TEXCOORDINDEX, 0); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); - - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLOROP, D3DTOP_ADD); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_TEXCOORDINDEX, 1); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLORARG1, D3DTA_DIFFUSE | D3DTA_COMPLEMENT | D3DTA_ALPHAREPLICATE); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLORARG2, D3DTA_DIFFUSE); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAOP, D3DTOP_ADD); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAARG1, D3DTA_TFACTOR | D3DTA_COMPLEMENT); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAARG2, D3DTA_TFACTOR); - - DX8Wrapper::Set_DX8_Texture(2, NULL); - DX8Wrapper::Set_DX8_Texture_Stage_State( 2, D3DTSS_COLOROP, D3DTOP_MODULATE); - DX8Wrapper::Set_DX8_Texture_Stage_State( 2, D3DTSS_TEXCOORDINDEX, 2); - DX8Wrapper::Set_DX8_Texture_Stage_State( 2, D3DTSS_COLORARG1, D3DTA_TEXTURE); - DX8Wrapper::Set_DX8_Texture_Stage_State( 2, D3DTSS_COLORARG2, D3DTA_TEXTURE); - DX8Wrapper::Set_DX8_Texture_Stage_State( 2, D3DTSS_ALPHAOP, D3DTOP_MODULATE); - DX8Wrapper::Set_DX8_Texture_Stage_State( 2, D3DTSS_ALPHAARG1, D3DTA_TFACTOR); - DX8Wrapper::Set_DX8_Texture_Stage_State( 2, D3DTSS_ALPHAARG2, D3DTA_TFACTOR); - - DX8Wrapper::Set_DX8_Texture(3, NULL); - DX8Wrapper::Set_DX8_Texture_Stage_State( 3, D3DTSS_COLOROP, D3DTOP_SELECTARG1); - DX8Wrapper::Set_DX8_Texture_Stage_State( 3, D3DTSS_TEXCOORDINDEX, 3); - DX8Wrapper::Set_DX8_Texture_Stage_State( 3, D3DTSS_COLORARG1, D3DTA_DIFFUSE | 0 | D3DTA_ALPHAREPLICATE); - DX8Wrapper::Set_DX8_Texture_Stage_State( 3, D3DTSS_COLORARG2, D3DTA_DIFFUSE); - DX8Wrapper::Set_DX8_Texture_Stage_State( 3, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1); - DX8Wrapper::Set_DX8_Texture_Stage_State( 3, D3DTSS_ALPHAARG1, D3DTA_TFACTOR); - DX8Wrapper::Set_DX8_Texture_Stage_State( 3, D3DTSS_ALPHAARG2, D3DTA_TFACTOR); - - DX8Wrapper::Set_DX8_Texture(4, NULL); - DX8Wrapper::Set_DX8_Texture_Stage_State( 4, D3DTSS_COLOROP, D3DTOP_MODULATE); - DX8Wrapper::Set_DX8_Texture_Stage_State( 4, D3DTSS_TEXCOORDINDEX, 4); - DX8Wrapper::Set_DX8_Texture_Stage_State( 4, D3DTSS_COLORARG1, D3DTA_CURRENT); - DX8Wrapper::Set_DX8_Texture_Stage_State( 4, D3DTSS_COLORARG2, D3DTA_DIFFUSE); - DX8Wrapper::Set_DX8_Texture_Stage_State( 4, D3DTSS_ALPHAOP, D3DTOP_MODULATE); - DX8Wrapper::Set_DX8_Texture_Stage_State( 4, D3DTSS_ALPHAARG1, D3DTA_CURRENT); - DX8Wrapper::Set_DX8_Texture_Stage_State( 4, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); - - DX8Wrapper::Set_DX8_Texture(5, NULL); - DX8Wrapper::Set_DX8_Texture_Stage_State( 5, D3DTSS_COLOROP, D3DTOP_ADD); - DX8Wrapper::Set_DX8_Texture_Stage_State( 5, D3DTSS_TEXCOORDINDEX, 5); - DX8Wrapper::Set_DX8_Texture_Stage_State( 5, D3DTSS_COLORARG1, D3DTA_DIFFUSE); - DX8Wrapper::Set_DX8_Texture_Stage_State( 5, D3DTSS_COLORARG2, D3DTA_DIFFUSE); - DX8Wrapper::Set_DX8_Texture_Stage_State( 5, D3DTSS_ALPHAOP, D3DTOP_ADD); - DX8Wrapper::Set_DX8_Texture_Stage_State( 5, D3DTSS_ALPHAARG1, D3DTA_TFACTOR | D3DTA_COMPLEMENT); - DX8Wrapper::Set_DX8_Texture_Stage_State( 5, D3DTSS_ALPHAARG2, D3DTA_TFACTOR); - - DX8Wrapper::Set_DX8_Texture(6, NULL); - DX8Wrapper::Set_DX8_Texture_Stage_State( 6, D3DTSS_COLOROP, D3DTOP_MODULATE); - DX8Wrapper::Set_DX8_Texture_Stage_State( 6, D3DTSS_TEXCOORDINDEX, 6); - DX8Wrapper::Set_DX8_Texture_Stage_State( 6, D3DTSS_COLORARG1, D3DTA_TFACTOR); - DX8Wrapper::Set_DX8_Texture_Stage_State( 6, D3DTSS_COLORARG2, D3DTA_TFACTOR); - DX8Wrapper::Set_DX8_Texture_Stage_State( 6, D3DTSS_ALPHAOP, D3DTOP_MODULATE); - DX8Wrapper::Set_DX8_Texture_Stage_State( 6, D3DTSS_ALPHAARG1, D3DTA_TFACTOR); - DX8Wrapper::Set_DX8_Texture_Stage_State( 6, D3DTSS_ALPHAARG2, D3DTA_TFACTOR); - - DX8Wrapper::Set_DX8_Texture(7, NULL); - DX8Wrapper::Set_DX8_Texture_Stage_State( 7, D3DTSS_COLOROP, D3DTOP_SELECTARG1); - DX8Wrapper::Set_DX8_Texture_Stage_State( 7, D3DTSS_TEXCOORDINDEX, 7); - DX8Wrapper::Set_DX8_Texture_Stage_State( 7, D3DTSS_COLORARG1, D3DTA_TFACTOR); - DX8Wrapper::Set_DX8_Texture_Stage_State( 7, D3DTSS_COLORARG2, D3DTA_TFACTOR); - DX8Wrapper::Set_DX8_Texture_Stage_State( 7, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1); - DX8Wrapper::Set_DX8_Texture_Stage_State( 7, D3DTSS_ALPHAARG1, D3DTA_TFACTOR); - DX8Wrapper::Set_DX8_Texture_Stage_State( 7, D3DTSS_ALPHAARG2, D3DTA_TFACTOR); - } - else - { - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 ); - - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLORARG1, D3DTA_TEXTURE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLOROP, D3DTOP_MODULATE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLORARG2, D3DTA_CURRENT ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAARG1, D3DTA_TEXTURE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 ); - } - } -} - - -/****************************************************************************** - LightMapTerrainTextureClass -******************************************************************************/ -//----------------------------------------------------------------------------- -// Public Functions -//----------------------------------------------------------------------------- - -//============================================================================= -// LightMapTerrainTextureClass::LightMapTerrainTextureClass -//============================================================================= -/** Constructor. Calls parent constructor to load the .tga texture. */ -//============================================================================= -LightMapTerrainTextureClass::LightMapTerrainTextureClass(AsciiString name, MipCountType mipLevelCount) : -TextureClass(name.isEmpty()?"TSNoiseUrb.tga":name.str(),name.isEmpty()?"TSNoiseUrb.tga":name.str(), mipLevelCount ) -{ - Get_Filter().Set_Min_Filter(TextureFilterClass::FILTER_TYPE_BEST); - Get_Filter().Set_Mag_Filter(TextureFilterClass::FILTER_TYPE_BEST); - Get_Filter().Set_U_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_REPEAT); - Get_Filter().Set_V_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_REPEAT); -} - -#define STRETCH_FACTOR ((float)(1/(63.0*MAP_XY_FACTOR/2))) /* covers 63/2 tiles */ - -//============================================================================= -// LightMapTerrainTextureClass::Apply -//============================================================================= -/** Sets the texture as the current D3D texture, and does some custom setup. -The LightMapTerrainTextureClass may be applied by itself, or with the -CloudMapTerrainTextureClass. This may be applied in either single pass, -as the second texture in the pipe, -or multipass. If stage==0, we are doing multipass and we set up the pipe -for a single texture. If stage==1, then we are doing a single pass, and we -set up the pipe so that we blend onto the cloud map texture in stage 0. -Also, texture is mapped using the x/y coordinates of the map, saving us -yet another set of uv coordinates. -(standard D3D setup, but beyond the scope of W3D). */ -//============================================================================= -void LightMapTerrainTextureClass::Apply(unsigned int stage) -{ - TextureClass::Apply(stage); -#if 0 // obsolete [4/1/2003] - // Do the base apply. - /* previous setup */ - if (TheGlobalData && TheGlobalData->m_trilinearTerrainTex) { - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MIPFILTER, D3DTEXF_LINEAR); - } else { - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MIPFILTER, D3DTEXF_POINT); - } - - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MINFILTER, D3DTEXF_POINT); - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MAGFILTER, D3DTEXF_LINEAR); - - // Disable 3rd stage just in case. - DX8Wrapper::Set_DX8_Texture_Stage_State( 2, D3DTSS_COLOROP, D3DTOP_DISABLE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 2, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); - - // Now setup the texture pipeline. - DX8Wrapper::Set_DX8_Texture_Stage_State( stage, D3DTSS_COLORARG1, D3DTA_TEXTURE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( stage, D3DTSS_COLORARG2, D3DTA_CURRENT ); - if (stage == 0) { - DX8Wrapper::Set_DX8_Texture_Stage_State( stage, D3DTSS_COLOROP, D3DTOP_SELECTARG1 ); - //Disable second stage - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLOROP, D3DTOP_DISABLE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); - } else { - DX8Wrapper::Set_DX8_Texture_Stage_State( stage, D3DTSS_COLOROP, D3DTOP_MODULATE ); - } - DX8Wrapper::Set_DX8_Texture_Stage_State( stage, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION); - // Two output coordinates are used. - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2); - - - DX8Wrapper::Set_DX8_Texture_Stage_State( stage, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); - DX8Wrapper::Set_DX8_Texture_Stage_State( stage, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); - - Matrix4x4 curView; - DX8Wrapper::_Get_DX8_Transform(D3DTS_VIEW, curView); - - - D3DXMATRIX inv; - float det; - D3DXMatrixInverse(&inv, &det, (D3DXMATRIX*)&curView); - D3DXMATRIX scale; - D3DXMatrixScaling(&scale, STRETCH_FACTOR, STRETCH_FACTOR,1); - inv *=scale; - if (stage==0) { - DX8Wrapper::_Set_DX8_Transform(D3DTS_TEXTURE0, *((Matrix4x4*)&inv)); - } if (stage==1) { - DX8Wrapper::_Set_DX8_Transform(D3DTS_TEXTURE1, *((Matrix4x4*)&inv)); - } - - - if (stage==0) { - DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE,true); - DX8Wrapper::Set_DX8_Render_State(D3DRS_SRCBLEND,D3DBLEND_DESTCOLOR); - DX8Wrapper::Set_DX8_Render_State(D3DRS_DESTBLEND,D3DBLEND_ZERO); - } -#endif -} - - - - - - - - - -/****************************************************************************** - AlphaEdgeTextureClass -******************************************************************************/ -//----------------------------------------------------------------------------- -// Public Functions -//----------------------------------------------------------------------------- - -/** -* AlphaEdgeTextureClass - Generates the alpha edge blending for terrain. -* -*/ -AlphaEdgeTextureClass::AlphaEdgeTextureClass( int height, MipCountType mipLevelCount) : -// TextureClass("EdgingTemplate.tga","EdgingTemplate.tga", mipLevelCount ) - TextureClass(TEXTURE_WIDTH, height, WW3D_FORMAT_A8R8G8B8, mipLevelCount ) -{ - -} - -int AlphaEdgeTextureClass::update256(WorldHeightMap *htMap) -{ - return 1; -} - -int AlphaEdgeTextureClass::update(WorldHeightMap *htMap) -{ - // D3DTexture is our texture; - - IDirect3DSurface8 *surface_level; - D3DSURFACE_DESC surface_desc; - D3DLOCKED_RECT locked_rect; - 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)); - - Int tilePixelExtent = TILE_PIXEL_EXTENT; // blend tiles are 1/4 tiles. -// Int tilesPerRow = surface_desc.Width / (tilePixelExtent+8); - -// Int numRows = surface_desc.Height/(tilePixelExtent+8); - - if (surface_desc.Format == D3DFMT_A8R8G8B8) { -#if 1 -#if 1 - Int cellX, cellY; - for (cellX = 0; (UnsignedInt)cellX < surface_desc.Width; cellX++) { - for (cellY = 0; cellY < surface_desc.Height; cellY++) { - UnsignedByte *pBGR = ((UnsignedByte *)locked_rect.pBits)+(cellY*surface_desc.Width+cellX)*4; - pBGR[2] = 255-cellY/2; - pBGR[0] = cellX/2; - pBGR[3] = cellX/2; // alpha. - pBGR[3] = 128; // alpha. - } - } -#endif -#if 1 - Int tileNdx; - Int pixelBytes = 4; - for (tileNdx=0; tileNdx < htMap->m_numEdgeTiles; tileNdx++) { - TileData *pTile = htMap->getEdgeTile(tileNdx); - if (!pTile) continue; - ICoord2D position = pTile->m_tileLocationInTexture; - if (position.x<=0) continue; // all real edge offsets start at 4. jba. - Int i,j; - Int column = position.x; - for (j=0; jgetEdgeTile(tileNdx)->getRGBDataForWidth(tilePixelExtent); - pBGR += (tilePixelExtent-1-j)*TILE_BYTES_PER_PIXEL*tilePixelExtent; // invert to match. - UnsignedByte *pBGRX = ((UnsignedByte*)locked_rect.pBits) + - (row)*surface_desc.Width*pixelBytes; - pBGRX += column*pixelBytes; - - for (i=0; iUnlockRect(); - surface_level->Release(); - DX8_ErrorCode(D3DXFilterTexture(Peek_D3D_Texture(), NULL, 0, D3DX_FILTER_BOX)); - return(surface_desc.Height); -} - -void AlphaEdgeTextureClass::Apply(unsigned int stage) -{ - // Do the base apply. - TextureClass::Apply(stage); -#if 0 // obsolete [4/1/2003] - - if (TheGlobalData && (TheGlobalData->m_bilinearTerrainTex || TheGlobalData->m_trilinearTerrainTex)) { - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MINFILTER, D3DTEXF_LINEAR); - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MAGFILTER, D3DTEXF_LINEAR); - } else { - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MINFILTER, D3DTEXF_POINT); - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MAGFILTER, D3DTEXF_POINT); - } - if (TheGlobalData && TheGlobalData->m_trilinearTerrainTex) { - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MIPFILTER, D3DTEXF_LINEAR); - } else { - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MIPFILTER, D3DTEXF_POINT); - } - - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP); - // Now setup the texture pipeline. - if (stage==0) { - - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_TEXCOORDINDEX, 1 ); - DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE,true); - DX8Wrapper::Set_DX8_Render_State(D3DRS_SRCBLEND,D3DBLEND_SRCALPHA); - DX8Wrapper::Set_DX8_Render_State(D3DRS_DESTBLEND,D3DBLEND_INVSRCALPHA); - - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLOROP, D3DTOP_DISABLE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); - - } else if (stage==1) { - // Drawing texture through the mask. - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAARG1, D3DTA_CURRENT ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 ); - - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLORARG1, D3DTA_CURRENT ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLORARG2, D3DTA_TEXTURE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLOROP, D3DTOP_SELECTARG1 ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAARG1, D3DTA_CURRENT ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAARG2, D3DTA_TEXTURE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAOP, D3DTOP_SELECTARG2 ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_TEXCOORDINDEX, 1 ); - DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE,true); - DX8Wrapper::Set_DX8_Render_State(D3DRS_SRCBLEND,D3DBLEND_ONE); - DX8Wrapper::Set_DX8_Render_State(D3DRS_DESTBLEND,D3DBLEND_ZERO); - - } -#endif -} - - -/****************************************************************************** - CloudMapTerrainTextureClass -******************************************************************************/ -//----------------------------------------------------------------------------- -// Public Functions -//----------------------------------------------------------------------------- - -//============================================================================= -// CloudMapTerrainTextureClass::CloudMapTerrainTextureClass -//============================================================================= -/** Constructor. Calls parent constructor to load the .tga texture, and sets -up the "sliding" parameters for the clouds to slide over the terrain. */ -//============================================================================= -//@todo - Allow adjustment of the cloud slide rate, and lose the hard coded "cloudmap.tga" -CloudMapTerrainTextureClass::CloudMapTerrainTextureClass(MipCountType mipLevelCount) : - TextureClass("TSCloudMed.tga","TSCloudMed.tga", mipLevelCount ) -{ - Get_Filter().Set_Mip_Mapping( TextureFilterClass::FILTER_TYPE_FAST ); - m_xSlidePerSecond = -0.02f; - m_ySlidePerSecond = 1.50f * m_xSlidePerSecond; - m_curTick = 0; - m_xOffset = 0; - m_yOffset = 0; - -} - -//============================================================================= -// CloudMapTerrainTextureClass::Apply -//============================================================================= -/** Sets the texture as the current D3D texture, and does some custom setup. -The CloudMapTerrainTextureClass may be applied by itself, or with the -LightMapTerrainTexture. This may be applied in either single pass, -as the first texture in the pipe with LightMapTerrainTextureClass as the -second stage of the pape, or multipass. We setup for stage 0, assuming that -we are the only texture, as LightMapTerrainTexture will adjust for multitexture -if it is applied to stage 1. -Also, texture is mapped using the x/y coordinates of the map, saving us -yet another set of uv coordinates. -(standard D3D setup, but beyond the scope of W3D). */ -//============================================================================= -void CloudMapTerrainTextureClass::Apply(unsigned int stage) -{ - - - // Do the base apply. - TextureClass::Apply(stage); -#if 0 // obsolete - /* previous setup */ - if (TheGlobalData && TheGlobalData->m_trilinearTerrainTex) { - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MIPFILTER, D3DTEXF_LINEAR); - } else { - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MIPFILTER, D3DTEXF_POINT); - } - - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MINFILTER, D3DTEXF_LINEAR); - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MAGFILTER, D3DTEXF_LINEAR); - - // Now setup the texture pipeline. - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION); - // Two output coordinates are used. - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2); - - - DX8Wrapper::Set_DX8_Texture_Stage_State( stage, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); - DX8Wrapper::Set_DX8_Texture_Stage_State( stage, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); - - Matrix4x4 curView; - DX8Wrapper::_Get_DX8_Transform(D3DTS_VIEW, curView); - - - D3DXMATRIX inv; - float det; - D3DXMatrixInverse(&inv, &det, (D3DXMATRIX*)&curView); - D3DXMATRIX scale; - D3DXMatrixScaling(&scale, STRETCH_FACTOR, STRETCH_FACTOR,1); - inv *=scale; - D3DXMATRIX offset; - - Int delta = m_curTick; - m_curTick = ::GetTickCount(); - delta = m_curTick-delta; - m_xOffset += m_xSlidePerSecond*delta/1000; - m_yOffset += m_ySlidePerSecond*delta/1000; - - if (m_xOffset > 1) m_xOffset -= 1; - if (m_yOffset > 1) m_yOffset -= 1; - if (m_xOffset < -1) m_xOffset += 1; - if (m_yOffset < -1) m_yOffset += 1; - - - D3DXMatrixTranslation(&offset, m_xOffset, m_yOffset,0); - - inv *= offset; - - if (stage==0) { - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); - - DX8Wrapper::_Set_DX8_Transform(D3DTS_TEXTURE0, *((Matrix4x4*)&inv)); - - // Disable 3rd stage just in case. - DX8Wrapper::Set_DX8_Texture_Stage_State( 2, D3DTSS_COLOROP, D3DTOP_DISABLE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 2, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); - - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLOROP, D3DTOP_DISABLE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); - - DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE,true); - DX8Wrapper::Set_DX8_Render_State(D3DRS_SRCBLEND,D3DBLEND_DESTCOLOR); - DX8Wrapper::Set_DX8_Render_State(D3DRS_DESTBLEND,D3DBLEND_ZERO); - } else if (stage==1) { - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLORARG1, D3DTA_TEXTURE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLORARG2, D3DTA_CURRENT ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLOROP, D3DTOP_MODULATE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAARG1, D3DTA_CURRENT ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 ); - - DX8Wrapper::_Set_DX8_Transform(D3DTS_TEXTURE1, *((Matrix4x4*)&inv)); - } -#endif -} - -//============================================================================= -// CloudMapTerrainTextureClass::restore -//============================================================================= -/** Cleans up any custom settings to the texturing pipeline that may not be -understood by w3d. */ -//============================================================================= -void CloudMapTerrainTextureClass::restore(void) -{ - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); - - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_TEXCOORDINDEX, 0 ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE); - - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLORARG1, D3DTA_TEXTURE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLOROP, D3DTOP_MODULATE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); - - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_TEXCOORDINDEX, 0 ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE); - DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE,false); - DX8Wrapper::Set_DX8_Render_State(D3DRS_SRCBLEND,D3DBLEND_SRCALPHA); - DX8Wrapper::Set_DX8_Render_State(D3DRS_DESTBLEND,D3DBLEND_INVSRCALPHA); - - - if (TheGlobalData && !TheGlobalData->m_multiPassTerrain) - { - ///@todo: Remove 8-Stage Nvidia hack after drivers are fixed. - //This method is a backdoor specific to Nvidia based cards. It will fail on - //other hardware. Allows single pass blend of 2 textures and post modulate diffuse. - Int i; - for (i=0; i<8; i++) { - DX8Wrapper::Set_DX8_Texture_Stage_State( i, D3DTSS_COLOROP, D3DTOP_DISABLE); - DX8Wrapper::Set_DX8_Texture_Stage_State( i, D3DTSS_TEXCOORDINDEX, i); - DX8Wrapper::Set_DX8_Texture_Stage_State( i, D3DTSS_COLORARG1, D3DTA_TEXTURE); - DX8Wrapper::Set_DX8_Texture_Stage_State( i, D3DTSS_COLORARG2, D3DTA_DIFFUSE); - DX8Wrapper::Set_DX8_Texture_Stage_State( i, D3DTSS_ALPHAOP, D3DTOP_DISABLE); - DX8Wrapper::Set_DX8_Texture_Stage_State( i, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); - DX8Wrapper::Set_DX8_Texture_Stage_State( i, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); - - DX8Wrapper::Set_DX8_Texture(i, NULL); - } - } -} - -/****************************************************************************** - ScorchTextureClass -******************************************************************************/ -//----------------------------------------------------------------------------- -// Public Functions -//----------------------------------------------------------------------------- - -//============================================================================= -// ScorchTextureClass::ScorchTextureClass -//============================================================================= -/** Constructor. Calls parent constructor to load the .tga texture. */ -//============================================================================= -/// @todo - get "EXScorch01.tga" from not hard coded location. -ScorchTextureClass::ScorchTextureClass(MipCountType mipLevelCount) : - TextureClass("EXScorch01.tga","EXScorch01.tga", mipLevelCount ) -// Hack to disable texture reduction. -// TextureClass("EXScorch01.tga","EXScorch01.tga", mipLevelCount,WW3D_FORMAT_UNKNOWN,true,false) -{ -} - -//============================================================================= -// ScorchTextureClass::Apply -//============================================================================= -/** Sets the texture as the current D3D texture, and does some custom setup. -The ScorchTextureClass is applied by iteself, as it's mesh is a subset of the -terrain mesh. -(standard D3D setup, but beyond the scope of W3D). */ -//============================================================================= -void ScorchTextureClass::Apply(unsigned int stage) -{ - // Do the base apply. - TextureClass::Apply(stage); - // Setup bilinear or trilinear filtering as specified in global data. - if (TheGlobalData && (TheGlobalData->m_bilinearTerrainTex || TheGlobalData->m_trilinearTerrainTex)) { - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MINFILTER, D3DTEXF_LINEAR); - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MAGFILTER, D3DTEXF_LINEAR); - } else { - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MINFILTER, D3DTEXF_POINT); - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MAGFILTER, D3DTEXF_POINT); - } - if (TheGlobalData && TheGlobalData->m_trilinearTerrainTex) { - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MIPFILTER, D3DTEXF_LINEAR); - } else { - DX8Wrapper::Set_DX8_Texture_Stage_State(stage, D3DTSS_MIPFILTER, D3DTEXF_POINT); - } - - DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP); - // Now setup the texture pipeline. - - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_TEXCOORDINDEX, 0 ); - DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE,true); - DX8Wrapper::Set_DX8_Render_State(D3DRS_SRCBLEND,D3DBLEND_SRCALPHA); - DX8Wrapper::Set_DX8_Render_State(D3DRS_DESTBLEND,D3DBLEND_INVSRCALPHA); - - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_COLOROP, D3DTOP_DISABLE ); - DX8Wrapper::Set_DX8_Texture_Stage_State( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); -} - - diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/TileData.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/TileData.cpp deleted file mode 100644 index 6566b9f399..0000000000 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/TileData.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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// TileData.cpp -// Class to handle tile data. -// Author: John Ahlquist, April 2001 - -#include "W3DDevice/GameClient/TileData.h" -#include "W3DDevice/GameClient/WorldHeightMap.h" - - - -// -// TileData - no destructor. -// - -// -// TileData - create a new texture tile . -// -TileData::TileData() -{ - -} - -#define TILE_PIXEL_EXTENT_MIP1 32 -#define TILE_PIXEL_EXTENT_MIP2 16 -#define TILE_PIXEL_EXTENT_MIP3 8 -#define TILE_PIXEL_EXTENT_MIP4 4 -#define TILE_PIXEL_EXTENT_MIP5 2 -#define TILE_PIXEL_EXTENT_MIP6 1 - -Bool TileData::hasRGBDataForWidth(Int width) -{ - if (width == TILE_PIXEL_EXTENT) return(true); - if (width == TILE_PIXEL_EXTENT_MIP1) return(true); - if (width == TILE_PIXEL_EXTENT_MIP2) return(true); - if (width == TILE_PIXEL_EXTENT_MIP3) return(true); - if (width == TILE_PIXEL_EXTENT_MIP4) return(true); - if (width == TILE_PIXEL_EXTENT_MIP5) return(true); - if (width == TILE_PIXEL_EXTENT_MIP6) return(true); - return(false); -} - -UnsignedByte * TileData::getRGBDataForWidth(Int width) -{ - // default - if (width == TILE_PIXEL_EXTENT_MIP1) return(m_tileDataMip32); - if (width == TILE_PIXEL_EXTENT_MIP2) return(m_tileDataMip16); - if (width == TILE_PIXEL_EXTENT_MIP3) return(m_tileDataMip8); - if (width == TILE_PIXEL_EXTENT_MIP4) return(m_tileDataMip4); - if (width == TILE_PIXEL_EXTENT_MIP5) return(m_tileDataMip2); - if (width == TILE_PIXEL_EXTENT_MIP6) return(m_tileDataMip1); - return(m_tileData); -} - -void TileData::updateMips(void) -{ - doMip(m_tileData, TILE_PIXEL_EXTENT, m_tileDataMip32); - doMip(m_tileDataMip32, TILE_PIXEL_EXTENT_MIP1, m_tileDataMip16); - doMip(m_tileDataMip16, TILE_PIXEL_EXTENT_MIP2, m_tileDataMip8); - doMip(m_tileDataMip8, TILE_PIXEL_EXTENT_MIP3, m_tileDataMip4); - doMip(m_tileDataMip4, TILE_PIXEL_EXTENT_MIP4, m_tileDataMip2); - doMip(m_tileDataMip2, TILE_PIXEL_EXTENT_MIP5, m_tileDataMip1); -} - - -void TileData::doMip(UnsignedByte *pHiRes, Int hiRow, UnsignedByte *pLoRes) -{ - Int i, j; - for (i=0; i. -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: W3DTerrainTracks.cpp //////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: W3DTerrainTracks.cpp -// -// Created: Mark Wilczynski, May 2001 -// -// Desc: Draw track marks on the terrain. Uses a sequence of connected -// quads that are oriented to fit the terrain and updated when object -// moves. -//----------------------------------------------------------------------------- - -#include "W3DDevice/GameClient/W3DTerrainTracks.h" -#include "W3DDevice/GameClient/HeightMap.h" -#include "Common/PerfTimer.h" -#include "Common/GlobalData.h" -#include "Common/Debug.h" -#include "texture.h" -#include "colmath.h" -#include "coltest.h" -#include "rinfo.h" -#include "camera.h" -#include "assetmgr.h" -#include "WW3D2/dx8wrapper.h" -#include "WW3D2/scene.h" -#include "GameLogic/TerrainLogic.h" -#include "GameLogic/Object.h" -#include "GameClient/Drawable.h" - - -#define BRIDGE_OFFSET_FACTOR 0.25f //amount to raise tracks above bridges. -//============================================================================= -// TerrainTracksRenderObjClass::~TerrainTracksRenderObjClass -//============================================================================= -/** Destructor. Releases w3d assets. */ -//============================================================================= -TerrainTracksRenderObjClass::~TerrainTracksRenderObjClass(void) -{ - freeTerrainTracksResources(); -} - -//============================================================================= -// TerrainTracksRenderObjClass::TerrainTracksRenderObjClass -//============================================================================= -/** Constructor. Just nulls out some variables. */ -//============================================================================= -TerrainTracksRenderObjClass::TerrainTracksRenderObjClass(void) -{ - m_stageZeroTexture=NULL; - m_lastAnchor=Vector3(0,1,2.25); - m_haveAnchor=false; - m_haveCap=true; - m_topIndex=0; - m_bottomIndex=0; - m_activeEdgeCount=0; - m_totalEdgesAdded=0; - m_bound=false; - m_ownerDrawable = NULL; -} - -//============================================================================= -// TerrainTracksRenderObjClass::Get_Obj_Space_Bounding_Sphere -//============================================================================= -/** WW3D method that returns object bounding sphere used in frustum culling*/ -//============================================================================= -void TerrainTracksRenderObjClass::Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const -{ /// @todo: Add code to cull track marks to screen by constantly updating bounding volumes - sphere=m_boundingSphere; -} - -//============================================================================= -// TerrainTracksRenderObjClass::Get_Obj_Space_Bounding_Box -//============================================================================= -/** WW3D method that returns object bounding box used in collision detection*/ -//============================================================================= -void TerrainTracksRenderObjClass::Get_Obj_Space_Bounding_Box(AABoxClass & box) const -{ - box=m_boundingBox; -} - -//============================================================================= -// MirrorRenderObjClass::Class_ID -//============================================================================= -/** returns the class id, so the scene can tell what kind of render object it has. */ -//============================================================================= -Int TerrainTracksRenderObjClass::Class_ID(void) const -{ - return RenderObjClass::CLASSID_IMAGE3D; -} - -//============================================================================= -// TerrainTracksRenderObjClass::Clone -//============================================================================= -/** Not used, but required virtual method. */ -//============================================================================= -RenderObjClass * TerrainTracksRenderObjClass::Clone(void) const -{ - assert(false); - return NULL; -} - -//============================================================================= -// TerrainTracksRenderObjClass::freeTerrainTracksResources -//============================================================================= -/** Free any W3D resources associated with this object */ -//============================================================================= -Int TerrainTracksRenderObjClass::freeTerrainTracksResources(void) -{ - REF_PTR_RELEASE(m_stageZeroTexture); - m_haveAnchor=false; - m_haveCap=true; - m_topIndex=0; - m_bottomIndex=0; - m_activeEdgeCount=0; - m_totalEdgesAdded=0; - m_ownerDrawable = NULL; - - return 0; -} - -//============================================================================= -// TerrainTracksRenderObjClass::init -//============================================================================= -/** Setup size settings and allocate W3D texture */ -//============================================================================= -void TerrainTracksRenderObjClass::init( Real width, Real length, const Char *texturename) -{ - freeTerrainTracksResources(); //free old data and ib/vb - - m_boundingSphere.Init(Vector3(0,0,0),400*MAP_XY_FACTOR); - m_boundingBox.Center.Set(0.0f, 0.0f, 0.0f); - m_boundingBox.Extent.Set(400.0f*MAP_XY_FACTOR, 400.0f*MAP_XY_FACTOR, 1.0f); - m_width=width; - m_length=length; - //no sense culling these things since they have very irregular shape and fade - //out over time. - Set_Force_Visible(TRUE); - m_stageZeroTexture=WW3DAssetManager::Get_Instance()->Get_Texture(texturename); -} - -//============================================================================= -// TerrainTracksRenderObjClass::addCapEdgeToTrack -//============================================================================= -/** Cap the current track (adding an feathered edge) so we're ready to resume - the track at a new location. Used by objects entering FOW where we need to - stop adding edges to the track when they enter the fog boundary but resume - elsewhere if they become visible again. -*/ -//============================================================================= -void TerrainTracksRenderObjClass::addCapEdgeToTrack(Real x, Real y) -{ - /// @todo: Have object pass its height and orientation so we can remove extra calls. - - if (m_haveCap) - { //we already have a cap or there are no segments to cap - return; - } - - if (m_activeEdgeCount == 1) - { //if we only have one edge, then it must be the current anchor edge. - //since achnors are caps, there is not point in adding another. - m_haveCap=TRUE; - m_haveAnchor=false; //recreate a new anchor when track resumes. - return; - } - - Vector3 vPos,vZ; - Coord3D vZTmp; - PathfindLayerEnum objectLayer; - Real eHeight; - - if (m_ownerDrawable && (objectLayer=m_ownerDrawable->getObject()->getLayer()) != LAYER_GROUND) - eHeight=BRIDGE_OFFSET_FACTOR+TheTerrainLogic->getLayerHeight(x,y,objectLayer,&vZTmp); - else - eHeight=TheTerrainLogic->getGroundHeight(x,y,&vZTmp); - - vZ.X = vZTmp.x; - vZ.Y = vZTmp.y; - vZ.Z = vZTmp.z; - - vPos.X=x; - vPos.Y=y; - vPos.Z=eHeight; - - Vector3 vDir=Vector3(x,y,eHeight)-m_lastAnchor; - Int maxEdgeCount=TheTerrainTracksRenderObjClassSystem->m_maxTankTrackEdges; - - //avoid sqrt() by checking distance squared since last track mark - if (vDir.Length2() < sqr(m_length)) - { //not far enough from anchor to add track - //since this is a cap, we'll force the previous segment to transparent - Int lastAddedEdge=m_topIndex-1; - if (lastAddedEdge < 0) - lastAddedEdge = maxEdgeCount-1; - m_edges[lastAddedEdge].alpha=0.0f; //force the last added edge to transparent. - m_haveCap=TRUE; - m_haveAnchor=false; //recreate a new anchor when track resumes. - return; - } - - if (m_activeEdgeCount >= maxEdgeCount) - { //no more room in buffer so release oldest edge - m_bottomIndex++; - m_activeEdgeCount--; - - if (m_bottomIndex >= maxEdgeCount) - m_bottomIndex=0; //roll buffer back to start - } - - if (m_topIndex >= maxEdgeCount) - m_topIndex=0; //roll around buffer - - //we traveled far enough from last point. - //accept new point - vDir.Z=0; //ignore height - vDir.Normalize(); - - Vector3 vX; - - Vector3::Cross_Product(vDir,vZ,&vX); - - //calculate left end point - edgeInfo& topEdge = m_edges[m_topIndex]; - - topEdge.endPointPos[0]=vPos-(m_width*0.5f*vX); ///@todo: try getting height at endpoint - topEdge.endPointPos[0].Z += 0.2f * MAP_XY_FACTOR; //raise above terrain slightly - - if (m_totalEdgesAdded&1) //every other edge has different set of UV's - { - topEdge.endPointUV[0].X=0.0f; - topEdge.endPointUV[0].Y=0.0f; - } - else - { - topEdge.endPointUV[0].X=0.0f; - topEdge.endPointUV[0].Y=1.0f; - } - - //calculate right end point - topEdge.endPointPos[1]=vPos+(m_width*0.5f*vX); ///@todo: try getting height at endpoint - topEdge.endPointPos[1].Z += 0.2f * MAP_XY_FACTOR; //raise above terrain slightly - - if (m_totalEdgesAdded&1) //every other edge has different set of UV's - { - topEdge.endPointUV[1].X=1.0f; - topEdge.endPointUV[1].Y=0.0f; - } - else - { - topEdge.endPointUV[1].X=1.0f; - topEdge.endPointUV[1].Y=1.0f; - } - - topEdge.timeAdded=WW3D::Get_Sync_Time(); - topEdge.alpha=0.0f; //fully transparent at cap. - m_lastAnchor=vPos; - m_activeEdgeCount++; - m_totalEdgesAdded++; - m_topIndex++; //make space for new edge - m_haveCap=TRUE; - m_haveAnchor=false; -} - -//============================================================================= -// TerrainTracksRenderObjClass::addEdgeToTrack -//============================================================================= -/** Try to add an additional segment to track mark. Will do nothing if distance -* from last edge is too small. Will overwrite the oldest edge if maximum track -* length is reached. Oldest edges should by faded out by that time. -*/ -//============================================================================= -void TerrainTracksRenderObjClass::addEdgeToTrack(Real x, Real y) -{ - /// @todo: Have object pass its height and orientation so we can remove extra calls. - - if (!m_haveAnchor) - { //no anchor yet, make this point an anchor. - PathfindLayerEnum objectLayer; - if (m_ownerDrawable && (objectLayer=m_ownerDrawable->getObject()->getLayer()) != LAYER_GROUND) - m_lastAnchor=Vector3(x,y,TheTerrainLogic->getLayerHeight(x,y,objectLayer)+BRIDGE_OFFSET_FACTOR); - else - m_lastAnchor=Vector3(x,y,TheTerrainLogic->getGroundHeight(x,y)); - - m_haveAnchor=true; - m_airborne = true; - m_haveCap = true; //single segment tracks are always capped because nothing is drawn. - return; - } - - m_haveCap = false; //have more than 1 segment now so will need to cap if it's interrupted. - - Vector3 vPos,vZ; - Coord3D vZTmp; - Real eHeight; - PathfindLayerEnum objectLayer; - - if (m_ownerDrawable && (objectLayer=m_ownerDrawable->getObject()->getLayer()) != LAYER_GROUND) - eHeight=BRIDGE_OFFSET_FACTOR+TheTerrainLogic->getLayerHeight(x,y,objectLayer,&vZTmp); - else - eHeight=TheTerrainLogic->getGroundHeight(x,y,&vZTmp); - - vZ.X = vZTmp.x; - vZ.Y = vZTmp.y; - vZ.Z = vZTmp.z; - - vPos.X=x; - vPos.Y=y; - vPos.Z=eHeight; - - Vector3 vDir=Vector3(x,y,eHeight)-m_lastAnchor; - - //avoid sqrt() by checking distance squared since last track mark - if (vDir.Length2() < sqr(m_length)) - return; //not far enough from anchor to add track - - Int maxEdgeCount=TheTerrainTracksRenderObjClassSystem->m_maxTankTrackEdges; - - if (m_activeEdgeCount >= maxEdgeCount) - { //no more room in buffer so release oldest edge - m_bottomIndex++; - m_activeEdgeCount--; - - if (m_bottomIndex >= maxEdgeCount) - m_bottomIndex=0; //roll buffer back to start - } - - if (m_topIndex >= maxEdgeCount) - m_topIndex=0; //roll around buffer - - //we traveled far enough from last point. - //accept new point - vDir.Z=0; //ignore height - vDir.Normalize(); - - Vector3 vX; - - Vector3::Cross_Product(vDir,vZ,&vX); - - edgeInfo& topEdge = m_edges[m_topIndex]; - - //calculate left end point - topEdge.endPointPos[0]=vPos-(m_width*0.5f*vX); ///@todo: try getting height at endpoint - topEdge.endPointPos[0].Z += 0.2f * MAP_XY_FACTOR; //raise above terrain slightly - - if (m_totalEdgesAdded&1) //every other edge has different set of UV's - { - topEdge.endPointUV[0].X=0.0f; - topEdge.endPointUV[0].Y=0.0f; - } - else - { - topEdge.endPointUV[0].X=0.0f; - topEdge.endPointUV[0].Y=1.0f; - } - - //calculate right end point - topEdge.endPointPos[1]=vPos+(m_width*0.5f*vX); ///@todo: try getting height at endpoint - topEdge.endPointPos[1].Z += 0.2f * MAP_XY_FACTOR; //raise above terrain slightly - - if (m_totalEdgesAdded&1) //every other edge has different set of UV's - { - topEdge.endPointUV[1].X=1.0f; - topEdge.endPointUV[1].Y=0.0f; - } - else - { - topEdge.endPointUV[1].X=1.0f; - topEdge.endPointUV[1].Y=1.0f; - } - - topEdge.timeAdded=WW3D::Get_Sync_Time(); - topEdge.alpha=1.0f; //fully opaque at start. - if (m_airborne || m_activeEdgeCount <= 1) { - topEdge.alpha=0.0f; //smooth out track restarts by setting transparent - } - m_airborne = false; - - m_lastAnchor=vPos; - m_activeEdgeCount++; - m_totalEdgesAdded++; - m_topIndex++; //make space for new edge -} - -//============================================================================= -// TerrainTracksRenderObjClass::Render -//============================================================================= -/** Does nothing. Just increments a counter of how many track edges were -* requested for rendering this frame. Actual rendering is done in flush(). -*/ -//============================================================================= -void TerrainTracksRenderObjClass::Render(RenderInfoClass & rinfo) -{ ///@todo: After adding track mark visibility tests, add visible marks to another list. - if (TheGlobalData->m_makeTrackMarks && m_activeEdgeCount >= 2) - TheTerrainTracksRenderObjClassSystem->m_edgesToFlush += m_activeEdgeCount; -} - -#define DEFAULT_TRACK_SPACING (MAP_XY_FACTOR * 1.4f) -#define DEFAULT_TRACK_WIDTH 4.0f; - -/**Find distance between the "trackfx" bones of the model. This tells us the correct - width for the trackmarks. -*/ -static Real computeTrackSpacing(RenderObjClass *renderObj) -{ - Real trackSpacing = DEFAULT_TRACK_SPACING; - Int leftTrack; - Int rightTrack; - - if ((leftTrack=renderObj->Get_Bone_Index( "TREADFX01" )) != 0 && (rightTrack=renderObj->Get_Bone_Index( "TREADFX02" )) != 0) - { //both bones found, determine distance between them. - Vector3 leftPos,rightPos; - leftPos=renderObj->Get_Bone_Transform( leftTrack ).Get_Translation(); - rightPos=renderObj->Get_Bone_Transform( rightTrack ).Get_Translation(); - rightPos -= leftPos; //get distance between centers of tracks - trackSpacing = rightPos.Length() + DEFAULT_TRACK_WIDTH; //add width of each track - ///@todo: It's assumed that all tank treads have the same width. - }; - - return trackSpacing; -} - -//============================================================================= -//TerrainTracksRenderObjClassSystem::bindTrack -//============================================================================= -/** Grab a track from the free store. If no free tracks exist, return NULL. - As long as a track is bound to an object (like a tank) it is ready to accept - updates with additional edges. Once it is unbound, it will expire and return - to the free store once all tracks have faded out. - - Input: width in world units of each track edge (should probably width of vehicle). - length in world units between edges. Shorter lengths produce more edges and - smoother curves. - texture to use for the tracks - image should be symetrical and include alpha channel. -*/ -//============================================================================= -TerrainTracksRenderObjClass *TerrainTracksRenderObjClassSystem::bindTrack( RenderObjClass *renderObject, Real length, const Char *texturename) -{ - TerrainTracksRenderObjClass *mod; - - mod = m_freeModules; - if( mod ) - { - // take module off the free list - if( mod->m_nextSystem ) - mod->m_nextSystem->m_prevSystem = mod->m_prevSystem; - if( mod->m_prevSystem ) - mod->m_prevSystem->m_nextSystem = mod->m_nextSystem; - else - m_freeModules = mod->m_nextSystem; - - // put module on the used list - mod->m_prevSystem = NULL; - mod->m_nextSystem = m_usedModules; - if( m_usedModules ) - m_usedModules->m_prevSystem = mod; - m_usedModules = mod; - - mod->init(computeTrackSpacing(renderObject),length,texturename); - mod->m_bound=true; - m_TerrainTracksScene->Add_Render_Object( mod); - } - - return mod; - -} - -//============================================================================= -//TerrainTracksRenderObjClassSystem::unbindTrack -//============================================================================= -/** Called when an object (i.e Tank) will not lay down any more tracks and -doesn't need this object anymore. The track-laying object will be returned -to pool of available tracks as soon as any remaining track edges have faded out. -*/ -//============================================================================= -void TerrainTracksRenderObjClassSystem::unbindTrack( TerrainTracksRenderObjClass *mod ) -{ - //this object should return to free store as soon as there is nothing - //left to render. - mod->m_bound=false; - mod->m_ownerDrawable = NULL; -} - -//============================================================================= -//TerrainTracksRenderObjClassSystem::releaseTrack -//============================================================================= -/** Returns a track laying object to free store to be used again later. -*/ -void TerrainTracksRenderObjClassSystem::releaseTrack( TerrainTracksRenderObjClass *mod ) -{ - if (mod==NULL) - return; - - DEBUG_ASSERTCRASH(mod->m_bound == false, ("mod is bound.")); - - // remove module from used list - if( mod->m_nextSystem ) - mod->m_nextSystem->m_prevSystem = mod->m_prevSystem; - if( mod->m_prevSystem ) - mod->m_prevSystem->m_nextSystem = mod->m_nextSystem; - else - m_usedModules = mod->m_nextSystem; - - // add module to free list - mod->m_prevSystem = NULL; - mod->m_nextSystem = m_freeModules; - if( m_freeModules ) - m_freeModules->m_prevSystem = mod; - m_freeModules = mod; - mod->freeTerrainTracksResources(); - m_TerrainTracksScene->Remove_Render_Object(mod); -} - -//============================================================================= -// TerrainTracksRenderObjClassSystem::TerrainTracksRenderObjClassSystem -//============================================================================= -/** Constructor. Just nulls out some variables. */ -//============================================================================= -TerrainTracksRenderObjClassSystem::TerrainTracksRenderObjClassSystem() -{ - m_usedModules = NULL; - m_freeModules = NULL; - m_TerrainTracksScene = NULL; - m_edgesToFlush = 0; - m_indexBuffer = NULL; - m_vertexMaterialClass = NULL; - m_vertexBuffer = NULL; - - m_maxTankTrackEdges=TheGlobalData->m_maxTankTrackEdges; - m_maxTankTrackOpaqueEdges=TheGlobalData->m_maxTankTrackOpaqueEdges; - m_maxTankTrackFadeDelay=TheGlobalData->m_maxTankTrackFadeDelay; -} - -//============================================================================= -// TerrainTracksRenderObjClassSystem::~TerrainTracksRenderObjClassSystem -//============================================================================= -/** Destructor. Free all pre-allocated track laying render objects*/ -//============================================================================= -TerrainTracksRenderObjClassSystem::~TerrainTracksRenderObjClassSystem( void ) -{ - - // free all data - shutdown(); - - m_vertexMaterialClass=NULL; - m_TerrainTracksScene=NULL; - -} - -//============================================================================= -// TerrainTracksRenderObjClassSystem::ReAcquireResources -//============================================================================= -/** (Re)allocates all W3D assets after a reset.. */ -//============================================================================= -void TerrainTracksRenderObjClassSystem::ReAcquireResources(void) -{ - Int i; - const Int numModules=TheGlobalData->m_maxTerrainTracks; - - // just for paranoia's sake. - REF_PTR_RELEASE(m_indexBuffer); - REF_PTR_RELEASE(m_vertexBuffer); - - //Create static index buffers. These will index the vertex buffers holding the track segments - m_indexBuffer=NEW_REF(DX8IndexBufferClass,((m_maxTankTrackEdges-1)*6)); - - // Fill up the IB - { - DX8IndexBufferClass::WriteLockClass lockIdxBuffer(m_indexBuffer); - UnsignedShort *ib=lockIdxBuffer.Get_Index_Array(); - - for (i=0; i<(m_maxTankTrackEdges-1); i++) - { - ib[3]=ib[0]=i*2; - ib[1]=i*2+1; - ib[4]=ib[2]=(i+1)*2+1; - ib[5]=(i+1)*2; - ib+=6; //skip the 6 indices we just filled - } - } - - DEBUG_ASSERTCRASH(numModules*m_maxTankTrackEdges*2 < 65535, ("Too many terrain track edges")); - - m_vertexBuffer=NEW_REF(DX8VertexBufferClass,(DX8_FVF_XYZDUV1,numModules*m_maxTankTrackEdges*2,DX8VertexBufferClass::USAGE_DYNAMIC)); -} - -//============================================================================= -// TerrainTracksRenderObjClassSystem::ReleaseResources -//============================================================================= -/** (Re)allocates all W3D assets after a reset.. */ -//============================================================================= -void TerrainTracksRenderObjClassSystem::ReleaseResources(void) -{ - REF_PTR_RELEASE(m_indexBuffer); - REF_PTR_RELEASE(m_vertexBuffer); - // Note - it is ok to not release the material, as it is a w3d object that - // has no dx8 resources. jba. -} - -//============================================================================= -// TerrainTracksRenderObjClassSystem::init -//============================================================================= -/** initialize the system, allocate all the render objects we will need */ -//============================================================================= -void TerrainTracksRenderObjClassSystem::init( SceneClass *TerrainTracksScene ) -{ - const Int numModules=TheGlobalData->m_maxTerrainTracks; - - Int i; - TerrainTracksRenderObjClass *mod; - - m_TerrainTracksScene=TerrainTracksScene; - - ReAcquireResources(); - //go with a preset material for now. - m_vertexMaterialClass=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_DIFFUSE); - - //use a multi-texture shader: (text1*diffuse)*text2. - m_shaderClass = ShaderClass::_PresetAlphaShader;//_PresetATestSpriteShader;//_PresetOpaqueShader; - - // we cannot initialize a system that is already initialized - if( m_freeModules || m_usedModules ) - { - - // system already online! - assert( 0 ); - return; - - } - - // allocate our modules for this system - for( i = 0; i < numModules; i++ ) - { - - mod = NEW_REF( TerrainTracksRenderObjClass, () ); - - if( mod == NULL ) - { - - // unable to allocate modules needed - assert( 0 ); - return; - - } - - mod->m_prevSystem = NULL; - mod->m_nextSystem = m_freeModules; - if( m_freeModules ) - m_freeModules->m_prevSystem = mod; - m_freeModules = mod; - - } - -} - -//============================================================================= -// TerrainTracksRenderObjClassSystem::shutdown -//============================================================================= -/** Shutdown and free all memory for this system */ -//============================================================================= -void TerrainTracksRenderObjClassSystem::shutdown( void ) -{ - TerrainTracksRenderObjClass *nextMod,*mod; - - //release unbound tracks that may still be fading out - mod=m_usedModules; - - while(mod) - { - nextMod=mod->m_nextSystem; - - if (!mod->m_bound) - releaseTrack(mod); - - mod = nextMod; - } - - - // free all attached things and used modules - assert( m_usedModules == NULL ); - - // free all module storage - while( m_freeModules ) - { - - nextMod = m_freeModules->m_nextSystem; - REF_PTR_RELEASE (m_freeModules); - m_freeModules = nextMod; - - } - - REF_PTR_RELEASE(m_indexBuffer); - REF_PTR_RELEASE(m_vertexMaterialClass); - REF_PTR_RELEASE(m_vertexBuffer); - -} - -//============================================================================= -// TerrainTracksRenderObjClassSystem::update -//============================================================================= -/** Update the state of all active track marks - fade, expire, etc. */ -//============================================================================= -void TerrainTracksRenderObjClassSystem::update() -{ - - Int iTime=WW3D::Get_Sync_Time(); - Real iDiff; - TerrainTracksRenderObjClass *mod=m_usedModules,*nextMod; - - //first update all the tracks - while( mod ) - { - Int i,index; - Vector3 *endPoint; - Vector2 *endPointUV; - - nextMod = mod->m_nextSystem; - - if (!TheGlobalData->m_makeTrackMarks) - mod->m_haveAnchor=false; //force a track restart next time around. - - for (i=0,index=mod->m_bottomIndex; im_activeEdgeCount; i++,index++) - { - if (index >= m_maxTankTrackEdges) - index=0; - - endPoint=&mod->m_edges[index].endPointPos[0]; //left endpoint - endPointUV=&mod->m_edges[index].endPointUV[0]; - iDiff=(float)(iTime-mod->m_edges[index].timeAdded); - iDiff = 1.0f - iDiff/(Real)m_maxTankTrackFadeDelay; - if (iDiff < 0.0) - iDiff=0.0f; - if (mod->m_edges[index].alpha>0.0f) { - mod->m_edges[index].alpha=iDiff; - } - - if (iDiff == 0.0f) - { //this edge was invisible, we can remove it - mod->m_bottomIndex++; - mod->m_activeEdgeCount--; - - if (mod->m_bottomIndex >= m_maxTankTrackEdges) - mod->m_bottomIndex=0; //roll buffer back to start - } - if (mod->m_activeEdgeCount == 0 && !mod->m_bound) - releaseTrack(mod); - } - mod = nextMod; - } -} - - -//============================================================================= -// TerrainTracksRenderObjClassSystem::flush -//============================================================================= -/** Draw all active track marks for this frame */ -//============================================================================= -void TerrainTracksRenderObjClassSystem::flush() -{ -/** @todo: Optimize system by drawing tracks as triangle strips and use dynamic vertex buffer access. -May also try rendering all tracks with one call to W3D/D3D by grouping them by texture. -Try improving the fit to vertical surfaces like cliffs. -*/ - - Int diffuseLight; - TerrainTracksRenderObjClass *mod=m_usedModules; - if (!mod) - return; //nothing to render - - Int trackStartIndex; - Real distanceFade; - - if (ShaderClass::Is_Backface_Culling_Inverted()) - return; //don't render track marks in reflections. - - // adjust shading for time of day. - Real shadeR, shadeG, shadeB; - shadeR = TheGlobalData->m_terrainAmbient[0].red; - shadeG = TheGlobalData->m_terrainAmbient[0].green; - shadeB = TheGlobalData->m_terrainAmbient[0].blue; - shadeR += TheGlobalData->m_terrainDiffuse[0].red/2; - shadeG += TheGlobalData->m_terrainDiffuse[0].green/2; - shadeB += TheGlobalData->m_terrainDiffuse[0].blue/2; - shadeR*=255.0f; - shadeG*=255.0f; - shadeB*=255.0f; - - diffuseLight = REAL_TO_INT(shadeB) | (REAL_TO_INT(shadeG) << 8) | (REAL_TO_INT(shadeR) << 16); - Real numFadedEdges=m_maxTankTrackEdges-m_maxTankTrackOpaqueEdges; - - //check if there is anything to draw and fill vertex buffer - if (m_edgesToFlush >= 2) - { - DX8VertexBufferClass::WriteLockClass lockVtxBuffer(m_vertexBuffer); - VertexFormatXYZDUV1 *verts = (VertexFormatXYZDUV1*)lockVtxBuffer.Get_Vertex_Array(); - trackStartIndex=0; - - mod=m_usedModules; - //Fill our vertex buffer with all the tracks - while( mod ) - { - Int i,index; - Vector3 *endPoint; - Vector2 *endPointUV; - - if (mod->m_activeEdgeCount >= 2 && mod->Is_Really_Visible()) - { - for (i=0,index=mod->m_bottomIndex; im_activeEdgeCount; i++,index++) - { - if (index >= m_maxTankTrackEdges) - index=0; - - endPoint=&mod->m_edges[index].endPointPos[0]; //left endpoint - endPointUV=&mod->m_edges[index].endPointUV[0]; - - distanceFade=1.0f; - - if ((mod->m_activeEdgeCount -1 -i) >= m_maxTankTrackOpaqueEdges)// && i < (MAX_PER_TRACK_EDGE_COUNT-FORCE_FADE_AT_EDGE)) - { //we're getting close to the limit on the number of track pieces allowed - //so force it to fade out. - distanceFade=1.0f-(float)((mod->m_activeEdgeCount -i)-m_maxTankTrackOpaqueEdges)/numFadedEdges; - } - - distanceFade *= mod->m_edges[index].alpha; //adjust fade with distance from start of track - - verts->x=endPoint->X; - verts->y=endPoint->Y; - verts->z=endPoint->Z; - - verts->u1=endPointUV->X; - verts->v1=endPointUV->Y; - - //fade the alpha channel with distance - verts->diffuse=diffuseLight | ( REAL_TO_INT(distanceFade*255.0f) <<24); - verts++; - - endPoint=&mod->m_edges[index].endPointPos[1]; //right endpoint - endPointUV=&mod->m_edges[index].endPointUV[1]; - - verts->x=endPoint->X; - verts->y=endPoint->Y; - verts->z=endPoint->Z; - - verts->u1=endPointUV->X; - verts->v1=endPointUV->Y; ///@todo: Add diffuse lighting. - - verts->diffuse=diffuseLight | ( REAL_TO_INT(distanceFade*255.0f) <<24); - verts++; - } - } - mod = mod->m_nextSystem; - } - } - - //draw the filled vertex buffers - if (m_edgesToFlush >= 2) - { - ShaderClass::Invalidate(); - DX8Wrapper::Set_Material(m_vertexMaterialClass); - DX8Wrapper::Set_Shader(m_shaderClass); - DX8Wrapper::Set_Index_Buffer(m_indexBuffer,0); - DX8Wrapper::Set_Vertex_Buffer(m_vertexBuffer); - - trackStartIndex=0; - mod=m_usedModules; - Matrix3D tm(mod->Transform); - DX8Wrapper::Set_Transform(D3DTS_WORLD,tm); - while (mod) - { - if (mod->m_activeEdgeCount >= 2 && mod->Is_Really_Visible()) - { - DX8Wrapper::Set_Texture(0,mod->m_stageZeroTexture); - DX8Wrapper::Set_Index_Buffer_Index_Offset(trackStartIndex); - DX8Wrapper::Draw_Triangles( 0,(mod->m_activeEdgeCount-1)*2, 0, mod->m_activeEdgeCount*2); - - trackStartIndex += mod->m_activeEdgeCount*2; - } - mod=mod->m_nextSystem; - } - } - - m_edgesToFlush=0; //reset count for next flush -} - -/**Removes all remaining tracks from the rendering system*/ -void TerrainTracksRenderObjClassSystem::Reset(void) -{ - TerrainTracksRenderObjClass *nextMod,*mod=m_usedModules; - - while(mod) - { - nextMod=mod->m_nextSystem; - - releaseTrack(mod); - - mod = nextMod; - } - - - // free all attached things and used modules - assert( m_usedModules == NULL ); - m_edgesToFlush=0; -} - -/**Clear the treads from each track laying object without freeing the objects. -Mostly used when user changed LOD level*/ -void TerrainTracksRenderObjClassSystem::clearTracks(void) -{ - TerrainTracksRenderObjClass *mod=m_usedModules; - - while(mod) - { - mod->m_haveAnchor=false; - mod->m_haveCap=true; - mod->m_topIndex=0; - mod->m_bottomIndex=0; - mod->m_activeEdgeCount=0; - mod->m_totalEdgesAdded=0; - - mod = mod->m_nextSystem; - } - - m_edgesToFlush=0; -} - -/**Adjust various paremeters which affect the cost of rendering tracks on the map. -Parameters are passed via GlobalData*/ -void TerrainTracksRenderObjClassSystem::setDetail(void) -{ - //Remove all existing track segments from screen. - clearTracks(); - ReleaseResources(); - - m_maxTankTrackEdges=TheGlobalData->m_maxTankTrackEdges; - m_maxTankTrackOpaqueEdges=TheGlobalData->m_maxTankTrackOpaqueEdges; - m_maxTankTrackFadeDelay=TheGlobalData->m_maxTankTrackFadeDelay; - - //We changed the maximum number of visible edges so re-allocate our resources to match. - ReAcquireResources(); -}; - -TerrainTracksRenderObjClassSystem *TheTerrainTracksRenderObjClassSystem=NULL; ///< singleton for track drawing system. diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp deleted file mode 100644 index 754be44e7e..0000000000 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp +++ /dev/null @@ -1,1261 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public 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: W3DTerrainVisual.cpp ///////////////////////////////////////////////////////////////////// -// W3D implementation details for visual aspects of terrain -// Author: Colin Day, April 2001 -/////////////////////////////////////////////////////////////////////////////////////////////////// - -#include -#include - -#include "Common/GameState.h" -#include "Common/GlobalData.h" -#include "Common/PerfTimer.h" -#include "Common/MapReaderWriterInfo.h" -#include "Common/ThingTemplate.h" -#include "Common/WellKnownKeys.h" -#include "Common/TerrainTypes.h" -#include "Common/Xfer.h" -#include "Common/UnitTimings.h" //Contains the DO_UNIT_TIMINGS define jba. - -#include "GameClient/Drawable.h" -#include "GameClient/ClientRandomValue.h" - -#include "GameLogic/Object.h" -#include "GameLogic/GameLogic.h" - -#include "W3DDevice/GameClient/W3DScene.h" -#include "W3DDevice/GameClient/W3DTerrainVisual.h" -#include "W3DDevice/GameClient/WorldHeightMap.h" -#include "W3DDevice/GameClient/W3DWater.h" -#include "W3DDevice/GameClient/W3DDisplay.h" -#include "W3DDevice/GameClient/W3DDebugIcons.h" -#include "W3DDevice/GameClient/W3DTerrainTracks.h" -#include "W3DDevice/GameClient/W3DShadow.h" -#include "W3DDevice/GameClient/HeightMap.h" -#include "W3DDevice/GameClient/FlatHeightMap.h" -#include "W3DDevice/GameClient/W3DSmudge.h" -#include "W3DDevice/GameClient/Module/W3DModelDraw.h" -#include "WW3D2/light.h" -#include "WW3D2/rendobj.h" -#include "WW3D2/coltype.h" -#include "WW3D2/coltest.h" -#include "WW3D2/assetmgr.h" - - - -class TestSeismicFilter : public SeismicSimulationFilterBase -{ - - virtual SeismicSimStatusCode filterCallback( WorldHeightMapInterfaceClass *heightMap, const SeismicSimulationNode *node ) - { - - - Int life = node->m_life; - - if ( heightMap == NULL ) - return SEISMIC_STATUS_INVALID; - - - if ( life == 0 ) - return SEISMIC_STATUS_ACTIVE; - if ( life < 15 ) - { - // ADD HEIGHT BECAUSE THE EXPLOSION IS PUSHING DIRT UP - - Real magnitude = node->m_magnitude; - - Real offsScalar = magnitude / (Real)life; // real-life, get it? - Int radius = node->m_radius; - Int border = heightMap->getBorderSize(); - Int centerX = node->m_center.x + border ; - Int centerY = node->m_center.y + border ; - - UnsignedInt workspaceWidth = radius*2; - Real *workspace = NEW Real[ sqr(workspaceWidth) ]; - Real *workspaceEnd = workspace + sqr(workspaceWidth); - - - for ( Real *t = workspace; t < workspaceEnd; ++t ) *t = 0.0f;// clear the workspace - - Int x = 0; - for (; x < radius; ++x) - { - for (Int y = 0; y < radius; ++y) - { - - Real distance = sqrt( sqr(x) + sqr(y) );//Pythagoras - - if ( distance < radius ) - { - Real distScalar = cos( ( distance / radius * (PI/2) ) ); - Real height = (offsScalar * distScalar); - - workspace[ (radius + x) + workspaceWidth * (radius + y) ] = height + heightMap->getBilinearSampleSeismicZVelocity( centerX + x, centerY + y ) ;//kaleidoscope - - if ( x != 0 ) // non-zero test prevents cross-shaped double stamp - { - workspace[ (radius - x) + workspaceWidth * (radius + y) ] = height + heightMap->getBilinearSampleSeismicZVelocity( centerX - x, centerY + y ) ; - if ( y != 0 ) - workspace[ (radius - x) + workspaceWidth * (radius - y) ] = height + heightMap->getBilinearSampleSeismicZVelocity( centerX - x, centerY - y ) ; - } - if ( y != 0 ) - workspace[ (radius + x) + workspaceWidth * (radius - y) ] = height + heightMap->getBilinearSampleSeismicZVelocity( centerX + x, centerY - y ) ; - } - } - } - - // stuff the values from the workspace into the heightmap's velocities - for (x = 0; x < workspaceWidth; ++x) - for (Int y = 0; y < workspaceWidth; ++y) - heightMap->setSeismicZVelocity( centerX - radius + x, centerY - radius + y, workspace[ x + workspaceWidth * y ] ); - - delete [] workspace; - - return SEISMIC_STATUS_ACTIVE; - } - else - return SEISMIC_STATUS_ZERO_ENERGY; - } - - virtual Real applyGravityCallback( Real velocityIn ) - { - Real velocityOut = velocityIn; - velocityOut -= 1.5f; - return velocityOut; - } - - -}; -static TestSeismicFilter testSeismicFilter; - - - - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -W3DTerrainVisual::W3DTerrainVisual() -{ - - m_terrainRenderObject = NULL; - m_waterRenderObject = NULL; - TheWaterRenderObj = NULL; - - m_logicHeightMap = NULL; - -#ifdef DO_SEISMIC_SIMULATIONS - m_clientHeightMap = NULL; -#endif - -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -W3DTerrainVisual::~W3DTerrainVisual() -{ - // release our render object - if (TheTerrainRenderObject == m_terrainRenderObject) { - TheTerrainRenderObject = NULL; - } - - delete TheTerrainTracksRenderObjClassSystem; - TheTerrainTracksRenderObjClassSystem=NULL; - - delete TheW3DShadowManager; - TheW3DShadowManager=NULL; - - delete TheSmudgeManager; - TheSmudgeManager=NULL; - - REF_PTR_RELEASE( m_waterRenderObject ); - TheWaterRenderObj=NULL; - REF_PTR_RELEASE( m_terrainRenderObject ); - REF_PTR_RELEASE( m_logicHeightMap ); - -#ifdef DO_SEISMIC_SIMULATIONS - REF_PTR_RELEASE( m_clientHeightMap ); -#endif -} - -//------------------------------------------------------------------------------------------------- -/** init */ -//------------------------------------------------------------------------------------------------- -void W3DTerrainVisual::init( void ) -{ - - // extend - TerrainVisual::init(); - // create a new render object for W3D - m_terrainRenderObject = NEW_REF( HeightMapRenderObjClass, () ); - m_terrainRenderObject->Set_Collision_Type( PICK_TYPE_TERRAIN ); - TheTerrainRenderObject = m_terrainRenderObject; - - if (!TheGlobalData->m_headless) - { - // initialize track drawing system - TheTerrainTracksRenderObjClassSystem = NEW TerrainTracksRenderObjClassSystem; - TheTerrainTracksRenderObjClassSystem->init(W3DDisplay::m_3DScene); - - // initialize object shadow drawing system - TheW3DShadowManager = NEW W3DShadowManager; - TheW3DShadowManager->init(); - - // create a water plane render object - TheWaterRenderObj=m_waterRenderObject = NEW_REF( WaterRenderObjClass, () ); - m_waterRenderObject->init(TheGlobalData->m_waterPositionZ, TheGlobalData->m_waterExtentX, TheGlobalData->m_waterExtentY, W3DDisplay::m_3DScene, (WaterRenderObjClass::WaterType)TheGlobalData->m_waterType); //create a water plane that's 128x128 units - m_waterRenderObject->Set_Position(Vector3(TheGlobalData->m_waterPositionX,TheGlobalData->m_waterPositionY,TheGlobalData->m_waterPositionZ)); //place water in world - - // create smudge rendering system. - TheSmudgeManager = NEW(W3DSmudgeManager); - TheSmudgeManager->init(); - -#ifdef DO_UNIT_TIMINGS -#pragma MESSAGE("********************* WARNING- Doing UNIT TIMINGS. ") -#else - if (TheGlobalData->m_waterType == WaterRenderObjClass::WATER_TYPE_1_FB_REFLECTION) - { // add water render object to the pre-pass scene (to be rendered before main scene) - //W3DDisplay::m_prePass3DScene->Add_Render_Object( m_waterRenderObject); - } - else - { // add water render object to the post-pass scene (to be rendered after main scene) - W3DDisplay::m_3DScene->Add_Render_Object( m_waterRenderObject); - } -#endif - if (TheGlobalData->m_useCloudPlane) - m_waterRenderObject->toggleCloudLayer(true); - else - m_waterRenderObject->toggleCloudLayer(false); - } - - // set the vertex animated water properties - Int waterSettingIndex = 0; // use index 0 settings by default - TheTerrainVisual->setWaterGridHeightClamps( NULL, - TheGlobalData->m_vertexWaterHeightClampLow[ waterSettingIndex ], - TheGlobalData->m_vertexWaterHeightClampHi[ waterSettingIndex ] ); - TheTerrainVisual->setWaterTransform( NULL, - TheGlobalData->m_vertexWaterAngle[ waterSettingIndex ], - TheGlobalData->m_vertexWaterXPosition[ waterSettingIndex ], - TheGlobalData->m_vertexWaterYPosition[ waterSettingIndex ], - TheGlobalData->m_vertexWaterZPosition[ waterSettingIndex ] ); - TheTerrainVisual->setWaterGridResolution( NULL, - TheGlobalData->m_vertexWaterXGridCells[ waterSettingIndex ], - TheGlobalData->m_vertexWaterYGridCells[ waterSettingIndex ], - TheGlobalData->m_vertexWaterGridSize[ waterSettingIndex ] ); - TheTerrainVisual->setWaterAttenuationFactors( NULL, - TheGlobalData->m_vertexWaterAttenuationA[ waterSettingIndex ], - TheGlobalData->m_vertexWaterAttenuationB[ waterSettingIndex ], - TheGlobalData->m_vertexWaterAttenuationC[ waterSettingIndex ], - TheGlobalData->m_vertexWaterAttenuationRange[ waterSettingIndex ] ); - m_isWaterGridRenderingEnabled = FALSE; - -#ifdef DO_SEISMIC_SIMULATIONS - m_seismicSimulationList.clear(); -#endif - -} - -//------------------------------------------------------------------------------------------------- -/** reset */ -//------------------------------------------------------------------------------------------------- -void W3DTerrainVisual::reset( void ) -{ - - // extend - TerrainVisual::reset(); - - m_terrainRenderObject->reset(); - - if (TheW3DShadowManager) - TheW3DShadowManager->Reset(); - - if (TheSmudgeManager) - TheSmudgeManager->reset(); - - if (TheTerrainTracksRenderObjClassSystem) - TheTerrainTracksRenderObjClassSystem->Reset(); - - // reset water render object if present - if( m_waterRenderObject ) - { - for (Int i=0; i<5; i++) - { - //check if this texture was ever changed from default - if (m_currentSkyboxTexNames[i] != m_initialSkyboxTexNames[i]) - { - m_waterRenderObject->replaceSkyboxTexture(m_currentSkyboxTexNames[i], m_initialSkyboxTexNames[i]); - m_currentSkyboxTexNames[i]=m_initialSkyboxTexNames[i]; //update current state to new texture - } - } - - m_waterRenderObject->reset(); - } - -#ifdef DO_SEISMIC_SIMULATIONS - m_seismicSimulationList.clear(); -#endif - -} - -//------------------------------------------------------------------------------------------------- -/** update */ -//------------------------------------------------------------------------------------------------- -void W3DTerrainVisual::update( void ) -{ - - // extend - TerrainVisual::update(); - -#ifdef DO_SEISMIC_SIMULATIONS - handleSeismicSimulations(); -#endif - // if we have a water render object, it has an update method - if( m_waterRenderObject ) - m_waterRenderObject->update(); - -} - - -#ifdef DO_SEISMIC_SIMULATIONS - -void W3DTerrainVisual::addSeismicSimulation( const SeismicSimulationNode& sim ) -{ - // HERE WOULD BE A GREAT PLACE FOR AN IDIOT TEST: - // REJECT SIMULATION NODES THAT ARE OFF SCREEN!!!!!!!!!! - // HERE WOULD BE A GREAT PLACE FOR AN IDIOT TEST: - // REJECT SIMULATION NODES THAT ARE OFF SCREEN!!!!!!!!!! - - - m_seismicSimulationList.push_back( sim ); -} - - - -void W3DTerrainVisual::handleSeismicSimulations( void ) -{ - if ( ! m_clientHeightMap || ! m_logicHeightMap || ! m_terrainRenderObject ) - return; - - - if ( ! m_seismicSimulationList.empty() ) - { - SeismicSimulationListIt it = m_seismicSimulationList.begin(); - - - m_clientHeightMap->clearSeismicUpdateFlags(); - - - while ( it != m_seismicSimulationList.end() ) - { - SeismicSimulationNode *ssn = &*it; - - if ( ssn ) - { - SeismicSimulationFilterBase::SeismicSimStatusCode code = ssn->handleFilterCallback( m_clientHeightMap ); - DEBUG_ASSERTCRASH( code != SeismicSimulationFilterBase::SEISMIC_STATUS_INVALID, ("Trouble in the Seismic simulator.") ); - - switch ( code ) - { - case SeismicSimulationFilterBase::SEISMIC_STATUS_ACTIVE: - { - break; - } - case SeismicSimulationFilterBase::SEISMIC_STATUS_ZERO_ENERGY: - { - break; - } - } - - Int border = m_clientHeightMap->getBorderSizeInline(); - - // Now we apply some gravity to the dirt, so it falls back to its "original" height - UnsignedInt fallCount = 0; - for (Int x = border+ssn->m_region.lo.x; x < border+ssn->m_region.hi.x; ++x) - { - for (Int y = border+ssn->m_region.lo.y; y < border+ssn->m_region.hi.y; ++y) - { - if ( ! m_clientHeightMap->getSeismicUpdateFlag( x, y ) ) - { - UnsignedByte heightOfOriginal = m_logicHeightMap->getHeight( x, y ); // LOGIC, YES DEFINITELY THE LOGIC - - Real oldSpeed = m_clientHeightMap->getSeismicZVelocity( x, y ); - Real newSpeed = ssn->applyGravity( oldSpeed );// - 0.5f; - - m_clientHeightMap->setSeismicZVelocity( x, y, newSpeed ); - - Int heightToUse = m_clientHeightMap->getHeight( x, y ) + newSpeed ; - - - if (heightToUse <= heightOfOriginal) - { - heightToUse = heightOfOriginal; - m_clientHeightMap->setSeismicZVelocity( x, y, 0.0f ); //poof! the dirt hit ground level so stop "falling" - } - else - { - ++fallCount; - - if ( heightToUse > 255 ) - heightToUse = 255; - - } - m_clientHeightMap->setRawHeight( x, y, heightToUse ); - m_clientHeightMap->setSeismicUpdateFlag( x, y, TRUE ); - } - - } - } - - if ( fallCount == 0 ) - ssn->m_clean = TRUE; - - } - - ++it; - - } - } - -} - - /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -void W3DTerrainVisual::updateSeismicSimulations( void ) -{ - - if (m_logicHeightMap==NULL) - return; - - if (m_clientHeightMap==NULL) - return; - - if (m_terrainRenderObject==NULL) - return; - - if ( ! m_seismicSimulationList.empty() ) - { - SeismicSimulationListIt it = m_seismicSimulationList.begin(); - - // First we run through the list and do our business for each region - - while ( it != m_seismicSimulationList.end() ) - { - SeismicSimulationNode *hur = &*it; - if ( hur ) - { - Int border = m_clientHeightMap->getBorderSizeInline(); - - TheTerrainRenderObject->updateBlock( - hur->m_region.lo.x + border, - hur->m_region.lo.y + border, - hur->m_region.hi.x + border, - hur->m_region.hi.y + border, - m_clientHeightMap, - 0); - } - - ++it; - - } - // Then we check to see if these need to get erased from the list - it = m_seismicSimulationList.begin(); - while ( it != m_seismicSimulationList.end() ) - { - SeismicSimulationNode *hur = &*it; - if ( hur->m_clean ) - { - it = m_seismicSimulationList.erase( it ); - } - else - ++it; - - } - - } -} - - -#endif //#defined DO_SEISMIC_SIMULATIONS - /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - - -//------------------------------------------------------------------------------------------------- -/** load method for W3D visual terrain */ -//------------------------------------------------------------------------------------------------- -Bool W3DTerrainVisual::load( AsciiString filename ) -{ - -#if 0 - // (gth) Testing exclusion list asset releasing - DynamicVectorClass exclusion_list(8000); - - WW3DAssetManager::Get_Instance()->Create_Asset_List(exclusion_list); - - exclusion_list.Add(StringClass("avcomanche")); - exclusion_list.Add(StringClass("avcomanche_d")); - exclusion_list.Add(StringClass("ptdogwood08")); - exclusion_list.Add(StringClass("ptdogwood01_b")); - exclusion_list.Add(StringClass("ptpalm01")); - exclusion_list.Add(StringClass("ptpalm01_b")); - exclusion_list.Add(StringClass("avhummer")); - exclusion_list.Add(StringClass("avhummer_d")); - exclusion_list.Add(StringClass("avleopard")); - exclusion_list.Add(StringClass("avleopard_d")); - - WW3DAssetManager::Get_Instance()->Free_Assets_With_Exclusion_List(exclusion_list); -#endif - - // enhancing functionality specific for W3D terrain - if( TerrainVisual::load( filename ) == FALSE ) - return FALSE; // failed - - // open the terrain file - CachedFileInputStream fileStrm; - if( !fileStrm.open(filename) ) - { - - REF_PTR_RELEASE( m_terrainRenderObject ); - return FALSE; - - } - - if( m_terrainRenderObject == NULL ) - return FALSE; - - - ChunkInputStream *pStrm = &fileStrm; - - // allocate new height map data to read from file - REF_PTR_RELEASE( m_logicHeightMap ); - m_logicHeightMap = NEW WorldHeightMap(pStrm); - -#ifdef DO_SEISMIC_SIMULATIONS - - fileStrm.close(); - fileStrm.open(filename); - pStrm = &fileStrm; - - REF_PTR_RELEASE( m_clientHeightMap ); - m_clientHeightMap = NEW WorldHeightMap( pStrm ); - -#endif - - // Add any lights loaded by map. - MapObject *pMapObj = MapObject::getFirstMapObject(); - while (pMapObj) - { - Dict *d = pMapObj->getProperties(); - if (pMapObj->isLight()) - { - Coord3D loc = *pMapObj->getLocation(); - if (loc.z < 0) { - Vector3 vec; - loc.z = m_terrainRenderObject->getHeightMapHeight(loc.x, loc.y, NULL); - loc.z += d->getReal(TheKey_lightHeightAboveTerrain); - } - // It is a light, and handled at the device level. jba. - LightClass* lightP = NEW_REF(LightClass, (LightClass::POINT)); - - RGBColor c; - c.setFromInt(d->getInt(TheKey_lightAmbientColor)); - lightP->Set_Ambient( Vector3( c.red, c.green, c.blue ) ); - - c.setFromInt(d->getInt(TheKey_lightDiffuseColor)); - lightP->Set_Diffuse( Vector3( c.red, c.green, c.blue) ); - - lightP->Set_Position(Vector3(loc.x, loc.y, loc.z)); - - lightP->Set_Far_Attenuation_Range(d->getReal(TheKey_lightInnerRadius), d->getReal(TheKey_lightOuterRadius)); - W3DDisplay::m_3DScene->Add_Render_Object(lightP); - REF_PTR_RELEASE( lightP ); - } - pMapObj = pMapObj->getNext(); - } - - - RefRenderObjListIterator *it = W3DDisplay::m_3DScene ? W3DDisplay::m_3DScene->createLightsIterator() : NULL; - // apply the heightmap to the terrain render object - -#ifdef DO_SEISMIC_SIMULATIONS - m_terrainRenderObject->initHeightData( m_clientHeightMap->getDrawWidth(), - m_clientHeightMap->getDrawHeight(), - m_clientHeightMap, - it); -#else - m_terrainRenderObject->initHeightData( m_logicHeightMap->getDrawWidth(), - m_logicHeightMap->getDrawHeight(), - m_logicHeightMap, - it); -#endif - - - if (it) { - W3DDisplay::m_3DScene->destroyLightsIterator(it); - it = NULL; - } - // add our terrain render object to the scene - if (W3DDisplay::m_3DScene != NULL) - W3DDisplay::m_3DScene->Add_Render_Object( m_terrainRenderObject ); - -#if defined(RTS_DEBUG) - // Icon drawing utility object for pathfinding. - if (W3DDisplay::m_3DScene != NULL) - { - W3DDebugIcons *icons = NEW W3DDebugIcons; - W3DDisplay::m_3DScene->Add_Render_Object( icons ); - icons->Release_Ref(); // belongs to scene. - } -#endif - -#ifdef DO_UNIT_TIMINGS -#pragma MESSAGE("********************* WARNING- Doing UNIT TIMINGS. ") -#else - if (m_waterRenderObject) - { - W3DDisplay::m_3DScene->Add_Render_Object( m_waterRenderObject); - m_waterRenderObject->enableWaterGrid(false); - m_waterRenderObject->updateMapOverrides(); - } -#endif - - pMapObj = MapObject::getFirstMapObject(); - while (pMapObj) - { - Dict *d = pMapObj->getProperties(); - if (pMapObj->isScorch()) { - const Coord3D *pos = pMapObj->getLocation(); - Vector3 loc(pos->x, pos->y, pos->z); - Real radius = d->getReal(TheKey_objectRadius); - Scorches type = (Scorches)d->getInt(TheKey_scorchType); - m_terrainRenderObject->addScorch(loc, radius, type); - } - pMapObj = pMapObj->getNext(); - } - - // reset water render object if present - if( m_waterRenderObject ) - { - m_waterRenderObject->load(); - } - - return TRUE; // success - -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::enableWaterGrid( Bool enable ) -{ - - //Get default water type - m_isWaterGridRenderingEnabled = enable; - - // make the changes in the water render object - if( m_waterRenderObject ) - m_waterRenderObject->enableWaterGrid( enable ); - -} - -//------------------------------------------------------------------------------------------------- -/** intersect the ray with the terrain, if a hit occurs TRUE is returned - * and the result point on the terrain is returned in "result" */ -//------------------------------------------------------------------------------------------------- -Bool W3DTerrainVisual::intersectTerrain( Coord3D *rayStart, - Coord3D *rayEnd, - Coord3D *result ) -{ - Bool hit = FALSE; - - // sanity - if( rayStart == NULL || rayEnd == NULL ) - return hit; - - if( m_terrainRenderObject ) - { - CastResultStruct res; - LineSegClass lineSeg( Vector3( rayStart->x, rayStart->y, rayStart->z ), - Vector3( rayEnd->x, rayEnd->y, rayEnd->z ) ); - RayCollisionTestClass rayTest( lineSeg, &res ); - - hit = m_terrainRenderObject->Cast_Ray( rayTest ); - if( hit && result ) - { - Vector3 point = rayTest.Result->ContactPoint; - - result->x = point.X; - result->y = point.Y; - result->z = point.Z; - - } - - } - - // return hit result - return hit; - -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -void W3DTerrainVisual::getTerrainColorAt( Real x, Real y, RGBColor *pColor ) -{ - -#ifdef DO_SEISMIC_SIMULATIONS - if( m_clientHeightMap ) - m_clientHeightMap->getTerrainColorAt( x, y, pColor ); -#else - if( m_logicHeightMap ) - m_logicHeightMap->getTerrainColorAt( x, y, pColor ); -#endif - -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -TerrainType *W3DTerrainVisual::getTerrainTile( Real x, Real y ) -{ - TerrainType *tile = NULL; - -#ifdef DO_SEISMIC_SIMULATIONS - if( m_clientHeightMap ) - { - AsciiString tileName = m_clientHeightMap->getTerrainNameAt( x, y ); - tile = TheTerrainTypes->findTerrain( tileName ); - } -#else - if( m_logicHeightMap ) - { - AsciiString tileName = m_logicHeightMap->getTerrainNameAt( x, y ); - tile = TheTerrainTypes->findTerrain( tileName ); - } -#endif - - return tile; -} - -// ------------------------------------------------------------------------------------------------ -/** set min/max height values allowed in water grid pointed to by waterTable */ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::setWaterGridHeightClamps( const WaterHandle *waterTable, - Real minZ, Real maxZ ) -{ - - if( m_waterRenderObject ) - m_waterRenderObject->setGridHeightClamps( minZ, maxZ ); - -} - -// ------------------------------------------------------------------------------------------------ -/** adjust fallof parameters for grid change method */ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::setWaterAttenuationFactors( const WaterHandle *waterTable, - Real a, Real b, Real c, Real range ) -{ - - if( m_waterRenderObject ) - m_waterRenderObject->setGridChangeAttenuationFactors( a, b, c, range ); - -} - -// ------------------------------------------------------------------------------------------------ -/** set the water table position and orientation in world space */ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::setWaterTransform( const WaterHandle *waterTable, - Real angle, Real x, Real y, Real z ) -{ - - if( m_waterRenderObject ) - m_waterRenderObject->setGridTransform( angle, x, y, z ); - -} - -// ------------------------------------------------------------------------------------------------ -/** set water table transform by matrix */ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::setWaterTransform( const Matrix3D *transform ) -{ - - if( m_waterRenderObject ) - m_waterRenderObject->setGridTransform( transform ); - -} - -// ------------------------------------------------------------------------------------------------ -/** get the water transform matrix */ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::getWaterTransform( const WaterHandle *waterTable, Matrix3D *transform ) -{ - - if( m_waterRenderObject ) - m_waterRenderObject->getGridTransform( transform ); - -} - -// ------------------------------------------------------------------------------------------------ -/** water grid resolution spacing */ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::setWaterGridResolution( const WaterHandle *waterTable, - Real gridCellsX, Real gridCellsY, Real cellSize ) -{ - - if( m_waterRenderObject ) - m_waterRenderObject->setGridResolution( gridCellsX, gridCellsY, cellSize ); - -} - -// ------------------------------------------------------------------------------------------------ -/** get water grid resolution spacing */ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::getWaterGridResolution( const WaterHandle *waterTable, - Real *gridCellsX, Real *gridCellsY, Real *cellSize ) -{ - - if( m_waterRenderObject ) - m_waterRenderObject->getGridResolution( gridCellsX, gridCellsY, cellSize ); - -} - -// ------------------------------------------------------------------------------------------------ -/** adjust the water grid in world coords by the delta */ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::changeWaterHeight( Real x, Real y, Real delta ) -{ - - if( m_waterRenderObject ) - m_waterRenderObject->changeGridHeight( x, y, delta ); - -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::addWaterVelocity( Real worldX, Real worldY, - Real velocity, Real preferredHeight ) -{ - - if( m_waterRenderObject ) - m_waterRenderObject->addVelocity( worldX, worldY, velocity, preferredHeight ); - -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -Bool W3DTerrainVisual::getWaterGridHeight( Real worldX, Real worldY, Real *height) -{ - Real gridX, gridY; - - if (m_isWaterGridRenderingEnabled && m_waterRenderObject && - m_waterRenderObject->worldToGridSpace(worldX, worldY, gridX, gridY)) - { //point falls within grid, return correct height - m_waterRenderObject->getGridVertexHeight(REAL_TO_INT(gridX),REAL_TO_INT(gridY),height); - return TRUE; - } - return FALSE; -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::setRawMapHeight(const ICoord2D *gridPos, Int height) -{ - // This method writes to the m_logicHeightMap member, - // since m_logicHeightMap is the true, golden standard to which m_clientHeightMap - // interpolates during or after its Seismic simulation displaces it.. - // THIS IS TRUE ONLY WHEN DO_SEISMIC_SIMULATIONS is defined M Lorenzen, 8/23/03 - - if (m_logicHeightMap) - { - Int x = gridPos->x+m_logicHeightMap->getBorderSizeInline(); - Int y = gridPos->y+m_logicHeightMap->getBorderSizeInline(); - //if (m_logicHeightMap->getHeight(x,y) != height) //ML changed to prevent scissoring with roads - if (m_logicHeightMap->getHeight(x,y) > height) - { - m_logicHeightMap->setRawHeight(x, y, height); - m_terrainRenderObject->staticLightingChanged(); // OOH! this could benefit from the new Seismic update code - - -#ifdef DO_SEISMIC_SIMULATIONS - if ( m_clientHeightMap ) - { - if ( height < m_clientHeightMap->getHeight( x,y ) ) - m_clientHeightMap->setRawHeight( x, y, height ); // if the client map is heigher than this height, it will fall down to it anyway! - } -#endif - - } - } -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -Int W3DTerrainVisual::getRawMapHeight(const ICoord2D *gridPos) -{ - if (m_logicHeightMap) - { - Int x = gridPos->x+m_logicHeightMap->getBorderSizeInline(); - Int y = gridPos->y+m_logicHeightMap->getBorderSizeInline(); - //if (m_logicHeightMap->getHeight(x,y) != height) //ML changed to prevent scissoring with roads - return m_logicHeightMap->getHeight(x,y) ; - } - return 0; - -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::addFactionBibDrawable(Drawable *factionBuilding, Bool highlight, Real extra) -{ -#ifdef DO_SEISMIC_SIMULATIONS - if (m_clientHeightMap) -#else - if (m_logicHeightMap) -#endif - { - const Matrix3D * mtx = factionBuilding->getTransformMatrix(); - Vector3 corners[4]; - Coord3D pos; - pos.set(0,0,0); - Real exitWidth = factionBuilding->getTemplate()->getFactoryExitWidth(); - Real extraWidth = factionBuilding->getTemplate()->getFactoryExtraBibWidth() + extra; - const GeometryInfo info = factionBuilding->getTemplate()->getTemplateGeometryInfo(); - Real sizeX = info.getMajorRadius(); - Real sizeY = info.getMinorRadius(); - if (info.getGeomType() != GEOMETRY_BOX) { - sizeY = sizeX; - } - corners[0].Set(pos.x, pos.y, pos.z); - corners[0].X -= sizeX+extraWidth; - corners[0].Y -= sizeY+extraWidth; - corners[1].Set(pos.x, pos.y, pos.z); - corners[1].X += sizeX+exitWidth+extraWidth; - corners[1].Y -= sizeY+extraWidth; - corners[2].Set(pos.x, pos.y, pos.z); - corners[2].X += sizeX+exitWidth+extraWidth; - corners[2].Y += sizeY+extraWidth; - corners[3].Set(pos.x, pos.y, pos.z); - corners[3].X -= sizeX+extraWidth; - corners[3].Y += sizeY+extraWidth; - mtx->Transform_Vector(*mtx, corners[0], &corners[0]); - mtx->Transform_Vector(*mtx, corners[1], &corners[1]); - mtx->Transform_Vector(*mtx, corners[2], &corners[2]); - mtx->Transform_Vector(*mtx, corners[3], &corners[3]); - m_terrainRenderObject->addTerrainBibDrawable(corners, factionBuilding->getID(), highlight); - } -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::addFactionBib(Object *factionBuilding, Bool highlight, Real extra) -{ -#ifdef DO_SEISMIC_SIMULATIONS - if (m_clientHeightMap) -#else - if (m_logicHeightMap) -#endif - { - const Matrix3D * mtx = factionBuilding->getTransformMatrix(); - Vector3 corners[4]; - Coord3D pos; - pos.set(0,0,0); - Real exitWidth = factionBuilding->getTemplate()->getFactoryExitWidth(); - Real extraWidth = factionBuilding->getTemplate()->getFactoryExtraBibWidth() + extra; - const GeometryInfo info = factionBuilding->getGeometryInfo(); - Real sizeX = info.getMajorRadius(); - Real sizeY = info.getMinorRadius(); - if (info.getGeomType() != GEOMETRY_BOX) { - sizeY = sizeX; - } - corners[0].Set(pos.x, pos.y, pos.z); - corners[0].X -= sizeX+extraWidth; - corners[0].Y -= sizeY+extraWidth; - corners[1].Set(pos.x, pos.y, pos.z); - corners[1].X += sizeX+exitWidth+extraWidth; - corners[1].Y -= sizeY+extraWidth; - corners[2].Set(pos.x, pos.y, pos.z); - corners[2].X += sizeX+exitWidth+extraWidth; - corners[2].Y += sizeY+extraWidth; - corners[3].Set(pos.x, pos.y, pos.z); - corners[3].X -= sizeX+extraWidth; - corners[3].Y += sizeY+extraWidth; - mtx->Transform_Vector(*mtx, corners[0], &corners[0]); - mtx->Transform_Vector(*mtx, corners[1], &corners[1]); - mtx->Transform_Vector(*mtx, corners[2], &corners[2]); - mtx->Transform_Vector(*mtx, corners[3], &corners[3]); - m_terrainRenderObject->addTerrainBib(corners, factionBuilding->getID(), highlight); - } -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::removeFactionBibDrawable(Drawable *factionBuilding) -{ - if (m_terrainRenderObject) { - m_terrainRenderObject->removeTerrainBibDrawable(factionBuilding->getID()); - } -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::removeFactionBib(Object *factionBuilding) -{ - if (m_terrainRenderObject) { - m_terrainRenderObject->removeTerrainBib(factionBuilding->getID()); - } -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::removeAllBibs(void) -{ - if (m_terrainRenderObject) { - m_terrainRenderObject->removeAllTerrainBibs(); - } -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::removeBibHighlighting(void) -{ - if (m_terrainRenderObject) { - m_terrainRenderObject->removeTerrainBibHighlighting(); - } -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::removeTreesAndPropsForConstruction(const Coord3D* pos, - const GeometryInfo& geom, - Real angle) -{ - if (m_terrainRenderObject) { - m_terrainRenderObject->removeTreesAndPropsForConstruction(pos, geom, angle); - } -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::addProp(const ThingTemplate *tTemplate, const Coord3D *pos, Real angle) -{ - ModelConditionFlags state; - state.clear(); - if (TheGlobalData->m_weather == WEATHER_SNOWY) - { - state.set(MODELCONDITION_SNOW); - } - if (TheGlobalData->m_timeOfDay == TIME_OF_DAY_NIGHT) - { - state.set(MODELCONDITION_NIGHT); - } - AsciiString modelName; - Real scale = tTemplate->getAssetScale(); - const ModuleInfo& mi = tTemplate->getDrawModuleInfo(); - if (mi.getCount() > 0) - { - const ModuleData* mdd = mi.getNthData(0); - const W3DModelDrawModuleData* md = mdd ? mdd->getAsW3DModelDrawModuleData() : NULL; - if (md) - { - modelName = md->getBestModelNameForWB(state); - } - } - if (m_terrainRenderObject && modelName.isNotEmpty()) { - m_terrainRenderObject->addProp(1, *pos, angle, scale, modelName); - } -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::setTerrainTracksDetail(void) -{ - if (TheTerrainTracksRenderObjClassSystem) - TheTerrainTracksRenderObjClassSystem->setDetail(); -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::setShoreLineDetail(void) -{ - if (m_terrainRenderObject) - m_terrainRenderObject->setShoreLineDetail(); -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -/// Replace the skybox texture -void W3DTerrainVisual::replaceSkyboxTextures(const AsciiString *oldTexName[5], const AsciiString *newTexName[5]) -{ - if (m_waterRenderObject) - { - for (Int i=0; i<5; i++) - { - //check if this texture was never changed before and is still using the default art. - if (m_initialSkyboxTexNames[i].isEmpty()) - { m_initialSkyboxTexNames[i]=*oldTexName[i]; - m_currentSkyboxTexNames[i]=*oldTexName[i]; - } - - if (m_currentSkyboxTexNames[i] != *newTexName[i]) - { m_waterRenderObject->replaceSkyboxTexture(m_currentSkyboxTexNames[i], *newTexName[i]); - m_currentSkyboxTexNames[i]=*newTexName[i]; //update current state to new texture - } - } - } -} - -// ------------------------------------------------------------------------------------------------ -/** CRC */ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::crc( Xfer *xfer ) -{ - - // extend base class - TerrainVisual::crc( xfer ); - -} - -// ------------------------------------------------------------------------------------------------ -/** Xfer - * Version Info: - * 1: Initial version - * 2: Add height map heights. - * 3: Add client side trees & props. jba. (Added for Zero Hour) -*/ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::xfer( Xfer *xfer ) -{ - - // version -#if RTS_GENERALS && RETAIL_COMPATIBLE_XFER_SAVE - XferVersion currentVersion = 2; -#else - XferVersion currentVersion = 3; -#endif - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // extend base class - TerrainVisual::xfer( xfer ); - - // flag for whether or not the water grid is enabled - Bool gridEnabled = m_isWaterGridRenderingEnabled; - xfer->xferBool( &gridEnabled ); - if( gridEnabled != m_isWaterGridRenderingEnabled ) - { - - DEBUG_CRASH(( "W3DTerrainVisual::xfer - m_isWaterGridRenderingEnabled mismatch" )); - throw SC_INVALID_DATA; - - } - - // xfer grid data if enabled - if( gridEnabled ) - xfer->xferSnapshot( m_waterRenderObject ); - -/* - { - - // grid width and height - Int width = getGridWidth(); - Int height = getGridheight(); - xfer->xferInt( &width ); - xfer->xferInt( &height ); - if( width != getGridWidth() ) - { - - DEBUG_CRASH(( "W3DTerainVisual::xfer - grid width mismatch '%d' should be '%d'", - width, getGridWidth() )); - throw SC_INVALID_DATA; - - } - if( height != getGridHeight() ) - { - - DEBUG_CRASH(( "W3DTerainVisual::xfer - grid height mismatch '%d' should be '%d'", - height, getGridHeight() )); - throw SC_INVALID_DATA; - - } - - // write data for each grid - - } -*/ - - // Write out the terrain height data. - if (version >= 2) { - UnsignedByte *data = m_logicHeightMap->getDataPtr(); - Int len = m_logicHeightMap->getXExtent()*m_logicHeightMap->getYExtent(); - Int xferLen = len; - xfer->xferInt(&xferLen); - if (len!=xferLen) { - DEBUG_CRASH(("Bad height map length.")); - if (len>xferLen) { - len = xferLen; - } - } - xfer->xferUser(data, len); - if (xfer->getXferMode() == XFER_LOAD) - { - // Update the display height map. - m_terrainRenderObject->staticLightingChanged(); - } - } - - if (version >= 3) { - xfer->xferSnapshot(m_terrainRenderObject); - } - - // XFER // - // X R // - // X R // - // XFER // - ///// /USE CLIENT HEIGHT MAPCLIENT HEIGHT MAP -// // /USE CLIENT HEIGHT MAPCLIENT HEIGHT MAP -// ////USE CLIENT HEIGHT MAPCLIENT HEIGHT MAP---------------------------- -// // /USE CLIENT HEIGHT MAPCLIENT HEIGHT MAP ^ - ///// /USE CLIENT HEIGHT MAPCLIENT HEIGHT MAP 0 - // XFER // - // X R // - // X R // - // XFER // - -} - -// ------------------------------------------------------------------------------------------------ -/** Load post process */ -// ------------------------------------------------------------------------------------------------ -void W3DTerrainVisual::loadPostProcess( void ) -{ - - // extend base class - TerrainVisual::loadPostProcess(); - -} - diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp deleted file mode 100644 index 294e6db54a..0000000000 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp +++ /dev/null @@ -1,2040 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public 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: W3DTreeBuffer.cpp //////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: W3DTreeBuffer.cpp -// -// Created: John Ahlquist, May 2001 -// -// Desc: Draw buffer to handle all the trees in a scene. -// -//----------------------------------------------------------------------------- - -// ------------------------------------------------------------------------------------------------ -/** Topple options */ -// ------------------------------------------------------------------------------------------------ -enum -{ - W3D_TOPPLE_OPTIONS_NONE = 0x00000000, - W3D_TOPPLE_OPTIONS_NO_BOUNCE = 0x00000001, ///< do not bounce when hit the ground - W3D_TOPPLE_OPTIONS_NO_FX = 0x00000002 ///< do not play any FX when hit the ground -}; -//----------------------------------------------------------------------------- -// Includes -//----------------------------------------------------------------------------- -#include "W3DDevice/GameClient/W3DTreeBuffer.h" - -#include -#include -#include "Common/FramePacer.h" -#include "Common/GameUtility.h" -#include "Common/MapReaderWriterInfo.h" -#include "Common/FileSystem.h" -#include "Common/file.h" -#include "Common/PerfTimer.h" -#include "Common/Player.h" -#include "Common/PlayerList.h" -#include "GameLogic/ScriptEngine.h" -#include "GameLogic/GameLogic.h" -#include "GameLogic/Object.h" -#include "GameLogic/PartitionManager.h" -#include "GameClient/ClientRandomValue.h" -#include "GameClient/FXList.h" -#include "W3DDevice/GameClient/TerrainTex.h" -#include "W3DDevice/GameClient/HeightMap.h" -#include "W3DDevice/GameClient/W3DDynamicLight.h" -#include "W3DDevice/GameClient/Module/W3DTreeDraw.h" -#include "W3DDevice/GameClient/W3DShaderManager.h" -#include "W3DDevice/GameClient/W3DShadow.h" -#include "W3DDevice/GameClient/W3DShroud.h" -#include "W3DDevice/GameClient/W3DProjectedShadow.h" -#include "WW3D2/camera.h" -#include "WW3D2/dx8wrapper.h" -#include "WW3D2/dx8renderer.h" -#include "WW3D2/matinfo.h" -#include "WW3D2/mesh.h" -#include "WW3D2/meshmdl.h" -#include "d3dx8tex.h" - - -// If TEST_AND_BLEND is defined, it will do an alpha test and blend. Otherwise just alpha test. jba. [5/30/2003] -#define dontTEST_AND_BLEND 1 - -#define USE_STATIC 1 - -#define END_OF_PARTITION (-1) - -#define DELETED_TREE_TYPE (-2) - -/****************************************************************************** - W3DTreeTextureClass -******************************************************************************/ -//----------------------------------------------------------------------------- -// Public Functions -//----------------------------------------------------------------------------- - -//============================================================================= -// W3DTreeBuffer::W3DTreeTextureClass::W3DTreeTextureClass -//============================================================================= -/** Constructor. Calls parent constructor to create a 16 bit per pixel D3D -texture of the desired height and mip level. */ -//============================================================================= -W3DTreeBuffer::W3DTreeTextureClass::W3DTreeTextureClass(unsigned width, unsigned height) : - TextureClass(width, height, - WW3D_FORMAT_A8R8G8B8, MIP_LEVELS_ALL ) -{ -} - -//============================================================================= -// W3DTreeBuffer::W3DTreeTextureClass::update -//============================================================================= -/** Sets the tile bitmap data into the texture. The tiles are placed with 4 - pixel borders around them, so that when the tiles are scaled and bilinearly - interpolated, you don't get seams between the tiles. */ -//============================================================================= -int W3DTreeBuffer::W3DTreeTextureClass::update(W3DTreeBuffer *buffer) -{ - - //Set to clamp. - Get_Filter().Set_U_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); - Get_Filter().Set_V_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); - - IDirect3DSurface8 *surface_level; - D3DSURFACE_DESC surface_desc; - D3DLOCKED_RECT locked_rect; - DX8_ErrorCode(Peek_D3D_Texture()->GetSurfaceLevel(0, &surface_level)); - DX8_ErrorCode(surface_level->GetDesc(&surface_desc)); - - DX8_ErrorCode(surface_level->LockRect(&locked_rect, NULL, 0)); - - Int tilePixelExtent = TILE_PIXEL_EXTENT; -// Int numRows = surface_desc.Height/(tilePixelExtent+TILE_OFFSET); -#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 - if (surface_desc.Format == D3DFMT_A8R8G8B8) { - Int tileNdx; - Int pixelBytes = 4; -#if 0 // Fill unused texture for debug display. - UnsignedInt cellX, cellY; - for (cellX = 0; cellX < surface_desc.Width; cellX++) { - for (cellY = 0; cellY < surface_desc.Height; cellY++) { - UnsignedByte *pBGR = ((UnsignedByte *)locked_rect.pBits)+(cellY*surface_desc.Width+cellX)*pixelBytes; - //*((Short*)pBGR) = 0x8000 + (((255-2*cellY)>>3)<<10) + ((4*cellX)>>4); - *((Int*)pBGR) = 0xFF000000 | ( (((255-cellY))<<16) + ((cellX)) ); - - } - } -#endif - for (tileNdx=0; tileNdx < buffer->getNumTiles(); tileNdx++) { - TileData *pTile = buffer->getSourceTile(tileNdx); - if (!pTile) continue; - ICoord2D position = pTile->m_tileLocationInTexture; - if (position.x<0) { - continue; - } - Int i,j; - for (j=0; jgetRGBDataForWidth(tilePixelExtent); - pBGR += (tilePixelExtent-(1+j))*TILE_BYTES_PER_PIXEL*tilePixelExtent; // invert to match. - Int row = position.y+j; - UnsignedByte *pBGRA = ((UnsignedByte*)locked_rect.pBits) + - (row)*surface_desc.Width*pixelBytes; - - Int column = position.x; - pBGRA += column*pixelBytes; - for (i=0; i>3)<<10) + ((pBGR[1]>>3)<<5) + (pBGR[0]>>3); - *((Int *)pBGRA) = (pBGR[3]<<24) + (pBGR[2]<<16) + (pBGR[1]<<8) + (pBGR[0]); - pBGRA +=pixelBytes; - pBGR +=TILE_BYTES_PER_PIXEL; - } - } - } - - } - DX8_ErrorCode(surface_level->UnlockRect()); - surface_level->Release(); - DX8_ErrorCode(D3DXFilterTexture(Peek_D3D_Texture(), NULL, (UINT)0, D3DX_FILTER_BOX)); - if (WW3D::Get_Texture_Reduction()) { - DX8_ErrorCode(Peek_D3D_Texture()->SetLOD((DWORD)WW3D::Get_Texture_Reduction())); - } - return(surface_desc.Height); -} - - -//============================================================================= -// W3DTreeBuffer::W3DTreeTextureClass::setLOD -//============================================================================= -/** Sets the lod of the texture to be loaded into the video card. */ -//============================================================================= -void W3DTreeBuffer::W3DTreeTextureClass::setLOD(Int LOD) const -{ - if (Peek_D3D_Texture()) { - DX8_ErrorCode(Peek_D3D_Texture()->SetLOD((DWORD)LOD)); - } -} -//============================================================================= -// W3DTreeBuffer::W3DTreeTextureClass::Apply -//============================================================================= -/** Sets the texture as the current D3D texture, and does some custom setup -(standard D3D setup, but beyond the scope of W3D). */ -//============================================================================= -void W3DTreeBuffer::W3DTreeTextureClass::Apply(unsigned int stage) -{ - // Do the base apply. - TextureClass::Apply(stage); -} -//----------------------------------------------------------------------------- -// Private Data -//----------------------------------------------------------------------------- - -#ifdef TEST_AND_BLEND -// A W3D shader that does alpha, texturing, tests zbuffer, doesn't update zbuffer. -#define SC_ALPHA_DETAIL ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_ENABLE, ShaderClass::COLOR_WRITE_ENABLE, ShaderClass::SRCBLEND_SRC_ALPHA, \ - ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE, ShaderClass::SECONDARY_GRADIENT_DISABLE, ShaderClass::TEXTURING_ENABLE, \ - ShaderClass::ALPHATEST_ENABLE, ShaderClass::CULL_MODE_ENABLE, \ - ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE) ) - -#define SC_ALPHA_DETAIL_2X ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_ENABLE, ShaderClass::COLOR_WRITE_ENABLE, ShaderClass::SRCBLEND_SRC_ALPHA, \ - ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE2X, ShaderClass::SECONDARY_GRADIENT_DISABLE, ShaderClass::TEXTURING_ENABLE, \ - ShaderClass::ALPHATEST_ENABLE, ShaderClass::CULL_MODE_ENABLE, \ - ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE) ) - -#else -#define SC_ALPHA_DETAIL ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_ENABLE, ShaderClass::COLOR_WRITE_ENABLE, ShaderClass::SRCBLEND_ONE, \ - ShaderClass::DSTBLEND_ZERO, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE, ShaderClass::SECONDARY_GRADIENT_DISABLE, ShaderClass::TEXTURING_ENABLE, \ - ShaderClass::ALPHATEST_ENABLE, ShaderClass::CULL_MODE_DISABLE, \ - ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE) ) - -#define SC_ALPHA_DETAIL_2X ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_ENABLE, ShaderClass::COLOR_WRITE_ENABLE, ShaderClass::SRCBLEND_ONE, \ - ShaderClass::DSTBLEND_ZERO, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE2X, ShaderClass::SECONDARY_GRADIENT_DISABLE, ShaderClass::TEXTURING_ENABLE, \ - ShaderClass::ALPHATEST_ENABLE, ShaderClass::CULL_MODE_ENABLE, \ - ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE) ) -#endif -static ShaderClass detailAlphaShader(SC_ALPHA_DETAIL); -static ShaderClass detailAlphaShader2X(SC_ALPHA_DETAIL_2X); - - -/* -#define SC_ALPHA_DETAIL ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_ENABLE, ShaderClass::COLOR_WRITE_ENABLE, ShaderClass::SRCBLEND_ONE, \ - ShaderClass::DSTBLEND_ZERO, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE, ShaderClass::SECONDARY_GRADIENT_DISABLE, ShaderClass::TEXTURING_ENABLE, \ - ShaderClass::ALPHATEST_ENABLE, ShaderClass::CULL_MODE_DISABLE, \ - ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE) ) - -static ShaderClass detailAlphaShader(SC_ALPHA_DETAIL); -*/ - -/* -#define SC_ALPHA_DETAIL ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_DISABLE, ShaderClass::COLOR_WRITE_ENABLE, ShaderClass::SRCBLEND_SRC_ALPHA, \ - ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE, ShaderClass::SECONDARY_GRADIENT_DISABLE, ShaderClass::TEXTURING_ENABLE, \ - ShaderClass::ALPHATEST_ENABLE, ShaderClass::CULL_MODE_ENABLE, \ - ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE) ) - -static ShaderClass detailAlphaShader(SC_ALPHA_DETAIL); -*/ - -/* -#define SC_ALPHA_MIRROR ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_DISABLE, ShaderClass::COLOR_WRITE_ENABLE, ShaderClass::SRCBLEND_SRC_ALPHA, \ - ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE, ShaderClass::SECONDARY_GRADIENT_DISABLE, ShaderClass::TEXTURING_ENABLE, \ - ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE, ShaderClass::ALPHATEST_DISABLE, ShaderClass::CULL_MODE_DISABLE, \ - ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE) ) - -static ShaderClass mirrorAlphaShader(SC_ALPHA_DETAIL); - -// ShaderClass::PASS_ALWAYS, - -#define SC_ALPHA_2D ( SHADE_CNST(PASS_ALWAYS, DEPTH_WRITE_DISABLE, COLOR_WRITE_ENABLE, \ - SRCBLEND_SRC_ALPHA, DSTBLEND_ONE_MINUS_SRC_ALPHA, FOG_DISABLE, GRADIENT_DISABLE, \ - SECONDARY_GRADIENT_DISABLE, TEXTURING_ENABLE, DETAILCOLOR_DISABLE, DETAILALPHA_DISABLE, \ - ALPHATEST_DISABLE, CULL_MODE_ENABLE, DETAILCOLOR_DISABLE, DETAILALPHA_DISABLE) ) -ShaderClass ShaderClass::_PresetAlpha2DShader(SC_ALPHA_2D); -*/ -//----------------------------------------------------------------------------- -// Private Functions -//----------------------------------------------------------------------------- - -//============================================================================= -// W3DTreeBuffer::cull -//============================================================================= -/** Culls the trees, marking the visible flag. If a tree becomes visible, it sets -it's sortKey */ -//============================================================================= -void W3DTreeBuffer::cull(const CameraClass * camera) -{ - Int curTree; - - // Calulate the vector direction that the camera is looking at. - Matrix3D camera_matrix = camera->Get_Transform(); - float zmod = -1; - float x = zmod * camera_matrix[0][2] ; - float y = zmod * camera_matrix[1][2] ; - float z = zmod * camera_matrix[2][2] ; - m_cameraLookAtVector.Set(x,y,z); - - for (curTree=0; curTreeCull_Sphere(m_trees[curTree].bounds); - if (visible != m_trees[curTree].visible) { - m_trees[curTree].visible=visible; - m_anythingChanged = true; - if (visible) { - doKey = true; - } - } - // Also calculate sort key if a tree is visible, and the view changed setting m_updateAllKeys to true. - if (doKey || (visible&&m_updateAllKeys)) { - // The sort key is essentially the distance of location in the direction of the - // camera look at. - m_trees[curTree].sortKey = Vector3::Dot_Product(m_trees[curTree].location, m_cameraLookAtVector); - } - } - m_updateAllKeys = false; -} -//============================================================================= -// W3DTreeBuffer::cullMirror -//============================================================================= -/** Culls the trees, marking the visible flag for the mirror view. Unlike cull(), -doesn't update anything except the visible flag. */ -//============================================================================= -Int W3DTreeBuffer::getPartitionBucket(const Coord3D &pos) const -{ - Real x = pos.x; - Real y = pos.y; - if (xm_bounds.hi.x) x = m_bounds.hi.x; - if (y>m_bounds.hi.y) y = m_bounds.hi.y; - Int xIndex = REAL_TO_INT_FLOOR ( (x/(m_bounds.hi.x-m_bounds.lo.x)) * (PARTITION_WIDTH_HEIGHT-0.1f) ); - Int yIndex = REAL_TO_INT_FLOOR ( (y/(m_bounds.hi.y-m_bounds.lo.y)) * (PARTITION_WIDTH_HEIGHT-0.1f) ); - DEBUG_ASSERTCRASH(xIndex>=0 && yIndex>=0 && xIndex m_trees[i].sortKey) { - TTree tmp = m_trees[cur]; - m_trees[cur] = m_trees[i]; - m_trees[i] = tmp; - swap = true; - } - cur = i; - } - } - if (!swap) { - return; - } - m_anythingChanged = true; - } -} -#endif - -/********** GDIFileStream2 class ****************************/ -class GDIFileStream2 : public InputStream -{ -protected: - File* m_file; -public: - GDIFileStream2():m_file(NULL) {}; - GDIFileStream2(File* pFile):m_file(pFile) {}; - virtual Int read(void *pData, Int numBytes) { - return(m_file?m_file->read(pData, numBytes):0); - }; -}; - -//============================================================================= -// W3DTreeBuffer::updateTexture -//============================================================================= -/** Creates a new texture. */ -//============================================================================= -void W3DTreeBuffer::updateTexture(void) -{ - - const Int MAX_TEX_WIDTH = 2048; - - Int i, j; - Int maxHeight = 0; - const Int maxTilesPerRow = MAX_TEX_WIDTH/(TILE_PIXEL_EXTENT); - - REF_PTR_RELEASE(m_treeTexture); - - Bool availableGrid[maxTilesPerRow][maxTilesPerRow]; - Int row, column; - for (row=0; rowm_textureName.str() ); - theFile = TheFileSystem->openFile( texturePath, File::READ|File::BINARY); - if (theFile==NULL) { - sprintf( texturePath, "%s%s", TGA_DIR_PATH, m_treeTypes[i].m_data->m_textureName.str() ); - theFile = TheFileSystem->openFile( texturePath, File::READ|File::BINARY); - } - if (theFile != NULL) { - GDIFileStream2 theStream(theFile); - InputStream *pStr = &theStream; - Bool halfTile; - Int numTiles = WorldHeightMap::countTiles(pStr, &halfTile); - Int width; - for (width = 10; width >= 1; width--) { - if (numTiles >= width*width) { - numTiles = width*width; - break; - } - } - Bool texFound = false; - for (j=0; jm_textureName.compareNoCase(m_treeTypes[i].m_data->m_textureName)==0) { - m_treeTypes[i].m_firstTile = 0; - m_treeTypes[i].m_tileWidth = width; - m_treeTypes[i].m_numTiles = 0; - texFound = true; - break; - } - } - if (texFound) { - theFile->close(); - continue; - } - if (m_numTiles+numTiles<=MAX_TILES) { - theFile->seek(0, File::START); - m_treeTypes[i].m_firstTile = m_numTiles; - m_treeTypes[i].m_tileWidth = width; - m_treeTypes[i].m_numTiles = numTiles; - m_treeTypes[i].m_halfTile = halfTile; - WorldHeightMap::readTiles(pStr, m_sourceTiles+m_treeTypes[i].m_firstTile, width); - m_numTiles += numTiles; - } else { - m_treeTypes[i].m_firstTile = 0; - m_treeTypes[i].m_tileWidth = 0; - m_treeTypes[i].m_numTiles = 0; - } - theFile->close(); - } else { - DEBUG_CRASH(("Could not find texture %s", m_treeTypes[i].m_data->m_textureName.str())); - m_treeTypes[i].m_firstTile = 0; - m_treeTypes[i].m_tileWidth = 0; - m_treeTypes[i].m_numTiles = 0; - } - } - - Int tmpWidth = 8; - while (tmpWidth*tmpWidthMAX_TEX_WIDTH) { - m_textureWidth = 64; - m_textureHeight = 64; - if (m_treeTexture==NULL) { - m_treeTexture = new TextureClass("missing.tga"); - } - DEBUG_CRASH(("Too many trees in a scene.")); - return; - } - - for (i=0; im_tileLocationInTexture.x = -1; - m_sourceTiles[i]->m_tileLocationInTexture.y = -1; - } - } - - /* put the tree tiles into the texture */ - Int texClass; - Int tileWidth; - for (tileWidth = tilesPerRow; tileWidth>0; tileWidth--) { - for (texClass=0; texClassm_textureName.compareNoCase(m_treeTypes[texClass].m_data->m_textureName)==0) { - m_treeTypes[texClass].m_textureOrigin.x = m_treeTypes[i].m_textureOrigin.x; - m_treeTypes[texClass].m_textureOrigin.y = m_treeTypes[i].m_textureOrigin.y; - texFound = true; - break; - } - } - if (texFound) { - continue; - } - - // Find an available block of space. - Bool found = false; - for (row=0; row<(tilesPerRow-width)+1 && !found; row++) { - for (column=0; column<(tilesPerRow-width)+1 && !found; column++) { - if (availableGrid[row][column]) { - Bool open = true; - for (i=0; im_tileLocationInTexture.x = x; - m_sourceTiles[baseNdx]->m_tileLocationInTexture.y = y; - } - } - } - } - DEBUG_ASSERTCRASH(maxHeight<=m_textureWidth, ("Bad max height.")); - W3DTreeTextureClass *tex = new W3DTreeTextureClass((DWORD)m_textureWidth, (DWORD)m_textureWidth); - m_textureHeight = tex->update(this); - - m_treeTexture = tex; - - for (i=0; isetLOD(lod); -} - -//============================================================================= -// W3DTreeBuffer::doLighting -//============================================================================= -/** Calculates the diffuse lighting as affected by dynamic lighting. */ -//============================================================================= -UnsignedInt W3DTreeBuffer::doLighting(const Vector3 *normal, - const GlobalData::TerrainLighting *objectLighting, - const Vector3 *emissive, UnsignedInt vertDiffuse, Real scale) const -{ - - Real shadeR, shadeG, shadeB; - Real shade; - shadeR = objectLighting[0].ambient.red+emissive->X; //only the first light contributes to ambient - shadeG = objectLighting[0].ambient.green+emissive->Y; - shadeB = objectLighting[0].ambient.blue+emissive->Z; - - Int i; - for (i=0; i 1.0) shade = 1.0; - if(shade < 0.0f) shade = 0.0f; - shadeR += shade*objectLighting[i].diffuse.red; - shadeG += shade*objectLighting[i].diffuse.green; - shadeB += shade*objectLighting[i].diffuse.blue; - } - - shadeR *= scale; - shadeG *= scale; - shadeB *= scale; - - if (shadeR > 1.0) shadeR = 1.0; - if(shadeR < 0.0f) shadeR = 0.0f; - if (shadeG > 1.0) shadeG = 1.0; - if(shadeG < 0.0f) shadeG = 0.0f; - if (shadeB > 1.0) shadeB = 1.0; - if(shadeB < 0.0f) shadeB = 0.0f; - - if (vertDiffuse!=0xFFFFFFFF) { - shade = vertDiffuse&0xff; //blue; - shadeB *= shade/255.0f; - shade = (vertDiffuse>>8)&0xFF; // green; - shadeG *= shade/255.0f; - shade = (vertDiffuse>>16)&0xFF; // red; - shadeR *= shade/255.0f; - } - - shadeR*=255.0f; - shadeG*=255.0f; - shadeB*=255.0f; - const Real alpha = 255.0; - return REAL_TO_UNSIGNEDINT(shadeB) | (REAL_TO_INT(shadeG) << 8) | (REAL_TO_INT(shadeR) << 16) | ((Int)alpha << 24); - -} - -//============================================================================= -// W3DTreeBuffer::loadTreesInVertexAndIndexBuffers -//============================================================================= -/** Loads the trees into the vertex buffer for drawing. */ -//============================================================================= -void W3DTreeBuffer::loadTreesInVertexAndIndexBuffers(RefRenderObjListIterator *pDynamicLightsIterator) -{ - if (!m_indexTree[0] || !m_vertexTree[0] || !m_initialized) { - return; - } - if (!m_anythingChanged) { - return; - } - - if (m_shadow == NULL && TheW3DProjectedShadowManager) { - Shadow::ShadowTypeInfo shadowInfo; - shadowInfo.m_ShadowName[0] = 0; - shadowInfo.allowUpdates=FALSE; //shadow image will never update - shadowInfo.allowWorldAlign=TRUE; //shadow image will wrap around world objects - shadowInfo.m_type = (ShadowType)SHADOW_DECAL; - shadowInfo.m_sizeX=20; - shadowInfo.m_sizeY=20; - shadowInfo.m_offsetX=0; - shadowInfo.m_offsetY=0; - m_shadow = TheW3DProjectedShadowManager->createDecalShadow(&shadowInfo); - } - - m_anythingChanged = false; - Int curTree=0; - Int bNdx; - const GlobalData::TerrainLighting *objectLighting = TheGlobalData->m_terrainObjectsLighting[TheGlobalData->m_timeOfDay]; - for (bNdx=0; bNdx= m_numTrees) { - break; - } - VertexFormatXYZNDUV1 *vb; - UnsignedShort *ib; - // Lock the buffers. - #ifdef USE_STATIC - DX8IndexBufferClass::WriteLockClass lockIdxBuffer(m_indexTree[bNdx], 0); - DX8VertexBufferClass::WriteLockClass lockVtxBuffer(m_vertexTree[bNdx], 0); - #else - DX8IndexBufferClass::WriteLockClass lockIdxBuffer(m_indexTree[bNdx], D3DLOCK_DISCARD); - DX8VertexBufferClass::WriteLockClass lockVtxBuffer(m_vertexTree[bNdx], D3DLOCK_DISCARD); - #endif - vb=(VertexFormatXYZNDUV1*)lockVtxBuffer.Get_Vertex_Array(); - ib = lockIdxBuffer.Get_Index_Array(); - // Add to the index buffer & vertex buffer. - Vector2 lookAtVector(m_cameraLookAtVector.X, m_cameraLookAtVector.Y); - lookAtVector.Normalize(); - // We draw from back to front, so we put the indexes in the buffer - // from back to front. - UnsignedShort *curIb = ib; - - VertexFormatXYZNDUV1 *curVb = vb; - - - - - for ( ;curTreeFirst(); !pDynamicLightsIterator->Is_Done(); pDynamicLightsIterator->Next()) - { - W3DDynamicLight *pLight = (W3DDynamicLight*)pDynamicLightsIterator->Peek_Obj(); - if (!pLight->isEnabled()) { - continue; // he is turned off. - } - if (CollisionMath::Overlap_Test(m_trees[curTree].bounds, pLight->Get_Bounding_Sphere()) == CollisionMath::OUTSIDE) { - continue; // this tree is outside of the light's influence. - } - doVertexLighting = true; - } - #endif - Vector3 emissive(0.0f,0.0f,0.0f); - MaterialInfoClass * matInfo = m_treeTypes[type].m_mesh->Get_Material_Info(); - if (matInfo) { - VertexMaterialClass *vertMat = matInfo->Peek_Vertex_Material(0); - if (vertMat) { - vertMat->Get_Emissive(&emissive); - } - } - REF_PTR_RELEASE(matInfo); - - - Int startVertex = m_curNumTreeVertices[bNdx]; - m_trees[curTree].firstIndex = startVertex; - m_trees[curTree].bufferNdx = bNdx; - Int i; - Int numVertex = m_treeTypes[type].m_mesh->Peek_Model()->Get_Vertex_Count(); - Vector3 *pVert = m_treeTypes[type].m_mesh->Peek_Model()->Get_Vertex_Array(); - - - - // If we happen to have too many trees, stop. - if (m_curNumTreeVertices[bNdx]+numVertex+2>= MAX_TREE_VERTEX) { - break; - } - Int numIndex = m_treeTypes[type].m_mesh->Peek_Model()->Get_Polygon_Count(); - const TriIndex *pPoly = m_treeTypes[type].m_mesh->Peek_Model()->Get_Polygon_Array(); - if (m_curNumTreeIndices[bNdx]+3*numIndex+6 >= MAX_TREE_INDEX) { - break; - } - - const Vector2*uvs=m_treeTypes[type].m_mesh->Peek_Model()->Get_UV_Array_By_Index(0); - - const Vector3*normals = m_treeTypes[type].m_mesh->Peek_Model()->Get_Vertex_Normal_Array(); - const unsigned *vecDiffuse = m_treeTypes[type].m_mesh->Peek_Model()->Get_Color_Array(0, false); - - Int diffuse = 0; - if (normals == NULL) { - doVertexLighting = false; - Vector3 normal(0.0f,0.0f,1.0f); - diffuse = doLighting(&normal, objectLighting, &emissive, 0xFFFFFFFF, 1.0f); - } - /* - * - // If we are doing reduced resolution terrain, do reduced - // poly trees. - Bool doPanel = (TheGlobalData->m_useHalfHeightMap || TheGlobalData->m_stretchTerrain); - - if (doPanel) { - if (m_trees[curTree].rotates) { - theSin = -lookAtVector.X; - theCos = lookAtVector.Y; - } - // panel start is index offset, there are 3 index per triangle. - if (m_trees[curTree].panelStart/3 + 2 > numIndex) { - continue; // not enought polygons for the offset. jba. - } - for (j=0; j<6; j++) { - i = ((Int *)pPoly)[j+m_trees[curTree].panelStart]; - if (m_curNumTreeVertices >= MAX_TREE_VERTEX) - break; - - // Update the uv values. The W3D models each have their own texture, and - // we use one texture with all images in one, so we have to change the uvs to - // match. - Real U, V; - if (type==SHRUB) { - // shrub texture is tucked in the corner - U = ((512-64)+uvs[i].U*64.0f)/512.0f; - V = ((256-64)+uvs[i].V*64.0f)/256.0f; - } else if (type==FENCE) { - U = uvs[i].U*0.5f; - V = 1.0f + uvs[i].V; - } else { - U = typeOffset+uvs[i].U*0.5f; - V = uvs[i].V; - } - - curVb->u1 = U; - curVb->v1 = V/2.0; - Vector3 vLoc; - vLoc.X = pVert[i].X*scale*theCos - pVert[i].Y*scale*theSin; - vLoc.Y = pVert[i].Y*scale*theCos + pVert[i].X*scale*theSin; - - vLoc.X += loc.X; - vLoc.Y += loc.Y; - vLoc.Z = loc.Z + pVert[i].Z*scale; - - curVb->x = vLoc.X; - curVb->y = vLoc.Y; - curVb->z = vLoc.Z; - if (doVertexLighting) { - curVb->diffuse = doLighting(&vLoc, shadeR, shadeG, shadeB, m_trees[curTree].bounds, pDynamicLightsIterator); - } else { - curVb->diffuse = diffuse; - } - curVb++; - m_curNumTreeVertices++; - } - - for (i=0; i<6; i++) { - if (m_curNumTreeIndices+4 > MAX_TREE_INDEX) - break; - curIb--; - *curIb = startVertex + i; - m_curNumTreeIndices++; - } - } else { - */ - Real Uscale = m_treeTypes[type].m_tileWidth * (Real)TILE_PIXEL_EXTENT / (Real)m_textureWidth; - Real Vscale = m_treeTypes[type].m_tileWidth * (Real)TILE_PIXEL_EXTENT / (Real)m_textureHeight; - Real UOffset = m_treeTypes[type].m_textureOrigin.x/(Real)m_textureWidth; - Real VOffset = m_treeTypes[type].m_textureOrigin.y/(Real)m_textureHeight; - if (m_treeTypes[type].m_halfTile) { - Uscale *= 0.5f; - Vscale *= 0.5f; - VOffset += (TILE_PIXEL_EXTENT/2) / (Real)m_textureHeight; - } - for (i=0; i= MAX_TREE_VERTEX) - break; - - // Update the uv values. The W3D models each have their own texture, and - // we use one texture with all images in one, so we have to change the uvs to - // match. - Real U, V; - U = uvs[i].U; - V = uvs[i].V; - - if (U>1.0f) U=1.0f; - if (U<0.0f) U=0.0f; - if (V>1.0f) V=1.0f; - if (V<0.0f) V=0.0f; - - curVb->u1 = U*Uscale + UOffset; - curVb->v1 = V*Vscale + VOffset; - Real x = pVert[i].X; - Real y = pVert[i].Y; - - - Vector3 vLoc; - x += m_treeTypes[type].m_offset.X; - y += m_treeTypes[type].m_offset.Y; - vLoc.X = x*scale*theCos - y*scale*theSin; - vLoc.Y = y*scale*theCos + x*scale*theSin; - vLoc.Z = pVert[i].Z*scale; - vLoc.Z += m_treeTypes[type].m_offset.Z; - - if (m_trees[curTree].m_toppleState != TOPPLE_UPRIGHT) { - Matrix3D::Transform_Vector(m_trees[curTree].m_mtx, vLoc, &vLoc); - } else { - if (m_trees[curTree].pushAside>0.0f) { - vLoc.X += pVert[i].Z * m_trees[curTree].pushAside * m_trees[curTree].pushAsideCos * m_treeTypes[type].m_data->m_maxOutwardMovement; - vLoc.Y += pVert[i].Z * m_trees[curTree].pushAside * m_trees[curTree].pushAsideSin* m_treeTypes[type].m_data->m_maxOutwardMovement; - } - vLoc.X += loc.X; - vLoc.Y += loc.Y; - vLoc.Z += loc.Z; - } - - - curVb->x = vLoc.X; - curVb->y = vLoc.Y; - curVb->z = vLoc.Z; - curVb->nx = m_trees[curTree].swayType; - curVb->ny = 1.0f - m_treeTypes[type].m_data->m_darkening*m_trees[curTree].pushAside; - curVb->nz = loc.Z; - if (doVertexLighting) { - Vector3 normal(0.0f, 0.0f, 1.0f); - if (normals) { - normal.X = normals[i].X*theCos - normals[i].Y*theSin; - normal.Y = normals[i].Y*theCos + normals[i].X*theSin; - normal.Z = normals[i].Z; - } - UnsignedInt vertexDiffuse; - if (vecDiffuse) { - vertexDiffuse = vecDiffuse[i]; - } else { - vertexDiffuse = 0xffffffff; - } - curVb->diffuse = doLighting(&normal, objectLighting, &emissive, - vertexDiffuse, 1.0f); - } else { - curVb->diffuse = diffuse; - } - curVb++; - m_curNumTreeVertices[bNdx]++; - } - - for (i=0; i MAX_TREE_INDEX) - break; - *curIb++ = startVertex + pPoly[i].I; - *curIb++ = startVertex + pPoly[i].J; - *curIb++ = startVertex + pPoly[i].K; - m_curNumTreeIndices[bNdx]+=3; - } - } - } - -} -//============================================================================= -// W3DTreeBuffer::updateVertexBuffer -//============================================================================= -/** Updates the push aside offset in vertex buffer. */ -//============================================================================= -void W3DTreeBuffer::updateVertexBuffer(void) -{ - if (!m_indexTree[0] || !m_vertexTree[0] || !m_initialized) { - return; - } - Int bNdx; - for (bNdx = 0; bNdxPeek_Model()->Get_Vertex_Count(); - Vector3 *pVert = m_treeTypes[type].m_mesh->Peek_Model()->Get_Vertex_Array(); - - for (i=0; i0.0f) { - vLoc.X += pVert[i].Z * m_trees[curTree].pushAside * m_trees[curTree].pushAsideCos * m_treeTypes[type].m_data->m_maxOutwardMovement; - vLoc.Y += pVert[i].Z * m_trees[curTree].pushAside * m_trees[curTree].pushAsideSin* m_treeTypes[type].m_data->m_maxOutwardMovement; - } - vLoc.X += loc.X; - vLoc.Y += loc.Y; - vLoc.Z += loc.Z; - } - - curVb->x = vLoc.X; - curVb->y = vLoc.Y; - curVb->z = vLoc.Z; - curVb->ny = 1.0f - m_treeTypes[type].m_data->m_darkening*m_trees[curTree].pushAside; - curVb++; - } - } - } -} - -//----------------------------------------------------------------------------- -// Public Functions -//----------------------------------------------------------------------------- - -//============================================================================= -// W3DTreeBuffer::~W3DTreeBuffer -//============================================================================= -/** Destructor. Releases w3d assets. */ -//============================================================================= -W3DTreeBuffer::~W3DTreeBuffer(void) -{ - freeTreeBuffers(); - REF_PTR_RELEASE(m_treeTexture); - Int i; - for (i=0; iDeletePixelShader(m_dwTreePixelShader); - m_dwTreePixelShader = 0; - - if (m_dwTreeVertexShader) - DX8Wrapper::_Get_D3D_Device8()->DeleteVertexShader(m_dwTreeVertexShader); - m_dwTreeVertexShader = 0; -} - -//============================================================================= -// W3DTreeBuffer::unitMoved -//============================================================================= -/** Check to see if a unit collided with a tree/grass/bush. */ -//============================================================================= -void W3DTreeBuffer::unitMoved(Object *unit) -{ - if (unit->isKindOf(KINDOF_IMMOBILE)) { - // This is the initial positioning of the object, and we don't care. jba. [6/5/2003] - return; - } - Real radius = unit->getGeometryInfo().getMajorRadius(); - if (unit->getGeometryInfo().getGeomType()==GEOMETRY_BOX) { - if (radius>unit->getGeometryInfo().getMinorRadius()) { - radius = unit->getGeometryInfo().getMinorRadius(); - } - } - // Value to assume for the tree radius. -#define TREE_RADIUS_APPROX 7.0f - radius += TREE_RADIUS_APPROX; - - Coord3D pos = *unit->getPosition(); - Real x = pos.x-radius; - Real y = pos.y-radius; - if (xm_bounds.hi.x) x = m_bounds.hi.x; - if (y>m_bounds.hi.y) y = m_bounds.hi.y; - Int xIndex = REAL_TO_INT_FLOOR ( (x/(m_bounds.hi.x-m_bounds.lo.x)) * (PARTITION_WIDTH_HEIGHT-0.1f) ); - Int yIndex = REAL_TO_INT_FLOOR ( (y/(m_bounds.hi.y-m_bounds.lo.y)) * (PARTITION_WIDTH_HEIGHT-0.1f) ); - DEBUG_ASSERTCRASH(xIndex>=0 && yIndex>=0 && xIndexm_bounds.hi.x) x = m_bounds.hi.x; - if (y>m_bounds.hi.y) y = m_bounds.hi.y; - Int xMax = REAL_TO_INT_CEIL ( (x/(m_bounds.hi.x-m_bounds.lo.x)) * (PARTITION_WIDTH_HEIGHT-0.1f) ); - Int yMax = REAL_TO_INT_CEIL ( (y/(m_bounds.hi.y-m_bounds.lo.y)) * (PARTITION_WIDTH_HEIGHT-0.1f) ); - DEBUG_ASSERTCRASH(xMax>=0 && yMax>=0 && xMax<=PARTITION_WIDTH_HEIGHT && yMax<=PARTITION_WIDTH_HEIGHT, ("Invalid range.")); - Int i, j; - for (i=xIndex; i=m_numTrees) { - DEBUG_CRASH(("Invalid index.")); - break; - } - if (m_trees[treeNdx].treeType<0) { - treeNdx = m_trees[treeNdx].nextInPartition; - continue; // Tree is deleted. [7/11/2003] - } - Coord3D delta; - delta.set(m_trees[treeNdx].location.X, m_trees[treeNdx].location.Y, m_trees[treeNdx].location.Z ); - delta.sub(&pos); - if (radius*radius>delta.lengthSqr()) { - bool canTopple = unit->getCrusherLevel() > 1; - if (canTopple && m_treeTypes[m_trees[treeNdx].treeType].m_data->m_doTopple) { - // Give a vector with direction to thing. - Coord3D toppleVector; - toppleVector.set(m_trees[treeNdx].location.X, m_trees[treeNdx].location.Y, 0); - toppleVector.x -= unit->getPosition()->x; - toppleVector.y -= unit->getPosition()->y; - applyTopplingForce(m_trees+treeNdx, &toppleVector, 0, W3D_TOPPLE_OPTIONS_NONE); - } else if (m_treeTypes[m_trees[treeNdx].treeType].m_data->m_framesToMoveOutward>1) { - pushAsideTree(m_trees[treeNdx].drawableID, &pos, unit->getUnitDirectionVector2D(), unit->getID()); - } - } - treeNdx = m_trees[treeNdx].nextInPartition; - } - } - } - - -} - -//============================================================================= -// W3DTreeBuffer::allocateTreeBuffers -//============================================================================= -/** Allocates the index and vertex buffers. */ -//============================================================================= -void W3DTreeBuffer::allocateTreeBuffers(void) -{ - Int i; - for (i=0; igeomCollidesWithGeom( pos, geom, angle, &treePos, info, 0.0f)) { - // remove it [7/11/2003] - m_trees[i].treeType = DELETED_TREE_TYPE; - m_anythingChanged = true; - } - } -} - - -//============================================================================= -// W3DTreeBuffer::addTreeTypes -//============================================================================= -/** Adds a type of tree (model & texture). */ -//============================================================================= -Int W3DTreeBuffer::addTreeType(const W3DTreeDrawModuleData *data) -{ - if (m_numTreeTypes>=MAX_TYPES) { - DEBUG_CRASH(("Too many kinds of trees in map. Reduce kinds of trees, or raise tree limit. jba.")); - return 0; - } - m_needToUpdateTexture = true; - - m_treeTypes[m_numTreeTypes].m_mesh = NULL; - - RenderObjClass *robj=WW3DAssetManager::Get_Instance()->Create_Render_Obj(data->m_modelName.str()); - - if (robj==NULL) { - DEBUG_CRASH(("Unable to find model for tree %s", data->m_modelName.str())); - return 0; - } - AABoxClass box; - - robj->Get_Obj_Space_Bounding_Box(box); - Vector3 offset(0,0,0); - if (robj->Class_ID() == RenderObjClass::CLASSID_HLOD) { - RenderObjClass *hlod = robj; - robj = hlod->Get_Sub_Object(0); - const Matrix3D xfm = robj->Get_Bone_Transform(0); - xfm.Get_Translation(&offset); - REF_PTR_RELEASE(hlod); - } - - if (robj->Class_ID() == RenderObjClass::CLASSID_MESH) - m_treeTypes[m_numTreeTypes].m_mesh = (MeshClass*)robj; - - if (m_treeTypes[m_numTreeTypes].m_mesh==NULL) { - DEBUG_CRASH(("Tree %s is not simple mesh. Tell artist to re-export. Don't Ignore!!!", data->m_modelName.str())); - return 0; - } - - Int numVertex = m_treeTypes[m_numTreeTypes].m_mesh->Peek_Model()->Get_Vertex_Count(); - Vector3 *pVert = m_treeTypes[m_numTreeTypes].m_mesh->Peek_Model()->Get_Vertex_Array(); - - const Matrix3D xfm = m_treeTypes[m_numTreeTypes].m_mesh->Get_Transform(); - SphereClass bounds(pVert, numVertex); - bounds.Center += offset; - m_treeTypes[m_numTreeTypes].m_bounds = bounds; - m_treeTypes[m_numTreeTypes].m_textureOrigin.x = 0; - m_treeTypes[m_numTreeTypes].m_textureOrigin.y = 0; - m_treeTypes[m_numTreeTypes].m_data = data; - m_treeTypes[m_numTreeTypes].m_offset = offset; - m_treeTypes[m_numTreeTypes].m_shadowSize = (box.Extent.X + box.Extent.Y); // Average extent * 2. jba. - m_treeTypes[m_numTreeTypes].m_doShadow = data->m_doShadow; - m_numTreeTypes++; - return m_numTreeTypes-1; -} - -//============================================================================= -// W3DTreeBuffer::addTree -//============================================================================= -/** Adds a tree. Name is the W3D model name, supported models are -ALPINE, DECIDUOUS and SHRUB. */ -//============================================================================= -void W3DTreeBuffer::addTree(DrawableID id, Coord3D location, Real scale, Real angle, - Real randomScaleAmount, const W3DTreeDrawModuleData *data) -{ - if (m_numTrees >= MAX_TREES) { - return; - } - if (!m_initialized) { - return; - } - Int treeType = DELETED_TREE_TYPE; - Int i; - for (i=0; im_modelName.compareNoCase(data->m_modelName)==0 && - m_treeTypes[i].m_data->m_textureName.compareNoCase(data->m_textureName)==0) { - treeType = i; - break; - } - } - if (treeType<0) { - treeType = addTreeType(data); - if (treeType<0) { - return; - } - m_needToUpdateTexture = true; - } - if (data->m_framesToMoveOutward > 2 || data->m_doTopple) { - // Fences don't randomly scale & orient - Short bucket = getPartitionBucket(location); - m_trees[m_numTrees].nextInPartition = m_areaPartition[bucket]; - m_areaPartition[bucket] = m_numTrees; - } else { - m_trees[m_numTrees].nextInPartition = END_OF_PARTITION; - } - - Real randomScale = GameClientRandomValueReal( 1.0f - randomScaleAmount, 1.0f+ randomScaleAmount ); - m_trees[m_numTrees].sin = WWMath::Sin(angle); - m_trees[m_numTrees].cos = WWMath::Cos(angle); - if (randomScaleAmount>0.0f) { - // Randomizes the scale and orientation of trees. - m_trees[m_numTrees].scale = scale*randomScale; - } else { - // Don't randomly scale & orient - m_trees[m_numTrees].scale = scale; - } - m_trees[m_numTrees].location = Vector3(location.x, location.y, location.z); - m_trees[m_numTrees].treeType = treeType; - // Translate the bounding sphere of the model. - m_trees[m_numTrees].bounds = m_treeTypes[treeType].m_bounds; - m_trees[m_numTrees].bounds.Center *= m_trees[m_numTrees].scale; - m_trees[m_numTrees].bounds.Radius *= m_trees[m_numTrees].scale; - m_trees[m_numTrees].bounds.Center += m_trees[m_numTrees].location; - // Initially set it invisible. cull will update it's visiblity flag. - m_trees[m_numTrees].visible = false; - m_trees[m_numTrees].drawableID = id; - - m_trees[m_numTrees].firstIndex = 0; - m_trees[m_numTrees].bufferNdx = -1; - - m_trees[m_numTrees].swayType = GameClientRandomValue(1, MAX_SWAY_TYPES); - m_trees[m_numTrees].pushAside = 0; - m_trees[m_numTrees].lastFrameUpdated = 0; - m_trees[m_numTrees].pushAsideSource = INVALID_ID; - m_trees[m_numTrees].pushAsideDelta = 0; - m_trees[m_numTrees].pushAsideCos = 1; - m_trees[m_numTrees].pushAsideSin = 1; - m_trees[m_numTrees].m_toppleState = TOPPLE_UPRIGHT; - m_numTrees++; -} - -//============================================================================= -// W3DTreeBuffer::updateTreePosition -//============================================================================= -/** Updates a tree's position */ -//============================================================================= -Bool W3DTreeBuffer::updateTreePosition(DrawableID id, Coord3D location, Real angle) -{ - Int i; - for (i=0; igetFrame(); - if(m_trees[i].pushAsideSource == pusherID) { - if (m_trees[i].lastFrameUpdated - lastFrame < 3) - return; // already pushing. [5/28/2003] - } - - if(m_trees[i].pushAside != 0.0f) { - return; // already pushing. [5/28/2003] - } - m_trees[i].pushAsideSource = pusherID; - Coord3D delta; - delta.set(m_trees[i].location.X, m_trees[i].location.Y, m_trees[i].location.Z); - delta.sub(pusherPos); - - if (pusherDirection->x*delta.y - pusherDirection->y*delta.x > 0.0f) { - m_trees[i].pushAsideCos = -pusherDirection->y; - m_trees[i].pushAsideSin = pusherDirection->x; - } else { - m_trees[i].pushAsideCos = pusherDirection->y; - m_trees[i].pushAsideSin = -pusherDirection->x; - } - m_anyPushChanged = true; - m_trees[i].pushAsideDelta = 1.0f/(Real)m_treeTypes[m_trees[i].treeType].m_data->m_framesToMoveOutward; - } - } -} - -DECLARE_PERF_TIMER(Tree_Render) - -//============================================================================= -// W3DTreeBuffer::drawTrees -//============================================================================= -/** Draws the trees. Uses camera to cull. */ -//============================================================================= -void W3DTreeBuffer::drawTrees(CameraClass * camera, RefRenderObjListIterator *pDynamicLightsIterator) -{ - USE_PERF_TIMER(Tree_Render) - if (!m_isTerrainPass) { - return; - } - - // if breeze changes, always process the full update, even if not visible, - // so that things offscreen won't 'pop' when first viewed - const BreezeInfo& info = TheScriptEngine->getBreezeInfo(); - if (info.m_breezeVersion != m_curSwayVersion) - { - updateSway(info); - } - - // TheSuperHackers @tweak The tree sway, topple and sink time steps are now decoupled from the render update. - const Real timeScale = TheFramePacer->getActualLogicTimeScaleOverFpsRatio(); - Vector3 swayFactor[MAX_SWAY_TYPES]; - Int i; - for (i=0; i NUM_SWAY_ENTRIES-1) { - m_curSwayOffset[i] -= NUM_SWAY_ENTRIES-1; - } - Int minOffset = REAL_TO_INT_FLOOR(m_curSwayOffset[i]); - if (minOffset>=0 && minOffset+1m_useShadowDecals) { - for (curTree=0; curTreesetSize(m_treeTypes[type].m_shadowSize, m_treeTypes[type].m_shadowSize); - m_shadow->setPosition(m_trees[curTree].location.X, m_trees[curTree].location.Y, m_trees[curTree].location.Z); - TheW3DProjectedShadowManager->queueDecal(m_shadow); - } - TheW3DProjectedShadowManager->flushDecals(m_shadow->getTexture(0), SHADOW_DECAL); - } - - // Update pushed aside and toppling trees. - for (curTree=0; curTreem_killWhenToppled) { - if (m_trees[curTree].m_sinkFramesLeft <= 0.0f) { - m_trees[curTree].treeType = DELETED_TREE_TYPE; // delete it. [7/11/2003] - m_anythingChanged = true; // need to regenerate trees. [7/11/2003] - } - const Real sinkDistancePerFrame = moduleData->m_sinkDistance / moduleData->m_sinkFrames; - m_trees[curTree].m_sinkFramesLeft -= timeScale; - m_trees[curTree].location.Z -= sinkDistancePerFrame * timeScale; - m_trees[curTree].m_mtx.Set_Translation(m_trees[curTree].location); - } - } else if (m_trees[curTree].pushAsideDelta!=0.0f) { - m_trees[curTree].pushAside += m_trees[curTree].pushAsideDelta; - if (m_trees[curTree].pushAside>=1.0f) { - m_trees[curTree].pushAsideDelta = -1.0f/(Real)moduleData->m_framesToMoveInward; - } else if (m_trees[curTree].pushAside<=0.0f) { - m_trees[curTree].pushAsideDelta = 0.0f; - m_trees[curTree].pushAside = 0.0f; - } - } - } - - if (m_anythingChanged) { - loadTreesInVertexAndIndexBuffers(pDynamicLightsIterator); - m_anythingChanged = false; - } else if (m_anyPushChanged) { - m_anyPushChanged = false; - updateVertexBuffer(); - } - -//#define DEBUG_TEXTURE 1 -#ifdef DEBUG_TEXTURE // Draw the combined texture for debugging. jba. [4/21/2003] - // Setup the vertex buffer, shader & texture. - DX8Wrapper::Set_Shader(detailAlphaShader); - DX8Wrapper::Set_Texture(0,m_treeTexture); - DynamicIBAccessClass ib_access(BUFFER_TYPE_DYNAMIC_DX8, 6); - //draw an infinite sky plane - DynamicVBAccessClass vb_access(BUFFER_TYPE_DYNAMIC_DX8, DX8_FVF_XYZNDUV2, 4); - { - DynamicIBAccessClass::WriteLockClass ibLock(&ib_access); - UnsignedShort *ndx = ibLock.Get_Index_Array(); - - if (ndx) { - ndx[0] = 0; - ndx[1] = 1; - ndx[2] = 2; - ndx[3] = 1; - ndx[4] = 3; - ndx[5] = 2; - } - DynamicVBAccessClass::WriteLockClass lock(&vb_access); - VertexFormatXYZNDUV2* verts=lock.Get_Formatted_Vertex_Array(); - if(verts) - { - Real width = 300; - Real origin = 40; - verts[0].x=origin; - verts[0].y=origin; - verts[0].z=15; - verts[0].u1=0; - verts[0].v1=0; - verts[0].diffuse=0xffffffff; - - verts[1].x=origin+width; - verts[1].y=origin; - verts[1].z=15; - verts[1].u1=1; - verts[1].v1=0; - verts[1].diffuse=0xffffffff; - - verts[2].x=origin; - verts[2].y=origin+width; - verts[2].z=15; - verts[2].u1=0; - verts[2].v1=1; - verts[2].diffuse=0xffffffff; - - verts[3].x=origin+width; - verts[3].y=origin+width; - verts[3].z=15; - verts[3].u1=1; - verts[3].v1=1; - verts[3].diffuse=0xffffffff; - } - } - - DX8Wrapper::Set_Index_Buffer(ib_access,0); - DX8Wrapper::Set_Vertex_Buffer(vb_access); - - Matrix3D tm(1); - DX8Wrapper::Set_Transform(D3DTS_WORLD,tm); - - DX8Wrapper::Draw_Triangles( 0,2, 0, 4); //draw a quad, 2 triangles, 4 verts -#endif - - - if (m_curNumTreeIndices[0] == 0) { - return; - } - DX8Wrapper::Set_Shader(detailAlphaShader); - - DX8Wrapper::Set_Texture(0,m_treeTexture); - DX8Wrapper::Set_Texture(1,NULL); - DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_TEXCOORDINDEX, 0); - DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_TEXCOORDINDEX, 1); - // Draw all the trees. - DX8Wrapper::Apply_Render_State_Changes(); - W3DShaderManager::setShroudTex(1); - DX8Wrapper::Apply_Render_State_Changes(); - - if (m_dwTreeVertexShader) { - D3DXMATRIX matProj, matView, matWorld; - DX8Wrapper::_Get_DX8_Transform(D3DTS_WORLD, *(Matrix4x4*)&matWorld); - DX8Wrapper::_Get_DX8_Transform(D3DTS_VIEW, *(Matrix4x4*)&matView); - DX8Wrapper::_Get_DX8_Transform(D3DTS_PROJECTION, *(Matrix4x4*)&matProj); - D3DXMATRIX mat; - D3DXMatrixMultiply( &mat, &matView, &matProj ); - D3DXMatrixMultiply( &mat, &matWorld, &mat ); - D3DXMatrixTranspose( &mat, &mat ); - - // c4 - Composite World-View-Projection Matrix - DX8Wrapper::_Get_D3D_Device8()->SetVertexShaderConstant( 4, &mat, 4 ); - Vector4 noSway(0,0,0,0); - DX8Wrapper::_Get_D3D_Device8()->SetVertexShaderConstant( 8, &noSway, 1 ); - - // c8 - c8+MAX_SWAY_TYPES - the sway amount. - for (i=0; iSetVertexShaderConstant( 9+i, &sway4, 1 ); - } - - W3DShroud *shroud; - if ((shroud=TheTerrainRenderObject->getShroud()) != 0) { - // Setup shroud texture info [6/6/2003] - float xoffset = 0; - float yoffset = 0; - Real width=shroud->getCellWidth(); - Real height=shroud->getCellHeight(); - - xoffset = -(float)shroud->getDrawOriginX() + width; - yoffset = -(float)shroud->getDrawOriginY() + height; - Vector4 offset(xoffset, yoffset, 0, 0); - DX8Wrapper::_Get_D3D_Device8()->SetVertexShaderConstant( 32, &offset, 1 ); - width = 1.0f/(width*shroud->getTextureWidth()); - height = 1.0f/(height*shroud->getTextureHeight()); - offset.Set(width, height, 1, 1); - DX8Wrapper::_Get_D3D_Device8()->SetVertexShaderConstant( 33, &offset, 1 ); - - } else { - Vector4 offset(0,0,0,0); - DX8Wrapper::_Get_D3D_Device8()->SetVertexShaderConstant( 32, &offset, 1 ); - DX8Wrapper::_Get_D3D_Device8()->SetVertexShaderConstant( 33, &offset, 1 ); - } - - DX8Wrapper::Set_Vertex_Shader(m_dwTreeVertexShader); -#if 0 - DX8Wrapper::Set_Pixel_Shader(m_dwTreePixelShader); - // a.c. 6/16 - allow switching between normal and 2X mode for terrain - Real mulTwoX = 0.5f; - if(TheGlobalData && TheGlobalData->m_useOverbright) - mulTwoX = 1.0f; - DX8Wrapper::_Get_D3D_Device8()->SetPixelShaderConstant(1, D3DXVECTOR4(mulTwoX, mulTwoX, mulTwoX, mulTwoX), 1); -#endif - - } else { - DX8Wrapper::Set_Vertex_Shader(DX8_FVF_XYZNDUV1); - } - - - Int bNdx; - for (bNdx=0;bNdxSetVertexShader(m_dwTreeVertexShader); - DX8Wrapper::_Get_D3D_Device8()->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 0); - DX8Wrapper::_Get_D3D_Device8()->SetTextureStageState(1, D3DTSS_TEXCOORDINDEX, 1); - DX8Wrapper::_Get_D3D_Device8()->SetTextureStageState(1, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE); - } - DX8Wrapper::Draw_Triangles( 0, m_curNumTreeIndices[bNdx]/3, 0, m_curNumTreeVertices[bNdx]); - } - - DX8Wrapper::Set_Vertex_Shader(DX8_FVF_XYZNDUV1); - DX8Wrapper::Set_Pixel_Shader(NULL); - DX8Wrapper::Invalidate_Cached_Render_States(); //code above mucks around with W3D states so make sure we reset - -} - -//------------------------------------------------------------------------------------------------- -///< Start the toppling process by giving a force vector -//------------------------------------------------------------------------------------------------- -void W3DTreeBuffer::applyTopplingForce( TTree *tree, const Coord3D* toppleDirection, Real toppleSpeed, - UnsignedInt options ) -{ - if (tree->m_toppleState != TOPPLE_UPRIGHT) { - return; - } - const W3DTreeDrawModuleData* d = m_treeTypes[tree->treeType].m_data; - // Having a low toppleSpeed is BAD. In particular, if the toppleSpeed is exactly 0, the - // tree will stay upright forever, frozen in place (because the sway update is dead) - // but never dying - if ( toppleSpeed < d->m_minimumToppleSpeed ) - { - toppleSpeed = d->m_minimumToppleSpeed; - } - - tree->m_toppleDirection = *toppleDirection; - tree->m_toppleDirection.normalize(); - tree->m_angularAccumulation = 0; - - tree->m_angularVelocity = toppleSpeed * d->m_initialVelocityPercent; - tree->m_angularAcceleration = toppleSpeed * d->m_initialAccelPercent; - tree->m_toppleState = TOPPLE_FALLING; - tree->m_options = options; - Coord3D pos; - pos.set(tree->location.X, tree->location.Y, tree->location.Z); - FXList::doFXPos(d->m_toppleFX, &pos); - m_anyPushChanged = true; - tree->m_mtx.Make_Identity(); - tree->m_mtx.Set_Translation(tree->location); - -} - -// this is our "bounce" limit -- slightly less that 90 degrees, to account for slop. -static const Real ANGULAR_LIMIT = PI/2 - PI/64; - -//------------------------------------------------------------------------------------------------- -///< Keep track of rotational fall distance, bounce and/or stop when needed. -//------------------------------------------------------------------------------------------------- -void W3DTreeBuffer::updateTopplingTree(TTree *tree, Real timeScale) -{ - //DLOG(Debug::Format("updating W3DTreeBuffer %08lx\n",this)); - DEBUG_ASSERTCRASH(tree->m_toppleState != TOPPLE_UPRIGHT, ("hmm, we should be sleeping here")); - if ( (tree->m_toppleState == TOPPLE_UPRIGHT) || (tree->m_toppleState == TOPPLE_DOWN) ) - return; - - const W3DTreeDrawModuleData* d = m_treeTypes[tree->treeType].m_data; - const Int localPlayerIndex = rts::getObservedOrLocalPlayerIndex_Safe(); - Coord3D pos; - pos.set(tree->location.X, tree->location.Y, tree->location.Z); - ObjectShroudStatus ss = ThePartitionManager->getPropShroudStatusForPlayer(localPlayerIndex, &pos); - if (ss==OBJECTSHROUD_FOGGED) { - // Don't update fogged trees. [8/11/2003] - tree->m_toppleState = TOPPLE_FOGGED; - return; - } else if (tree->m_toppleState == TOPPLE_FOGGED) { - // was fogged, now isn't. - tree->m_angularVelocity = 0; - tree->m_toppleState = TOPPLE_DOWN; - tree->m_mtx.In_Place_Pre_Rotate_X(-ANGULAR_LIMIT * tree->m_toppleDirection.y); - tree->m_mtx.In_Place_Pre_Rotate_Y(ANGULAR_LIMIT * tree->m_toppleDirection.x); - if (d->m_killWhenToppled) { - // If got killed in the fog, just remove. jba [8/11/2003] - tree->m_sinkFramesLeft = 0.0f; - } - return; - } - const Real VELOCITY_BOUNCE_LIMIT = 0.01f; // if the velocity after a bounce will be this or lower, just stop at zero - const Real VELOCITY_BOUNCE_SOUND_LIMIT = 0.03f; // and if this low, then skip the bounce sound - - Real curVelToUse = tree->m_angularVelocity * timeScale; - if (tree->m_angularAccumulation + curVelToUse > ANGULAR_LIMIT) - curVelToUse = ANGULAR_LIMIT - tree->m_angularAccumulation; - - tree->m_mtx.In_Place_Pre_Rotate_X(-curVelToUse * tree->m_toppleDirection.y); - tree->m_mtx.In_Place_Pre_Rotate_Y(curVelToUse * tree->m_toppleDirection.x); - - tree->m_angularAccumulation += curVelToUse; - if ((tree->m_angularAccumulation >= ANGULAR_LIMIT) && (tree->m_angularVelocity > 0)) - { - // Hit so either bounce or stop if too little remaining velocity. - tree->m_angularVelocity *= -d->m_bounceVelocityPercent; - - if( BitIsSet( tree->m_options, W3D_TOPPLE_OPTIONS_NO_BOUNCE ) == TRUE || - fabs(tree->m_angularVelocity) < VELOCITY_BOUNCE_LIMIT ) - { - // too slow, just stop - tree->m_angularVelocity = 0; - tree->m_toppleState = TOPPLE_DOWN; - if (d->m_killWhenToppled) { - tree->m_sinkFramesLeft = d->m_sinkFrames; - } - } - else if( fabs(tree->m_angularVelocity) >= VELOCITY_BOUNCE_SOUND_LIMIT ) - { - // fast enough bounce to warrant the bounce fx - if( BitIsSet( tree->m_options, W3D_TOPPLE_OPTIONS_NO_FX ) == FALSE ) { - Vector3 loc(0, 0, 3*TREE_RADIUS_APPROX); // Kinda towards the top of the tree. jba. [7/11/2003] - Vector3 xloc; - tree->m_mtx.Transform_Vector(tree->m_mtx, loc, &xloc); - Coord3D pos; - pos.set(xloc.X, xloc.Y, xloc.Z); - FXList::doFXPos(d->m_bounceFX, &pos); - } - } - } - else - { - tree->m_angularVelocity += tree->m_angularAcceleration * timeScale; - } - -} - -// ------------------------------------------------------------------------------------------------ -/** CRC */ -// ------------------------------------------------------------------------------------------------ -void W3DTreeBuffer::crc( Xfer *xfer ) -{ - // empty. jba [8/11/2003] -} - -// ------------------------------------------------------------------------------------------------ -/** Xfer - * Version Info: - * 1: Initial version */ -// ------------------------------------------------------------------------------------------------ -void W3DTreeBuffer::xfer( Xfer *xfer ) -{ - - // version -#if RETAIL_COMPATIBLE_XFER_SAVE - XferVersion currentVersion = 1; -#else - XferVersion currentVersion = 2; -#endif - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - Int i; - Int numTrees = m_numTrees; - xfer->xferInt(&numTrees); - if (xfer->getXferMode() == XFER_LOAD) { - m_numTrees = 0; - for (i=0; igetXferMode() != XFER_LOAD) { - tree = m_trees[i]; - treeType = m_trees[i].treeType; - if (treeType != DELETED_TREE_TYPE) { - modelName = m_treeTypes[treeType].m_data->m_modelName; - modelTexture = m_treeTypes[treeType].m_data->m_textureName; - } - } - xfer->xferAsciiString(&modelName); - xfer->xferAsciiString(&modelTexture); - if (xfer->getXferMode() == XFER_LOAD) { - Int j; - for (j=0; jm_modelName.compareNoCase(modelName)==0 && - m_treeTypes[j].m_data->m_textureName.compareNoCase(modelTexture)==0) { - treeType = j; - break; - } - } - } - - xfer->xferReal(&tree.location.X); - xfer->xferReal(&tree.location.Y); - xfer->xferReal(&tree.location.Z); - - xfer->xferReal(&tree.scale); ///< Scale at location. - xfer->xferReal(&tree.sin); ///< Sine of the rotation angle at location. - xfer->xferReal(&tree.cos); ///< Cosine of the rotation angle at location. - - xfer->xferDrawableID(&tree.drawableID); ///< Drawable this tree corresponds to. - - // Topple parameters. [7/7/2003] - xfer->xferReal(&tree.m_angularVelocity); ///< Velocity in degrees per frame (or is it radians per frame?) - xfer->xferReal(&tree.m_angularAcceleration); ///< Acceleration angularVelocity is increasing - xfer->xferCoord3D(&tree.m_toppleDirection); ///< Z-less direction we are toppling - xfer->xferUser(&tree.m_toppleState, sizeof(tree.m_toppleState)); ///< Stage this module is in. - xfer->xferReal(&tree.m_angularAccumulation); ///< How much have I rotated so I know when to bounce. - xfer->xferUnsignedInt(&tree.m_options); ///< topple options - xfer->xferMatrix3D(&tree.m_mtx); - - if (version <= 1) - { - UnsignedInt sinkFramesLeft = (UnsignedInt)tree.m_sinkFramesLeft; - xfer->xferUnsignedInt(&sinkFramesLeft); ///< Toppled trees sink into the terrain & disappear, how many frames left. - tree.m_sinkFramesLeft = (Real)sinkFramesLeft; - } - else - { - xfer->xferReal(&tree.m_sinkFramesLeft); ///< Toppled trees sink into the terrain & disappear, how many frames left. - } - - if (xfer->getXferMode() == XFER_LOAD && treeType != DELETED_TREE_TYPE && treeType < m_numTreeTypes) { - Coord3D pos; - pos.set(tree.location.X, tree.location.Y, tree.location.Z); - Real angle = 0; - addTree(tree.drawableID, pos, tree.scale, angle, 0, m_treeTypes[treeType].m_data); - if (m_numTrees) { - TTree *curTree = &m_trees[m_numTrees-1]; - curTree->m_angularAcceleration = tree.m_angularAcceleration; - curTree->m_angularVelocity = tree.m_angularVelocity; - curTree->m_toppleDirection = tree.m_toppleDirection; - curTree->m_toppleState = tree.m_toppleState; - curTree->m_options = tree.m_options; - curTree->m_mtx = tree.m_mtx; - curTree->m_sinkFramesLeft = tree.m_sinkFramesLeft; - } - } - } - -} - -// ------------------------------------------------------------------------------------------------ -/** Load post process */ -// ------------------------------------------------------------------------------------------------ -void W3DTreeBuffer::loadPostProcess( void ) -{ - // empty. jba [8/11/2003] -} - - - - diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp deleted file mode 100644 index b8211abbcc..0000000000 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp +++ /dev/null @@ -1,2545 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public 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. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// WorldHeightMap.cpp -// Class to encapsulate height map. -// Author: John Ahlquist, April 2001 - -#define INSTANTIATE_WELL_KNOWN_KEYS - -#include "windows.h" -#include "stdlib.h" -#include "Common/STLTypedefs.h" - -#include "Common/DataChunk.h" -//#include "Common/GameFileSystem.h" -#include "Common/FileSystem.h" // for LOAD_TEST_ASSETS -#include "Common/GlobalData.h" -#include "Common/MapReaderWriterInfo.h" -#include "Common/TerrainTypes.h" -#include "Common/ThingFactory.h" -#include "Common/ThingTemplate.h" -#include "Common/WellKnownKeys.h" - -#include "GameLogic/PolygonTrigger.h" -#include "GameLogic/SidesList.h" - -#include "W3DDevice/GameClient/WorldHeightMap.h" -#include "W3DDevice/GameClient/TileData.h" -#include "W3DDevice/GameClient/HeightMap.h" -#include "W3DDevice/GameClient/TerrainTex.h" -#include "W3DDevice/GameClient/W3DShadow.h" - -#include "Common/file.h" - - -#define K_OBSOLETE_HEIGHT_MAP_VERSION 8 - -#define PATHFIND_CLIFF_SLOPE_LIMIT_F 9.8f - -// ----------------------------------------------------------- -static AsciiString validateName(AsciiString n, Int flags) -{ - - return n; - -} - -/* ********* GDIFileStream class ****************************/ -class GDIFileStream : public InputStream -{ -protected: - File* m_file; -public: - GDIFileStream(File* pFile):m_file(pFile) {}; - virtual Int read(void *pData, Int numBytes) { - return(m_file->read(pData, numBytes)); - }; -}; - - -/* ********* MapObject class ****************************/ -/*static*/ MapObject *MapObject::TheMapObjectListPtr = NULL; -/*static*/ Dict MapObject::TheWorldDict; - -MapObject::MapObject(Coord3D loc, AsciiString name, Real angle, Int flags, const Dict* props, - const ThingTemplate *thingTemplate ) -{ - m_objectName = validateName( name, flags ); - m_thingTemplate = thingTemplate; - m_nextMapObject = NULL; - m_location = loc; - m_angle = normalizeAngle(angle); - m_color = (0xff)<<8; // Bright green. - m_flags = flags; - m_renderObj = NULL; - m_shadowObj = NULL; - m_runtimeFlags = 0; - // Note - do NOT set TheKey_objectSelectable on creation - allow it to follow the .ini value unless specified by user action. jba. [3/20/2003] - if (props) - { - m_properties = *props; - } - else - { - m_properties.setInt(TheKey_objectInitialHealth, 100); - m_properties.setBool(TheKey_objectEnabled, true); - m_properties.setBool(TheKey_objectIndestructible, false); - m_properties.setBool(TheKey_objectUnsellable, false); - m_properties.setBool(TheKey_objectPowered, true); - m_properties.setBool(TheKey_objectRecruitableAI, true); - m_properties.setBool(TheKey_objectTargetable, false ); - } - - for( Int i = 0; i < BRIDGE_MAX_TOWERS; ++i ) - setBridgeRenderObject( (BridgeTowerType)i, NULL ); - -} - - -MapObject::~MapObject(void) -{ - setRenderObj(NULL); - setShadowObj(NULL); - if (m_nextMapObject) { - MapObject *cur = m_nextMapObject; - MapObject *next; - while (cur) { - next = cur->getNext(); - cur->setNextMap(NULL); // prevents recursion. - deleteInstance(cur); - cur = next; - } - } - for( Int i = 0; i < BRIDGE_MAX_TOWERS; ++i ) - setBridgeRenderObject( (BridgeTowerType)i, NULL ); - -} - -MapObject *MapObject::duplicate(void) -{ - MapObject *pObj = newInstance( MapObject)(m_location, m_objectName, m_angle, m_flags, &m_properties, m_thingTemplate); - pObj->setColor(getColor()); - pObj->m_runtimeFlags = m_runtimeFlags; - return pObj; -} - -void MapObject::setRenderObj(RenderObjClass *pObj) -{ - REF_PTR_SET(m_renderObj, pObj); -} - -void MapObject::setBridgeRenderObject( BridgeTowerType type, RenderObjClass* renderObj ) -{ - - if( type >= 0 && type < BRIDGE_MAX_TOWERS ) - REF_PTR_SET( m_bridgeTowers[ type ], renderObj ); - -} - -RenderObjClass* MapObject::getBridgeRenderObject( BridgeTowerType type ) -{ - - if( type >= 0 && type < BRIDGE_MAX_TOWERS ) - return m_bridgeTowers[ type ]; - return NULL; - -} - -void MapObject::validate(void) -{ - verifyValidTeam(); - verifyValidUniqueID(); -} - -void MapObject::verifyValidTeam(void) -{ - // if this map object has a valid team, then do nothing. - // if it has an invalid team, the place it on the default neutral team, (by clearing the - // existing team name.) - Bool exists; - AsciiString teamName = getProperties()->getAsciiString(TheKey_originalOwner, &exists); - if (exists) { - Bool valid = false; - - int numSides = TheSidesList->getNumTeams(); - - for (int i = 0; i < numSides; ++i) { - TeamsInfo *teamInfo = TheSidesList->getTeamInfo(i); - if (!teamInfo) { - continue; - } - - Bool itBetter; - AsciiString testAgainstTeamName = teamInfo->getDict()->getAsciiString(TheKey_teamName, &itBetter); - if (itBetter) { - if (testAgainstTeamName.compare(teamName) == 0) { - valid = true; - } - } - } - - if (!valid) { - getProperties()->remove(TheKey_originalOwner); - } - } -} - -void MapObject::verifyValidUniqueID(void) -{ - Bool exists; - AsciiString uniqueID = getProperties()->getAsciiString(TheKey_uniqueID, &exists); - MapObject *obj = MapObject::getFirstMapObject(); - - // -1 is the sentinel - int highestIndex = -1; - - while (obj) { - if (obj == this) { - // the first object is THIS OBJECT, cause we've already been added. - obj = obj->getNext(); - continue; - } - - if (obj->isWaypoint()) { - // waypoints throw this off. Sad but true. :-( - obj = obj->getNext(); - continue; - } - - Bool iterateExists; - AsciiString tempStr = obj->getProperties()->getAsciiString(TheKey_uniqueID, &iterateExists); - const char* lastSpace = tempStr.reverseFind(' '); - - int testIndex = -1; - if (lastSpace) { - testIndex = atoi(lastSpace); - } - - if (testIndex > highestIndex) { - highestIndex = testIndex; - } - break; - } - - int indexOfThisObject = highestIndex + 1; - - const char* thingName; - if (getThingTemplate()) { - thingName = getThingTemplate()->getName().str(); - } else if (isWaypoint()) { - thingName = getWaypointName().str(); - } else { - thingName = getName().str(); - } - const char* pName = thingName; - - while (*thingName) { - if ((*thingName) == '/') { - pName = thingName + 1; - } - ++thingName; - } - - AsciiString newID; - if (isWaypoint()) { - newID.format("%s", pName); - } else { - newID.format("%s %d", pName, indexOfThisObject); - } - getProperties()->setAsciiString(TheKey_uniqueID, newID); -} - -void MapObject::fastAssignAllUniqueIDs(void) -{ - // here's what we do. Take all of them, push them onto a stack. Then, pop each one, setting its id. - // should be much faster than what we currently do. - - MapObject *pMapObj = getFirstMapObject(); - - std::stack objStack; - Int actualNumObjects = 0; - - while (pMapObj) { - ++actualNumObjects; - objStack.push(pMapObj); - pMapObj = pMapObj->getNext(); - } - - Int indexOfThisObject = 0; - while (actualNumObjects) { - MapObject *obj = objStack.top(); - - - const char* thingName; - if (obj->getThingTemplate()) { - thingName = obj->getThingTemplate()->getName().str(); - } else if (obj->isWaypoint()) { - thingName = obj->getWaypointName().str(); - } else { - thingName = obj->getName().str(); - } - const char* pName = thingName; - - while (*thingName) { - if ((*thingName) == '/') { - pName = thingName + 1; - } - ++thingName; - } - - AsciiString newID; - if (obj->isWaypoint()) { - newID.format("%s", pName); - } else { - newID.format("%s %d", pName, indexOfThisObject); - } - - obj->getProperties()->setAsciiString(TheKey_uniqueID, newID); - objStack.pop(); - - ++indexOfThisObject; - --actualNumObjects; - } -} - - - -void MapObject::setThingTemplate(const ThingTemplate *thing) -{ - m_thingTemplate = thing; - m_objectName = thing->getName(); -} - - -void MapObject::setName(AsciiString name) -{ - m_objectName = name; -} - -WaypointID MapObject::getWaypointID() { return (WaypointID)getProperties()->getInt(TheKey_waypointID); } -AsciiString MapObject::getWaypointName() { return getProperties()->getAsciiString(TheKey_waypointName); } -void MapObject::setWaypointID(Int i) { getProperties()->setInt(TheKey_waypointID, i); } -void MapObject::setWaypointName(AsciiString n) { getProperties()->setAsciiString(TheKey_waypointName, n); } - -/*static */ Int MapObject::countMapObjectsWithOwner(const AsciiString& n) -{ - Int count = 0; - for (MapObject *pMapObj = MapObject::getFirstMapObject(); pMapObj; pMapObj = pMapObj->getNext()) - { - if (pMapObj->getProperties()->getAsciiString(TheKey_originalOwner) == n) - ++count; - } - return count; -} - -//------------------------------------------------------------------------------------------------- -const ThingTemplate *MapObject::getThingTemplate( void ) const -{ - if (m_thingTemplate) - return (const ThingTemplate*) m_thingTemplate->getFinalOverride(); - - return NULL; -} - - -/* ********* WorldHeightMap class ****************************/ - -TileData *WorldHeightMap::m_alphaTiles[NUM_ALPHA_TILES]={0,0,0,0,0,0,0,0,0,0,0,0}; - -// -// WorldHeightMap destructor . -// -WorldHeightMap::~WorldHeightMap(void) -{ - delete[](m_data); - m_data = NULL; - - delete[](m_tileNdxes); - m_tileNdxes = NULL; - - delete[](m_blendTileNdxes); - m_blendTileNdxes = NULL; - - delete[](m_extraBlendTileNdxes); - m_extraBlendTileNdxes = NULL; - - delete[](m_cliffInfoNdxes); - m_cliffInfoNdxes = NULL; - - delete[](m_cellFlipState); - m_cellFlipState = NULL; - - delete[](m_seismicUpdateFlag); - m_seismicUpdateFlag = NULL; - - delete[](m_seismicZVelocities); - m_seismicZVelocities = NULL; - - delete[](m_cellCliffState); - m_cellCliffState = NULL; - - int i; - for (i=0; iclear(); -} - - -/** - WorldHeightMap - create a new height map for class WorldHeightMap. - Note that there is 1 m_numBlendedTiles, which is the implied - transparent tile for non-blended tiles. -*/ -WorldHeightMap::WorldHeightMap(): - m_width(0), m_height(0), m_dataSize(0), m_data(NULL), m_cellFlipState(NULL), m_seismicUpdateFlag(NULL), m_seismicZVelocities(NULL), - m_drawOriginX(0), m_drawOriginY(0), - m_numTextureClasses(0), - m_drawWidthX(NORMAL_DRAW_WIDTH), m_drawHeightY(NORMAL_DRAW_HEIGHT), - m_tileNdxes(NULL), m_blendTileNdxes(NULL), m_extraBlendTileNdxes(NULL), m_cliffInfoNdxes(NULL), - m_terrainTexHeight(1), m_alphaTexHeight(1), m_cellCliffState(NULL), -#ifdef EVAL_TILING_MODES - m_tileMode(TILE_4x4), -#endif - m_numCliffInfo(1), - m_terrainTex(NULL), m_alphaTerrainTex(NULL), m_numBitmapTiles(0), m_numBlendedTiles(1) -{ - Int i; - for (i=0; ivalidateSides(); - setupAlphaTiles(); -} - -#ifdef EVAL_TILING_MODES -static Bool ParseFunkyTilingDataChunk(DataChunkInput &file, DataChunkInfo *info, void *userData) -{ - WorldHeightMap *pThis = (WorldHeightMap *)userData; - *((Int *)&pThis->m_tileMode) = file.readInt(); - return true; -} -#endif - -/** -* WorldHeightMap - read a height map from a file. -* Format is Chunky. -* -* Input: ChunkInputStream, -* -*/ -WorldHeightMap::WorldHeightMap(ChunkInputStream *pStrm, Bool logicalDataOnly): - m_width(0), m_height(0), m_dataSize(0), m_data(NULL), m_cellFlipState(NULL), m_seismicUpdateFlag(NULL), m_seismicZVelocities(NULL), - m_drawOriginX(0), m_cellCliffState(NULL), m_drawOriginY(0), - m_numTextureClasses(0), - m_drawWidthX(NORMAL_DRAW_WIDTH), m_drawHeightY(NORMAL_DRAW_HEIGHT), - m_tileNdxes(NULL), m_blendTileNdxes(NULL), m_extraBlendTileNdxes(NULL), m_cliffInfoNdxes(NULL), - m_terrainTexHeight(1), m_alphaTexHeight(1), -#ifdef EVAL_TILING_MODES - m_tileMode(TILE_4x4), -#endif - m_numCliffInfo(1), - m_terrainTex(NULL), m_alphaTerrainTex(NULL), m_numBitmapTiles(0), m_numBlendedTiles(1) -{ - - int i; - for (i=0; im_stretchTerrain) { - m_drawWidthX=STRETCH_DRAW_WIDTH; - m_drawHeightY=STRETCH_DRAW_HEIGHT; - } - - DataChunkInput file( pStrm ); - - if (logicalDataOnly) { - file.registerParser( "HeightMapData", AsciiString::TheEmptyString, ParseSizeOnlyInChunk ); - file.registerParser( "WorldInfo", AsciiString::TheEmptyString, ParseWorldDictDataChunk ); - file.registerParser( "ObjectsList", AsciiString::TheEmptyString, ParseObjectsDataChunk ); - freeListOfMapObjects(); // just in case. - file.registerParser( "PolygonTriggers", AsciiString::TheEmptyString, PolygonTrigger::ParsePolygonTriggersDataChunk ); - PolygonTrigger::deleteTriggers(); // just in case. - TheSidesList->emptySides(); - file.registerParser("SidesList", AsciiString::TheEmptyString, SidesList::ParseSidesDataChunk ); - } else { - file.registerParser( "HeightMapData", AsciiString::TheEmptyString, ParseHeightMapDataChunk ); - file.registerParser( "BlendTileData", AsciiString::TheEmptyString, ParseBlendTileDataChunk ); -#ifdef EVAL_TILING_MODES - file.registerParser( "FUNKY_TILING", AsciiString::TheEmptyString, ParseFunkyTilingDataChunk ); -#endif - file.registerParser( "GlobalLighting", AsciiString::TheEmptyString, ParseLightingDataChunk ); - } - if (!file.parse(this)) { - - throw(ERROR_CORRUPT_FILE_FORMAT); - } - // patch bad maps. - if (!logicalDataOnly) { - for(i=0; i= m_numCliffInfo) { - m_cliffInfoNdxes[i] = 0; - } - if (m_blendTileNdxes[i]<0 || m_blendTileNdxes[i]>= m_numBlendedTiles) { - m_blendTileNdxes[i] = 0; - } - if (m_extraBlendTileNdxes[i]<0 || m_extraBlendTileNdxes[i]>= m_numBlendedTiles) { - m_extraBlendTileNdxes[i] = 0; - } - } - } - if (TheGlobalData && TheGlobalData->m_drawEntireTerrain) { - m_drawWidthX=m_width; - m_drawHeightY=m_height; - } - if (m_drawWidthX > m_width) { - m_drawWidthX = m_width; - } - if (m_drawHeightY > m_height) { - m_drawHeightY = m_height; - } - - TheSidesList->validateSides(); - setupAlphaTiles(); -} - -/** Optimized version of method to get triangle flip state of a terrain cell. Use this -* instead of getAlphaUVData() whenever possible. -*/ -Bool WorldHeightMap::getFlipState(Int xIndex, Int yIndex) const -{ - if (xIndex<0 || yIndex<0) return false; - if (yIndex>=m_height) return false; - if (xIndex>=m_width) return false; - if (!m_cellFlipState) return false; - return m_cellFlipState[yIndex*m_flipStateWidth + (xIndex >> 3)] & (1<<(xIndex&0x7)); -} - -/** Sets the value of the flip state bit. -*/ -void WorldHeightMap::setFlipState(Int xIndex, Int yIndex, Bool value) -{ - if (xIndex<0 || yIndex<0) return ; - if (yIndex>=m_height) return ; - if (xIndex>=m_width) return ; - if (!m_cellFlipState) return ; - UnsignedByte *curVal = &m_cellFlipState[yIndex*m_flipStateWidth + (xIndex >> 3)]; - if (value) { - *curVal |= (1<<(xIndex&0x7)); - } else { - *curVal &= ~(1<<(xIndex&0x7)); - } -} - -/** Clears all flip state bits. -*/ -void WorldHeightMap::clearFlipStates(void) { - if (m_cellFlipState) { - memset(m_cellFlipState,0,m_flipStateWidth*m_height); //clear all flags - } -} - -//////////////////////////////////////////////////////////////////////////////m_SeismicUpdateFlag -Bool WorldHeightMap::getSeismicUpdateFlag(Int xIndex, Int yIndex) const -{ - if (xIndex<0 || yIndex<0) return false; - if (yIndex>=m_height) return false; - if (xIndex>=m_width) return false; - if (!m_seismicUpdateFlag) return false; - return m_seismicUpdateFlag[yIndex*m_seismicUpdateWidth + (xIndex >> 3)] & (1<<(xIndex&0x7)); -} -void WorldHeightMap::setSeismicUpdateFlag(Int xIndex, Int yIndex, Bool value) -{ - if (xIndex<0 || yIndex<0) return ; - if (yIndex>=m_height) return ; - if (xIndex>=m_width) return ; - if (!m_seismicUpdateFlag) return ; - UnsignedByte *curVal = &m_seismicUpdateFlag[yIndex*m_seismicUpdateWidth + (xIndex >> 3)]; - if (value) { - *curVal |= (1<<(xIndex&0x7)); - } else { - *curVal &= ~(1<<(xIndex&0x7)); - } -} -void WorldHeightMap::clearSeismicUpdateFlags(void) -{ - if (m_seismicUpdateFlag) { - memset(m_seismicUpdateFlag,0,m_seismicUpdateWidth*m_height); //clear all flags - } -} - -///////////////////////////////////////////////m_SeismicZVelocities -Real WorldHeightMap::getSeismicZVelocity(Int xIndex, Int yIndex) const -{ - if (xIndex<0 || yIndex<0) return false; - if (yIndex>=m_height) return false; - if (xIndex>=m_width) return false; - if (!m_seismicZVelocities) return false; - return m_seismicZVelocities[yIndex*m_width + xIndex]; -} -void WorldHeightMap::setSeismicZVelocity(Int xIndex, Int yIndex, Real value) -{ - if (xIndex<0 || yIndex<0) return ; - if (yIndex>=m_height) return ; - if (xIndex>=m_width) return ; - if (!m_seismicZVelocities) return ; - m_seismicZVelocities[yIndex*m_width + xIndex] = value; -} -void WorldHeightMap::fillSeismicZVelocities( Real value ) -{ - if (!m_seismicZVelocities) return ; - for (Int idx = 0; idx < m_width*m_height; ++idx) - m_seismicZVelocities[idx] = value; -} - -Real WorldHeightMap::getBilinearSampleSeismicZVelocity( Int x, Int y) -{ - if ( x < 0 || y < 0 ) return 0; - if ( y >= m_height ) return 0; - if ( x >= m_width ) return 0; - if (!m_seismicZVelocities) return 0; - - Real collector = 0.0f; - Real divisor = 0.0f; - - collector += m_seismicZVelocities[ y * m_width + x ]; - ++divisor; - - if ( y > 0 ) - { - collector += m_seismicZVelocities[ (y-1) * m_width + x ];//bottom - ++divisor; - - if( x > 0 ) - { - collector += m_seismicZVelocities[ (y-1) * m_width + (x-1) ];//lower left - ++divisor; - } - if ( x < m_width-1 ) - { - collector += m_seismicZVelocities[ (y-1) * m_width + (x+1) ];//lower right - ++divisor; - } - } - if ( y < m_height-1 ) - { - collector += m_seismicZVelocities[ (y+1) * m_width + x ];//top - ++divisor; - - if( x > 0 ) - { - collector += m_seismicZVelocities[ (y+1) * m_width + (x-1) ];//upper left - ++divisor; - } - if ( x < m_width-1 ) - { - collector += m_seismicZVelocities[ (y+1) * m_width + (x+1) ];//upper right - ++divisor; - } - } - if( x > 0 ) - { - collector += m_seismicZVelocities[ y * m_width + (x-1) ];//left - ++divisor; - } - if ( x < m_width-1 ) - { - collector += m_seismicZVelocities[ y * m_width + (x+1) ];//right - ++divisor; - } - - collector /= divisor; - - return collector; - -} - -/** Get whether the cell is a cliff cell (impassable to ground vehicles). -*/ -Bool WorldHeightMap::getCliffState(Int xIndex, Int yIndex) const -{ - if (xIndex<0 || yIndex<0) return false; - if (yIndex>=m_height) return false; - if (xIndex>=m_width) return false; - if (!m_cellCliffState) return false; - return m_cellCliffState[yIndex*m_flipStateWidth + (xIndex >> 3)] & (1<<(xIndex&0x7)); -} - -//============================================================================= -// setCliffState -//============================================================================= -/** Sets the cliff state for a given cell. */ -//============================================================================= -void WorldHeightMap::setCliffState(Int xIndex, Int yIndex, Bool state) -{ - if (xIndex<0 || yIndex<0) return; - if (yIndex>=m_height) return; - if (xIndex>=m_width) return; - if (!m_cellCliffState) return; - UnsignedByte flagByte = m_cellCliffState[yIndex*m_flipStateWidth + (xIndex >> 3)]; - UnsignedByte flagMask = (1<<(xIndex&0x7)); - if (state) { - flagByte |= flagMask; - } else { - flagByte &= (~flagMask); - } - m_cellCliffState[yIndex*m_flipStateWidth + (xIndex >> 3)] = flagByte; -} - -Bool WorldHeightMap::ParseWorldDictDataChunk(DataChunkInput &file, DataChunkInfo *info, void *userData) -{ - Dict d = file.readDict(); - *MapObject::getWorldDict() = d; - Bool exists; - Int theWeather = MapObject::getWorldDict()->getInt(TheKey_weather, &exists); - if (exists) { - TheWritableGlobalData->m_weather = (Weather) theWeather; - } - return true; -} - -/** -* WorldHeightMap::ParseLightingDataChunk - read a global lights chunk. -* Format is the newer CHUNKY format. -* See WHeightMapEdit.cpp for the writer. -* Input: DataChunkInput -* -*/ -Bool WorldHeightMap::ParseLightingDataChunk(DataChunkInput &file, DataChunkInfo *info, void *userData) -{ - TheWritableGlobalData->m_timeOfDay = (TimeOfDay)file.readInt(); - Int i; - GlobalData::TerrainLighting initLightValues = { { 0,0,0},{0,0,0},{0,0,-1.0f}}; - - // initialize the directions of the lights to not be totally invalid, in case old maps are read - for (i=0; i<4; i++) { - for (Int j=0;jm_terrainObjectsLighting[i+TIME_OF_DAY_FIRST][j]=initLightValues; - TheWritableGlobalData->m_terrainLighting[i+TIME_OF_DAY_FIRST][j]=initLightValues; - } - } - - for (i=0; i<4; i++) { - TheWritableGlobalData->m_terrainLighting[i+TIME_OF_DAY_FIRST][0].ambient.red = file.readReal(); - TheWritableGlobalData->m_terrainLighting[i+TIME_OF_DAY_FIRST][0].ambient.green = file.readReal(); - TheWritableGlobalData->m_terrainLighting[i+TIME_OF_DAY_FIRST][0].ambient.blue = file.readReal(); - TheWritableGlobalData->m_terrainLighting[i+TIME_OF_DAY_FIRST][0].diffuse.red = file.readReal(); - TheWritableGlobalData->m_terrainLighting[i+TIME_OF_DAY_FIRST][0].diffuse.green = file.readReal(); - TheWritableGlobalData->m_terrainLighting[i+TIME_OF_DAY_FIRST][0].diffuse.blue = file.readReal(); - TheWritableGlobalData->m_terrainLighting[i+TIME_OF_DAY_FIRST][0].lightPos.x = file.readReal(); - TheWritableGlobalData->m_terrainLighting[i+TIME_OF_DAY_FIRST][0].lightPos.y = file.readReal(); - TheWritableGlobalData->m_terrainLighting[i+TIME_OF_DAY_FIRST][0].lightPos.z = file.readReal(); - - TheWritableGlobalData->m_terrainObjectsLighting[i+TIME_OF_DAY_FIRST][0].ambient.red = file.readReal(); - TheWritableGlobalData->m_terrainObjectsLighting[i+TIME_OF_DAY_FIRST][0].ambient.green = file.readReal(); - TheWritableGlobalData->m_terrainObjectsLighting[i+TIME_OF_DAY_FIRST][0].ambient.blue = file.readReal(); - TheWritableGlobalData->m_terrainObjectsLighting[i+TIME_OF_DAY_FIRST][0].diffuse.red = file.readReal(); - TheWritableGlobalData->m_terrainObjectsLighting[i+TIME_OF_DAY_FIRST][0].diffuse.green = file.readReal(); - TheWritableGlobalData->m_terrainObjectsLighting[i+TIME_OF_DAY_FIRST][0].diffuse.blue = file.readReal(); - TheWritableGlobalData->m_terrainObjectsLighting[i+TIME_OF_DAY_FIRST][0].lightPos.x = file.readReal(); - TheWritableGlobalData->m_terrainObjectsLighting[i+TIME_OF_DAY_FIRST][0].lightPos.y = file.readReal(); - TheWritableGlobalData->m_terrainObjectsLighting[i+TIME_OF_DAY_FIRST][0].lightPos.z = file.readReal(); - - if (info->version >= K_LIGHTING_VERSION_2) { - for (Int j=1; j<3; j++) //added support for 2 extra object lights - { - TheWritableGlobalData->m_terrainObjectsLighting[i+TIME_OF_DAY_FIRST][j].ambient.red = file.readReal(); - TheWritableGlobalData->m_terrainObjectsLighting[i+TIME_OF_DAY_FIRST][j].ambient.green = file.readReal(); - TheWritableGlobalData->m_terrainObjectsLighting[i+TIME_OF_DAY_FIRST][j].ambient.blue = file.readReal(); - TheWritableGlobalData->m_terrainObjectsLighting[i+TIME_OF_DAY_FIRST][j].diffuse.red = file.readReal(); - TheWritableGlobalData->m_terrainObjectsLighting[i+TIME_OF_DAY_FIRST][j].diffuse.green = file.readReal(); - TheWritableGlobalData->m_terrainObjectsLighting[i+TIME_OF_DAY_FIRST][j].diffuse.blue = file.readReal(); - TheWritableGlobalData->m_terrainObjectsLighting[i+TIME_OF_DAY_FIRST][j].lightPos.x = file.readReal(); - TheWritableGlobalData->m_terrainObjectsLighting[i+TIME_OF_DAY_FIRST][j].lightPos.y = file.readReal(); - TheWritableGlobalData->m_terrainObjectsLighting[i+TIME_OF_DAY_FIRST][j].lightPos.z = file.readReal(); - } - } - if (info->version >= K_LIGHTING_VERSION_3) { - for (Int j=1; j<3; j++) //added support for 2 extra terrain lights - { - TheWritableGlobalData->m_terrainLighting[i+TIME_OF_DAY_FIRST][j].ambient.red = file.readReal(); - TheWritableGlobalData->m_terrainLighting[i+TIME_OF_DAY_FIRST][j].ambient.green = file.readReal(); - TheWritableGlobalData->m_terrainLighting[i+TIME_OF_DAY_FIRST][j].ambient.blue = file.readReal(); - TheWritableGlobalData->m_terrainLighting[i+TIME_OF_DAY_FIRST][j].diffuse.red = file.readReal(); - TheWritableGlobalData->m_terrainLighting[i+TIME_OF_DAY_FIRST][j].diffuse.green = file.readReal(); - TheWritableGlobalData->m_terrainLighting[i+TIME_OF_DAY_FIRST][j].diffuse.blue = file.readReal(); - TheWritableGlobalData->m_terrainLighting[i+TIME_OF_DAY_FIRST][j].lightPos.x = file.readReal(); - TheWritableGlobalData->m_terrainLighting[i+TIME_OF_DAY_FIRST][j].lightPos.y = file.readReal(); - TheWritableGlobalData->m_terrainLighting[i+TIME_OF_DAY_FIRST][j].lightPos.z = file.readReal(); - } - } - } - if (!file.atEndOfChunk()) { - UnsignedInt shadowColor = file.readInt(); - if (TheW3DShadowManager) { - TheW3DShadowManager->setShadowColor(shadowColor); - } - } - DEBUG_ASSERTCRASH(file.atEndOfChunk(), ("Unexpected data left over.")); - return true; -} - -/** -* WorldHeightMap::ParseObjectsDataChunk - read a height map chunk. -* Format is the newer CHUNKY format. -* See WHeightMapEdit.cpp for the writer. -* Input: DataChunkInput -* -*/ -Bool WorldHeightMap::ParseObjectsDataChunk(DataChunkInput &file, DataChunkInfo *info, void *userData) -{ - file.m_currentObject = NULL; - file.registerParser( "Object", info->label, ParseObjectDataChunk ); - return (file.parse(userData)); -} - -/** -* WorldHeightMap::ParseHeightMapData - read a height map chunk. -* Format is the newer CHUNKY format. -* See WHeightMapEdit.cpp for the writer. -* Input: DataChunkInput -* -*/ -Bool WorldHeightMap::ParseHeightMapDataChunk(DataChunkInput &file, DataChunkInfo *info, void *userData) -{ - WorldHeightMap *pThis = (WorldHeightMap *)userData; - return pThis->ParseHeightMapData(file, info, userData); -} - -/** -* WorldHeightMap::ParseHeightMapData - read a height map chunk. -* Format is the newer CHUNKY format. -* See WHeightMapEdit.cpp for the writer. -* Input: DataChunkInput -* -*/ -Bool WorldHeightMap::ParseHeightMapData(DataChunkInput &file, DataChunkInfo *info, void *userData) -{ - m_width = file.readInt(); - m_height = file.readInt(); - if (info->version >= K_HEIGHT_MAP_VERSION_3) { - m_borderSize = file.readInt(); - } else { - m_borderSize = 0; - } - - if (info->version >= K_HEIGHT_MAP_VERSION_4) { - Int numBorders = file.readInt(); - m_boundaries.resize(numBorders); - for (int i = 0; i < numBorders; ++i) { - m_boundaries[i].x = file.readInt(); - m_boundaries[i].y = file.readInt(); - } - } else { - m_boundaries.resize(1); - m_boundaries[0].x = m_width - 2 * m_borderSize; - m_boundaries[0].y = m_height - 2 * m_borderSize; - } - - m_dataSize = file.readInt(); - m_data = MSGNEW("WorldHeightMap_ParseHeightMapData") UnsignedByte[m_dataSize]; - if (m_dataSize <= 0 || (m_dataSize != (m_width*m_height))) { - throw ERROR_CORRUPT_FILE_FORMAT ; - } - - Int numBytesX = (m_width+7)/8; //how many bytes to fit all bitflags - Int numBytesY = m_height; - m_seismicUpdateWidth=numBytesX; - m_seismicUpdateFlag = MSGNEW("WorldHeightMap::ParseHeightMapData _ m_seismicUpdateFlag allocated") UnsignedByte[numBytesX*numBytesY]; - clearSeismicUpdateFlags(); - m_seismicZVelocities = MSGNEW("WorldHeightMap_ParseHeightMapData _ zvelocities allocated") Real[m_dataSize]; - fillSeismicZVelocities( 0 ); - - - file.readArrayOfBytes((char *)m_data, m_dataSize); - // Resize me. - if (info->version == K_HEIGHT_MAP_VERSION_1) { - Int newWidth = (m_width+1)/2; - Int newHeight = (m_height+1)/2; - Int i, j; - for (i=0; iParseSizeOnly(file, info, userData); -} - -/** -* WorldHeightMap::ParseHeightMapData - read a height map chunk. -* Format is the newer CHUNKY format. -* See WHeightMapEdit.cpp for the writer. -* Input: DataChunkInput -* -*/ -Bool WorldHeightMap::ParseSizeOnly(DataChunkInput &file, DataChunkInfo *info, void *userData) -{ - m_width = file.readInt(); - m_height = file.readInt(); - if (info->version >= K_HEIGHT_MAP_VERSION_3) { - m_borderSize = file.readInt(); - } else { - m_borderSize = 0; - } - - if (info->version >= K_HEIGHT_MAP_VERSION_4) { - Int numBorders = file.readInt(); - m_boundaries.resize(numBorders); - for (int i = 0; i < numBorders; ++i) { - m_boundaries[i].x = file.readInt(); - m_boundaries[i].y = file.readInt(); - } - } else { - m_boundaries.resize(1); - m_boundaries[0].x = m_width - 2 * m_borderSize; - m_boundaries[0].y = m_height - 2 * m_borderSize; - } - - m_dataSize = file.readInt(); - m_data = MSGNEW("WorldHeightMap_ParseSizeOnly") UnsignedByte[m_dataSize]; - if (m_dataSize <= 0 || (m_dataSize != (m_width*m_height))) { - throw ERROR_CORRUPT_FILE_FORMAT ; - } - file.readArrayOfBytes((char *)m_data, m_dataSize); - // Resize me. - if (info->version == K_HEIGHT_MAP_VERSION_1) { - Int newWidth = (m_width+1)/2; - Int newHeight = (m_height+1)/2; - Int i, j; - for (i=0; iParseBlendTileData(file, info, userData); -} - -/** Function to read in the tiles for a texture class. */ -void WorldHeightMap::readTexClass(TXTextureClass *texClass, TileData **tileData) -{ - char path[_MAX_PATH]; - path[0] = 0; - File *theFile = NULL; - - // get the file from the description in TheTerrainTypes - TerrainType *terrain = TheTerrainTypes->findTerrain( texClass->name ); - char texturePath[ _MAX_PATH ]; - if (terrain==NULL) - { -#ifdef LOAD_TEST_ASSETS - theFile = TheFileSystem->openFile( texClass->name.str(), File::READ|File::BINARY); -#endif - } - else - { - sprintf( texturePath, "%s%s", TERRAIN_TGA_DIR_PATH, terrain->getTexture().str() ); - theFile = TheFileSystem->openFile( texturePath, File::READ|File::BINARY); - } - - if (theFile != NULL) { - GDIFileStream theStream(theFile); - InputStream *pStr = &theStream; - Int numTiles = WorldHeightMap::countTiles(pStr); - theFile->seek(0, File::START); - if (numTiles >= texClass->numTiles) { - numTiles = texClass->numTiles; - Int width; - for (width = 10; width >= 1; width--) { - if (numTiles >= width*width) { - numTiles = width*width; - break; - } - } - WorldHeightMap::readTiles(pStr, tileData+texClass->firstTile, width); - } - theFile->close(); - } -} - -/** -* WorldHeightMap::ParseBlendTileData - read a blend tile info chunk. -* Format is the newer CHUNKY format. -* See WHeightMapEdit.cpp for the writer. -* Input: DataChunkInput -* -*/ -Bool WorldHeightMap::ParseBlendTileData(DataChunkInput &file, DataChunkInfo *info, void *userData) -{ - int i, j; - Int len = file.readInt(); - if (m_dataSize != len) { - throw ERROR_CORRUPT_FILE_FORMAT ; - } - m_tileNdxes = MSGNEW("WorldHeightMap_ParseBlendTileData") Short[m_dataSize]; - m_cliffInfoNdxes = MSGNEW("WorldHeightMap_ParseBlendTileData") Short[m_dataSize]; - m_blendTileNdxes = MSGNEW("WorldHeightMap_ParseBlendTileData") Short[m_dataSize]; - m_extraBlendTileNdxes = MSGNEW("WorldHeightMap_ParseBlendTileData") Short[m_dataSize]; - // Note - we have one less cell than the width & height. But for paranoia, allocate - // extra row. jba. - // - Int numBytesX = (m_width+7)/8; //how many bytes to fit all bitflags - Int numBytesY = m_height; - - m_flipStateWidth=numBytesX; - - m_cellFlipState = MSGNEW("WorldHeightMap_getTerrainTexture") UnsignedByte[numBytesX*numBytesY]; - m_cellCliffState = MSGNEW("WorldHeightMap_getTerrainTexture") UnsignedByte[numBytesX*numBytesY]; - memset(m_cellFlipState,0,numBytesX*numBytesY); //clear all flags - memset(m_cellCliffState,0,numBytesX*numBytesY); //clear all flags - - file.readArrayOfBytes((char*)m_tileNdxes, m_dataSize*sizeof(Short)); - file.readArrayOfBytes((char*)m_blendTileNdxes, m_dataSize*sizeof(Short)); - if (info->version >= K_BLEND_TILE_VERSION_6) { - file.readArrayOfBytes((char*)m_extraBlendTileNdxes, m_dataSize*sizeof(Short)); - //Allow clearing of extra blend tiles via ini and resaving of map. - //Useful for flushing out initial maps made with buggy 3-way blending. - if (!TheGlobalData->m_use3WayTerrainBlends) - memset(m_extraBlendTileNdxes,0,m_dataSize*sizeof(Short)); - } - if (info->version >= K_BLEND_TILE_VERSION_5) { - file.readArrayOfBytes((char*)m_cliffInfoNdxes, m_dataSize*sizeof(Short)); - } - if (info->version >= K_BLEND_TILE_VERSION_7) { - if (info->version==K_BLEND_TILE_VERSION_7) { - Int byteWidth = (m_width+1)/8; // previous incorrect length that got used to save the file. jba. [4/3/2003] - UnsignedByte *data = new UnsignedByte[m_height*byteWidth]; - file.readArrayOfBytes((char*)data, m_height*byteWidth); - for (j=0; j0 && m_numBitmapTiles<2048, ("Unlikely numBitmapTiles.")); - m_numBlendedTiles = file.readInt(); - DEBUG_ASSERTCRASH(m_numBlendedTiles>0 && m_numBlendedTilesversion >= K_BLEND_TILE_VERSION_5) { - m_numCliffInfo = file.readInt(); - } else { - m_numCliffInfo = 1; // cliffInfo[0] is the default info. - } -// --> file loading here - m_numTextureClasses = file.readInt(); - DEBUG_ASSERTCRASH(m_numTextureClasses>0 && m_numTextureClasses<200, ("Unlikely m_numTextureClasses.")); - for (i=0; iversion >= K_BLEND_TILE_VERSION_4) { - m_numEdgeTiles = file.readInt(); - m_numEdgeTextureClasses = file.readInt(); - for (i=0; im_use3WayTerrainBlends) - m_blendedTiles[i].inverted &= ~FLIPPED_MASK; //filter out extra flips from 3-way - - if (info->version >= K_BLEND_TILE_VERSION_3) { - m_blendedTiles[i].longDiagonal = file.readByte(); - } else { - m_blendedTiles[i].longDiagonal = false; - } - if (info->version >= K_BLEND_TILE_VERSION_4) { - m_blendedTiles[i].customBlendEdgeClass = file.readInt(); - } else { - m_blendedTiles[i].customBlendEdgeClass = -1; - } - - flag = file.readInt(); - DEBUG_ASSERTCRASH(flag==FLAG_VAL, ("Invalid format.")); - if (flag != FLAG_VAL) { - throw ERROR_CORRUPT_FILE_FORMAT; - } - } - if (info->version >= K_BLEND_TILE_VERSION_5) { - for (i=1; iversion == K_BLEND_TILE_VERSION_1) { - Int newWidth = (m_width+1)/2; - Int newHeight = (m_height+1)/2; - Int i, j; - for (i=0; iParseObjectData(file, info, userData, info->version >= K_OBJECTS_VERSION_2); -} - -/** -* WorldHeightMap::ParseObjectData - read a object info chunk. -* Format is the newer CHUNKY format. -* See WHeightMapEdit.cpp for the writer. -* Input: DataChunkInput -* -*/ -Bool WorldHeightMap::ParseObjectData(DataChunkInput &file, DataChunkInfo *info, void *userData, Bool readDict) -{ - MapObject *pPrevious = (MapObject *)file.m_currentObject; - - Coord3D loc; - loc.x = file.readReal(); - loc.y = file.readReal(); - loc.z = file.readReal(); - - Real minZ = -100*MAP_XY_FACTOR; - Real maxZ = (255*10)*MAP_HEIGHT_SCALE; - - if (info->version <= K_OBJECTS_VERSION_2) { - loc.z = 0; - } - - Real angle = file.readReal(); - Int flags = file.readInt(); - AsciiString name = file.readAsciiString(); - Dict d; - if (readDict) - { - d = file.readDict(); - } - - if (loc.zmaxZ) { - DEBUG_LOG(("Removing object at z height %f", loc.z)); - return true; - } - - MapObject *pThisOne; - - // create the map object - pThisOne = newInstance( MapObject )( loc, name, angle, flags, &d, - TheThingFactory->findTemplate( name, FALSE ) ); - -//DEBUG_LOG(("obj %s owner %s",name.str(),d.getAsciiString(TheKey_originalOwner).str())); - - if (pThisOne->getProperties()->getType(TheKey_waypointID) == Dict::DICT_INT) - pThisOne->setIsWaypoint(); - - if (pThisOne->getProperties()->getType(TheKey_lightHeightAboveTerrain) == Dict::DICT_REAL) - pThisOne->setIsLight(); - - if (pThisOne->getProperties()->getType(TheKey_scorchType) == Dict::DICT_INT) - pThisOne->setIsScorch(); - - - if (pPrevious) { - DEBUG_ASSERTCRASH(MapObject::TheMapObjectListPtr != NULL && pPrevious->getNext() == NULL, ("Bad linkage.")); - pPrevious->setNextMap(pThisOne); - } else { - DEBUG_ASSERTCRASH(MapObject::TheMapObjectListPtr == NULL, ("Bad linkage.")); - MapObject::TheMapObjectListPtr = pThisOne; - } - file.m_currentObject = pThisOne; - return true; -} - - - -// Targa format: Header - -typedef struct { - UnsignedByte idLength; - UnsignedByte colorMapType; // 0 = rgb, 1 = indexed. - UnsignedByte imageType; //0x1 = indexed, 0x2 = rgb, 0x8 = rle. - UnsignedByte colorMapInfo[5]; // we ignore, only do rgb. - Short xOrigin; - Short yOrigin; - Short imageWidth; - Short imageHeight; - UnsignedByte pixelDepth; - UnsignedByte flags; // &0x0F = alpha channel bits, &0x10 is right to left flag, - // 0x20 is top to bottom flag. (0x0? is left to right, bottom to top) - // 0x3? is top to bottom, right to left. -} TTargaHeader; - -// followed by idLength bytes of ascii data - -// followed by pixel data - -// followed by optional data. - - - -/// Count how many tiles come in from a targa file. -Int WorldHeightMap::countTiles(InputStream *pStr, Bool *halfTile) -{ - TTargaHeader hdr; - if (halfTile) { - *halfTile = false; - } - Int len = pStr->read(&hdr,sizeof(hdr)); - if (len!=sizeof(hdr)) return(0); - Int tileWidth = hdr.imageWidth/TILE_PIXEL_EXTENT; - Int tileHeight = hdr.imageHeight/TILE_PIXEL_EXTENT; - - if (hdr.colorMapType != 0) { - return(0); // we don't do indexed at this time. jba. - } - if (hdr.imageType != 0x2 && hdr.imageType != 0xA) { - return(0); // we don't do indexed at this time. jba. - } - - if (hdr.pixelDepth < 24) return(false); - if (hdr.pixelDepth > 32) return(false); - // 3x3 gives 9, - // 2x2 gives 4, - // 1x1 gives 1, - // else 0; - if (tileWidth>10 || tileHeight>10) return(0); // don't do huge images, or bad files. - if (tileWidth>=10 && tileHeight >=10) return(100); - if (tileWidth>=9 && tileHeight >=9) return(81); - if (tileWidth>=8 && tileHeight >=8) return(64); - if (tileWidth>=7 && tileHeight >=7) return(49); - if (tileWidth>=6 && tileHeight >=6) return(36); - if (tileWidth>=5 && tileHeight >=5) return(25); - if (tileWidth>=4 && tileHeight >=4) return(16); - if (tileWidth>=3 && tileHeight >=3) return(9); - if (tileWidth>=2 && tileHeight >=2) return(4); - if (tileWidth>=1 && tileHeight >=1) return(1); - if (halfTile && hdr.imageHeight==TILE_PIXEL_EXTENT/2 && hdr.imageWidth==TILE_PIXEL_EXTENT/2) { - *halfTile = true; - return 1; - } - return(0); -} -/*Break down a .tga file into a collection of tiles. numRows * numRows total tiles.*/ -Bool WorldHeightMap::readTiles(InputStream *pStr, TileData **tiles, Int numRows) -{ - TTargaHeader hdr; - pStr->read(&hdr, sizeof(hdr)); - Int tileWidth = hdr.imageWidth/TILE_PIXEL_EXTENT; - Int tileHeight = hdr.imageHeight/TILE_PIXEL_EXTENT; - - if (hdr.imageHeight==TILE_PIXEL_EXTENT/2) { - tileHeight = 1; - } - if (hdr.imageWidth==TILE_PIXEL_EXTENT/2) { - tileWidth = 1; - } - - if (tileWidth 4) return(false); - int i; - for (i=0; iread(&flag, 1); - repeatCount = flag&0x7f; - repeatCount++; - if (flag&0x80) { - running = true; - pStr->read(buf, bytesPerPixel); - } else { - running = false; - } - } - if (compressed) repeatCount--; - if (!running) { - pStr->read(buf, bytesPerPixel); - } - r = buf[2]; g = buf[1]; b = buf[0]; - if (bytesPerPixel==4) { - a = buf[3]; - } else { - a = 255;// solid alpha. - } - } else { - r = g = b = a = 0; - } - if (column >= (numRows*TILE_PIXEL_EXTENT)) continue; - int tileNdx = (column/TILE_PIXEL_EXTENT) + numRows*(row/TILE_PIXEL_EXTENT); - int pixelNdx = (column%TILE_PIXEL_EXTENT) + TILE_PIXEL_EXTENT*(row%TILE_PIXEL_EXTENT); - - UnsignedByte *pixel = tiles[tileNdx]->getDataPtr(); - - pixel += pixelNdx*TILE_BYTES_PER_PIXEL; - *pixel++ = b; - *pixel++ = g; - *pixel++ = r; - *pixel = a; - - } - DEBUG_ASSERTCRASH(repeatCount==0, ("Invalid tga.")); - } - for (i=0; iupdateMips(); - } - return(true); -} - - - -/** updateTileTexturePositions - assigns each tile a location in the texture. -*/ -Int WorldHeightMap::updateTileTexturePositions(Int *edgeHeight) -{ - Int i, j; - Int maxHeight = 0; - const Int tilesPerRow = TEXTURE_WIDTH/(TILE_PIXEL_EXTENT+TILE_OFFSET); - - Bool availableGrid[tilesPerRow][tilesPerRow]; - Int row, column; - for (row=0; rowm_tileLocationInTexture.x = 0; - m_sourceTiles[i]->m_tileLocationInTexture.y = 0; - } - } - - /* put the normal tiles into the terrain texture */ - Int texClass; - Int tileWidth; - for (tileWidth = tilesPerRow; tileWidth>0; tileWidth--) { - for (texClass=0; texClassm_tileLocationInTexture.x = x; - m_sourceTiles[baseNdx]->m_tileLocationInTexture.y = y; - } - } - } - } - - for (i=0; im_tileLocationInTexture.x = 0; - m_edgeTiles[i]->m_tileLocationInTexture.y = 0; - } - } - - /* put the blend edge tiles into the blend edges texture */ - Int maxEdgeHeight = 0; - // Reset the grid, cause we're using a different texture now. - for (row=0; rowm_tileLocationInTexture.x = x; - m_edgeTiles[baseNdx]->m_tileLocationInTexture.y = y; - } - } - } - if (edgeHeight) *edgeHeight = maxEdgeHeight; - return maxHeight; -} - -/** getUVData - Gets the texture coordinates to use. See getTerrainTexture. -*/ -void WorldHeightMap::getUVForNdx(Int tileNdx, float *minU, float *minV, float *maxU, float*maxV, Bool fullTile) -{ - Short baseNdx = tileNdx>>2; - if (m_sourceTiles[baseNdx] == NULL) { - // Missing texture. - *minU = *minV = *maxU = *maxV = 0.0f; - return; - } - ICoord2D pos = m_sourceTiles[baseNdx]->m_tileLocationInTexture; - *minU = pos.x; - *minV = pos.y; - *maxU = *minU+TILE_PIXEL_EXTENT; - *maxV = *minV+TILE_PIXEL_EXTENT; -#ifdef EVAL_TILING_MODES - if (m_tileMode == TILE_8x8) { - *maxU = *minU+TILE_PIXEL_EXTENT/2.0f; - *maxV = *minV+TILE_PIXEL_EXTENT/2.0f; - } else if (m_tileMode == TILE_6x6) { - *maxU = *minU+2.0f*TILE_PIXEL_EXTENT/3.0f; - *maxV = *minV+2.0f*TILE_PIXEL_EXTENT/3.0f; - } else { - *maxU = *minU+TILE_PIXEL_EXTENT; - *maxV = *minV+TILE_PIXEL_EXTENT; - } -#endif - *minU/=TEXTURE_WIDTH; - *minV/=m_terrainTexHeight; - *maxU/=TEXTURE_WIDTH; - *maxV/=m_terrainTexHeight; - if (!fullTile) { - // Tiles are 64x64 pixels, height grids map to 32x32. - // So get the proper quadrant of the tile. - Real midX = (*minU+*maxU)/2; - Real midY = (*minV+*maxV)/2; - if (tileNdx&2) { // y's are flipped. - *maxV = midY; - } else { - *minV = midY; - } - if (tileNdx&1) { - *minU = midX; - } else { - *maxU = midX; - } - } -} - -/** getUVData - Gets the texture coordinates to use. See getTerrainTexture. -*/ -void WorldHeightMap::getUVForBlend(Int edgeClass, Region2D *range) -{ - ICoord2D pos = m_edgeTextureClasses[edgeClass].positionInTexture; - Int width = m_edgeTextureClasses[edgeClass].width; - range->lo.x = (Real)pos.x/TEXTURE_WIDTH; - range->lo.y = (Real)pos.y/m_alphaEdgeHeight; - range->hi.x = ((Real)pos.x + width*TILE_PIXEL_EXTENT)/TEXTURE_WIDTH; - range->hi.y = ((Real)pos.y + width*TILE_PIXEL_EXTENT)/m_alphaEdgeHeight; -} - -/// Get whether something is cliff indexed with the offset that HeightMapRenderObjClass uses built in. -Bool WorldHeightMap::isCliffMappedTexture(Int x, Int y) { - Int ndx = x+m_drawOriginX+m_width*(y+m_drawOriginY); - if (ndx>=0 && ndxm_adjustCliffTextures) { - return false; - } - if (nU==0.0) { - return false; // missing texture. - } - if (fullTile) { - return false; - } - if (m_cliffInfoNdxes[ndx]) { - TCliffInfo info = m_cliffInfo[m_cliffInfoNdxes[ndx]]; - Bool tilesMatch = false; - Int ndx1 = tileNdx>>2; - Int ndx2 = info.tileIndex>>2; - Int i; - for (i=0; im_numTextureClasses; i++) { - if (ndx1 >= m_textureClasses[i].firstTile && ndx1 < m_textureClasses[i].firstTile + m_textureClasses[i].numTiles) { - tilesMatch = ndx2 >= m_textureClasses[i].firstTile && ndx2 < m_textureClasses[i].firstTile + m_textureClasses[i].numTiles; - //tilesMatch = true; - break; - } - } - if (tilesMatch) { - Real minU = m_textureClasses[i].positionInTexture.x; - Real maxV = m_textureClasses[i].positionInTexture.y + m_textureClasses[i].width*TILE_PIXEL_EXTENT; - minU/=TEXTURE_WIDTH; - maxV/=m_terrainTexHeight; - Real vFactor = TEXTURE_WIDTH/m_terrainTexHeight; - U[0] = info.u0+minU; - U[1] = info.u1+minU; - U[2] = info.u2+minU; - U[3] = info.u3+minU; - V[0] = info.v0*vFactor+maxV; - V[1] = info.v1*vFactor+maxV; - V[2] = info.v2*vFactor+maxV; - V[3] = info.v3*vFactor+maxV; - return info.flip; - } - } -#define DO_OLD_UV -#ifdef DO_OLD_UV -// old uv adjustment for cliffs - static Real STRETCH_LIMIT = 1.5f; // If it is stretching less than this, don't adjust. - static Real TILE_LIMIT = 4.0; // Our tiles are currently 4 cells wide & tall, so dont' - // adjust to more than 4.0. - - static Real TALL_STRETCH_LIMIT = 2.0f; - static Real DIAMOND_STRETCH_LIMIT = 2.4f; - static Real HEIGHT_SCALE = MAP_HEIGHT_SCALE / MAP_XY_FACTOR; - - Real nU, nV, xU, xV; - nU=nV=xU=xV = 0.0f; - Int tilesPerRow = TEXTURE_WIDTH/(2*TILE_PIXEL_EXTENT+TILE_OFFSET); - tilesPerRow *= 4; - - - getUVForNdx(tileNdx, &nU, &nV, &xU, &xV, fullTile); - U[0] = nU; U[1] = xU; U[2] = xU; U[3] = nU; - V[0] = xV; V[1] = xV; V[2] = nV; V[3] = nV; - if (TheGlobalData && !TheGlobalData->m_adjustCliffTextures) { - return false; - } - if (nU==0.0) { - return false; // missing texture. - } - if (fullTile) { - return false; - } - // check for excessive heights. - if (ndx < this->m_dataSize - m_width - 1) { - Int h0 = m_data[ndx]; - Int h1 = m_data[ndx+1]; - Int h2 = m_data[ndx+m_width+1]; - Int h3 = m_data[ndx+m_width]; - Int minH, maxH; - minH = maxH = h0; - if (minH>h1) minH = h1; - if (maxHh2) minH = h2; - if (maxHh3) minH = h3; - if (maxHaboveLimit) above++; - if (h1>aboveLimit) above++; - if (h2>aboveLimit) above++; - if (h3>aboveLimit) above++; - if (deltaH*HEIGHT_SCALE < STRETCH_LIMIT) { - return false; - } - - Short baseNdx = tileNdx>>2; - Short texClass; - for (texClass=0; texClass= m_textureClasses[texClass].firstTile && - baseNdx < m_textureClasses[texClass].firstTile+m_textureClasses[texClass].numTiles) { - break; - } - } - if (texClass>= m_numTextureClasses) return false; - Real nUb, nVb, xUb, xVb; - nUb = m_textureClasses[texClass].positionInTexture.x; - nVb = m_textureClasses[texClass].positionInTexture.y; - xUb = nUb+m_textureClasses[texClass].width*TILE_PIXEL_EXTENT; - xVb = nVb+m_textureClasses[texClass].width*TILE_PIXEL_EXTENT; - nUb/=TEXTURE_WIDTH; - nVb/=m_terrainTexHeight; - xUb/=TEXTURE_WIDTH; - xVb/=m_terrainTexHeight; - // Now covers texture bounds. - // too much stretch. - Real divisor = TILE_LIMIT/(deltaH*HEIGHT_SCALE); - if (divisor > TILE_LIMIT) divisor = TILE_LIMIT; - if (divisor < 1.0f) divisor = 1.0f; - Real deltaV = (xVb-nVb); -// Real deltaU = (xUb-nUb); - - if (above != 1 && below != 1 && (above!=2 || below != 2)) { - // diamond shaped. Use default if it is not too stretched, as - // the fix is not that appealing either. - if (deltaH*HEIGHT_SCALE < DIAMOND_STRETCH_LIMIT) { - return false; - } - } - - if (below==1 || above>below) { //(avgH > minH + (2*deltaH+2)/3) - // we got one low guy. - if (h0==minH) { - V[0] = nV+deltaV/divisor; - } else if (h1 == minH) { - V[1] = nV+deltaV/divisor; - } else if (h2 == minH) { - V[2] = xV-deltaV/divisor; - } else if (h3 == minH) { - V[3] = xV-deltaV/divisor; - } -#if 0 - nU = nV = xU = xV = 1.0f; - U[0] = nU; U[1] = xU; U[2] = xU; U[3] = nU; - V[0] = xV; V[1] = xV; V[2] = nV; V[3] = nV; - return false; -#endif - } else if (above==1 || below>above) { //(avgH < minH + (deltaH+1)/3) - // we got one high guy - if (h0==maxH) { - V[0] = nV+deltaV/divisor; - } else if (h1 == maxH) { - V[1] = nV+deltaV/divisor; - } else if (h2 == maxH) { - V[2] = xV-deltaV/divisor; - } else if (h3 == maxH) { - V[3] = xV-deltaV/divisor; - } -#if 0 - nU = nV = xU = xV = 0.0f; - U[0] = nU; U[1] = xU; U[2] = xU; U[3] = nU; - V[0] = xV; V[1] = xV; V[2] = nV; V[3] = nV; - return false; -#endif - } else { - // we got two up and two down. - if (deltaH*HEIGHT_SCALE < TALL_STRETCH_LIMIT) { - return false; - } -#if 0 - nU = nV = xU = xV = 0.0f; - U[0] = nU; U[1] = xU; U[2] = xU; U[3] = nU; - V[0] = xV; V[1] = xV; V[2] = nV; V[3] = nV; - return; -#endif - Real dx = (h3-h2)*HEIGHT_SCALE; - dx = sqrt(1+dx*dx); // lenght of the bottom of the cell - Real dy = (h3-h0)*HEIGHT_SCALE; - dy = sqrt(1+dy*dy); // length of the left side. - if (dxTILE_LIMIT) dx = TILE_LIMIT; // don't tile past the texture's edge. - if (dy>TILE_LIMIT) dy = TILE_LIMIT; // don't tile past the texture's edge. - dx *= xU-nU; - dy *= xV-nV; - U[0] = nU; U[1] = nU+dx; U[2] = nU+dx; U[3] = nU; - V[0] = nV+dy; V[1] = nV+dy; V[2] = nV; V[3] = nV; - if (below==1) { - below = 1; - } - // recalc for point 1. - dx = (h1-h0)*HEIGHT_SCALE; - dx = sqrt(1+dx*dx); // lenght of the bottom of the cell - dy = (h2-h1)*HEIGHT_SCALE; - dy = sqrt(1+dy*dy); // length of the left side. - if (dxTILE_LIMIT) dx = TILE_LIMIT; // don't tile past the texture's edge. - if (dy>TILE_LIMIT) dy = TILE_LIMIT; // don't tile past the texture's edge. - dx *= xU-nU; - dy *= xV-nV; - U[1] = U[0]+dx; - V[1] = V[3] + dy; - } - // Make sure we are within the texture; - Real adjU = 0; - Real adjV = 0; - Int i; - for (i=0; i<4; i++) { - if (nVb - V[i] > adjV) adjV = nVb - V[i]; - } - for (i=0; i<4; i++) { - V[i] += adjV; - } - adjV = 0; - for (i=0; i<4; i++) { - if (U[i] - xUb > adjU) adjU = U[i]-xUb; - if (V[i] - xVb > adjV) adjV = V[i]-xVb; - } - for (i=0; i<4; i++) { - U[i] -= adjU; - V[i] -= adjV; - } - } - return true; -// -#endif - - } - return false; -} - -///@todo: Are the different "if" cases mutually exclusive? If so, should add else statements. -Bool WorldHeightMap::getExtraAlphaUVData(Int xIndex, Int yIndex, float U[4], float V[4], UnsignedByte alpha[4], Bool *needFlip, Bool *cliff) -{ - Int ndx = (yIndex*m_width)+xIndex; - *needFlip = FALSE; - *cliff = FALSE; - - if ( (ndx>=0) && (ndx=0) { - alpha[0] = alpha[1] = alpha[2] = alpha[3] = 0; - // No alpha blend, so never need to flip. - *needFlip = FALSE; - } - } - } - - return TRUE; -} - -/** getUVData - Gets the texture coordinates to use with the alpha texture. - xIndex and yIndex are the integer coorddinates into the height map. - U and V are the texture coordiantes for the 4 corners of a height map cell. - fullTile is true if we are doing 1/2 resolution height map, and require a full - tile to texture a cell. Otherwise, we use quarter tiles per cell. - flip is set if we need to flip the diagonal across the cell to make the - alpha coordinates blend properly. Filling a square with 2 triangles is not symmetrical :) -*/ -void WorldHeightMap::getAlphaUVData(Int xIndex, Int yIndex, float U[4], float V[4], - UnsignedByte alpha[4], Bool *flip, Bool fullTile) -{ - xIndex += m_drawOriginX; - yIndex += m_drawOriginY; - Int ndx = (yIndex*m_width)+xIndex; - Bool stretchedForCliff = false; - Bool needFlip = false; - - if ((ndx=0) { - alpha[0] = alpha[1] = alpha[2] = alpha[3] = 0; - // No alpha blend, so never need to flip. - needFlip = false; - } - } - } - if (stretchedForCliff) { - // If we had to stretch for clif, check heights. - Int p0=getHeight(xIndex, yIndex); - Int p1=getHeight(xIndex+1, yIndex); - Int p2=getHeight(xIndex+1, yIndex+1); - Int p3=getHeight(xIndex, yIndex+1); - Int dz1 = abs(p0-p2); - Int dz2 = abs(p1-p3); - needFlip = dz1>dz2; - } -#ifdef FLIP_TRIANGLES - *flip = needFlip; -#endif -} - -void WorldHeightMap::setTextureLOD(Int lod) -{ - if (m_terrainTex) - m_terrainTex->setLOD(lod); -} - -TextureClass *WorldHeightMap::getTerrainTexture(void) -{ - if (m_terrainTex == NULL) { - Int edgeHeight; - Int height = updateTileTexturePositions(&edgeHeight); - Int pow2Height = 1; - while (pow2Heightupdate(this); - char buf[64]; - sprintf(buf, "Base tex height %d", pow2Height); - DEBUG_LOG((buf)); - REF_PTR_RELEASE(m_alphaTerrainTex); - m_alphaTerrainTex = MSGNEW("WorldHeightMap_getTerrainTexture") AlphaTerrainTextureClass(m_terrainTex); - - pow2Height = 1; - while (pow2Heightupdate(this); - - //Generate lookup table for determining triangle order in each terrain cell. - //Not the best place to put this but getAlphaUVData() requires a valid terrain - //texture to return valid values. - - for (Int y=0; y<(m_height-1); y++) - for (Int x=0; x<(m_width-1); x++) - { - UnsignedByte alpha[4]; - float UA[4], VA[4]; - Bool flipForBlend; - - getAlphaUVData(x, y, UA, VA, alpha, &flipForBlend, false); - - m_cellFlipState[y*m_flipStateWidth+(x>>3)] |= flipForBlend << (x & 0x7); - DEBUG_ASSERTCRASH ((y*m_flipStateWidth+(x>>3)) < (m_flipStateWidth * m_height), ("Bad range")); - } - } - - return m_terrainTex; -} - -TextureClass *WorldHeightMap::getAlphaTerrainTexture(void) -{ - if (m_alphaTerrainTex == NULL) { - getTerrainTexture(); - } - return m_alphaTerrainTex; -} - -TextureClass *WorldHeightMap::getEdgeTerrainTexture(void) -{ - if (m_alphaEdgeTex == NULL) { - getTerrainTexture(); - } - return m_alphaEdgeTex; -} - -TerrainTextureClass *WorldHeightMap::getFlatTexture(Int xCell, Int yCell, Int cellWidth, Int pixelsPerCell) -{ - if (WW3D::Get_Texture_Reduction()) { - if (WW3D::Get_Texture_Reduction()>1) { - pixelsPerCell /= 4; - } else { - pixelsPerCell /= 2; - } - } - Int pow2Height = 1; - while (pow2HeightupdateFlat(this, xCell, yCell, cellWidth, pixelsPerCell); - return newTexture; -} - - -Bool WorldHeightMap::setDrawOrg(Int xOrg, Int yOrg) -{ - Int newX, newY; - Int newWidth, newHeight; - newX = xOrg; - newY = yOrg; - newWidth = m_drawWidthX; - newHeight = m_drawHeightY; - if (TheGlobalData && TheGlobalData->m_stretchTerrain) { - newWidth=STRETCH_DRAW_WIDTH; - newHeight=STRETCH_DRAW_HEIGHT; - } - if (TheGlobalData && TheGlobalData->m_drawEntireTerrain) { - newWidth=m_width; - newHeight=m_height; - } - if (newWidth > m_width) newWidth = m_width; - if (newHeight > m_height) newHeight = m_height; - if (newX > m_width - newWidth) newX = m_width-newWidth; - if (newX<0) newX=0; - if (newY > m_height - newHeight) newY = m_height - newHeight; - if (newY<0) newY=0; - Bool anythingDifferent = (m_drawOriginX!=newX) || - (m_drawOriginY!=newY) || - (m_drawWidthX!=newWidth) || - (m_drawHeightY!=newHeight) ; - - if (anythingDifferent) { - m_drawOriginX=newX; - m_drawOriginY=newY; - m_drawWidthX=newWidth; - m_drawHeightY=newHeight; - return(true); - } - return(false); -} - -/** Gets global texture class. */ -Int WorldHeightMap::getTextureClass(Int xIndex, Int yIndex, Bool baseClass) -{ - Int ndx = (yIndex*m_width)+xIndex; - DEBUG_ASSERTCRASH((ndx>=0 && ndxm_dataSize),("oops")); - if (ndx<0 || ndx >= this->m_dataSize) return(-1); - Int textureNdx = m_tileNdxes[ndx]; - if (!baseClass && (m_blendTileNdxes[ndx] != 0 || m_extraBlendTileNdxes[ndx] != 0)) { - return(-1); // blended, so not of the original class. - } - return getTextureClassFromNdx(textureNdx); -} - - -/** Sets all the cliff flags in map based on height. */ -void WorldHeightMap::initCliffFlagsFromHeights() -{ - Int xIndex, yIndex; - - for (xIndex=0; xIndex height2) minZ = height2; - if (minZ > height3) minZ = height3; - if (minZ > height4) minZ = height4; - Real maxZ = height1; - if (maxZ < height2) maxZ = height2; - if (maxZ < height3) maxZ = height3; - if (maxZ < height4) maxZ = height4; - const Real cliffRange = PATHFIND_CLIFF_SLOPE_LIMIT_F; - Bool isCliff = (maxZ-minZ > cliffRange); - setCliffState(xIndex, yIndex, isCliff); - -} - -/** Gets global texture class. */ -Int WorldHeightMap::getTextureClassFromNdx(Int tileNdx) -{ - Int i; - tileNdx = tileNdx>>2; - for (i=0; i= m_textureClasses[i].firstTile && - tileNdx < m_textureClasses[i].firstTile+m_textureClasses[i].numTiles) { - return(m_textureClasses[i].globalTextureClass); - } - } - return(-1); -} - -TXTextureClass WorldHeightMap::getTextureFromIndex( Int textureIndex ) -{ - return m_textureClasses[textureIndex]; -} - -void WorldHeightMap::getTerrainColorAt(Real x, Real y, RGBColor *pColor) -{ - Int xIndex = REAL_TO_INT_FLOOR(x/MAP_XY_FACTOR); - Int yIndex = REAL_TO_INT_FLOOR(y/MAP_XY_FACTOR); - xIndex += m_borderSize; - yIndex += m_borderSize; - pColor->red = pColor->green = pColor->blue = 0; - if (xIndex<0) xIndex = 0; - if (yIndex<0) yIndex = 0; - if (xIndex >= m_width) xIndex = m_width-1; - if (yIndex >= m_height) yIndex = m_height-1; - Int ndx = (yIndex*m_width)+xIndex; - if (ndx<0 || ndx >= this->m_dataSize) return; - Int tileNdx = m_tileNdxes[ndx]; - tileNdx = tileNdx>>2; // We pack 4 grids into a tile. - - TileData *pTile = getSourceTile(tileNdx); - if (pTile) { - // pTile contains the bitmap data for 4 squares. - // Get the data mipped down to one pixel for the tile. - UnsignedByte *pData = pTile->getRGBDataForWidth(1); - // Data is in microsoft bgra format. - pColor->red = pData[2]/255.0; - pColor->green = pData[1]/255.0; - pColor->blue = pData[0]/255.0; - } -} - -AsciiString WorldHeightMap::getTerrainNameAt(Real x, Real y) -{ - Int xIndex = REAL_TO_INT_FLOOR(x/MAP_XY_FACTOR); - Int yIndex = REAL_TO_INT_FLOOR(y/MAP_XY_FACTOR); - xIndex += m_borderSize; - yIndex += m_borderSize; - if (xIndex<0) xIndex = 0; - if (yIndex<0) yIndex = 0; - if (xIndex >= m_width) xIndex = m_width-1; - if (yIndex >= m_height) yIndex = m_height-1; - Int ndx = (yIndex*m_width)+xIndex; - if (ndx<0 || ndx >= this->m_dataSize) return AsciiString::TheEmptyString; - Int tileNdx = m_tileNdxes[ndx]; - tileNdx = tileNdx>>2; // We pack 4 grids into a tile. - - Int i; - for (i=0; im_numTextureClasses; i++) { - if (tileNdx >= m_textureClasses[i].firstTile && tileNdx < m_textureClasses[i].firstTile + m_textureClasses[i].numTiles) { - return(m_textureClasses[i].name); - } - } - return AsciiString::TheEmptyString; -} - - -static UnsignedByte s_buffer[DATA_LEN_BYTES]; -static UnsignedByte s_blendBuffer[DATA_LEN_BYTES]; - -UnsignedByte * WorldHeightMap::getPointerToTileData(Int xIndex, Int yIndex, Int width) -{ - Int ndx = (yIndex*m_width)+xIndex; - if (yIndex<0 || xIndex<0 || xIndex>=m_width || yIndex>=m_height) { - return NULL; - } - if (ndx<0 || ndx>=m_dataSize) { - return NULL; - } - TBlendTileInfo *pBlend = NULL; - Short tileNdx = m_tileNdxes[ndx]; - if (getRawTileData(tileNdx, width, s_buffer, DATA_LEN_BYTES)) { - Short blendTileNdx = m_blendTileNdxes[ndx]; - if (blendTileNdx>0 && blendTileNdx < NUM_BLEND_TILES) { - pBlend = &m_blendedTiles[blendTileNdx]; - if (getRawTileData(pBlend->blendNdx, width, s_blendBuffer, DATA_LEN_BYTES)) { - UnsignedByte *pAlpha = getRGBAlphaDataForWidth(width, pBlend); - pAlpha += 3; // skip over the rgb to the a. - Int i, limit; - limit = width*width; - UnsignedByte *pBlendData = s_blendBuffer; - UnsignedByte *pDestData = s_buffer; - for (i=0; ihoriz) { - alphaTileNdx = K_HORIZ; - } else if (pBlend->vert) { - alphaTileNdx = K_VERT; - } else if (pBlend->rightDiagonal) { - alphaTileNdx = K_RDIAG; - if (pBlend->longDiagonal) alphaTileNdx=K_LRDIAG; - } else if (pBlend->leftDiagonal) { - alphaTileNdx = K_LDIAG; - if (pBlend->longDiagonal) alphaTileNdx=K_LLDIAG; - } - if (pBlend->inverted) { - alphaTileNdx += K_INV; - } - return m_alphaTiles[alphaTileNdx]->getRGBDataForWidth(width); -} - -void WorldHeightMap::setupAlphaTiles(void) -{ - TBlendTileInfo blendInfo; - if (m_alphaTiles[0] != NULL) return; - Int k; - for (k=0; k=K_INV) { - blendInfo.inverted = true; - baseK -= K_INV; - } - switch(baseK) { - case K_HORIZ : blendInfo.horiz = true; break; - case K_VERT : blendInfo.vert = true; break; - case K_LDIAG : blendInfo.leftDiagonal = true; break; - case K_RDIAG : blendInfo.rightDiagonal = true; break; - case K_LLDIAG : blendInfo.leftDiagonal = true; blendInfo.longDiagonal = true; break; - case K_LRDIAG : blendInfo.rightDiagonal = true; blendInfo.longDiagonal = true; break; - } - m_alphaTiles[k] = new TileData; - TileData *pTile = m_alphaTiles[k]; - - Int i, j; - UnsignedByte *pDest = pTile->getDataPtr(); - for (j=0; j 255) alpha = 255; - if (alpha<0) alpha = 0; - alpha = 255-alpha; - - pDest += 3; // skip blue, green & red bytes. - *pDest = alpha; // alpha. - //*pDest = 255; - pDest++; - } - } - pTile->updateMips(); - } -} - - -Bool WorldHeightMap::getRawTileData(Short tileNdx, Int width, - UnsignedByte *buffer, Int bufLen) -{ - TileData *pSrc = NULL; - if (tileNdx/4 < NUM_SOURCE_TILES) { - pSrc = m_sourceTiles[tileNdx/4]; - } - if (bufLen < (width*width*TILE_BYTES_PER_PIXEL)) { - return(false); - } - if (pSrc && pSrc->hasRGBDataForWidth(2*width)) { - Int j; - UnsignedByte *pSrcData = pSrc->getRGBDataForWidth(2*width); - Int xOffset=0; - Int yOffset=0; - if (tileNdx & 1) xOffset = width; - if (tileNdx & 2) yOffset = width; - for (j=0; j Date: Tue, 16 Dec 2025 21:04:55 +0100 Subject: [PATCH 37/70] bugfix(input): Disable mouse waypoint mode after using alt tab (#1987) --- .../GameEngine/Include/GameClient/Keyboard.h | 2 ++ .../Source/GameClient/Input/Keyboard.cpp | 23 +++++++++++++++++++ Generals/Code/Main/WinMain.cpp | 4 ++-- .../GameEngine/Include/GameClient/Keyboard.h | 2 ++ .../Source/GameClient/Input/Keyboard.cpp | 23 +++++++++++++++++++ GeneralsMD/Code/Main/WinMain.cpp | 4 ++-- 6 files changed, 54 insertions(+), 4 deletions(-) diff --git a/Generals/Code/GameEngine/Include/GameClient/Keyboard.h b/Generals/Code/GameEngine/Include/GameClient/Keyboard.h index 5e21e33e5f..e4ee92bf49 100644 --- a/Generals/Code/GameEngine/Include/GameClient/Keyboard.h +++ b/Generals/Code/GameEngine/Include/GameClient/Keyboard.h @@ -119,6 +119,8 @@ class Keyboard : public SubsystemInterface WideChar translateKey( WideChar keyCode ); ///< translate key code to printable UNICODE char WideChar getPrintableKey( KeyDefType key, Int state ); enum { MAX_KEY_STATES = 3}; +private: + void refreshAltKeys() const; ///< refresh the state of the alt keys, necessary after alt tab protected: /** get the key data for a single key, KEY_NONE should be returned when diff --git a/Generals/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp b/Generals/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp index 3705c791c2..5eb6a69cce 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp @@ -748,6 +748,10 @@ void Keyboard::update( void ) void Keyboard::resetKeys( void ) { + // TheSuperHackers @fix Caball009 13/12/2025 Fix bug where game remains in waypoint mode + // because the key up state for the alt key is not detected after alt tab. + refreshAltKeys(); + memset( m_keys, 0, sizeof( m_keys ) ); memset( m_keyStatus, 0, sizeof( m_keyStatus ) ); m_modifiers = KEY_STATE_NONE; @@ -758,6 +762,25 @@ void Keyboard::resetKeys( void ) } +//------------------------------------------------------------------------------------------------- +// Refresh the state of the alt keys, necessary after alt tab +//------------------------------------------------------------------------------------------------- +void Keyboard::refreshAltKeys() const +{ + if (BitIsSet(m_keyStatus[KEY_LALT].state, KEY_STATE_DOWN)) + { + GameMessage* msg = TheMessageStream->appendMessage(GameMessage::MSG_RAW_KEY_UP); + msg->appendIntegerArgument(KEY_LALT); + msg->appendIntegerArgument(KEY_STATE_UP); + } + if (BitIsSet(m_keyStatus[KEY_RALT].state, KEY_STATE_DOWN)) + { + GameMessage* msg = TheMessageStream->appendMessage(GameMessage::MSG_RAW_KEY_UP); + msg->appendIntegerArgument(KEY_RALT); + msg->appendIntegerArgument(KEY_STATE_UP); + } +} + //------------------------------------------------------------------------------------------------- /** get the first key in our current state of the keyboard */ //------------------------------------------------------------------------------------------------- diff --git a/Generals/Code/Main/WinMain.cpp b/Generals/Code/Main/WinMain.cpp index 1bdfe50293..3c34a3e81c 100644 --- a/Generals/Code/Main/WinMain.cpp +++ b/Generals/Code/Main/WinMain.cpp @@ -401,7 +401,7 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, // reset the state of our keyboard cause we haven't been paying // attention to the keys while focus was away // - if( TheKeyboard ) + if (TheKeyboard) TheKeyboard->resetKeys(); if (TheMouse) @@ -413,7 +413,7 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, //------------------------------------------------------------------------- case WM_KILLFOCUS: { - if (TheKeyboard ) + if (TheKeyboard) TheKeyboard->resetKeys(); if (TheMouse) diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Keyboard.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Keyboard.h index 99a4cd54ce..fa54abe226 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/Keyboard.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Keyboard.h @@ -119,6 +119,8 @@ class Keyboard : public SubsystemInterface WideChar translateKey( WideChar keyCode ); ///< translate key code to printable UNICODE char WideChar getPrintableKey( KeyDefType key, Int state ); enum { MAX_KEY_STATES = 3}; +private: + void refreshAltKeys() const; ///< refresh the state of the alt keys, necessary after alt tab protected: /** get the key data for a single key, KEY_NONE should be returned when diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp index 5a642bdff8..bb151a18d7 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp @@ -748,6 +748,10 @@ void Keyboard::update( void ) void Keyboard::resetKeys( void ) { + // TheSuperHackers @fix Caball009 13/12/2025 Fix bug where game remains in waypoint mode + // because the key up state for the alt key is not detected after alt tab. + refreshAltKeys(); + memset( m_keys, 0, sizeof( m_keys ) ); memset( m_keyStatus, 0, sizeof( m_keyStatus ) ); m_modifiers = KEY_STATE_NONE; @@ -758,6 +762,25 @@ void Keyboard::resetKeys( void ) } +//------------------------------------------------------------------------------------------------- +// Refresh the state of the alt keys, necessary after alt tab +//------------------------------------------------------------------------------------------------- +void Keyboard::refreshAltKeys() const +{ + if (BitIsSet(m_keyStatus[KEY_LALT].state, KEY_STATE_DOWN)) + { + GameMessage* msg = TheMessageStream->appendMessage(GameMessage::MSG_RAW_KEY_UP); + msg->appendIntegerArgument(KEY_LALT); + msg->appendIntegerArgument(KEY_STATE_UP); + } + if (BitIsSet(m_keyStatus[KEY_RALT].state, KEY_STATE_DOWN)) + { + GameMessage* msg = TheMessageStream->appendMessage(GameMessage::MSG_RAW_KEY_UP); + msg->appendIntegerArgument(KEY_RALT); + msg->appendIntegerArgument(KEY_STATE_UP); + } +} + //------------------------------------------------------------------------------------------------- /** get the first key in our current state of the keyboard */ //------------------------------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/Main/WinMain.cpp b/GeneralsMD/Code/Main/WinMain.cpp index 8d0dc1aa6c..3f887a07ca 100644 --- a/GeneralsMD/Code/Main/WinMain.cpp +++ b/GeneralsMD/Code/Main/WinMain.cpp @@ -423,7 +423,7 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, // reset the state of our keyboard cause we haven't been paying // attention to the keys while focus was away // - if( TheKeyboard ) + if (TheKeyboard) TheKeyboard->resetKeys(); if (TheMouse) @@ -435,7 +435,7 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message, //------------------------------------------------------------------------- case WM_KILLFOCUS: { - if (TheKeyboard ) + if (TheKeyboard) TheKeyboard->resetKeys(); if (TheMouse) From 123492ce1d34b52ae25ca22b93e4a5520b1d71ad Mon Sep 17 00:00:00 2001 From: Stubbjax Date: Thu, 18 Dec 2025 05:02:57 +1100 Subject: [PATCH 38/70] bugfix(object): Fix visibility conditions for client-side effects (#1964) --- .../GameEngine/Include/GameLogic/Object.h | 2 ++ .../Source/GameLogic/Object/Object.cpp | 30 ++++++++++++++++--- .../Source/GameLogic/Object/Weapon.cpp | 6 +--- .../GameEngine/Include/GameLogic/Object.h | 2 ++ .../Source/GameLogic/Object/Object.cpp | 30 ++++++++++++++++--- .../Update/AIUpdate/HackInternetAIUpdate.cpp | 3 +- .../Object/Update/AutoDepositUpdate.cpp | 3 +- .../DockUpdate/SupplyCenterDockUpdate.cpp | 3 +- .../Source/GameLogic/Object/Weapon.cpp | 6 +--- 9 files changed, 61 insertions(+), 24 deletions(-) diff --git a/Generals/Code/GameEngine/Include/GameLogic/Object.h b/Generals/Code/GameEngine/Include/GameLogic/Object.h index 49617d3fc0..9f0f0869b3 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Object.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Object.h @@ -237,6 +237,8 @@ class Object : public Thing, public Snapshot void setCustomIndicatorColor(Color c); void removeCustomIndicatorColor(); + Bool isLogicallyVisible() const; ///< Returns whether the object is logically visible to the player, irrespective of shroud. + Bool isLocallyControlled() const; Bool isLocallyViewed() const; Bool isNeutralControlled() const; diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp index d0f4b52301..49d49491de 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp @@ -1541,6 +1541,31 @@ Color Object::getNightIndicatorColor() const } } +//============================================================================= +// Object::isLogicallyVisible +//============================================================================= +Bool Object::isLogicallyVisible() const +{ + const Object* obj = getOuterObject(); + + // Disguisers are always visible to all players, irrespective of any stealth + // status. We thus need to check the type rather than the status as the + // disguise status is absent during the disguise transition phase. + if (obj->isKindOf(KINDOF_DISGUISER)) + return true; + + if (obj->testStatus(OBJECT_STATUS_STEALTHED) && !obj->testStatus(OBJECT_STATUS_DETECTED)) + { + const Player* player = rts::getObservedOrLocalPlayer(); + const Relationship relationship = player->getRelationship(getTeam()); + + if (player->isPlayerActive() && relationship != ALLIES) + return false; + } + + return true; +} + //============================================================================= // Object::isLocallyControlled //============================================================================= @@ -2835,13 +2860,10 @@ void Object::onVeterancyLevelChanged( VeterancyLevel oldLevel, VeterancyLevel ne break; } - Drawable* outerDrawable = getOuterObject()->getDrawable(); - Bool doAnimation = provideFeedback && newLevel > oldLevel && !isKindOf(KINDOF_IGNORED_IN_GUI) - && outerDrawable - && outerDrawable->isVisible(); + && isLogicallyVisible(); if( doAnimation && TheGameLogic->getDrawIconUI() ) { diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp index 7bae95eebb..d625c5c9ce 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp @@ -886,11 +886,7 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate // TheSuperHackers @todo: Remove hardcoded KINDOF_MINE check and apply PlayFXWhenStealthed = Yes to the mine weapons instead. - Drawable* outerDrawable = sourceObj->getOuterObject()->getDrawable(); - const Bool isVisible = outerDrawable && outerDrawable->isVisible(); - - if (!isVisible // if user watching cannot see us - && sourceObj->testStatus(OBJECT_STATUS_STEALTHED) // if unit is stealthed (like a Pathfinder) + if (!sourceObj->isLogicallyVisible() // if user watching cannot see us && !sourceObj->isKindOf(KINDOF_MINE) // and not a mine (which always do the FX, even if hidden)... && !isPlayFXWhenStealthed() // and not a weapon marked to playwhenstealthed ) diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h index a2f51fe28b..9c601848f6 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h @@ -253,6 +253,8 @@ class Object : public Thing, public Snapshot void setCustomIndicatorColor(Color c); void removeCustomIndicatorColor(); + Bool isLogicallyVisible() const; ///< Returns whether the object is logically visible to the player, irrespective of shroud. + Bool isLocallyControlled() const; Bool isLocallyViewed() const; Bool isNeutralControlled() const; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp index 598e266bea..bca7c39b87 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp @@ -1696,6 +1696,31 @@ Color Object::getNightIndicatorColor() const } } +//============================================================================= +// Object::isLogicallyVisible +//============================================================================= +Bool Object::isLogicallyVisible() const +{ + const Object* obj = getOuterObject(); + + // Disguisers are always visible to all players, irrespective of any stealth + // status. We thus need to check the type rather than the status as the + // disguise status is absent during the disguise transition phase. + if (obj->isKindOf(KINDOF_DISGUISER)) + return true; + + if (obj->testStatus(OBJECT_STATUS_STEALTHED) && !obj->testStatus(OBJECT_STATUS_DETECTED)) + { + const Player* player = rts::getObservedOrLocalPlayer(); + const Relationship relationship = player->getRelationship(getTeam()); + + if (player->isPlayerActive() && relationship != ALLIES) + return false; + } + + return true; +} + //============================================================================= // Object::isLocallyControlled //============================================================================= @@ -3150,13 +3175,10 @@ void Object::onVeterancyLevelChanged( VeterancyLevel oldLevel, VeterancyLevel ne break; } - Drawable* outerDrawable = getOuterObject()->getDrawable(); - Bool doAnimation = provideFeedback && newLevel > oldLevel && !isKindOf(KINDOF_IGNORED_IN_GUI) - && outerDrawable - && outerDrawable->isVisible(); + && isLogicallyVisible(); if( doAnimation && TheGameLogic->getDrawIconUI() ) { 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 b395edd50e..d7f60873e8 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/HackInternetAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/HackInternetAIUpdate.cpp @@ -543,8 +543,7 @@ StateReturnType HackInternetState::update() //Grant the unit some experience for a successful hack. xp->addExperiencePoints( ai->getXpPerCashUpdate() ); - Drawable* outerDrawable = owner->getOuterObject()->getDrawable(); - if (outerDrawable && outerDrawable->isVisible()) + if (owner->isLogicallyVisible()) { // OY LOOK! I AM USING LOCAL PLAYER. Do not put anything other than TheInGameUI->addFloatingText in the block this controls!!! //Display cash income floating over the hacker. diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AutoDepositUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AutoDepositUpdate.cpp index 6c12c9a553..7c423f04ff 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AutoDepositUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AutoDepositUpdate.cpp @@ -172,8 +172,7 @@ UpdateSleepTime AutoDepositUpdate::update( void ) getObject()->getControllingPlayer()->getScoreKeeper()->addMoneyEarned( modData->m_depositAmount); } - Drawable* outerDrawable = getObject()->getOuterObject()->getDrawable(); - if (moneyAmount > 0 && outerDrawable && outerDrawable->isVisible()) + if (moneyAmount > 0 && getObject()->isLogicallyVisible()) { const Object *owner = getObject(); 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 407b32a0dc..769a8843bf 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/SupplyCenterDockUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/SupplyCenterDockUpdate.cpp @@ -129,8 +129,7 @@ Bool SupplyCenterDockUpdate::action( Object* docker, Object *drone ) } } - Drawable* outerDrawable = getObject()->getOuterObject()->getDrawable(); - if (value > 0 && outerDrawable && outerDrawable->isVisible()) + if (value > 0 && getObject()->isLogicallyVisible()) { // OY LOOK! I AM USING LOCAL PLAYER. Do not put anything other than TheInGameUI->addFloatingText in the block this controls!!! // Setup info for adding a floating text diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp index 69bcca6606..fe0eed142d 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp @@ -917,11 +917,7 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate // TheSuperHackers @todo: Remove hardcoded KINDOF_MINE check and apply PlayFXWhenStealthed = Yes to the mine weapons instead. - Drawable* outerDrawable = sourceObj->getOuterObject()->getDrawable(); - const Bool isVisible = outerDrawable && outerDrawable->isVisible(); - - if (!isVisible // if user watching cannot see us - && sourceObj->testStatus(OBJECT_STATUS_STEALTHED) // if unit is stealthed (like a Pathfinder) + if (!sourceObj->isLogicallyVisible() // if user watching cannot see us && !sourceObj->isKindOf(KINDOF_MINE) // and not a mine (which always do the FX, even if hidden)... && !isPlayFXWhenStealthed() // and not a weapon marked to playwhenstealthed ) From 4951762d4ea1c1bdddf1009963ec99e2977565c3 Mon Sep 17 00:00:00 2001 From: Stubbjax Date: Thu, 18 Dec 2025 05:03:26 +1100 Subject: [PATCH 39/70] bugfix(experience): Prevent ranking of riders that are not trainable (#1970) --- .../Include/GameLogic/ExperienceTracker.h | 3 + .../GameClient/MessageStream/CommandXlat.cpp | 57 ++++++++-------- .../GameLogic/Object/ExperienceTracker.cpp | 25 ++++++- .../Include/GameLogic/ExperienceTracker.h | 3 + .../GameClient/MessageStream/CommandXlat.cpp | 67 +++++++++---------- .../Object/Contain/RiderChangeContain.cpp | 6 ++ .../GameLogic/Object/ExperienceTracker.cpp | 25 ++++++- 7 files changed, 123 insertions(+), 63 deletions(-) diff --git a/Generals/Code/GameEngine/Include/GameLogic/ExperienceTracker.h b/Generals/Code/GameEngine/Include/GameLogic/ExperienceTracker.h index d524772aac..8f33f93d11 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/ExperienceTracker.h +++ b/Generals/Code/GameEngine/Include/GameLogic/ExperienceTracker.h @@ -46,6 +46,8 @@ class ExperienceTracker : public MemoryPoolObject, public Snapshot Int getExperienceValue( const Object* killer ) const; ///< How much do give for being killed Int getCurrentExperience( void ) const { return m_currentExperience; }; ///< How much experience do I have at the moment? Bool isTrainable() const; ///< Can I gain experience? + void setTrainable(Bool trainable); ///< Set whether I can gain experience + void resetTrainable(); ///< Set to default trainable state from template Bool isAcceptingExperiencePoints() const; ///< Either I am trainable, or I have a Sink set up void setVeterancyLevel( VeterancyLevel newLevel, Bool provideFeedback = TRUE ); ///< Set Level to this @@ -71,4 +73,5 @@ 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. + Bool m_isTrainable; ///< Can I gain experience? }; diff --git a/Generals/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp b/Generals/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp index f0590f22b3..35a406d462 100644 --- a/Generals/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp @@ -4113,42 +4113,45 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage case GameMessage::MSG_META_DEBUG_GIVE_VETERANCY: case GameMessage::MSG_META_DEBUG_TAKE_VETERANCY: { + if (TheGameLogic->isInMultiplayerGame()) + break; + const DrawableList *list = TheInGameUI->getAllSelectedDrawables(); for (DrawableListCIt it = list->begin(); it != list->end(); ++it) { Drawable *pDraw = *it; - if (pDraw) + if (!pDraw) + continue; + + Object *pObject = pDraw->getObject(); + if (!pObject) + continue; + + ExperienceTracker *et = pObject->getExperienceTracker(); + if (!et || !et->isTrainable()) + continue; + + VeterancyLevel oldVet = et->getVeterancyLevel(); + VeterancyLevel newVet = oldVet; + + if (t == GameMessage::MSG_META_DEBUG_GIVE_VETERANCY) { - Object *pObject = pDraw->getObject(); - if (pObject) + if (oldVet < LEVEL_LAST) { - ExperienceTracker *et = pObject->getExperienceTracker(); - if (et) - { - if (et->isTrainable()) - { - VeterancyLevel oldVet = et->getVeterancyLevel(); - VeterancyLevel newVet = oldVet; - if (t == GameMessage::MSG_META_DEBUG_GIVE_VETERANCY) - { - if (oldVet < LEVEL_LAST) - { - newVet = (VeterancyLevel)((Int)oldVet + 1); - } - } - else - { - if (oldVet > LEVEL_FIRST) - { - newVet = (VeterancyLevel)((Int)oldVet - 1); - } - } - et->setVeterancyLevel(newVet); - } - } + newVet = (VeterancyLevel)((Int)oldVet + 1); } } + else + { + if (oldVet > LEVEL_FIRST) + { + newVet = (VeterancyLevel)((Int)oldVet - 1); + } + } + + et->setVeterancyLevel(newVet); } + disp = DESTROY_MESSAGE; break; } diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp index f6a1b05032..2518b38a34 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp @@ -45,6 +45,7 @@ ExperienceTracker::ExperienceTracker(Object *parent) : m_experienceScalar( 1.0f ), m_currentExperience(0) { + resetTrainable(); } //------------------------------------------------------------------------------------------------- @@ -65,7 +66,19 @@ Int ExperienceTracker::getExperienceValue( const Object* killer ) const //------------------------------------------------------------------------------------------------- Bool ExperienceTracker::isTrainable() const { - return m_parent->getTemplate()->isTrainable(); + return m_isTrainable; +} + +//------------------------------------------------------------------------------------------------- +void ExperienceTracker::setTrainable(Bool trainable) +{ + m_isTrainable = trainable; +} + +//------------------------------------------------------------------------------------------------- +void ExperienceTracker::resetTrainable() +{ + m_isTrainable = m_parent->getTemplate()->isTrainable(); } //------------------------------------------------------------------------------------------------- @@ -236,19 +249,27 @@ void ExperienceTracker::crc( Xfer *xfer ) { xfer->xferInt( &m_currentExperience ); xfer->xferUser( &m_currentLevel, sizeof( VeterancyLevel ) ); +#if !RETAIL_COMPATIBLE_CRC + xfer->xferBool(&m_isTrainable); +#endif } //----------------------------------------------------------------------------- /** Xfer method * Version Info: * 1: Initial version + * 2: TheSuperHackers @tweak Serialize m_isTrainable */ // ---------------------------------------------------------------------------- void ExperienceTracker::xfer( Xfer *xfer ) { // version +#if RETAIL_COMPATIBLE_XFER_SAVE XferVersion currentVersion = 1; +#else + XferVersion currentVersion = 2; +#endif XferVersion version = currentVersion; xfer->xferVersion( &version, currentVersion ); @@ -267,6 +288,8 @@ void ExperienceTracker::xfer( Xfer *xfer ) // experience scalar xfer->xferReal( &m_experienceScalar ); + if (version >= 2) + xfer->xferBool(&m_isTrainable); } //----------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/ExperienceTracker.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/ExperienceTracker.h index a275b24b11..671183d092 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/ExperienceTracker.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/ExperienceTracker.h @@ -46,6 +46,8 @@ class ExperienceTracker : public MemoryPoolObject, public Snapshot Int getExperienceValue( const Object* killer ) const; ///< How much do give for being killed Int getCurrentExperience( void ) const { return m_currentExperience; }; ///< How much experience do I have at the moment? Bool isTrainable() const; ///< Can I gain experience? + void setTrainable(Bool trainable); ///< Set whether I can gain experience + void resetTrainable(); ///< Set to default trainable state from template Bool isAcceptingExperiencePoints() const; ///< Either I am trainable, or I have a Sink set up void setVeterancyLevel( VeterancyLevel newLevel, Bool provideFeedback = TRUE ); ///< Set Level to this @@ -71,4 +73,5 @@ 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. + Bool m_isTrainable; ///< Can I gain experience? }; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp index c4056a6c92..653756fa31 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp @@ -4499,47 +4499,46 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage case GameMessage::MSG_META_DEBUG_GIVE_VETERANCY: case GameMessage::MSG_META_DEBUG_TAKE_VETERANCY: { - if ( !TheGameLogic->isInMultiplayerGame() ) + if (TheGameLogic->isInMultiplayerGame()) + break; + + const DrawableList *list = TheInGameUI->getAllSelectedDrawables(); + for (DrawableListCIt it = list->begin(); it != list->end(); ++it) { + Drawable *pDraw = *it; + if (!pDraw) + continue; - const DrawableList *list = TheInGameUI->getAllSelectedDrawables(); - for (DrawableListCIt it = list->begin(); it != list->end(); ++it) + Object *pObject = pDraw->getObject(); + if (!pObject) + continue; + + ExperienceTracker *et = pObject->getExperienceTracker(); + if (!et || !et->isTrainable()) + continue; + + VeterancyLevel oldVet = et->getVeterancyLevel(); + VeterancyLevel newVet = oldVet; + + if (t == GameMessage::MSG_META_DEBUG_GIVE_VETERANCY) { - Drawable *pDraw = *it; - if (pDraw) + if (oldVet < LEVEL_LAST) { - Object *pObject = pDraw->getObject(); - if (pObject) - { - ExperienceTracker *et = pObject->getExperienceTracker(); - if (et) - { - if (et->isTrainable()) - { - VeterancyLevel oldVet = et->getVeterancyLevel(); - VeterancyLevel newVet = oldVet; - if (t == GameMessage::MSG_META_DEBUG_GIVE_VETERANCY) - { - if (oldVet < LEVEL_LAST) - { - newVet = (VeterancyLevel)((Int)oldVet + 1); - } - } - else - { - if (oldVet > LEVEL_FIRST) - { - newVet = (VeterancyLevel)((Int)oldVet - 1); - } - } - et->setVeterancyLevel(newVet); - } - } - } + newVet = (VeterancyLevel)((Int)oldVet + 1); } } - disp = DESTROY_MESSAGE; + else + { + if (oldVet > LEVEL_FIRST) + { + newVet = (VeterancyLevel)((Int)oldVet - 1); + } + } + + et->setVeterancyLevel(newVet); } + + disp = DESTROY_MESSAGE; break; } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/RiderChangeContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/RiderChangeContain.cpp index ed9babbea3..563071c09d 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/RiderChangeContain.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/RiderChangeContain.cpp @@ -246,6 +246,11 @@ void RiderChangeContain::onContaining( Object *rider, Bool wasSelected ) //Transfer experience from the rider to the bike. ExperienceTracker *riderTracker = rider->getExperienceTracker(); ExperienceTracker *bikeTracker = obj->getExperienceTracker(); +#if !RETAIL_COMPATIBLE_CRC + // TheSuperHackers @bugfix Stubbjax 15/12/2025 Copy trainable flag from the rider to prevent + // Workers and other untrainable riders from ranking up via the bike's experience tracker. + bikeTracker->setTrainable(riderTracker->isTrainable()); +#endif bikeTracker->setVeterancyLevel( riderTracker->getVeterancyLevel(), FALSE ); riderTracker->setExperienceAndLevel( 0, FALSE ); @@ -301,6 +306,7 @@ void RiderChangeContain::onRemoving( Object *rider ) //Transfer experience from the bike to the rider. ExperienceTracker *riderTracker = rider->getExperienceTracker(); ExperienceTracker *bikeTracker = bike->getExperienceTracker(); + bikeTracker->resetTrainable(); riderTracker->setVeterancyLevel( bikeTracker->getVeterancyLevel(), FALSE ); bikeTracker->setExperienceAndLevel( 0, FALSE ); } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp index d589e30d33..21364efd90 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp @@ -45,6 +45,7 @@ ExperienceTracker::ExperienceTracker(Object *parent) : m_experienceScalar( 1.0f ), m_currentExperience(0) { + resetTrainable(); } //------------------------------------------------------------------------------------------------- @@ -65,7 +66,19 @@ Int ExperienceTracker::getExperienceValue( const Object* killer ) const //------------------------------------------------------------------------------------------------- Bool ExperienceTracker::isTrainable() const { - return m_parent->getTemplate()->isTrainable(); + return m_isTrainable; +} + +//------------------------------------------------------------------------------------------------- +void ExperienceTracker::setTrainable(Bool trainable) +{ + m_isTrainable = trainable; +} + +//------------------------------------------------------------------------------------------------- +void ExperienceTracker::resetTrainable() +{ + m_isTrainable = m_parent->getTemplate()->isTrainable(); } //------------------------------------------------------------------------------------------------- @@ -236,19 +249,27 @@ void ExperienceTracker::crc( Xfer *xfer ) { xfer->xferInt( &m_currentExperience ); xfer->xferUser( &m_currentLevel, sizeof( VeterancyLevel ) ); +#if !RETAIL_COMPATIBLE_CRC + xfer->xferBool(&m_isTrainable); +#endif } //----------------------------------------------------------------------------- /** Xfer method * Version Info: * 1: Initial version + * 2: TheSuperHackers @tweak Serialize m_isTrainable */ // ---------------------------------------------------------------------------- void ExperienceTracker::xfer( Xfer *xfer ) { // version +#if RETAIL_COMPATIBLE_XFER_SAVE XferVersion currentVersion = 1; +#else + XferVersion currentVersion = 2; +#endif XferVersion version = currentVersion; xfer->xferVersion( &version, currentVersion ); @@ -267,6 +288,8 @@ void ExperienceTracker::xfer( Xfer *xfer ) // experience scalar xfer->xferReal( &m_experienceScalar ); + if (version >= 2) + xfer->xferBool(&m_isTrainable); } //----------------------------------------------------------------------------- From bffbcb4e0adf9073fc35f9ff989f8e624ea23093 Mon Sep 17 00:00:00 2001 From: Bobby Battista Date: Wed, 17 Dec 2025 14:37:57 -0500 Subject: [PATCH 40/70] refactor: Apply integer value comparisons for strcmp and stricmp with clang-tidy (#1956) --- .../Source/Common/System/GameMemory.cpp | 2 +- .../Source/GameNetwork/GameSpy/PeerDefs.cpp | 2 +- .../GameNetwork/GameSpy/Thread/PeerThread.cpp | 12 ++-- Core/GameEngine/Source/GameNetwork/NAT.cpp | 8 +-- .../StdDevice/Common/StdLocalFileSystem.cpp | 4 +- .../Common/Win32LocalFileSystem.cpp | 4 +- .../Source/WWVegas/WW3D2/texturethumbnail.cpp | 2 +- .../Source/WWVegas/WWDownload/Download.cpp | 2 +- Core/Libraries/Source/WWVegas/WWLib/argv.cpp | 10 +-- .../Source/WWVegas/WWLib/cpudetect.cpp | 2 +- Core/Libraries/Source/WWVegas/WWLib/ini.cpp | 2 +- Core/Libraries/Source/debug/debug_cmd.cpp | 48 +++++++------- Core/Libraries/Source/debug/debug_debug.cpp | 12 ++-- Core/Libraries/Source/debug/debug_io_con.cpp | 4 +- Core/Libraries/Source/debug/debug_io_flat.cpp | 24 +++---- Core/Libraries/Source/debug/debug_io_net.cpp | 4 +- .../Source/debug/netserv/netserv.cpp | 2 +- Core/Libraries/Source/debug/test2/test2.cpp | 2 +- Core/Libraries/Source/profile/profile.cpp | 6 +- Core/Libraries/Source/profile/profile_cmd.cpp | 26 ++++---- .../Source/profile/profile_highlevel.cpp | 2 +- .../Source/profile/profile_result.cpp | 6 +- Core/Tools/Autorun/GETCD.cpp | 4 +- Core/Tools/Autorun/GameText.cpp | 6 +- Core/Tools/Babylon/Babylon.cpp | 2 +- Core/Tools/Babylon/BabylonDlg.cpp | 20 +++--- Core/Tools/Babylon/TransDB.cpp | 18 +++--- Core/Tools/Compress/Compress.cpp | 10 +-- Core/Tools/ImagePacker/Source/ImagePacker.cpp | 40 ++++++------ Core/Tools/W3DView/W3DView.cpp | 2 +- Core/Tools/assetcull/assetcull.cpp | 4 +- Core/Tools/mangler/wlib/configfile.cpp | 4 +- Core/Tools/matchbot/wlib/configfile.cpp | 4 +- .../Tools/textureCompress/textureCompress.cpp | 2 +- .../GameEngine/Source/Common/Recorder.cpp | 2 +- .../Source/Common/System/Directory.cpp | 2 +- .../GUICallbacks/Menus/WOLBuddyOverlay.cpp | 2 +- .../GUICallbacks/Menus/WOLGameSetupMenu.cpp | 20 +++--- .../GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp | 2 +- .../GUICallbacks/Menus/WOLQuickMatchMenu.cpp | 4 +- .../GUI/GameWindowManagerScript.cpp | 62 +++++++++---------- .../GameEngine/Source/GameClient/GameText.cpp | 10 +-- .../GameLogic/Object/Update/AIUpdate.cpp | 2 +- .../GameEngine/Source/GameNetwork/GameSpy.cpp | 6 +- .../Source/WWVegas/WW3D2/assetmgr.cpp | 2 +- .../Tools/WorldBuilder/src/ObjectPreview.cpp | 2 +- .../Code/Tools/WorldBuilder/src/wbview3d.cpp | 6 +- .../GameEngine/Source/Common/Recorder.cpp | 2 +- .../Source/Common/System/Directory.cpp | 2 +- .../GUICallbacks/Menus/WOLBuddyOverlay.cpp | 2 +- .../GUICallbacks/Menus/WOLGameSetupMenu.cpp | 20 +++--- .../GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp | 2 +- .../GUICallbacks/Menus/WOLQuickMatchMenu.cpp | 4 +- .../GUI/GameWindowManagerScript.cpp | 62 +++++++++---------- .../GameEngine/Source/GameClient/GameText.cpp | 10 +-- .../GameLogic/Object/Update/AIUpdate.cpp | 2 +- .../Source/WWVegas/WW3D2/assetmgr.cpp | 2 +- .../Source/WWVegas/WW3D2/dx8caps.cpp | 18 +++--- 58 files changed, 275 insertions(+), 275 deletions(-) diff --git a/Core/GameEngine/Source/Common/System/GameMemory.cpp b/Core/GameEngine/Source/Common/System/GameMemory.cpp index 78a855c00d..2ede5c780b 100644 --- a/Core/GameEngine/Source/Common/System/GameMemory.cpp +++ b/Core/GameEngine/Source/Common/System/GameMemory.cpp @@ -2681,7 +2681,7 @@ MemoryPool *MemoryPoolFactory::findMemoryPool(const char *poolName) { for (MemoryPool *pool = m_firstPoolInFactory; pool; pool = pool->getNextPoolInList()) { - if (!strcmp(poolName, pool->getPoolName())) + if (strcmp(poolName, pool->getPoolName()) == 0) { DEBUG_ASSERTCRASH(poolName == pool->getPoolName(), ("hmm, ptrs should probably match here")); return pool; diff --git a/Core/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp b/Core/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp index 4e64c1b167..cd67390e83 100644 --- a/Core/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp +++ b/Core/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp @@ -340,7 +340,7 @@ void GameSpyInfo::addGroupRoom( GameSpyGroupRoom room ) groupLabel.format("GUI:%s", room.m_name.str()); room.m_translatedName = TheGameText->fetch(groupLabel); m_groupRooms[room.m_groupID] = room; - if ( !stricmp("quickmatch", room.m_name.str()) ) + if ( stricmp("quickmatch", room.m_name.str()) == 0 ) { DEBUG_LOG(("Group room %d (%s) is the QuickMatch room", room.m_groupID, room.m_name.str())); TheGameSpyConfig->setQMChannel(room.m_groupID); diff --git a/Core/GameEngine/Source/GameNetwork/GameSpy/Thread/PeerThread.cpp b/Core/GameEngine/Source/GameNetwork/GameSpy/Thread/PeerThread.cpp index 40c5c660e9..8be4c993d9 100644 --- a/Core/GameEngine/Source/GameNetwork/GameSpy/Thread/PeerThread.cpp +++ b/Core/GameEngine/Source/GameNetwork/GameSpy/Thread/PeerThread.cpp @@ -471,7 +471,7 @@ Int PeerThreadClass::findServer( SBServer server ) UnsignedInt oldPrivateIP = SBServerGetPrivateInetAddress(it->second); UnsignedShort oldPrivatePort = SBServerGetPrivateQueryPort(it->second); UnsignedInt oldPublicIP = SBServerGetPublicInetAddress(it->second); - if (!strcmp(oldName, newName) && + if (strcmp(oldName, newName) == 0 && oldPrivateIP == newPrivateIP && oldPublicIP == newPublicIP && oldPrivatePort == newPrivatePort) @@ -1842,7 +1842,7 @@ void PeerThreadClass::handleQMMatch(PEER peer, Int mapIndex, Int seed, Int i=0; for (; igetQMStatus() != QM_IDLE && t->getQMStatus() != QM_STOPPED) { - if (!stricmp(t->getQMBotName().c_str(), nick)) + if (stricmp(t->getQMBotName().c_str(), nick) == 0) { // matchbot left - bail PeerResponse resp; @@ -2845,9 +2845,9 @@ static void listingGamesCallback(PEER peer, PEERBool success, const char * name, DEBUG_LOG(("Game name is '%s'", name)); const char *newname = SBServerGetStringValue(server, "gamename", (char *)name); #if RTS_GENERALS - if (strcmp(newname, "ccgenerals")) + if (strcmp(newname, "ccgenerals") != 0) #elif RTS_ZEROHOUR - if (strcmp(newname, "ccgenzh")) + if (strcmp(newname, "ccgenzh") != 0) #endif name = newname; DEBUG_LOG(("Game name is now '%s'", name)); diff --git a/Core/GameEngine/Source/GameNetwork/NAT.cpp b/Core/GameEngine/Source/GameNetwork/NAT.cpp index 76428c7038..03e5855675 100644 --- a/Core/GameEngine/Source/GameNetwork/NAT.cpp +++ b/Core/GameEngine/Source/GameNetwork/NAT.cpp @@ -1169,7 +1169,7 @@ void NAT::processGlobalMessage(Int slotNum, const char *options) { ++ptr; } DEBUG_LOG(("NAT::processGlobalMessage - got message from slot %d, message is \"%s\"", slotNum, ptr)); - if (!strncmp(ptr, "PROBED", strlen("PROBED"))) { + if (strncmp(ptr, "PROBED", strlen("PROBED")) == 0) { // format: PROBED // a probe has been sent at us, if we are waiting because of a netgear or something, we // should start sending our own probes. @@ -1180,7 +1180,7 @@ void NAT::processGlobalMessage(Int slotNum, const char *options) { } else { DEBUG_LOG(("NAT::processGlobalMessage - probed by node %d, not our target", node)); } - } else if (!strncmp(ptr, "CONNDONE", strlen("CONNDONE"))) { + } else if (strncmp(ptr, "CONNDONE", strlen("CONNDONE")) == 0) { // format: CONNDONE // we should get the node number of the player who's connection is done from the options // and mark that down as part of the connectionStates. @@ -1205,7 +1205,7 @@ void NAT::processGlobalMessage(Int slotNum, const char *options) { } else { DEBUG_LOG(("NAT::processGlobalMessage - got a connection done message that isn't from this round. node: %d sending node: %d", node, sendingNode)); } - } else if (!strncmp(ptr, "CONNFAILED", strlen("CONNFAILED"))) { + } else if (strncmp(ptr, "CONNFAILED", strlen("CONNFAILED")) == 0) { // format: CONNFAILED // we should get the node number of the player who's connection failed from the options // and mark that down as part of the connectionStates. @@ -1214,7 +1214,7 @@ void NAT::processGlobalMessage(Int slotNum, const char *options) { DEBUG_LOG(("NAT::processGlobalMessage - node %d's connection failed, setting connection state to failed", node)); setConnectionState(node, NATCONNECTIONSTATE_FAILED); } - } else if (!strncmp(ptr, "PORT", strlen("PORT"))) { + } else if (strncmp(ptr, "PORT", strlen("PORT")) == 0) { // format: PORT // we should get the node number and the mangled port number of the client we // are supposed to be communicating with and start probing them. No, that was not diff --git a/Core/GameEngineDevice/Source/StdDevice/Common/StdLocalFileSystem.cpp b/Core/GameEngineDevice/Source/StdDevice/Common/StdLocalFileSystem.cpp index b20aa0eda6..119cd94a35 100644 --- a/Core/GameEngineDevice/Source/StdDevice/Common/StdLocalFileSystem.cpp +++ b/Core/GameEngineDevice/Source/StdDevice/Common/StdLocalFileSystem.cpp @@ -241,7 +241,7 @@ void StdLocalFileSystem::getFileListInDirectory(const AsciiString& currentDirect 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(), ".."))) { + (strcmp(filenameStr.c_str(), ".") != 0 && strcmp(filenameStr.c_str(), "..") != 0)) { // 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(); @@ -268,7 +268,7 @@ void StdLocalFileSystem::getFileListInDirectory(const AsciiString& currentDirect while (!done) { std::string filenameStr = iter->path().filename().string(); if(iter->is_directory() && - (strcmp(filenameStr.c_str(), ".") && strcmp(filenameStr.c_str(), ".."))) { + (strcmp(filenameStr.c_str(), ".") != 0 && strcmp(filenameStr.c_str(), "..") != 0)) { AsciiString tempsearchstr(filenameStr.c_str()); // recursively add files in subdirectories if required. diff --git a/Core/GameEngineDevice/Source/Win32Device/Common/Win32LocalFileSystem.cpp b/Core/GameEngineDevice/Source/Win32Device/Common/Win32LocalFileSystem.cpp index 7b63431cbe..84236de436 100644 --- a/Core/GameEngineDevice/Source/Win32Device/Common/Win32LocalFileSystem.cpp +++ b/Core/GameEngineDevice/Source/Win32Device/Common/Win32LocalFileSystem.cpp @@ -139,7 +139,7 @@ void Win32LocalFileSystem::getFileListInDirectory(const AsciiString& currentDire while (!done) { if (!(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && - (strcmp(findData.cFileName, ".") && strcmp(findData.cFileName, ".."))) { + (strcmp(findData.cFileName, ".") != 0 && strcmp(findData.cFileName, "..") != 0)) { // if we haven't already, add this filename to the list. // a stl set should only allow one copy of each filename AsciiString newFilename; @@ -165,7 +165,7 @@ void Win32LocalFileSystem::getFileListInDirectory(const AsciiString& currentDire while (!done) { if ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && - (strcmp(findData.cFileName, ".") && strcmp(findData.cFileName, ".."))) { + (strcmp(findData.cFileName, ".") != 0 && strcmp(findData.cFileName, "..") != 0)) { AsciiString tempsearchstr; tempsearchstr.concat(currentDirectory); diff --git a/Core/Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp b/Core/Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp index 9c7a124863..03c803491a 100644 --- a/Core/Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp +++ b/Core/Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp @@ -37,7 +37,7 @@ static void Create_Hash_Name(StringClass& name, const StringClass& thumb_name) { name=thumb_name; int len=name.Get_Length(); - WWASSERT(!stricmp(&name[len-4],".tga") || !stricmp(&name[len-4],".dds")); + WWASSERT(stricmp(&name[len-4],".tga") == 0 || stricmp(&name[len-4],".dds") == 0); name[len-4]='\0'; _strlwr(name.Peek_Buffer()); } diff --git a/Core/Libraries/Source/WWVegas/WWDownload/Download.cpp b/Core/Libraries/Source/WWVegas/WWDownload/Download.cpp index 30cf21c44f..8f8ab20e21 100644 --- a/Core/Libraries/Source/WWVegas/WWDownload/Download.cpp +++ b/Core/Libraries/Source/WWVegas/WWDownload/Download.cpp @@ -47,7 +47,7 @@ HRESULT CDownload::DownloadFile(LPCSTR server, LPCSTR username, LPCSTR password, // 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))) + if ((strcmp(m_Server, server) != 0) || (strcmp(m_Login, username) != 0)) { // Damn, a server switch. Close conn & fix state m_Ftp->DisconnectFromServer(); diff --git a/Core/Libraries/Source/WWVegas/WWLib/argv.cpp b/Core/Libraries/Source/WWVegas/WWLib/argv.cpp index db7829e5d5..28958b3fbb 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/argv.cpp +++ b/Core/Libraries/Source/WWVegas/WWLib/argv.cpp @@ -103,7 +103,7 @@ const char *ArgvClass::Find_Again(const char *arg) if (Is_Exact_Size()) { // Case Sensitive, Exact Size. for (; CurrentPos < Argc; CurrentPos++) { - if (!strcmp(arg, Argv[CurrentPos])) { + if (strcmp(arg, Argv[CurrentPos]) == 0) { return Argv[CurrentPos]; } } @@ -111,7 +111,7 @@ const char *ArgvClass::Find_Again(const char *arg) // Case Sensitive, Match first strlen(arg). int len = strlen(arg); for (; CurrentPos < Argc; CurrentPos++) { - if (!strncmp(arg, Argv[CurrentPos], len)) { + if (strncmp(arg, Argv[CurrentPos], len) == 0) { return Argv[CurrentPos]; } } @@ -120,7 +120,7 @@ const char *ArgvClass::Find_Again(const char *arg) if (Is_Exact_Size()) { // Note case sensitive, Exact Size. for (; CurrentPos < Argc; CurrentPos++) { - if (!stricmp(arg, Argv[CurrentPos])) { + if (stricmp(arg, Argv[CurrentPos]) == 0) { return Argv[CurrentPos]; } } @@ -128,7 +128,7 @@ const char *ArgvClass::Find_Again(const char *arg) // Note case sensitive, Match first strlen(arg). int len = strlen(arg); for (; CurrentPos < Argc; CurrentPos++) { - if (!strnicmp(arg, Argv[CurrentPos], len)) { + if (strnicmp(arg, Argv[CurrentPos], len) == 0) { return Argv[CurrentPos]; } } @@ -201,7 +201,7 @@ int ArgvClass::Init(char *lpCmdLine, const char *fileprefix) bool was_file = false; // See if we are to load a file with parameters in it. - if (fp_cmp_len && !strncmp(fileprefix, ptr, fp_cmp_len)) { + if (fp_cmp_len && strncmp(fileprefix, ptr, fp_cmp_len) == 0) { ptr += fp_cmp_len; if (*ptr) { was_file = Load_File(ptr); diff --git a/Core/Libraries/Source/WWVegas/WWLib/cpudetect.cpp b/Core/Libraries/Source/WWVegas/WWLib/cpudetect.cpp index e08182ff2a..622753fa1a 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/cpudetect.cpp +++ b/Core/Libraries/Source/WWVegas/WWLib/cpudetect.cpp @@ -1113,7 +1113,7 @@ void CPUDetectClass::Init_Compact_Log() Get_OS_Info(os_info,OSVersionPlatformId,OSVersionNumberMajor,OSVersionNumberMinor,OSVersionBuildNumber); COMPACTLOG(("%s\t",os_info.Code)); - if (!stricmp(os_info.SubCode,"UNKNOWN")) { + if (stricmp(os_info.SubCode,"UNKNOWN") == 0) { COMPACTLOG(("%d\t",OSVersionBuildNumber&0xffff)); } else { diff --git a/Core/Libraries/Source/WWVegas/WWLib/ini.cpp b/Core/Libraries/Source/WWVegas/WWLib/ini.cpp index fa264d0782..9a1f3c09fe 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/ini.cpp +++ b/Core/Libraries/Source/WWVegas/WWLib/ini.cpp @@ -1637,7 +1637,7 @@ bool INIClass::Put_String(char const * section, char const * entry, char const * */ INIEntry * entryptr = secptr->Find_Entry(entry); if (entryptr != NULL) { - if (strcmp(entryptr->Entry, entry)) { + if (strcmp(entryptr->Entry, entry) != 0) { DuplicateCRCError("INIClass::Put_String", section, entry); } else { #if 0 diff --git a/Core/Libraries/Source/debug/debug_cmd.cpp b/Core/Libraries/Source/debug/debug_cmd.cpp index 09bc9b67d9..019e2e3f7d 100644 --- a/Core/Libraries/Source/debug/debug_cmd.cpp +++ b/Core/Libraries/Source/debug/debug_cmd.cpp @@ -39,7 +39,7 @@ bool DebugCmdInterfaceDebug::Execute(class Debug& dbg, const char *cmd, // just for convenience... bool normalMode=cmdmode==CommandMode::Normal; - if (!strcmp(cmd,"help")) + if (strcmp(cmd,"help") == 0) { if (!normalMode) return true; @@ -50,7 +50,7 @@ bool DebugCmdInterfaceDebug::Execute(class Debug& dbg, const char *cmd, " list, io, alwaysflush, timestamp, exit, clear, add, view\n"; return true; } - else if (!strcmp(argv[0],"list")) + else if (strcmp(argv[0],"list") == 0) { dbg << "list (g|l|d|a|c) [ ]\n" "\n" @@ -72,7 +72,7 @@ bool DebugCmdInterfaceDebug::Execute(class Debug& dbg, const char *cmd, "e.g. debug.cpp(13).\n"; return true; } - else if (!strcmp(argv[0],"io")) + else if (strcmp(argv[0],"io") == 0) { dbg << "io { }]\n" "\n" @@ -91,33 +91,33 @@ bool DebugCmdInterfaceDebug::Execute(class Debug& dbg, const char *cmd, "a list of possible I/O classes.\n"; return true; } - else if (!strcmp(argv[0],"alwaysflush")) + else if (strcmp(argv[0],"alwaysflush") == 0) { dbg << "alwaysflush [ (+|-) ]\n\n" "Enables/disables flushing after each new entry in\n" "the log file (default: off).\n"; return true; } - else if (!strcmp(argv[0],"timestamp")) + else if (strcmp(argv[0],"timestamp") == 0) { dbg << "timestamp [ (+|-) ]\n\n" "Enables/disables timestamping each log entry\n" "(default: off).\n"; return true; } - else if (!strcmp(argv[0],"exit")) + else if (strcmp(argv[0],"exit") == 0) { dbg << "exit\n\nExits program immediately.\n"; return true; } - else if (!strcmp(argv[0],"clear")) + else if (strcmp(argv[0],"clear") == 0) { dbg << "clear (l|a|c)\n\n" "Clears the given inclusion/exclusion list\n" "(l=logs, a=asserts/crashes, c=checks).\n"; return true; } - else if (!strcmp(argv[0],"add")) + else if (strcmp(argv[0],"add") == 0) { dbg << "add (l|a|c) (+|-) \n" "\n" @@ -132,7 +132,7 @@ bool DebugCmdInterfaceDebug::Execute(class Debug& dbg, const char *cmd, "the last match."; return true; } - else if (!strcmp(argv[0],"view")) + else if (strcmp(argv[0],"view") == 0) { dbg << "view [ (l|a|c) ]\n\n" "Shows the active pattern for the given list\n" @@ -141,7 +141,7 @@ bool DebugCmdInterfaceDebug::Execute(class Debug& dbg, const char *cmd, } return false; } - if (!strcmp(cmd,"list")) + if (strcmp(cmd,"list") == 0) { const char *pattern=argn>=2?argv[1]:"*"; @@ -204,10 +204,10 @@ bool DebugCmdInterfaceDebug::Execute(class Debug& dbg, const char *cmd, return true; } - if (!strcmp(cmd,"io")) + if (strcmp(cmd,"io") == 0) { // cmd: io - if (!argn||!strcmp(argv[0],"?")) + if (!argn||strcmp(argv[0],"?") == 0) { // show active/all I/O classes if (normalMode) @@ -232,7 +232,7 @@ bool DebugCmdInterfaceDebug::Execute(class Debug& dbg, const char *cmd, // find I/O class Debug::IOFactoryListEntry *cur=dbg.firstIOFactory; for (;cur;cur=cur->next) - if (!strcmp(argv[0],cur->ioID)) + if (strcmp(argv[0],cur->ioID) == 0) break; if (!cur) { @@ -243,7 +243,7 @@ bool DebugCmdInterfaceDebug::Execute(class Debug& dbg, const char *cmd, if (argn>1) { // 'add' command? - if (!strcmp(argv[1],"add")) + if (strcmp(argv[1],"add") == 0) { if (cur->io) { @@ -258,7 +258,7 @@ bool DebugCmdInterfaceDebug::Execute(class Debug& dbg, const char *cmd, } } // 'remove' command? - if (!strcmp(argv[1],"remove")) + if (strcmp(argv[1],"remove") == 0) { if (cur->io) { @@ -280,7 +280,7 @@ bool DebugCmdInterfaceDebug::Execute(class Debug& dbg, const char *cmd, } return true; } - if (!strcmp(cmd,"alwaysflush")) + if (strcmp(cmd,"alwaysflush") == 0) { if (argn) { @@ -296,7 +296,7 @@ bool DebugCmdInterfaceDebug::Execute(class Debug& dbg, const char *cmd, return true; } - if (!strcmp(cmd,"timestamp")) + if (strcmp(cmd,"timestamp") == 0) { if (argn) { @@ -312,14 +312,14 @@ bool DebugCmdInterfaceDebug::Execute(class Debug& dbg, const char *cmd, return true; } - if (!strcmp(cmd,"exit")) + if (strcmp(cmd,"exit") == 0) { exit(1); return true; } - if (!strcmp(cmd,"clear")|| - !strcmp(cmd,"add")|| - !strcmp(cmd,"view")) + if (strcmp(cmd,"clear") == 0|| + strcmp(cmd,"add") == 0|| + strcmp(cmd,"view") == 0) { unsigned mask=0; if (argn) @@ -338,7 +338,7 @@ bool DebugCmdInterfaceDebug::Execute(class Debug& dbg, const char *cmd, mask=0xffffffff; bool modified=false; - if (!strcmp(cmd,"clear")) + if (strcmp(cmd,"clear") == 0) { // remove some (or all) pattern const char *pattern=argn<2?"*":argv[1]; @@ -368,7 +368,7 @@ bool DebugCmdInterfaceDebug::Execute(class Debug& dbg, const char *cmd, else dbg.lastPatternEntry=NULL; } - if (!strcmp(cmd,"add")) + if (strcmp(cmd,"add") == 0) { // add a pattern if (argn<3) @@ -379,7 +379,7 @@ bool DebugCmdInterfaceDebug::Execute(class Debug& dbg, const char *cmd, modified=true; } } - if (!strcmp(cmd,"view")) + if (strcmp(cmd,"view") == 0) { // show list of defined patterns for (Debug::PatternListEntry *cur=dbg.firstPatternEntry;cur;cur=cur->next) diff --git a/Core/Libraries/Source/debug/debug_debug.cpp b/Core/Libraries/Source/debug/debug_debug.cpp index 5bc38c7c5b..7704975032 100644 --- a/Core/Libraries/Source/debug/debug_debug.cpp +++ b/Core/Libraries/Source/debug/debug_debug.cpp @@ -526,7 +526,7 @@ Debug& Debug::LogBegin(const char *fileOrGroup) // we're doing all this extra work so that DLOGs can be spread across // multiple calls if (Instance.curType==DebugIOInterface::StringType::Log&& - strcmp(Instance.curSource,Instance.curFrameEntry->fileOrGroup)) + strcmp(Instance.curSource,Instance.curFrameEntry->fileOrGroup) != 0) Instance.FlushOutput(); if (Instance.curType!=DebugIOInterface::StringType::Log) @@ -1227,7 +1227,7 @@ const char *Debug::AddLogGroup(const char *fileOrGroup, const char *descr) KnownLogGroupList *cur=firstLogGroup; for (;cur;cur=cur->next) { - if (!strcmp(cur->nameGroup,fileOrGroup)) + if (strcmp(cur->nameGroup,fileOrGroup) == 0) { // yes, return translated name return cur->nameGroup; @@ -1547,7 +1547,7 @@ void Debug::ExecCommand(const char *cmdstart, const char *cmdend) // command group known? for (CmdInterfaceListEntry *cur=firstCmdGroup;cur;cur=cur->next) - if (!strcmp(curCommandGroup,cur->group)) + if (strcmp(curCommandGroup,cur->group) == 0) break; if (!cur) { @@ -1563,18 +1563,18 @@ void Debug::ExecCommand(const char *cmdstart, const char *cmdend) // search for a matching command handler for (CmdInterfaceListEntry *cur=firstCmdGroup;cur;cur=cur->next) { - if (strcmp(curCommandGroup,cur->group)) + if (strcmp(curCommandGroup,cur->group) != 0) continue; bool doneCommand=cur->cmdif->Execute(*this,p,mode,numParts-1,parts+1); - if (doneCommand&&(strcmp(p,"help")||numParts>1)) + if (doneCommand&&(strcmp(p,"help") != 0||numParts>1)) break; } // display error message if command not found, break away if (!cur&&mode==DebugCmdInterface::CommandMode::Normal) { - if (strcmp(p,"help")) + if (strcmp(p,"help") != 0) operator<<("Unknown command"); else if (numParts>1) operator<<("Unknown command, help not available"); diff --git a/Core/Libraries/Source/debug/debug_io_con.cpp b/Core/Libraries/Source/debug/debug_io_con.cpp index 3319496c0e..0b9c2d605e 100644 --- a/Core/Libraries/Source/debug/debug_io_con.cpp +++ b/Core/Libraries/Source/debug/debug_io_con.cpp @@ -194,13 +194,13 @@ void DebugIOCon::Write(StringType type, const char *src, const char *str) void DebugIOCon::Execute(class Debug& dbg, const char *cmd, bool structuredCmd, unsigned argn, const char * const * argv) { - if (!cmd||!strcmp(cmd,"help")) + if (!cmd||strcmp(cmd,"help") == 0) { dbg << "con I/O help:\n" " add [ [ ] ]\n" " create con I/O (optionally specifying the window size)\n"; } - else if (!strcmp(cmd,"add")) + else if (strcmp(cmd,"add") == 0) { if (argn>0&&m_allocatedConsole) { diff --git a/Core/Libraries/Source/debug/debug_io_flat.cpp b/Core/Libraries/Source/debug/debug_io_flat.cpp index eec7cd31f6..7e7d00ca63 100644 --- a/Core/Libraries/Source/debug/debug_io_flat.cpp +++ b/Core/Libraries/Source/debug/debug_io_flat.cpp @@ -332,14 +332,14 @@ void DebugIOFlat::EmergencyFlush(void) void DebugIOFlat::Execute(class Debug& dbg, const char *cmd, bool structuredCmd, unsigned argn, const char * const * argv) { - if (!cmd||!strcmp(cmd,"help")) + if (!cmd||strcmp(cmd,"help") == 0) { if (!argn) dbg << "flat I/O help:\n" "The following I/O commands are defined:\n" " add, copy, splitadd, splitview, splitremove\n" "Type in debug.io flat help for a detailed command help.\n"; - else if (!strcmp(argv[0],"add")) + else if (strcmp(argv[0],"add") == 0) dbg << "add [ [ ] ]\n\n" "Create flat file I/O (optionally specifying file name and file size).\n" @@ -363,13 +363,13 @@ void DebugIOFlat::Execute(class Debug& dbg, const char *cmd, bool structuredCmd, "size memory based ring buffer. This data is flushed out once the \n" "program exits. If no size is given then the size of the log file is not \n" "limited and any log data is written out immediately.\n"; - else if (!strcmp(argv[0],"copy")) + else if (strcmp(argv[0],"copy") == 0) dbg << "copy \n\n" "Copies generated log file(s) into the given directory if the program\n" "exists or crashes. If there is already a log file with the same\n" "name a unique number is appended to the current log files' name.\n"; - else if (!strcmp(argv[0],"splitadd")) + else if (strcmp(argv[0],"splitadd") == 0) dbg << "splitadd [ ]\n\n" "Splits off part of the log data. Multiple splits can be defined. They \n" @@ -402,16 +402,16 @@ void DebugIOFlat::Execute(class Debug& dbg, const char *cmd, bool structuredCmd, "\n" "If no size is given then the size of the log file is not limited and \n" "any log data is written out immediately.\n"; - else if (!strcmp(argv[0],"splitview")) + else if (strcmp(argv[0],"splitview") == 0) dbg << "splitview\n\n" "Shows all existing splits in the order they are evaluated."; - else if (!strcmp(argv[0],"splitremove")) + else if (strcmp(argv[0],"splitremove") == 0) dbg << "splitremove \n\n" "Removes all active splits matching the given name pattern."; else dbg << "Unknown flat I/O command"; } - else if (!strcmp(cmd,"add")) + else if (strcmp(cmd,"add") == 0) { // add [ [ ] ] __ASSERT(m_firstStream==NULL); @@ -426,7 +426,7 @@ void DebugIOFlat::Execute(class Debug& dbg, const char *cmd, bool structuredCmd, m_firstStream->stream=OutputStream::Create(fn,argn>1?atoi(argv[1])*1024:0); m_lastStreamPtr=&m_firstStream->next; } - else if (!strcmp(cmd,"copy")) + else if (strcmp(cmd,"copy") == 0) { // copy if (argn) @@ -434,7 +434,7 @@ void DebugIOFlat::Execute(class Debug& dbg, const char *cmd, bool structuredCmd, strlcpy(m_copyDir,argv[0],sizeof(m_copyDir)); } } - else if (!strcmp(cmd,"splitadd")) + else if (strcmp(cmd,"splitadd") == 0) { // splitadd [ ] if (argn>=3) @@ -470,7 +470,7 @@ void DebugIOFlat::Execute(class Debug& dbg, const char *cmd, bool structuredCmd, ExpandMagic(m_baseFilename,cur->name,fn); StreamListEntry *stream=m_firstStream; for (;stream;stream=stream->next) - if (!strcmp(stream->stream->GetFilename(),fn)) + if (strcmp(stream->stream->GetFilename(),fn) == 0) break; if (!stream) { @@ -484,7 +484,7 @@ void DebugIOFlat::Execute(class Debug& dbg, const char *cmd, bool structuredCmd, cur->stream=stream->stream; } } - else if (!strcmp(cmd,"splitview")) + else if (strcmp(cmd,"splitview") == 0) { // splitview for (SplitListEntry *cur=m_firstSplit;cur;cur=cur->next) @@ -507,7 +507,7 @@ void DebugIOFlat::Execute(class Debug& dbg, const char *cmd, bool structuredCmd, dbg << " " << cur->items << " " << cur->name << "\n"; } } - else if (!strcmp(cmd,"splitremove")) + else if (strcmp(cmd,"splitremove") == 0) { // splitremove const char *pattern=argn<1?"*":argv[0]; diff --git a/Core/Libraries/Source/debug/debug_io_net.cpp b/Core/Libraries/Source/debug/debug_io_net.cpp index ebb8bdba6a..52e3166102 100644 --- a/Core/Libraries/Source/debug/debug_io_net.cpp +++ b/Core/Libraries/Source/debug/debug_io_net.cpp @@ -86,13 +86,13 @@ void DebugIONet::EmergencyFlush(void) void DebugIONet::Execute(class Debug& dbg, const char *cmd, bool structuredCmd, unsigned argn, const char * const * argv) { - if (!cmd||!strcmp(cmd,"help")) + if (!cmd||strcmp(cmd,"help") == 0) { dbg << "net I/O help:\n" " add [ ]\n" " create net I/O (optionally specifying the machine to connect to)\n"; } - else if (!strcmp(cmd,"add")) + else if (strcmp(cmd,"add") == 0) { const char *machine=argn?argv[0]:"."; diff --git a/Core/Libraries/Source/debug/netserv/netserv.cpp b/Core/Libraries/Source/debug/netserv/netserv.cpp index 63c1d806f4..45abd3717c 100644 --- a/Core/Libraries/Source/debug/netserv/netserv.cpp +++ b/Core/Libraries/Source/debug/netserv/netserv.cpp @@ -297,7 +297,7 @@ int CALLBACK WinMain(HINSTANCE,HINSTANCE,LPSTR,int) char *input=InputConsole(); if (input) { - if (!strcmp(input,"quit")) + if (strcmp(input,"quit") == 0) break; } diff --git a/Core/Libraries/Source/debug/test2/test2.cpp b/Core/Libraries/Source/debug/test2/test2.cpp index b8352794da..0980746ec0 100644 --- a/Core/Libraries/Source/debug/test2/test2.cpp +++ b/Core/Libraries/Source/debug/test2/test2.cpp @@ -51,7 +51,7 @@ class TestCmdInterface: public DebugCmdInterface virtual bool Execute(class Debug& dbg, const char *cmd, CommandMode cmdmode, unsigned argn, const char * const * argv) { - if (strcmp(cmd,"box")) + if (strcmp(cmd,"box") != 0) return false; MessageBox(NULL,"Hello world!","Command",MB_OK); diff --git a/Core/Libraries/Source/profile/profile.cpp b/Core/Libraries/Source/profile/profile.cpp index b7fb9ad86c..66981103b7 100644 --- a/Core/Libraries/Source/profile/profile.cpp +++ b/Core/Libraries/Source/profile/profile.cpp @@ -166,7 +166,7 @@ void Profile::StartRange(const char *range) // known name? unsigned k=0; for (;k\n" "\n" @@ -112,7 +112,7 @@ bool ProfileCmdInterface::Execute(class Debug& dbg, const char *cmd, CommandMode "- for inactive). The final state is always the last match."; return true; } - else if (!strcmp(argv[0],"view")) + else if (strcmp(argv[0],"view") == 0) { dbg << "view\n\n" "Shows the active pattern list.\n"; @@ -122,7 +122,7 @@ bool ProfileCmdInterface::Execute(class Debug& dbg, const char *cmd, CommandMode } // command: result - if (!strcmp(cmd,"result")) + if (strcmp(cmd,"result") == 0) { if (!argn) { @@ -139,7 +139,7 @@ bool ProfileCmdInterface::Execute(class Debug& dbg, const char *cmd, CommandMode { unsigned k=0; for (;knext) diff --git a/Core/Libraries/Source/profile/profile_highlevel.cpp b/Core/Libraries/Source/profile/profile_highlevel.cpp index bc418d6fdd..fa55293e93 100644 --- a/Core/Libraries/Source/profile/profile_highlevel.cpp +++ b/Core/Libraries/Source/profile/profile_highlevel.cpp @@ -324,7 +324,7 @@ bool ProfileHighLevel::FindProfile(const char *name, Id &id) ProfileFastCS::Lock lock(cs); for (ProfileId *cur=ProfileId::GetFirst();cur;cur=cur->GetNext()) - if (!strcmp(name,cur->GetName())) + if (strcmp(name,cur->GetName()) == 0) { id.m_idPtr=cur; return true; diff --git a/Core/Libraries/Source/profile/profile_result.cpp b/Core/Libraries/Source/profile/profile_result.cpp index cec326936a..13d55a679b 100644 --- a/Core/Libraries/Source/profile/profile_result.cpp +++ b/Core/Libraries/Source/profile/profile_result.cpp @@ -196,7 +196,7 @@ void ProfileResultFileDOT::WriteResults(void) if (m_frameName) { for (unsigned k=0;knext) - if (!strcmp(source,cur->source)) + if (strcmp(source,cur->source) == 0) { if (cur->numIdid[cur->numId++]=id; @@ -264,7 +264,7 @@ void ProfileResultFileDOT::WriteResults(void) { const char *s=caller.GetSource(); for (FoldHelper *cur2=fold;cur2;cur2=cur2->next) - if (!strcmp(cur2->source,s)) + if (strcmp(cur2->source,s) == 0) break; if (!cur2||cur2->mark) continue; diff --git a/Core/Tools/Autorun/GETCD.cpp b/Core/Tools/Autorun/GETCD.cpp index f0d56b1775..fa8df05e26 100644 --- a/Core/Tools/Autorun/GETCD.cpp +++ b/Core/Tools/Autorun/GETCD.cpp @@ -200,7 +200,7 @@ int GetCDClass::Get_CD_Drive_For_This_Volume ( const char *volume_label ) volume_name[11] = '\0'; } - if ( !_stricmp( volume_label, volume_name )) { + if ( _stricmp( volume_label, volume_name ) == 0) { return( cd_drive ); } @@ -385,7 +385,7 @@ bool CD_Volume_Verification ( int cd_drive, char *volume_label, char *volume_to_ strncpy( volume_label, volume_name, 128 ); } - if ( !_stricmp( volume_to_find, volume_name )) { + if ( _stricmp( volume_to_find, volume_name ) == 0) { return TRUE; } diff --git a/Core/Tools/Autorun/GameText.cpp b/Core/Tools/Autorun/GameText.cpp index f961646d97..c2f990fc4e 100644 --- a/Core/Tools/Autorun/GameText.cpp +++ b/Core/Tools/Autorun/GameText.cpp @@ -778,7 +778,7 @@ Bool GameTextManager::getStringCount( char *filename ) m_buffer[ len+1] = 0; readToEndOfQuote( &file, &m_buffer[1], m_buffer2, m_buffer3, MAX_UITEXT_LENGTH ); } - else if( !stricmp( m_buffer, "END") ) + else if( stricmp( m_buffer, "END") == 0 ) { m_textCount++; } @@ -974,7 +974,7 @@ Bool GameTextManager::parseStringFile( char *filename ) for ( Int i = 0; i < listCount; i++ ) { - if ( !stricmp ( m_stringInfo[i].label.c_str(), m_buffer )) + if ( stricmp ( m_stringInfo[i].label.c_str(), m_buffer ) == 0 ) { DEBUG_ASSERTCRASH ( FALSE, ("String label '%s' multiply defined!", m_buffer )); } @@ -1025,7 +1025,7 @@ Bool GameTextManager::parseStringFile( char *filename ) readString = TRUE; } } - else if ( !stricmp ( m_buffer, "END" )) + else if ( stricmp ( m_buffer, "END" ) == 0 ) { break; } diff --git a/Core/Tools/Babylon/Babylon.cpp b/Core/Tools/Babylon/Babylon.cpp index fede71fa44..7354eefcb9 100644 --- a/Core/Tools/Babylon/Babylon.cpp +++ b/Core/Tools/Babylon/Babylon.cpp @@ -220,7 +220,7 @@ BOOL CALLBACK EnumAllWindowsProcExact(HWND hWnd, LPARAM lParam) GetWindowText(hWnd, szText, sizeof(szText)); - if ( !strncmp (szText, szSearchTitle, strlen ( szSearchTitle))) + if ( strncmp (szText, szSearchTitle, strlen ( szSearchTitle)) == 0) { * (BOOL *) lParam = TRUE; FoundWindow = hWnd; diff --git a/Core/Tools/Babylon/BabylonDlg.cpp b/Core/Tools/Babylon/BabylonDlg.cpp index 0b40dbc28b..27706df01f 100644 --- a/Core/Tools/Babylon/BabylonDlg.cpp +++ b/Core/Tools/Babylon/BabylonDlg.cpp @@ -980,27 +980,27 @@ static int parseComment ( FILE *file, char *buffer, INFO *info ) return new_lines; } - if ( !stricmp ( token, "COMMENT" ) ) + if ( stricmp ( token, "COMMENT" ) == 0 ) { new_lines += getString ( file, buffer, info->comment ); } - else if ( !stricmp ( token, "CONTEXT" ) ) + else if ( stricmp ( token, "CONTEXT" ) == 0 ) { new_lines += getString ( file, buffer, info->context ); } - else if ( !stricmp ( token, "SPEAKER" ) ) + else if ( stricmp ( token, "SPEAKER" ) == 0 ) { new_lines += getString ( file, buffer, info->speaker ); } - else if ( !stricmp ( token, "LISTENER" ) ) + else if ( stricmp ( token, "LISTENER" ) == 0 ) { new_lines += getString ( file, buffer, info->listener ); } - else if ( !stricmp ( token, "MAXLEN" ) ) + else if ( stricmp ( token, "MAXLEN" ) == 0 ) { info->maxlen = atoi ( buffer ); } - else if ( !stricmp ( token, "WAVE" ) ) + else if ( stricmp ( token, "WAVE" ) == 0 ) { new_lines += getString ( file, buffer, info->wave ); } @@ -1024,7 +1024,7 @@ static int getLabelCount( char *filename ) if( fscanf( fp, "%s", buffer ) == EOF ) break; - if ( !stricmp( buffer, "END" ) ) + if ( stricmp( buffer, "END" ) == 0 ) { count++; } @@ -1083,7 +1083,7 @@ int CBabylonDlg::LoadStrFile ( TransDB *db, const char *filename, void (*cb) ( v line_number++; removeLeadingAndTrailing ( buffer ); - if ( !stricmp ( buffer, "END" ) ) + if ( stricmp ( buffer, "END" ) == 0 ) { break; } @@ -1607,7 +1607,7 @@ int CBabylonDlg::UpdateLabel( BabylonLabel *source, BabylonLabel *destination, U if ( (stext = (BabylonText *) dtext->Matched ()) ) { // stext is the newer version; - if ( wcscmp ( dtext->Get (), stext->Get ())) + if ( wcscmp ( dtext->Get (), stext->Get ()) != 0) { if ( update ) { @@ -1617,7 +1617,7 @@ int CBabylonDlg::UpdateLabel( BabylonLabel *source, BabylonLabel *destination, U label_modified = TRUE; info.changes ++; } - if ( wcsicmp ( dtext->Wave (), stext->Wave ())) + if ( wcsicmp ( dtext->Wave (), stext->Wave ()) != 0) { if ( update ) { diff --git a/Core/Tools/Babylon/TransDB.cpp b/Core/Tools/Babylon/TransDB.cpp index ac462c927c..5ef14300b9 100644 --- a/Core/Tools/Babylon/TransDB.cpp +++ b/Core/Tools/Babylon/TransDB.cpp @@ -96,7 +96,7 @@ LANGINFO *GetLangInfo ( char *language ) while ( item->langid != LANGID_UNKNOWN ) { - if ( !stricmp ( language, item->name ) ) + if ( stricmp ( language, item->name ) == 0 ) { return item; } @@ -330,7 +330,7 @@ BabylonText* TransDB::FindSubText ( OLECHAR *pattern, int item ) while ( text ) { - if ( !wcsnicmp ( text->Get (), pattern, 15 )) + if ( wcsnicmp ( text->Get (), pattern, 15 ) == 0) { if ( !item ) { @@ -692,7 +692,7 @@ BabylonText* BabylonLabel::FindText ( OLECHAR *find_text ) while ( txt ) { - if ( !wcscmp ( txt->Get(), find_text )) + if ( wcscmp ( txt->Get(), find_text ) == 0) { return txt; } @@ -836,25 +836,25 @@ void BabylonLabel::AddToTree ( CTreeCtrl *tc, HTREEITEM parent, int changes txt = NextText ( sh ); } - if ( strcmp ( CommentSB(), "" ) ) + if ( strcmp ( CommentSB(), "" ) != 0 ) { sprintf ( buffer, "COMMENT : %s", CommentSB() ); tc->InsertItem ( buffer, litem ); } - if ( strcmp ( ContextSB(), "" ) ) + if ( strcmp ( ContextSB(), "" ) != 0 ) { sprintf ( buffer, "CONTEXT : %s", ContextSB() ); tc->InsertItem ( buffer, litem ); } - if ( strcmp ( SpeakerSB(), "" ) ) + if ( strcmp ( SpeakerSB(), "" ) != 0 ) { sprintf ( buffer, "SPEAKER : %s", SpeakerSB() ); tc->InsertItem ( buffer, litem ); } - if ( strcmp ( ListenerSB(), "" ) ) + if ( strcmp ( ListenerSB(), "" ) != 0 ) { sprintf ( buffer, "LISTENER: %s", ListenerSB() ); tc->InsertItem ( buffer, litem ); @@ -1341,7 +1341,7 @@ void BabylonText::AddToTree ( CTreeCtrl *tc, HTREEITEM parent, int changes tc->InsertItem ( buffer, item ); } - if ( strcmp ( WaveSB(), "" ) ) + if ( strcmp ( WaveSB(), "" ) != 0 ) { sprintf ( buffer, "WAVE : %s", WaveSB() ); tc->InsertItem ( buffer, item ); @@ -1411,7 +1411,7 @@ void Translation::AddToTree ( CTreeCtrl *tc, HTREEITEM parent, int changes item = tc->InsertItem ( buffer, parent ); - if ( strcmp ( CommentSB(), "" ) ) + if ( strcmp ( CommentSB(), "" ) != 0 ) { sprintf ( buffer, "COMMENT: %s", CommentSB() ); tc->InsertItem ( buffer, item ); diff --git a/Core/Tools/Compress/Compress.cpp b/Core/Tools/Compress/Compress.cpp index 323d557d42..66466171cc 100644 --- a/Core/Tools/Compress/Compress.cpp +++ b/Core/Tools/Compress/Compress.cpp @@ -58,13 +58,13 @@ int main(int argc, char **argv) for (int i=1; iActiveRefInfo); if ( ref->File && search_ref->File && - !strcmp(search_ref->File, ref->File) && + strcmp(search_ref->File, ref->File) == 0 && (search_ref->Line == ref->Line) ) { count++; } else if ( (ref->File == NULL) && (search_ref->File == NULL) ) { diff --git a/Core/Tools/assetcull/assetcull.cpp b/Core/Tools/assetcull/assetcull.cpp index dc55dcdd36..4535a6f9c3 100644 --- a/Core/Tools/assetcull/assetcull.cpp +++ b/Core/Tools/assetcull/assetcull.cpp @@ -69,7 +69,7 @@ static bool filesEqual(const char *fn1, const char *fn2) if (fread(buf1,cur,1,f1)!=1|| fread(buf2,cur,1,f2)!=1) break; - if (memcmp(buf1,buf2,cur)) + if (memcmp(buf1,buf2,cur) != 0) break; k+=cur; } @@ -105,7 +105,7 @@ static int recursiveCull(FILE *batchFile, { if (fd.attrib&_A_SUBDIR) { - if (strcmp(fd.name,".")&& + if (strcmp(fd.name,".") != 0&& strcmp(fd.name,"..")) subdir.push_back(fd.name); } diff --git a/Core/Tools/mangler/wlib/configfile.cpp b/Core/Tools/mangler/wlib/configfile.cpp index bed6c86446..b8d465b750 100644 --- a/Core/Tools/mangler/wlib/configfile.cpp +++ b/Core/Tools/mangler/wlib/configfile.cpp @@ -340,7 +340,7 @@ bit8 ConfigFile::setString(IN Wstring &_key, IN Wstring &value, IN char *section for (i=0; iread( &genrep, sizeof(s_genrep) - 1 ); - if ( strncmp(genrep, s_genrep, sizeof(s_genrep) - 1 ) ) { + if ( strncmp(genrep, s_genrep, sizeof(s_genrep) - 1 ) != 0 ) { DEBUG_LOG(("RecorderClass::readReplayHeader - replay file did not have GENREP at the start.")); m_file->close(); m_file = NULL; diff --git a/Generals/Code/GameEngine/Source/Common/System/Directory.cpp b/Generals/Code/GameEngine/Source/Common/System/Directory.cpp index cc221d5005..7dfb7c1e94 100644 --- a/Generals/Code/GameEngine/Source/Common/System/Directory.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/Directory.cpp @@ -97,7 +97,7 @@ Directory::Directory( const AsciiString& dirPath ) : m_dirPath(dirPath) // if this is a subdirectory keep the name around till the end if( BitIsSet( item.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY ) ) { - if ( strcmp( item.cFileName, "." ) && strcmp( item.cFileName, ".." ) ) + if ( strcmp( item.cFileName, "." ) != 0 && strcmp( item.cFileName, ".." ) != 0 ) { info.set(item); m_subdirs.insert( info ); 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 6da46946c0..afba8a27e0 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLBuddyOverlay.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLBuddyOverlay.cpp @@ -508,7 +508,7 @@ void HandleBuddyResponses( void ) break; case BuddyResponse::BUDDYRESPONSE_MESSAGE: { - if ( !wcscmp(resp.arg.message.text, L"I have authorized your request to add me to your list") ) + if ( wcscmp(resp.arg.message.text, L"I have authorized your request to add me to your list") == 0 ) break; if (TheGameSpyInfo->isSavedIgnored(resp.profile)) 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 db5ffbd2a2..8c5ec5718c 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp @@ -1779,7 +1779,7 @@ void WOLGameSetupMenuUpdate( WindowLayout * layout, void *userData) resp.command.c_str(), resp.commandOptions.c_str())); } #endif - if (!strcmp(resp.command.c_str(), "SL")) + if (strcmp(resp.command.c_str(), "SL") == 0) { // slotlist GameSpyStagingRoom *game = TheGameSpyInfo->getCurrentStagingRoom(); @@ -1949,7 +1949,7 @@ void WOLGameSetupMenuUpdate( WindowLayout * layout, void *userData) } } } - else if (!strcmp(resp.command.c_str(), "HWS")) + else if (strcmp(resp.command.c_str(), "HWS") == 0) { // host wants to start GameInfo *game = TheGameSpyInfo->getCurrentStagingRoom(); @@ -1963,13 +1963,13 @@ void WOLGameSetupMenuUpdate( WindowLayout * layout, void *userData) } } } - else if (!stricmp(resp.command.c_str(), "NAT")) + else if (stricmp(resp.command.c_str(), "NAT") == 0) { if (TheNAT != NULL) { TheNAT->processGlobalMessage(-1, resp.commandOptions.c_str()); } } - else if (!stricmp(resp.command.c_str(), "Pings")) + else if (stricmp(resp.command.c_str(), "Pings") == 0) { if (!TheGameSpyInfo->amIHost()) { @@ -1996,7 +1996,7 @@ void WOLGameSetupMenuUpdate( WindowLayout * layout, void *userData) case PeerResponse::PEERRESPONSE_PLAYERUTM: { sawImportantMessage = TRUE; - if (!strcmp(resp.command.c_str(), "STATS")) + if (strcmp(resp.command.c_str(), "STATS") == 0) { PSPlayerStats stats = TheGameSpyPSMessageQueue->parsePlayerKVPairs(resp.commandOptions.c_str()); if (stats.id && (TheGameSpyPSMessageQueue->findPlayerStatsByID(stats.id).id == 0)) @@ -2007,7 +2007,7 @@ void WOLGameSetupMenuUpdate( WindowLayout * layout, void *userData) if (game) { Int slotNum = game->getSlotNum(resp.nick.c_str()); - if ((slotNum >= 0) && (slotNum < MAX_SLOTS) && (!stricmp(resp.command.c_str(), "NAT"))) { + if ((slotNum >= 0) && (slotNum < MAX_SLOTS) && (stricmp(resp.command.c_str(), "NAT") == 0)) { // this is a command for NAT negotiations, pass if off to TheNAT if (TheNAT != NULL) { TheNAT->processGlobalMessage(slotNum, resp.commandOptions.c_str()); @@ -2015,7 +2015,7 @@ void WOLGameSetupMenuUpdate( WindowLayout * layout, void *userData) } if (slotNum == 0 && !TheGameSpyInfo->amIHost()) { - if (!strcmp(resp.command.c_str(), "KICK")) + if (strcmp(resp.command.c_str(), "KICK") == 0) { // oops - we've been kicked. bail. buttonPushed = true; @@ -2041,13 +2041,13 @@ void WOLGameSetupMenuUpdate( WindowLayout * layout, void *userData) } else if (slotNum > 0 && TheGameSpyInfo->amIHost()) { - if (!strcmp(resp.command.c_str(), "accept")) + if (strcmp(resp.command.c_str(), "accept") == 0) { game->getSlot(slotNum)->setAccept(); TheGameSpyInfo->setGameOptions(); WOLDisplaySlotList(); } - else if (!strcmp(resp.command.c_str(), "MAP")) + else if (strcmp(resp.command.c_str(), "MAP") == 0) { Bool hasMap = atoi(resp.commandOptions.c_str()); game->getSlot(slotNum)->setMapAvailability(hasMap); @@ -2076,7 +2076,7 @@ void WOLGameSetupMenuUpdate( WindowLayout * layout, void *userData) } WOLDisplaySlotList(); } - else if (!strcmp(resp.command.c_str(), "REQ")) + else if (strcmp(resp.command.c_str(), "REQ") == 0) { AsciiString options = resp.commandOptions.c_str(); options.trim(); 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 ee6569ab86..cb9b2057b1 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp @@ -1067,7 +1067,7 @@ void WOLLobbyMenuUpdate( WindowLayout * layout, void *userData) AsciiString hostName; hostName.translate(room->getConstSlot(0)->getName()); const char *firstPlayer = resp.stagingRoomPlayerNames[i].c_str(); - if (!strcmp(hostName.str(), firstPlayer)) + if (strcmp(hostName.str(), firstPlayer) == 0) { DEBUG_LOG(("Saw host %s == %s in slot %d", hostName.str(), firstPlayer, i)); isHostPresent = TRUE; 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 10018d7577..5d8eefe7cb 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp @@ -1133,7 +1133,7 @@ void WOLQuickMatchMenuUpdate( WindowLayout * layout, void *userData) { case PeerResponse::PEERRESPONSE_PLAYERUTM: { - if (!stricmp(resp.command.c_str(), "STATS")) + if (stricmp(resp.command.c_str(), "STATS") == 0) { DEBUG_LOG(("Saw STATS from %s, data was '%s'", resp.nick.c_str(), resp.commandOptions.c_str())); AsciiString data = resp.commandOptions.c_str(); @@ -1162,7 +1162,7 @@ void WOLQuickMatchMenuUpdate( WindowLayout * layout, void *userData) } } Int slotNum = TheGameSpyGame->getSlotNum(resp.nick.c_str()); - if ((slotNum >= 0) && (slotNum < MAX_SLOTS) && (!stricmp(resp.command.c_str(), "NAT"))) { + if ((slotNum >= 0) && (slotNum < MAX_SLOTS) && (stricmp(resp.command.c_str(), "NAT") == 0)) { // this is a command for NAT negotiations, pass if off to TheNAT sawImportantMessage = TRUE; if (TheNAT != NULL) { diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp index d7c25e469d..ae800d56ce 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp @@ -207,7 +207,7 @@ static Bool parseBitFlag( const char *flagString, UnsignedInt *bits, for( i = 0, c = flagList; *c; i++, c++ ) { - if( !stricmp( *c, flagString ) ) + if( stricmp( *c, flagString ) == 0 ) { *bits |= (1 << i); return TRUE; @@ -233,7 +233,7 @@ static void parseBitString( const char *inBuffer, UnsignedInt *bits, ConstCharPt // do not modify the inBuffer argument strlcpy(buffer, inBuffer, ARRAY_SIZE(buffer)); - if( strncmp( buffer, "NULL", 4 ) ) + if( strncmp( buffer, "NULL", 4 ) != 0 ) { for( tok = strtok( buffer, "+" ); tok; tok = strtok( NULL, "+" ) ) { @@ -436,7 +436,7 @@ static Bool parseDefaultColor( Color *color, File *inFile, char *buffer ) // Read the rest of the color definition readUntilSemicolon( inFile, buffer, WIN_BUFFER_LENGTH ); - if (!strcmp( buffer, "TRANSPARENT" )) + if (strcmp( buffer, "TRANSPARENT" ) == 0) { *color = WIN_COLOR_UNDEFINED; @@ -838,7 +838,7 @@ static Bool parseListboxData( const char *token, WinInstanceData *instData, // "SCROLLIFATEND" (optional) c = strtok( NULL, seps ); // label - if ( !stricmp(c, "ScrollIfAtEnd") ) + if ( stricmp(c, "ScrollIfAtEnd") == 0 ) { c = strtok( NULL, seps ); // value scanBool( c, listData->scrollIfAtEnd ); @@ -1314,8 +1314,8 @@ static Bool parseDrawData( const char *token, WinInstanceData *instData, first = FALSE; c = strtok( NULL, seps ); // value - if( strcmp( c, "NoImage" ) ) - drawData->image = TheMappedImageCollection->findImageByName( c ); + if( strcmp( c, "NoImage" ) != 0 ) + drawData->image = TheMappedImageCollection->findImageByName( AsciiString( c ) ); else drawData->image = NULL; // COLOR: R G B A @@ -1364,46 +1364,46 @@ void *getDataTemplate( char *type ) static ComboBoxData cData; void *data; - if( !strcmp( type, "VERTSLIDER" ) || !strcmp( type, "HORZSLIDER" ) ) + if( strcmp( type, "VERTSLIDER" ) == 0 || strcmp( type, "HORZSLIDER" ) == 0 ) { memset( &sData, 0, sizeof( SliderData ) ); data = &sData; } - else if( !strcmp( type, "SCROLLLISTBOX" ) ) + else if( strcmp( type, "SCROLLLISTBOX" ) == 0 ) { memset( &lData, 0, sizeof( ListboxData ) ); data = &lData; } - else if( !strcmp( type, "TABCONTROL" ) ) + else if( strcmp( type, "TABCONTROL" ) == 0 ) { memset( &tcData, 0, sizeof( TabControlData ) ); data = &tcData; } - else if( !strcmp( type, "ENTRYFIELD" ) ) + else if( strcmp( type, "ENTRYFIELD" ) == 0 ) { memset( &eData, 0, sizeof( EntryData ) ); data = &eData; } - else if( !strcmp( type, "STATICTEXT" ) ) + else if( strcmp( type, "STATICTEXT" ) == 0 ) { memset( &tData, 0, sizeof( TextData ) ); data = &tData; } - else if( !strcmp( type, "RADIOBUTTON" ) ) + else if( strcmp( type, "RADIOBUTTON" ) == 0 ) { memset( &rData, 0, sizeof( RadioButtonData ) ); data = &rData; } - else if( !strcmp( type, "COMBOBOX" ) ) + else if( strcmp( type, "COMBOBOX" ) == 0 ) { memset( &cData, 0, sizeof( ComboBoxData ) ); @@ -1446,7 +1446,7 @@ static Bool parseData( void **data, char *type, char *buffer ) static RadioButtonData rData; static ComboBoxData cData; - if( !strcmp( type, "VERTSLIDER" ) || !strcmp( type, "HORZSLIDER" ) ) + if( strcmp( type, "VERTSLIDER" ) == 0 || strcmp( type, "HORZSLIDER" ) == 0 ) { memset( &sData, 0, sizeof( SliderData ) ); @@ -1460,7 +1460,7 @@ static Bool parseData( void **data, char *type, char *buffer ) *data = &sData; } - else if( !strcmp( type, "SCROLLLISTBOX" ) ) + else if( strcmp( type, "SCROLLLISTBOX" ) == 0 ) { memset( &lData, 0, sizeof( ListboxData ) ); @@ -1489,7 +1489,7 @@ static Bool parseData( void **data, char *type, char *buffer ) *data = &lData; } - else if( !strcmp( type, "ENTRYFIELD" ) ) + else if( strcmp( type, "ENTRYFIELD" ) == 0 ) { memset( &eData, 0, sizeof( EntryData ) ); @@ -1530,7 +1530,7 @@ static Bool parseData( void **data, char *type, char *buffer ) *data = &eData; } - else if( !strcmp( type, "STATICTEXT" ) ) + else if( strcmp( type, "STATICTEXT" ) == 0 ) { c = strtok( buffer, " \t\n\r" ); @@ -1551,7 +1551,7 @@ static Bool parseData( void **data, char *type, char *buffer ) *data = &tData; } - else if( !strcmp( type, "RADIOBUTTON" ) ) + else if( strcmp( type, "RADIOBUTTON" ) == 0 ) { c = strtok( buffer, " \t\n\r" ); @@ -1617,7 +1617,7 @@ static GameWindow *createGadget( char *type, instData->m_owner = parent; - if( !strcmp( type, "PUSHBUTTON" ) ) + if( strcmp( type, "PUSHBUTTON" ) == 0 ) { instData->m_style |= GWS_PUSH_BUTTON; @@ -1627,7 +1627,7 @@ static GameWindow *createGadget( char *type, instData->m_font, FALSE ); } - else if( !strcmp( type, "RADIOBUTTON" ) ) + else if( strcmp( type, "RADIOBUTTON" ) == 0 ) { RadioButtonData *rData = (RadioButtonData *)data; char filename[ MAX_WINDOW_NAME_LEN ]; @@ -1653,7 +1653,7 @@ static GameWindow *createGadget( char *type, instData->m_font, FALSE ); } - else if( !strcmp( type, "CHECKBOX" ) ) + else if( strcmp( type, "CHECKBOX" ) == 0 ) { instData->m_style |= GWS_CHECK_BOX; @@ -1663,7 +1663,7 @@ static GameWindow *createGadget( char *type, instData->m_font, FALSE ); } - else if( !strcmp( type, "TABCONTROL" ) ) + else if( strcmp( type, "TABCONTROL" ) == 0 ) { TabControlData *tcData = (TabControlData *)data; instData->m_style |= GWS_TAB_CONTROL; @@ -1672,7 +1672,7 @@ static GameWindow *createGadget( char *type, instData, tcData, instData->m_font, FALSE ); } - else if( !strcmp( type, "VERTSLIDER" ) ) + else if( strcmp( type, "VERTSLIDER" ) == 0 ) { SliderData *sData = (SliderData *)data; @@ -1704,7 +1704,7 @@ static GameWindow *createGadget( char *type, } } - else if( !strcmp( type, "HORZSLIDER" ) ) + else if( strcmp( type, "HORZSLIDER" ) == 0 ) { SliderData *sData = (SliderData *)data; @@ -1736,7 +1736,7 @@ static GameWindow *createGadget( char *type, } } - else if( !strcmp( type, "SCROLLLISTBOX" ) ) + else if( strcmp( type, "SCROLLLISTBOX" ) == 0 ) { ListboxData *lData = (ListboxData *)data; @@ -1818,7 +1818,7 @@ static GameWindow *createGadget( char *type, } } - else if( !strcmp( type, "COMBOBOX" ) ) + else if( strcmp( type, "COMBOBOX" ) == 0 ) { ComboBoxData *cData = (ComboBoxData *)data; cData->entryData = NEW EntryData; @@ -1966,7 +1966,7 @@ static GameWindow *createGadget( char *type, } } } - else if( !strcmp( type, "ENTRYFIELD" ) ) + else if( strcmp( type, "ENTRYFIELD" ) == 0 ) { EntryData *eData = (EntryData *)data; @@ -1977,7 +1977,7 @@ static GameWindow *createGadget( char *type, instData->m_font, FALSE ); } - else if( !strcmp( type, "STATICTEXT" ) ) + else if( strcmp( type, "STATICTEXT" ) == 0 ) { TextData *tData = (TextData *)data; @@ -1989,7 +1989,7 @@ static GameWindow *createGadget( char *type, } - else if( !strcmp( type, "PROGRESSBAR" ) ) + else if( strcmp( type, "PROGRESSBAR" ) == 0 ) { instData->m_style |= GWS_PROGRESS_BAR; @@ -2025,7 +2025,7 @@ static GameWindow *createWindow( char *type, parent = peekWindow(); // If this is a regular window just create it - if( !strcmp( type, "USER" ) ) + if( strcmp( type, "USER" ) == 0 ) { window = TheWindowManager->winCreate( parent, @@ -2042,7 +2042,7 @@ static GameWindow *createWindow( char *type, } } - else if( !strcmp( type, "TABPANE" ) ) + else if( strcmp( type, "TABPANE" ) == 0 ) { window = TheWindowManager->winCreate( parent, diff --git a/Generals/Code/GameEngine/Source/GameClient/GameText.cpp b/Generals/Code/GameEngine/Source/GameClient/GameText.cpp index 8bbc840f2b..80d83c9ba2 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GameText.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GameText.cpp @@ -824,7 +824,7 @@ Bool GameTextManager::getStringCount( const char *filename, Int& textCount ) m_buffer[ len+1] = 0; readToEndOfQuote( file, &m_buffer[1], m_buffer2, m_buffer3, MAX_UITEXT_LENGTH ); } - else if( !stricmp( m_buffer, "END") ) + else if( stricmp( m_buffer, "END") == 0 ) { textCount++; } @@ -1035,7 +1035,7 @@ Bool GameTextManager::parseStringFile( const char *filename ) for ( Int i = 0; i < listCount; i++ ) { - if ( !stricmp ( m_stringInfo[i].label.str(), m_buffer )) + if ( stricmp ( m_stringInfo[i].label.str(), m_buffer ) == 0) { DEBUG_ASSERTCRASH ( FALSE, ("String label '%s' multiply defined!", m_buffer )); } @@ -1086,7 +1086,7 @@ Bool GameTextManager::parseStringFile( const char *filename ) readString = TRUE; } } - else if ( !stricmp ( m_buffer, "END" )) + else if ( stricmp ( m_buffer, "END" ) == 0) { break; } @@ -1166,7 +1166,7 @@ Bool GameTextManager::parseMapStringFile( const char *filename ) for ( Int i = 0; i < listCount; i++ ) { - if ( !stricmp ( m_mapStringInfo[i].label.str(), m_buffer )) + if ( stricmp ( m_mapStringInfo[i].label.str(), m_buffer ) == 0) { DEBUG_ASSERTCRASH ( FALSE, ("String label '%s' multiply defined!", m_buffer )); } @@ -1221,7 +1221,7 @@ Bool GameTextManager::parseMapStringFile( const char *filename ) readString = TRUE; } } - else if ( !stricmp ( m_buffer, "END" )) + else if ( stricmp ( m_buffer, "END" ) == 0) { break; } diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp index 678d87cfeb..67cedc7f37 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp @@ -174,7 +174,7 @@ const LocomotorTemplateVector* AIUpdateModuleData::findLocomotorTemplateVector(L self->m_locomotorTemplates[set].clear(); for (const char* locoName = ini->getNextToken(); locoName; locoName = ini->getNextTokenOrNull()) { - if (!*locoName || !stricmp(locoName, "None")) + if (!*locoName || stricmp(locoName, "None") == 0) continue; NameKeyType locoKey = NAMEKEY(locoName); diff --git a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy.cpp b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy.cpp index 79a79303d6..65be44e5c3 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy.cpp @@ -645,14 +645,14 @@ static void RoomUTMCallback(PEER peer, RoomType roomType, const char * nick, Int slotNum = TheGameSpyGame->getSlotNum(nick); if (slotNum == 0 && !TheGameSpyGame->amIHost()) { - if (!strcmp(command, "SL")) + if (strcmp(command, "SL") == 0) { AsciiString options = parameters; options.trim(); ParseAsciiStringToGameInfo(TheGameSpyGame, options.str()); WOLDisplaySlotList(); } - else if (!strcmp(command, "HWS")) // HostWantsStart + else if (strcmp(command, "HWS") == 0) // HostWantsStart { Int slotNum = TheGameSpyGame->getLocalSlotNum(); GameSlot *slot = TheGameSpyGame->getSlot(slotNum); @@ -675,7 +675,7 @@ static void PlayerUTMCallback(PEER peer, const char * nick, Int slotNum = TheGameSpyGame->getSlotNum(nick); if (slotNum != 0 && TheGameSpyGame->amIHost()) { - if (!strcmp(command, "REQ")) + if (strcmp(command, "REQ") == 0) { AsciiString options = parameters; options.trim(); diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.cpp index 2afb91369d..15afd75578 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.cpp @@ -1342,7 +1342,7 @@ Font3DDataClass * WW3DAssetManager::Get_Font3DData( const char *name ) // loop through and see if the Font3D we are looking for has already been // allocated and thus we can just return it. for ( SLNode *node = Font3DDatas.Head(); node; node = node->Next()) { - if (!stricmp(name, node->Data()->Name)) { + if (stricmp(name, node->Data()->Name) == 0) { node->Data()->Add_Ref(); return node->Data(); } diff --git a/Generals/Code/Tools/WorldBuilder/src/ObjectPreview.cpp b/Generals/Code/Tools/WorldBuilder/src/ObjectPreview.cpp index 0e3cc1618f..6ed63b1bb4 100644 --- a/Generals/Code/Tools/WorldBuilder/src/ObjectPreview.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/ObjectPreview.cpp @@ -197,7 +197,7 @@ static UnsignedByte * generatePreview( const ThingTemplate *tt ) } // set render object, or create if we need to if( modelName.isEmpty() == FALSE && - strncmp( modelName.str(), "No ", 3 ) ) + strncmp( modelName.str(), "No ", 3 ) != 0 ) { WW3DAssetManager *pMgr = W3DAssetManager::Get_Instance(); model = pMgr->Create_Render_Obj(modelName.str()); diff --git a/Generals/Code/Tools/WorldBuilder/src/wbview3d.cpp b/Generals/Code/Tools/WorldBuilder/src/wbview3d.cpp index ee07f29dfb..52cfb0e994 100644 --- a/Generals/Code/Tools/WorldBuilder/src/wbview3d.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/wbview3d.cpp @@ -1004,7 +1004,7 @@ void WbView3d::updateFenceListObjects(MapObject *pObject) AsciiString modelName = getModelNameAndScale(pMapObj, &scale, BODY_PRISTINE); // set render object, or create if we need to if( renderObj == NULL && modelName.isEmpty() == FALSE && - strncmp( modelName.str(), "No ", 3 ) ) + strncmp( modelName.str(), "No ", 3 ) != 0 ) { renderObj = m_assetManager->Create_Render_Obj( modelName.str(), scale, 0); @@ -1130,7 +1130,7 @@ void WbView3d::invalBuildListItemInView(BuildListInfo *pBuildToInval) } // set render object, or create if we need to if( renderObj == NULL && modelName.isEmpty() == FALSE && - strncmp( modelName.str(), "No ", 3 ) ) + strncmp( modelName.str(), "No ", 3 ) != 0 ) { renderObj = m_assetManager->Create_Render_Obj( modelName.str(), scale, playerColor); @@ -1395,7 +1395,7 @@ void WbView3d::invalObjectInView(MapObject *pMapObjIn) AsciiString modelName = getModelNameAndScale(pMapObj, &scale, curDamageState); // set render object, or create if we need to if( renderObj == NULL && modelName.isEmpty() == FALSE && - strncmp( modelName.str(), "No ", 3 ) ) + strncmp( modelName.str(), "No ", 3 ) != 0 ) { if (!getShowModels()) { diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp index a90b4903f7..e5bc9ebbfa 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp @@ -894,7 +894,7 @@ Bool RecorderClass::readReplayHeader(ReplayHeader& header) // Read the GENREP header. char genrep[sizeof(s_genrep) - 1] = {0}; m_file->read( &genrep, sizeof(s_genrep) - 1 ); - if ( strncmp(genrep, s_genrep, sizeof(s_genrep) - 1 ) ) { + if ( strncmp(genrep, s_genrep, sizeof(s_genrep) - 1 ) != 0 ) { DEBUG_LOG(("RecorderClass::readReplayHeader - replay file did not have GENREP at the start.")); m_file->close(); m_file = NULL; diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/Directory.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/Directory.cpp index 23a78434a6..c2d526c649 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/Directory.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/Directory.cpp @@ -97,7 +97,7 @@ Directory::Directory( const AsciiString& dirPath ) : m_dirPath(dirPath) // if this is a subdirectory keep the name around till the end if( BitIsSet( item.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY ) ) { - if ( strcmp( item.cFileName, "." ) && strcmp( item.cFileName, ".." ) ) + if ( strcmp( item.cFileName, "." ) != 0 && strcmp( item.cFileName, ".." ) != 0 ) { info.set(item); m_subdirs.insert( info ); 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 166659a950..e109cfb88e 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLBuddyOverlay.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLBuddyOverlay.cpp @@ -508,7 +508,7 @@ void HandleBuddyResponses( void ) break; case BuddyResponse::BUDDYRESPONSE_MESSAGE: { - if ( !wcscmp(resp.arg.message.text, L"I have authorized your request to add me to your list") ) + if ( wcscmp(resp.arg.message.text, L"I have authorized your request to add me to your list") == 0 ) break; if (TheGameSpyInfo->isSavedIgnored(resp.profile)) 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 bb36b3501f..c5a6755723 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp @@ -1957,7 +1957,7 @@ void WOLGameSetupMenuUpdate( WindowLayout * layout, void *userData) resp.command.c_str(), resp.commandOptions.c_str())); } #endif - if (!strcmp(resp.command.c_str(), "SL")) + if (strcmp(resp.command.c_str(), "SL") == 0) { // slotlist GameSpyStagingRoom *game = TheGameSpyInfo->getCurrentStagingRoom(); @@ -2127,7 +2127,7 @@ void WOLGameSetupMenuUpdate( WindowLayout * layout, void *userData) } } } - else if (!strcmp(resp.command.c_str(), "HWS")) + else if (strcmp(resp.command.c_str(), "HWS") == 0) { // host wants to start GameInfo *game = TheGameSpyInfo->getCurrentStagingRoom(); @@ -2141,13 +2141,13 @@ void WOLGameSetupMenuUpdate( WindowLayout * layout, void *userData) } } } - else if (!stricmp(resp.command.c_str(), "NAT")) + else if (stricmp(resp.command.c_str(), "NAT") == 0) { if (TheNAT != NULL) { TheNAT->processGlobalMessage(-1, resp.commandOptions.c_str()); } } - else if (!stricmp(resp.command.c_str(), "Pings")) + else if (stricmp(resp.command.c_str(), "Pings") == 0) { if (!TheGameSpyInfo->amIHost()) { @@ -2174,7 +2174,7 @@ void WOLGameSetupMenuUpdate( WindowLayout * layout, void *userData) case PeerResponse::PEERRESPONSE_PLAYERUTM: { sawImportantMessage = TRUE; - if (!strcmp(resp.command.c_str(), "STATS")) + if (strcmp(resp.command.c_str(), "STATS") == 0) { PSPlayerStats stats = TheGameSpyPSMessageQueue->parsePlayerKVPairs(resp.commandOptions.c_str()); if (stats.id && (TheGameSpyPSMessageQueue->findPlayerStatsByID(stats.id).id == 0)) @@ -2185,7 +2185,7 @@ void WOLGameSetupMenuUpdate( WindowLayout * layout, void *userData) if (game) { Int slotNum = game->getSlotNum(resp.nick.c_str()); - if ((slotNum >= 0) && (slotNum < MAX_SLOTS) && (!stricmp(resp.command.c_str(), "NAT"))) { + if ((slotNum >= 0) && (slotNum < MAX_SLOTS) && (stricmp(resp.command.c_str(), "NAT") == 0)) { // this is a command for NAT negotiations, pass if off to TheNAT if (TheNAT != NULL) { TheNAT->processGlobalMessage(slotNum, resp.commandOptions.c_str()); @@ -2193,7 +2193,7 @@ void WOLGameSetupMenuUpdate( WindowLayout * layout, void *userData) } if (slotNum == 0 && !TheGameSpyInfo->amIHost()) { - if (!strcmp(resp.command.c_str(), "KICK")) + if (strcmp(resp.command.c_str(), "KICK") == 0) { // oops - we've been kicked. bail. buttonPushed = true; @@ -2219,13 +2219,13 @@ void WOLGameSetupMenuUpdate( WindowLayout * layout, void *userData) } else if (slotNum > 0 && TheGameSpyInfo->amIHost()) { - if (!strcmp(resp.command.c_str(), "accept")) + if (strcmp(resp.command.c_str(), "accept") == 0) { game->getSlot(slotNum)->setAccept(); TheGameSpyInfo->setGameOptions(); WOLDisplaySlotList(); } - else if (!strcmp(resp.command.c_str(), "MAP")) + else if (strcmp(resp.command.c_str(), "MAP") == 0) { Bool hasMap = atoi(resp.commandOptions.c_str()); game->getSlot(slotNum)->setMapAvailability(hasMap); @@ -2254,7 +2254,7 @@ void WOLGameSetupMenuUpdate( WindowLayout * layout, void *userData) } WOLDisplaySlotList(); } - else if (!strcmp(resp.command.c_str(), "REQ")) + else if (strcmp(resp.command.c_str(), "REQ") == 0) { AsciiString options = resp.commandOptions.c_str(); options.trim(); 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 6ad99be4c4..9f98a002a8 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp @@ -1085,7 +1085,7 @@ void WOLLobbyMenuUpdate( WindowLayout * layout, void *userData) AsciiString hostName; hostName.translate(room->getConstSlot(0)->getName()); const char *firstPlayer = resp.stagingRoomPlayerNames[i].c_str(); - if (!strcmp(hostName.str(), firstPlayer)) + if (strcmp(hostName.str(), firstPlayer) == 0) { DEBUG_LOG(("Saw host %s == %s in slot %d", hostName.str(), firstPlayer, i)); isHostPresent = TRUE; 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 5557eade74..6ebb5c6804 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp @@ -1112,7 +1112,7 @@ void WOLQuickMatchMenuUpdate( WindowLayout * layout, void *userData) { case PeerResponse::PEERRESPONSE_PLAYERUTM: { - if (!stricmp(resp.command.c_str(), "STATS")) + if (stricmp(resp.command.c_str(), "STATS") == 0) { DEBUG_LOG(("Saw STATS from %s, data was '%s'", resp.nick.c_str(), resp.commandOptions.c_str())); AsciiString data = resp.commandOptions.c_str(); @@ -1141,7 +1141,7 @@ void WOLQuickMatchMenuUpdate( WindowLayout * layout, void *userData) } } Int slotNum = TheGameSpyGame->getSlotNum(resp.nick.c_str()); - if ((slotNum >= 0) && (slotNum < MAX_SLOTS) && (!stricmp(resp.command.c_str(), "NAT"))) { + if ((slotNum >= 0) && (slotNum < MAX_SLOTS) && (stricmp(resp.command.c_str(), "NAT") == 0)) { // this is a command for NAT negotiations, pass if off to TheNAT sawImportantMessage = TRUE; if (TheNAT != NULL) { diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp index f5e2871c92..b416fd0f5b 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp @@ -208,7 +208,7 @@ static Bool parseBitFlag( const char *flagString, UnsignedInt *bits, for( i = 0, c = flagList; *c; i++, c++ ) { - if( !stricmp( *c, flagString ) ) + if( stricmp( *c, flagString ) == 0 ) { *bits |= (1 << i); return TRUE; @@ -234,7 +234,7 @@ static void parseBitString( const char *inBuffer, UnsignedInt *bits, ConstCharPt // do not modify the inBuffer argument strlcpy(buffer, inBuffer, ARRAY_SIZE(buffer)); - if( strncmp( buffer, "NULL", 4 ) ) + if( strncmp( buffer, "NULL", 4 ) != 0 ) { for( tok = strtok( buffer, "+" ); tok; tok = strtok( NULL, "+" ) ) { @@ -437,7 +437,7 @@ static Bool parseDefaultColor( Color *color, File *inFile, char *buffer ) // Read the rest of the color definition readUntilSemicolon( inFile, buffer, WIN_BUFFER_LENGTH ); - if (!strcmp( buffer, "TRANSPARENT" )) + if (strcmp( buffer, "TRANSPARENT" ) == 0) { *color = WIN_COLOR_UNDEFINED; @@ -839,7 +839,7 @@ static Bool parseListboxData( const char *token, WinInstanceData *instData, // "SCROLLIFATEND" (optional) c = strtok( NULL, seps ); // label - if ( !stricmp(c, "ScrollIfAtEnd") ) + if ( stricmp(c, "ScrollIfAtEnd") == 0 ) { c = strtok( NULL, seps ); // value scanBool( c, listData->scrollIfAtEnd ); @@ -1322,8 +1322,8 @@ static Bool parseDrawData( const char *token, WinInstanceData *instData, first = FALSE; c = strtok( NULL, seps ); // value - if( strcmp( c, "NoImage" ) ) - drawData->image = TheMappedImageCollection->findImageByName( c ); + if( strcmp( c, "NoImage" ) != 0 ) + drawData->image = TheMappedImageCollection->findImageByName( AsciiString( c ) ); else drawData->image = NULL; // COLOR: R G B A @@ -1372,46 +1372,46 @@ void *getDataTemplate( char *type ) static ComboBoxData cData; void *data; - if( !strcmp( type, "VERTSLIDER" ) || !strcmp( type, "HORZSLIDER" ) ) + if( strcmp( type, "VERTSLIDER" ) == 0 || strcmp( type, "HORZSLIDER" ) == 0 ) { memset( &sData, 0, sizeof( SliderData ) ); data = &sData; } - else if( !strcmp( type, "SCROLLLISTBOX" ) ) + else if( strcmp( type, "SCROLLLISTBOX" ) == 0 ) { memset( &lData, 0, sizeof( ListboxData ) ); data = &lData; } - else if( !strcmp( type, "TABCONTROL" ) ) + else if( strcmp( type, "TABCONTROL" ) == 0 ) { memset( &tcData, 0, sizeof( TabControlData ) ); data = &tcData; } - else if( !strcmp( type, "ENTRYFIELD" ) ) + else if( strcmp( type, "ENTRYFIELD" ) == 0 ) { memset( &eData, 0, sizeof( EntryData ) ); data = &eData; } - else if( !strcmp( type, "STATICTEXT" ) ) + else if( strcmp( type, "STATICTEXT" ) == 0 ) { memset( &tData, 0, sizeof( TextData ) ); data = &tData; } - else if( !strcmp( type, "RADIOBUTTON" ) ) + else if( strcmp( type, "RADIOBUTTON" ) == 0 ) { memset( &rData, 0, sizeof( RadioButtonData ) ); data = &rData; } - else if( !strcmp( type, "COMBOBOX" ) ) + else if( strcmp( type, "COMBOBOX" ) == 0 ) { memset( &cData, 0, sizeof( ComboBoxData ) ); @@ -1454,7 +1454,7 @@ static Bool parseData( void **data, char *type, char *buffer ) static RadioButtonData rData; static ComboBoxData cData; - if( !strcmp( type, "VERTSLIDER" ) || !strcmp( type, "HORZSLIDER" ) ) + if( strcmp( type, "VERTSLIDER" ) == 0 || strcmp( type, "HORZSLIDER" ) == 0 ) { memset( &sData, 0, sizeof( SliderData ) ); @@ -1468,7 +1468,7 @@ static Bool parseData( void **data, char *type, char *buffer ) *data = &sData; } - else if( !strcmp( type, "SCROLLLISTBOX" ) ) + else if( strcmp( type, "SCROLLLISTBOX" ) == 0 ) { memset( &lData, 0, sizeof( ListboxData ) ); @@ -1497,7 +1497,7 @@ static Bool parseData( void **data, char *type, char *buffer ) *data = &lData; } - else if( !strcmp( type, "ENTRYFIELD" ) ) + else if( strcmp( type, "ENTRYFIELD" ) == 0 ) { memset( &eData, 0, sizeof( EntryData ) ); @@ -1538,7 +1538,7 @@ static Bool parseData( void **data, char *type, char *buffer ) *data = &eData; } - else if( !strcmp( type, "STATICTEXT" ) ) + else if( strcmp( type, "STATICTEXT" ) == 0 ) { c = strtok( buffer, " \t\n\r" ); @@ -1559,7 +1559,7 @@ static Bool parseData( void **data, char *type, char *buffer ) *data = &tData; } - else if( !strcmp( type, "RADIOBUTTON" ) ) + else if( strcmp( type, "RADIOBUTTON" ) == 0 ) { c = strtok( buffer, " \t\n\r" ); @@ -1625,7 +1625,7 @@ static GameWindow *createGadget( char *type, instData->m_owner = parent; - if( !strcmp( type, "PUSHBUTTON" ) ) + if( strcmp( type, "PUSHBUTTON" ) == 0 ) { instData->m_style |= GWS_PUSH_BUTTON; @@ -1635,7 +1635,7 @@ static GameWindow *createGadget( char *type, instData->m_font, FALSE ); } - else if( !strcmp( type, "RADIOBUTTON" ) ) + else if( strcmp( type, "RADIOBUTTON" ) == 0 ) { RadioButtonData *rData = (RadioButtonData *)data; char filename[ MAX_WINDOW_NAME_LEN ]; @@ -1661,7 +1661,7 @@ static GameWindow *createGadget( char *type, instData->m_font, FALSE ); } - else if( !strcmp( type, "CHECKBOX" ) ) + else if( strcmp( type, "CHECKBOX" ) == 0 ) { instData->m_style |= GWS_CHECK_BOX; @@ -1671,7 +1671,7 @@ static GameWindow *createGadget( char *type, instData->m_font, FALSE ); } - else if( !strcmp( type, "TABCONTROL" ) ) + else if( strcmp( type, "TABCONTROL" ) == 0 ) { TabControlData *tcData = (TabControlData *)data; instData->m_style |= GWS_TAB_CONTROL; @@ -1680,7 +1680,7 @@ static GameWindow *createGadget( char *type, instData, tcData, instData->m_font, FALSE ); } - else if( !strcmp( type, "VERTSLIDER" ) ) + else if( strcmp( type, "VERTSLIDER" ) == 0 ) { SliderData *sData = (SliderData *)data; @@ -1712,7 +1712,7 @@ static GameWindow *createGadget( char *type, } } - else if( !strcmp( type, "HORZSLIDER" ) ) + else if( strcmp( type, "HORZSLIDER" ) == 0 ) { SliderData *sData = (SliderData *)data; @@ -1744,7 +1744,7 @@ static GameWindow *createGadget( char *type, } } - else if( !strcmp( type, "SCROLLLISTBOX" ) ) + else if( strcmp( type, "SCROLLLISTBOX" ) == 0 ) { ListboxData *lData = (ListboxData *)data; @@ -1826,7 +1826,7 @@ static GameWindow *createGadget( char *type, } } - else if( !strcmp( type, "COMBOBOX" ) ) + else if( strcmp( type, "COMBOBOX" ) == 0 ) { ComboBoxData *cData = (ComboBoxData *)data; cData->entryData = NEW EntryData; @@ -1974,7 +1974,7 @@ static GameWindow *createGadget( char *type, } } } - else if( !strcmp( type, "ENTRYFIELD" ) ) + else if( strcmp( type, "ENTRYFIELD" ) == 0 ) { EntryData *eData = (EntryData *)data; @@ -1985,7 +1985,7 @@ static GameWindow *createGadget( char *type, instData->m_font, FALSE ); } - else if( !strcmp( type, "STATICTEXT" ) ) + else if( strcmp( type, "STATICTEXT" ) == 0 ) { TextData *tData = (TextData *)data; @@ -1997,7 +1997,7 @@ static GameWindow *createGadget( char *type, } - else if( !strcmp( type, "PROGRESSBAR" ) ) + else if( strcmp( type, "PROGRESSBAR" ) == 0 ) { instData->m_style |= GWS_PROGRESS_BAR; @@ -2033,7 +2033,7 @@ static GameWindow *createWindow( char *type, parent = peekWindow(); // If this is a regular window just create it - if( !strcmp( type, "USER" ) ) + if( strcmp( type, "USER" ) == 0 ) { window = TheWindowManager->winCreate( parent, @@ -2050,7 +2050,7 @@ static GameWindow *createWindow( char *type, } } - else if( !strcmp( type, "TABPANE" ) ) + else if( strcmp( type, "TABPANE" ) == 0 ) { window = TheWindowManager->winCreate( parent, diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GameText.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GameText.cpp index 7492768036..8f0a037f53 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GameText.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GameText.cpp @@ -825,7 +825,7 @@ Bool GameTextManager::getStringCount( const char *filename, Int& textCount ) m_buffer[ len+1] = 0; readToEndOfQuote( file, &m_buffer[1], m_buffer2, m_buffer3, MAX_UITEXT_LENGTH ); } - else if( !stricmp( m_buffer, "END") ) + else if( stricmp( m_buffer, "END") == 0 ) { textCount++; } @@ -1036,7 +1036,7 @@ Bool GameTextManager::parseStringFile( const char *filename ) for ( Int i = 0; i < listCount; i++ ) { - if ( !stricmp ( m_stringInfo[i].label.str(), m_buffer )) + if ( stricmp ( m_stringInfo[i].label.str(), m_buffer ) == 0) { DEBUG_ASSERTCRASH ( FALSE, ("String label '%s' multiply defined!", m_buffer )); } @@ -1087,7 +1087,7 @@ Bool GameTextManager::parseStringFile( const char *filename ) readString = TRUE; } } - else if ( !stricmp ( m_buffer, "END" )) + else if ( stricmp ( m_buffer, "END" ) == 0) { break; } @@ -1167,7 +1167,7 @@ Bool GameTextManager::parseMapStringFile( const char *filename ) for ( Int i = 0; i < listCount; i++ ) { - if ( !stricmp ( m_mapStringInfo[i].label.str(), m_buffer )) + if ( stricmp ( m_mapStringInfo[i].label.str(), m_buffer ) == 0) { DEBUG_ASSERTCRASH ( FALSE, ("String label '%s' multiply defined!", m_buffer )); } @@ -1222,7 +1222,7 @@ Bool GameTextManager::parseMapStringFile( const char *filename ) readString = TRUE; } } - else if ( !stricmp ( m_buffer, "END" )) + else if ( stricmp ( m_buffer, "END" ) == 0) { break; } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp index bfc97640c3..7bc310b7d6 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp @@ -179,7 +179,7 @@ const LocomotorTemplateVector* AIUpdateModuleData::findLocomotorTemplateVector(L self->m_locomotorTemplates[set].clear(); for (const char* locoName = ini->getNextToken(); locoName; locoName = ini->getNextTokenOrNull()) { - if (!*locoName || !stricmp(locoName, "None")) + if (!*locoName || stricmp(locoName, "None") == 0) continue; NameKeyType locoKey = NAMEKEY(locoName); diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.cpp index 597db9f6bc..56b257de89 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.cpp +++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.cpp @@ -1347,7 +1347,7 @@ Font3DDataClass * WW3DAssetManager::Get_Font3DData( const char *name ) // loop through and see if the Font3D we are looking for has already been // allocated and thus we can just return it. for ( SLNode *node = Font3DDatas.Head(); node; node = node->Next()) { - if (!stricmp(name, node->Data()->Name)) { + if (stricmp(name, node->Data()->Name) == 0) { node->Data()->Add_Ref(); return node->Data(); } diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.cpp index e1bcf0dc23..c63442871a 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.cpp +++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.cpp @@ -833,14 +833,14 @@ void DX8Caps::Check_Driver_Version_Status() DriverVersionStatus=DRIVER_STATUS_BAD; break; case VENDOR_NVIDIA: - if (!stricmp(DriverDLL,"nv4.dll")) { + if (stricmp(DriverDLL,"nv4.dll") == 0) { switch (DriverBuildVersion) { case 327: // 5.00.2165.327 DriverVersionStatus=DRIVER_STATUS_BAD; } } - if (!stricmp(DriverDLL,"nv4_disp.dll") || !stricmp(DriverDLL,"nvdd32.dll")) { + if (stricmp(DriverDLL,"nv4_disp.dll") == 0 || stricmp(DriverDLL,"nvdd32.dll") == 0) { switch (DriverBuildVersion) { // 23.11 Is known to be very unstable case 2311: @@ -902,7 +902,7 @@ void DX8Caps::Check_Driver_Version_Status() } } // Elsa OEM drivers? - if (!stricmp(DriverDLL,"egdad.dll")) { + if (stricmp(DriverDLL,"egdad.dll") == 0) { // We know of version 5.9.0.312 (asked MShelling if he the drivers seem ok) switch (DriverBuildVersion) { default: @@ -913,7 +913,7 @@ void DX8Caps::Check_Driver_Version_Status() } // Elsa GLoria - if (!stricmp(DriverDLL,"egliid.dll")) { + if (stricmp(DriverDLL,"egliid.dll") == 0) { switch (DriverBuildVersion) { default: DriverVersionStatus=DRIVER_STATUS_UNKNOWN; @@ -924,12 +924,12 @@ void DX8Caps::Check_Driver_Version_Status() } // ASUS OEM drivers? - if (!stricmp(DriverDLL,"v66_disp.dll")) { + if (stricmp(DriverDLL,"v66_disp.dll") == 0) { // TOMSS1: 5.0.2195.379 } break; case VENDOR_ATI: - if (!stricmp(DriverDLL,"ati2dvag.dll")) { + if (stricmp(DriverDLL,"ati2dvag.dll") == 0) { switch (DriverBuildVersion) { case 3287: DriverVersionStatus=DRIVER_STATUS_UNKNOWN; @@ -948,13 +948,13 @@ void DX8Caps::Check_Driver_Version_Status() break; } } - if (!stricmp(DriverDLL,"atid32ae.dll")) { + if (stricmp(DriverDLL,"atid32ae.dll") == 0) { switch (DriverBuildVersion) { case 1010: DriverVersionStatus=DRIVER_STATUS_OK; } } - if (!stricmp(DriverDLL,"ati3drai.dll")) { + if (stricmp(DriverDLL,"ati3drai.dll") == 0) { switch (DriverBuildVersion) { case 1119: DriverVersionStatus=DRIVER_STATUS_UNKNOWN; @@ -962,7 +962,7 @@ void DX8Caps::Check_Driver_Version_Status() } break; case VENDOR_POWERVR: - if (!stricmp(DriverDLL,"pmx2hal.dll")) { + if (stricmp(DriverDLL,"pmx2hal.dll") == 0) { switch (DriverBuildVersion) { case 3111: // Michael Ruppert - TESTIBM104 default: DriverVersionStatus=DRIVER_STATUS_UNKNOWN; From 3b7e734f863150b4b5602470353da0d848f13f57 Mon Sep 17 00:00:00 2001 From: Tomas Date: Wed, 17 Dec 2025 22:21:13 +0100 Subject: [PATCH 41/70] build: Implement docker build (#1774) --- resources/dockerbuild/Dockerfile | 93 +++++++++++++++++++++++++++++ resources/dockerbuild/entrypoint.sh | 28 +++++++++ scripts/dockerbuild.sh | 78 ++++++++++++++++++++++++ 3 files changed, 199 insertions(+) create mode 100644 resources/dockerbuild/Dockerfile create mode 100644 resources/dockerbuild/entrypoint.sh create mode 100755 scripts/dockerbuild.sh diff --git a/resources/dockerbuild/Dockerfile b/resources/dockerbuild/Dockerfile new file mode 100644 index 0000000000..cad26eb69b --- /dev/null +++ b/resources/dockerbuild/Dockerfile @@ -0,0 +1,93 @@ +FROM debian:12.10-slim + +# Build arguments +ARG CMAKE_VERSION="3.31.6" +ARG GIT_VERSION="2.49.0" +ARG UID +ARG GID + +# Install utils +RUN apt update \ + && apt install wget gpg unzip git -y \ + && dpkg --add-architecture i386 \ + && apt clean \ + && rm -rf /var/lib/apt/lists/* + +# Install wine +RUN mkdir -pm755 /etc/apt/keyrings \ + && (wget -O - https://dl.winehq.org/wine-builds/winehq.key | gpg --dearmor -o /etc/apt/keyrings/winehq-archive.key -) \ + && wget -NP /etc/apt/sources.list.d/ https://dl.winehq.org/wine-builds/debian/dists/bookworm/winehq-bookworm.sources \ + && apt update \ + && apt install --no-install-recommends winehq-stable -y \ + && apt clean \ + && rm -rf /var/lib/apt/lists/* +# Setup build folder +RUN mkdir /build +RUN chown ${UID}:${GID} /build + +USER ${UID}:${GID} +WORKDIR /build/tools + +# Install cmake windows +RUN wget https://github.com/Kitware/CMake/releases/download/v${CMAKE_VERSION}/cmake-${CMAKE_VERSION}-windows-x86_64.zip \ + && unzip cmake-${CMAKE_VERSION}-windows-x86_64.zip -d /build/tools/ \ + && mv /build/tools/cmake-${CMAKE_VERSION}-windows-x86_64 /build/tools/cmake \ + && find /build/tools/ -name "*.zip" -exec rm -f {} + + +# Install git windows +RUN wget https://github.com/git-for-windows/git/releases/download/v${GIT_VERSION}.windows.1/MinGit-${GIT_VERSION}-64-bit.zip \ + && unzip MinGit-${GIT_VERSION}-64-bit.zip -d /build/tools/ \ + && mv /build/tools/cmd /build/tools/git \ + && find /build/tools/ -name "*.zip" -exec rm -f {} + + +# Install Visual Studio 6 Portable +RUN wget https://github.com/itsmattkc/MSVC600/archive/refs/heads/master.zip \ + && unzip master.zip -d /build/tools \ + && mv /build/tools/MSVC600-master/ /build/tools/vs6 \ + && find /build/tools/ -name "*.zip" -exec rm -f {} + + + +#Install ninja +RUN wget https://github.com/ninja-build/ninja/releases/download/v1.13.1/ninja-win.zip \ + && unzip ninja-win.zip -d /build/tools/ \ + && find /build/tools/ -name "*.zip" -exec rm -f {} + + +# Setup wine prefix +ENV WINEDEBUG=-all +ENV WINEARCH=win64 +ENV WINEPREFIX=/build/prefix64 + +# Create empty TEMP folder for linking +RUN mkdir /build/tmp +ENV TMP="Z:\\build\\tmp" +ENV TEMP="Z:\\build\\tmp" +ENV TEMPDIR="Z:\\build\\tmp" + +# Setup Visual Studio 6 Environment variables +ENV VS="Z:\\build\\tools\\vs6" +ENV MSVCDir="$VS\\vc98" +ENV WINEPATH="C:\\windows\\system32;\ +$VS\\vc98\\bin;\ +$VS\\vc98\\lib;\ +$VS\\vc98\\include;\ +$VS\\common\\Tools;\ +$VS\\common\\MSDev98\\bin" +ENV LIB="$VS\\vc98\\Lib;$VS\\vc98\\MFC\\Lib;Z:\\build\\cnc\\build\\vc6" +ENV INCLUDE="$VS\\vc98\\ATL\\INCLUDE;\ +$VS\\vc98\\INCLUDE;\ +$VS\\vc98\\MFC\\INCLUDE;\ +$VS\\vc98\\Include" +ENV CC="$VS\\vc98\\bin\\CL.exe" +ENV CXX="$VS\\vc98\\bin\\CL.exe" +ENV PRESET=vc6 + +#prevent cache warning +ENV HOME=/build/tmp/home +RUN mkdir /build/tmp/home + +WORKDIR /build/cnc + +USER root +COPY entrypoint.sh /entrypoint.sh +RUN chmod +x /entrypoint.sh +CMD /entrypoint.sh diff --git a/resources/dockerbuild/entrypoint.sh b/resources/dockerbuild/entrypoint.sh new file mode 100644 index 0000000000..1fe64c12ea --- /dev/null +++ b/resources/dockerbuild/entrypoint.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail +cd /build/cnc +wineboot +if [ "${FORCE_CMAKE:-}" = "true" ] || [ ! -f build/docker/build.ninja ]; then + wine /build/tools/cmake/bin/cmake.exe \ + --preset ${PRESET} \ + -DCMAKE_SYSTEM="Windows" \ + -DCMAKE_SYSTEM_NAME="Windows" \ + -DCMAKE_SIZEOF_VOID_P=4 \ + -DCMAKE_MAKE_PROGRAM="Z:/build/tools/ninja.exe" \ + -DCMAKE_C_COMPILER="Z:/build/tools/vs6/vc98/bin/cl.exe" \ + -DCMAKE_CXX_COMPILER="Z:/build/tools/vs6/vc98/bin/cl.exe" \ + -DGIT_EXECUTABLE="Z:/build/tools/git/git.exe" \ + -DCMAKE_FIND_ROOT_PATH_MODE_PROGRAM=NEVER \ + -DCMAKE_FIND_ROOT_PATH_MODE_LIBRARY=ONLY \ + -DCMAKE_FIND_ROOT_PATH_MODE_INCLUDE=ONLY \ + -DCMAKE_FIND_ROOT_PATH_MODE_PACKAGE=ONLY \ + -DCMAKE_DISABLE_PRECOMPILE_HEADERS=1 \ + -DCMAKE_C_COMPILER_WORKS=1 \ + -DCMAKE_CXX_COMPILER_WORKS=1 \ + -B /build/cnc/build/docker +fi + +cd /build/cnc/build/docker +wine cmd /c "set TMP=Z:\build\tmp& set TEMP=Z:\build\tmp& Z:\build\tools\ninja.exe $MAKE_TARGET" + + diff --git a/scripts/dockerbuild.sh b/scripts/dockerbuild.sh new file mode 100755 index 0000000000..ec8ae69856 --- /dev/null +++ b/scripts/dockerbuild.sh @@ -0,0 +1,78 @@ +#!/bin/bash +#!/usr/bin/env bash + +set -euo pipefail + +SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) +RESOURCES_DIR=$SCRIPT_DIR/../resources + + +usage() { + cat <&2 + usage + exit 1 + ;; + *) + # Positional TARGET (accept only one) + MAKE_TARGET="$MAKE_TARGET $1" + shift + ;; + esac +done + + +docker build --build-arg UID=$(id -u) --build-arg GID=$(id -g) $RESOURCES_DIR/dockerbuild -t zerohour-build +if [[ "$INTERACTIVE" == "true" ]]; then + FLAGS=" -it --entrypoint bash" +else + FLAGS="" +fi +docker run -u $(id -u):$(id -g) -e MAKE_TARGET="$MAKE_TARGET" -e FORCE_CMAKE=$FORCE_CMAKE -v "`pwd`":/build/cnc --rm $FLAGS zerohour-build + + + + + From fc36efc88783bcde5c12defd7add34c3c976fad9 Mon Sep 17 00:00:00 2001 From: Mauller <26652186+Mauller@users.noreply.github.com> Date: Thu, 18 Dec 2025 18:09:09 +0000 Subject: [PATCH 42/70] bugfix(network): Fix data offset for string reads in NetPacket::readFileMessage() and NetPacket::readFileAnnounceMessage() (#2005) Co-authored-by: SkyAero --- Core/GameEngine/Source/GameNetwork/NetPacket.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Core/GameEngine/Source/GameNetwork/NetPacket.cpp b/Core/GameEngine/Source/GameNetwork/NetPacket.cpp index 8b9590124c..be74404bae 100644 --- a/Core/GameEngine/Source/GameNetwork/NetPacket.cpp +++ b/Core/GameEngine/Source/GameNetwork/NetPacket.cpp @@ -5809,7 +5809,7 @@ NetCommandMsg * NetPacket::readFileMessage(UnsignedByte *data, Int &i) { char filename[_MAX_PATH]; // TheSuperHackers @security Mauller/Jbremer/SkyAero 11/12/2025 Prevent buffer overflow when copying filepath string - i += strlcpy(filename, reinterpret_cast(data), ARRAY_SIZE(filename)); + i += strlcpy(filename, reinterpret_cast(data + i), ARRAY_SIZE(filename)); ++i; //Increment for null terminator msg->setPortableFilename(AsciiString(filename)); // it's transferred as a portable filename @@ -5831,7 +5831,7 @@ NetCommandMsg * NetPacket::readFileAnnounceMessage(UnsignedByte *data, Int &i) { char filename[_MAX_PATH]; // TheSuperHackers @security Mauller/Jbremer/SkyAero 11/12/2025 Prevent buffer overflow when copying filepath string - i += strlcpy(filename, reinterpret_cast(data), ARRAY_SIZE(filename)); + i += strlcpy(filename, reinterpret_cast(data + i), ARRAY_SIZE(filename)); ++i; //Increment for null terminator msg->setPortableFilename(AsciiString(filename)); // it's transferred as a portable filename From 23a29265e5229868be66ad9c9be8069ad26941af Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Fri, 19 Dec 2025 22:34:17 +0100 Subject: [PATCH 43/70] tweak(metaevent): Change COMMANDUSABLE_OBSERVER to no longer apply in Shell Map (#2002) Keys P and O no longer pause the Shell Map. But Shift+P and Shift+O still do --- Core/GameEngine/Include/Common/GameUtility.h | 1 - Core/GameEngine/Source/Common/GameUtility.cpp | 11 ----------- Generals/Code/GameEngine/Include/Common/Player.h | 6 +++--- .../Source/GameClient/MessageStream/MetaEvent.cpp | 8 +++++--- GeneralsMD/Code/GameEngine/Include/Common/Player.h | 6 +++--- .../Source/GameClient/MessageStream/MetaEvent.cpp | 8 +++++--- 6 files changed, 16 insertions(+), 24 deletions(-) diff --git a/Core/GameEngine/Include/Common/GameUtility.h b/Core/GameEngine/Include/Common/GameUtility.h index 8380a9742f..86790ff484 100644 --- a/Core/GameEngine/Include/Common/GameUtility.h +++ b/Core/GameEngine/Include/Common/GameUtility.h @@ -28,7 +28,6 @@ typedef Int PlayerIndex; namespace rts { -bool localPlayerIsObserving(); bool localPlayerHasRadar(); Player* getObservedOrLocalPlayer(); ///< Get the current observed or local player. Is never null. Player* getObservedOrLocalPlayer_Safe(); ///< Get the current observed or local player. Is never null, except when the application does not have players. diff --git a/Core/GameEngine/Source/Common/GameUtility.cpp b/Core/GameEngine/Source/Common/GameUtility.cpp index b62447291c..386fefdb3e 100644 --- a/Core/GameEngine/Source/Common/GameUtility.cpp +++ b/Core/GameEngine/Source/Common/GameUtility.cpp @@ -49,17 +49,6 @@ static void changePlayerCommon(Player* player) } // namespace detail -bool localPlayerIsObserving() -{ - if (TheGameLogic->isInReplayGame() || TheGameLogic->isInShellGame()) - return true; - - if (ThePlayerList->getLocalPlayer()->isPlayerObserver()) - return true; - - return false; -} - bool localPlayerHasRadar() { // Using "local" instead of "observed or local" player because as an observer we prefer diff --git a/Generals/Code/GameEngine/Include/Common/Player.h b/Generals/Code/GameEngine/Include/Common/Player.h index ddf3e3006b..69327b447f 100644 --- a/Generals/Code/GameEngine/Include/Common/Player.h +++ b/Generals/Code/GameEngine/Include/Common/Player.h @@ -590,9 +590,9 @@ class Player : public Snapshot Bool isPlayableSide( void ) const; - Bool isPlayerObserver( void ) const; // Favor !isActive() - this is used for Observer GUI mostly, not in-game stuff - Bool isPlayerDead(void) const; // Favor !isActive() - this is used so OCLs don't give us stuff after death. - Bool isPlayerActive(void) const; + Bool isPlayerObserver( void ) const; // Favor !isPlayerActive() - this is used for Observer GUI mostly, not in-game stuff + Bool isPlayerDead(void) const; // Favor !isPlayerActive() - this is used so OCLs don't give us stuff after death. + Bool isPlayerActive(void) const; // Player is alive and not observer. !isPlayerActive() is synonymous with observing. Bool didPlayerPreorder( void ) const { return m_isPreorder; } diff --git a/Generals/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp b/Generals/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp index 82e81e29f7..2e45e5abab 100644 --- a/Generals/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp @@ -380,14 +380,16 @@ static Bool isMessageUsable(CommandUsableInType usableIn) const Bool usableInShell = (usableIn & COMMANDUSABLE_SHELL); const Bool usableInGame = (usableIn & COMMANDUSABLE_GAME); const Bool usableAsObserver = (usableIn & COMMANDUSABLE_OBSERVER); + const Bool isShellActive = TheShell && TheShell->isShellActive(); + const Bool isObserving = !ThePlayerList->getLocalPlayer()->isPlayerActive(); - if (usableInShell && TheShell && TheShell->isShellActive()) + if (usableInShell && isShellActive) return true; - if (usableInGame && (!TheShell || !TheShell->isShellActive())) + if (usableInGame && !isShellActive) return true; - if (usableAsObserver && rts::localPlayerIsObserving()) + if (usableAsObserver && isObserving) return true; return false; diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Player.h b/GeneralsMD/Code/GameEngine/Include/Common/Player.h index ac292248cd..ad150eb5df 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/Player.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/Player.h @@ -617,9 +617,9 @@ class Player : public Snapshot Bool isPlayableSide( void ) const; - Bool isPlayerObserver( void ) const; // Favor !isActive() - this is used for Observer GUI mostly, not in-game stuff - Bool isPlayerDead(void) const; // Favor !isActive() - this is used so OCLs don't give us stuff after death. - Bool isPlayerActive(void) const; + Bool isPlayerObserver( void ) const; // Favor !isPlayerActive() - this is used for Observer GUI mostly, not in-game stuff + Bool isPlayerDead(void) const; // Favor !isPlayerActive() - this is used so OCLs don't give us stuff after death. + Bool isPlayerActive(void) const; // Player is alive and not observer. !isPlayerActive() is synonymous with observing. Bool didPlayerPreorder( void ) const { return m_isPreorder; } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp index aeaf2287b4..7c347eff72 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp @@ -418,14 +418,16 @@ static Bool isMessageUsable(CommandUsableInType usableIn) const Bool usableInShell = (usableIn & COMMANDUSABLE_SHELL); const Bool usableInGame = (usableIn & COMMANDUSABLE_GAME); const Bool usableAsObserver = (usableIn & COMMANDUSABLE_OBSERVER); + const Bool isShellActive = TheShell && TheShell->isShellActive(); + const Bool isObserving = !ThePlayerList->getLocalPlayer()->isPlayerActive(); - if (usableInShell && TheShell && TheShell->isShellActive()) + if (usableInShell && isShellActive) return true; - if (usableInGame && (!TheShell || !TheShell->isShellActive())) + if (usableInGame && !isShellActive) return true; - if (usableAsObserver && rts::localPlayerIsObserving()) + if (usableAsObserver && isObserving) return true; return false; From 09e6ce77fe7c1dd5d7cd1bc2030eb1048cc781f8 Mon Sep 17 00:00:00 2001 From: Stubbjax Date: Sun, 21 Dec 2025 03:35:57 +1100 Subject: [PATCH 44/70] bugfix(network): Assign disconnect frame when quitting the game via the disconnection menu (#2020) --- Core/GameEngine/Source/GameNetwork/ConnectionManager.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Core/GameEngine/Source/GameNetwork/ConnectionManager.cpp b/Core/GameEngine/Source/GameNetwork/ConnectionManager.cpp index 7b3450a960..6e17e386dc 100644 --- a/Core/GameEngine/Source/GameNetwork/ConnectionManager.cpp +++ b/Core/GameEngine/Source/GameNetwork/ConnectionManager.cpp @@ -1771,6 +1771,7 @@ void ConnectionManager::quitGame() { // Need to do the NetDisconnectPlayerCommandMsg creation and sending here. NetDisconnectPlayerCommandMsg *disconnectMsg = newInstance(NetDisconnectPlayerCommandMsg); disconnectMsg->setDisconnectSlot(m_localSlot); + disconnectMsg->setDisconnectFrame(TheGameLogic->getFrame()); disconnectMsg->setPlayerID(m_localSlot); if (DoesCommandRequireACommandID(disconnectMsg->getNetCommandType())) { disconnectMsg->setID(GenerateNextCommandID()); From 529675f98bfceba107a0755944972534083341a8 Mon Sep 17 00:00:00 2001 From: Bobby Battista Date: Sat, 20 Dec 2025 16:43:56 -0500 Subject: [PATCH 45/70] chore: Implement scripts for custom isEmpty() and singleton refs clang-tidy checks (#2010) --- scripts/clang-tidy-plugin/CMakeLists.txt | 63 +++++ .../GeneralsGameCodeTidyModule.cpp | 30 +++ .../GeneralsGameCodeTidyModule.h | 24 ++ scripts/clang-tidy-plugin/README.md | 250 +++++++++++++++++ .../readability/UseIsEmptyCheck.cpp | 254 ++++++++++++++++++ .../readability/UseIsEmptyCheck.h | 45 ++++ .../UseThisInsteadOfSingletonCheck.cpp | 225 ++++++++++++++++ .../UseThisInsteadOfSingletonCheck.h | 22 ++ scripts/run-clang-tidy.py | 131 ++++++++- 9 files changed, 1034 insertions(+), 10 deletions(-) create mode 100644 scripts/clang-tidy-plugin/CMakeLists.txt create mode 100644 scripts/clang-tidy-plugin/GeneralsGameCodeTidyModule.cpp create mode 100644 scripts/clang-tidy-plugin/GeneralsGameCodeTidyModule.h create mode 100644 scripts/clang-tidy-plugin/README.md create mode 100644 scripts/clang-tidy-plugin/readability/UseIsEmptyCheck.cpp create mode 100644 scripts/clang-tidy-plugin/readability/UseIsEmptyCheck.h create mode 100644 scripts/clang-tidy-plugin/readability/UseThisInsteadOfSingletonCheck.cpp create mode 100644 scripts/clang-tidy-plugin/readability/UseThisInsteadOfSingletonCheck.h diff --git a/scripts/clang-tidy-plugin/CMakeLists.txt b/scripts/clang-tidy-plugin/CMakeLists.txt new file mode 100644 index 0000000000..e8fdbd2581 --- /dev/null +++ b/scripts/clang-tidy-plugin/CMakeLists.txt @@ -0,0 +1,63 @@ +# Custom clang-tidy plugin for GeneralsGameCode +# This plugin provides checks for custom types like AsciiString and UnicodeString + +cmake_minimum_required(VERSION 3.20) +project(GeneralsGameCodeClangTidyPlugin) + +# Find LLVM and Clang +find_package(LLVM REQUIRED CONFIG) +find_package(Clang REQUIRED CONFIG) + +message(STATUS "Found LLVM ${LLVM_PACKAGE_VERSION}") +message(STATUS "Using LLVMConfig.cmake in: ${LLVM_DIR}") +message(STATUS "Using ClangConfig.cmake in: ${Clang_DIR}") + +# Set up include directories +include_directories(${LLVM_INCLUDE_DIRS}) +include_directories(${CLANG_INCLUDE_DIRS}) + +# Add definitions +add_definitions(${LLVM_DEFINITIONS}) +add_definitions(${CLANG_DEFINITIONS}) + +# Set C++ standard +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +# Source files +set(SOURCES + GeneralsGameCodeTidyModule.cpp + readability/UseIsEmptyCheck.cpp + readability/UseThisInsteadOfSingletonCheck.cpp +) + +# Header files +set(HEADERS + GeneralsGameCodeTidyModule.h + readability/UseIsEmptyCheck.h + readability/UseThisInsteadOfSingletonCheck.h +) + +# Create the module library +add_library(GeneralsGameCodeClangTidyPlugin MODULE ${SOURCES} ${HEADERS}) + +# Link against required libraries +target_link_libraries(GeneralsGameCodeClangTidyPlugin + PRIVATE + clangTidy + clangTidyReadabilityModule + clangAST + clangASTMatchers + clangBasic + clangFrontend + clangLex + clangTooling + LLVMSupport +) + +# Set output directory +set_target_properties(GeneralsGameCodeClangTidyPlugin PROPERTIES + LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib + RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin +) + diff --git a/scripts/clang-tidy-plugin/GeneralsGameCodeTidyModule.cpp b/scripts/clang-tidy-plugin/GeneralsGameCodeTidyModule.cpp new file mode 100644 index 0000000000..ff4222cceb --- /dev/null +++ b/scripts/clang-tidy-plugin/GeneralsGameCodeTidyModule.cpp @@ -0,0 +1,30 @@ +//===--- GeneralsGameCodeTidyModule.cpp - GeneralsGameCode Tidy Module ---===// +// +// Custom clang-tidy module for GeneralsGameCode +// Provides GeneralsGameCode-specific checks +// +//===----------------------------------------------------------------------===// + +#include "GeneralsGameCodeTidyModule.h" +#include "readability/UseIsEmptyCheck.h" +#include "readability/UseThisInsteadOfSingletonCheck.h" +#include "llvm/Support/Registry.h" + +namespace clang::tidy::generalsgamecode { + +void GeneralsGameCodeTidyModule::addCheckFactories( + ClangTidyCheckFactories &CheckFactories) { + CheckFactories.registerCheck( + "generals-use-is-empty"); + CheckFactories.registerCheck( + "generals-use-this-instead-of-singleton"); +} + +} // namespace clang::tidy::generalsgamecode + +static llvm::Registry<::clang::tidy::ClangTidyModule>::Add< + ::clang::tidy::generalsgamecode::GeneralsGameCodeTidyModule> + X("generalsgamecode", "GeneralsGameCode-specific checks"); + +volatile int GeneralsGameCodeTidyModuleAnchorSource = 0; + diff --git a/scripts/clang-tidy-plugin/GeneralsGameCodeTidyModule.h b/scripts/clang-tidy-plugin/GeneralsGameCodeTidyModule.h new file mode 100644 index 0000000000..f597578acb --- /dev/null +++ b/scripts/clang-tidy-plugin/GeneralsGameCodeTidyModule.h @@ -0,0 +1,24 @@ +//===--- GeneralsGameCodeTidyModule.h - GeneralsGameCode Tidy Module -----===// +// +// Custom clang-tidy module for GeneralsGameCode +// Provides checks for custom types like AsciiString and UnicodeString +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_GENERALSGAMECODE_GENERALSGAMECODETIDYMODULE_H +#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_GENERALSGAMECODE_GENERALSGAMECODETIDYMODULE_H + +#include "clang-tidy/ClangTidyModule.h" + +namespace clang::tidy::generalsgamecode { + +/// This module is for GeneralsGameCode-specific checks. +class GeneralsGameCodeTidyModule : public ClangTidyModule { +public: + void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override; +}; + +} // namespace clang::tidy::generalsgamecode + +#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_GENERALSGAMECODE_GENERALSGAMECODETIDYMODULE_H + diff --git a/scripts/clang-tidy-plugin/README.md b/scripts/clang-tidy-plugin/README.md new file mode 100644 index 0000000000..cbd9a2f83e --- /dev/null +++ b/scripts/clang-tidy-plugin/README.md @@ -0,0 +1,250 @@ +# GeneralsGameCode Clang-Tidy Custom Checks + +Custom clang-tidy checks for the GeneralsGameCode codebase. **This is primarily designed for Windows**, where checks are built directly into clang-tidy. Mac/Linux users can optionally use the plugin version. + +## Quick Start + +### Windows + +**Option 1: Use Pre-built clang-tidy** +- Precompiled binaries can be found at: https://github.com/TheSuperHackers/GeneralsTools + +**Option 2: Build It Yourself** + +Follow the manual steps in the [Windows: Building Checks Into clang-tidy](#windows-building-checks-into-clang-tidy) section below. + +**Usage** +```powershell +llvm-project\build\bin\clang-tidy.exe -p build/clang-tidy ` + --checks='-*,generals-use-is-empty,generals-use-this-instead-of-singleton' ` + file.cpp +``` + +### macOS/Linux (Plugin Version) + +If you prefer the plugin approach on macOS/Linux: + +```bash +# Build the plugin +cd scripts/clang-tidy-plugin +mkdir build && cd build +cmake .. -DLLVM_DIR=/path/to/llvm/lib/cmake/llvm +cmake --build . --config Release + +# Use with --load flag +clang-tidy -p build/clang-tidy \ + --checks='-*,generals-use-is-empty' \ + -load scripts/clang-tidy-plugin/build/lib/libGeneralsGameCodeClangTidyPlugin.so \ + file.cpp +``` + +**Note:** On Windows, plugin loading via `--load` is **not supported** due to DLL static initialization limitations. Windows users must use the built-in version. + +## Checks + +### `generals-use-is-empty` + +Finds uses of `getLength() == 0`, `getLength() > 0`, `compare("") == 0`, or `compareNoCase("") == 0` on `AsciiString` and `UnicodeString`, and `Get_Length() == 0` on `StringClass` and `WideStringClass`, and suggests using `isEmpty()`/`Is_Empty()` or `!isEmpty()`/`!Is_Empty()` instead. + +**Examples:** + +```cpp +// Before (AsciiString/UnicodeString) +if (str.getLength() == 0) { ... } +if (str.getLength() > 0) { ... } +if (str.compare("") == 0) { ... } +if (str.compareNoCase("") == 0) { ... } +if (str.compare(AsciiString::TheEmptyString) == 0) { ... } + +// After (AsciiString/UnicodeString) +if (str.isEmpty()) { ... } +if (!str.isEmpty()) { ... } +if (str.isEmpty()) { ... } +if (str.isEmpty()) { ... } +if (str.isEmpty()) { ... } + +// Before (StringClass/WideStringClass) +if (str.Get_Length() == 0) { ... } +if (str.Get_Length() > 0) { ... } + +// After (StringClass/WideStringClass) +if (str.Is_Empty()) { ... } +if (!str.Is_Empty()) { ... } +``` + +### `generals-use-this-instead-of-singleton` + +Finds uses of singleton global variables (like `TheGameLogic->method()` or `TheGlobalData->member`) inside member functions of the same class type, and suggests using the member directly (e.g., `method()` or `member`) instead of the singleton reference. + +**Examples:** + +```cpp +// Before +void GameLogic::update() { + UnsignedInt now = TheGameLogic->getFrame(); + TheGameLogic->setFrame(now + 1); + TheGameLogic->m_frame = 10; +} + +// After +void GameLogic::update() { + UnsignedInt now = getFrame(); + setFrame(now + 1); + m_frame = 10; +} +``` + +## Prerequisites + +Before using clang-tidy, you need to generate a compile commands database: + +```bash +cmake -B build/clang-tidy -DCMAKE_DISABLE_PRECOMPILE_HEADERS=ON -G Ninja +``` + +This creates `build/clang-tidy/compile_commands.json` which tells clang-tidy how to compile each file. + +## Windows: Building Checks Into clang-tidy + +Since plugin loading via `--load` doesn't work on Windows, the checks are integrated directly into the clang-tidy source tree. This is the recommended approach for Windows. + +### Step 1: Clone and Build LLVM + +### Step 2: Copy Plugin Files to LLVM Source Tree + +```powershell +# Create the plugin directory in clang-tools-extra +mkdir llvm-project\clang-tools-extra\clang-tidy\plugins\generalsgamecode + +# Copy the plugin source files +cp -r scripts\clang-tidy-plugin\*.cpp llvm-project\clang-tools-extra\clang-tidy\plugins\generalsgamecode\ +cp -r scripts\clang-tidy-plugin\*.h llvm-project\clang-tools-extra\clang-tidy\plugins\generalsgamecode\ +cp -r scripts\clang-tidy-plugin\readability llvm-project\clang-tools-extra\clang-tidy\plugins\generalsgamecode\ +``` + +**Important:** After copying, you need to update the include paths in the headers: +- Change `#include "clang-tidy/ClangTidyCheck.h"` to `#include "../../../ClangTidyCheck.h"` +- Change `#include "clang-tidy/ClangTidyModule.h"` to `#include "../../ClangTidyModule.h"` + +### Step 3: Create CMakeLists.txt for the Module + +Create `llvm-project/clang-tools-extra/clang-tidy/plugins/generalsgamecode/CMakeLists.txt`: + +```cmake +add_clang_library(clangTidyGeneralsGameCodeModule STATIC + GeneralsGameCodeTidyModule.cpp + readability/UseIsEmptyCheck.cpp + readability/UseThisInsteadOfSingletonCheck.cpp + + LINK_LIBS + clangTidy + clangTidyUtils + ) + +clang_target_link_libraries(clangTidyGeneralsGameCodeModule + PRIVATE + clangAST + clangASTMatchers + clangBasic + clangLex + clangTooling + ) +``` + +### Step 4: Register the Module + +**Modify `llvm-project/clang-tools-extra/clang-tidy/CMakeLists.txt`:** + +Add the subdirectory: +```cmake +add_subdirectory(plugins/generalsgamecode) +``` + +Add to `ALL_CLANG_TIDY_CHECKS`: +```cmake +set(ALL_CLANG_TIDY_CHECKS + ... + clangTidyGeneralsGameCodeModule + ... +) +``` + +**Modify `llvm-project/clang-tools-extra/clang-tidy/ClangTidyForceLinker.h`:** + +Add the anchor to force linker inclusion: +```cpp +// This anchor is used to force the linker to link the GeneralsGameCodeModule. +extern volatile int GeneralsGameCodeModuleAnchorSource; +static int LLVM_ATTRIBUTE_UNUSED GeneralsGameCodeModuleAnchorDestination = + GeneralsGameCodeModuleAnchorSource; +``` + +**Modify `llvm-project/clang-tools-extra/clang-tidy/plugins/generalsgamecode/GeneralsGameCodeTidyModule.cpp`:** + +Ensure the anchor is defined: +```cpp +namespace clang::tidy { +// ... module registration ... + +// Force linker to include this module +volatile int GeneralsGameCodeModuleAnchorSource = 0; +} +``` + +### Step 5: Rebuild clang-tidy + +```powershell +cd llvm-project\build +ninja clang-tidy +``` + +### Step 6: Use the Built-in Checks + +Once rebuilt, the checks are always available - no `--load` flag needed: + +```powershell +llvm-project\build\bin\clang-tidy.exe -p build/clang-tidy ` + --checks='-*,generals-use-is-empty,generals-use-this-instead-of-singleton' ` + file.cpp +``` + + +## macOS/Linux: Building the Plugin + +If you're on macOS or Linux and want to use the plugin version: + +### Prerequisites + +**macOS:** +```bash +brew install llvm@21 +``` + +**Linux (Ubuntu/Debian):** +```bash +sudo apt-get install llvm-21-dev clang-21 libclang-21-dev +``` + +### Building the Plugin + +```bash +cd scripts/clang-tidy-plugin +mkdir build && cd build +cmake .. -DLLVM_DIR=/path/to/llvm/lib/cmake/llvm -DClang_DIR=/path/to/clang/lib/cmake/clang +cmake --build . --config Release +``` + +The plugin will be built as a shared library (`.so` on Linux, `.dylib` on macOS) in the `build/lib/` directory. + +### Using the Plugin + +```bash +clang-tidy -p build/clang-tidy \ + --checks='-*,generals-use-is-empty,generals-use-this-instead-of-singleton' \ + -load scripts/clang-tidy-plugin/build/lib/libGeneralsGameCodeClangTidyPlugin.so \ + file.cpp +``` + +**Important:** The plugin must be built with the same LLVM version as the `clang-tidy` executable in your PATH. The CMake build will display which LLVM version it found (e.g., `Found LLVM 21.1.7`). Verify this matches your `clang-tidy --version` output. + +- Windows plugins not working is a known limitation - see [GitHub issue #159710](https://github.com/llvm/llvm-project/issues/159710) and [LLVM Discourse discussion](https://discourse.llvm.org/t/clang-tidy-is-clang-tidy-out-of-tree-check-plugin-load-mechanism-guaranteed-to-work-with-msvc/84111) diff --git a/scripts/clang-tidy-plugin/readability/UseIsEmptyCheck.cpp b/scripts/clang-tidy-plugin/readability/UseIsEmptyCheck.cpp new file mode 100644 index 0000000000..fe70a15b5e --- /dev/null +++ b/scripts/clang-tidy-plugin/readability/UseIsEmptyCheck.cpp @@ -0,0 +1,254 @@ +//===--- UseIsEmptyCheck.cpp - Use isEmpty() instead of getLength() == 0 -===// +// +// This check finds patterns like: +// - AsciiString::getLength() == 0 -> AsciiString::isEmpty() +// - AsciiString::getLength() > 0 -> !AsciiString::isEmpty() +// - UnicodeString::getLength() == 0 -> UnicodeString::isEmpty() +// - UnicodeString::getLength() > 0 -> !UnicodeString::isEmpty() +// - StringClass::Get_Length() == 0 -> StringClass::Is_Empty() +// - WideStringClass::Get_Length() == 0 -> WideStringClass::Is_Empty() +// - AsciiString::compare("") == 0 -> AsciiString::isEmpty() +// - UnicodeString::compare(L"") == 0 -> UnicodeString::isEmpty() +// - AsciiString::compare(AsciiString::TheEmptyString) == 0 -> AsciiString::isEmpty() +// - UnicodeString::compare(UnicodeString::TheEmptyString) == 0 -> UnicodeString::isEmpty() +// +//===----------------------------------------------------------------------===// + +#include "UseIsEmptyCheck.h" +#include "clang/AST/ASTContext.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/Basic/SourceLocation.h" +#include "clang/Lex/Lexer.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::generalsgamecode::readability { + +void UseIsEmptyCheck::registerMatchers(MatchFinder *Finder) { + // Matcher for AsciiString/UnicodeString with getLength() + auto GetLengthCall = cxxMemberCallExpr( + callee(cxxMethodDecl(hasName("getLength"))), + on(hasType(hasUnqualifiedDesugaredType( + recordType(hasDeclaration(cxxRecordDecl( + hasAnyName("AsciiString", "UnicodeString")))))))); + + // Matcher for StringClass/WideStringClass with Get_Length() + auto GetLengthCallWWVegas = cxxMemberCallExpr( + callee(cxxMethodDecl(hasName("Get_Length"))), + on(hasType(hasUnqualifiedDesugaredType( + recordType(hasDeclaration(cxxRecordDecl( + hasAnyName("StringClass", "WideStringClass")))))))); + + // Helper function to add matchers for a given GetLength call matcher + auto addMatchersForGetLength = [&](const auto &GetLengthMatcher) { + Finder->addMatcher( + binaryOperator( + hasOperatorName("=="), + hasLHS(ignoringParenImpCasts(GetLengthMatcher.bind("getLengthCall"))), + hasRHS(integerLiteral(equals(0)).bind("zero"))) + .bind("comparison"), + this); + + Finder->addMatcher( + binaryOperator( + hasOperatorName("!="), + hasLHS(ignoringParenImpCasts(GetLengthMatcher.bind("getLengthCall"))), + hasRHS(integerLiteral(equals(0)).bind("zero"))) + .bind("comparison"), + this); + + Finder->addMatcher( + binaryOperator( + hasOperatorName(">"), + hasLHS(ignoringParenImpCasts(GetLengthMatcher.bind("getLengthCall"))), + hasRHS(integerLiteral(equals(0)).bind("zero"))) + .bind("comparison"), + this); + + Finder->addMatcher( + binaryOperator( + hasOperatorName("<="), + hasLHS(ignoringParenImpCasts(GetLengthMatcher.bind("getLengthCall"))), + hasRHS(integerLiteral(equals(0)).bind("zero"))) + .bind("comparison"), + this); + + Finder->addMatcher( + binaryOperator( + hasOperatorName("=="), + hasLHS(integerLiteral(equals(0)).bind("zero")), + hasRHS(ignoringParenImpCasts(GetLengthMatcher.bind("getLengthCall")))) + .bind("comparison"), + this); + + Finder->addMatcher( + binaryOperator( + hasOperatorName("!="), + hasLHS(integerLiteral(equals(0)).bind("zero")), + hasRHS(ignoringParenImpCasts(GetLengthMatcher.bind("getLengthCall")))) + .bind("comparison"), + this); + }; + + addMatchersForGetLength(GetLengthCall); + addMatchersForGetLength(GetLengthCallWWVegas); + + // Matcher for TheEmptyString static member access (AsciiString::TheEmptyString or UnicodeString::TheEmptyString) + auto TheEmptyStringRef = memberExpr( + member(hasName("TheEmptyString")), + hasObjectExpression(hasType(hasUnqualifiedDesugaredType( + recordType(hasDeclaration(cxxRecordDecl( + hasAnyName("AsciiString", "UnicodeString")))))))); + + // Matcher for AsciiString/UnicodeString with compare() - we'll check if argument is empty in check() + auto CompareCall = cxxMemberCallExpr( + callee(cxxMethodDecl(hasName("compare"))), + on(hasType(hasUnqualifiedDesugaredType( + recordType(hasDeclaration(cxxRecordDecl( + hasAnyName("AsciiString", "UnicodeString"))))))), + hasArgument(0, anyOf( + stringLiteral().bind("stringLiteralArg"), + TheEmptyStringRef.bind("theEmptyStringArg")))); + + // Matcher for AsciiString/UnicodeString with compareNoCase() - we'll check if argument is empty in check() + auto CompareNoCaseCall = cxxMemberCallExpr( + callee(cxxMethodDecl(hasName("compareNoCase"))), + on(hasType(hasUnqualifiedDesugaredType( + recordType(hasDeclaration(cxxRecordDecl( + hasAnyName("AsciiString", "UnicodeString"))))))), + hasArgument(0, anyOf( + stringLiteral().bind("stringLiteralArg"), + TheEmptyStringRef.bind("theEmptyStringArg")))); + + // Helper function to add matchers for compare() and compareNoCase() calls + auto addMatchersForCompare = [&](const auto &CompareMatcher, const char *BindingName) { + Finder->addMatcher( + binaryOperator( + hasOperatorName("=="), + hasLHS(ignoringParenImpCasts(CompareMatcher.bind(BindingName))), + hasRHS(integerLiteral(equals(0)).bind("zero"))) + .bind("comparison"), + this); + + Finder->addMatcher( + binaryOperator( + hasOperatorName("!="), + hasLHS(ignoringParenImpCasts(CompareMatcher.bind(BindingName))), + hasRHS(integerLiteral(equals(0)).bind("zero"))) + .bind("comparison"), + this); + + Finder->addMatcher( + binaryOperator( + hasOperatorName("=="), + hasLHS(integerLiteral(equals(0)).bind("zero")), + hasRHS(ignoringParenImpCasts(CompareMatcher.bind(BindingName)))) + .bind("comparison"), + this); + + Finder->addMatcher( + binaryOperator( + hasOperatorName("!="), + hasLHS(integerLiteral(equals(0)).bind("zero")), + hasRHS(ignoringParenImpCasts(CompareMatcher.bind(BindingName)))) + .bind("comparison"), + this); + }; + + addMatchersForCompare(CompareCall, "compareCall"); + addMatchersForCompare(CompareNoCaseCall, "compareNoCaseCall"); +} + +void UseIsEmptyCheck::check(const MatchFinder::MatchResult &Result) { + const auto *Comparison = Result.Nodes.getNodeAs("comparison"); + const auto *GetLengthCall = + Result.Nodes.getNodeAs("getLengthCall"); + const auto *CompareCall = + Result.Nodes.getNodeAs("compareCall"); + const auto *CompareNoCaseCall = + Result.Nodes.getNodeAs("compareNoCaseCall"); + + if (!Comparison) + return; + + const CXXMemberCallExpr *MethodCall = GetLengthCall ? GetLengthCall : + (CompareCall ? CompareCall : CompareNoCaseCall); + if (!MethodCall) + return; + + // For compare() and compareNoCase() calls, verify the argument is actually empty + if (CompareCall || CompareNoCaseCall) { + const auto *StringLit = Result.Nodes.getNodeAs("stringLiteralArg"); + const auto *TheEmptyString = Result.Nodes.getNodeAs("theEmptyStringArg"); + + if (StringLit) { + // Check if string literal is actually empty ("" or L"") + StringRef Str = StringLit->getString(); + if (!Str.empty()) { + return; // Not an empty string literal + } + } else if (!TheEmptyString) { + return; // Not matching empty string pattern + } + } + + const Expr *ObjectExpr = MethodCall->getImplicitObjectArgument(); + if (!ObjectExpr) + return; + + // Determine which method name to use based on the called method + StringRef MethodName = MethodCall->getMethodDecl()->getName(); + std::string IsEmptyMethodName; + std::string MethodNameStr; + + if (MethodName == "Get_Length") { + IsEmptyMethodName = "Is_Empty()"; + MethodNameStr = "Get_Length()"; + } else if (MethodName == "compare") { + IsEmptyMethodName = "isEmpty()"; + MethodNameStr = "compare()"; + } else if (MethodName == "compareNoCase") { + IsEmptyMethodName = "isEmpty()"; + MethodNameStr = "compareNoCase()"; + } else { + IsEmptyMethodName = "isEmpty()"; + MethodNameStr = "getLength()"; + } + + StringRef Operator = Comparison->getOpcodeStr(); + bool ShouldNegate = false; + + if (Operator == "==") { + ShouldNegate = false; + } else if (Operator == "!=") { + ShouldNegate = true; + } else if (Operator == ">") { + ShouldNegate = true; + } else if (Operator == "<=") { + ShouldNegate = false; + } else { + return; + } + + StringRef ObjectText = Lexer::getSourceText( + CharSourceRange::getTokenRange(ObjectExpr->getSourceRange()), + *Result.SourceManager, Result.Context->getLangOpts()); + + std::string Replacement; + if (ShouldNegate) { + Replacement = "!" + ObjectText.str() + "." + IsEmptyMethodName; + } else { + Replacement = ObjectText.str() + "." + IsEmptyMethodName; + } + + SourceLocation StartLoc = Comparison->getBeginLoc(); + SourceLocation EndLoc = Comparison->getEndLoc(); + + diag(Comparison->getBeginLoc(), + "use %0 instead of comparing %1 with 0") + << Replacement << MethodNameStr + << FixItHint::CreateReplacement( + CharSourceRange::getTokenRange(StartLoc, EndLoc), Replacement); +} + +} // namespace clang::tidy::generalsgamecode::readability diff --git a/scripts/clang-tidy-plugin/readability/UseIsEmptyCheck.h b/scripts/clang-tidy-plugin/readability/UseIsEmptyCheck.h new file mode 100644 index 0000000000..2d6dd84253 --- /dev/null +++ b/scripts/clang-tidy-plugin/readability/UseIsEmptyCheck.h @@ -0,0 +1,45 @@ +//===--- UseIsEmptyCheck.h - Use isEmpty() instead of getLength() == 0 ---===// +// +// This check finds patterns like: +// - AsciiString::getLength() == 0 -> AsciiString::isEmpty() +// - AsciiString::getLength() > 0 -> !AsciiString::isEmpty() +// - UnicodeString::getLength() == 0 -> UnicodeString::isEmpty() +// - UnicodeString::getLength() > 0 -> !UnicodeString::isEmpty() +// - StringClass::Get_Length() == 0 -> StringClass::Is_Empty() +// - WideStringClass::Get_Length() == 0 -> WideStringClass::Is_Empty() +// - AsciiString::compare("") == 0 -> AsciiString::isEmpty() +// - UnicodeString::compare(L"") == 0 -> UnicodeString::isEmpty() +// - AsciiString::compare(AsciiString::TheEmptyString) == 0 -> AsciiString::isEmpty() +// - UnicodeString::compare(UnicodeString::TheEmptyString) == 0 -> UnicodeString::isEmpty() +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_GENERALSGAMECODE_READABILITY_USEISEMPTYCHECK_H +#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_GENERALSGAMECODE_READABILITY_USEISEMPTYCHECK_H + +#include "clang-tidy/ClangTidyCheck.h" + +namespace clang::tidy::generalsgamecode::readability { + +/// Finds uses of getLength() == 0 or getLength() > 0 on AsciiString and +/// UnicodeString, and Get_Length() == 0 on StringClass and WideStringClass, +/// and suggests using isEmpty()/Is_Empty() or !isEmpty()/!Is_Empty() instead. +/// Also finds uses of compare("") == 0 or compare(TheEmptyString) == 0 and +/// suggests using isEmpty() instead. +/// +/// For the user-facing documentation see: +/// http://clang.llvm.org/extra/clang-tidy/checks/generals-use-is-empty.html +class UseIsEmptyCheck : public ClangTidyCheck { +public: + UseIsEmptyCheck(StringRef Name, ClangTidyContext *Context) + : ClangTidyCheck(Name, Context) {} + void registerMatchers(ast_matchers::MatchFinder *Finder) override; + void check(const ast_matchers::MatchFinder::MatchResult &Result) override; + bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { + return LangOpts.CPlusPlus; + } +}; + +} // namespace clang::tidy::generalsgamecode::readability + +#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_GENERALSGAMECODE_READABILITY_USEISEMPTYCHECK_H diff --git a/scripts/clang-tidy-plugin/readability/UseThisInsteadOfSingletonCheck.cpp b/scripts/clang-tidy-plugin/readability/UseThisInsteadOfSingletonCheck.cpp new file mode 100644 index 0000000000..51eff283ef --- /dev/null +++ b/scripts/clang-tidy-plugin/readability/UseThisInsteadOfSingletonCheck.cpp @@ -0,0 +1,225 @@ +#include "UseThisInsteadOfSingletonCheck.h" +#include "clang/AST/ASTContext.h" +#include "clang/AST/Decl.h" +#include "clang/AST/DeclCXX.h" +#include "clang/AST/Expr.h" +#include "clang/AST/ExprCXX.h" +#include "clang/AST/Type.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/Basic/SourceLocation.h" +#include "clang/Lex/Lexer.h" + +using namespace clang; +using namespace clang::ast_matchers; + +namespace clang::tidy::generalsgamecode::readability { + + +static const CXXMethodDecl *getEnclosingMethod(ASTContext *Context, + const Stmt *S) { + const CXXMethodDecl *Method = nullptr; + + auto Parents = Context->getParents(*S); + while (!Parents.empty()) { + if (const auto *M = Parents[0].get()) { + if (!M->isStatic()) { + Method = M; + break; + } + } + Parents = Context->getParents(Parents[0]); + } + + return Method; +} + +static bool typesMatch(const QualType &SingletonType, + const CXXRecordDecl *EnclosingClass) { + if (!EnclosingClass) { + return false; + } + + const Type *TypePtr = SingletonType.getTypePtrOrNull(); + if (!TypePtr) { + return false; + } + + if (const PointerType *PtrType = TypePtr->getAs()) { + QualType PointeeType = PtrType->getPointeeType(); + if (const RecordType *RecordTy = PointeeType->getAs()) { + if (const CXXRecordDecl *RecordDecl = + dyn_cast(RecordTy->getDecl())) { + return RecordDecl->getCanonicalDecl() == + EnclosingClass->getCanonicalDecl(); + } + } + } + + return false; +} + +void UseThisInsteadOfSingletonCheck::registerMatchers(MatchFinder *Finder) { + auto MemberExprMatcher = memberExpr( + hasObjectExpression(ignoringParenImpCasts(declRefExpr(to(varDecl(anyOf(hasGlobalStorage(), hasExternalFormalLinkage())).bind("singletonVar"))))), + hasDeclaration(fieldDecl()), + unless(hasAncestor(cxxMemberCallExpr()))) + .bind("memberExpr"); + + auto MemberCallMatcher = cxxMemberCallExpr( + on(ignoringParenImpCasts(declRefExpr(to(varDecl(anyOf(hasGlobalStorage(), hasExternalFormalLinkage())).bind("singletonVarCall")))))) + .bind("memberCall"); + + Finder->addMatcher(MemberExprMatcher, this); + Finder->addMatcher(MemberCallMatcher, this); +} + +void UseThisInsteadOfSingletonCheck::check( + const MatchFinder::MatchResult &Result) { + const auto *MemExpr = Result.Nodes.getNodeAs("memberExpr"); + const auto *MemberCall = Result.Nodes.getNodeAs("memberCall"); + + if (!MemExpr && !MemberCall) { + return; + } + + const Stmt *TargetStmt = nullptr; + const VarDecl *FoundSingletonVar = nullptr; + bool IsCall = false; + + if (MemberCall) { + IsCall = true; + TargetStmt = MemberCall; + FoundSingletonVar = Result.Nodes.getNodeAs("singletonVarCall"); + if (!FoundSingletonVar) { + const Expr *ImplicitObject = MemberCall->getImplicitObjectArgument(); + if (ImplicitObject) { + ImplicitObject = ImplicitObject->IgnoreParenImpCasts(); + if (const DeclRefExpr *DRE = dyn_cast(ImplicitObject)) { + FoundSingletonVar = dyn_cast(DRE->getDecl()); + } + } + } + } else if (MemExpr) { + TargetStmt = MemExpr; + FoundSingletonVar = Result.Nodes.getNodeAs("singletonVar"); + } + + if (!TargetStmt || !FoundSingletonVar) { + return; + } + + StringRef SingletonName = FoundSingletonVar->getName(); + if (!SingletonName.starts_with("The") || SingletonName.size() <= 3 || + (SingletonName[3] < 'A' || SingletonName[3] > 'Z')) { + return; + } + + const ASTContext *Context = Result.Context; + + const CXXMethodDecl *EnclosingMethod = getEnclosingMethod( + const_cast(Context), TargetStmt); + if (!EnclosingMethod) { + return; + } + + const CXXRecordDecl *EnclosingClass = EnclosingMethod->getParent(); + if (!EnclosingClass) { + return; + } + + QualType SingletonType = FoundSingletonVar->getType(); + if (!typesMatch(SingletonType, EnclosingClass)) { + return; + } + + const ValueDecl *Member = nullptr; + StringRef MemberName; + SourceLocation StartLoc, EndLoc; + + if (IsCall && MemberCall) { + const CXXMethodDecl *Method = MemberCall->getMethodDecl(); + if (!Method) { + return; + } + if (Method->isStatic()) { + return; + } + if (EnclosingMethod->isConst() && !Method->isConst()) { + return; + } + Member = Method; + MemberName = Method->getName(); + StartLoc = MemberCall->getBeginLoc(); + EndLoc = MemberCall->getEndLoc(); + } else if (MemExpr) { + Member = MemExpr->getMemberDecl(); + if (!Member) { + return; + } + MemberName = Member->getName(); + StartLoc = MemExpr->getBeginLoc(); + EndLoc = MemExpr->getEndLoc(); + } else { + return; + } + + SourceManager &SM = *Result.SourceManager; + + std::string Replacement = std::string(MemberName); + + if (IsCall && MemberCall) { + SourceLocation RParenLoc = MemberCall->getRParenLoc(); + const Expr *Callee = MemberCall->getCallee(); + + if (RParenLoc.isValid() && Callee) { + SourceLocation CalleeEnd = Lexer::getLocForEndOfToken( + Callee->getEndLoc(), 0, SM, Result.Context->getLangOpts()); + + if (CalleeEnd.isValid() && CalleeEnd < RParenLoc) { + SourceLocation ArgsStart = CalleeEnd; + SourceLocation ArgsEnd = Lexer::getLocForEndOfToken( + RParenLoc, 0, SM, Result.Context->getLangOpts()); + + if (ArgsStart.isValid() && ArgsEnd.isValid() && ArgsStart < ArgsEnd) { + StringRef ArgsText = Lexer::getSourceText( + CharSourceRange::getCharRange(ArgsStart, ArgsEnd), SM, + Result.Context->getLangOpts()); + ArgsText = ArgsText.ltrim(); + if (!ArgsText.empty()) { + Replacement += ArgsText.str(); + } else { + Replacement += "()"; + } + } else { + Replacement += "()"; + } + } else { + SourceLocation CallEnd = Lexer::getLocForEndOfToken( + MemberCall->getEndLoc(), 0, SM, Result.Context->getLangOpts()); + if (CalleeEnd.isValid() && CallEnd.isValid() && CalleeEnd < CallEnd) { + StringRef ArgsText = Lexer::getSourceText( + CharSourceRange::getCharRange(CalleeEnd, CallEnd), SM, + Result.Context->getLangOpts()); + ArgsText = ArgsText.ltrim(); + if (!ArgsText.empty()) { + Replacement += ArgsText.str(); + } else { + Replacement += "()"; + } + } else { + Replacement += "()"; + } + } + } else { + Replacement += "()"; + } + } + + diag(StartLoc, "use '%0' instead of '%1->%2' when inside a member function") + << Replacement << FoundSingletonVar->getName() << MemberName + << FixItHint::CreateReplacement( + CharSourceRange::getTokenRange(StartLoc, EndLoc), Replacement); +} + +} // namespace clang::tidy::generalsgamecode::readability + diff --git a/scripts/clang-tidy-plugin/readability/UseThisInsteadOfSingletonCheck.h b/scripts/clang-tidy-plugin/readability/UseThisInsteadOfSingletonCheck.h new file mode 100644 index 0000000000..1005d5d84b --- /dev/null +++ b/scripts/clang-tidy-plugin/readability/UseThisInsteadOfSingletonCheck.h @@ -0,0 +1,22 @@ +#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_GENERALSGAMECODE_READABILITY_USETHISINSTEADOFSINGLETONCHECK_H +#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_GENERALSGAMECODE_READABILITY_USETHISINSTEADOFSINGLETONCHECK_H + +#include "clang-tidy/ClangTidyCheck.h" + +namespace clang::tidy::generalsgamecode::readability { + +class UseThisInsteadOfSingletonCheck : public ClangTidyCheck { +public: + UseThisInsteadOfSingletonCheck(StringRef Name, ClangTidyContext *Context) + : ClangTidyCheck(Name, Context) {} + void registerMatchers(ast_matchers::MatchFinder *Finder) override; + void check(const ast_matchers::MatchFinder::MatchResult &Result) override; + bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { + return LangOpts.CPlusPlus; + } +}; + +} // namespace clang::tidy::generalsgamecode::readability + +#endif + diff --git a/scripts/run-clang-tidy.py b/scripts/run-clang-tidy.py index 49f06b4563..71b41ab70c 100755 --- a/scripts/run-clang-tidy.py +++ b/scripts/run-clang-tidy.py @@ -27,7 +27,7 @@ def find_clang_tidy() -> str: - """Find clang-tidy executable in PATH.""" + """Find clang-tidy executable in PATH or common locations.""" try: result = subprocess.run( ['clang-tidy', '--version'], @@ -40,8 +40,38 @@ def find_clang_tidy() -> str: except (FileNotFoundError, subprocess.TimeoutExpired): pass + import platform + if platform.system() == 'Darwin': + import glob + import re + possible_paths = glob.glob('/opt/homebrew/Cellar/llvm*/*/bin/clang-tidy') + possible_paths.extend(glob.glob('/usr/local/Cellar/llvm*/*/bin/clang-tidy')) + + def extract_version(path): + match = re.search(r'llvm@?(\d+)', path) + if match: + return int(match.group(1)) + match = re.search(r'/(\d+)\.(\d+)\.(\d+)', path) + if match: + return int(match.group(1)) * 10000 + int(match.group(2)) * 100 + int(match.group(3)) + return 0 + + for path in sorted(possible_paths, key=extract_version, reverse=True): + try: + result = subprocess.run( + [path, '--version'], + capture_output=True, + text=True, + timeout=5 + ) + if result.returncode == 0: + return path + except (FileNotFoundError, subprocess.TimeoutExpired): + continue + raise RuntimeError( "clang-tidy not found in PATH. Please install clang-tidy:\n" + " macOS: brew install llvm\n" " Windows: Install LLVM from https://llvm.org/builds/" ) @@ -56,6 +86,54 @@ def find_project_root() -> Path: raise RuntimeError("Could not find project root (no CMakeLists.txt found)") +def get_clang_tidy_version(clang_tidy_exe: str) -> Optional[str]: + """Get the version string from clang-tidy.""" + try: + result = subprocess.run( + [clang_tidy_exe, '--version'], + capture_output=True, + text=True, + timeout=5 + ) + if result.returncode == 0: + return result.stdout.strip() + except (FileNotFoundError, subprocess.TimeoutExpired): + pass + return None + + +def extract_llvm_version(version_string: str) -> Optional[str]: + """Extract LLVM version number from clang-tidy version string.""" + import re + patterns = [ + r'LLVM version (\d+\.\d+\.\d+)', + r'llvm version (\d+\.\d+\.\d+)', + r'Homebrew LLVM version (\d+\.\d+\.\d+)', + r'version (\d+\.\d+\.\d+)', + ] + for pattern in patterns: + match = re.search(pattern, version_string, re.IGNORECASE) + if match: + return match.group(1) + return None + + +def find_clang_tidy_plugin(project_root: Path) -> Optional[str]: + """Find the GeneralsGameCode clang-tidy plugin.""" + possible_paths = [ + project_root / "scripts" / "clang-tidy-plugin" / "build" / "lib" / "libGeneralsGameCodeClangTidyPlugin.so", + project_root / "scripts" / "clang-tidy-plugin" / "build" / "lib" / "libGeneralsGameCodeClangTidyPlugin.dylib", + project_root / "scripts" / "clang-tidy-plugin" / "build" / "lib" / "libGeneralsGameCodeClangTidyPlugin.dll", + project_root / "scripts" / "clang-tidy-plugin" / "build" / "bin" / "libGeneralsGameCodeClangTidyPlugin.dll", + ] + + for path in possible_paths: + if path.exists(): + return str(path) + + return None + + def find_compile_commands(build_dir: Optional[Path] = None) -> Path: """Find compile_commands.json from the clang-tidy analysis build.""" project_root = find_project_root() @@ -174,7 +252,7 @@ def _run_batch(args: Tuple) -> Tuple[int, Dict[str, List[str]]]: if is_warning_or_error or verbose: issues_by_file[file_key].append(line) - + return result.returncode, dict(issues_by_file) except FileNotFoundError: error_msg = "Error: clang-tidy not found. Please install LLVM/Clang." @@ -188,7 +266,8 @@ def run_clang_tidy(source_files: List[str], extra_args: List[str], fix: bool = False, jobs: int = 1, - verbose: bool = False) -> int: + verbose: bool = False, + load_plugin: bool = True) -> int: """Run clang-tidy on source files in batches, optionally in parallel.""" if not source_files: print("No source files to analyze.") @@ -196,17 +275,41 @@ def run_clang_tidy(source_files: List[str], clang_tidy_exe = find_clang_tidy() + project_root = find_project_root() + plugin_path = None + if load_plugin: + plugin_path = find_clang_tidy_plugin(project_root) + if plugin_path: + clang_tidy_version_str = get_clang_tidy_version(clang_tidy_exe) + if clang_tidy_version_str: + detected_version = extract_llvm_version(clang_tidy_version_str) + if detected_version: + if verbose: + print(f"Found clang-tidy plugin: {plugin_path}") + print(f"Using clang-tidy LLVM version: {detected_version}") + print("Note: Ensure the plugin was built with the same LLVM version (check CMake build output).\n") + else: + print(f"Note: Verify plugin was built with LLVM {detected_version} (check CMake build output)") + else: + if verbose: + print(f"Found clang-tidy plugin: {plugin_path}\n") + else: + if verbose: + print(f"Found clang-tidy plugin: {plugin_path}\n") + BATCH_SIZE = 50 total_files = len(source_files) batches = [source_files[i:i + BATCH_SIZE] for i in range(0, total_files, BATCH_SIZE)] - project_root = find_project_root() compile_commands_dir = compile_commands_path.parent all_issues = defaultdict(list) files_with_issues = set() total_issues = 0 + if plugin_path and '-load' not in ' '.join(extra_args): + extra_args = ['-load', plugin_path] + extra_args + if jobs > 1: if verbose: print(f"Running clang-tidy on {total_files} file(s) in {len(batches)} batch(es) with {jobs} workers...\n") @@ -232,7 +335,7 @@ def run_clang_tidy(source_files: List[str], all_issues[file_path].extend(file_issues) files_with_issues.add(file_path) total_issues += len(file_issues) - + if not verbose: print(" done.") except KeyboardInterrupt: @@ -249,7 +352,7 @@ def run_clang_tidy(source_files: List[str], try: if verbose: print(f"Batch {batch_num}/{len(batches)}: {len(batch)} file(s)...") - + returncode, issues = _run_batch((batch_num, batch, compile_commands_dir, fix, extra_args, project_root, clang_tidy_exe, verbose)) if returncode != 0: overall_returncode = returncode @@ -259,7 +362,7 @@ def run_clang_tidy(source_files: List[str], all_issues[file_path].extend(file_issues) files_with_issues.add(file_path) total_issues += len(file_issues) - + if not verbose and batch_num < len(batches): print('.', end='', flush=True) except KeyboardInterrupt: @@ -277,7 +380,7 @@ def run_clang_tidy(source_files: List[str], print(f"\n{file_path}:") for issue in all_issues[file_path]: print(f" {issue}") - + return overall_returncode @@ -355,6 +458,12 @@ def main(): help='Show detailed output for each file (default: only show warnings/errors)' ) + parser.add_argument( + '--no-plugin', + action='store_true', + help='Do not automatically load the GeneralsGameCode clang-tidy plugin' + ) + parser.add_argument( 'clang_tidy_args', nargs='*', @@ -390,7 +499,8 @@ def main(): clang_tidy_args, args.fix, args.jobs, - args.verbose + args.verbose, + load_plugin=not args.no_plugin ) compile_commands = load_compile_commands(compile_commands_path) @@ -423,7 +533,8 @@ def main(): clang_tidy_args, args.fix, args.jobs, - args.verbose + args.verbose, + load_plugin=not args.no_plugin ) except Exception as e: From 1f2c1a38b3d1cfdcffe2f523c770685baad2181c Mon Sep 17 00:00:00 2001 From: Bobby Battista Date: Sun, 21 Dec 2025 04:44:36 -0500 Subject: [PATCH 46/70] bugfix(input): Replace frame-based timings with real-time timings in input system (#1835) --- .../GameEngine/Include/GameClient/Keyboard.h | 10 +++-- .../Include/GameClient/LookAtXlat.h | 4 +- .../GameEngine/Include/GameClient/Mouse.h | 9 +---- .../Source/GameClient/Input/Keyboard.cpp | 38 +++++++++---------- .../Source/GameClient/Input/Mouse.cpp | 29 ++------------ .../GameClient/MessageStream/LookAtXlat.cpp | 36 ++++++++++-------- .../GameClient/Win32DIKeyboard.cpp | 14 ++++--- .../Win32Device/GameClient/Win32DIMouse.cpp | 11 ++---- .../Win32Device/GameClient/Win32Mouse.cpp | 23 +---------- .../GameEngine/Include/GameClient/Keyboard.h | 10 +++-- .../Include/GameClient/LookAtXlat.h | 4 +- .../GameEngine/Include/GameClient/Mouse.h | 9 +---- .../Source/GameClient/Input/Keyboard.cpp | 36 ++++++++---------- .../Source/GameClient/Input/Mouse.cpp | 29 ++------------ .../GameClient/MessageStream/LookAtXlat.cpp | 36 ++++++++++-------- .../GameClient/Win32DIKeyboard.cpp | 14 ++++--- .../Win32Device/GameClient/Win32DIMouse.cpp | 11 ++---- .../Win32Device/GameClient/Win32Mouse.cpp | 23 +---------- 18 files changed, 128 insertions(+), 218 deletions(-) diff --git a/Generals/Code/GameEngine/Include/GameClient/Keyboard.h b/Generals/Code/GameEngine/Include/GameClient/Keyboard.h index e4ee92bf49..8e54ae6ac1 100644 --- a/Generals/Code/GameEngine/Include/GameClient/Keyboard.h +++ b/Generals/Code/GameEngine/Include/GameClient/Keyboard.h @@ -76,7 +76,7 @@ struct KeyboardIO UnsignedByte key; // KeyDefType, key data UnsignedByte status; // StatusType, above UnsignedShort state; // KEY_STATE_* in KeyDefs.h - UnsignedInt sequence; // sequence info from DirectX used for order + UnsignedInt keyDownTimeMsec; // real-time in milliseconds when key went down }; @@ -86,7 +86,11 @@ struct KeyboardIO class Keyboard : public SubsystemInterface { - enum { KEY_REPEAT_DELAY = 10 }; + enum + { + KEY_REPEAT_DELAY_MSEC = 333, // 10 frames at 30 FPS + KEY_REPEAT_INTERVAL_MSEC = 67 // ~2 frames at 30 FPS + }; public: @@ -133,7 +137,6 @@ class Keyboard : public SubsystemInterface Bool checkKeyRepeat( void ); ///< check for repeating keys UnsignedByte getKeyStatusData( KeyDefType key ); ///< get key status Bool getKeyStateBit( KeyDefType key, Int bit ); ///< get key state bit - UnsignedInt getKeySequenceData( KeyDefType key ); ///< get key sequence void setKeyStateData( KeyDefType key, UnsignedByte data ); ///< get key state UnsignedShort m_modifiers; @@ -161,7 +164,6 @@ class Keyboard : public SubsystemInterface WideChar shifted2; } m_keyNames[ KEY_COUNT ]; - UnsignedInt m_inputFrame; ///< frame input was gathered on }; diff --git a/Generals/Code/GameEngine/Include/GameClient/LookAtXlat.h b/Generals/Code/GameEngine/Include/GameClient/LookAtXlat.h index 91522d87b1..619f9bea85 100644 --- a/Generals/Code/GameEngine/Include/GameClient/LookAtXlat.h +++ b/Generals/Code/GameEngine/Include/GameClient/LookAtXlat.h @@ -76,12 +76,12 @@ class LookAtTranslator : public GameMessageTranslator Bool m_isRotating; // set to true if we are in the act of MMB rotating Bool m_isPitching; // set to true if we are in the act of ALT pitch rotation Bool m_isChangingFOV; // set to true if we are in the act of changing the field of view - UnsignedInt m_timestamp; // set when button goes down + UnsignedInt m_middleButtonDownTimeMsec; // real-time in milliseconds when middle button goes down DrawableID m_lastPlaneID; ViewLocation m_viewLocation[ MAX_VIEW_LOCS ]; ScrollType m_scrollType; ScreenEdgeScrollMode m_screenEdgeScrollMode; - UnsignedInt m_lastMouseMoveFrame; + UnsignedInt m_lastMouseMoveTimeMsec; // real-time in milliseconds when mouse last moved void setScrolling( ScrollType scrollType ); void stopScrolling( void ); diff --git a/Generals/Code/GameEngine/Include/GameClient/Mouse.h b/Generals/Code/GameEngine/Include/GameClient/Mouse.h index 92fd80497c..07583b79f7 100644 --- a/Generals/Code/GameEngine/Include/GameClient/Mouse.h +++ b/Generals/Code/GameEngine/Include/GameClient/Mouse.h @@ -62,6 +62,7 @@ enum GameMode CPP_11(: Int); enum MouseButtonState CPP_11(: Int) { + MBS_None = -1, MBS_Up = 0, MBS_Down, MBS_DoubleClick, @@ -105,17 +106,14 @@ struct MouseIO user while - is down/toward user */ ICoord2D deltaPos; ///< overall change in mouse pointer this frame - MouseButtonState leftState; // button state: Up, Down, DoubleClick (Which is also down) + MouseButtonState leftState; // button state: None (no event), Up, Down, DoubleClick Int leftEvent; // Most important event this frame - Int leftFrame; // last frame button state changed MouseButtonState rightState; Int rightEvent; - Int rightFrame; MouseButtonState middleState; Int middleEvent; - Int middleFrame; }; class CursorInfo @@ -393,9 +391,6 @@ class Mouse : public SubsystemInterface Int m_minY; ///< mouse is locked to this region Int m_maxY; ///< mouse is locked to this region - UnsignedInt m_inputFrame; ///< frame input was gathered on - UnsignedInt m_deadInputFrame; ///< Frame which last input occured - Bool m_inputMovesAbsolute; /**< if TRUE, when processing mouse position chanages the movement will be done treating the coords as ABSOLUTE positions and NOT diff --git a/Generals/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp b/Generals/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp index 5eb6a69cce..3e69d321a3 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp @@ -140,7 +140,12 @@ void Keyboard::updateKeys( void ) m_keyStatus[ m_keys[ index ].key ].state = m_keys[ index ].state; m_keyStatus[ m_keys[ index ].key ].status = m_keys[ index ].status; - m_keyStatus[ m_keys[ index ].key ].sequence = m_inputFrame; + + // Update key down time for new key presses + if( BitIsSet( m_keys[ index ].state, KEY_STATE_DOWN ) ) + { + m_keyStatus[ m_keys[ index ].key ].keyDownTimeMsec = m_keys[ index ].keyDownTimeMsec; + } // prevent ALT-TAB from causing a TAB event if( m_keys[ index ].key == KEY_TAB ) @@ -195,7 +200,7 @@ void Keyboard::updateKeys( void ) } //------------------------------------------------------------------------------------------------- -/** check key repeat sequences, TRUE is returned if repeat is occurring */ +/** check key repeat timing, TRUE is returned if repeat is occurring */ //------------------------------------------------------------------------------------------------- Bool Keyboard::checkKeyRepeat( void ) { @@ -220,7 +225,13 @@ Bool Keyboard::checkKeyRepeat( void ) if( BitIsSet( m_keyStatus[ key ].state, KEY_STATE_DOWN ) ) { - if( (m_inputFrame - m_keyStatus[ key ].sequence) > Keyboard::KEY_REPEAT_DELAY ) + const UnsignedInt now = timeGetTime(); + const UnsignedInt keyDownTime = m_keyStatus[ key ].keyDownTimeMsec; + + // Unsigned subtraction handles wraparound correctly + const UnsignedInt elapsedMsec = now - keyDownTime; + + if( elapsedMsec > Keyboard::KEY_REPEAT_DELAY_MSEC ) { // Add key to this frame m_keys[ index ].key = (UnsignedByte)key; @@ -232,10 +243,10 @@ Bool Keyboard::checkKeyRepeat( void ) // Set all keys as new to prevent multiple keys repeating for( index = 0; index< NUM_KEYS; index++ ) - m_keyStatus[ index ].sequence = m_inputFrame; + m_keyStatus[ index ].keyDownTimeMsec = now; - // Set repeated key so it will repeat again in two frames - m_keyStatus[ key ].sequence = m_inputFrame - (Keyboard::KEY_REPEAT_DELAY + 2); + // Set repeated key so it will repeat again after the interval + m_keyStatus[ key ].keyDownTimeMsec = now - (Keyboard::KEY_REPEAT_DELAY_MSEC + Keyboard::KEY_REPEAT_INTERVAL_MSEC); retVal = TRUE; break; // exit for key @@ -694,7 +705,6 @@ Keyboard::Keyboard( void ) m_shift2Key = KEY_NONE; memset( m_keyNames, 0, sizeof( m_keyNames ) ); - m_inputFrame = 0; } @@ -714,9 +724,6 @@ void Keyboard::init( void ) // initialize the key names initKeyNames(); - // first input frame - m_inputFrame = 0; - } //------------------------------------------------------------------------------------------------- @@ -733,9 +740,6 @@ void Keyboard::reset( void ) void Keyboard::update( void ) { - // increment input frame - m_inputFrame++; - // update the key data updateKeys(); @@ -819,14 +823,6 @@ Bool Keyboard::getKeyStateBit( KeyDefType key, Int bit ) return (m_keyStatus[ key ].state & bit) ? 1 : 0; } -//------------------------------------------------------------------------------------------------- -/** return the sequence data for the given key */ -//------------------------------------------------------------------------------------------------- -UnsignedInt Keyboard::getKeySequenceData( KeyDefType key ) -{ - return m_keyStatus[ key ].sequence; -} - //------------------------------------------------------------------------------------------------- /** set the key status data */ //------------------------------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp b/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp index 903a52b8a2..8f02f88d27 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp @@ -183,9 +183,6 @@ void Mouse::updateMouseData( ) else m_eventsThisFrame = 0; - if( index != 0 ) - m_deadInputFrame = m_inputFrame; - } //------------------------------------------------------------------------------------------------- @@ -221,7 +218,7 @@ void Mouse::processMouseEvent( Int index ) m_currMouse.wheelPos += m_mouseEvents[ index ].wheelPos; // Check Left Mouse State - if( m_mouseEvents[ index ].leftFrame ) + if( m_mouseEvents[ index ].leftState != MBS_None ) { if( m_currMouse.leftState != m_mouseEvents[ index ].leftState ) { @@ -231,21 +228,18 @@ void Mouse::processMouseEvent( Int index ) // Mouse Down m_currMouse.leftEvent = GWM_LEFT_DOWN; m_currMouse.leftState = MBS_Down; - m_currMouse.leftFrame = m_inputFrame; } else if ( m_mouseEvents[ index ].leftState == MBS_DoubleClick ) { // Mouse Double Click m_currMouse.leftEvent = GWM_LEFT_DOUBLE_CLICK; m_currMouse.leftState = MBS_DoubleClick; - m_currMouse.leftFrame = m_inputFrame; } else { // Mouse Up m_currMouse.leftEvent = GWM_LEFT_UP; m_currMouse.leftState = MBS_Up; - m_currMouse.leftFrame = m_inputFrame; } } } @@ -257,7 +251,7 @@ void Mouse::processMouseEvent( Int index ) } // Check Right Mouse State - if( m_mouseEvents[ index ].rightFrame ) + if( m_mouseEvents[ index ].rightState != MBS_None ) { if( m_currMouse.rightState != m_mouseEvents[ index ].rightState ) { @@ -267,21 +261,18 @@ void Mouse::processMouseEvent( Int index ) // Mouse Down m_currMouse.rightEvent = GWM_RIGHT_DOWN; m_currMouse.rightState = MBS_Down; - m_currMouse.rightFrame = m_inputFrame; } else if( m_mouseEvents[ index ].rightState == MBS_DoubleClick ) { // Mouse Double Click m_currMouse.rightEvent = GWM_RIGHT_DOUBLE_CLICK; m_currMouse.rightState = MBS_DoubleClick; - m_currMouse.rightFrame = m_inputFrame; } else { // Mouse Up m_currMouse.rightEvent = GWM_RIGHT_UP; m_currMouse.rightState = MBS_Up; - m_currMouse.rightFrame = m_inputFrame; } } } @@ -293,7 +284,7 @@ void Mouse::processMouseEvent( Int index ) } // Check Middle Mouse State - if( m_mouseEvents[ index ].middleFrame ) + if( m_mouseEvents[ index ].middleState != MBS_None ) { if( m_currMouse.middleState != m_mouseEvents[index].middleState ) { @@ -302,20 +293,17 @@ void Mouse::processMouseEvent( Int index ) { m_currMouse.middleEvent = GWM_MIDDLE_DOWN; m_currMouse.middleState = MBS_Down; - m_currMouse.middleFrame = m_inputFrame; } else if( m_mouseEvents[index].middleState == MBS_DoubleClick ) { m_currMouse.middleEvent = GWM_MIDDLE_DOUBLE_CLICK; m_currMouse.middleState = MBS_DoubleClick; - m_currMouse.middleFrame = m_inputFrame; } else { // Mouse Up m_currMouse.middleEvent = GWM_MIDDLE_UP; m_currMouse.middleState = MBS_Up; - m_currMouse.middleFrame = m_inputFrame; } } } @@ -328,7 +316,7 @@ void Mouse::processMouseEvent( Int index ) m_currMouse.deltaPos.x = m_currMouse.pos.x - m_prevMouse.pos.x; m_currMouse.deltaPos.y = m_currMouse.pos.y - m_prevMouse.pos.y; -// DEBUG_LOG(("Mouse dx %d, dy %d, index %d, frame %d", m_currMouse.deltaPos.x, m_currMouse.deltaPos.y, index, m_inputFrame)); +// DEBUG_LOG(("Mouse dx %d, dy %d, index %d", m_currMouse.deltaPos.x, m_currMouse.deltaPos.y, index)); // // check if mouse is still and flag tooltip // if( ((dx*dx) + (dy*dy)) < CURSOR_MOVE_TOL_SQ ) // { @@ -474,9 +462,6 @@ Mouse::Mouse( void ) m_maxY = 0; m_eventsThisFrame = 0; - m_inputFrame = 0; - m_deadInputFrame =0; - m_inputMovesAbsolute = FALSE; m_currentCursor = ARROW; @@ -590,9 +575,6 @@ void Mouse::init( void ) m_minY = 0; m_maxY = 599; - m_inputFrame = 0; - m_deadInputFrame =0; - m_inputMovesAbsolute = FALSE; m_eventsThisFrame = 0; @@ -676,9 +658,6 @@ void Mouse::reset( void ) void Mouse::update( void ) { - // increment input frame - m_inputFrame++; - // update the mouse data updateMouseData( ); diff --git a/Generals/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp b/Generals/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp index 1f0d4e7cc7..761992f743 100644 --- a/Generals/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp @@ -137,9 +137,9 @@ LookAtTranslator::LookAtTranslator() : m_isRotating(false), m_isPitching(false), m_isChangingFOV(false), - m_timestamp(0), + m_middleButtonDownTimeMsec(0), m_lastPlaneID(INVALID_DRAWABLE_ID), - m_lastMouseMoveFrame(0), + m_lastMouseMoveTimeMsec(0), m_scrollType(SCROLL_NONE) { m_anchor.x = m_anchor.y = 0; @@ -171,13 +171,12 @@ const ICoord2D* LookAtTranslator::getRMBScrollAnchor(void) Bool LookAtTranslator::hasMouseMovedRecently( void ) { - if (m_lastMouseMoveFrame > TheGameLogic->getFrame()) - m_lastMouseMoveFrame = 0; // reset for new game + const UnsignedInt now = timeGetTime(); + const UnsignedInt lastMove = m_lastMouseMoveTimeMsec; - if (m_lastMouseMoveFrame + LOGICFRAMES_PER_SECOND < TheGameLogic->getFrame()) - return false; + const UnsignedInt elapsedMsec = now - lastMove; - return true; + return elapsedMsec <= MSEC_PER_SECOND; } void LookAtTranslator::setCurrentPos( const ICoord2D& pos ) @@ -256,7 +255,7 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage //----------------------------------------------------------------------------- case GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_DOWN: { - m_lastMouseMoveFrame = TheGameLogic->getFrame(); + m_lastMouseMoveTimeMsec = timeGetTime(); m_anchor = msg->getArgument( 0 )->pixel; m_currentPos = msg->getArgument( 0 )->pixel; @@ -272,7 +271,7 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage //----------------------------------------------------------------------------- case GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_UP: { - m_lastMouseMoveFrame = TheGameLogic->getFrame(); + m_lastMouseMoveTimeMsec = timeGetTime(); if (m_scrollType == SCROLL_RMB) { @@ -284,23 +283,25 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage //----------------------------------------------------------------------------- case GameMessage::MSG_RAW_MOUSE_MIDDLE_BUTTON_DOWN: { - m_lastMouseMoveFrame = TheGameLogic->getFrame(); + const UnsignedInt now = timeGetTime(); + m_lastMouseMoveTimeMsec = now; + m_middleButtonDownTimeMsec = now; m_isRotating = true; m_anchor = msg->getArgument( 0 )->pixel; m_anchorAngle = TheTacticalView->getAngle(); m_originalAnchor = msg->getArgument( 0 )->pixel; m_currentPos = msg->getArgument( 0 )->pixel; - m_timestamp = TheGameClient->getFrame(); break; } //----------------------------------------------------------------------------- case GameMessage::MSG_RAW_MOUSE_MIDDLE_BUTTON_UP: { - m_lastMouseMoveFrame = TheGameLogic->getFrame(); + const UnsignedInt now = timeGetTime(); + m_lastMouseMoveTimeMsec = now; - const UnsignedInt CLICK_DURATION = 5; + const UnsignedInt CLICK_DURATION_MSEC = 167; const UnsignedInt PIXEL_OFFSET = 5; m_isRotating = false; @@ -308,8 +309,11 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage if (dx<0) dx = -dx; Int dy = m_currentPos.y-m_originalAnchor.y; Bool didMove = dx>PIXEL_OFFSET || dy>PIXEL_OFFSET; + + const UnsignedInt elapsedMsec = now - m_middleButtonDownTimeMsec; + // if middle button is "clicked", reset to "home" orientation - if (!didMove && TheGameClient->getFrame() - m_timestamp < CLICK_DURATION) + if (!didMove && elapsedMsec < CLICK_DURATION_MSEC) { TheTacticalView->setAngleAndPitchToDefault(); TheTacticalView->setZoomToDefault(); @@ -322,7 +326,7 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage case GameMessage::MSG_RAW_MOUSE_POSITION: { if (m_currentPos.x != msg->getArgument( 0 )->pixel.x || m_currentPos.y != msg->getArgument( 0 )->pixel.y) - m_lastMouseMoveFrame = TheGameLogic->getFrame(); + m_lastMouseMoveTimeMsec = timeGetTime(); m_currentPos = msg->getArgument( 0 )->pixel; @@ -402,7 +406,7 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage //----------------------------------------------------------------------------- case GameMessage::MSG_RAW_MOUSE_WHEEL: { - m_lastMouseMoveFrame = TheGameLogic->getFrame(); + m_lastMouseMoveTimeMsec = timeGetTime(); Int spin = msg->getArgument( 1 )->integer; diff --git a/Generals/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIKeyboard.cpp b/Generals/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIKeyboard.cpp index 6bc06e14ea..f0b7d39b15 100644 --- a/Generals/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIKeyboard.cpp +++ b/Generals/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIKeyboard.cpp @@ -251,7 +251,6 @@ void DirectInputKeyboard::getKey( KeyboardIO *key ) HRESULT hr; assert( key ); - key->sequence = 0; key->key = KEY_NONE; if( m_pKeyboardDevice ) @@ -315,15 +314,20 @@ void DirectInputKeyboard::getKey( KeyboardIO *key ) // set the key key->key = (UnsignedByte)(kbdat.dwOfs & 0xFF); - // sequence - key->sequence = kbdat.dwSequence; - // // state of key, note we are setting the key state here with an assignment // and not a bit set of the up/down state, this is the "start" // of building this "key" // - key->state = (( kbdat.dwData & 0x0080 ) ? KEY_STATE_DOWN : KEY_STATE_UP); + if( kbdat.dwData & 0x0080 ) + { + key->state = KEY_STATE_DOWN; + key->keyDownTimeMsec = kbdat.dwTimeStamp; + } + else + { + key->state = KEY_STATE_UP; + } // set status as unused (unprocessed) key->status = KeyboardIO::STATUS_UNUSED; diff --git a/Generals/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIMouse.cpp b/Generals/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIMouse.cpp index 56eadc80fb..0df595f04c 100644 --- a/Generals/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIMouse.cpp +++ b/Generals/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIMouse.cpp @@ -202,7 +202,7 @@ UnsignedByte DirectInputMouse::getMouseEvent( MouseIO *result, Bool flush ) /* set these to defaults */ result->leftState = result->middleState = result->rightState = FALSE; - result->leftFrame = result->middleFrame = result->rightFrame = 0; + result->leftState = result->middleState = result->rightState = MBS_None; result->pos.x = result->pos.y = result->wheelPos = 0; if( m_pMouseDevice ) @@ -282,18 +282,15 @@ void DirectInputMouse::mapDirectInputMouse( MouseIO *mouse, switch( mdat->dwOfs ) { case DIMOFS_BUTTON0: - mouse->leftState = (( mdat->dwData & 0x0080 ) ? TRUE : FALSE); - mouse->leftFrame = mdat->dwSequence; + mouse->leftState = (( mdat->dwData & 0x0080 ) ? MBS_Down : MBS_Up); break; case DIMOFS_BUTTON1: - mouse->rightState = (( mdat->dwData & 0x0080 ) ? TRUE : FALSE); - mouse->rightFrame = mdat->dwSequence; + mouse->rightState = (( mdat->dwData & 0x0080 ) ? MBS_Down : MBS_Up); break; case DIMOFS_BUTTON2: - mouse->middleState = (( mdat->dwData & 0x0080 ) ? TRUE : FALSE); - mouse->middleFrame = mdat->dwSequence; + mouse->middleState = (( mdat->dwData & 0x0080 ) ? MBS_Down : MBS_Up); break; case DIMOFS_BUTTON3: diff --git a/Generals/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32Mouse.cpp b/Generals/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32Mouse.cpp index 5f84cca905..533c0d908a 100644 --- a/Generals/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32Mouse.cpp +++ b/Generals/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32Mouse.cpp @@ -85,21 +85,9 @@ void Win32Mouse::translateEvent( UnsignedInt eventIndex, MouseIO *result ) UINT msg = m_eventBuffer[ eventIndex ].msg; WPARAM wParam = m_eventBuffer[ eventIndex ].wParam; LPARAM lParam = m_eventBuffer[ eventIndex ].lParam; - UnsignedInt frame; - - // - // get the current input frame from the client, if we don't have - // a client (like in the GUI editor) we just use frame 1 so it - // registers with the system - // - if( TheGameClient ) - frame = TheGameClient->getFrame(); - else - frame = 1; // set these to defaults - result->leftState = result->middleState = result->rightState = MBS_Up; - result->leftFrame = result->middleFrame = result->rightFrame = 0; + result->leftState = result->middleState = result->rightState = MBS_None; result->pos.x = result->pos.y = result->wheelPos = 0; // Time is the same for all events @@ -113,7 +101,6 @@ void Win32Mouse::translateEvent( UnsignedInt eventIndex, MouseIO *result ) { result->leftState = MBS_Down; - result->leftFrame = frame; result->pos.x = LOWORD( lParam ); result->pos.y = HIWORD( lParam ); break; @@ -125,7 +112,6 @@ void Win32Mouse::translateEvent( UnsignedInt eventIndex, MouseIO *result ) { result->leftState = MBS_Up; - result->leftFrame = frame; result->pos.x = LOWORD( lParam ); result->pos.y = HIWORD( lParam ); break; @@ -137,7 +123,6 @@ void Win32Mouse::translateEvent( UnsignedInt eventIndex, MouseIO *result ) { result->leftState = MBS_DoubleClick; - result->leftFrame = frame; result->pos.x = LOWORD( lParam ); result->pos.y = HIWORD( lParam ); break; @@ -149,7 +134,6 @@ void Win32Mouse::translateEvent( UnsignedInt eventIndex, MouseIO *result ) { result->middleState = MBS_Down; - result->middleFrame = frame; result->pos.x = LOWORD( lParam ); result->pos.y = HIWORD( lParam ); break; @@ -161,7 +145,6 @@ void Win32Mouse::translateEvent( UnsignedInt eventIndex, MouseIO *result ) { result->middleState = MBS_Up; - result->middleFrame = frame; result->pos.x = LOWORD( lParam ); result->pos.y = HIWORD( lParam ); break; @@ -173,7 +156,6 @@ void Win32Mouse::translateEvent( UnsignedInt eventIndex, MouseIO *result ) { result->middleState = MBS_DoubleClick; - result->middleFrame = frame; result->pos.x = LOWORD( lParam ); result->pos.y = HIWORD( lParam ); break; @@ -185,7 +167,6 @@ void Win32Mouse::translateEvent( UnsignedInt eventIndex, MouseIO *result ) { result->rightState = MBS_Down; - result->rightFrame = frame; result->pos.x = LOWORD( lParam ); result->pos.y = HIWORD( lParam ); break; @@ -197,7 +178,6 @@ void Win32Mouse::translateEvent( UnsignedInt eventIndex, MouseIO *result ) { result->rightState = MBS_Up; - result->rightFrame = frame; result->pos.x = LOWORD( lParam ); result->pos.y = HIWORD( lParam ); break; @@ -209,7 +189,6 @@ void Win32Mouse::translateEvent( UnsignedInt eventIndex, MouseIO *result ) { result->rightState = MBS_DoubleClick; - result->rightFrame = frame; result->pos.x = LOWORD( lParam ); result->pos.y = HIWORD( lParam ); break; diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Keyboard.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Keyboard.h index fa54abe226..79a11a6d82 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/Keyboard.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Keyboard.h @@ -76,7 +76,7 @@ struct KeyboardIO UnsignedByte key; // KeyDefType, key data UnsignedByte status; // StatusType, above UnsignedShort state; // KEY_STATE_* in KeyDefs.h - UnsignedInt sequence; // sequence info from DirectX used for order + UnsignedInt keyDownTimeMsec; // real-time in milliseconds when key went down }; @@ -86,7 +86,11 @@ struct KeyboardIO class Keyboard : public SubsystemInterface { - enum { KEY_REPEAT_DELAY = 10 }; + enum + { + KEY_REPEAT_DELAY_MSEC = 333, // 10 frames at 30 FPS + KEY_REPEAT_INTERVAL_MSEC = 67 // ~2 frames at 30 FPS + }; public: @@ -133,7 +137,6 @@ class Keyboard : public SubsystemInterface Bool checkKeyRepeat( void ); ///< check for repeating keys UnsignedByte getKeyStatusData( KeyDefType key ); ///< get key status Bool getKeyStateBit( KeyDefType key, Int bit ); ///< get key state bit - UnsignedInt getKeySequenceData( KeyDefType key ); ///< get key sequence void setKeyStateData( KeyDefType key, UnsignedByte data ); ///< get key state UnsignedShort m_modifiers; @@ -161,7 +164,6 @@ class Keyboard : public SubsystemInterface WideChar shifted2; } m_keyNames[ KEY_COUNT ]; - UnsignedInt m_inputFrame; ///< frame input was gathered on }; diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/LookAtXlat.h b/GeneralsMD/Code/GameEngine/Include/GameClient/LookAtXlat.h index e91b98f66e..db162de3ed 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/LookAtXlat.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/LookAtXlat.h @@ -76,12 +76,12 @@ class LookAtTranslator : public GameMessageTranslator Bool m_isRotating; // set to true if we are in the act of MMB rotating Bool m_isPitching; // set to true if we are in the act of ALT pitch rotation Bool m_isChangingFOV; // set to true if we are in the act of changing the field of view - UnsignedInt m_timestamp; // set when button goes down + UnsignedInt m_middleButtonDownTimeMsec; // real-time in milliseconds when middle button goes down DrawableID m_lastPlaneID; ViewLocation m_viewLocation[ MAX_VIEW_LOCS ]; ScrollType m_scrollType; ScreenEdgeScrollMode m_screenEdgeScrollMode; - UnsignedInt m_lastMouseMoveFrame; + UnsignedInt m_lastMouseMoveTimeMsec; // real-time in milliseconds when mouse last moved void setScrolling( ScrollType scrollType ); void stopScrolling( void ); diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Mouse.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Mouse.h index abd5c0c403..6170da909f 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/Mouse.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Mouse.h @@ -62,6 +62,7 @@ enum GameMode CPP_11(: Int); enum MouseButtonState CPP_11(: Int) { + MBS_None = -1, MBS_Up = 0, MBS_Down, MBS_DoubleClick, @@ -105,17 +106,14 @@ struct MouseIO user while - is down/toward user */ ICoord2D deltaPos; ///< overall change in mouse pointer this frame - MouseButtonState leftState; // button state: Up, Down, DoubleClick (Which is also down) + MouseButtonState leftState; // button state: None (no event), Up, Down, DoubleClick Int leftEvent; // Most important event this frame - Int leftFrame; // last frame button state changed MouseButtonState rightState; Int rightEvent; - Int rightFrame; MouseButtonState middleState; Int middleEvent; - Int middleFrame; }; class CursorInfo @@ -394,9 +392,6 @@ class Mouse : public SubsystemInterface Int m_minY; ///< mouse is locked to this region Int m_maxY; ///< mouse is locked to this region - UnsignedInt m_inputFrame; ///< frame input was gathered on - UnsignedInt m_deadInputFrame; ///< Frame which last input occured - Bool m_inputMovesAbsolute; /**< if TRUE, when processing mouse position chanages the movement will be done treating the coords as ABSOLUTE positions and NOT diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp index bb151a18d7..9ef9c3b142 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp @@ -140,7 +140,12 @@ void Keyboard::updateKeys( void ) m_keyStatus[ m_keys[ index ].key ].state = m_keys[ index ].state; m_keyStatus[ m_keys[ index ].key ].status = m_keys[ index ].status; - m_keyStatus[ m_keys[ index ].key ].sequence = m_inputFrame; + + // Update key down time for new key presses + if( BitIsSet( m_keys[ index ].state, KEY_STATE_DOWN ) ) + { + m_keyStatus[ m_keys[ index ].key ].keyDownTimeMsec = m_keys[ index ].keyDownTimeMsec; + } // prevent ALT-TAB from causing a TAB event if( m_keys[ index ].key == KEY_TAB ) @@ -195,7 +200,7 @@ void Keyboard::updateKeys( void ) } //------------------------------------------------------------------------------------------------- -/** check key repeat sequences, TRUE is returned if repeat is occurring */ +/** check key repeat timing, TRUE is returned if repeat is occurring */ //------------------------------------------------------------------------------------------------- Bool Keyboard::checkKeyRepeat( void ) { @@ -220,7 +225,11 @@ Bool Keyboard::checkKeyRepeat( void ) if( BitIsSet( m_keyStatus[ key ].state, KEY_STATE_DOWN ) ) { - if( (m_inputFrame - m_keyStatus[ key ].sequence) > Keyboard::KEY_REPEAT_DELAY ) + const UnsignedInt now = timeGetTime(); + const UnsignedInt keyDownTime = m_keyStatus[ key ].keyDownTimeMsec; + const UnsignedInt elapsedMsec = now - keyDownTime; + + if( elapsedMsec > Keyboard::KEY_REPEAT_DELAY_MSEC ) { // Add key to this frame m_keys[ index ].key = (UnsignedByte)key; @@ -232,10 +241,10 @@ Bool Keyboard::checkKeyRepeat( void ) // Set all keys as new to prevent multiple keys repeating for( index = 0; index< NUM_KEYS; index++ ) - m_keyStatus[ index ].sequence = m_inputFrame; + m_keyStatus[ index ].keyDownTimeMsec = now; - // Set repeated key so it will repeat again in two frames - m_keyStatus[ key ].sequence = m_inputFrame - (Keyboard::KEY_REPEAT_DELAY + 2); + // Set repeated key so it will repeat again after the interval + m_keyStatus[ key ].keyDownTimeMsec = now - (Keyboard::KEY_REPEAT_DELAY_MSEC + Keyboard::KEY_REPEAT_INTERVAL_MSEC); retVal = TRUE; break; // exit for key @@ -694,7 +703,6 @@ Keyboard::Keyboard( void ) m_shift2Key = KEY_NONE; memset( m_keyNames, 0, sizeof( m_keyNames ) ); - m_inputFrame = 0; } @@ -714,9 +722,6 @@ void Keyboard::init( void ) // initialize the key names initKeyNames(); - // first input frame - m_inputFrame = 0; - } //------------------------------------------------------------------------------------------------- @@ -733,9 +738,6 @@ void Keyboard::reset( void ) void Keyboard::update( void ) { - // increment input frame - m_inputFrame++; - // update the key data updateKeys(); @@ -819,14 +821,6 @@ Bool Keyboard::getKeyStateBit( KeyDefType key, Int bit ) return (m_keyStatus[ key ].state & bit) ? 1 : 0; } -//------------------------------------------------------------------------------------------------- -/** return the sequence data for the given key */ -//------------------------------------------------------------------------------------------------- -UnsignedInt Keyboard::getKeySequenceData( KeyDefType key ) -{ - return m_keyStatus[ key ].sequence; -} - //------------------------------------------------------------------------------------------------- /** set the key status data */ //------------------------------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp index db0e9c745f..2310d9ccc6 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp @@ -183,9 +183,6 @@ void Mouse::updateMouseData( ) else m_eventsThisFrame = 0; - if( index != 0 ) - m_deadInputFrame = m_inputFrame; - } //------------------------------------------------------------------------------------------------- @@ -221,7 +218,7 @@ void Mouse::processMouseEvent( Int index ) m_currMouse.wheelPos += m_mouseEvents[ index ].wheelPos; // Check Left Mouse State - if( m_mouseEvents[ index ].leftFrame ) + if( m_mouseEvents[ index ].leftState != MBS_None ) { if( m_currMouse.leftState != m_mouseEvents[ index ].leftState ) { @@ -231,21 +228,18 @@ void Mouse::processMouseEvent( Int index ) // Mouse Down m_currMouse.leftEvent = GWM_LEFT_DOWN; m_currMouse.leftState = MBS_Down; - m_currMouse.leftFrame = m_inputFrame; } else if ( m_mouseEvents[ index ].leftState == MBS_DoubleClick ) { // Mouse Double Click m_currMouse.leftEvent = GWM_LEFT_DOUBLE_CLICK; m_currMouse.leftState = MBS_DoubleClick; - m_currMouse.leftFrame = m_inputFrame; } else { // Mouse Up m_currMouse.leftEvent = GWM_LEFT_UP; m_currMouse.leftState = MBS_Up; - m_currMouse.leftFrame = m_inputFrame; } } } @@ -257,7 +251,7 @@ void Mouse::processMouseEvent( Int index ) } // Check Right Mouse State - if( m_mouseEvents[ index ].rightFrame ) + if( m_mouseEvents[ index ].rightState != MBS_None ) { if( m_currMouse.rightState != m_mouseEvents[ index ].rightState ) { @@ -267,21 +261,18 @@ void Mouse::processMouseEvent( Int index ) // Mouse Down m_currMouse.rightEvent = GWM_RIGHT_DOWN; m_currMouse.rightState = MBS_Down; - m_currMouse.rightFrame = m_inputFrame; } else if( m_mouseEvents[ index ].rightState == MBS_DoubleClick ) { // Mouse Double Click m_currMouse.rightEvent = GWM_RIGHT_DOUBLE_CLICK; m_currMouse.rightState = MBS_DoubleClick; - m_currMouse.rightFrame = m_inputFrame; } else { // Mouse Up m_currMouse.rightEvent = GWM_RIGHT_UP; m_currMouse.rightState = MBS_Up; - m_currMouse.rightFrame = m_inputFrame; } } } @@ -293,7 +284,7 @@ void Mouse::processMouseEvent( Int index ) } // Check Middle Mouse State - if( m_mouseEvents[ index ].middleFrame ) + if( m_mouseEvents[ index ].middleState != MBS_None ) { if( m_currMouse.middleState != m_mouseEvents[index].middleState ) { @@ -302,20 +293,17 @@ void Mouse::processMouseEvent( Int index ) { m_currMouse.middleEvent = GWM_MIDDLE_DOWN; m_currMouse.middleState = MBS_Down; - m_currMouse.middleFrame = m_inputFrame; } else if( m_mouseEvents[index].middleState == MBS_DoubleClick ) { m_currMouse.middleEvent = GWM_MIDDLE_DOUBLE_CLICK; m_currMouse.middleState = MBS_DoubleClick; - m_currMouse.middleFrame = m_inputFrame; } else { // Mouse Up m_currMouse.middleEvent = GWM_MIDDLE_UP; m_currMouse.middleState = MBS_Up; - m_currMouse.middleFrame = m_inputFrame; } } } @@ -328,7 +316,7 @@ void Mouse::processMouseEvent( Int index ) m_currMouse.deltaPos.x = m_currMouse.pos.x - m_prevMouse.pos.x; m_currMouse.deltaPos.y = m_currMouse.pos.y - m_prevMouse.pos.y; -// DEBUG_LOG(("Mouse dx %d, dy %d, index %d, frame %d", m_currMouse.deltaPos.x, m_currMouse.deltaPos.y, index, m_inputFrame)); +// DEBUG_LOG(("Mouse dx %d, dy %d, index %d", m_currMouse.deltaPos.x, m_currMouse.deltaPos.y, index)); // // check if mouse is still and flag tooltip // if( ((dx*dx) + (dy*dy)) < CURSOR_MOVE_TOL_SQ ) // { @@ -474,9 +462,6 @@ Mouse::Mouse( void ) m_maxY = 0; m_eventsThisFrame = 0; - m_inputFrame = 0; - m_deadInputFrame =0; - m_inputMovesAbsolute = FALSE; m_currentCursor = ARROW; @@ -590,9 +575,6 @@ void Mouse::init( void ) m_minY = 0; m_maxY = 599; - m_inputFrame = 0; - m_deadInputFrame =0; - m_inputMovesAbsolute = FALSE; m_eventsThisFrame = 0; @@ -676,9 +658,6 @@ void Mouse::reset( void ) void Mouse::update( void ) { - // increment input frame - m_inputFrame++; - // update the mouse data updateMouseData( ); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp index 8d900a3636..6168f28233 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp @@ -137,9 +137,9 @@ LookAtTranslator::LookAtTranslator() : m_isRotating(false), m_isPitching(false), m_isChangingFOV(false), - m_timestamp(0), + m_middleButtonDownTimeMsec(0), m_lastPlaneID(INVALID_DRAWABLE_ID), - m_lastMouseMoveFrame(0), + m_lastMouseMoveTimeMsec(0), m_scrollType(SCROLL_NONE) { m_anchor.x = m_anchor.y = 0; @@ -171,13 +171,12 @@ const ICoord2D* LookAtTranslator::getRMBScrollAnchor(void) Bool LookAtTranslator::hasMouseMovedRecently( void ) { - if (m_lastMouseMoveFrame > TheGameLogic->getFrame()) - m_lastMouseMoveFrame = 0; // reset for new game + const UnsignedInt now = timeGetTime(); + const UnsignedInt lastMove = m_lastMouseMoveTimeMsec; - if (m_lastMouseMoveFrame + LOGICFRAMES_PER_SECOND < TheGameLogic->getFrame()) - return false; + const UnsignedInt elapsedMsec = now - lastMove; - return true; + return elapsedMsec <= MSEC_PER_SECOND; } void LookAtTranslator::setCurrentPos( const ICoord2D& pos ) @@ -256,7 +255,7 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage //----------------------------------------------------------------------------- case GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_DOWN: { - m_lastMouseMoveFrame = TheGameLogic->getFrame(); + m_lastMouseMoveTimeMsec = timeGetTime(); m_anchor = msg->getArgument( 0 )->pixel; m_currentPos = msg->getArgument( 0 )->pixel; @@ -271,7 +270,7 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage //----------------------------------------------------------------------------- case GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_UP: { - m_lastMouseMoveFrame = TheGameLogic->getFrame(); + m_lastMouseMoveTimeMsec = timeGetTime(); if (m_scrollType == SCROLL_RMB) { @@ -283,23 +282,25 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage //----------------------------------------------------------------------------- case GameMessage::MSG_RAW_MOUSE_MIDDLE_BUTTON_DOWN: { - m_lastMouseMoveFrame = TheGameLogic->getFrame(); + const UnsignedInt now = timeGetTime(); + m_lastMouseMoveTimeMsec = now; + m_middleButtonDownTimeMsec = now; m_isRotating = true; m_anchor = msg->getArgument( 0 )->pixel; m_anchorAngle = TheTacticalView->getAngle(); m_originalAnchor = msg->getArgument( 0 )->pixel; m_currentPos = msg->getArgument( 0 )->pixel; - m_timestamp = TheGameClient->getFrame(); break; } //----------------------------------------------------------------------------- case GameMessage::MSG_RAW_MOUSE_MIDDLE_BUTTON_UP: { - m_lastMouseMoveFrame = TheGameLogic->getFrame(); + const UnsignedInt now = timeGetTime(); + m_lastMouseMoveTimeMsec = now; - const UnsignedInt CLICK_DURATION = 5; + const UnsignedInt CLICK_DURATION_MSEC = 167; const UnsignedInt PIXEL_OFFSET = 5; m_isRotating = false; @@ -307,8 +308,11 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage if (dx<0) dx = -dx; Int dy = m_currentPos.y-m_originalAnchor.y; Bool didMove = dx>PIXEL_OFFSET || dy>PIXEL_OFFSET; + + const UnsignedInt elapsedMsec = now - m_middleButtonDownTimeMsec; + // if middle button is "clicked", reset to "home" orientation - if (!didMove && TheGameClient->getFrame() - m_timestamp < CLICK_DURATION) + if (!didMove && elapsedMsec < CLICK_DURATION_MSEC) { TheTacticalView->setAngleAndPitchToDefault(); TheTacticalView->setZoomToDefault(); @@ -321,7 +325,7 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage case GameMessage::MSG_RAW_MOUSE_POSITION: { if (m_currentPos.x != msg->getArgument( 0 )->pixel.x || m_currentPos.y != msg->getArgument( 0 )->pixel.y) - m_lastMouseMoveFrame = TheGameLogic->getFrame(); + m_lastMouseMoveTimeMsec = timeGetTime(); m_currentPos = msg->getArgument( 0 )->pixel; @@ -401,7 +405,7 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage //----------------------------------------------------------------------------- case GameMessage::MSG_RAW_MOUSE_WHEEL: { - m_lastMouseMoveFrame = TheGameLogic->getFrame(); + m_lastMouseMoveTimeMsec = timeGetTime(); Int spin = msg->getArgument( 1 )->integer; diff --git a/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIKeyboard.cpp b/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIKeyboard.cpp index 027a95f479..0591902e29 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIKeyboard.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIKeyboard.cpp @@ -251,7 +251,6 @@ void DirectInputKeyboard::getKey( KeyboardIO *key ) HRESULT hr; assert( key ); - key->sequence = 0; key->key = KEY_NONE; if( m_pKeyboardDevice ) @@ -315,15 +314,20 @@ void DirectInputKeyboard::getKey( KeyboardIO *key ) // set the key key->key = (UnsignedByte)(kbdat.dwOfs & 0xFF); - // sequence - key->sequence = kbdat.dwSequence; - // // state of key, note we are setting the key state here with an assignment // and not a bit set of the up/down state, this is the "start" // of building this "key" // - key->state = (( kbdat.dwData & 0x0080 ) ? KEY_STATE_DOWN : KEY_STATE_UP); + if( kbdat.dwData & 0x0080 ) + { + key->state = KEY_STATE_DOWN; + key->keyDownTimeMsec = kbdat.dwTimeStamp; + } + else + { + key->state = KEY_STATE_UP; + } // set status as unused (unprocessed) key->status = KeyboardIO::STATUS_UNUSED; diff --git a/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIMouse.cpp b/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIMouse.cpp index e5b195fe6c..c8b59e10e6 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIMouse.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIMouse.cpp @@ -202,7 +202,7 @@ UnsignedByte DirectInputMouse::getMouseEvent( MouseIO *result, Bool flush ) /* set these to defaults */ result->leftState = result->middleState = result->rightState = FALSE; - result->leftFrame = result->middleFrame = result->rightFrame = 0; + result->leftState = result->middleState = result->rightState = MBS_None; result->pos.x = result->pos.y = result->wheelPos = 0; if( m_pMouseDevice ) @@ -282,18 +282,15 @@ void DirectInputMouse::mapDirectInputMouse( MouseIO *mouse, switch( mdat->dwOfs ) { case DIMOFS_BUTTON0: - mouse->leftState = (( mdat->dwData & 0x0080 ) ? TRUE : FALSE); - mouse->leftFrame = mdat->dwSequence; + mouse->leftState = (( mdat->dwData & 0x0080 ) ? MBS_Down : MBS_Up); break; case DIMOFS_BUTTON1: - mouse->rightState = (( mdat->dwData & 0x0080 ) ? TRUE : FALSE); - mouse->rightFrame = mdat->dwSequence; + mouse->rightState = (( mdat->dwData & 0x0080 ) ? MBS_Down : MBS_Up); break; case DIMOFS_BUTTON2: - mouse->middleState = (( mdat->dwData & 0x0080 ) ? TRUE : FALSE); - mouse->middleFrame = mdat->dwSequence; + mouse->middleState = (( mdat->dwData & 0x0080 ) ? MBS_Down : MBS_Up); break; case DIMOFS_BUTTON3: diff --git a/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32Mouse.cpp b/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32Mouse.cpp index 9b89deba00..085bcd461d 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32Mouse.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32Mouse.cpp @@ -85,21 +85,9 @@ void Win32Mouse::translateEvent( UnsignedInt eventIndex, MouseIO *result ) UINT msg = m_eventBuffer[ eventIndex ].msg; WPARAM wParam = m_eventBuffer[ eventIndex ].wParam; LPARAM lParam = m_eventBuffer[ eventIndex ].lParam; - UnsignedInt frame; - - // - // get the current input frame from the client, if we don't have - // a client (like in the GUI editor) we just use frame 1 so it - // registers with the system - // - if( TheGameClient ) - frame = TheGameClient->getFrame(); - else - frame = 1; // set these to defaults - result->leftState = result->middleState = result->rightState = MBS_Up; - result->leftFrame = result->middleFrame = result->rightFrame = 0; + result->leftState = result->middleState = result->rightState = MBS_None; result->pos.x = result->pos.y = result->wheelPos = 0; // Time is the same for all events @@ -113,7 +101,6 @@ void Win32Mouse::translateEvent( UnsignedInt eventIndex, MouseIO *result ) { result->leftState = MBS_Down; - result->leftFrame = frame; result->pos.x = LOWORD( lParam ); result->pos.y = HIWORD( lParam ); break; @@ -125,7 +112,6 @@ void Win32Mouse::translateEvent( UnsignedInt eventIndex, MouseIO *result ) { result->leftState = MBS_Up; - result->leftFrame = frame; result->pos.x = LOWORD( lParam ); result->pos.y = HIWORD( lParam ); break; @@ -137,7 +123,6 @@ void Win32Mouse::translateEvent( UnsignedInt eventIndex, MouseIO *result ) { result->leftState = MBS_DoubleClick; - result->leftFrame = frame; result->pos.x = LOWORD( lParam ); result->pos.y = HIWORD( lParam ); break; @@ -149,7 +134,6 @@ void Win32Mouse::translateEvent( UnsignedInt eventIndex, MouseIO *result ) { result->middleState = MBS_Down; - result->middleFrame = frame; result->pos.x = LOWORD( lParam ); result->pos.y = HIWORD( lParam ); break; @@ -161,7 +145,6 @@ void Win32Mouse::translateEvent( UnsignedInt eventIndex, MouseIO *result ) { result->middleState = MBS_Up; - result->middleFrame = frame; result->pos.x = LOWORD( lParam ); result->pos.y = HIWORD( lParam ); break; @@ -173,7 +156,6 @@ void Win32Mouse::translateEvent( UnsignedInt eventIndex, MouseIO *result ) { result->middleState = MBS_DoubleClick; - result->middleFrame = frame; result->pos.x = LOWORD( lParam ); result->pos.y = HIWORD( lParam ); break; @@ -185,7 +167,6 @@ void Win32Mouse::translateEvent( UnsignedInt eventIndex, MouseIO *result ) { result->rightState = MBS_Down; - result->rightFrame = frame; result->pos.x = LOWORD( lParam ); result->pos.y = HIWORD( lParam ); break; @@ -197,7 +178,6 @@ void Win32Mouse::translateEvent( UnsignedInt eventIndex, MouseIO *result ) { result->rightState = MBS_Up; - result->rightFrame = frame; result->pos.x = LOWORD( lParam ); result->pos.y = HIWORD( lParam ); break; @@ -209,7 +189,6 @@ void Win32Mouse::translateEvent( UnsignedInt eventIndex, MouseIO *result ) { result->rightState = MBS_DoubleClick; - result->rightFrame = frame; result->pos.x = LOWORD( lParam ); result->pos.y = HIWORD( lParam ); break; From 03b9ae8b3d198fa8672d02e09fa4a1faae22e358 Mon Sep 17 00:00:00 2001 From: Stubbjax Date: Sun, 21 Dec 2025 22:20:40 +1100 Subject: [PATCH 47/70] bugfix(aiupdate): Repairing Chinooks and Helixes no longer take off after evacuating all passengers (#1762) --- .../GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp | 6 ++++++ .../GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp | 6 ++++++ 2 files changed, 12 insertions(+) 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 eff1686059..173c3f6a2b 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp @@ -1123,8 +1123,14 @@ void ChinookAIUpdate::privateCombatDrop( Object* target, const Coord3D& pos, Com //------------------------------------------------------------------------------------------------- void ChinookAIUpdate::aiDoCommand(const AICommandParms* parms) { +#if RETAIL_COMPATIBLE_CRC // this gets reset every time a command is issued. setAirfieldForHealing(INVALID_ID); +#else + // TheSuperHackers @bugfix Stubbjax 31/10/2025 Don't leave healing state for evacuation commands. + if (parms->m_cmd != AICMD_EVACUATE && parms->m_cmd != AICMD_EXIT) + setAirfieldForHealing(INVALID_ID); +#endif if (!isAllowedToRespondToAiCommands(parms)) return; 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 87f5b42d9d..4490a237dd 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp @@ -1258,8 +1258,14 @@ void ChinookAIUpdate::privateCombatDrop( Object* target, const Coord3D& pos, Com //------------------------------------------------------------------------------------------------- void ChinookAIUpdate::aiDoCommand(const AICommandParms* parms) { +#if RETAIL_COMPATIBLE_CRC // this gets reset every time a command is issued. setAirfieldForHealing(INVALID_ID); +#else + // TheSuperHackers @bugfix Stubbjax 31/10/2025 Don't leave healing state for evacuation commands. + if (parms->m_cmd != AICMD_EVACUATE && parms->m_cmd != AICMD_EXIT) + setAirfieldForHealing(INVALID_ID); +#endif if (!isAllowedToRespondToAiCommands(parms)) return; From 646e3dddb681fe2e6bc0aee1ed3c0c8e58f7bf6e Mon Sep 17 00:00:00 2001 From: Stubbjax Date: Sun, 21 Dec 2025 22:20:51 +1100 Subject: [PATCH 48/70] bugfix(aiupdate): Chinooks and Helixes no longer take off after repair if passengers want to board or exit (#1787) --- .../GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp | 9 +++++++-- .../GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp | 9 +++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) 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 173c3f6a2b..60dbd2361e 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp @@ -1002,9 +1002,16 @@ Bool ChinookAIUpdate::chooseLocomotorSet(LocomotorSetType wst) UpdateSleepTime ChinookAIUpdate::update() { ParkingPlaceBehaviorInterface* pp = getPP(m_airfieldForHealing); + const ContainModuleInterface* contain = getObject()->getContain(); + const Bool waitingToEnterOrExit = contain && contain->hasObjectsWantingToEnterOrExit(); + if (pp != NULL) { if (m_flightStatus == CHINOOK_LANDED && +#if !RETAIL_COMPATIBLE_CRC + // TheSuperHackers @bugfix Stubbjax 03/11/2025 Prevent Chinooks from taking off while there are still units wanting to enter or exit. + !waitingToEnterOrExit && +#endif !m_hasPendingCommand && getObject()->getBodyModule()->getHealth() == getObject()->getBodyModule()->getMaxHealth()) { @@ -1026,10 +1033,8 @@ UpdateSleepTime ChinookAIUpdate::update() // when we have a pending command... if (SupplyTruckAIUpdate::isIdle()) { - ContainModuleInterface* contain = getObject()->getContain(); if( contain ) { - 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 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 4490a237dd..dd33e54cbd 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp @@ -1064,9 +1064,16 @@ Bool ChinookAIUpdate::chooseLocomotorSet(LocomotorSetType wst) UpdateSleepTime ChinookAIUpdate::update() { ParkingPlaceBehaviorInterface* pp = getPP(m_airfieldForHealing); + const ContainModuleInterface* contain = getObject()->getContain(); + const Bool waitingToEnterOrExit = contain && contain->hasObjectsWantingToEnterOrExit(); + if (pp != NULL) { if (m_flightStatus == CHINOOK_LANDED && +#if !RETAIL_COMPATIBLE_CRC + // TheSuperHackers @bugfix Stubbjax 03/11/2025 Prevent Chinooks from taking off while there are still units wanting to enter or exit. + !waitingToEnterOrExit && +#endif !m_hasPendingCommand && getObject()->getBodyModule()->getHealth() == getObject()->getBodyModule()->getMaxHealth()) { @@ -1088,12 +1095,10 @@ UpdateSleepTime ChinookAIUpdate::update() // 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 From b878990ab3d030763cabbf7ea777f4b42d73418a Mon Sep 17 00:00:00 2001 From: Bobby Battista Date: Sun, 21 Dec 2025 12:30:34 -0500 Subject: [PATCH 49/70] refactor: Apply clang-tidy fixes for generals-use-this-instead-of-singleton (#2017) --- .../Source/GameNetwork/FirewallHelper.cpp | 2 +- .../GameSpy/StagingRoomGameInfo.cpp | 4 +- .../Source/GameNetwork/LANAPIhandlers.cpp | 2 +- .../GameClient/Water/W3DWaterTracks.cpp | 4 +- Core/Tools/ImagePacker/Source/ImagePacker.cpp | 20 +- .../Include/GameLogic/PartitionManager.h | 4 +- .../GameEngine/Source/Common/GlobalData.cpp | 2 +- .../Common/System/SaveGame/GameState.cpp | 2 +- .../GameClient/GUI/ControlBar/ControlBar.cpp | 10 +- .../GUI/ControlBar/ControlBarCommand.cpp | 2 +- .../ControlBarCommandProcessing.cpp | 2 +- .../ControlBarPopupDescription.cpp | 4 +- .../GameClient/GUI/GameWindowManager.cpp | 174 +++++++++--------- .../Source/GameClient/GameClient.cpp | 4 +- .../GameEngine/Source/GameClient/InGameUI.cpp | 84 ++++----- .../Source/GameClient/System/ParticleSys.cpp | 2 +- .../GameEngine/Source/GameLogic/AI/AI.cpp | 2 +- .../Source/GameLogic/Map/TerrainLogic.cpp | 6 +- .../GameLogic/Object/PartitionManager.cpp | 44 ++--- .../Source/GameLogic/Object/Weapon.cpp | 6 +- .../GameLogic/ScriptEngine/ScriptEngine.cpp | 4 +- .../Source/GameLogic/System/GameLogic.cpp | 14 +- .../GameLogic/System/GameLogicDispatch.cpp | 54 +++--- .../Code/Tools/GUIEdit/Source/EditWindow.cpp | 4 +- .../Code/Tools/GUIEdit/Source/GUIEdit.cpp | 34 ++-- .../Tools/GUIEdit/Source/HierarchyView.cpp | 2 +- Generals/Code/Tools/GUIEdit/Source/Save.cpp | 4 +- .../Include/GameLogic/PartitionManager.h | 4 +- .../GameEngine/Source/Common/GlobalData.cpp | 2 +- .../Common/System/SaveGame/GameState.cpp | 2 +- .../GameClient/GUI/ControlBar/ControlBar.cpp | 18 +- .../GUI/ControlBar/ControlBarCommand.cpp | 8 +- .../ControlBarCommandProcessing.cpp | 2 +- .../ControlBarPopupDescription.cpp | 4 +- .../GameClient/GUI/GameWindowManager.cpp | 174 +++++++++--------- .../Source/GameClient/GameClient.cpp | 4 +- .../GameEngine/Source/GameClient/InGameUI.cpp | 84 ++++----- .../Source/GameClient/System/ParticleSys.cpp | 2 +- .../GameEngine/Source/GameLogic/AI/AI.cpp | 2 +- .../Source/GameLogic/Map/TerrainLogic.cpp | 6 +- .../GameLogic/Object/PartitionManager.cpp | 44 ++--- .../Source/GameLogic/Object/Weapon.cpp | 6 +- .../GameLogic/ScriptEngine/ScriptEngine.cpp | 4 +- .../Source/GameLogic/System/GameLogic.cpp | 14 +- .../GameLogic/System/GameLogicDispatch.cpp | 54 +++--- .../Code/Tools/GUIEdit/Source/EditWindow.cpp | 4 +- .../Code/Tools/GUIEdit/Source/GUIEdit.cpp | 34 ++-- .../Tools/GUIEdit/Source/HierarchyView.cpp | 2 +- GeneralsMD/Code/Tools/GUIEdit/Source/Save.cpp | 4 +- 49 files changed, 487 insertions(+), 487 deletions(-) diff --git a/Core/GameEngine/Source/GameNetwork/FirewallHelper.cpp b/Core/GameEngine/Source/GameNetwork/FirewallHelper.cpp index 320b672ee9..2f0db33a44 100644 --- a/Core/GameEngine/Source/GameNetwork/FirewallHelper.cpp +++ b/Core/GameEngine/Source/GameNetwork/FirewallHelper.cpp @@ -508,7 +508,7 @@ void FirewallHelperClass::writeFirewallBehavior(void) numstr = num; (pref)["FirewallBehavior"] = numstr; - TheWritableGlobalData->m_firewallPortAllocationDelta = TheFirewallHelper->getSourcePortAllocationDelta(); + TheWritableGlobalData->m_firewallPortAllocationDelta = getSourcePortAllocationDelta(); num[0] = 0; itoa(TheGlobalData->m_firewallPortAllocationDelta, num, 10); numstr = num; diff --git a/Core/GameEngine/Source/GameNetwork/GameSpy/StagingRoomGameInfo.cpp b/Core/GameEngine/Source/GameNetwork/GameSpy/StagingRoomGameInfo.cpp index dc0aea8b3f..278f991793 100644 --- a/Core/GameEngine/Source/GameNetwork/GameSpy/StagingRoomGameInfo.cpp +++ b/Core/GameEngine/Source/GameNetwork/GameSpy/StagingRoomGameInfo.cpp @@ -844,7 +844,7 @@ void GameSpyStagingRoom::launchGame( void ) // shutdown the top, but do not pop it off the stack // TheShell->hideShell(); // setup the Global Data with the Map and Seed - TheWritableGlobalData->m_pendingFile = TheGameSpyGame->getMap(); + TheWritableGlobalData->m_pendingFile = getMap(); // send a message to the logic for a new game GameMessage *msg = TheMessageStream->appendMessage( GameMessage::MSG_NEW_GAME ); @@ -861,7 +861,7 @@ void GameSpyStagingRoom::launchGame( void ) req.buddyRequestType = BuddyRequest::BUDDYREQUEST_SETSTATUS; req.arg.status.status = GP_PLAYING; strcpy(req.arg.status.statusString, "Loading"); - sprintf(req.arg.status.locationString, "%s", WideCharStringToMultiByte(TheGameSpyGame->getGameName().str()).c_str()); + sprintf(req.arg.status.locationString, "%s", WideCharStringToMultiByte(getGameName().str()).c_str()); TheGameSpyBuddyMessageQueue->addRequest(req); delete TheNAT; diff --git a/Core/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp b/Core/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp index d6dbba0823..61660ff964 100644 --- a/Core/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp +++ b/Core/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp @@ -709,7 +709,7 @@ void LANAPI::handleInActive(LANMessage *msg, UnsignedInt senderIP) { } // don't want to unaccept the host, that's silly. They can't hit start alt-tabbed anyways. - if (senderIP == TheLAN->GetLocalIP()) { + if (senderIP == GetLocalIP()) { return; } diff --git a/Core/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp index afc6ed9013..6f34e7e7e7 100644 --- a/Core/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp +++ b/Core/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp @@ -1023,7 +1023,7 @@ void WaterTracksRenderSystem::loadTracks(void) goto tryagain; } - umod=TheWaterTracksRenderSystem->bindTrack(wtype); + umod=bindTrack(wtype); if (umod) { //umod->init(1.5f*MAP_XY_FACTOR,Vector2(0,0),Vector2(1,1),"wave256.tga"); flipU ^= 1; //toggle flip state @@ -1032,7 +1032,7 @@ void WaterTracksRenderSystem::loadTracks(void) if (waveTypeInfo[wtype].m_secondWaveTimeOffset) //check if we need a second wave to follow { - umod=TheWaterTracksRenderSystem->bindTrack(wtype); + umod=bindTrack(wtype); if (umod) { umod->init(waveTypeInfo[wtype].m_finalHeight,waveTypeInfo[wtype].m_finalWidth,startPos,endPos,waveTypeInfo[wtype].m_textureName,waveTypeInfo[wtype].m_secondWaveTimeOffset); diff --git a/Core/Tools/ImagePacker/Source/ImagePacker.cpp b/Core/Tools/ImagePacker/Source/ImagePacker.cpp index a113f4d7ea..d0abc547ba 100644 --- a/Core/Tools/ImagePacker/Source/ImagePacker.cpp +++ b/Core/Tools/ImagePacker/Source/ImagePacker.cpp @@ -179,7 +179,7 @@ Bool ImagePacker::validateImages( void ) proceed = DialogBox( ApplicationHInstance, (LPCTSTR)IMAGE_ERRORS, - TheImagePacker->getWindowHandle(), + getWindowHandle(), (DLGPROC)ImageErrorProc ); } @@ -317,7 +317,7 @@ void ImagePacker::writeFinalTextures( void ) DialogBox( ApplicationHInstance, (LPCTSTR)PAGE_ERRORS, - TheImagePacker->getWindowHandle(), + getWindowHandle(), (DLGPROC)PageErrorProc ); } @@ -998,33 +998,33 @@ Bool ImagePacker::getSettingsFromDialog( HWND dialog ) Bool outputAlpha = FALSE; if( IsDlgButtonChecked( dialog, CHECK_ALPHA ) == BST_CHECKED ) outputAlpha = TRUE; - TheImagePacker->setOutputAlpha( outputAlpha ); + setOutputAlpha( outputAlpha ); // get create INI option Bool createINI = FALSE; if( IsDlgButtonChecked( dialog, CHECK_INI ) == BST_CHECKED ) createINI = TRUE; - TheImagePacker->setINICreate( createINI ); + setINICreate( createINI ); // get preview with image option Bool useBitmap = FALSE; if( IsDlgButtonChecked( dialog, CHECK_BITMAP_PREVIEW ) == BST_CHECKED ) useBitmap = TRUE; - TheImagePacker->setUseTexturePreview( useBitmap ); + setUseTexturePreview( useBitmap ); // get option to compress final textures Bool compress = FALSE; if( IsDlgButtonChecked( dialog, CHECK_COMPRESS ) == BST_CHECKED ) compress = TRUE; - TheImagePacker->setCompressTextures( compress ); + setCompressTextures( compress ); // get options for the gap options - TheImagePacker->clearGapMethod( ImagePacker::GAP_METHOD_EXTEND_RGB ); + 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 ); + setGapMethod( ImagePacker::GAP_METHOD_EXTEND_RGB ); + clearGapMethod( ImagePacker::GAP_METHOD_GUTTER ); if( IsDlgButtonChecked( dialog, CHECK_GAP_GUTTER ) == BST_CHECKED ) - TheImagePacker->setGapMethod( ImagePacker::GAP_METHOD_GUTTER ); + setGapMethod( ImagePacker::GAP_METHOD_GUTTER ); // get gutter size whether we are using that option or not Int gutter = GetDlgItemInt( dialog, EDIT_GUTTER, NULL, FALSE ); diff --git a/Generals/Code/GameEngine/Include/GameLogic/PartitionManager.h b/Generals/Code/GameEngine/Include/GameLogic/PartitionManager.h index 18e278bb71..6631616c30 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/PartitionManager.h +++ b/Generals/Code/GameEngine/Include/GameLogic/PartitionManager.h @@ -1321,7 +1321,7 @@ class PartitionManager : public SubsystemInterface, public Snapshot void getCellCenterPos(Int x, Int y, Real& xx, Real& yy); // find the cell that covers the world coords (wx,wy) and return its coords. - void worldToCell(Real wx, Real wy, Int *cx, Int *cy); + void worldToCell(Real wx, Real wy, Int *cx, Int *cy) const; // given a distance in world coords, return the number of cells needed to cover that distance (rounding up) Int worldToCellDist(Real w); @@ -1494,7 +1494,7 @@ class PartitionManager : public SubsystemInterface, public Snapshot }; // ----------------------------------------------------------------------------- -inline void PartitionManager::worldToCell(Real wx, Real wy, Int *cx, Int *cy) +inline void PartitionManager::worldToCell(Real wx, Real wy, Int *cx, Int *cy) const { *cx = REAL_TO_INT_FLOOR((wx - m_worldExtents.lo.x) * m_cellSizeInv); *cy = REAL_TO_INT_FLOOR((wy - m_worldExtents.lo.y) * m_cellSizeInv); diff --git a/Generals/Code/GameEngine/Source/Common/GlobalData.cpp b/Generals/Code/GameEngine/Source/Common/GlobalData.cpp index 348374f57f..24d13f14da 100644 --- a/Generals/Code/GameEngine/Source/Common/GlobalData.cpp +++ b/Generals/Code/GameEngine/Source/Common/GlobalData.cpp @@ -1118,7 +1118,7 @@ void GlobalData::reset( void ) { // get next instance - GlobalData* next = TheWritableGlobalData->m_next; + GlobalData* next = m_next; // delete the head of the global data list (the latest override) delete TheWritableGlobalData; diff --git a/Generals/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp b/Generals/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp index 0d0229142d..2fd84f01c3 100644 --- a/Generals/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp @@ -636,7 +636,7 @@ SaveCode GameState::missionSave( void ) desc.format( format, TheGameText->fetch( campaign->m_campaignNameLabel ).str(), missionNumber ); // do an automatic mission save - return TheGameState->saveGame( "", desc, SAVE_FILE_TYPE_MISSION ); + return saveGame( "", desc, SAVE_FILE_TYPE_MISSION ); } diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp index dfc5f077e1..75952a05f2 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp @@ -188,9 +188,9 @@ void ControlBar::populatePurchaseScience( Player* player ) player->getPlayerTemplate()->getPurchaseScienceCommandSetRank3().isEmpty() || player->getPlayerTemplate()->getPurchaseScienceCommandSetRank8().isEmpty()) return; - commandSet1 = TheControlBar->findCommandSet(player->getPlayerTemplate()->getPurchaseScienceCommandSetRank1()); // TEMP WILL CHANGE TO PROPER WAY ONCE WORKING - commandSet3 = TheControlBar->findCommandSet(player->getPlayerTemplate()->getPurchaseScienceCommandSetRank3()); // TEMP WILL CHANGE TO PROPER WAY ONCE WORKING - commandSet8 = TheControlBar->findCommandSet(player->getPlayerTemplate()->getPurchaseScienceCommandSetRank8()); // TEMP WILL CHANGE TO PROPER WAY ONCE WORKING + commandSet1 = findCommandSet(player->getPlayerTemplate()->getPurchaseScienceCommandSetRank1()); // TEMP WILL CHANGE TO PROPER WAY ONCE WORKING + commandSet3 = findCommandSet(player->getPlayerTemplate()->getPurchaseScienceCommandSetRank3()); // TEMP WILL CHANGE TO PROPER WAY ONCE WORKING + commandSet8 = findCommandSet(player->getPlayerTemplate()->getPurchaseScienceCommandSetRank8()); // TEMP WILL CHANGE TO PROPER WAY ONCE WORKING for( i = 0; i < MAX_PURCHASE_SCIENCE_RANK_1; i++ ) m_sciencePurchaseWindowsRank1[i]->winHide(TRUE); @@ -2712,7 +2712,7 @@ void ControlBar::showRallyPoint(const Coord3D* loc) marker->setOrientation(TheGlobalData->m_downwindAngle); // To blow down wind -- ML // set the marker colors to that of the local player - Player* player = TheControlBar->getCurrentlyViewedPlayer(); + Player* player = getCurrentlyViewedPlayer(); if (player) { if (TheGlobalData->m_timeOfDay == TIME_OF_DAY_NIGHT) @@ -3258,7 +3258,7 @@ void ControlBar::populateSpecialPowerShortcut( Player *player) // get command set if(player->getPlayerTemplate()->getSpecialPowerShortcutCommandSet().isEmpty() ) return; - commandSet = TheControlBar->findCommandSet(player->getPlayerTemplate()->getSpecialPowerShortcutCommandSet()); // TEMP WILL CHANGE TO PROPER WAY ONCE WORKING + commandSet = findCommandSet(player->getPlayerTemplate()->getSpecialPowerShortcutCommandSet()); // TEMP WILL CHANGE TO PROPER WAY ONCE WORKING if(!commandSet) return; // populate the button with commands defined diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp index f70dcc6612..a02c6e7dd1 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp @@ -270,7 +270,7 @@ void ControlBar::populateCommand( Object *obj ) resetBuildQueueData(); // get command set - commandSet = TheControlBar->findCommandSet( obj->getCommandSetString() ); + commandSet = findCommandSet( obj->getCommandSetString() ); // if no command set match is found hide all the buttons if( commandSet == NULL ) diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp index 86b32cd64e..44f7f28fa0 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp @@ -125,7 +125,7 @@ CBCommandStatus ControlBar::processCommandUI( GameWindow *control, // if the button is flashing, tell it to stop flashing commandButton->setFlashCount(0); - TheControlBar->setFlash( FALSE ); + setFlash( FALSE ); if( commandButton->getCommandType() != GUI_COMMAND_EXIT_CONTAINER ) { diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp index 91483cdfaf..c658188dd0 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp @@ -518,7 +518,7 @@ void ControlBar::populateBuildTooltipLayout( const CommandButton *commandButton, name = TheGameText->fetch("CONTROLBAR:Power"); descrip = TheGameText->fetch("CONTROLBAR:PowerDescription"); - Player* playerToDisplay = TheControlBar->getCurrentlyViewedPlayer(); + Player* playerToDisplay = getCurrentlyViewedPlayer(); if( playerToDisplay && playerToDisplay->getEnergy() ) { @@ -598,7 +598,7 @@ void ControlBar::populateBuildTooltipLayout( const CommandButton *commandButton, { return; } - TheControlBar->getBackgroundMarkerPos(&basePos.x, &basePos.y); + getBackgroundMarkerPos(&basePos.x, &basePos.y); ICoord2D curPos, offset; marker->winGetScreenPosition(&curPos.x,&curPos.y); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp index de8aa1c029..2d43ebcc48 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp @@ -1584,7 +1584,7 @@ void GameWindowManager::winSetLoneWindow( GameWindow *window ) if( m_loneWindow == window ) return; if( m_loneWindow ) - TheWindowManager->winSendSystemMsg( m_loneWindow, GGM_CLOSE, 0, 0 ); + winSendSystemMsg( m_loneWindow, GGM_CLOSE, 0, 0 ); m_loneWindow = window; } @@ -1633,10 +1633,10 @@ GameWindow *GameWindowManager::gogoMessageBox(Int x, Int y, Int width, Int heigh tempName = menuName; tempName.concat("MessageBoxParent"); - parent = TheWindowManager->winGetWindowFromId(trueParent, TheNameKeyGenerator->nameToKey( tempName )); - TheWindowManager->winSetModal( trueParent ); - TheWindowManager->winSetFocus( NULL ); // make sure we lose focus from other windows even if we refuse focus ourselves - TheWindowManager->winSetFocus( parent ); + parent = winGetWindowFromId(trueParent, TheNameKeyGenerator->nameToKey( tempName )); + winSetModal( trueParent ); + winSetFocus( NULL ); // make sure we lose focus from other windows even if we refuse focus ourselves + winSetFocus( parent ); // If the user wants the size to be different then the default float ratioX, ratioY = 1; @@ -1680,25 +1680,25 @@ GameWindow *GameWindowManager::gogoMessageBox(Int x, Int y, Int width, Int heigh tempName = menuName; tempName.concat("ButtonOk"); buttonOkID = TheNameKeyGenerator->nameToKey( tempName ); - GameWindow *buttonOk = TheWindowManager->winGetWindowFromId(parent, buttonOkID); + GameWindow *buttonOk = winGetWindowFromId(parent, buttonOkID); buttonOk->winGetPosition(&buttonX[0], &buttonY[0]); tempName = menuName; tempName.concat("ButtonYes"); NameKeyType buttonYesID = TheNameKeyGenerator->nameToKey( tempName ); - GameWindow *buttonYes = TheWindowManager->winGetWindowFromId(parent, buttonYesID); + GameWindow *buttonYes = winGetWindowFromId(parent, buttonYesID); //buttonNo in the second position tempName = menuName; tempName.concat("ButtonNo"); NameKeyType buttonNoID = TheNameKeyGenerator->nameToKey(tempName); - GameWindow *buttonNo = TheWindowManager->winGetWindowFromId(parent, buttonNoID); + GameWindow *buttonNo = winGetWindowFromId(parent, buttonNoID); buttonNo->winGetPosition(&buttonX[1], &buttonY[1]); //and buttonCancel in the third tempName = menuName; tempName.concat("ButtonCancel"); NameKeyType buttonCancelID = TheNameKeyGenerator->nameToKey( tempName ); - GameWindow *buttonCancel = TheWindowManager->winGetWindowFromId(parent, buttonCancelID); + GameWindow *buttonCancel = winGetWindowFromId(parent, buttonCancelID); buttonCancel->winGetPosition(&buttonX[2], &buttonY[2]); //we shouldn't have button OK and Yes on the same dialog @@ -1745,12 +1745,12 @@ GameWindow *GameWindowManager::gogoMessageBox(Int x, Int y, Int width, Int heigh tempName = menuName; tempName.concat("StaticTextTitle"); NameKeyType staticTextTitleID = TheNameKeyGenerator->nameToKey( tempName ); - GameWindow *staticTextTitle = TheWindowManager->winGetWindowFromId(parent, staticTextTitleID); + GameWindow *staticTextTitle = winGetWindowFromId(parent, staticTextTitleID); GadgetStaticTextSetText(staticTextTitle,titleString); tempName = menuName; tempName.concat("StaticTextMessage"); NameKeyType staticTextMessageID = TheNameKeyGenerator->nameToKey( tempName ); - GameWindow *staticTextMessage = TheWindowManager->winGetWindowFromId(parent, staticTextMessageID); + GameWindow *staticTextMessage = winGetWindowFromId(parent, staticTextMessageID); GadgetStaticTextSetText(staticTextMessage,bodyString); // create a structure that will pass the functions to @@ -1794,7 +1794,7 @@ GameWindow *GameWindowManager::gogoGadgetPushButton( GameWindow *parent, } // create the button window - button = TheWindowManager->winCreate( parent, status, + button = winCreate( parent, status, x, y, width, height, GadgetPushButtonSystem, instData ); @@ -1862,7 +1862,7 @@ GameWindow *GameWindowManager::gogoGadgetCheckbox( GameWindow *parent, } // create the button window - checkbox = TheWindowManager->winCreate( parent, status, + checkbox = winCreate( parent, status, x, y, width, height, GadgetCheckBoxSystem, instData ); @@ -1929,7 +1929,7 @@ GameWindow *GameWindowManager::gogoGadgetRadioButton( GameWindow *parent, } // create the button window - radioButton = TheWindowManager->winCreate( parent, status, + radioButton = winCreate( parent, status, x, y, width, height, GadgetRadioButtonSystem, instData ); @@ -2001,7 +2001,7 @@ GameWindow *GameWindowManager::gogoGadgetTabControl( GameWindow *parent, } // create the tab control window - tabControl = TheWindowManager->winCreate( parent, status, + tabControl = winCreate( parent, status, x, y, width, height, GadgetTabControlSystem, instData ); @@ -2395,7 +2395,7 @@ GameWindow *GameWindowManager::gogoGadgetComboBox( GameWindow *parent, // remove unwanted status bits. status &= ~(WIN_STATUS_BORDER | WIN_STATUS_HIDDEN); - fontHeight = TheWindowManager->winFontHeight( comboBox->winGetFont() ); + fontHeight = winFontHeight( comboBox->winGetFont() ); top = title ? (fontHeight + 1):0; bottom = title ? (height - (fontHeight + 1)):height; @@ -2418,7 +2418,7 @@ GameWindow *GameWindowManager::gogoGadgetComboBox( GameWindow *parent, BitSet( winInstData.m_style, GWS_MOUSE_TRACK ); comboBoxData->dropDownButton = - TheWindowManager->gogoGadgetPushButton( comboBox, + gogoGadgetPushButton( comboBox, status | WIN_STATUS_ACTIVE | WIN_STATUS_ENABLED, width - buttonWidth, 0, buttonWidth, height, @@ -2446,7 +2446,7 @@ GameWindow *GameWindowManager::gogoGadgetComboBox( GameWindow *parent, statusTextEntry = status | WIN_STATUS_NO_INPUT ;//| WIN_STATUS_NO_FOCUS; comboBoxData->entryData->drawTextFromStart = TRUE; } - comboBoxData->editBox = TheWindowManager->gogoGadgetTextEntry( comboBox, statusTextEntry , + comboBoxData->editBox = gogoGadgetTextEntry( comboBox, statusTextEntry , 0,0 , width - buttonWidth , height , &winInstData, comboBoxData->entryData, @@ -2468,7 +2468,7 @@ GameWindow *GameWindowManager::gogoGadgetComboBox( GameWindow *parent, BitSet( winInstData.m_style, WIN_STATUS_HIDDEN ); winInstData.m_style |= GWS_SCROLL_LISTBOX; status &= ~(WIN_STATUS_IMAGE); - comboBoxData->listBox = TheWindowManager->gogoGadgetListBox( comboBox, status | WIN_STATUS_ABOVE | WIN_STATUS_ONE_LINE, 0, height, + comboBoxData->listBox = gogoGadgetListBox( comboBox, status | WIN_STATUS_ABOVE | WIN_STATUS_ONE_LINE, 0, height, width, height, &winInstData, comboBoxData->listboxData, winInstData.m_font, FALSE ); @@ -2545,7 +2545,7 @@ GameWindow *GameWindowManager::gogoGadgetProgressBar( GameWindow *parent, } // create the button window - progressBar = TheWindowManager->winCreate( parent, status, + progressBar = winCreate( parent, status, x, y, width, height, GadgetProgressBarSystem, instData ); @@ -2802,29 +2802,29 @@ void GameWindowManager::assignDefaultGadgetLook( GameWindow *gadget, Bool assignVisual ) { UnsignedByte alpha = 255; - static Color red = TheWindowManager->winMakeColor( 255, 0, 0, alpha ); - static Color darkRed = TheWindowManager->winMakeColor( 128, 0, 0, alpha ); - static Color lightRed = TheWindowManager->winMakeColor( 255, 128, 128, alpha ); - static Color green = TheWindowManager->winMakeColor( 0, 255, 0, alpha ); - static Color darkGreen = TheWindowManager->winMakeColor( 0, 128, 0, alpha ); - static Color lightGreen = TheWindowManager->winMakeColor( 128, 255, 128, alpha ); - static Color blue = TheWindowManager->winMakeColor( 0, 0, 255, alpha ); - static Color darkBlue = TheWindowManager->winMakeColor( 0, 0, 128, alpha ); - static Color lightBlue = TheWindowManager->winMakeColor( 128, 128, 255, alpha ); - static Color purple = TheWindowManager->winMakeColor( 255, 0, 255, alpha ); - static Color darkPurple = TheWindowManager->winMakeColor( 128, 0, 128, alpha ); - static Color lightPurple= TheWindowManager->winMakeColor( 255, 128, 255, alpha ); - static Color yellow = TheWindowManager->winMakeColor( 255, 255, 0, alpha ); - static Color darkYellow = TheWindowManager->winMakeColor( 128, 128, 0, alpha ); - static Color lightYellow= TheWindowManager->winMakeColor( 255, 255, 128, alpha ); - static Color cyan = TheWindowManager->winMakeColor( 0, 255, 255, alpha ); - static Color darkCyan = TheWindowManager->winMakeColor( 64, 128, 128, alpha ); - static Color lightCyan = TheWindowManager->winMakeColor( 128, 255, 255, alpha ); - static Color gray = TheWindowManager->winMakeColor( 128, 128, 128, alpha ); - static Color darkGray = TheWindowManager->winMakeColor( 64, 64, 64, alpha ); - static Color lightGray = TheWindowManager->winMakeColor( 192, 192, 192, alpha ); - static Color black = TheWindowManager->winMakeColor( 0, 0, 0, alpha ); - static Color white = TheWindowManager->winMakeColor( 254, 254, 254, alpha ); + static Color red = winMakeColor( 255, 0, 0, alpha ); + static Color darkRed = winMakeColor( 128, 0, 0, alpha ); + static Color lightRed = winMakeColor( 255, 128, 128, alpha ); + static Color green = winMakeColor( 0, 255, 0, alpha ); + static Color darkGreen = winMakeColor( 0, 128, 0, alpha ); + static Color lightGreen = winMakeColor( 128, 255, 128, alpha ); + static Color blue = winMakeColor( 0, 0, 255, alpha ); + static Color darkBlue = winMakeColor( 0, 0, 128, alpha ); + static Color lightBlue = winMakeColor( 128, 128, 255, alpha ); + static Color purple = winMakeColor( 255, 0, 255, alpha ); + static Color darkPurple = winMakeColor( 128, 0, 128, alpha ); + static Color lightPurple= winMakeColor( 255, 128, 255, alpha ); + static Color yellow = winMakeColor( 255, 255, 0, alpha ); + static Color darkYellow = winMakeColor( 128, 128, 0, alpha ); + static Color lightYellow= winMakeColor( 255, 255, 128, alpha ); + static Color cyan = winMakeColor( 0, 255, 255, alpha ); + static Color darkCyan = winMakeColor( 64, 128, 128, alpha ); + static Color lightCyan = winMakeColor( 128, 255, 255, alpha ); + static Color gray = winMakeColor( 128, 128, 128, alpha ); + static Color darkGray = winMakeColor( 64, 64, 64, alpha ); + static Color lightGray = winMakeColor( 192, 192, 192, alpha ); + static Color black = winMakeColor( 0, 0, 0, alpha ); + static Color white = winMakeColor( 254, 254, 254, alpha ); static Color enabledText = white; static Color enabledTextBorder = darkGray; static Color disabledText = darkGray; @@ -2848,13 +2848,13 @@ void GameWindowManager::assignDefaultGadgetLook( GameWindow *gadget, else { if (TheGlobalLanguageData && TheGlobalLanguageData->m_defaultWindowFont.name.isNotEmpty()) - { gadget->winSetFont( TheWindowManager->winFindFont( + { gadget->winSetFont( winFindFont( TheGlobalLanguageData->m_defaultWindowFont.name, TheGlobalLanguageData->m_defaultWindowFont.size, TheGlobalLanguageData->m_defaultWindowFont.bold) ); } else - gadget->winSetFont( TheWindowManager->winFindFont( "Times New Roman", 14, FALSE ) ); + gadget->winSetFont( winFindFont( "Times New Roman", 14, FALSE ) ); } // if we don't want to assign default colors/images get out of here @@ -3676,20 +3676,20 @@ Bool GameWindowManager::initTestGUI( void ) WinInstanceData instData; // make some windows inside each other in the upper left - window = TheWindowManager->winCreate( NULL, statusFlags, 0, 0, 100, 100, NULL, NULL ); + window = winCreate( NULL, statusFlags, 0, 0, 100, 100, NULL, NULL ); window->winSetInputFunc( testGrab ); - window->winSetEnabledColor( 0, TheWindowManager->winMakeColor( 255, 254, 255, 255 ) ); - window->winSetEnabledBorderColor( 0 , TheWindowManager->winMakeColor( 0, 0, 0, 255 ) ); - window = TheWindowManager->winCreate( window, statusFlags, 10, 10, 50, 50, NULL, NULL ); + window->winSetEnabledColor( 0, winMakeColor( 255, 254, 255, 255 ) ); + window->winSetEnabledBorderColor( 0 , winMakeColor( 0, 0, 0, 255 ) ); + window = winCreate( window, statusFlags, 10, 10, 50, 50, NULL, NULL ); window->winSetInputFunc( testGrab ); - window->winSetEnabledColor( 0, TheWindowManager->winMakeColor( 128, 128, 128, 255 ) ); - window->winSetEnabledBorderColor( 0 , TheWindowManager->winMakeColor( 0, 0, 0, 255 ) ); + window->winSetEnabledColor( 0, winMakeColor( 128, 128, 128, 255 ) ); + window->winSetEnabledBorderColor( 0 , winMakeColor( 0, 0, 0, 255 ) ); // make a push button instData.init(); BitSet( instData.m_style, GWS_PUSH_BUTTON | GWS_MOUSE_TRACK ); instData.m_textLabelString = "What Up?"; - window = TheWindowManager->gogoGadgetPushButton( NULL, + window = gogoGadgetPushButton( NULL, WIN_STATUS_ENABLED | WIN_STATUS_IMAGE, 200, 100, 100, 30, @@ -3699,7 +3699,7 @@ Bool GameWindowManager::initTestGUI( void ) instData.init(); BitSet( instData.m_style, GWS_PUSH_BUTTON | GWS_MOUSE_TRACK ); instData.m_textLabelString = "Enabled"; - window = TheWindowManager->gogoGadgetPushButton( NULL, + window = gogoGadgetPushButton( NULL, WIN_STATUS_ENABLED, 330, 100, 100, 30, @@ -3709,7 +3709,7 @@ Bool GameWindowManager::initTestGUI( void ) instData.init(); BitSet( instData.m_style, GWS_PUSH_BUTTON | GWS_MOUSE_TRACK ); instData.m_textLabelString = "Disabled"; - window = TheWindowManager->gogoGadgetPushButton( NULL, + window = gogoGadgetPushButton( NULL, 0, 450, 100, 100, 30, @@ -3719,7 +3719,7 @@ Bool GameWindowManager::initTestGUI( void ) instData.init(); instData.m_style = GWS_CHECK_BOX | GWS_MOUSE_TRACK; instData.m_textLabelString = "Check"; - window = TheWindowManager->gogoGadgetCheckbox( NULL, + window = gogoGadgetCheckbox( NULL, WIN_STATUS_ENABLED | WIN_STATUS_IMAGE, 200, 150, @@ -3730,18 +3730,18 @@ Bool GameWindowManager::initTestGUI( void ) instData.init(); instData.m_style = GWS_CHECK_BOX | GWS_MOUSE_TRACK; instData.m_textLabelString = "Check"; - window = TheWindowManager->gogoGadgetCheckbox( NULL, + window = gogoGadgetCheckbox( NULL, WIN_STATUS_ENABLED, 330, 150, 100, 30, &instData, NULL, TRUE ); // make window to hold radio buttons - window = TheWindowManager->winCreate( NULL, WIN_STATUS_ENABLED | WIN_STATUS_DRAGABLE, + window = winCreate( NULL, WIN_STATUS_ENABLED | WIN_STATUS_DRAGABLE, 200, 200, 250, 45, NULL ); window->winSetInputFunc( testGrab ); - window->winSetEnabledColor( 0, TheWindowManager->winMakeColor( 50, 50, 50, 200 ) ); - window->winSetEnabledBorderColor( 0, TheWindowManager->winMakeColor( 254, 254, 254, 255 ) ); + window->winSetEnabledColor( 0, winMakeColor( 50, 50, 50, 200 ) ); + window->winSetEnabledBorderColor( 0, winMakeColor( 254, 254, 254, 255 ) ); // make a radio button GameWindow *radio; @@ -3750,7 +3750,7 @@ Bool GameWindowManager::initTestGUI( void ) instData.m_style = GWS_RADIO_BUTTON | GWS_MOUSE_TRACK; instData.m_textLabelString = "Mama Said!"; rData.group = 1; - radio = TheWindowManager->gogoGadgetRadioButton( window, + radio = gogoGadgetRadioButton( window, WIN_STATUS_ENABLED | WIN_STATUS_IMAGE, 10, 10, 100, 30, @@ -3761,7 +3761,7 @@ Bool GameWindowManager::initTestGUI( void ) instData.init(); instData.m_style = GWS_RADIO_BUTTON | GWS_MOUSE_TRACK; instData.m_textLabelString = "On the Run"; - radio = TheWindowManager->gogoGadgetRadioButton( window, + radio = gogoGadgetRadioButton( window, WIN_STATUS_ENABLED, 130, 10, 100, 30, @@ -3784,24 +3784,24 @@ Bool GameWindowManager::initTestGUI( void ) listData.columnWidth = NULL; instData.init(); instData.m_style = GWS_SCROLL_LISTBOX | GWS_MOUSE_TRACK; - window = TheWindowManager->gogoGadgetListBox( NULL, + window = gogoGadgetListBox( NULL, WIN_STATUS_ENABLED, 200, 250, 100, 100, &instData, &listData, NULL, TRUE ); GadgetListBoxAddEntryText( window, L"Listbox text", - TheWindowManager->winMakeColor( 255, 255, 255, 255 ), -1, 0 ); + winMakeColor( 255, 255, 255, 255 ), -1, 0 ); GadgetListBoxAddEntryText( window, L"More text", - TheWindowManager->winMakeColor( 105, 105, 255, 255 ), -1, 0 ); + winMakeColor( 105, 105, 255, 255 ), -1, 0 ); GadgetListBoxAddEntryText( window, L"Nothing", - TheWindowManager->winMakeColor( 105, 105, 255, 255 ), -1, 0 ); + winMakeColor( 105, 105, 255, 255 ), -1, 0 ); GadgetListBoxAddEntryText( window, L"Seasons", - TheWindowManager->winMakeColor( 105, 205, 255, 255 ), -1, 0 ); + winMakeColor( 105, 205, 255, 255 ), -1, 0 ); GadgetListBoxAddEntryText( window, L"Misery", - TheWindowManager->winMakeColor( 235, 105, 255, 255 ), -1, 0 ); + winMakeColor( 235, 105, 255, 255 ), -1, 0 ); GadgetListBoxAddEntryText( window, L"Natural", - TheWindowManager->winMakeColor( 105, 205, 45, 255 ), -1, 0 ); + winMakeColor( 105, 205, 45, 255 ), -1, 0 ); window->winSetFont( TheFontLibrary->getFont( "Times New Roman", 12, FALSE ) ); // make a listbox @@ -3817,24 +3817,24 @@ Bool GameWindowManager::initTestGUI( void ) listData.columnWidth = NULL; instData.init(); instData.m_style = GWS_SCROLL_LISTBOX | GWS_MOUSE_TRACK; - window = TheWindowManager->gogoGadgetListBox( NULL, + window = gogoGadgetListBox( NULL, WIN_STATUS_ENABLED | WIN_STATUS_IMAGE, 75, 250, 100, 100, &instData, &listData, NULL, TRUE ); GadgetListBoxAddEntryText( window, L"Listbox text", - TheWindowManager->winMakeColor( 255, 255, 255, 255 ), -1, -1 ); + winMakeColor( 255, 255, 255, 255 ), -1, -1 ); GadgetListBoxAddEntryText( window, L"More text", - TheWindowManager->winMakeColor( 105, 105, 255, 255 ), -1, -1 ); + winMakeColor( 105, 105, 255, 255 ), -1, -1 ); GadgetListBoxAddEntryText( window, L"Nothing", - TheWindowManager->winMakeColor( 105, 105, 255, 255 ), -1, -1 ); + winMakeColor( 105, 105, 255, 255 ), -1, -1 ); GadgetListBoxAddEntryText( window, L"Seasons", - TheWindowManager->winMakeColor( 105, 205, 255, 255 ), -1, -1 ); + winMakeColor( 105, 205, 255, 255 ), -1, -1 ); GadgetListBoxAddEntryText( window, L"Misery", - TheWindowManager->winMakeColor( 235, 105, 255, 255 ), -1, -1 ); + winMakeColor( 235, 105, 255, 255 ), -1, -1 ); GadgetListBoxAddEntryText( window, L"Natural", - TheWindowManager->winMakeColor( 105, 205, 45, 255 ), -1, -1 ); + winMakeColor( 105, 205, 45, 255 ), -1, -1 ); // make a vert slider SliderData sliderData; @@ -3845,7 +3845,7 @@ Bool GameWindowManager::initTestGUI( void ) sliderData.position = 0; instData.init(); instData.m_style = GWS_VERT_SLIDER | GWS_MOUSE_TRACK; - window = TheWindowManager->gogoGadgetSlider( NULL, + window = gogoGadgetSlider( NULL, WIN_STATUS_ENABLED, 360, 250, 11, 100, @@ -3860,7 +3860,7 @@ Bool GameWindowManager::initTestGUI( void ) sliderData.position = 0; instData.init(); instData.m_style = GWS_VERT_SLIDER | GWS_MOUSE_TRACK; - window = TheWindowManager->gogoGadgetSlider( NULL, + window = gogoGadgetSlider( NULL, WIN_STATUS_ENABLED | WIN_STATUS_IMAGE, 400, 250, 11, 100, @@ -3875,7 +3875,7 @@ Bool GameWindowManager::initTestGUI( void ) sliderData.position = 0; instData.init(); instData.m_style = GWS_HORZ_SLIDER | GWS_MOUSE_TRACK; - window = TheWindowManager->gogoGadgetSlider( NULL, + window = gogoGadgetSlider( NULL, WIN_STATUS_ENABLED, 200, 400, 200, 11, @@ -3890,7 +3890,7 @@ Bool GameWindowManager::initTestGUI( void ) sliderData.position = 0; instData.init(); instData.m_style = GWS_HORZ_SLIDER | GWS_MOUSE_TRACK; - window = TheWindowManager->gogoGadgetSlider( NULL, + window = gogoGadgetSlider( NULL, WIN_STATUS_ENABLED | WIN_STATUS_IMAGE, 200, 420, 200, 11, @@ -3900,7 +3900,7 @@ Bool GameWindowManager::initTestGUI( void ) // make a progress bar instData.init(); instData.m_style = GWS_PROGRESS_BAR | GWS_MOUSE_TRACK; - window = TheWindowManager->gogoGadgetProgressBar( NULL, + window = gogoGadgetProgressBar( NULL, WIN_STATUS_ENABLED, 200, 450, 250, 15, @@ -3909,7 +3909,7 @@ Bool GameWindowManager::initTestGUI( void ) // make a progress bar instData.init(); instData.m_style = GWS_PROGRESS_BAR | GWS_MOUSE_TRACK; - window = TheWindowManager->gogoGadgetProgressBar( NULL, + window = gogoGadgetProgressBar( NULL, WIN_STATUS_ENABLED | WIN_STATUS_IMAGE, 200, 470, 250, 15, @@ -3921,7 +3921,7 @@ Bool GameWindowManager::initTestGUI( void ) instData.init(); instData.m_style = GWS_STATIC_TEXT | GWS_MOUSE_TRACK; instData.m_textLabelString = "Centered Static Text"; - window = TheWindowManager->gogoGadgetStaticText( NULL, + window = gogoGadgetStaticText( NULL, WIN_STATUS_ENABLED, 200, 490, 300, 25, @@ -3933,14 +3933,14 @@ Bool GameWindowManager::initTestGUI( void ) instData.init(); instData.m_style = GWS_STATIC_TEXT | GWS_MOUSE_TRACK; instData.m_textLabelString = "Not Centered Static Text"; - window = TheWindowManager->gogoGadgetStaticText( NULL, + window = gogoGadgetStaticText( NULL, WIN_STATUS_ENABLED | WIN_STATUS_IMAGE, 200, 520, 300, 25, &instData, &textData, NULL, TRUE ); - window->winSetEnabledTextColors( TheWindowManager->winMakeColor( 128, 128, 255, 255 ), - TheWindowManager->winMakeColor( 255, 255, 255, 255 ) ); + window->winSetEnabledTextColors( winMakeColor( 128, 128, 255, 255 ), + winMakeColor( 255, 255, 255, 255 ) ); // make some entry text EntryData entryData; @@ -3949,7 +3949,7 @@ Bool GameWindowManager::initTestGUI( void ) instData.init(); instData.m_style = GWS_ENTRY_FIELD | GWS_MOUSE_TRACK; instData.m_textLabelString = "Entry"; - window = TheWindowManager->gogoGadgetTextEntry( NULL, + window = gogoGadgetTextEntry( NULL, WIN_STATUS_ENABLED, 450, 270, 400, 30, @@ -3962,7 +3962,7 @@ Bool GameWindowManager::initTestGUI( void ) instData.init(); instData.m_style = GWS_ENTRY_FIELD | GWS_MOUSE_TRACK; instData.m_textLabelString = "Entry"; - window = TheWindowManager->gogoGadgetTextEntry( NULL, + window = gogoGadgetTextEntry( NULL, WIN_STATUS_ENABLED | WIN_STATUS_IMAGE, 450, 310, 400, 30, diff --git a/Generals/Code/GameEngine/Source/GameClient/GameClient.cpp b/Generals/Code/GameEngine/Source/GameClient/GameClient.cpp index 8f3a55c29c..6dbf2756c0 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GameClient.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GameClient.cpp @@ -1072,7 +1072,7 @@ void GameClient::preloadAssets( TimeOfDay timeOfDay ) draw->preloadAssets( timeOfDay ); // destroy the drawable - TheGameClient->destroyDrawable( draw ); + destroyDrawable( draw ); } @@ -1496,7 +1496,7 @@ void GameClient::xfer( Xfer *xfer ) const ThingTemplate* drawTemplate = draw->getTemplate(); if (drawTemplate->getFinalOverride() != thingTemplate->getFinalOverride()) { - TheGameClient->destroyDrawable( draw ); + destroyDrawable( draw ); draw = TheThingFactory->newDrawable( thingTemplate ); TheGameLogic->bindObjectAndDrawable(object, draw); } diff --git a/Generals/Code/GameEngine/Source/GameClient/InGameUI.cpp b/Generals/Code/GameEngine/Source/GameClient/InGameUI.cpp index 32df1e7dd2..34b0ab6320 100644 --- a/Generals/Code/GameEngine/Source/GameClient/InGameUI.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/InGameUI.cpp @@ -1588,7 +1588,7 @@ void InGameUI::handleBuildPlacements( void ) Int maxObjects = TheGlobalData->m_maxLineBuildObjects; // get the builder object that will be constructing things - Object *builderObject = TheGameLogic->findObjectByID( TheInGameUI->getPendingPlaceSourceObjectID() ); + Object *builderObject = TheGameLogic->findObjectByID( getPendingPlaceSourceObjectID() ); // // given the start/end points in the world and the the angle of the wall, fill @@ -2621,7 +2621,7 @@ void InGameUI::createMouseoverHint( const GameMessage *msg ) TheMouse->resetTooltipDelay(); } - if (m_mouseMode == MOUSEMODE_DEFAULT && !m_isScrolling && !m_isSelecting && !TheInGameUI->getSelectCount() && (TheRecorder->getMode() != RECORDERMODETYPE_PLAYBACK || TheLookAtTranslator->hasMouseMovedRecently())) + if (m_mouseMode == MOUSEMODE_DEFAULT && !m_isScrolling && !m_isSelecting && !getSelectCount() && (TheRecorder->getMode() != RECORDERMODETYPE_PLAYBACK || TheLookAtTranslator->hasMouseMovedRecently())) { if( m_mousedOverDrawableID != INVALID_DRAWABLE_ID ) { @@ -3359,7 +3359,7 @@ void InGameUI::deselectDrawable( Drawable *draw ) //------------------------------------------------------------------------------------------------- void InGameUI::deselectAllDrawables( Bool postMsg ) { - const DrawableList *selected = TheInGameUI->getAllSelectedDrawables(); + const DrawableList *selected = getAllSelectedDrawables(); // loop through all the selected drawables for ( DrawableListCIt it = selected->begin(); it != selected->end(); ) @@ -3369,7 +3369,7 @@ void InGameUI::deselectAllDrawables( Bool postMsg ) Drawable* draw = *it++; // do the deselection - TheInGameUI->deselectDrawable( draw ); + deselectDrawable( draw ); } @@ -4101,38 +4101,38 @@ void InGameUI::displayCantBuildMessage( LegalBuildCode lbc ) //--------------------------------------------------------------------------------------------- case LBC_RESTRICTED_TERRAIN: - TheInGameUI->message( "GUI:CantBuildRestrictedTerrain" ); + message( "GUI:CantBuildRestrictedTerrain" ); break; //--------------------------------------------------------------------------------------------- case LBC_NOT_FLAT_ENOUGH: - TheInGameUI->message( "GUI:CantBuildNotFlatEnough" ); + message( "GUI:CantBuildNotFlatEnough" ); break; //--------------------------------------------------------------------------------------------- case LBC_OBJECTS_IN_THE_WAY: - TheInGameUI->message( "GUI:CantBuildObjectsInTheWay" ); + message( "GUI:CantBuildObjectsInTheWay" ); break; //--------------------------------------------------------------------------------------------- case LBC_TOO_CLOSE_TO_SUPPLIES: - TheInGameUI->message( "GUI:CantBuildTooCloseToSupplies" ); + message( "GUI:CantBuildTooCloseToSupplies" ); break; //--------------------------------------------------------------------------------------------- case LBC_NO_CLEAR_PATH: - TheInGameUI->message( "GUI:CantBuildNoClearPath" ); + message( "GUI:CantBuildNoClearPath" ); break; //--------------------------------------------------------------------------------------------- case LBC_SHROUD: - TheInGameUI->message( "GUI:CantBuildShroud" ); + message( "GUI:CantBuildShroud" ); break; //--------------------------------------------------------------------------------------------- default: - TheInGameUI->message( "GUI:CantBuildThere" ); + message( "GUI:CantBuildThere" ); break; } @@ -4164,7 +4164,7 @@ void InGameUI::militarySubtitle( const AsciiString& label, Int duration ) const int messageTimeout = currLogicFrame + (Int)(((Real)LOGICFRAMES_PER_SECOND * duration)/1000.0f); // disable tooltips until this frame, cause we don't want to collide with the military subtitles. - TheInGameUI->disableTooltipsUntil(messageTimeout); + disableTooltipsUntil(messageTimeout); // calculate where this screen position should be since the position being passed in is based off 8x6 Coord2D multiplyer; @@ -4202,7 +4202,7 @@ void InGameUI::removeMilitarySubtitle( void ) if(!m_militarySubtitle) return; - TheInGameUI->clearTooltipsDisabled(); + clearTooltipsDisabled(); // loop through and free up the display strings for(UnsignedInt i = 0; i <= m_militarySubtitle->currentDisplayString; i ++) @@ -4221,7 +4221,7 @@ void InGameUI::removeMilitarySubtitle( void ) // ------------------------------------------------------------------------------------------------ Bool InGameUI::areSelectedObjectsControllable() const { - const DrawableList *selected = TheInGameUI->getAllSelectedDrawables(); + const DrawableList *selected = getAllSelectedDrawables(); // loop through all the selected drawables const Drawable *draw; @@ -4278,7 +4278,7 @@ CanAttackResult InGameUI::getCanSelectedObjectsAttack( ActionType action, const } // get selected list of drawables - const DrawableList *selected = TheInGameUI->getAllSelectedDrawables(); + const DrawableList *selected = getAllSelectedDrawables(); // set up counters for rule checking Int count = 0; @@ -4367,7 +4367,7 @@ Bool InGameUI::canSelectedObjectsDoAction( ActionType action, const Object *obje } // get selected list of drawables - const DrawableList *selected = TheInGameUI->getAllSelectedDrawables(); + const DrawableList *selected = getAllSelectedDrawables(); // set up counters for rule checking Int count = 0; @@ -4522,7 +4522,7 @@ Bool InGameUI::canSelectedObjectsDoSpecialPower( const CommandButton *command, c if (ignoreSelDraw) tmpList.push_back(ignoreSelDraw); - const DrawableList* selected = (!tmpList.empty()) ? &tmpList : TheInGameUI->getAllSelectedDrawables(); + const DrawableList* selected = (!tmpList.empty()) ? &tmpList : getAllSelectedDrawables(); // set up counters for rule checking Int count = 0; @@ -4588,7 +4588,7 @@ Bool InGameUI::canSelectedObjectsOverrideSpecialPowerDestination( const Coord3D Int qualify = 0; // get selected list of drawables - const DrawableList *selected = TheInGameUI->getAllSelectedDrawables(); + const DrawableList *selected = getAllSelectedDrawables(); // loop through all the selected drawables Drawable *other; @@ -4640,7 +4640,7 @@ Bool InGameUI::canSelectedObjectsEffectivelyUseWeapon( const CommandButton *comm } // get selected list of drawables - const DrawableList *selected = TheInGameUI->getAllSelectedDrawables(); + const DrawableList *selected = getAllSelectedDrawables(); // set up counters for rule checking Int count = 0; @@ -4857,16 +4857,16 @@ Int InGameUI::selectAllUnitsByTypeAcrossScreen(KindOfMaskType mustBeSet, KindOfM Int numSelected = selectAllUnitsByTypeAcrossRegion(®ion, mustBeSet, mustBeClear); if (numSelected == -1) { - UnicodeString message = TheGameText->fetch( "GUI:NothingSelected" ); - TheInGameUI->message( message ); + UnicodeString msgStr = TheGameText->fetch( "GUI:NothingSelected" ); + message( msgStr ); } else if (numSelected == 0) { } else { - UnicodeString message = TheGameText->fetch( "GUI:SelectedAcrossScreen" ); - TheInGameUI->message( message ); + UnicodeString msgStr = TheGameText->fetch( "GUI:SelectedAcrossScreen" ); + message( msgStr ); } return numSelected; } @@ -4891,16 +4891,16 @@ Int InGameUI::selectMatchingAcrossScreen( void ) Int numSelected = selectMatchingAcrossRegion(®ion); if (numSelected == -1) { - UnicodeString message = TheGameText->fetch( "GUI:NothingSelected" ); - TheInGameUI->message( message ); + UnicodeString msgStr = TheGameText->fetch( "GUI:NothingSelected" ); + message( msgStr ); } else if (numSelected == 0) { } else { - UnicodeString message = TheGameText->fetch( "GUI:SelectedAcrossScreen" ); - TheInGameUI->message( message ); + UnicodeString msgStr = TheGameText->fetch( "GUI:SelectedAcrossScreen" ); + message( msgStr ); } return numSelected; } @@ -4912,22 +4912,22 @@ Int InGameUI::selectAllUnitsByTypeAcrossMap(KindOfMaskType mustBeSet, KindOfMask Int numSelected = selectAllUnitsByTypeAcrossRegion(NULL, mustBeSet, mustBeClear); if (numSelected == -1) { - UnicodeString message = TheGameText->fetch( "GUI:NothingSelected" ); - TheInGameUI->message( message ); + UnicodeString msgStr = TheGameText->fetch( "GUI:NothingSelected" ); + message( msgStr ); } else if (numSelected == 0) { - Drawable *draw = TheInGameUI->getFirstSelectedDrawable(); + Drawable *draw = getFirstSelectedDrawable(); if( !draw || !draw->getObject() || !draw->getObject()->isKindOf( KINDOF_STRUCTURE ) ) { - UnicodeString message = TheGameText->fetch( "GUI:SelectedAcrossMap" ); - TheInGameUI->message( message ); + UnicodeString msgStr = TheGameText->fetch( "GUI:SelectedAcrossMap" ); + message( msgStr ); } } else { - UnicodeString message = TheGameText->fetch( "GUI:SelectedAcrossMap" ); - TheInGameUI->message( message ); + UnicodeString msgStr = TheGameText->fetch( "GUI:SelectedAcrossMap" ); + message( msgStr ); } return numSelected; } @@ -4941,22 +4941,22 @@ Int InGameUI::selectMatchingAcrossMap() Int numSelected = selectMatchingAcrossRegion(NULL); if (numSelected == -1) { - UnicodeString message = TheGameText->fetch( "GUI:NothingSelected" ); - TheInGameUI->message( message ); + UnicodeString msgStr = TheGameText->fetch( "GUI:NothingSelected" ); + message( msgStr ); } else if (numSelected == 0) { - Drawable *draw = TheInGameUI->getFirstSelectedDrawable(); + Drawable *draw = getFirstSelectedDrawable(); if( !draw || !draw->getObject() || !draw->getObject()->isKindOf( KINDOF_STRUCTURE ) ) { - UnicodeString message = TheGameText->fetch( "GUI:SelectedAcrossMap" ); - TheInGameUI->message( message ); + UnicodeString msgStr = TheGameText->fetch( "GUI:SelectedAcrossMap" ); + message( msgStr ); } } else { - UnicodeString message = TheGameText->fetch( "GUI:SelectedAcrossMap" ); - TheInGameUI->message( message ); + UnicodeString msgStr = TheGameText->fetch( "GUI:SelectedAcrossMap" ); + message( msgStr ); } return numSelected; } @@ -5578,7 +5578,7 @@ void InGameUI::selectNextIdleWorker( void ) } else { - Drawable *selectedDrawable = TheInGameUI->getFirstSelectedDrawable(); + Drawable *selectedDrawable = getFirstSelectedDrawable(); // TheSuperHackers @tweak Stubbjax 22/07/2025 Idle worker iteration now correctly identifies and // iterates contained idle workers. Previous iteration logic would not go past contained workers, // and was not guaranteed to select top-level containers. diff --git a/Generals/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp b/Generals/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp index 5e4c0e8b4d..4d8cd851e9 100644 --- a/Generals/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp @@ -3057,7 +3057,7 @@ ParticleSystemID ParticleSystemManager::createAttachedParticleSystemID( Object* attachTo, Bool createSlaves ) { - ParticleSystem* pSystem = TheParticleSystemManager->createParticleSystem(sysTemplate, createSlaves); + ParticleSystem* pSystem = createParticleSystem(sysTemplate, createSlaves); if (pSystem && attachTo) pSystem->attachToObject(attachTo); return pSystem ? pSystem->getSystemID() : INVALID_PARTICLE_SYSTEM_ID; diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/AI.cpp index 430028eb38..46ee5001a0 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/AI.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/AI.cpp @@ -707,7 +707,7 @@ Object *AI::findClosestEnemy( const Object *me, Real range, UnsignedInt qualifie Real distSqr = ThePartitionManager->getDistanceSquared(me, theEnemy, FROM_BOUNDINGSPHERE_2D); Real dist = sqrt(distSqr); - Int modifier = dist/TheAI->getAiData()->m_attackPriorityDistanceModifier; + Int modifier = dist/getAiData()->m_attackPriorityDistanceModifier; Int modPriority = curPriority-modifier; if (modPriority < 1) modPriority = 1; diff --git a/Generals/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp b/Generals/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp index 685cd22558..2a1898c62d 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp @@ -2699,7 +2699,7 @@ void TerrainLogic::flattenTerrain(Object *obj) match = true; } if (match) { - totalHeight += TheTerrainLogic->getGroundHeight(testPt.X, testPt.Y); + totalHeight += getGroundHeight(testPt.X, testPt.Y); numSamples++; } } @@ -2710,7 +2710,7 @@ void TerrainLogic::flattenTerrain(Object *obj) // Compare to the height at the building's origin, because setRawMapHeight will only lower, // not raise. jba - Int centerHeight = REAL_TO_INT_FLOOR(TheTerrainLogic->getGroundHeight(pos->x, pos->y)/MAP_HEIGHT_SCALE); + Int centerHeight = REAL_TO_INT_FLOOR(getGroundHeight(pos->x, pos->y)/MAP_HEIGHT_SCALE); if (rawDataHeight>centerHeight) rawDataHeight = centerHeight; for (i=iMin.x; i<=iMax.x; i++) { @@ -2788,7 +2788,7 @@ void TerrainLogic::flattenTerrain(Object *obj) match = true; } if (match) { - totalHeight += TheTerrainLogic->getGroundHeight(testPt.X, testPt.Y); + totalHeight += getGroundHeight(testPt.X, testPt.Y); numSamples++; } } diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp index 9986736965..cabb37d814 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp @@ -2699,7 +2699,7 @@ void PartitionManager::reset() void PartitionManager::shutdown() { m_updatedSinceLastReset = false; - ThePartitionManager->removeAllDirtyModules(); + removeAllDirtyModules(); #ifdef RTS_DEBUG // the above *should* remove all the touched cells (via unRegisterObject), but let's check: @@ -3074,7 +3074,7 @@ CellShroudStatus PartitionManager::getShroudStatusForPlayer(Int playerIndex, con { Int x, y; - ThePartitionManager->worldToCell( loc->x, loc->y, &x, &y ); + worldToCell( loc->x, loc->y, &x, &y ); return getShroudStatusForPlayer( playerIndex, x, y ); } @@ -3085,7 +3085,7 @@ ObjectShroudStatus PartitionManager::getPropShroudStatusForPlayer(Int playerInde { Int x, y; - ThePartitionManager->worldToCell( loc->x - m_cellSize*0.5f, loc->y - m_cellSize*0.5f, &x, &y ); + worldToCell( loc->x - m_cellSize*0.5f, loc->y - m_cellSize*0.5f, &x, &y ); CellShroudStatus cellStat = getShroudStatusForPlayer( playerIndex, x, y ); if (cellStat != getShroudStatusForPlayer( playerIndex, x+1, y )) { @@ -3805,7 +3805,7 @@ Bool PartitionManager::tryPosition( const Coord3D *center, // very small sphere geometry around the point // GeometryInfo geometry( GEOMETRY_SPHERE, TRUE, 5.0f, 5.0f, 5.0f ); - ObjectIterator *iter = ThePartitionManager->iteratePotentialCollisions( &pos, geometry, angle, true ); + ObjectIterator *iter = iteratePotentialCollisions( &pos, geometry, angle, true ); MemoryPoolObjectHolder hold( iter ); // Bool overlap = FALSE; @@ -3985,9 +3985,9 @@ Bool PartitionManager::findPositionAround( const Coord3D *center, void PartitionManager::doShroudReveal(Real centerX, Real centerY, Real radius, PlayerMaskType playerMask) { Int cellCenterX, cellCenterY; - ThePartitionManager->worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); + worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); - Int cellRadius = ThePartitionManager->worldToCellDist(radius); + Int cellRadius = worldToCellDist(radius); if (cellRadius < 1) cellRadius = 1; @@ -4052,9 +4052,9 @@ void PartitionManager::resetPendingUndoShroudRevealQueue() void PartitionManager::undoShroudReveal(Real centerX, Real centerY, Real radius, PlayerMaskType playerMask) { Int cellCenterX, cellCenterY; - ThePartitionManager->worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); + worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); - Int cellRadius = ThePartitionManager->worldToCellDist(radius); + Int cellRadius = worldToCellDist(radius); if (cellRadius < 1) cellRadius = 1; @@ -4089,9 +4089,9 @@ void PartitionManager::queueUndoShroudReveal(Real centerX, Real centerY, Real ra void PartitionManager::doShroudCover(Real centerX, Real centerY, Real radius, PlayerMaskType playerMask) { Int cellCenterX, cellCenterY; - ThePartitionManager->worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); + worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); - Int cellRadius = ThePartitionManager->worldToCellDist(radius); + Int cellRadius = worldToCellDist(radius); if (cellRadius < 1) cellRadius = 1; @@ -4113,9 +4113,9 @@ void PartitionManager::doShroudCover(Real centerX, Real centerY, Real radius, Pl void PartitionManager::undoShroudCover(Real centerX, Real centerY, Real radius, PlayerMaskType playerMask) { Int cellCenterX, cellCenterY; - ThePartitionManager->worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); + worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); - Int cellRadius = ThePartitionManager->worldToCellDist(radius); + Int cellRadius = worldToCellDist(radius); if (cellRadius < 1) cellRadius = 1; @@ -4135,11 +4135,11 @@ void PartitionManager::undoShroudCover(Real centerX, Real centerY, Real radius, void PartitionManager::doThreatAffect( Real centerX, Real centerY, Real radius, UnsignedInt threatVal, PlayerMaskType playerMask) { Int cellCenterX, cellCenterY; - ThePartitionManager->worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); + worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); Real fCellCenterX = INT_TO_REAL(cellCenterX); Real fCellCenterY = INT_TO_REAL(cellCenterY); - Int cellRadius = ThePartitionManager->worldToCellDist(radius); + Int cellRadius = worldToCellDist(radius); if (cellRadius < 1) cellRadius = 1; @@ -4168,11 +4168,11 @@ void PartitionManager::doThreatAffect( Real centerX, Real centerY, Real radius, void PartitionManager::undoThreatAffect( Real centerX, Real centerY, Real radius, UnsignedInt threatVal, PlayerMaskType playerMask) { Int cellCenterX, cellCenterY; - ThePartitionManager->worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); + worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); Real fCellCenterX = INT_TO_REAL(cellCenterX); Real fCellCenterY = INT_TO_REAL(cellCenterY); - Int cellRadius = ThePartitionManager->worldToCellDist(radius); + Int cellRadius = worldToCellDist(radius); if (cellRadius < 1) cellRadius = 1; @@ -4201,11 +4201,11 @@ void PartitionManager::undoThreatAffect( Real centerX, Real centerY, Real radius void PartitionManager::doValueAffect( Real centerX, Real centerY, Real radius, UnsignedInt valueVal, PlayerMaskType playerMask) { Int cellCenterX, cellCenterY; - ThePartitionManager->worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); + worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); Real fCellCenterX = INT_TO_REAL(cellCenterX); Real fCellCenterY = INT_TO_REAL(cellCenterY); - Int cellRadius = ThePartitionManager->worldToCellDist(radius); + Int cellRadius = worldToCellDist(radius); if (cellRadius < 1) cellRadius = 1; @@ -4234,11 +4234,11 @@ void PartitionManager::doValueAffect( Real centerX, Real centerY, Real radius, U void PartitionManager::undoValueAffect( Real centerX, Real centerY, Real radius, UnsignedInt valueVal, PlayerMaskType playerMask) { Int cellCenterX, cellCenterY; - ThePartitionManager->worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); + worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); Real fCellCenterX = INT_TO_REAL(cellCenterX); Real fCellCenterY = INT_TO_REAL(cellCenterY); - Int cellRadius = ThePartitionManager->worldToCellDist(radius); + Int cellRadius = worldToCellDist(radius); if (cellRadius < 1) cellRadius = 1; @@ -4402,7 +4402,7 @@ Int PartitionManager::iterateCellsAlongLine(const Coord3D& pos, const Coord3D& p for (Int curpixel = 0; curpixel <= numpixels; curpixel++) { - PartitionCell* cell = ThePartitionManager->getCellAt(x, y); // might be null if off the edge + PartitionCell* cell = getCellAt(x, y); // might be null if off the edge DEBUG_ASSERTCRASH(cell != NULL, ("off the map")); if (cell) { @@ -4435,7 +4435,7 @@ Int PartitionManager::iterateCellsBreadthFirst(const Coord3D *pos, CellBreadthFi // -1 means error, but we should add a define later for this. Int cellX, cellY; - ThePartitionManager->worldToCell(pos->x, pos->y, &cellX, &cellY); + worldToCell(pos->x, pos->y, &cellX, &cellY); // Note, bool. not Bool, cause bool will cause this to be a bitfield. std::vector bitField; diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp index d625c5c9ce..ff1dbf4ed1 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp @@ -1443,7 +1443,7 @@ WeaponStore::~WeaponStore() //------------------------------------------------------------------------------------------------- void WeaponStore::handleProjectileDetonation(const WeaponTemplate* wt, const Object *source, const Coord3D* pos, WeaponBonusConditionFlags extraBonusFlags) { - Weapon* w = TheWeaponStore->allocateNewWeapon(wt, PRIMARY_WEAPON); + Weapon* w = allocateNewWeapon(wt, PRIMARY_WEAPON); w->loadAmmoNow(source); w->fireProjectileDetonationWeapon(source, pos, extraBonusFlags); deleteInstance(w); @@ -1454,7 +1454,7 @@ void WeaponStore::createAndFireTempWeapon(const WeaponTemplate* wt, const Object { if (wt == NULL) return; - Weapon* w = TheWeaponStore->allocateNewWeapon(wt, PRIMARY_WEAPON); + Weapon* w = allocateNewWeapon(wt, PRIMARY_WEAPON); w->loadAmmoNow(source); w->fireWeapon(source, pos); deleteInstance(w); @@ -1466,7 +1466,7 @@ void WeaponStore::createAndFireTempWeapon(const WeaponTemplate* wt, const Object //CRCDEBUG_LOG(("WeaponStore::createAndFireTempWeapon() for %s", DescribeObject(source))); if (wt == NULL) return; - Weapon* w = TheWeaponStore->allocateNewWeapon(wt, PRIMARY_WEAPON); + Weapon* w = allocateNewWeapon(wt, PRIMARY_WEAPON); w->loadAmmoNow(source); w->fireWeapon(source, target); deleteInstance(w); diff --git a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp index 3430b6352a..5bb04e0817 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp @@ -5830,7 +5830,7 @@ void ScriptEngine::setPriorityThing( ScriptAction *pAction ) AsciiString typeArgument = pAction->getParameter(1)->getString(); // Our argument could be an individual type, or a list name. - const ObjectTypes *types = TheScriptEngine->getObjectTypes(typeArgument); + const ObjectTypes *types = getObjectTypes(typeArgument); if( !types ) { // Lookup failed, so it is just a single type @@ -6379,7 +6379,7 @@ void ScriptEngine::addObjectToCache(Object* pNewObject) if (it->second == NULL) { AsciiString newNameForDead; newNameForDead.format("Reassigning dead object's name '%s' to object (%d) of type '%s'", objName.str(), pNewObject->getID(), pNewObject->getTemplate()->getName().str()); - TheScriptEngine->AppendDebugMessage(newNameForDead, FALSE); + AppendDebugMessage(newNameForDead, FALSE); DEBUG_LOG((newNameForDead.str())); it->second = pNewObject; return; diff --git a/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp index 03b6cfda0f..dbfb226078 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp @@ -1540,8 +1540,8 @@ void GameLogic::startNewGame( Bool saveGame ) Region3D extent; TheTerrainLogic->getExtent( &extent ); - TheGameLogic->setWidth( extent.hi.x - extent.lo.x ); - TheGameLogic->setHeight( extent.hi.y - extent.lo.y ); + setWidth( extent.hi.x - extent.lo.x ); + setHeight( extent.hi.y - extent.lo.y ); // anytime the world's size changes, must reset the partition mgr ThePartitionManager->init(); @@ -2733,7 +2733,7 @@ void GameLogic::popSleepyUpdate() void GameLogic::friend_awakenUpdateModule(Object* obj, UpdateModulePtr u, UnsignedInt whenToWakeUp) { //USE_PERF_TIMER(friend_awakenUpdateModule) - UnsignedInt now = TheGameLogic->getFrame(); + UnsignedInt now = getFrame(); DEBUG_ASSERTCRASH(whenToWakeUp >= now, ("setWakeFrame frame is in the past... are you sure this is what you want?")); if (u == m_curUpdateModule) @@ -3161,7 +3161,7 @@ void GameLogic::update( void ) } // send the current time to the GameClient - UnsignedInt now = TheGameLogic->getFrame(); + UnsignedInt now = getFrame(); TheGameClient->setFrame(now); // update (execute) scripts @@ -3353,7 +3353,7 @@ void GameLogic::preUpdate() Bool pause = TRUE; Bool pauseMusic = FALSE; Bool pauseInput = FALSE; - TheGameLogic->setGamePaused(pause, pauseMusic, pauseInput); + setGamePaused(pause, pauseMusic, pauseInput); } } @@ -3418,7 +3418,7 @@ void GameLogic::registerObject( Object *obj ) // add object to lookup table addObjectToLookupTable( obj ); - UnsignedInt now = TheGameLogic->getFrame(); + UnsignedInt now = getFrame(); if (now == 0) now = 1; for (BehaviorModule** b = obj->getBehaviorModules(); *b; ++b) @@ -4637,7 +4637,7 @@ void GameLogic::loadPostProcess( void ) #ifdef ALLOW_NONSLEEPY_UPDATES m_normalUpdates.clear(); #else - UnsignedInt now = TheGameLogic->getFrame(); + UnsignedInt now = getFrame(); if (now == 0) now = 1; #endif diff --git a/Generals/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp b/Generals/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp index e556457319..aa4af7eb54 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp @@ -311,7 +311,7 @@ void GameLogic::prepareNewGame( GameMode gameMode, GameDifficulty diff, Int rank m_background->bringForward(); } m_background->getFirstWindow()->winClearStatus(WIN_STATUS_IMAGE); - TheGameLogic->setGameMode( gameMode ); + setGameMode( gameMode ); if (!TheGlobalData->m_pendingFile.isEmpty()) { TheWritableGlobalData->m_mapName = TheGlobalData->m_pendingFile; @@ -322,7 +322,7 @@ void GameLogic::prepareNewGame( GameMode gameMode, GameDifficulty diff, Int rank DEBUG_LOG(("GameLogic::prepareNewGame() - m_rankPointsToAddAtGameStart = %d", m_rankPointsToAddAtGameStart)); // If we're about to start a game, hide the shell. - if(!TheGameLogic->isInShellGame()) + if(!isInShellGame()) TheShell->hideShell(); m_startNewGame = FALSE; @@ -457,7 +457,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) #endif } currentlySelectedGroup = NULL; - TheGameLogic->clearGameData(); + clearGameData(); break; } @@ -500,7 +500,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) //--------------------------------------------------------------------------------------------- case GameMessage::MSG_SET_RALLY_POINT: { - Object *obj = TheGameLogic->findObjectByID( msg->getArgument( 0 )->objectID ); + Object *obj = findObjectByID( msg->getArgument( 0 )->objectID ); Coord3D dest = msg->getArgument( 1 )->location; if (obj) { @@ -529,7 +529,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) //--------------------------------------------------------------------------------------------- case GameMessage::MSG_COMBATDROP_AT_OBJECT: { - Object *targetObject = TheGameLogic->findObjectByID( msg->getArgument( 0 )->objectID ); + Object *targetObject = findObjectByID( msg->getArgument( 0 )->objectID ); // issue command for either single object or for selected group if( currentlySelectedGroup ) @@ -581,7 +581,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // Lock the weapon choice to the right weapon, then give an attack command WeaponSlotType weaponSlot = (WeaponSlotType)msg->getArgument( 0 )->integer; - Object *targetObject = TheGameLogic->findObjectByID( msg->getArgument( 1 )->objectID ); + Object *targetObject = findObjectByID( msg->getArgument( 1 )->objectID ); Int maxShotsToFire = msg->getArgument( 2 )->integer; // sanity @@ -654,7 +654,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // check for possible specific source, ignoring selection. ObjectID sourceID = msg->getArgument(2)->objectID; - Object* source = TheGameLogic->findObjectByID(sourceID); + Object* source = findObjectByID(sourceID); if (source != NULL) { AIGroupPtr theGroup = TheAI->createGroup(); @@ -689,14 +689,14 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // Object in way -- if applicable (some specials care, others don't) ObjectID objectID = msg->getArgument( 2 )->objectID; - Object *objectInWay = TheGameLogic->findObjectByID( objectID ); + Object *objectInWay = findObjectByID( objectID ); // Command button options -- special power may care about variance options UnsignedInt options = msg->getArgument( 3 )->integer; // check for possible specific source, ignoring selection. ObjectID sourceID = msg->getArgument(4)->objectID; - Object* source = TheGameLogic->findObjectByID(sourceID); + Object* source = findObjectByID(sourceID); if (source != NULL) { AIGroupPtr theGroup = TheAI->createGroup(); @@ -728,7 +728,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // argument 2 is target object ObjectID targetID = msg->getArgument(1)->objectID; - Object *target = TheGameLogic->findObjectByID( targetID ); + Object *target = findObjectByID( targetID ); if( !target ) { break; @@ -739,7 +739,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // check for possible specific source, ignoring selection. ObjectID sourceID = msg->getArgument(3)->objectID; - Object* source = TheGameLogic->findObjectByID(sourceID); + Object* source = findObjectByID(sourceID); if (source != NULL) { AIGroupPtr theGroup = TheAI->createGroup(); @@ -838,7 +838,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) //--------------------------------------------------------------------------------------------- case GameMessage::MSG_DO_GUARD_OBJECT: { - Object* obj = TheGameLogic->findObjectByID( msg->getArgument( 0 )->objectID ); + Object* obj = findObjectByID( msg->getArgument( 0 )->objectID ); if (!obj) break; @@ -972,7 +972,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) //--------------------------------------------------------------------------------------------- case GameMessage::MSG_ENTER: { - Object *enter = TheGameLogic->findObjectByID( msg->getArgument( 1 )->objectID ); + Object *enter = findObjectByID( msg->getArgument( 1 )->objectID ); // sanity if( enter == NULL ) @@ -991,7 +991,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) //--------------------------------------------------------------------------------------------- case GameMessage::MSG_EXIT: { - Object *objectWantingToExit = TheGameLogic->findObjectByID( msg->getArgument( 0 )->objectID ); + Object *objectWantingToExit = findObjectByID( msg->getArgument( 0 )->objectID ); #if RETAIL_COMPATIBLE_AIGROUP Object *objectContainingExiter = getSingleObjectFromSelection(currentlySelectedGroup); #else @@ -1081,7 +1081,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // -------------------------------------------------------------------------------------------- case GameMessage::MSG_GET_REPAIRED: { - Object *repairDepot = TheGameLogic->findObjectByID( msg->getArgument( 0 )->objectID ); + Object *repairDepot = findObjectByID( msg->getArgument( 0 )->objectID ); // sanity if( repairDepot == NULL ) @@ -1098,7 +1098,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // -------------------------------------------------------------------------------------------- case GameMessage::MSG_DOCK: { - Object *dockBuilding = TheGameLogic->findObjectByID( msg->getArgument( 0 )->objectID ); + Object *dockBuilding = findObjectByID( msg->getArgument( 0 )->objectID ); // sanity if( dockBuilding == NULL ) @@ -1115,7 +1115,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // -------------------------------------------------------------------------------------------- case GameMessage::MSG_GET_HEALED: { - Object *healDest = TheGameLogic->findObjectByID( msg->getArgument( 0 )->objectID ); + Object *healDest = findObjectByID( msg->getArgument( 0 )->objectID ); // sanity if( healDest == NULL ) @@ -1132,7 +1132,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // -------------------------------------------------------------------------------------------- case GameMessage::MSG_DO_REPAIR: { - Object *repairTarget = TheGameLogic->findObjectByID( msg->getArgument( 0 )->objectID ); + Object *repairTarget = findObjectByID( msg->getArgument( 0 )->objectID ); // sanity if( repairTarget == NULL ) @@ -1152,7 +1152,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // -------------------------------------------------------------------------------------------- case GameMessage::MSG_RESUME_CONSTRUCTION: { - Object *constructTarget = TheGameLogic->findObjectByID( msg->getArgument( 0 )->objectID ); + Object *constructTarget = findObjectByID( msg->getArgument( 0 )->objectID ); // sanity if( constructTarget == NULL ) @@ -1180,7 +1180,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) SpecialPowerType spType = (SpecialPowerType)msg->getArgument( 1 )->integer; ObjectID sourceID = msg->getArgument(2)->objectID; - Object* source = TheGameLogic->findObjectByID(sourceID); + Object* source = findObjectByID(sourceID); if (source != NULL) { AIGroupPtr theGroup = TheAI->createGroup(); @@ -1207,7 +1207,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) //--------------------------------------------------------------------------------------------- case GameMessage::MSG_DO_ATTACK_OBJECT: { - Object *enemy = TheGameLogic->findObjectByID( msg->getArgument( 0 )->objectID ); + Object *enemy = findObjectByID( msg->getArgument( 0 )->objectID ); // Check enemy, as it is possible that he died this frame. if (enemy) @@ -1229,7 +1229,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) //--------------------------------------------------------------------------------------------- case GameMessage::MSG_DO_FORCE_ATTACK_OBJECT: { - Object *enemy = TheGameLogic->findObjectByID( msg->getArgument( 0 )->objectID ); + Object *enemy = findObjectByID( msg->getArgument( 0 )->objectID ); // Check enemy, as it is possible that he died this frame. if (enemy) @@ -1565,12 +1565,12 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) Bool firstObject = TRUE; for (Int i = 1; i < msg->getArgumentCount(); ++i) { - Object *obj = TheGameLogic->findObjectByID( msg->getArgument( i )->objectID ); + Object *obj = findObjectByID( msg->getArgument( i )->objectID ); if (!obj) { continue; } - TheGameLogic->selectObject(obj, createNewGroup && firstObject, player->getPlayerMask()); + selectObject(obj, createNewGroup && firstObject, player->getPlayerMask()); firstObject = FALSE; } @@ -1590,12 +1590,12 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) for (Int i = 0; i < msg->getArgumentCount(); ++i) { ObjectID objID = msg->getArgument(i)->objectID; - Object *objToRemove = TheGameLogic->findObjectByID(objID); + Object *objToRemove = findObjectByID(objID); if (!objToRemove) { continue; } - TheGameLogic->deselectObject(objToRemove, player->getPlayerMask()); + deselectObject(objToRemove, player->getPlayerMask()); } break; @@ -1745,7 +1745,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) { if (beacon->getControllingPlayer() == thisPlayer) { - TheGameLogic->destroyObject(beacon); // the owner is telling it to go away. such is life. + destroyObject(beacon); // the owner is telling it to go away. such is life. TheControlBar->markUIDirty(); // check if we should un-grey out the button } diff --git a/Generals/Code/Tools/GUIEdit/Source/EditWindow.cpp b/Generals/Code/Tools/GUIEdit/Source/EditWindow.cpp index 7cb45b9e44..fcef339340 100644 --- a/Generals/Code/Tools/GUIEdit/Source/EditWindow.cpp +++ b/Generals/Code/Tools/GUIEdit/Source/EditWindow.cpp @@ -658,7 +658,7 @@ void EditWindow::mouseEvent( UnsignedInt windowsMessage, // if we have ONE window selected and are close to an anchor corner // to resize it change the cursor to resize cursor // - TheEditWindow->handleResizeAvailable( x, y ); + handleResizeAvailable( x, y ); } @@ -894,7 +894,7 @@ void EditWindow::mouseEvent( UnsignedInt windowsMessage, } // open right click menu - TheEditWindow->openPopupMenu( clickPos.x, clickPos.y ); + openPopupMenu( clickPos.x, clickPos.y ); break; diff --git a/Generals/Code/Tools/GUIEdit/Source/GUIEdit.cpp b/Generals/Code/Tools/GUIEdit/Source/GUIEdit.cpp index e5a350b1a9..2faba87eaf 100644 --- a/Generals/Code/Tools/GUIEdit/Source/GUIEdit.cpp +++ b/Generals/Code/Tools/GUIEdit/Source/GUIEdit.cpp @@ -275,10 +275,10 @@ Bool GUIEdit::validateParentForCreate( GameWindow *parent ) // gadgets are units themselves and should have no user defined // children // - if( parent && TheEditor->windowIsGadget( parent ) ) + if( parent && windowIsGadget( parent ) ) { - MessageBox( TheEditor->getWindowHandle(), + MessageBox( getWindowHandle(), "You cannot make a new window as a child to a GUI Gadget Control", "Illegal Parent", MB_OK ); return FALSE; @@ -717,7 +717,7 @@ void GUIEdit::update( void ) TheMouse->update(); // process the mouse if we're in test mode - if( TheEditor->getMode() == MODE_TEST_RUN ) + if( getMode() == MODE_TEST_RUN ) { // send input through the window system and clear all messages after @@ -762,12 +762,12 @@ Bool GUIEdit::writeConfigFile( const char *filename ) backColor.red, backColor.green, backColor.blue, backColor.alpha ); // grid settings - fprintf( fp, "GRIDRESOLUTION = %d\n", TheEditor->getGridResolution() ); - RGBColorInt *gridColor = TheEditor->getGridColor(); + fprintf( fp, "GRIDRESOLUTION = %d\n", getGridResolution() ); + RGBColorInt *gridColor = getGridColor(); fprintf( fp, "GRIDCOLOR = %d %d %d %d\n", gridColor->red, gridColor->green, gridColor->blue, gridColor->alpha ); - fprintf( fp, "SNAPTOGRID = %d\n", TheEditor->isGridSnapOn() ); - fprintf( fp, "GRIDVISIBLE = %d\n", TheEditor->isGridVisible() ); + fprintf( fp, "SNAPTOGRID = %d\n", isGridSnapOn() ); + fprintf( fp, "GRIDVISIBLE = %d\n", isGridVisible() ); // write hierarchy position and size ICoord2D pos, size; @@ -817,15 +817,15 @@ Bool GUIEdit::readConfigFile( const char *filename ) // grid settings Int intData; fscanf( fp, "GRIDRESOLUTION = %d\n", &intData ); - TheEditor->setGridResolution( intData ); + setGridResolution( intData ); RGBColorInt gridColor; fscanf( fp, "GRIDCOLOR = %d %d %d %d\n", &gridColor.red, &gridColor.green, &gridColor.blue, &gridColor.alpha ); - TheEditor->setGridColor( &gridColor ); + setGridColor( &gridColor ); fscanf( fp, "SNAPTOGRID = %d\n", &intData ); - TheEditor->setGridSnap( intData ); + setGridSnap( intData ); fscanf( fp, "GRIDVISIBLE = %d\n", &intData ); - TheEditor->setGridVisible( intData ); + setGridVisible( intData ); // hierarchy view ICoord2D pos, size; @@ -3446,7 +3446,7 @@ Bool GUIEdit::menuExit( void ) Bool success; // save all our data - success = TheEditor->menuSave(); + success = menuSave(); // // if we were unable to save file ask them if it's still OK to @@ -4000,7 +4000,7 @@ void GUIEdit::notifyNewWindow( GameWindow *window ) //============================================================================= void GUIEdit::deleteSelected( void ) { - Int count = TheEditor->selectionCount(); + Int count = selectionCount(); Int i; GameWindow **deleteList; WindowSelectionEntry *select; @@ -4042,7 +4042,7 @@ void GUIEdit::deleteSelected( void ) //============================================================================= void GUIEdit::bringSelectedToTop( void ) { - Int count = TheEditor->selectionCount(); + Int count = selectionCount(); // no-op if( count == 0 ) @@ -4118,8 +4118,8 @@ void GUIEdit::dragMoveSelectedWindows( ICoord2D *dragOrigin, moveLoc.y = origin.y + (dragDest->y - dragOrigin->y); // snap move location to grid if on - if( (TheEditor->getMode() == MODE_DRAG_MOVE) && TheEditor->isGridSnapOn() ) - TheEditor->gridSnapLocation( &moveLoc, &moveLoc ); + if( (getMode() == MODE_DRAG_MOVE) && isGridSnapOn() ) + gridSnapLocation( &moveLoc, &moveLoc ); // kee the location legal computeSafeLocation( window, moveLoc.x, moveLoc.y, &safeLoc.x, &safeLoc.y ); @@ -4523,7 +4523,7 @@ void GUIEdit::moveWindowTo( GameWindow *window, Int x, Int y ) window->winSetPosition( x, y ); // we've now made a change - TheEditor->setUnsaved( TRUE ); + setUnsaved( TRUE ); } diff --git a/Generals/Code/Tools/GUIEdit/Source/HierarchyView.cpp b/Generals/Code/Tools/GUIEdit/Source/HierarchyView.cpp index 45904e7c54..c28bdbb1bb 100644 --- a/Generals/Code/Tools/GUIEdit/Source/HierarchyView.cpp +++ b/Generals/Code/Tools/GUIEdit/Source/HierarchyView.cpp @@ -1211,7 +1211,7 @@ HTREEITEM HierarchyView::treePointToItem( Int x, Int y ) hitTest.pt.y = y; hitTest.hItem = NULL; hitTest.flags = TVHT_ONITEM; - return TreeView_HitTest( TheHierarchyView->getTreeHandle(), &hitTest ); + return TreeView_HitTest( getTreeHandle(), &hitTest ); } diff --git a/Generals/Code/Tools/GUIEdit/Source/Save.cpp b/Generals/Code/Tools/GUIEdit/Source/Save.cpp index ad880c3211..ecac794fd7 100644 --- a/Generals/Code/Tools/GUIEdit/Source/Save.cpp +++ b/Generals/Code/Tools/GUIEdit/Source/Save.cpp @@ -1124,7 +1124,7 @@ void GUIEdit::validateNames( GameWindow *root, char *filename, Bool *valid ) } // check for a duplicate filename - if( TheEditor->isNameDuplicate( TheWindowManager->winGetWindowList(), + if( isNameDuplicate( TheWindowManager->winGetWindowList(), root, instData->m_decoratedNameString ) ) { @@ -1228,7 +1228,7 @@ Bool GUIEdit::saveData( char *filePathAndFilename, char *filename ) if( valid == FALSE ) { - MessageBox( TheEditor->getWindowHandle(), offendingNames, "Window Name Error", MB_OK ); + MessageBox( getWindowHandle(), offendingNames, "Window Name Error", MB_OK ); return FALSE; } diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h index 010418a47c..627f5494d5 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h @@ -1358,7 +1358,7 @@ class PartitionManager : public SubsystemInterface, public Snapshot void getCellCenterPos(Int x, Int y, Real& xx, Real& yy); // find the cell that covers the world coords (wx,wy) and return its coords. - void worldToCell(Real wx, Real wy, Int *cx, Int *cy); + void worldToCell(Real wx, Real wy, Int *cx, Int *cy) const; // given a distance in world coords, return the number of cells needed to cover that distance (rounding up) Int worldToCellDist(Real w); @@ -1531,7 +1531,7 @@ class PartitionManager : public SubsystemInterface, public Snapshot }; // ----------------------------------------------------------------------------- -inline void PartitionManager::worldToCell(Real wx, Real wy, Int *cx, Int *cy) +inline void PartitionManager::worldToCell(Real wx, Real wy, Int *cx, Int *cy) const { *cx = REAL_TO_INT_FLOOR((wx - m_worldExtents.lo.x) * m_cellSizeInv); *cy = REAL_TO_INT_FLOOR((wy - m_worldExtents.lo.y) * m_cellSizeInv); diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp index 8da2880226..32808fab43 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp @@ -1155,7 +1155,7 @@ void GlobalData::reset( void ) { // get next instance - GlobalData* next = TheWritableGlobalData->m_next; + GlobalData* next = m_next; // delete the head of the global data list (the latest override) delete TheWritableGlobalData; diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp index b8add65553..87a5934f40 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp @@ -636,7 +636,7 @@ SaveCode GameState::missionSave( void ) desc.format( format, TheGameText->fetch( campaign->m_campaignNameLabel ).str(), missionNumber ); // do an automatic mission save - return TheGameState->saveGame( "", desc, SAVE_FILE_TYPE_MISSION ); + return saveGame( "", desc, SAVE_FILE_TYPE_MISSION ); } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp index c6f3972b40..6eb9066516 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp @@ -189,9 +189,9 @@ void ControlBar::populatePurchaseScience( Player* player ) player->getPlayerTemplate()->getPurchaseScienceCommandSetRank3().isEmpty() || player->getPlayerTemplate()->getPurchaseScienceCommandSetRank8().isEmpty()) return; - commandSet1 = TheControlBar->findCommandSet(player->getPlayerTemplate()->getPurchaseScienceCommandSetRank1()); // TEMP WILL CHANGE TO PROPER WAY ONCE WORKING - commandSet3 = TheControlBar->findCommandSet(player->getPlayerTemplate()->getPurchaseScienceCommandSetRank3()); // TEMP WILL CHANGE TO PROPER WAY ONCE WORKING - commandSet8 = TheControlBar->findCommandSet(player->getPlayerTemplate()->getPurchaseScienceCommandSetRank8()); // TEMP WILL CHANGE TO PROPER WAY ONCE WORKING + commandSet1 = findCommandSet(player->getPlayerTemplate()->getPurchaseScienceCommandSetRank1()); // TEMP WILL CHANGE TO PROPER WAY ONCE WORKING + commandSet3 = findCommandSet(player->getPlayerTemplate()->getPurchaseScienceCommandSetRank3()); // TEMP WILL CHANGE TO PROPER WAY ONCE WORKING + commandSet8 = findCommandSet(player->getPlayerTemplate()->getPurchaseScienceCommandSetRank8()); // TEMP WILL CHANGE TO PROPER WAY ONCE WORKING for( i = 0; i < MAX_PURCHASE_SCIENCE_RANK_1; i++ ) m_sciencePurchaseWindowsRank1[i]->winHide(TRUE); @@ -2737,7 +2737,7 @@ void ControlBar::showRallyPoint(const Coord3D* loc) marker->setOrientation(TheGlobalData->m_downwindAngle); // To blow down wind -- ML // set the marker colors to that of the local player - Player* player = TheControlBar->getCurrentlyViewedPlayer(); + Player* player = getCurrentlyViewedPlayer(); if (player) { if (TheGlobalData->m_timeOfDay == TIME_OF_DAY_NIGHT) @@ -3299,7 +3299,7 @@ void ControlBar::populateSpecialPowerShortcut( Player *player) // get command set if(player->getPlayerTemplate()->getSpecialPowerShortcutCommandSet().isEmpty() ) return; - commandSet = TheControlBar->findCommandSet(player->getPlayerTemplate()->getSpecialPowerShortcutCommandSet()); // TEMP WILL CHANGE TO PROPER WAY ONCE WORKING + commandSet = findCommandSet(player->getPlayerTemplate()->getSpecialPowerShortcutCommandSet()); // TEMP WILL CHANGE TO PROPER WAY ONCE WORKING if(!commandSet) return; // populate the button with commands defined @@ -3403,9 +3403,9 @@ void ControlBar::populateSpecialPowerShortcut( Player *player) { continue; } - commandSet1 = TheControlBar->findCommandSet( player->getPlayerTemplate()->getPurchaseScienceCommandSetRank1() ); - commandSet3 = TheControlBar->findCommandSet( player->getPlayerTemplate()->getPurchaseScienceCommandSetRank3() ); - commandSet8 = TheControlBar->findCommandSet( player->getPlayerTemplate()->getPurchaseScienceCommandSetRank8() ); + commandSet1 = findCommandSet( player->getPlayerTemplate()->getPurchaseScienceCommandSetRank1() ); + commandSet3 = findCommandSet( player->getPlayerTemplate()->getPurchaseScienceCommandSetRank3() ); + commandSet8 = findCommandSet( player->getPlayerTemplate()->getPurchaseScienceCommandSetRank8() ); if( !commandSet1 || !commandSet3 || !commandSet8 ) { @@ -3617,7 +3617,7 @@ void ControlBar::updateSpecialPowerShortcut( void ) { //Ugh... hacky. //Look for a command button for a special power and if so, then get the command availability for it. - const CommandSet *commandSet = TheControlBar->findCommandSet( obj->getCommandSetString() ); + const CommandSet *commandSet = findCommandSet( obj->getCommandSetString() ); if( commandSet ) { for( Int commandIndex = 0; commandIndex < MAX_COMMANDS_PER_SET; commandIndex++ ) diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp index d76112978d..ca67c21b7e 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp @@ -271,7 +271,7 @@ void ControlBar::populateCommand( Object *obj ) resetBuildQueueData(); // get command set - commandSet = TheControlBar->findCommandSet( obj->getCommandSetString() ); + commandSet = findCommandSet( obj->getCommandSetString() ); // if no command set match is found hide all the buttons if( commandSet == NULL ) @@ -396,9 +396,9 @@ void ControlBar::populateCommand( Object *obj ) { continue; } - commandSet1 = TheControlBar->findCommandSet( player->getPlayerTemplate()->getPurchaseScienceCommandSetRank1() ); - commandSet3 = TheControlBar->findCommandSet( player->getPlayerTemplate()->getPurchaseScienceCommandSetRank3() ); - commandSet8 = TheControlBar->findCommandSet( player->getPlayerTemplate()->getPurchaseScienceCommandSetRank8() ); + commandSet1 = findCommandSet( player->getPlayerTemplate()->getPurchaseScienceCommandSetRank1() ); + commandSet3 = findCommandSet( player->getPlayerTemplate()->getPurchaseScienceCommandSetRank3() ); + commandSet8 = findCommandSet( player->getPlayerTemplate()->getPurchaseScienceCommandSetRank8() ); if( !commandSet1 || !commandSet3 || !commandSet8 ) { diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp index dd1278d3bf..37261a151d 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp @@ -162,7 +162,7 @@ CBCommandStatus ControlBar::processCommandUI( GameWindow *control, // if the button is flashing, tell it to stop flashing commandButton->setFlashCount(0); - TheControlBar->setFlash( FALSE ); + setFlash( FALSE ); if( commandButton->getCommandType() != GUI_COMMAND_EXIT_CONTAINER ) { diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp index 8d2659db83..3619dd01bb 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp @@ -567,7 +567,7 @@ void ControlBar::populateBuildTooltipLayout( const CommandButton *commandButton, name = TheGameText->fetch("CONTROLBAR:Power"); descrip = TheGameText->fetch("CONTROLBAR:PowerDescription"); - Player* playerToDisplay = TheControlBar->getCurrentlyViewedPlayer(); + Player* playerToDisplay = getCurrentlyViewedPlayer(); if( playerToDisplay && playerToDisplay->getEnergy() ) { @@ -656,7 +656,7 @@ void ControlBar::populateBuildTooltipLayout( const CommandButton *commandButton, { return; } - TheControlBar->getBackgroundMarkerPos(&basePos.x, &basePos.y); + getBackgroundMarkerPos(&basePos.x, &basePos.y); ICoord2D curPos, offset; marker->winGetScreenPosition(&curPos.x,&curPos.y); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp index 197fdd05ec..bbe4bb38b9 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp @@ -1584,7 +1584,7 @@ void GameWindowManager::winSetLoneWindow( GameWindow *window ) if( m_loneWindow == window ) return; if( m_loneWindow ) - TheWindowManager->winSendSystemMsg( m_loneWindow, GGM_CLOSE, 0, 0 ); + winSendSystemMsg( m_loneWindow, GGM_CLOSE, 0, 0 ); m_loneWindow = window; } @@ -1633,10 +1633,10 @@ GameWindow *GameWindowManager::gogoMessageBox(Int x, Int y, Int width, Int heigh tempName = menuName; tempName.concat("MessageBoxParent"); - parent = TheWindowManager->winGetWindowFromId(trueParent, TheNameKeyGenerator->nameToKey( tempName )); - TheWindowManager->winSetModal( trueParent ); - TheWindowManager->winSetFocus( NULL ); // make sure we lose focus from other windows even if we refuse focus ourselves - TheWindowManager->winSetFocus( parent ); + parent = winGetWindowFromId(trueParent, TheNameKeyGenerator->nameToKey( tempName )); + winSetModal( trueParent ); + winSetFocus( NULL ); // make sure we lose focus from other windows even if we refuse focus ourselves + winSetFocus( parent ); // If the user wants the size to be different then the default float ratioX, ratioY = 1; @@ -1680,25 +1680,25 @@ GameWindow *GameWindowManager::gogoMessageBox(Int x, Int y, Int width, Int heigh tempName = menuName; tempName.concat("ButtonOk"); buttonOkID = TheNameKeyGenerator->nameToKey( tempName ); - GameWindow *buttonOk = TheWindowManager->winGetWindowFromId(parent, buttonOkID); + GameWindow *buttonOk = winGetWindowFromId(parent, buttonOkID); buttonOk->winGetPosition(&buttonX[0], &buttonY[0]); tempName = menuName; tempName.concat("ButtonYes"); NameKeyType buttonYesID = TheNameKeyGenerator->nameToKey( tempName ); - GameWindow *buttonYes = TheWindowManager->winGetWindowFromId(parent, buttonYesID); + GameWindow *buttonYes = winGetWindowFromId(parent, buttonYesID); //buttonNo in the second position tempName = menuName; tempName.concat("ButtonNo"); NameKeyType buttonNoID = TheNameKeyGenerator->nameToKey(tempName); - GameWindow *buttonNo = TheWindowManager->winGetWindowFromId(parent, buttonNoID); + GameWindow *buttonNo = winGetWindowFromId(parent, buttonNoID); buttonNo->winGetPosition(&buttonX[1], &buttonY[1]); //and buttonCancel in the third tempName = menuName; tempName.concat("ButtonCancel"); NameKeyType buttonCancelID = TheNameKeyGenerator->nameToKey( tempName ); - GameWindow *buttonCancel = TheWindowManager->winGetWindowFromId(parent, buttonCancelID); + GameWindow *buttonCancel = winGetWindowFromId(parent, buttonCancelID); buttonCancel->winGetPosition(&buttonX[2], &buttonY[2]); //we shouldn't have button OK and Yes on the same dialog @@ -1745,12 +1745,12 @@ GameWindow *GameWindowManager::gogoMessageBox(Int x, Int y, Int width, Int heigh tempName = menuName; tempName.concat("StaticTextTitle"); NameKeyType staticTextTitleID = TheNameKeyGenerator->nameToKey( tempName ); - GameWindow *staticTextTitle = TheWindowManager->winGetWindowFromId(parent, staticTextTitleID); + GameWindow *staticTextTitle = winGetWindowFromId(parent, staticTextTitleID); GadgetStaticTextSetText(staticTextTitle,titleString); tempName = menuName; tempName.concat("StaticTextMessage"); NameKeyType staticTextMessageID = TheNameKeyGenerator->nameToKey( tempName ); - GameWindow *staticTextMessage = TheWindowManager->winGetWindowFromId(parent, staticTextMessageID); + GameWindow *staticTextMessage = winGetWindowFromId(parent, staticTextMessageID); GadgetStaticTextSetText(staticTextMessage,bodyString); // create a structure that will pass the functions to @@ -1794,7 +1794,7 @@ GameWindow *GameWindowManager::gogoGadgetPushButton( GameWindow *parent, } // create the button window - button = TheWindowManager->winCreate( parent, status, + button = winCreate( parent, status, x, y, width, height, GadgetPushButtonSystem, instData ); @@ -1862,7 +1862,7 @@ GameWindow *GameWindowManager::gogoGadgetCheckbox( GameWindow *parent, } // create the button window - checkbox = TheWindowManager->winCreate( parent, status, + checkbox = winCreate( parent, status, x, y, width, height, GadgetCheckBoxSystem, instData ); @@ -1929,7 +1929,7 @@ GameWindow *GameWindowManager::gogoGadgetRadioButton( GameWindow *parent, } // create the button window - radioButton = TheWindowManager->winCreate( parent, status, + radioButton = winCreate( parent, status, x, y, width, height, GadgetRadioButtonSystem, instData ); @@ -2001,7 +2001,7 @@ GameWindow *GameWindowManager::gogoGadgetTabControl( GameWindow *parent, } // create the tab control window - tabControl = TheWindowManager->winCreate( parent, status, + tabControl = winCreate( parent, status, x, y, width, height, GadgetTabControlSystem, instData ); @@ -2395,7 +2395,7 @@ GameWindow *GameWindowManager::gogoGadgetComboBox( GameWindow *parent, // remove unwanted status bits. status &= ~(WIN_STATUS_BORDER | WIN_STATUS_HIDDEN); - fontHeight = TheWindowManager->winFontHeight( comboBox->winGetFont() ); + fontHeight = winFontHeight( comboBox->winGetFont() ); top = title ? (fontHeight + 1):0; bottom = title ? (height - (fontHeight + 1)):height; @@ -2418,7 +2418,7 @@ GameWindow *GameWindowManager::gogoGadgetComboBox( GameWindow *parent, BitSet( winInstData.m_style, GWS_MOUSE_TRACK ); comboBoxData->dropDownButton = - TheWindowManager->gogoGadgetPushButton( comboBox, + gogoGadgetPushButton( comboBox, status | WIN_STATUS_ACTIVE | WIN_STATUS_ENABLED, width - buttonWidth, 0, buttonWidth, height, @@ -2446,7 +2446,7 @@ GameWindow *GameWindowManager::gogoGadgetComboBox( GameWindow *parent, statusTextEntry = status | WIN_STATUS_NO_INPUT ;//| WIN_STATUS_NO_FOCUS; comboBoxData->entryData->drawTextFromStart = TRUE; } - comboBoxData->editBox = TheWindowManager->gogoGadgetTextEntry( comboBox, statusTextEntry , + comboBoxData->editBox = gogoGadgetTextEntry( comboBox, statusTextEntry , 0,0 , width - buttonWidth , height , &winInstData, comboBoxData->entryData, @@ -2468,7 +2468,7 @@ GameWindow *GameWindowManager::gogoGadgetComboBox( GameWindow *parent, BitSet( winInstData.m_style, WIN_STATUS_HIDDEN ); winInstData.m_style |= GWS_SCROLL_LISTBOX; status &= ~(WIN_STATUS_IMAGE); - comboBoxData->listBox = TheWindowManager->gogoGadgetListBox( comboBox, status | WIN_STATUS_ABOVE | WIN_STATUS_ONE_LINE, 0, height, + comboBoxData->listBox = gogoGadgetListBox( comboBox, status | WIN_STATUS_ABOVE | WIN_STATUS_ONE_LINE, 0, height, width, height, &winInstData, comboBoxData->listboxData, winInstData.m_font, FALSE ); @@ -2545,7 +2545,7 @@ GameWindow *GameWindowManager::gogoGadgetProgressBar( GameWindow *parent, } // create the button window - progressBar = TheWindowManager->winCreate( parent, status, + progressBar = winCreate( parent, status, x, y, width, height, GadgetProgressBarSystem, instData ); @@ -2802,29 +2802,29 @@ void GameWindowManager::assignDefaultGadgetLook( GameWindow *gadget, Bool assignVisual ) { UnsignedByte alpha = 255; - static Color red = TheWindowManager->winMakeColor( 255, 0, 0, alpha ); - static Color darkRed = TheWindowManager->winMakeColor( 128, 0, 0, alpha ); - static Color lightRed = TheWindowManager->winMakeColor( 255, 128, 128, alpha ); - static Color green = TheWindowManager->winMakeColor( 0, 255, 0, alpha ); - static Color darkGreen = TheWindowManager->winMakeColor( 0, 128, 0, alpha ); - static Color lightGreen = TheWindowManager->winMakeColor( 128, 255, 128, alpha ); - static Color blue = TheWindowManager->winMakeColor( 0, 0, 255, alpha ); - static Color darkBlue = TheWindowManager->winMakeColor( 0, 0, 128, alpha ); - static Color lightBlue = TheWindowManager->winMakeColor( 128, 128, 255, alpha ); - static Color purple = TheWindowManager->winMakeColor( 255, 0, 255, alpha ); - static Color darkPurple = TheWindowManager->winMakeColor( 128, 0, 128, alpha ); - static Color lightPurple= TheWindowManager->winMakeColor( 255, 128, 255, alpha ); - static Color yellow = TheWindowManager->winMakeColor( 255, 255, 0, alpha ); - static Color darkYellow = TheWindowManager->winMakeColor( 128, 128, 0, alpha ); - static Color lightYellow= TheWindowManager->winMakeColor( 255, 255, 128, alpha ); - static Color cyan = TheWindowManager->winMakeColor( 0, 255, 255, alpha ); - static Color darkCyan = TheWindowManager->winMakeColor( 64, 128, 128, alpha ); - static Color lightCyan = TheWindowManager->winMakeColor( 128, 255, 255, alpha ); - static Color gray = TheWindowManager->winMakeColor( 128, 128, 128, alpha ); - static Color darkGray = TheWindowManager->winMakeColor( 64, 64, 64, alpha ); - static Color lightGray = TheWindowManager->winMakeColor( 192, 192, 192, alpha ); - static Color black = TheWindowManager->winMakeColor( 0, 0, 0, alpha ); - static Color white = TheWindowManager->winMakeColor( 254, 254, 254, alpha ); + static Color red = winMakeColor( 255, 0, 0, alpha ); + static Color darkRed = winMakeColor( 128, 0, 0, alpha ); + static Color lightRed = winMakeColor( 255, 128, 128, alpha ); + static Color green = winMakeColor( 0, 255, 0, alpha ); + static Color darkGreen = winMakeColor( 0, 128, 0, alpha ); + static Color lightGreen = winMakeColor( 128, 255, 128, alpha ); + static Color blue = winMakeColor( 0, 0, 255, alpha ); + static Color darkBlue = winMakeColor( 0, 0, 128, alpha ); + static Color lightBlue = winMakeColor( 128, 128, 255, alpha ); + static Color purple = winMakeColor( 255, 0, 255, alpha ); + static Color darkPurple = winMakeColor( 128, 0, 128, alpha ); + static Color lightPurple= winMakeColor( 255, 128, 255, alpha ); + static Color yellow = winMakeColor( 255, 255, 0, alpha ); + static Color darkYellow = winMakeColor( 128, 128, 0, alpha ); + static Color lightYellow= winMakeColor( 255, 255, 128, alpha ); + static Color cyan = winMakeColor( 0, 255, 255, alpha ); + static Color darkCyan = winMakeColor( 64, 128, 128, alpha ); + static Color lightCyan = winMakeColor( 128, 255, 255, alpha ); + static Color gray = winMakeColor( 128, 128, 128, alpha ); + static Color darkGray = winMakeColor( 64, 64, 64, alpha ); + static Color lightGray = winMakeColor( 192, 192, 192, alpha ); + static Color black = winMakeColor( 0, 0, 0, alpha ); + static Color white = winMakeColor( 254, 254, 254, alpha ); static Color enabledText = white; static Color enabledTextBorder = darkGray; static Color disabledText = darkGray; @@ -2848,13 +2848,13 @@ void GameWindowManager::assignDefaultGadgetLook( GameWindow *gadget, else { if (TheGlobalLanguageData && TheGlobalLanguageData->m_defaultWindowFont.name.isNotEmpty()) - { gadget->winSetFont( TheWindowManager->winFindFont( + { gadget->winSetFont( winFindFont( TheGlobalLanguageData->m_defaultWindowFont.name, TheGlobalLanguageData->m_defaultWindowFont.size, TheGlobalLanguageData->m_defaultWindowFont.bold) ); } else - gadget->winSetFont( TheWindowManager->winFindFont( "Times New Roman", 14, FALSE ) ); + gadget->winSetFont( winFindFont( "Times New Roman", 14, FALSE ) ); } // if we don't want to assign default colors/images get out of here @@ -3676,20 +3676,20 @@ Bool GameWindowManager::initTestGUI( void ) WinInstanceData instData; // make some windows inside each other in the upper left - window = TheWindowManager->winCreate( NULL, statusFlags, 0, 0, 100, 100, NULL, NULL ); + window = winCreate( NULL, statusFlags, 0, 0, 100, 100, NULL, NULL ); window->winSetInputFunc( testGrab ); - window->winSetEnabledColor( 0, TheWindowManager->winMakeColor( 255, 254, 255, 255 ) ); - window->winSetEnabledBorderColor( 0 , TheWindowManager->winMakeColor( 0, 0, 0, 255 ) ); - window = TheWindowManager->winCreate( window, statusFlags, 10, 10, 50, 50, NULL, NULL ); + window->winSetEnabledColor( 0, winMakeColor( 255, 254, 255, 255 ) ); + window->winSetEnabledBorderColor( 0 , winMakeColor( 0, 0, 0, 255 ) ); + window = winCreate( window, statusFlags, 10, 10, 50, 50, NULL, NULL ); window->winSetInputFunc( testGrab ); - window->winSetEnabledColor( 0, TheWindowManager->winMakeColor( 128, 128, 128, 255 ) ); - window->winSetEnabledBorderColor( 0 , TheWindowManager->winMakeColor( 0, 0, 0, 255 ) ); + window->winSetEnabledColor( 0, winMakeColor( 128, 128, 128, 255 ) ); + window->winSetEnabledBorderColor( 0 , winMakeColor( 0, 0, 0, 255 ) ); // make a push button instData.init(); BitSet( instData.m_style, GWS_PUSH_BUTTON | GWS_MOUSE_TRACK ); instData.m_textLabelString = "What Up?"; - window = TheWindowManager->gogoGadgetPushButton( NULL, + window = gogoGadgetPushButton( NULL, WIN_STATUS_ENABLED | WIN_STATUS_IMAGE, 200, 100, 100, 30, @@ -3699,7 +3699,7 @@ Bool GameWindowManager::initTestGUI( void ) instData.init(); BitSet( instData.m_style, GWS_PUSH_BUTTON | GWS_MOUSE_TRACK ); instData.m_textLabelString = "Enabled"; - window = TheWindowManager->gogoGadgetPushButton( NULL, + window = gogoGadgetPushButton( NULL, WIN_STATUS_ENABLED, 330, 100, 100, 30, @@ -3709,7 +3709,7 @@ Bool GameWindowManager::initTestGUI( void ) instData.init(); BitSet( instData.m_style, GWS_PUSH_BUTTON | GWS_MOUSE_TRACK ); instData.m_textLabelString = "Disabled"; - window = TheWindowManager->gogoGadgetPushButton( NULL, + window = gogoGadgetPushButton( NULL, 0, 450, 100, 100, 30, @@ -3719,7 +3719,7 @@ Bool GameWindowManager::initTestGUI( void ) instData.init(); instData.m_style = GWS_CHECK_BOX | GWS_MOUSE_TRACK; instData.m_textLabelString = "Check"; - window = TheWindowManager->gogoGadgetCheckbox( NULL, + window = gogoGadgetCheckbox( NULL, WIN_STATUS_ENABLED | WIN_STATUS_IMAGE, 200, 150, @@ -3730,18 +3730,18 @@ Bool GameWindowManager::initTestGUI( void ) instData.init(); instData.m_style = GWS_CHECK_BOX | GWS_MOUSE_TRACK; instData.m_textLabelString = "Check"; - window = TheWindowManager->gogoGadgetCheckbox( NULL, + window = gogoGadgetCheckbox( NULL, WIN_STATUS_ENABLED, 330, 150, 100, 30, &instData, NULL, TRUE ); // make window to hold radio buttons - window = TheWindowManager->winCreate( NULL, WIN_STATUS_ENABLED | WIN_STATUS_DRAGABLE, + window = winCreate( NULL, WIN_STATUS_ENABLED | WIN_STATUS_DRAGABLE, 200, 200, 250, 45, NULL ); window->winSetInputFunc( testGrab ); - window->winSetEnabledColor( 0, TheWindowManager->winMakeColor( 50, 50, 50, 200 ) ); - window->winSetEnabledBorderColor( 0, TheWindowManager->winMakeColor( 254, 254, 254, 255 ) ); + window->winSetEnabledColor( 0, winMakeColor( 50, 50, 50, 200 ) ); + window->winSetEnabledBorderColor( 0, winMakeColor( 254, 254, 254, 255 ) ); // make a radio button GameWindow *radio; @@ -3750,7 +3750,7 @@ Bool GameWindowManager::initTestGUI( void ) instData.m_style = GWS_RADIO_BUTTON | GWS_MOUSE_TRACK; instData.m_textLabelString = "Mama Said!"; rData.group = 1; - radio = TheWindowManager->gogoGadgetRadioButton( window, + radio = gogoGadgetRadioButton( window, WIN_STATUS_ENABLED | WIN_STATUS_IMAGE, 10, 10, 100, 30, @@ -3761,7 +3761,7 @@ Bool GameWindowManager::initTestGUI( void ) instData.init(); instData.m_style = GWS_RADIO_BUTTON | GWS_MOUSE_TRACK; instData.m_textLabelString = "On the Run"; - radio = TheWindowManager->gogoGadgetRadioButton( window, + radio = gogoGadgetRadioButton( window, WIN_STATUS_ENABLED, 130, 10, 100, 30, @@ -3784,24 +3784,24 @@ Bool GameWindowManager::initTestGUI( void ) listData.columnWidth = NULL; instData.init(); instData.m_style = GWS_SCROLL_LISTBOX | GWS_MOUSE_TRACK; - window = TheWindowManager->gogoGadgetListBox( NULL, + window = gogoGadgetListBox( NULL, WIN_STATUS_ENABLED, 200, 250, 100, 100, &instData, &listData, NULL, TRUE ); GadgetListBoxAddEntryText( window, L"Listbox text", - TheWindowManager->winMakeColor( 255, 255, 255, 255 ), -1, 0 ); + winMakeColor( 255, 255, 255, 255 ), -1, 0 ); GadgetListBoxAddEntryText( window, L"More text", - TheWindowManager->winMakeColor( 105, 105, 255, 255 ), -1, 0 ); + winMakeColor( 105, 105, 255, 255 ), -1, 0 ); GadgetListBoxAddEntryText( window, L"Nothing", - TheWindowManager->winMakeColor( 105, 105, 255, 255 ), -1, 0 ); + winMakeColor( 105, 105, 255, 255 ), -1, 0 ); GadgetListBoxAddEntryText( window, L"Seasons", - TheWindowManager->winMakeColor( 105, 205, 255, 255 ), -1, 0 ); + winMakeColor( 105, 205, 255, 255 ), -1, 0 ); GadgetListBoxAddEntryText( window, L"Misery", - TheWindowManager->winMakeColor( 235, 105, 255, 255 ), -1, 0 ); + winMakeColor( 235, 105, 255, 255 ), -1, 0 ); GadgetListBoxAddEntryText( window, L"Natural", - TheWindowManager->winMakeColor( 105, 205, 45, 255 ), -1, 0 ); + winMakeColor( 105, 205, 45, 255 ), -1, 0 ); window->winSetFont( TheFontLibrary->getFont( "Times New Roman", 12, FALSE ) ); // make a listbox @@ -3817,24 +3817,24 @@ Bool GameWindowManager::initTestGUI( void ) listData.columnWidth = NULL; instData.init(); instData.m_style = GWS_SCROLL_LISTBOX | GWS_MOUSE_TRACK; - window = TheWindowManager->gogoGadgetListBox( NULL, + window = gogoGadgetListBox( NULL, WIN_STATUS_ENABLED | WIN_STATUS_IMAGE, 75, 250, 100, 100, &instData, &listData, NULL, TRUE ); GadgetListBoxAddEntryText( window, L"Listbox text", - TheWindowManager->winMakeColor( 255, 255, 255, 255 ), -1, -1 ); + winMakeColor( 255, 255, 255, 255 ), -1, -1 ); GadgetListBoxAddEntryText( window, L"More text", - TheWindowManager->winMakeColor( 105, 105, 255, 255 ), -1, -1 ); + winMakeColor( 105, 105, 255, 255 ), -1, -1 ); GadgetListBoxAddEntryText( window, L"Nothing", - TheWindowManager->winMakeColor( 105, 105, 255, 255 ), -1, -1 ); + winMakeColor( 105, 105, 255, 255 ), -1, -1 ); GadgetListBoxAddEntryText( window, L"Seasons", - TheWindowManager->winMakeColor( 105, 205, 255, 255 ), -1, -1 ); + winMakeColor( 105, 205, 255, 255 ), -1, -1 ); GadgetListBoxAddEntryText( window, L"Misery", - TheWindowManager->winMakeColor( 235, 105, 255, 255 ), -1, -1 ); + winMakeColor( 235, 105, 255, 255 ), -1, -1 ); GadgetListBoxAddEntryText( window, L"Natural", - TheWindowManager->winMakeColor( 105, 205, 45, 255 ), -1, -1 ); + winMakeColor( 105, 205, 45, 255 ), -1, -1 ); // make a vert slider SliderData sliderData; @@ -3845,7 +3845,7 @@ Bool GameWindowManager::initTestGUI( void ) sliderData.position = 0; instData.init(); instData.m_style = GWS_VERT_SLIDER | GWS_MOUSE_TRACK; - window = TheWindowManager->gogoGadgetSlider( NULL, + window = gogoGadgetSlider( NULL, WIN_STATUS_ENABLED, 360, 250, 11, 100, @@ -3860,7 +3860,7 @@ Bool GameWindowManager::initTestGUI( void ) sliderData.position = 0; instData.init(); instData.m_style = GWS_VERT_SLIDER | GWS_MOUSE_TRACK; - window = TheWindowManager->gogoGadgetSlider( NULL, + window = gogoGadgetSlider( NULL, WIN_STATUS_ENABLED | WIN_STATUS_IMAGE, 400, 250, 11, 100, @@ -3875,7 +3875,7 @@ Bool GameWindowManager::initTestGUI( void ) sliderData.position = 0; instData.init(); instData.m_style = GWS_HORZ_SLIDER | GWS_MOUSE_TRACK; - window = TheWindowManager->gogoGadgetSlider( NULL, + window = gogoGadgetSlider( NULL, WIN_STATUS_ENABLED, 200, 400, 200, 11, @@ -3890,7 +3890,7 @@ Bool GameWindowManager::initTestGUI( void ) sliderData.position = 0; instData.init(); instData.m_style = GWS_HORZ_SLIDER | GWS_MOUSE_TRACK; - window = TheWindowManager->gogoGadgetSlider( NULL, + window = gogoGadgetSlider( NULL, WIN_STATUS_ENABLED | WIN_STATUS_IMAGE, 200, 420, 200, 11, @@ -3900,7 +3900,7 @@ Bool GameWindowManager::initTestGUI( void ) // make a progress bar instData.init(); instData.m_style = GWS_PROGRESS_BAR | GWS_MOUSE_TRACK; - window = TheWindowManager->gogoGadgetProgressBar( NULL, + window = gogoGadgetProgressBar( NULL, WIN_STATUS_ENABLED, 200, 450, 250, 15, @@ -3909,7 +3909,7 @@ Bool GameWindowManager::initTestGUI( void ) // make a progress bar instData.init(); instData.m_style = GWS_PROGRESS_BAR | GWS_MOUSE_TRACK; - window = TheWindowManager->gogoGadgetProgressBar( NULL, + window = gogoGadgetProgressBar( NULL, WIN_STATUS_ENABLED | WIN_STATUS_IMAGE, 200, 470, 250, 15, @@ -3921,7 +3921,7 @@ Bool GameWindowManager::initTestGUI( void ) instData.init(); instData.m_style = GWS_STATIC_TEXT | GWS_MOUSE_TRACK; instData.m_textLabelString = "Centered Static Text"; - window = TheWindowManager->gogoGadgetStaticText( NULL, + window = gogoGadgetStaticText( NULL, WIN_STATUS_ENABLED, 200, 490, 300, 25, @@ -3933,14 +3933,14 @@ Bool GameWindowManager::initTestGUI( void ) instData.init(); instData.m_style = GWS_STATIC_TEXT | GWS_MOUSE_TRACK; instData.m_textLabelString = "Not Centered Static Text"; - window = TheWindowManager->gogoGadgetStaticText( NULL, + window = gogoGadgetStaticText( NULL, WIN_STATUS_ENABLED | WIN_STATUS_IMAGE, 200, 520, 300, 25, &instData, &textData, NULL, TRUE ); - window->winSetEnabledTextColors( TheWindowManager->winMakeColor( 128, 128, 255, 255 ), - TheWindowManager->winMakeColor( 255, 255, 255, 255 ) ); + window->winSetEnabledTextColors( winMakeColor( 128, 128, 255, 255 ), + winMakeColor( 255, 255, 255, 255 ) ); // make some entry text EntryData entryData; @@ -3949,7 +3949,7 @@ Bool GameWindowManager::initTestGUI( void ) instData.init(); instData.m_style = GWS_ENTRY_FIELD | GWS_MOUSE_TRACK; instData.m_textLabelString = "Entry"; - window = TheWindowManager->gogoGadgetTextEntry( NULL, + window = gogoGadgetTextEntry( NULL, WIN_STATUS_ENABLED, 450, 270, 400, 30, @@ -3962,7 +3962,7 @@ Bool GameWindowManager::initTestGUI( void ) instData.init(); instData.m_style = GWS_ENTRY_FIELD | GWS_MOUSE_TRACK; instData.m_textLabelString = "Entry"; - window = TheWindowManager->gogoGadgetTextEntry( NULL, + window = gogoGadgetTextEntry( NULL, WIN_STATUS_ENABLED | WIN_STATUS_IMAGE, 450, 310, 400, 30, diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp index 0c49c2a141..4b8c9f00e9 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp @@ -1110,7 +1110,7 @@ void GameClient::preloadAssets( TimeOfDay timeOfDay ) draw->preloadAssets( timeOfDay ); // destroy the drawable - TheGameClient->destroyDrawable( draw ); + destroyDrawable( draw ); } @@ -1534,7 +1534,7 @@ void GameClient::xfer( Xfer *xfer ) const ThingTemplate* drawTemplate = draw->getTemplate(); if (drawTemplate->getFinalOverride() != thingTemplate->getFinalOverride()) { - TheGameClient->destroyDrawable( draw ); + destroyDrawable( draw ); draw = TheThingFactory->newDrawable( thingTemplate ); TheGameLogic->bindObjectAndDrawable(object, draw); } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp index de61454f1d..6d41373cb1 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp @@ -1644,7 +1644,7 @@ void InGameUI::handleBuildPlacements( void ) Int maxObjects = TheGlobalData->m_maxLineBuildObjects; // get the builder object that will be constructing things - Object *builderObject = TheGameLogic->findObjectByID( TheInGameUI->getPendingPlaceSourceObjectID() ); + Object *builderObject = TheGameLogic->findObjectByID( getPendingPlaceSourceObjectID() ); // // given the start/end points in the world and the the angle of the wall, fill @@ -2682,7 +2682,7 @@ void InGameUI::createMouseoverHint( const GameMessage *msg ) TheMouse->resetTooltipDelay(); } - if (m_mouseMode == MOUSEMODE_DEFAULT && !m_isScrolling && !m_isSelecting && !TheInGameUI->getSelectCount() && (TheRecorder->getMode() != RECORDERMODETYPE_PLAYBACK || TheLookAtTranslator->hasMouseMovedRecently())) + if (m_mouseMode == MOUSEMODE_DEFAULT && !m_isScrolling && !m_isSelecting && !getSelectCount() && (TheRecorder->getMode() != RECORDERMODETYPE_PLAYBACK || TheLookAtTranslator->hasMouseMovedRecently())) { if( m_mousedOverDrawableID != INVALID_DRAWABLE_ID ) { @@ -3450,7 +3450,7 @@ void InGameUI::deselectDrawable( Drawable *draw ) //------------------------------------------------------------------------------------------------- void InGameUI::deselectAllDrawables( Bool postMsg ) { - const DrawableList *selected = TheInGameUI->getAllSelectedDrawables(); + const DrawableList *selected = getAllSelectedDrawables(); // loop through all the selected drawables for ( DrawableListCIt it = selected->begin(); it != selected->end(); ) @@ -3460,7 +3460,7 @@ void InGameUI::deselectAllDrawables( Bool postMsg ) Drawable* draw = *it++; // do the deselection - TheInGameUI->deselectDrawable( draw ); + deselectDrawable( draw ); } @@ -4255,39 +4255,39 @@ void InGameUI::displayCantBuildMessage( LegalBuildCode lbc ) //--------------------------------------------------------------------------------------------- case LBC_RESTRICTED_TERRAIN: - TheInGameUI->message( "GUI:CantBuildRestrictedTerrain" ); + message( "GUI:CantBuildRestrictedTerrain" ); break; //--------------------------------------------------------------------------------------------- case LBC_NOT_FLAT_ENOUGH: - TheInGameUI->message( "GUI:CantBuildNotFlatEnough" ); + message( "GUI:CantBuildNotFlatEnough" ); break; //--------------------------------------------------------------------------------------------- case LBC_OBJECTS_IN_THE_WAY: - TheInGameUI->message( "GUI:CantBuildObjectsInTheWay" ); + message( "GUI:CantBuildObjectsInTheWay" ); break; //--------------------------------------------------------------------------------------------- case LBC_TOO_CLOSE_TO_SUPPLIES: - TheInGameUI->message( "GUI:CantBuildTooCloseToSupplies" ); + message( "GUI:CantBuildTooCloseToSupplies" ); break; //--------------------------------------------------------------------------------------------- case LBC_NO_CLEAR_PATH: - TheInGameUI->message( "GUI:CantBuildNoClearPath" ); + message( "GUI:CantBuildNoClearPath" ); break; //--------------------------------------------------------------------------------------------- case LBC_SHROUD: - TheInGameUI->message( "GUI:CantBuildShroud" ); + message( "GUI:CantBuildShroud" ); break; //--------------------------------------------------------------------------------------------- case LBC_GENERIC_FAILURE: default: - TheInGameUI->message( "GUI:CantBuildThere" ); + message( "GUI:CantBuildThere" ); break; } @@ -4319,7 +4319,7 @@ void InGameUI::militarySubtitle( const AsciiString& label, Int duration ) const int messageTimeout = currLogicFrame + (Int)(((Real)LOGICFRAMES_PER_SECOND * duration)/1000.0f); // disable tooltips until this frame, cause we don't want to collide with the military subtitles. - TheInGameUI->disableTooltipsUntil(messageTimeout); + disableTooltipsUntil(messageTimeout); // calculate where this screen position should be since the position being passed in is based off 8x6 Coord2D multiplier; @@ -4357,7 +4357,7 @@ void InGameUI::removeMilitarySubtitle( void ) if(!m_militarySubtitle) return; - TheInGameUI->clearTooltipsDisabled(); + clearTooltipsDisabled(); // loop through and free up the display strings for(UnsignedInt i = 0; i <= m_militarySubtitle->currentDisplayString; i ++) @@ -4376,7 +4376,7 @@ void InGameUI::removeMilitarySubtitle( void ) // ------------------------------------------------------------------------------------------------ Bool InGameUI::areSelectedObjectsControllable() const { - const DrawableList *selected = TheInGameUI->getAllSelectedDrawables(); + const DrawableList *selected = getAllSelectedDrawables(); // loop through all the selected drawables const Drawable *draw; @@ -4438,7 +4438,7 @@ CanAttackResult InGameUI::getCanSelectedObjectsAttack( ActionType action, const } // get selected list of drawables - const DrawableList *selected = TheInGameUI->getAllSelectedDrawables(); + const DrawableList *selected = getAllSelectedDrawables(); // set up counters for rule checking Int count = 0; @@ -4537,7 +4537,7 @@ Bool InGameUI::canSelectedObjectsDoAction( ActionType action, const Object *obje } // get selected list of drawables - const DrawableList *selected = TheInGameUI->getAllSelectedDrawables(); + const DrawableList *selected = getAllSelectedDrawables(); // set up counters for rule checking Int count = 0; @@ -4695,7 +4695,7 @@ Bool InGameUI::canSelectedObjectsDoSpecialPower( const CommandButton *command, c if (ignoreSelDraw) tmpList.push_back(ignoreSelDraw); - const DrawableList* selected = (!tmpList.empty()) ? &tmpList : TheInGameUI->getAllSelectedDrawables(); + const DrawableList* selected = (!tmpList.empty()) ? &tmpList : getAllSelectedDrawables(); // set up counters for rule checking Int count = 0; @@ -4761,7 +4761,7 @@ Bool InGameUI::canSelectedObjectsOverrideSpecialPowerDestination( const Coord3D Int qualify = 0; // get selected list of drawables - const DrawableList *selected = TheInGameUI->getAllSelectedDrawables(); + const DrawableList *selected = getAllSelectedDrawables(); // loop through all the selected drawables Drawable *other; @@ -4813,7 +4813,7 @@ Bool InGameUI::canSelectedObjectsEffectivelyUseWeapon( const CommandButton *comm } // get selected list of drawables - const DrawableList *selected = TheInGameUI->getAllSelectedDrawables(); + const DrawableList *selected = getAllSelectedDrawables(); // set up counters for rule checking Int count = 0; @@ -5030,16 +5030,16 @@ Int InGameUI::selectAllUnitsByTypeAcrossScreen(KindOfMaskType mustBeSet, KindOfM Int numSelected = selectAllUnitsByTypeAcrossRegion(®ion, mustBeSet, mustBeClear); if (numSelected == -1) { - UnicodeString message = TheGameText->fetch( "GUI:NothingSelected" ); - TheInGameUI->message( message ); + UnicodeString msgStr = TheGameText->fetch( "GUI:NothingSelected" ); + message( msgStr ); } else if (numSelected == 0) { } else { - UnicodeString message = TheGameText->fetch( "GUI:SelectedAcrossScreen" ); - TheInGameUI->message( message ); + UnicodeString msgStr = TheGameText->fetch( "GUI:SelectedAcrossScreen" ); + message( msgStr ); } return numSelected; } @@ -5064,16 +5064,16 @@ Int InGameUI::selectMatchingAcrossScreen( void ) Int numSelected = selectMatchingAcrossRegion(®ion); if (numSelected == -1) { - UnicodeString message = TheGameText->fetch( "GUI:NothingSelected" ); - TheInGameUI->message( message ); + UnicodeString msgStr = TheGameText->fetch( "GUI:NothingSelected" ); + message( msgStr ); } else if (numSelected == 0) { } else { - UnicodeString message = TheGameText->fetch( "GUI:SelectedAcrossScreen" ); - TheInGameUI->message( message ); + UnicodeString msgStr = TheGameText->fetch( "GUI:SelectedAcrossScreen" ); + message( msgStr ); } return numSelected; } @@ -5085,22 +5085,22 @@ Int InGameUI::selectAllUnitsByTypeAcrossMap(KindOfMaskType mustBeSet, KindOfMask Int numSelected = selectAllUnitsByTypeAcrossRegion(NULL, mustBeSet, mustBeClear); if (numSelected == -1) { - UnicodeString message = TheGameText->fetch( "GUI:NothingSelected" ); - TheInGameUI->message( message ); + UnicodeString msgStr = TheGameText->fetch( "GUI:NothingSelected" ); + message( msgStr ); } else if (numSelected == 0) { - Drawable *draw = TheInGameUI->getFirstSelectedDrawable(); + Drawable *draw = getFirstSelectedDrawable(); if( !draw || !draw->getObject() || !draw->getObject()->isKindOf( KINDOF_STRUCTURE ) ) { - UnicodeString message = TheGameText->fetch( "GUI:SelectedAcrossMap" ); - TheInGameUI->message( message ); + UnicodeString msgStr = TheGameText->fetch( "GUI:SelectedAcrossMap" ); + message( msgStr ); } } else { - UnicodeString message = TheGameText->fetch( "GUI:SelectedAcrossMap" ); - TheInGameUI->message( message ); + UnicodeString msgStr = TheGameText->fetch( "GUI:SelectedAcrossMap" ); + message( msgStr ); } return numSelected; } @@ -5114,22 +5114,22 @@ Int InGameUI::selectMatchingAcrossMap() Int numSelected = selectMatchingAcrossRegion(NULL); if (numSelected == -1) { - UnicodeString message = TheGameText->fetch( "GUI:NothingSelected" ); - TheInGameUI->message( message ); + UnicodeString msgStr = TheGameText->fetch( "GUI:NothingSelected" ); + message( msgStr ); } else if (numSelected == 0) { - Drawable *draw = TheInGameUI->getFirstSelectedDrawable(); + Drawable *draw = getFirstSelectedDrawable(); if( !draw || !draw->getObject() || !draw->getObject()->isKindOf( KINDOF_STRUCTURE ) ) { - UnicodeString message = TheGameText->fetch( "GUI:SelectedAcrossMap" ); - TheInGameUI->message( message ); + UnicodeString msgStr = TheGameText->fetch( "GUI:SelectedAcrossMap" ); + message( msgStr ); } } else { - UnicodeString message = TheGameText->fetch( "GUI:SelectedAcrossMap" ); - TheInGameUI->message( message ); + UnicodeString msgStr = TheGameText->fetch( "GUI:SelectedAcrossMap" ); + message( msgStr ); } return numSelected; } @@ -5751,7 +5751,7 @@ void InGameUI::selectNextIdleWorker( void ) } else { - Drawable *selectedDrawable = TheInGameUI->getFirstSelectedDrawable(); + Drawable *selectedDrawable = getFirstSelectedDrawable(); // TheSuperHackers @tweak Stubbjax 22/07/2025 Idle worker iteration now correctly identifies and // iterates contained idle workers. Previous iteration logic would not go past contained workers, // and was not guaranteed to select top-level containers. diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp index d847d9df59..2cd89f1371 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp @@ -2959,7 +2959,7 @@ ParticleSystemID ParticleSystemManager::createAttachedParticleSystemID( Object* attachTo, Bool createSlaves ) { - ParticleSystem* pSystem = TheParticleSystemManager->createParticleSystem(sysTemplate, createSlaves); + ParticleSystem* pSystem = createParticleSystem(sysTemplate, createSlaves); if (pSystem && attachTo) pSystem->attachToObject(attachTo); return pSystem ? pSystem->getSystemID() : INVALID_PARTICLE_SYSTEM_ID; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp index 5cf8868c99..2f4713f51c 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp @@ -710,7 +710,7 @@ Object *AI::findClosestEnemy( const Object *me, Real range, UnsignedInt qualifie Real distSqr = ThePartitionManager->getDistanceSquared(me, theEnemy, FROM_BOUNDINGSPHERE_2D); Real dist = sqrt(distSqr); - Int modifier = dist/TheAI->getAiData()->m_attackPriorityDistanceModifier; + Int modifier = dist/getAiData()->m_attackPriorityDistanceModifier; Int modPriority = curPriority-modifier; if (modPriority < 1) modPriority = 1; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp index 6af3e05b1b..daaa6f9f0d 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp @@ -2699,7 +2699,7 @@ void TerrainLogic::flattenTerrain(Object *obj) match = true; } if (match) { - totalHeight += TheTerrainLogic->getGroundHeight(testPt.X, testPt.Y); + totalHeight += getGroundHeight(testPt.X, testPt.Y); numSamples++; } } @@ -2710,7 +2710,7 @@ void TerrainLogic::flattenTerrain(Object *obj) // Compare to the height at the building's origin, because setRawMapHeight will only lower, // not raise. jba - Int centerHeight = REAL_TO_INT_FLOOR(TheTerrainLogic->getGroundHeight(pos->x, pos->y)/MAP_HEIGHT_SCALE); + Int centerHeight = REAL_TO_INT_FLOOR(getGroundHeight(pos->x, pos->y)/MAP_HEIGHT_SCALE); if (rawDataHeight>centerHeight) rawDataHeight = centerHeight; for (i=iMin.x; i<=iMax.x; i++) { @@ -2788,7 +2788,7 @@ void TerrainLogic::flattenTerrain(Object *obj) match = true; } if (match) { - totalHeight += TheTerrainLogic->getGroundHeight(testPt.X, testPt.Y); + totalHeight += getGroundHeight(testPt.X, testPt.Y); numSamples++; } } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp index e92ad16f32..e5f48c1213 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp @@ -2706,7 +2706,7 @@ void PartitionManager::reset() void PartitionManager::shutdown() { m_updatedSinceLastReset = false; - ThePartitionManager->removeAllDirtyModules(); + removeAllDirtyModules(); #ifdef RTS_DEBUG // the above *should* remove all the touched cells (via unRegisterObject), but let's check: @@ -3081,7 +3081,7 @@ CellShroudStatus PartitionManager::getShroudStatusForPlayer(Int playerIndex, con { Int x, y; - ThePartitionManager->worldToCell( loc->x, loc->y, &x, &y ); + worldToCell( loc->x, loc->y, &x, &y ); return getShroudStatusForPlayer( playerIndex, x, y ); } @@ -3092,7 +3092,7 @@ ObjectShroudStatus PartitionManager::getPropShroudStatusForPlayer(Int playerInde { Int x, y; - ThePartitionManager->worldToCell( loc->x - m_cellSize*0.5f, loc->y - m_cellSize*0.5f, &x, &y ); + worldToCell( loc->x - m_cellSize*0.5f, loc->y - m_cellSize*0.5f, &x, &y ); CellShroudStatus cellStat = getShroudStatusForPlayer( playerIndex, x, y ); if (cellStat != getShroudStatusForPlayer( playerIndex, x+1, y )) { @@ -3815,7 +3815,7 @@ Bool PartitionManager::tryPosition( const Coord3D *center, // very small sphere geometry around the point // GeometryInfo geometry( GEOMETRY_SPHERE, TRUE, 5.0f, 5.0f, 5.0f ); - ObjectIterator *iter = ThePartitionManager->iteratePotentialCollisions( &pos, geometry, angle, true ); + ObjectIterator *iter = iteratePotentialCollisions( &pos, geometry, angle, true ); MemoryPoolObjectHolder hold( iter ); // Bool overlap = FALSE; @@ -3995,9 +3995,9 @@ Bool PartitionManager::findPositionAround( const Coord3D *center, void PartitionManager::doShroudReveal(Real centerX, Real centerY, Real radius, PlayerMaskType playerMask) { Int cellCenterX, cellCenterY; - ThePartitionManager->worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); + worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); - Int cellRadius = ThePartitionManager->worldToCellDist(radius); + Int cellRadius = worldToCellDist(radius); if (cellRadius < 1) cellRadius = 1; @@ -4062,9 +4062,9 @@ void PartitionManager::resetPendingUndoShroudRevealQueue() void PartitionManager::undoShroudReveal(Real centerX, Real centerY, Real radius, PlayerMaskType playerMask) { Int cellCenterX, cellCenterY; - ThePartitionManager->worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); + worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); - Int cellRadius = ThePartitionManager->worldToCellDist(radius); + Int cellRadius = worldToCellDist(radius); if (cellRadius < 1) cellRadius = 1; @@ -4099,9 +4099,9 @@ void PartitionManager::queueUndoShroudReveal(Real centerX, Real centerY, Real ra void PartitionManager::doShroudCover(Real centerX, Real centerY, Real radius, PlayerMaskType playerMask) { Int cellCenterX, cellCenterY; - ThePartitionManager->worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); + worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); - Int cellRadius = ThePartitionManager->worldToCellDist(radius); + Int cellRadius = worldToCellDist(radius); if (cellRadius < 1) cellRadius = 1; @@ -4123,9 +4123,9 @@ void PartitionManager::doShroudCover(Real centerX, Real centerY, Real radius, Pl void PartitionManager::undoShroudCover(Real centerX, Real centerY, Real radius, PlayerMaskType playerMask) { Int cellCenterX, cellCenterY; - ThePartitionManager->worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); + worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); - Int cellRadius = ThePartitionManager->worldToCellDist(radius); + Int cellRadius = worldToCellDist(radius); if (cellRadius < 1) cellRadius = 1; @@ -4145,11 +4145,11 @@ void PartitionManager::undoShroudCover(Real centerX, Real centerY, Real radius, void PartitionManager::doThreatAffect( Real centerX, Real centerY, Real radius, UnsignedInt threatVal, PlayerMaskType playerMask) { Int cellCenterX, cellCenterY; - ThePartitionManager->worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); + worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); Real fCellCenterX = INT_TO_REAL(cellCenterX); Real fCellCenterY = INT_TO_REAL(cellCenterY); - Int cellRadius = ThePartitionManager->worldToCellDist(radius); + Int cellRadius = worldToCellDist(radius); if (cellRadius < 1) cellRadius = 1; @@ -4178,11 +4178,11 @@ void PartitionManager::doThreatAffect( Real centerX, Real centerY, Real radius, void PartitionManager::undoThreatAffect( Real centerX, Real centerY, Real radius, UnsignedInt threatVal, PlayerMaskType playerMask) { Int cellCenterX, cellCenterY; - ThePartitionManager->worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); + worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); Real fCellCenterX = INT_TO_REAL(cellCenterX); Real fCellCenterY = INT_TO_REAL(cellCenterY); - Int cellRadius = ThePartitionManager->worldToCellDist(radius); + Int cellRadius = worldToCellDist(radius); if (cellRadius < 1) cellRadius = 1; @@ -4211,11 +4211,11 @@ void PartitionManager::undoThreatAffect( Real centerX, Real centerY, Real radius void PartitionManager::doValueAffect( Real centerX, Real centerY, Real radius, UnsignedInt valueVal, PlayerMaskType playerMask) { Int cellCenterX, cellCenterY; - ThePartitionManager->worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); + worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); Real fCellCenterX = INT_TO_REAL(cellCenterX); Real fCellCenterY = INT_TO_REAL(cellCenterY); - Int cellRadius = ThePartitionManager->worldToCellDist(radius); + Int cellRadius = worldToCellDist(radius); if (cellRadius < 1) cellRadius = 1; @@ -4244,11 +4244,11 @@ void PartitionManager::doValueAffect( Real centerX, Real centerY, Real radius, U void PartitionManager::undoValueAffect( Real centerX, Real centerY, Real radius, UnsignedInt valueVal, PlayerMaskType playerMask) { Int cellCenterX, cellCenterY; - ThePartitionManager->worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); + worldToCell(centerX, centerY, &cellCenterX, &cellCenterY); Real fCellCenterX = INT_TO_REAL(cellCenterX); Real fCellCenterY = INT_TO_REAL(cellCenterY); - Int cellRadius = ThePartitionManager->worldToCellDist(radius); + Int cellRadius = worldToCellDist(radius); if (cellRadius < 1) cellRadius = 1; @@ -4412,7 +4412,7 @@ Int PartitionManager::iterateCellsAlongLine(const Coord3D& pos, const Coord3D& p for (Int curpixel = 0; curpixel <= numpixels; curpixel++) { - PartitionCell* cell = ThePartitionManager->getCellAt(x, y); // might be null if off the edge + PartitionCell* cell = getCellAt(x, y); // might be null if off the edge DEBUG_ASSERTCRASH(cell != NULL, ("off the map")); if (cell) { @@ -4445,7 +4445,7 @@ Int PartitionManager::iterateCellsBreadthFirst(const Coord3D *pos, CellBreadthFi // -1 means error, but we should add a define later for this. Int cellX, cellY; - ThePartitionManager->worldToCell(pos->x, pos->y, &cellX, &cellY); + worldToCell(pos->x, pos->y, &cellX, &cellY); // Note, bool. not Bool, cause bool will cause this to be a bitfield. std::vector bitField; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp index fe0eed142d..7720c5cc71 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp @@ -1588,7 +1588,7 @@ WeaponStore::~WeaponStore() //------------------------------------------------------------------------------------------------- void WeaponStore::handleProjectileDetonation(const WeaponTemplate* wt, const Object *source, const Coord3D* pos, WeaponBonusConditionFlags extraBonusFlags, Bool inflictDamage ) { - Weapon* w = TheWeaponStore->allocateNewWeapon(wt, PRIMARY_WEAPON); + Weapon* w = allocateNewWeapon(wt, PRIMARY_WEAPON); w->loadAmmoNow(source); w->fireProjectileDetonationWeapon( source, pos, extraBonusFlags, inflictDamage ); deleteInstance(w); @@ -1599,7 +1599,7 @@ void WeaponStore::createAndFireTempWeapon(const WeaponTemplate* wt, const Object { if (wt == NULL) return; - Weapon* w = TheWeaponStore->allocateNewWeapon(wt, PRIMARY_WEAPON); + Weapon* w = allocateNewWeapon(wt, PRIMARY_WEAPON); w->loadAmmoNow(source); w->fireWeapon(source, pos); deleteInstance(w); @@ -1611,7 +1611,7 @@ void WeaponStore::createAndFireTempWeapon(const WeaponTemplate* wt, const Object //CRCDEBUG_LOG(("WeaponStore::createAndFireTempWeapon() for %s", DescribeObject(source))); if (wt == NULL) return; - Weapon* w = TheWeaponStore->allocateNewWeapon(wt, PRIMARY_WEAPON); + Weapon* w = allocateNewWeapon(wt, PRIMARY_WEAPON); w->loadAmmoNow(source); w->fireWeapon(source, target); deleteInstance(w); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp index 865d1bd2d8..1afe8e19c1 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp @@ -6551,7 +6551,7 @@ void ScriptEngine::setPriorityThing( ScriptAction *pAction ) AsciiString typeArgument = pAction->getParameter(1)->getString(); // Our argument could be an individual type, or a list name. - const ObjectTypes *types = TheScriptEngine->getObjectTypes(typeArgument); + const ObjectTypes *types = getObjectTypes(typeArgument); if( !types ) { // Lookup failed, so it is just a single type @@ -7100,7 +7100,7 @@ void ScriptEngine::addObjectToCache(Object* pNewObject) if (it->second == NULL) { AsciiString newNameForDead; newNameForDead.format("Reassigning dead object's name '%s' to object (%d) of type '%s'", objName.str(), pNewObject->getID(), pNewObject->getTemplate()->getName().str()); - TheScriptEngine->AppendDebugMessage(newNameForDead, FALSE); + AppendDebugMessage(newNameForDead, FALSE); DEBUG_LOG((newNameForDead.str())); it->second = pNewObject; return; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp index a6001e2206..c729fb81cd 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp @@ -1702,8 +1702,8 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) Region3D extent; TheTerrainLogic->getExtent( &extent ); - TheGameLogic->setWidth( extent.hi.x - extent.lo.x ); - TheGameLogic->setHeight( extent.hi.y - extent.lo.y ); + setWidth( extent.hi.x - extent.lo.x ); + setHeight( extent.hi.y - extent.lo.y ); // anytime the world's size changes, must reset the partition mgr ThePartitionManager->init(); @@ -3060,7 +3060,7 @@ void GameLogic::popSleepyUpdate() void GameLogic::friend_awakenUpdateModule(Object* obj, UpdateModulePtr u, UnsignedInt whenToWakeUp) { //USE_PERF_TIMER(friend_awakenUpdateModule) - UnsignedInt now = TheGameLogic->getFrame(); + UnsignedInt now = getFrame(); DEBUG_ASSERTCRASH(whenToWakeUp >= now, ("setWakeFrame frame is in the past... are you sure this is what you want?")); if (u == m_curUpdateModule) @@ -3692,7 +3692,7 @@ void GameLogic::update( void ) } // send the current time to the GameClient - UnsignedInt now = TheGameLogic->getFrame(); + UnsignedInt now = getFrame(); TheGameClient->setFrame(now); // update (execute) scripts @@ -3888,7 +3888,7 @@ void GameLogic::preUpdate() Bool pause = TRUE; Bool pauseMusic = FALSE; Bool pauseInput = FALSE; - TheGameLogic->setGamePaused(pause, pauseMusic, pauseInput); + setGamePaused(pause, pauseMusic, pauseInput); } } @@ -3960,7 +3960,7 @@ void GameLogic::registerObject( Object *obj ) // add object to lookup table addObjectToLookupTable( obj ); - UnsignedInt now = TheGameLogic->getFrame(); + UnsignedInt now = getFrame(); if (now == 0) now = 1; for (BehaviorModule** b = obj->getBehaviorModules(); *b; ++b) @@ -5206,7 +5206,7 @@ void GameLogic::loadPostProcess( void ) #ifdef ALLOW_NONSLEEPY_UPDATES m_normalUpdates.clear(); #else - UnsignedInt now = TheGameLogic->getFrame(); + UnsignedInt now = getFrame(); if (now == 0) now = 1; #endif diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp index 23d726911a..07cdbb63b3 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp @@ -320,7 +320,7 @@ void GameLogic::prepareNewGame( GameMode gameMode, GameDifficulty diff, Int rank m_background->bringForward(); } m_background->getFirstWindow()->winClearStatus(WIN_STATUS_IMAGE); - TheGameLogic->setGameMode( gameMode ); + setGameMode( gameMode ); if (!TheGlobalData->m_pendingFile.isEmpty()) { TheWritableGlobalData->m_mapName = TheGlobalData->m_pendingFile; @@ -331,7 +331,7 @@ void GameLogic::prepareNewGame( GameMode gameMode, GameDifficulty diff, Int rank DEBUG_LOG(("GameLogic::prepareNewGame() - m_rankPointsToAddAtGameStart = %d", m_rankPointsToAddAtGameStart)); // If we're about to start a game, hide the shell. - if(!TheGameLogic->isInShellGame()) + if(!isInShellGame()) TheShell->hideShell(); m_startNewGame = FALSE; @@ -466,7 +466,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) #endif } currentlySelectedGroup = NULL; - TheGameLogic->clearGameData(); + clearGameData(); break; } @@ -509,7 +509,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) //--------------------------------------------------------------------------------------------- case GameMessage::MSG_SET_RALLY_POINT: { - Object *obj = TheGameLogic->findObjectByID( msg->getArgument( 0 )->objectID ); + Object *obj = findObjectByID( msg->getArgument( 0 )->objectID ); Coord3D dest = msg->getArgument( 1 )->location; if (obj) { @@ -538,7 +538,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) //--------------------------------------------------------------------------------------------- case GameMessage::MSG_COMBATDROP_AT_OBJECT: { - Object *targetObject = TheGameLogic->findObjectByID( msg->getArgument( 0 )->objectID ); + Object *targetObject = findObjectByID( msg->getArgument( 0 )->objectID ); // issue command for either single object or for selected group if( currentlySelectedGroup ) @@ -590,7 +590,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // Lock the weapon choice to the right weapon, then give an attack command WeaponSlotType weaponSlot = (WeaponSlotType)msg->getArgument( 0 )->integer; - Object *targetObject = TheGameLogic->findObjectByID( msg->getArgument( 1 )->objectID ); + Object *targetObject = findObjectByID( msg->getArgument( 1 )->objectID ); Int maxShotsToFire = msg->getArgument( 2 )->integer; // sanity @@ -677,7 +677,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // check for possible specific source, ignoring selection. ObjectID sourceID = msg->getArgument(2)->objectID; - Object* source = TheGameLogic->findObjectByID(sourceID); + Object* source = findObjectByID(sourceID); if (source != NULL) { AIGroupPtr theGroup = TheAI->createGroup(); @@ -715,14 +715,14 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // Object in way -- if applicable (some specials care, others don't) ObjectID objectID = msg->getArgument( 3 )->objectID; - Object *objectInWay = TheGameLogic->findObjectByID( objectID ); + Object *objectInWay = findObjectByID( objectID ); // Command button options -- special power may care about variance options UnsignedInt options = msg->getArgument( 4 )->integer; // check for possible specific source, ignoring selection. ObjectID sourceID = msg->getArgument(5)->objectID; - Object* source = TheGameLogic->findObjectByID(sourceID); + Object* source = findObjectByID(sourceID); if (source != NULL) { AIGroupPtr theGroup = TheAI->createGroup(); @@ -754,7 +754,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // argument 2 is target object ObjectID targetID = msg->getArgument(1)->objectID; - Object *target = TheGameLogic->findObjectByID( targetID ); + Object *target = findObjectByID( targetID ); if( !target ) { break; @@ -765,7 +765,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // check for possible specific source, ignoring selection. ObjectID sourceID = msg->getArgument(3)->objectID; - Object* source = TheGameLogic->findObjectByID(sourceID); + Object* source = findObjectByID(sourceID); if (source != NULL) { AIGroupPtr theGroup = TheAI->createGroup(); @@ -864,7 +864,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) //--------------------------------------------------------------------------------------------- case GameMessage::MSG_DO_GUARD_OBJECT: { - Object* obj = TheGameLogic->findObjectByID( msg->getArgument( 0 )->objectID ); + Object* obj = findObjectByID( msg->getArgument( 0 )->objectID ); if (!obj) break; @@ -1000,7 +1000,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) //--------------------------------------------------------------------------------------------- case GameMessage::MSG_ENTER: { - Object *enter = TheGameLogic->findObjectByID( msg->getArgument( 1 )->objectID ); + Object *enter = findObjectByID( msg->getArgument( 1 )->objectID ); // sanity if( enter == NULL ) @@ -1019,7 +1019,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) //--------------------------------------------------------------------------------------------- case GameMessage::MSG_EXIT: { - Object *objectWantingToExit = TheGameLogic->findObjectByID( msg->getArgument( 0 )->objectID ); + Object *objectWantingToExit = findObjectByID( msg->getArgument( 0 )->objectID ); #if RETAIL_COMPATIBLE_AIGROUP Object *objectContainingExiter = getSingleObjectFromSelection(currentlySelectedGroup); #else @@ -1109,7 +1109,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // -------------------------------------------------------------------------------------------- case GameMessage::MSG_GET_REPAIRED: { - Object *repairDepot = TheGameLogic->findObjectByID( msg->getArgument( 0 )->objectID ); + Object *repairDepot = findObjectByID( msg->getArgument( 0 )->objectID ); // sanity if( repairDepot == NULL ) @@ -1126,7 +1126,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // -------------------------------------------------------------------------------------------- case GameMessage::MSG_DOCK: { - Object *dockBuilding = TheGameLogic->findObjectByID( msg->getArgument( 0 )->objectID ); + Object *dockBuilding = findObjectByID( msg->getArgument( 0 )->objectID ); // sanity if( dockBuilding == NULL ) @@ -1143,7 +1143,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // -------------------------------------------------------------------------------------------- case GameMessage::MSG_GET_HEALED: { - Object *healDest = TheGameLogic->findObjectByID( msg->getArgument( 0 )->objectID ); + Object *healDest = findObjectByID( msg->getArgument( 0 )->objectID ); // sanity if( healDest == NULL ) @@ -1160,7 +1160,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // -------------------------------------------------------------------------------------------- case GameMessage::MSG_DO_REPAIR: { - Object *repairTarget = TheGameLogic->findObjectByID( msg->getArgument( 0 )->objectID ); + Object *repairTarget = findObjectByID( msg->getArgument( 0 )->objectID ); // sanity if( repairTarget == NULL ) @@ -1180,7 +1180,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // -------------------------------------------------------------------------------------------- case GameMessage::MSG_RESUME_CONSTRUCTION: { - Object *constructTarget = TheGameLogic->findObjectByID( msg->getArgument( 0 )->objectID ); + Object *constructTarget = findObjectByID( msg->getArgument( 0 )->objectID ); // sanity if( constructTarget == NULL ) @@ -1208,7 +1208,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) SpecialPowerType spType = (SpecialPowerType)msg->getArgument( 1 )->integer; ObjectID sourceID = msg->getArgument(2)->objectID; - Object* source = TheGameLogic->findObjectByID(sourceID); + Object* source = findObjectByID(sourceID); if (source != NULL) { AIGroupPtr theGroup = TheAI->createGroup(); @@ -1235,7 +1235,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) //--------------------------------------------------------------------------------------------- case GameMessage::MSG_DO_ATTACK_OBJECT: { - Object *enemy = TheGameLogic->findObjectByID( msg->getArgument( 0 )->objectID ); + Object *enemy = findObjectByID( msg->getArgument( 0 )->objectID ); // Check enemy, as it is possible that he died this frame. if (enemy) @@ -1257,7 +1257,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) //--------------------------------------------------------------------------------------------- case GameMessage::MSG_DO_FORCE_ATTACK_OBJECT: { - Object *enemy = TheGameLogic->findObjectByID( msg->getArgument( 0 )->objectID ); + Object *enemy = findObjectByID( msg->getArgument( 0 )->objectID ); // Check enemy, as it is possible that he died this frame. if (enemy) @@ -1593,12 +1593,12 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) Bool firstObject = TRUE; for (Int i = 1; i < msg->getArgumentCount(); ++i) { - Object *obj = TheGameLogic->findObjectByID( msg->getArgument( i )->objectID ); + Object *obj = findObjectByID( msg->getArgument( i )->objectID ); if (!obj) { continue; } - TheGameLogic->selectObject(obj, createNewGroup && firstObject, player->getPlayerMask()); + selectObject(obj, createNewGroup && firstObject, player->getPlayerMask()); firstObject = FALSE; } @@ -1618,12 +1618,12 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) for (Int i = 0; i < msg->getArgumentCount(); ++i) { ObjectID objID = msg->getArgument(i)->objectID; - Object *objToRemove = TheGameLogic->findObjectByID(objID); + Object *objToRemove = findObjectByID(objID); if (!objToRemove) { continue; } - TheGameLogic->deselectObject(objToRemove, player->getPlayerMask()); + deselectObject(objToRemove, player->getPlayerMask()); } break; @@ -1773,7 +1773,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) { if (beacon->getControllingPlayer() == thisPlayer) { - TheGameLogic->destroyObject(beacon); // the owner is telling it to go away. such is life. + destroyObject(beacon); // the owner is telling it to go away. such is life. TheControlBar->markUIDirty(); // check if we should un-grey out the button } diff --git a/GeneralsMD/Code/Tools/GUIEdit/Source/EditWindow.cpp b/GeneralsMD/Code/Tools/GUIEdit/Source/EditWindow.cpp index 9f43480cf3..d541e5d000 100644 --- a/GeneralsMD/Code/Tools/GUIEdit/Source/EditWindow.cpp +++ b/GeneralsMD/Code/Tools/GUIEdit/Source/EditWindow.cpp @@ -658,7 +658,7 @@ void EditWindow::mouseEvent( UnsignedInt windowsMessage, // if we have ONE window selected and are close to an anchor corner // to resize it change the cursor to resize cursor // - TheEditWindow->handleResizeAvailable( x, y ); + handleResizeAvailable( x, y ); } @@ -896,7 +896,7 @@ void EditWindow::mouseEvent( UnsignedInt windowsMessage, } // open right click menu - TheEditWindow->openPopupMenu( clickPos.x, clickPos.y ); + openPopupMenu( clickPos.x, clickPos.y ); break; diff --git a/GeneralsMD/Code/Tools/GUIEdit/Source/GUIEdit.cpp b/GeneralsMD/Code/Tools/GUIEdit/Source/GUIEdit.cpp index 401e29e834..301dc0c86e 100644 --- a/GeneralsMD/Code/Tools/GUIEdit/Source/GUIEdit.cpp +++ b/GeneralsMD/Code/Tools/GUIEdit/Source/GUIEdit.cpp @@ -275,10 +275,10 @@ Bool GUIEdit::validateParentForCreate( GameWindow *parent ) // gadgets are units themselves and should have no user defined // children // - if( parent && TheEditor->windowIsGadget( parent ) ) + if( parent && windowIsGadget( parent ) ) { - MessageBox( TheEditor->getWindowHandle(), + MessageBox( getWindowHandle(), "You cannot make a new window as a child to a GUI Gadget Control", "Illegal Parent", MB_OK ); return FALSE; @@ -717,7 +717,7 @@ void GUIEdit::update( void ) TheMouse->update(); // process the mouse if we're in test mode - if( TheEditor->getMode() == MODE_TEST_RUN ) + if( getMode() == MODE_TEST_RUN ) { // send input through the window system and clear all messages after @@ -762,12 +762,12 @@ Bool GUIEdit::writeConfigFile( const char *filename ) backColor.red, backColor.green, backColor.blue, backColor.alpha ); // grid settings - fprintf( fp, "GRIDRESOLUTION = %d\n", TheEditor->getGridResolution() ); - RGBColorInt *gridColor = TheEditor->getGridColor(); + fprintf( fp, "GRIDRESOLUTION = %d\n", getGridResolution() ); + RGBColorInt *gridColor = getGridColor(); fprintf( fp, "GRIDCOLOR = %d %d %d %d\n", gridColor->red, gridColor->green, gridColor->blue, gridColor->alpha ); - fprintf( fp, "SNAPTOGRID = %d\n", TheEditor->isGridSnapOn() ); - fprintf( fp, "GRIDVISIBLE = %d\n", TheEditor->isGridVisible() ); + fprintf( fp, "SNAPTOGRID = %d\n", isGridSnapOn() ); + fprintf( fp, "GRIDVISIBLE = %d\n", isGridVisible() ); // write hierarchy position and size ICoord2D pos, size; @@ -817,15 +817,15 @@ Bool GUIEdit::readConfigFile( const char *filename ) // grid settings Int intData; fscanf( fp, "GRIDRESOLUTION = %d\n", &intData ); - TheEditor->setGridResolution( intData ); + setGridResolution( intData ); RGBColorInt gridColor; fscanf( fp, "GRIDCOLOR = %d %d %d %d\n", &gridColor.red, &gridColor.green, &gridColor.blue, &gridColor.alpha ); - TheEditor->setGridColor( &gridColor ); + setGridColor( &gridColor ); fscanf( fp, "SNAPTOGRID = %d\n", &intData ); - TheEditor->setGridSnap( intData ); + setGridSnap( intData ); fscanf( fp, "GRIDVISIBLE = %d\n", &intData ); - TheEditor->setGridVisible( intData ); + setGridVisible( intData ); // hierarchy view ICoord2D pos, size; @@ -3446,7 +3446,7 @@ Bool GUIEdit::menuExit( void ) Bool success; // save all our data - success = TheEditor->menuSave(); + success = menuSave(); // // if we were unable to save file ask them if it's still OK to @@ -4000,7 +4000,7 @@ void GUIEdit::notifyNewWindow( GameWindow *window ) //============================================================================= void GUIEdit::deleteSelected( void ) { - Int count = TheEditor->selectionCount(); + Int count = selectionCount(); Int i; GameWindow **deleteList; WindowSelectionEntry *select; @@ -4042,7 +4042,7 @@ void GUIEdit::deleteSelected( void ) //============================================================================= void GUIEdit::bringSelectedToTop( void ) { - Int count = TheEditor->selectionCount(); + Int count = selectionCount(); // no-op if( count == 0 ) @@ -4118,8 +4118,8 @@ void GUIEdit::dragMoveSelectedWindows( ICoord2D *dragOrigin, moveLoc.y = origin.y + (dragDest->y - dragOrigin->y); // snap move location to grid if on - if( (TheEditor->getMode() == MODE_DRAG_MOVE) && TheEditor->isGridSnapOn() ) - TheEditor->gridSnapLocation( &moveLoc, &moveLoc ); + if( (getMode() == MODE_DRAG_MOVE) && isGridSnapOn() ) + gridSnapLocation( &moveLoc, &moveLoc ); // kee the location legal computeSafeLocation( window, moveLoc.x, moveLoc.y, &safeLoc.x, &safeLoc.y ); @@ -4523,7 +4523,7 @@ void GUIEdit::moveWindowTo( GameWindow *window, Int x, Int y ) window->winSetPosition( x, y ); // we've now made a change - TheEditor->setUnsaved( TRUE ); + setUnsaved( TRUE ); } diff --git a/GeneralsMD/Code/Tools/GUIEdit/Source/HierarchyView.cpp b/GeneralsMD/Code/Tools/GUIEdit/Source/HierarchyView.cpp index 1945184152..98648b24f2 100644 --- a/GeneralsMD/Code/Tools/GUIEdit/Source/HierarchyView.cpp +++ b/GeneralsMD/Code/Tools/GUIEdit/Source/HierarchyView.cpp @@ -1231,7 +1231,7 @@ HTREEITEM HierarchyView::treePointToItem( Int x, Int y ) hitTest.pt.y = y; hitTest.hItem = NULL; hitTest.flags = TVHT_ONITEM; - return TreeView_HitTest( TheHierarchyView->getTreeHandle(), &hitTest ); + return TreeView_HitTest( getTreeHandle(), &hitTest ); } diff --git a/GeneralsMD/Code/Tools/GUIEdit/Source/Save.cpp b/GeneralsMD/Code/Tools/GUIEdit/Source/Save.cpp index 7849582e6b..0cafceb966 100644 --- a/GeneralsMD/Code/Tools/GUIEdit/Source/Save.cpp +++ b/GeneralsMD/Code/Tools/GUIEdit/Source/Save.cpp @@ -1124,7 +1124,7 @@ void GUIEdit::validateNames( GameWindow *root, char *filename, Bool *valid ) } // check for a duplicate filename - if( TheEditor->isNameDuplicate( TheWindowManager->winGetWindowList(), + if( isNameDuplicate( TheWindowManager->winGetWindowList(), root, instData->m_decoratedNameString ) ) { @@ -1228,7 +1228,7 @@ Bool GUIEdit::saveData( char *filePathAndFilename, char *filename ) if( valid == FALSE ) { - MessageBox( TheEditor->getWindowHandle(), offendingNames, "Window Name Error", MB_OK ); + MessageBox( getWindowHandle(), offendingNames, "Window Name Error", MB_OK ); return FALSE; } From abd092c94729f4b8d25df1cd38ff25e529cec199 Mon Sep 17 00:00:00 2001 From: Bobby Battista Date: Mon, 22 Dec 2025 14:33:04 -0500 Subject: [PATCH 50/70] refactor: Apply clang-tidy fixes for generals-use-is-empty (#2018) --- .../Source/Common/System/ArchiveFile.cpp | 14 +++++++------- .../Source/Common/System/ArchiveFileSystem.cpp | 2 +- .../Source/GameNetwork/ConnectionManager.cpp | 2 +- Core/GameEngine/Source/GameNetwork/GameInfo.cpp | 10 +++++----- Core/GameEngine/Source/GameNetwork/NetworkUtil.cpp | 2 +- .../Win32Device/Common/Win32LocalFileSystem.cpp | 2 +- .../Source/WWVegas/WW3D2/animatedsoundmgr.cpp | 2 +- .../Source/WWVegas/WWAudio/AudibleSound.cpp | 2 +- Core/Libraries/Source/WWVegas/WWAudio/WWAudio.cpp | 2 +- .../Libraries/Source/WWVegas/WWDebug/wwprofile.cpp | 2 +- Core/Libraries/Source/WWVegas/WWLib/rawfile.cpp | 4 ++-- Core/Libraries/Source/WWVegas/WWLib/textfile.cpp | 2 +- Core/Tools/W3DView/SoundEditDialog.cpp | 2 +- .../Code/GameEngine/Source/Common/CommandLine.cpp | 2 +- .../GUI/DisconnectMenu/DisconnectMenu.cpp | 6 +++--- .../GUI/GUICallbacks/Menus/LanLobbyMenu.cpp | 2 +- .../GUICallbacks/Menus/NetworkDirectConnect.cpp | 2 +- .../GUI/GUICallbacks/Menus/PopupHostGame.cpp | 2 +- .../Libraries/Source/WWVegas/WW3D2/hmorphanim.cpp | 2 +- .../Code/GameEngine/Source/Common/CommandLine.cpp | 2 +- .../GUI/DisconnectMenu/DisconnectMenu.cpp | 6 +++--- .../GUI/GUICallbacks/Menus/LanLobbyMenu.cpp | 2 +- .../GUICallbacks/Menus/NetworkDirectConnect.cpp | 2 +- .../GUI/GUICallbacks/Menus/PopupHostGame.cpp | 2 +- .../Libraries/Source/WWVegas/WW3D2/hmorphanim.cpp | 2 +- 25 files changed, 40 insertions(+), 40 deletions(-) diff --git a/Core/GameEngine/Source/Common/System/ArchiveFile.cpp b/Core/GameEngine/Source/Common/System/ArchiveFile.cpp index c10b42754c..88cd657646 100644 --- a/Core/GameEngine/Source/Common/System/ArchiveFile.cpp +++ b/Core/GameEngine/Source/Common/System/ArchiveFile.cpp @@ -39,13 +39,13 @@ // and ? is used to denote a single wildcard character. static Bool SearchStringMatches(AsciiString str, AsciiString searchString) { - if (str.getLength() == 0) { - if (searchString.getLength() == 0) { + if (str.isEmpty()) { + if (searchString.isEmpty()) { return TRUE; } return FALSE; } - if (searchString.getLength() == 0) { + if (searchString.isEmpty()) { return FALSE; } @@ -103,7 +103,7 @@ void ArchiveFile::addFile(const AsciiString& path, const ArchivedFileInfo *fileI tokenizer.toLower(); tokenizer.nextToken(&token, "\\/"); - while (token.getLength() > 0) + while (!token.isEmpty()) { DetailedArchivedDirectoryInfoMap::iterator tempiter = dirInfo->m_directories.find(token); if (tempiter == dirInfo->m_directories.end()) @@ -131,7 +131,7 @@ void ArchiveFile::getFileListInDirectory(const AsciiString& currentDirectory, co tokenizer.toLower(); tokenizer.nextToken(&token, "\\/"); - while (token.getLength() > 0) { + while (!token.isEmpty()) { DetailedArchivedDirectoryInfoMap::const_iterator it = dirInfo->m_directories.find(token); if (it != dirInfo->m_directories.end()) @@ -157,7 +157,7 @@ void ArchiveFile::getFileListInDirectory(const DetailedArchivedDirectoryInfo *di const DetailedArchivedDirectoryInfo *tempDirInfo = &(diriter->second); AsciiString tempdirname; tempdirname = currentDirectory; - if ((tempdirname.getLength() > 0) && (!tempdirname.endsWith("\\"))) { + if ((!tempdirname.isEmpty()) && (!tempdirname.endsWith("\\"))) { tempdirname.concat('\\'); } tempdirname.concat(tempDirInfo->m_directoryName); @@ -170,7 +170,7 @@ void ArchiveFile::getFileListInDirectory(const DetailedArchivedDirectoryInfo *di if (SearchStringMatches(fileiter->second.m_filename, searchName)) { AsciiString tempfilename; tempfilename = currentDirectory; - if ((tempfilename.getLength() > 0) && (!tempfilename.endsWith("\\"))) { + if ((!tempfilename.isEmpty()) && (!tempfilename.endsWith("\\"))) { tempfilename.concat('\\'); } tempfilename.concat(fileiter->second.m_filename); diff --git a/Core/GameEngine/Source/Common/System/ArchiveFileSystem.cpp b/Core/GameEngine/Source/Common/System/ArchiveFileSystem.cpp index 1d8223a014..b422e5cd1d 100644 --- a/Core/GameEngine/Source/Common/System/ArchiveFileSystem.cpp +++ b/Core/GameEngine/Source/Common/System/ArchiveFileSystem.cpp @@ -305,7 +305,7 @@ Bool ArchiveFileSystem::getFileInfo(const AsciiString& filename, FileInfo *fileI return FALSE; } - if (filename.getLength() <= 0) { + if (filename.isEmpty()) { return FALSE; } diff --git a/Core/GameEngine/Source/GameNetwork/ConnectionManager.cpp b/Core/GameEngine/Source/GameNetwork/ConnectionManager.cpp index 6e17e386dc..cef851a74a 100644 --- a/Core/GameEngine/Source/GameNetwork/ConnectionManager.cpp +++ b/Core/GameEngine/Source/GameNetwork/ConnectionManager.cpp @@ -1714,7 +1714,7 @@ PlayerLeaveCode ConnectionManager::disconnectPlayer(Int slot) { UnicodeString unicodeName; unicodeName = getPlayerName(slot); - if (unicodeName.getLength() > 0 && m_connections[slot]) { + if (!unicodeName.isEmpty() && m_connections[slot]) { TheInGameUI->message("Network:PlayerLeftGame", unicodeName.str()); // People are boneheads. Also play a sound diff --git a/Core/GameEngine/Source/GameNetwork/GameInfo.cpp b/Core/GameEngine/Source/GameNetwork/GameInfo.cpp index 8551069dae..6b3298d6ef 100644 --- a/Core/GameEngine/Source/GameNetwork/GameInfo.cpp +++ b/Core/GameEngine/Source/GameNetwork/GameInfo.cpp @@ -525,7 +525,7 @@ void GameInfo::setMap( AsciiString mapName ) } AsciiString newMapName; - if (mapName.getLength() > 0) + if (!mapName.isEmpty()) { AsciiString token; mapName.nextToken(&token, "\\/"); @@ -536,7 +536,7 @@ void GameInfo::setMap( AsciiString mapName ) // added onto it. while (mapName.find('\\') != NULL) { - if (newMapName.getLength() > 0) + if (!newMapName.isEmpty()) { newMapName.concat('/'); } @@ -896,7 +896,7 @@ AsciiString GameInfoToAsciiString( const GameInfo *game ) AsciiString mapName = game->getMap(); mapName = TheGameState->realMapPathToPortableMapPath(mapName); AsciiString newMapName; - if (mapName.getLength() > 0) + if (!mapName.isEmpty()) { AsciiString token; mapName.nextToken(&token, "\\/"); @@ -907,7 +907,7 @@ AsciiString GameInfoToAsciiString( const GameInfo *game ) // added onto it. while (mapName.find('\\') != NULL) { - if (newMapName.getLength() > 0) + if (!newMapName.isEmpty()) { newMapName.concat('/'); } @@ -1073,7 +1073,7 @@ Bool ParseAsciiStringToGameInfo(GameInfo *game, AsciiString options) AsciiString token; tempstr = val.str()+2; tempstr.nextToken(&token, "\\/"); - while (tempstr.getLength() > 0) + while (!tempstr.isEmpty()) { mapName.concat(token); mapName.concat('\\'); diff --git a/Core/GameEngine/Source/GameNetwork/NetworkUtil.cpp b/Core/GameEngine/Source/GameNetwork/NetworkUtil.cpp index 4d04807d28..d8f7b172c7 100644 --- a/Core/GameEngine/Source/GameNetwork/NetworkUtil.cpp +++ b/Core/GameEngine/Source/GameNetwork/NetworkUtil.cpp @@ -84,7 +84,7 @@ UnsignedInt ResolveIP(AsciiString host) struct hostent *hostStruct; struct in_addr *hostNode; - if (host.getLength() == 0) + if (host.isEmpty()) { DEBUG_LOG(("ResolveIP(): Can't resolve NULL")); return 0; diff --git a/Core/GameEngineDevice/Source/Win32Device/Common/Win32LocalFileSystem.cpp b/Core/GameEngineDevice/Source/Win32Device/Common/Win32LocalFileSystem.cpp index 84236de436..424c446996 100644 --- a/Core/GameEngineDevice/Source/Win32Device/Common/Win32LocalFileSystem.cpp +++ b/Core/GameEngineDevice/Source/Win32Device/Common/Win32LocalFileSystem.cpp @@ -206,7 +206,7 @@ Bool Win32LocalFileSystem::getFileInfo(const AsciiString& filename, FileInfo *fi Bool Win32LocalFileSystem::createDirectory(AsciiString directory) { - if ((directory.getLength() > 0) && (directory.getLength() < _MAX_DIR)) { + if ((!directory.isEmpty()) && (directory.getLength() < _MAX_DIR)) { return (CreateDirectory(directory.str(), NULL) != 0); } return FALSE; diff --git a/Core/Libraries/Source/WWVegas/WW3D2/animatedsoundmgr.cpp b/Core/Libraries/Source/WWVegas/WW3D2/animatedsoundmgr.cpp index 8202d5ce2f..a521e5679e 100644 --- a/Core/Libraries/Source/WWVegas/WW3D2/animatedsoundmgr.cpp +++ b/Core/Libraries/Source/WWVegas/WW3D2/animatedsoundmgr.cpp @@ -164,7 +164,7 @@ Build_List_From_String // // Add this entry to our list // - if ((entry_string.Get_Length () > 0) || (count == 0)) { + if ((!entry_string.Is_Empty()) || (count == 0)) { (*string_list)[count++] = entry_string; } } diff --git a/Core/Libraries/Source/WWVegas/WWAudio/AudibleSound.cpp b/Core/Libraries/Source/WWVegas/WWAudio/AudibleSound.cpp index 370b4537f0..19f416d490 100644 --- a/Core/Libraries/Source/WWVegas/WWAudio/AudibleSound.cpp +++ b/Core/Libraries/Source/WWVegas/WWAudio/AudibleSound.cpp @@ -1780,7 +1780,7 @@ AudibleSoundClass::Load (ChunkLoadClass &cload) // // Reconstruct the sound buffer we had before we saved // - if (filename.Get_Length () > 0) { + if (!filename.Is_Empty()) { bool is_3d = (As_Sound3DClass () != NULL); SoundBufferClass *buffer = WWAudioClass::Get_Instance ()->Get_Sound_Buffer (filename, is_3d); Set_Buffer (buffer); diff --git a/Core/Libraries/Source/WWVegas/WWAudio/WWAudio.cpp b/Core/Libraries/Source/WWVegas/WWAudio/WWAudio.cpp index 6590cbe88c..34b88f28b6 100644 --- a/Core/Libraries/Source/WWVegas/WWAudio/WWAudio.cpp +++ b/Core/Libraries/Source/WWVegas/WWAudio/WWAudio.cpp @@ -2267,7 +2267,7 @@ WWAudioClass::UnRegister_Text_Callback (LPFNTEXTCALLBACK callback) void WWAudioClass::Fire_Text_Callback (AudibleSoundClass *sound_obj, const StringClass &text) { - if (text.Get_Length () > 0) { + if (!text.Is_Empty()) { // // Loop over all the text-callbacks that have been registered diff --git a/Core/Libraries/Source/WWVegas/WWDebug/wwprofile.cpp b/Core/Libraries/Source/WWVegas/WWDebug/wwprofile.cpp index c02c4e5dd5..d3a9e53478 100644 --- a/Core/Libraries/Source/WWVegas/WWDebug/wwprofile.cpp +++ b/Core/Libraries/Source/WWVegas/WWDebug/wwprofile.cpp @@ -221,7 +221,7 @@ void WWProfileHierachyNodeClass::Add_To_String_Compact(StringClass& string,int r if (Child) { StringClass work; Child->Add_To_String_Compact(work,recursion+1); - if (work.Get_Length()!=0) { + if (!work.Is_Empty()) { string+="{"; string+=work; string+="}"; diff --git a/Core/Libraries/Source/WWVegas/WWLib/rawfile.cpp b/Core/Libraries/Source/WWVegas/WWLib/rawfile.cpp index f282d3ee30..9ebd2d2d35 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/rawfile.cpp +++ b/Core/Libraries/Source/WWVegas/WWLib/rawfile.cpp @@ -402,7 +402,7 @@ int RawFileClass::Open(int rights) ** Verify that there is a filename associated with this file object. If not, then this is a ** big error condition. */ - if (Filename.Get_Length()==0) { + if (Filename.Is_Empty()) { Error(ENOENT, false); } @@ -492,7 +492,7 @@ int RawFileClass::Open(int rights) *=============================================================================================*/ bool RawFileClass::Is_Available(int forced) { - if (Filename.Get_Length()==0) return(false); + if (Filename.Is_Empty()) return(false); /* ** If the file is already open, then is must have already passed the availability check. diff --git a/Core/Libraries/Source/WWVegas/WWLib/textfile.cpp b/Core/Libraries/Source/WWVegas/WWLib/textfile.cpp index 52d33f6f7d..bc36014894 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/textfile.cpp +++ b/Core/Libraries/Source/WWVegas/WWLib/textfile.cpp @@ -130,7 +130,7 @@ TextFileClass::Read_Line (StringClass &string) } } - bool retval = (string.Get_Length () > 0); + bool retval = (!string.Is_Empty()); if (retval) { int len = string.Get_Length (); diff --git a/Core/Tools/W3DView/SoundEditDialog.cpp b/Core/Tools/W3DView/SoundEditDialog.cpp index 6ed5c3c6ac..b14bccb37e 100644 --- a/Core/Tools/W3DView/SoundEditDialog.cpp +++ b/Core/Tools/W3DView/SoundEditDialog.cpp @@ -278,7 +278,7 @@ SoundEditDialogClass::OnOK (void) // // Update the asset manager with the new prototype // - if (OldName.Get_Length () > 0) { + if (!OldName.Is_Empty()) { WW3DAssetManager::Get_Instance()->Remove_Prototype (OldName); } WW3DAssetManager::Get_Instance()->Add_Prototype (prototype); diff --git a/Generals/Code/GameEngine/Source/Common/CommandLine.cpp b/Generals/Code/GameEngine/Source/Common/CommandLine.cpp index 19678a6744..0ec260b386 100644 --- a/Generals/Code/GameEngine/Source/Common/CommandLine.cpp +++ b/Generals/Code/GameEngine/Source/Common/CommandLine.cpp @@ -83,7 +83,7 @@ static void ConvertShortMapPathToLongMapPath(AsciiString &mapName) return; } path.nextToken(&token, "\\/"); - while (!token.endsWithNoCase(".map") && (token.getLength() > 0)) + while (!token.endsWithNoCase(".map") && (!token.isEmpty())) { actualpath.concat(token); actualpath.concat('\\'); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/DisconnectMenu/DisconnectMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/DisconnectMenu/DisconnectMenu.cpp index e249a7fe96..293a5b36ae 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/DisconnectMenu/DisconnectMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/DisconnectMenu/DisconnectMenu.cpp @@ -122,7 +122,7 @@ void DisconnectMenu::setPlayerName(Int playerNum, UnicodeString name) { GameWindow *control = TheWindowManager->winGetWindowFromId(NULL, id); if (control != NULL) { - if (name.getLength() > 0) { + if (!name.isEmpty()) { GadgetStaticTextSetText(control, name); // showPlayerControls(playerNum); } @@ -132,12 +132,12 @@ void DisconnectMenu::setPlayerName(Int playerNum, UnicodeString name) { control = TheWindowManager->winGetWindowFromId(NULL, id); if (control != NULL) { - if (name.getLength() > 0) { + if (!name.isEmpty()) { GadgetStaticTextSetText(control, L""); } } - if (name.getLength() > 0) { + if (!name.isEmpty()) { showPlayerControls(playerNum); } else { hidePlayerControls(playerNum); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp index 89e8efd685..36467a3d0f 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp @@ -233,7 +233,7 @@ UnicodeString LANPreferences::getRemoteIPEntry(Int i) asciientry.set(asciientry.str() + 1); // skip the ':' ret.translate(ipstr); - if (asciientry.getLength() > 0) + if (!asciientry.isEmpty()) { ret.concat(L"("); ret.concat(QuotedPrintableToUnicodeString(asciientry)); 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 f9e7349779..8d3b77b289 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp @@ -285,7 +285,7 @@ void NetworkDirectConnectInit( WindowLayout *layout, void *userData ) UnicodeString name; name = userprefs.getUserName(); - if (name.getLength() == 0) + if (name.isEmpty()) { name = TheGameText->fetch("GUI:Player"); } 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 4d9081deca..77b256438e 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupHostGame.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupHostGame.cpp @@ -504,7 +504,7 @@ WindowMsgHandledType PopupHostGameSystem( GameWindow *window, UnsignedInt msg, W UnicodeString name; name = GadgetTextEntryGetText(textEntryGameName); name.trim(); - if(name.getLength() <= 0) + if(name.isEmpty()) { name.translate(TheGameSpyInfo->getLocalName()); GadgetTextEntrySetText(textEntryGameName, name); diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/hmorphanim.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/hmorphanim.cpp index 27ea79983c..f30f54eb30 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/hmorphanim.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/hmorphanim.cpp @@ -300,7 +300,7 @@ static int Build_List_From_String // // Add this entry to our list // - if ((entry_string.Get_Length () > 0) || (count == 0)) { + if ((!entry_string.Is_Empty()) || (count == 0)) { (*string_list)[count++] = entry_string; } } diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp index 19678a6744..0ec260b386 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp @@ -83,7 +83,7 @@ static void ConvertShortMapPathToLongMapPath(AsciiString &mapName) return; } path.nextToken(&token, "\\/"); - while (!token.endsWithNoCase(".map") && (token.getLength() > 0)) + while (!token.endsWithNoCase(".map") && (!token.isEmpty())) { actualpath.concat(token); actualpath.concat('\\'); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/DisconnectMenu/DisconnectMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/DisconnectMenu/DisconnectMenu.cpp index 13c80807ea..6c2ffe60e4 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/DisconnectMenu/DisconnectMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/DisconnectMenu/DisconnectMenu.cpp @@ -121,7 +121,7 @@ void DisconnectMenu::setPlayerName(Int playerNum, UnicodeString name) { GameWindow *control = TheWindowManager->winGetWindowFromId(NULL, id); if (control != NULL) { - if (name.getLength() > 0) { + if (!name.isEmpty()) { GadgetStaticTextSetText(control, name); // showPlayerControls(playerNum); } @@ -131,12 +131,12 @@ void DisconnectMenu::setPlayerName(Int playerNum, UnicodeString name) { control = TheWindowManager->winGetWindowFromId(NULL, id); if (control != NULL) { - if (name.getLength() > 0) { + if (!name.isEmpty()) { GadgetStaticTextSetText(control, L""); } } - if (name.getLength() > 0) { + if (!name.isEmpty()) { showPlayerControls(playerNum); } else { hidePlayerControls(playerNum); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp index 359d9da101..58418c946d 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp @@ -233,7 +233,7 @@ UnicodeString LANPreferences::getRemoteIPEntry(Int i) asciientry.set(asciientry.str() + 1); // skip the ':' ret.translate(ipstr); - if (asciientry.getLength() > 0) + if (!asciientry.isEmpty()) { ret.concat(L"("); ret.concat(QuotedPrintableToUnicodeString(asciientry)); 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 bd85e8826f..c6132c56e4 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp @@ -285,7 +285,7 @@ void NetworkDirectConnectInit( WindowLayout *layout, void *userData ) UnicodeString name; name = userprefs.getUserName(); - if (name.getLength() == 0) + if (name.isEmpty()) { name = TheGameText->fetch("GUI:Player"); } 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 76a55a69e9..9d55935b35 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupHostGame.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupHostGame.cpp @@ -537,7 +537,7 @@ WindowMsgHandledType PopupHostGameSystem( GameWindow *window, UnsignedInt msg, W UnicodeString name; name = GadgetTextEntryGetText(textEntryGameName); name.trim(); - if(name.getLength() <= 0) + if(name.isEmpty()) { name.translate(TheGameSpyInfo->getLocalName()); GadgetTextEntrySetText(textEntryGameName, name); diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmorphanim.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmorphanim.cpp index af10ea6633..0696c96d36 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmorphanim.cpp +++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmorphanim.cpp @@ -300,7 +300,7 @@ static int Build_List_From_String // // Add this entry to our list // - if ((entry_string.Get_Length () > 0) || (count == 0)) { + if ((!entry_string.Is_Empty()) || (count == 0)) { (*string_list)[count++] = entry_string; } } From e616d8217e614e074aae733c72a28bed54381cc9 Mon Sep 17 00:00:00 2001 From: Bobby Battista Date: Mon, 22 Dec 2025 15:02:10 -0500 Subject: [PATCH 51/70] fix(logic): Fix unexpected return in GameLogic::logicMessageDispatcher's switch case MSG_CANCEL_UNIT_CREATE (#1881) --- .../GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp | 2 +- .../GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Generals/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp b/Generals/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp index aa4af7eb54..dc05ea60e6 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp @@ -1387,7 +1387,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // get the unit production interface ProductionUpdateInterface *pu = producer->getProductionUpdateInterface(); if( pu == NULL ) - return; + break; // cancel the production pu->cancelUnitCreate( productionID ); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp index 07cdbb63b3..ef0b9794c0 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp @@ -1415,7 +1415,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) // get the unit production interface ProductionUpdateInterface *pu = producer->getProductionUpdateInterface(); if( pu == NULL ) - return; + break; // cancel the production pu->cancelUnitCreate( productionID ); From 5dba2a08abf57175c8a66cc05f8a34fa85e39ba5 Mon Sep 17 00:00:00 2001 From: Bobby Battista Date: Mon, 22 Dec 2025 15:02:39 -0500 Subject: [PATCH 52/70] perf(audio): Optimize fail condition order in AudioManager::addAudioEvent (#1843) --- Core/GameEngine/Source/Common/Audio/GameAudio.cpp | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/Core/GameEngine/Source/Common/Audio/GameAudio.cpp b/Core/GameEngine/Source/Common/Audio/GameAudio.cpp index 9917266a64..8db82783b3 100644 --- a/Core/GameEngine/Source/Common/Audio/GameAudio.cpp +++ b/Core/GameEngine/Source/Common/Audio/GameAudio.cpp @@ -440,6 +440,11 @@ AudioHandle AudioManager::addAudioEvent(const AudioEventRTS *eventToAdd) return AHSV_NoSound; } + if (!eventToAdd->getUninterruptable()) { + if (!shouldPlayLocally(eventToAdd)) { + return AHSV_NotForLocal; + } + } AudioEventRTS *audioEvent = MSGNEW("AudioEventRTS") AudioEventRTS(*eventToAdd); // poolify audioEvent->setPlayingHandle( allocateNewHandle() ); @@ -455,13 +460,6 @@ AudioHandle AudioManager::addAudioEvent(const AudioEventRTS *eventToAdd) } } - if (!audioEvent->getUninterruptable()) { - if (!shouldPlayLocally(audioEvent)) { - releaseAudioEventRTS(audioEvent); - return AHSV_NotForLocal; - } - } - // cull muted audio if (audioEvent->getVolume() < m_audioSettings->m_minVolume) { #ifdef INTENSIVE_AUDIO_DEBUG From 2b37732cbe3f666ad5a437f2d3c204049ca9d39d Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Tue, 30 Dec 2025 16:41:20 +0100 Subject: [PATCH 53/70] refactor(audio): Simplify volume related code in AudioManager and MilesAudioManager (#2030) --- Core/GameEngine/Include/Common/GameAudio.h | 4 ++-- .../Source/Common/Audio/AudioEventRTS.cpp | 24 ++++++++----------- .../Source/Common/Audio/GameAudio.cpp | 18 +++++++------- .../MilesAudioDevice/MilesAudioManager.cpp | 18 +++++++++----- 4 files changed, 34 insertions(+), 30 deletions(-) diff --git a/Core/GameEngine/Include/Common/GameAudio.h b/Core/GameEngine/Include/Common/GameAudio.h index c88b9303ac..de19bb7fcc 100644 --- a/Core/GameEngine/Include/Common/GameAudio.h +++ b/Core/GameEngine/Include/Common/GameAudio.h @@ -105,7 +105,7 @@ enum local player affiliation, etc. (The entire list of checks is contained in shouldPlayLocally()). In addition, the world and unit audio are never allowed to exceed their footprint, as specified - in the audio settings INI file. In order to accomodate this, the audio uses an audio cache. The + in the audio settings INI file. In order to accommodate this, the audio uses an audio cache. The audio cache will attempt to load a sample, assuming there is enough room. If there is not enough room, then it goes through and finds any samples that are lower priority, and kills them until enough room is present for the sample. If it cannot free enough room, nothing happens to the @@ -190,7 +190,7 @@ class AudioManager : public SubsystemInterface virtual void closeDevice( void ) = 0; virtual void *getDevice( void ) = 0; - // Debice Dependent notification functions + // Device Dependent notification functions virtual void notifyOfAudioCompletion( UnsignedInt audioCompleted, UnsignedInt flags ) = 0; // Device Dependent enumerate providers functions. It is okay for there to be only 1 provider (Miles provides a maximum of 64. diff --git a/Core/GameEngine/Source/Common/Audio/AudioEventRTS.cpp b/Core/GameEngine/Source/Common/Audio/AudioEventRTS.cpp index eda40c71c7..c15c26a570 100644 --- a/Core/GameEngine/Source/Common/Audio/AudioEventRTS.cpp +++ b/Core/GameEngine/Source/Common/Audio/AudioEventRTS.cpp @@ -724,14 +724,13 @@ void AudioEventRTS::setVolume( Real vol ) //------------------------------------------------------------------------------------------------- const Coord3D *AudioEventRTS::getCurrentPosition( void ) { - if (m_ownerType == OT_Positional) + switch (m_ownerType) { + case OT_Positional: return &m_positionOfAudio; - } - else if (m_ownerType == OT_Object) - { - Object *obj = TheGameLogic->findObjectByID(m_objectID); - if (obj) + + case OT_Object: + if (Object *obj = TheGameLogic->findObjectByID(m_objectID)) { m_positionOfAudio.set( obj->getPosition() ); } @@ -740,11 +739,9 @@ const Coord3D *AudioEventRTS::getCurrentPosition( void ) m_ownerType = OT_Dead; } return &m_positionOfAudio; - } - else if (m_ownerType == OT_Drawable) - { - Drawable *draw = TheGameClient->findDrawableByID(m_drawableID); - if( draw ) + + case OT_Drawable: + if (Drawable *draw = TheGameClient->findDrawableByID(m_drawableID)) { m_positionOfAudio.set( draw->getPosition() ); } @@ -753,9 +750,8 @@ const Coord3D *AudioEventRTS::getCurrentPosition( void ) m_ownerType = OT_Dead; } return &m_positionOfAudio; - } - else if( m_ownerType == OT_Dead ) - { + + case OT_Dead: return &m_positionOfAudio; } diff --git a/Core/GameEngine/Source/Common/Audio/GameAudio.cpp b/Core/GameEngine/Source/Common/Audio/GameAudio.cpp index 8db82783b3..23c944fd95 100644 --- a/Core/GameEngine/Source/Common/Audio/GameAudio.cpp +++ b/Core/GameEngine/Source/Common/Audio/GameAudio.cpp @@ -419,7 +419,12 @@ AudioHandle AudioManager::addAudioEvent(const AudioEventRTS *eventToAdd) } } - switch (eventToAdd->getAudioEventInfo()->m_soundType) + const AudioType soundType = eventToAdd->getAudioEventInfo()->m_soundType; + + // Check if audio type is on + // TheSuperHackers @info Zero audio volume is not a fail condition, because music, speech and sounds + // still need to be in flight in case the user raises the volume on runtime after the audio was already triggered. + switch (soundType) { case AT_Music: if (!isOn(AudioAffect_Music)) @@ -430,16 +435,14 @@ AudioHandle AudioManager::addAudioEvent(const AudioEventRTS *eventToAdd) return AHSV_NoSound; break; case AT_Streaming: + // if we're currently playing uninterruptable speech, then disallow the addition of this sample + if (getDisallowSpeech()) + return AHSV_NoSound; if (!isOn(AudioAffect_Speech)) return AHSV_NoSound; break; } - // if we're currently playing uninterruptable speech, then disallow the addition of this sample - if (getDisallowSpeech() && eventToAdd->getAudioEventInfo()->m_soundType == AT_Streaming) { - return AHSV_NoSound; - } - if (!eventToAdd->getUninterruptable()) { if (!shouldPlayLocally(eventToAdd)) { return AHSV_NotForLocal; @@ -469,8 +472,7 @@ AudioHandle AudioManager::addAudioEvent(const AudioEventRTS *eventToAdd) return AHSV_Muted; } - AudioType type = eventToAdd->getAudioEventInfo()->m_soundType; - if (type == AT_Music) + if (soundType == AT_Music) { m_music->addAudioEvent(audioEvent); } diff --git a/Core/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp b/Core/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp index 973669ed6b..5a47735ca7 100644 --- a/Core/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp +++ b/Core/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp @@ -2677,25 +2677,29 @@ Bool MilesAudioManager::isOnScreen( const Coord3D *pos ) const //------------------------------------------------------------------------------------------------- Real MilesAudioManager::getEffectiveVolume(AudioEventRTS *event) const { - Real volume = 1.0f; - volume *= (event->getVolume() * event->getVolumeShift()); - if (event->getAudioEventInfo()->m_soundType == AT_Music) + Real volume = event->getVolume() * event->getVolumeShift(); + + switch (event->getAudioEventInfo()->m_soundType) + { + case AT_Music: { volume *= m_musicVolume; + break; } - else if (event->getAudioEventInfo()->m_soundType == AT_Streaming) + case AT_Streaming: { volume *= m_speechVolume; + break; } - else + case AT_SoundEffect: { if (event->isPositionalAudio()) { volume *= m_sound3DVolume; - Coord3D distance = m_listenerPosition; const Coord3D *pos = event->getCurrentPosition(); if (pos) { + Coord3D distance = m_listenerPosition; distance.sub(pos); Real objMinDistance; Real objMaxDistance; @@ -2730,6 +2734,8 @@ Real MilesAudioManager::getEffectiveVolume(AudioEventRTS *event) const { volume *= m_soundVolume; } + break; + } } return volume; From 20927af519499222a68ad50c5f270dbbccc88aca Mon Sep 17 00:00:00 2001 From: Bobby Battista Date: Tue, 30 Dec 2025 16:18:57 -0500 Subject: [PATCH 54/70] ci(vcpkg): Stabilize vcpkg binary caching; add compiler-aware keys and explicit cache path (#2028) --- .github/workflows/build-toolchain.yml | 86 +++++++++++++++++++++------ 1 file changed, 69 insertions(+), 17 deletions(-) diff --git a/.github/workflows/build-toolchain.yml b/.github/workflows/build-toolchain.yml index 5999ee132b..6dcad70e0d 100644 --- a/.github/workflows/build-toolchain.yml +++ b/.github/workflows/build-toolchain.yml @@ -31,23 +31,16 @@ jobs: name: ${{ inputs.preset }}${{ inputs.tools && '+t' || '' }}${{ inputs.extras && '+e' || '' }} runs-on: windows-2022 timeout-minutes: 30 + env: VCPKG_FILE_CACHE: ${{ github.workspace }}\vcpkg-bincache VCPKG_BINARY_SOURCES: clear;files,${{ github.workspace }}\vcpkg-bincache,readwrite VCPKG_FEATURE_FLAGS: manifests,versions,binarycaching + steps: - name: Checkout Code uses: actions/checkout@v4 - - name: Cache vcpkg binary artifacts - uses: actions/cache@v4 - with: - path: ${{ github.workspace }}\vcpkg-bincache - key: vcpkg-bincache-${{ runner.os }}-${{ hashFiles('vcpkg.json','vcpkg-lock.json') }}-${{ inputs.preset }} - restore-keys: | - vcpkg-bincache-${{ runner.os }}-${{ hashFiles('vcpkg.json','vcpkg-lock.json') }}- - vcpkg-bincache-${{ runner.os }}- - - name: Cache VC6 Installation if: startsWith(inputs.preset, 'vc6') id: cache-vc6 @@ -112,15 +105,65 @@ jobs: with: arch: x86 + - name: Compute vcpkg cache key parts + if: startsWith(inputs.preset, 'win32') + id: vcpkg_key + shell: pwsh + run: | + $baseline = (Get-Content vcpkg.json | ConvertFrom-Json)."builtin-baseline" + + $msvc = $env:VCToolsVersion + if (-not $msvc) { $msvc = "unknown" } + + # Reduce churn: keep major.minor (e.g. 14.44) + $msvcMajorMinor = ($msvc -split '\.')[0..1] -join '.' + + $triplet = "x86-windows" + if ("${{ inputs.preset }}" -like "x64*") { $triplet = "x64-windows" } + + "baseline=$baseline" >> $env:GITHUB_OUTPUT + "msvc=$msvcMajorMinor" >> $env:GITHUB_OUTPUT + "triplet=$triplet" >> $env:GITHUB_OUTPUT + + Write-Host "vcpkg cache key parts: baseline=$baseline, msvc=$msvcMajorMinor, triplet=$triplet" + + - name: Restore vcpkg binary cache + if: startsWith(inputs.preset, 'win32') + id: vcpkg_cache + uses: actions/cache/restore@v4 + with: + path: ${{ github.workspace }}\vcpkg-bincache + key: vcpkg-bincache-v2-${{ runner.os }}-msvc${{ steps.vcpkg_key.outputs.msvc }}-baseline${{ steps.vcpkg_key.outputs.baseline }}-${{ steps.vcpkg_key.outputs.triplet }} + restore-keys: | + vcpkg-bincache-v2-${{ runner.os }}-msvc${{ steps.vcpkg_key.outputs.msvc }}-baseline${{ steps.vcpkg_key.outputs.baseline }}- + vcpkg-bincache-v2-${{ runner.os }}- + - name: Setup vcpkg uses: lukka/run-vcpkg@v11 + with: + runVcpkgInstall: false + doNotCache: true + + - name: Configure vcpkg to use cached directory + if: startsWith(inputs.preset, 'win32') + shell: pwsh + run: | + $cacheDir = "${{ github.workspace }}\vcpkg-bincache" + New-Item -ItemType Directory -Force -Path $cacheDir | Out-Null + + # lukka/run-vcpkg sets its own temp cache dir; override to force our cached dir + $env:VCPKG_DEFAULT_BINARY_CACHE = $cacheDir + $env:VCPKG_BINARY_SOURCES = "clear;files,$cacheDir,readwrite" + + "VCPKG_DEFAULT_BINARY_CACHE=$cacheDir" >> $env:GITHUB_ENV + "VCPKG_BINARY_SOURCES=$env:VCPKG_BINARY_SOURCES" >> $env:GITHUB_ENV - name: Configure ${{ inputs.game }} with CMake Using ${{ inputs.preset }}${{ inputs.tools && '+t' || '' }}${{ inputs.extras && '+e' || '' }} Preset shell: pwsh run: | $buildFlags = @( - "-DRTS_BUILD_ZEROHOUR=${{ inputs.game == 'GeneralsMD' && 'ON' || 'OFF' }}", - "-DRTS_BUILD_GENERALS=${{ inputs.game == 'Generals' && 'ON' || 'OFF' }}" + "-DRTS_BUILD_ZEROHOUR=${{ inputs.game == 'GeneralsMD' && 'ON' || 'OFF' }}", + "-DRTS_BUILD_GENERALS=${{ inputs.game == 'Generals' && 'ON' || 'OFF' }}" ) $gamePrefix = "${{ inputs.game == 'Generals' && 'GENERALS' || 'ZEROHOUR' }}" @@ -130,7 +173,6 @@ jobs: $buildFlags += "-DRTS_BUILD_${gamePrefix}_EXTRAS=${{ inputs.extras && 'ON' || 'OFF' }}" Write-Host "Build flags: $($buildFlags -join ' | ')" - cmake --preset ${{ inputs.preset }} $buildFlags - name: Build ${{ inputs.game }} with CMake Using ${{ inputs.preset }}${{ inputs.tools && '+t' || '' }}${{ inputs.extras && '+e' || '' }} Preset @@ -138,19 +180,29 @@ jobs: run: | cmake --build --preset ${{ inputs.preset }} + - name: Save vcpkg binary cache + # Only one job should save to avoid "Unable to reserve cache" conflicts. + if: ${{ startsWith(inputs.preset, 'win32') && steps.vcpkg_cache.outputs.cache-hit != 'true' && inputs.game == 'Generals' && inputs.preset == 'win32-vcpkg-debug' }} + uses: actions/cache/save@v4 + with: + path: ${{ github.workspace }}\vcpkg-bincache + key: vcpkg-bincache-v2-${{ runner.os }}-msvc${{ steps.vcpkg_key.outputs.msvc }}-baseline${{ steps.vcpkg_key.outputs.baseline }}-${{ steps.vcpkg_key.outputs.triplet }} + - name: Collect ${{ inputs.game }} ${{ inputs.preset }}${{ inputs.tools && '+t' || '' }}${{ inputs.extras && '+e' || '' }} Artifact shell: pwsh run: | $buildDir = "build\${{ inputs.preset }}" $artifactsDir = New-Item -ItemType Directory -Force -Path "$buildDir\${{ inputs.game }}\artifacts" -Verbose - if ("${{ inputs.preset }}" -like "win32*") { - # For win32 preset, look in config-specific subdirectories + if ("${{ inputs.preset }}" -like "win32*") { $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\Core","$buildDir\${{ inputs.game }}" -File | Where-Object { $_.Extension -in @(".exe", ".dll", ".pdb") } -Verbose + $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\Core","$buildDir\${{ inputs.game }}" -File | + Where-Object { $_.Extension -in @(".exe", ".dll", ".pdb") } -Verbose } + $files | Move-Item -Destination $artifactsDir -Verbose -Force - name: Upload ${{ inputs.game }} ${{ inputs.preset }}${{ inputs.tools && '+t' || '' }}${{ inputs.extras && '+e' || '' }} Artifact From f5ccc9cb9550515f608cfeb980a0b79ea314a37b Mon Sep 17 00:00:00 2001 From: Stubbjax Date: Wed, 31 Dec 2025 20:55:19 +1100 Subject: [PATCH 55/70] bugfix(aiupdate): Invalidate build task of Dozers and Workers if the assigned target scaffold no longer exists (#1868) --- .../GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp | 5 +++++ .../GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp | 5 +++++ .../GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp | 5 +++++ .../GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp | 5 +++++ 4 files changed, 20 insertions(+) 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 32aa3ece0f..4ef21b66eb 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp @@ -1594,9 +1594,14 @@ UpdateSleepTime DozerAIUpdate::update( void ) Bool invalidTask = FALSE; // validate the task and the target + // TheSuperHackers @bugfix Stubbjax 16/11/2025 Invalidate the task when the build scaffold is destroyed. if( currentTask == DOZER_TASK_REPAIR && TheActionManager->canRepairObject( getObject(), targetObject, getLastCommandSource() ) == FALSE ) invalidTask = TRUE; +#if !RETAIL_COMPATIBLE_CRC + else if (currentTask == DOZER_TASK_BUILD && targetObject == NULL) + invalidTask = TRUE; +#endif // cancel the task if it's now invalid if( invalidTask == TRUE ) 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 4721df43da..54a92e7666 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp @@ -275,9 +275,14 @@ UpdateSleepTime WorkerAIUpdate::update( void ) Bool invalidTask = FALSE; // validate the task and the target + // TheSuperHackers @bugfix Stubbjax 16/11/2025 Invalidate the task when the build scaffold is destroyed. if( currentTask == DOZER_TASK_REPAIR && TheActionManager->canRepairObject( getObject(), targetObject, getLastCommandSource() ) == FALSE ) invalidTask = TRUE; +#if !RETAIL_COMPATIBLE_CRC + else if (currentTask == DOZER_TASK_BUILD && targetObject == NULL) + invalidTask = TRUE; +#endif // cancel the task if it's now invalid if( invalidTask == TRUE ) 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 e901fd9df8..40c16a53d4 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp @@ -1599,9 +1599,14 @@ UpdateSleepTime DozerAIUpdate::update( void ) Bool invalidTask = FALSE; // validate the task and the target + // TheSuperHackers @bugfix Stubbjax 16/11/2025 Invalidate the task when the build scaffold is destroyed. if( currentTask == DOZER_TASK_REPAIR && TheActionManager->canRepairObject( getObject(), targetObject, getLastCommandSource() ) == FALSE ) invalidTask = TRUE; +#if !RETAIL_COMPATIBLE_CRC + else if (currentTask == DOZER_TASK_BUILD && targetObject == NULL) + invalidTask = TRUE; +#endif // cancel the task if it's now invalid if( invalidTask == TRUE ) 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 f36a83f720..5233e93bf0 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp @@ -275,9 +275,14 @@ UpdateSleepTime WorkerAIUpdate::update( void ) Bool invalidTask = FALSE; // validate the task and the target + // TheSuperHackers @bugfix Stubbjax 16/11/2025 Invalidate the task when the build scaffold is destroyed. if( currentTask == DOZER_TASK_REPAIR && TheActionManager->canRepairObject( getObject(), targetObject, getLastCommandSource() ) == FALSE ) invalidTask = TRUE; +#if !RETAIL_COMPATIBLE_CRC + else if (currentTask == DOZER_TASK_BUILD && targetObject == NULL) + invalidTask = TRUE; +#endif // cancel the task if it's now invalid if( invalidTask == TRUE ) From a4c76b980d5c2ebc8c3e289358f0fe9cf2bcbf57 Mon Sep 17 00:00:00 2001 From: Bobby Battista Date: Wed, 31 Dec 2025 07:21:47 -0500 Subject: [PATCH 56/70] perf(contain): Optimize Object::isHero with cached hero counter (#1841) --- .../Include/GameLogic/Module/ContainModule.h | 1 + .../Include/GameLogic/Module/OpenContain.h | 3 ++ .../GameLogic/Object/Contain/OpenContain.cpp | 44 +++++++++++++++++-- .../Source/GameLogic/Object/Object.cpp | 16 +------ .../Include/GameLogic/Module/ContainModule.h | 1 + .../Include/GameLogic/Module/OpenContain.h | 3 ++ .../GameLogic/Object/Contain/OpenContain.cpp | 43 +++++++++++++++++- .../Source/GameLogic/Object/Object.cpp | 15 +------ 8 files changed, 94 insertions(+), 32 deletions(-) diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/ContainModule.h b/Generals/Code/GameEngine/Include/GameLogic/Module/ContainModule.h index a07b9a856b..b62b2a7f24 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/ContainModule.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/ContainModule.h @@ -155,6 +155,7 @@ class ContainModuleInterface virtual const Object *friend_getRider() const = 0; ///< Damn. The draw order dependency bug for riders means that our draw module needs to cheat to get around it. virtual Real getContainedItemsMass() const = 0; virtual UnsignedInt getStealthUnitsContained() const = 0; + virtual UnsignedInt getHeroUnitsContained() const = 0; virtual Bool calcBestGarrisonPosition( Coord3D *sourcePos, const Coord3D *targetPos ) = 0; virtual Bool attemptBestFirePointPosition( Object *source, Weapon *weapon, Object *victim ) = 0; diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/OpenContain.h b/Generals/Code/GameEngine/Include/GameLogic/Module/OpenContain.h index fecfaa2e13..a60d56c3ce 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/OpenContain.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/OpenContain.h @@ -164,6 +164,7 @@ class OpenContain : public UpdateModule, virtual const Object *friend_getRider() const{return NULL;} ///< Damn. The draw order dependency bug for riders means that our draw module needs to cheat to get around it. virtual Real getContainedItemsMass() const; virtual UnsignedInt getStealthUnitsContained() const { return m_stealthUnitsContained; } + virtual UnsignedInt getHeroUnitsContained() const { return m_heroUnitsContained; } virtual PlayerMaskType getPlayerWhoEntered(void) const { return m_playerEnteredMask; } @@ -238,6 +239,8 @@ class OpenContain : public UpdateModule, ObjectEnterExitMap m_objectEnterExitInfo; UnsignedInt m_stealthUnitsContained; ///< number of stealth units that can't be seen by enemy players. + UnsignedInt m_heroUnitsContained; ///< cached hero count + XferVersion m_xferVersion; ///< version of loaded save file for loadPostProcess Int m_whichExitPath; ///< Cycles from 1 to n and is used only in modules whose data has numberOfExitPaths > 1. UnsignedInt m_doorCloseCountdown; ///< When should I shut my door. diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp index 9cff8d09cd..659ae112d5 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp @@ -125,6 +125,8 @@ OpenContain::OpenContain( Thing *thing, const ModuleData* moduleData ) : UpdateM m_lastLoadSoundFrame = 0; m_containListSize = 0; m_stealthUnitsContained = 0; + m_heroUnitsContained = 0; + m_xferVersion = 1; m_doorCloseCountdown = 0; m_rallyPoint.zero(); @@ -352,6 +354,10 @@ void OpenContain::addToContainList( Object *rider ) { m_stealthUnitsContained++; } + if( rider->isKindOf( KINDOF_HERO ) ) + { + m_heroUnitsContained++; + } } //------------------------------------------------------------------------------------------------- @@ -532,6 +538,7 @@ void OpenContain::removeFromContainViaIterator( ContainedItemsList::iterator it, m_containListSize--; if( rider->isKindOf( KINDOF_STEALTH_GARRISON ) ) { + DEBUG_ASSERTCRASH( m_stealthUnitsContained > 0, ("OpenContain::removeFromContainViaIterator - Removing stealth unit but stealth count is %d", m_stealthUnitsContained) ); m_stealthUnitsContained--; if( exposeStealthUnits ) { @@ -542,6 +549,11 @@ void OpenContain::removeFromContainViaIterator( ContainedItemsList::iterator it, } } } + if( rider->isKindOf( KINDOF_HERO ) ) + { + DEBUG_ASSERTCRASH( m_heroUnitsContained > 0, ("OpenContain::removeFromContainViaIterator - Removing hero but hero count is %d", m_heroUnitsContained) ); + m_heroUnitsContained--; + } if (isEnclosingContainerFor( rider )) @@ -620,7 +632,7 @@ void OpenContain::scatterToNearbyPosition(Object* rider) } //------------------------------------------------------------------------------------------------- -void OpenContain::onContaining( Object * /*rider*/ ) +void OpenContain::onContaining( Object *rider ) { // Play audio if( m_loadSoundsEnabled ) @@ -1442,15 +1454,22 @@ void OpenContain::crc( Xfer *xfer ) // ------------------------------------------------------------------------------------------------ /** Xfer method * Version Info: - * 1: Initial version */ + * 1: Initial version + * 2: TheSuperHackers @tweak Serialize hero units contained count + */ // ------------------------------------------------------------------------------------------------ void OpenContain::xfer( Xfer *xfer ) { // version - const XferVersion currentVersion = 1; +#if RETAIL_COMPATIBLE_XFER_SAVE + XferVersion currentVersion = 1; +#else + XferVersion currentVersion = 2; +#endif XferVersion version = currentVersion; xfer->xferVersion( &version, currentVersion ); + m_xferVersion = version; // extend base class UpdateModule::xfer( xfer ); @@ -1526,6 +1545,12 @@ void OpenContain::xfer( Xfer *xfer ) // stealth units contained xfer->xferUnsignedInt( &m_stealthUnitsContained ); + // hero units contained + if (version >= 2) + { + xfer->xferUnsignedInt( &m_heroUnitsContained ); + } + // door close countdown xfer->xferUnsignedInt( &m_doorCloseCountdown ); @@ -1658,6 +1683,19 @@ void OpenContain::loadPostProcess( void ) } + if (m_xferVersion < 2) + { + // Restore hero count by iterating hero objects for old save versions + m_heroUnitsContained = 0; + for( ContainedItemsList::const_iterator it = m_containList.begin(); it != m_containList.end(); ++it ) + { + if( (*it)->isKindOf( KINDOF_HERO ) ) + { + m_heroUnitsContained++; + } + } + } + // sanity DEBUG_ASSERTCRASH( m_containListSize == m_containList.size(), ("OpenContain::loadPostProcess - contain list count mismatch") ); diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp index 49d49491de..7634db8058 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp @@ -593,25 +593,13 @@ Object::~Object() } //------------------------------------------------------------------------------------------------- -void localIsHero( Object *obj, void* userData ) -{ - Bool *hero = (Bool*)userData; - - if( obj && obj->isKindOf( KINDOF_HERO ) ) - { - *hero = TRUE; - } -} - -//------------------------------------------------------------------------------------------------- +// TheSuperHackers @performance bobtista 13/11/2025 Use cached hero count for O(1) lookup instead of O(n) iteration. Bool Object::isHero() const { ContainModuleInterface *contain = getContain(); if( contain ) { - Bool heroInside = FALSE; - contain->iterateContained( localIsHero, (void*)(&heroInside), FALSE ); - if( heroInside ) + if( contain->getHeroUnitsContained() > 0 ) { return TRUE; } diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ContainModule.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ContainModule.h index f85817f831..5a2db53fd1 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ContainModule.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ContainModule.h @@ -175,6 +175,7 @@ class ContainModuleInterface virtual const Object *friend_getRider() const = 0; ///< Damn. The draw order dependency bug for riders means that our draw module needs to cheat to get around it. virtual Real getContainedItemsMass() const = 0; virtual UnsignedInt getStealthUnitsContained() const = 0; + virtual UnsignedInt getHeroUnitsContained() const = 0; virtual Bool calcBestGarrisonPosition( Coord3D *sourcePos, const Coord3D *targetPos ) = 0; virtual Bool attemptBestFirePointPosition( Object *source, Weapon *weapon, Object *victim ) = 0; diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/OpenContain.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/OpenContain.h index 180fc86aac..3af77883ed 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/OpenContain.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/OpenContain.h @@ -174,6 +174,7 @@ class OpenContain : public UpdateModule, virtual const Object *friend_getRider() const{return NULL;} ///< Damn. The draw order dependency bug for riders means that our draw module needs to cheat to get around it. virtual Real getContainedItemsMass() const; virtual UnsignedInt getStealthUnitsContained() const { return m_stealthUnitsContained; } + virtual UnsignedInt getHeroUnitsContained() const { return m_heroUnitsContained; } virtual PlayerMaskType getPlayerWhoEntered(void) const { return m_playerEnteredMask; } @@ -259,6 +260,8 @@ class OpenContain : public UpdateModule, ObjectEnterExitMap m_objectEnterExitInfo; UnsignedInt m_stealthUnitsContained; ///< number of stealth units that can't be seen by enemy players. + UnsignedInt m_heroUnitsContained; ///< cached hero count + XferVersion m_xferVersion; ///< version of loaded save file for loadPostProcess Int m_whichExitPath; ///< Cycles from 1 to n and is used only in modules whose data has numberOfExitPaths > 1. UnsignedInt m_doorCloseCountdown; ///< When should I shut my door. diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp index 2f2bbea878..51f088d961 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp @@ -129,6 +129,8 @@ OpenContain::OpenContain( Thing *thing, const ModuleData* moduleData ) : UpdateM m_lastLoadSoundFrame = 0; m_containListSize = 0; m_stealthUnitsContained = 0; + m_heroUnitsContained = 0; + m_xferVersion = 1; m_doorCloseCountdown = 0; m_rallyPoint.zero(); @@ -374,6 +376,10 @@ void OpenContain::addToContainList( Object *rider ) { m_stealthUnitsContained++; } + if( rider->isKindOf( KINDOF_HERO ) ) + { + m_heroUnitsContained++; + } } //------------------------------------------------------------------------------------------------- @@ -650,6 +656,7 @@ void OpenContain::removeFromContainViaIterator( ContainedItemsList::iterator it, m_containListSize--; if( rider->isKindOf( KINDOF_STEALTH_GARRISON ) ) { + DEBUG_ASSERTCRASH( m_stealthUnitsContained > 0, ("OpenContain::removeFromContainViaIterator - Removing stealth unit but stealth count is %d", m_stealthUnitsContained) ); m_stealthUnitsContained--; if( exposeStealthUnits ) { @@ -660,6 +667,11 @@ void OpenContain::removeFromContainViaIterator( ContainedItemsList::iterator it, } } } + if( rider->isKindOf( KINDOF_HERO ) ) + { + DEBUG_ASSERTCRASH( m_heroUnitsContained > 0, ("OpenContain::removeFromContainViaIterator - Removing hero but hero count is %d", m_heroUnitsContained) ); + m_heroUnitsContained--; + } if (isEnclosingContainerFor( rider )) @@ -1667,15 +1679,23 @@ void OpenContain::crc( Xfer *xfer ) // ------------------------------------------------------------------------------------------------ /** Xfer method * Version Info: - * 1: Initial version */ + * 1: Initial version + * 2: Added m_passengerAllowedToFire + * 3: TheSuperHackers @tweak Serialize hero units contained count + */ // ------------------------------------------------------------------------------------------------ void OpenContain::xfer( Xfer *xfer ) { // version - const XferVersion currentVersion = 2; +#if RETAIL_COMPATIBLE_XFER_SAVE + XferVersion currentVersion = 2; +#else + XferVersion currentVersion = 3; +#endif XferVersion version = currentVersion; xfer->xferVersion( &version, currentVersion ); + m_xferVersion = version; // extend base class UpdateModule::xfer( xfer ); @@ -1751,6 +1771,12 @@ void OpenContain::xfer( Xfer *xfer ) // stealth units contained xfer->xferUnsignedInt( &m_stealthUnitsContained ); + // hero units contained + if (version >= 3) + { + xfer->xferUnsignedInt( &m_heroUnitsContained ); + } + // door close countdown xfer->xferUnsignedInt( &m_doorCloseCountdown ); @@ -1890,6 +1916,19 @@ void OpenContain::loadPostProcess( void ) } + if (m_xferVersion < 3) + { + // Restore hero count by iterating hero objects for old save versions + m_heroUnitsContained = 0; + for( ContainedItemsList::const_iterator it = m_containList.begin(); it != m_containList.end(); ++it ) + { + if( (*it)->isKindOf( KINDOF_HERO ) ) + { + m_heroUnitsContained++; + } + } + } + // sanity DEBUG_ASSERTCRASH( m_containListSize == m_containList.size(), ("OpenContain::loadPostProcess - contain list count mismatch") ); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp index bca7c39b87..7052147358 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp @@ -2067,25 +2067,14 @@ Bool Object::isNonFactionStructure(void) const return isStructure() && !isFactionStructure(); } -void localIsHero( Object *obj, void* userData ) -{ - Bool *hero = (Bool*)userData; - - if( obj && obj->isKindOf( KINDOF_HERO ) ) - { - *hero = TRUE; - } -} - //------------------------------------------------------------------------------------------------- +// TheSuperHackers @performance bobtista 13/11/2025 Use cached hero count for O(1) lookup instead of O(n) iteration. Bool Object::isHero(void) const { ContainModuleInterface *contain = getContain(); if( contain ) { - Bool heroInside = FALSE; - contain->iterateContained( localIsHero, (void*)(&heroInside), FALSE ); - if( heroInside ) + if( contain->getHeroUnitsContained() > 0 ) { return TRUE; } From 5e8f1b8df3b97244185c4cbc9d6c3832acc14037 Mon Sep 17 00:00:00 2001 From: Bobby Battista Date: Wed, 31 Dec 2025 07:25:23 -0500 Subject: [PATCH 57/70] refactor(network): Simplify error prone net packet size calculations with packed structs (#1675) --- Core/GameEngine/CMakeLists.txt | 1 + .../Include/GameNetwork/NetCommandMsg.h | 80 ++- .../Include/GameNetwork/NetPacket.h | 3 +- .../Include/GameNetwork/NetPacketStructs.h | 420 +++++++++++ .../System/GameMemoryInitPools_Generals.inl | 2 + .../System/GameMemoryInitPools_GeneralsMD.inl | 2 + .../Source/GameNetwork/ConnectionManager.cpp | 6 +- .../Source/GameNetwork/NetCommandMsg.cpp | 211 +++++- .../Source/GameNetwork/NetPacket.cpp | 650 ++---------------- 9 files changed, 781 insertions(+), 594 deletions(-) create mode 100644 Core/GameEngine/Include/GameNetwork/NetPacketStructs.h diff --git a/Core/GameEngine/CMakeLists.txt b/Core/GameEngine/CMakeLists.txt index cd3cb89e9e..eb7b7541e1 100644 --- a/Core/GameEngine/CMakeLists.txt +++ b/Core/GameEngine/CMakeLists.txt @@ -546,6 +546,7 @@ set(GAMEENGINE_SRC Include/GameNetwork/NetCommandRef.h Include/GameNetwork/NetCommandWrapperList.h Include/GameNetwork/NetPacket.h + Include/GameNetwork/NetPacketStructs.h Include/GameNetwork/NetworkDefs.h Include/GameNetwork/NetworkInterface.h Include/GameNetwork/networkutil.h diff --git a/Core/GameEngine/Include/GameNetwork/NetCommandMsg.h b/Core/GameEngine/Include/GameNetwork/NetCommandMsg.h index 59b05f88e2..84eb156668 100644 --- a/Core/GameEngine/Include/GameNetwork/NetCommandMsg.h +++ b/Core/GameEngine/Include/GameNetwork/NetCommandMsg.h @@ -44,12 +44,13 @@ class NetCommandMsg : public MemoryPoolObject void setExecutionFrame(UnsignedInt frame) { m_executionFrame = frame; } void setPlayerID(UnsignedInt playerID) { m_playerID = playerID; } void setID(UnsignedShort id) { m_id = id; } - UnsignedInt getExecutionFrame() { return m_executionFrame; } - UnsignedInt getPlayerID() { return m_playerID; } - UnsignedShort getID() { return m_id; } + UnsignedInt getExecutionFrame() const { return m_executionFrame; } + UnsignedInt getPlayerID() const { return m_playerID; } + UnsignedShort getID() const { return m_id; } void setNetCommandType(NetCommandType type) { m_commandType = type; } NetCommandType getNetCommandType() { return m_commandType; } virtual Int getSortNumber(); + virtual size_t getPackedByteCount() const = 0; void attach(); void detach(); @@ -76,10 +77,12 @@ class NetGameCommandMsg : public NetCommandMsg NetGameCommandMsg(GameMessage *msg); //virtual ~NetGameCommandMsg(); - GameMessage *constructGameMessage(); + GameMessage *constructGameMessage() const; void addArgument(const GameMessageArgumentDataType type, GameMessageArgumentType arg); void setGameMessageType(GameMessage::Type type); + virtual size_t getPackedByteCount() const; + protected: Int m_numArgs; Int m_argSize; @@ -106,6 +109,8 @@ class NetAckBothCommandMsg : public NetCommandMsg void setOriginalPlayerID(UnsignedByte originalPlayerID); virtual Int getSortNumber(); + virtual size_t getPackedByteCount() const; + protected: UnsignedShort m_commandID; UnsignedByte m_originalPlayerID; @@ -130,6 +135,8 @@ class NetAckStage1CommandMsg : public NetCommandMsg void setOriginalPlayerID(UnsignedByte originalPlayerID); virtual Int getSortNumber(); + virtual size_t getPackedByteCount() const; + protected: UnsignedShort m_commandID; UnsignedByte m_originalPlayerID; @@ -154,6 +161,8 @@ class NetAckStage2CommandMsg : public NetCommandMsg void setOriginalPlayerID(UnsignedByte originalPlayerID); virtual Int getSortNumber(); + virtual size_t getPackedByteCount() const; + protected: UnsignedShort m_commandID; UnsignedByte m_originalPlayerID; @@ -170,6 +179,8 @@ class NetFrameCommandMsg : public NetCommandMsg void setCommandCount(UnsignedShort commandCount); UnsignedShort getCommandCount(); + virtual size_t getPackedByteCount() const; + protected: UnsignedShort m_commandCount; }; @@ -185,6 +196,8 @@ class NetPlayerLeaveCommandMsg : public NetCommandMsg UnsignedByte getLeavingPlayerID(); void setLeavingPlayerID(UnsignedByte id); + virtual size_t getPackedByteCount() const; + protected: UnsignedByte m_leavingPlayerID; }; @@ -202,6 +215,8 @@ class NetRunAheadMetricsCommandMsg : public NetCommandMsg Int getAverageFps(); void setAverageFps(Int fps); + virtual size_t getPackedByteCount() const; + protected: Real m_averageLatency; Int m_averageFps; @@ -221,6 +236,8 @@ class NetRunAheadCommandMsg : public NetCommandMsg UnsignedByte getFrameRate(); void setFrameRate(UnsignedByte frameRate); + virtual size_t getPackedByteCount() const; + protected: UnsignedShort m_runAhead; UnsignedByte m_frameRate; @@ -237,6 +254,8 @@ class NetDestroyPlayerCommandMsg : public NetCommandMsg UnsignedInt getPlayerIndex(); void setPlayerIndex(UnsignedInt playerIndex); + virtual size_t getPackedByteCount() const; + protected: UnsignedInt m_playerIndex; }; @@ -248,6 +267,8 @@ class NetKeepAliveCommandMsg : public NetCommandMsg public: NetKeepAliveCommandMsg(); //virtual ~NetKeepAliveCommandMsg(); + + virtual size_t getPackedByteCount() const; }; //----------------------------------------------------------------------------- @@ -257,6 +278,8 @@ class NetDisconnectKeepAliveCommandMsg : public NetCommandMsg public: NetDisconnectKeepAliveCommandMsg(); //virtual ~NetDisconnectKeepAliveCommandMsg(); + + virtual size_t getPackedByteCount() const; }; //----------------------------------------------------------------------------- @@ -273,6 +296,8 @@ class NetDisconnectPlayerCommandMsg : public NetCommandMsg UnsignedInt getDisconnectFrame(); void setDisconnectFrame(UnsignedInt frame); + virtual size_t getPackedByteCount() const; + protected: UnsignedByte m_disconnectSlot; UnsignedInt m_disconnectFrame; @@ -285,6 +310,8 @@ class NetPacketRouterQueryCommandMsg : public NetCommandMsg public: NetPacketRouterQueryCommandMsg(); //virtual ~NetPacketRouterQueryCommandMsg(); + + virtual size_t getPackedByteCount() const; }; //----------------------------------------------------------------------------- @@ -294,6 +321,8 @@ class NetPacketRouterAckCommandMsg : public NetCommandMsg public: NetPacketRouterAckCommandMsg(); //virtual ~NetPacketRouterAckCommandMsg(); + + virtual size_t getPackedByteCount() const; }; //----------------------------------------------------------------------------- @@ -307,6 +336,8 @@ class NetDisconnectChatCommandMsg : public NetCommandMsg UnicodeString getText(); void setText(UnicodeString text); + virtual size_t getPackedByteCount() const; + protected: UnicodeString m_text; }; @@ -325,6 +356,8 @@ class NetChatCommandMsg : public NetCommandMsg Int getPlayerMask( void ); void setPlayerMask( Int playerMask ); + virtual size_t getPackedByteCount() const; + protected: UnicodeString m_text; Int m_playerMask; @@ -344,6 +377,8 @@ class NetDisconnectVoteCommandMsg : public NetCommandMsg UnsignedInt getVoteFrame(); void setVoteFrame(UnsignedInt voteFrame); + virtual size_t getPackedByteCount() const; + protected: UnsignedByte m_slot; UnsignedInt m_voteFrame; @@ -359,6 +394,9 @@ class NetProgressCommandMsg: public NetCommandMsg UnsignedByte getPercentage(); void setPercentage( UnsignedByte percent ); + + virtual size_t getPackedByteCount() const; + protected: UnsignedByte m_percent; }; @@ -374,6 +412,8 @@ class NetWrapperCommandMsg : public NetCommandMsg UnsignedByte * getData(); void setData(UnsignedByte *data, UnsignedInt dataLength); + virtual size_t getPackedByteCount() const; + UnsignedInt getChunkNumber(); void setChunkNumber(UnsignedInt chunkNumber); @@ -421,6 +461,8 @@ class NetFileCommandMsg : public NetCommandMsg UnsignedByte * getFileData(); void setFileData(UnsignedByte *data, UnsignedInt dataLength); + virtual size_t getPackedByteCount() const; + protected: AsciiString m_portableFilename; @@ -448,6 +490,8 @@ class NetFileAnnounceCommandMsg : public NetCommandMsg UnsignedByte getPlayerMask(void); void setPlayerMask(UnsignedByte playerMask); + virtual size_t getPackedByteCount() const; + protected: AsciiString m_portableFilename; UnsignedShort m_fileID; @@ -468,6 +512,8 @@ class NetFileProgressCommandMsg : public NetCommandMsg Int getProgress(); void setProgress(Int val); + virtual size_t getPackedByteCount() const; + protected: UnsignedShort m_fileID; Int m_progress; @@ -483,6 +529,8 @@ class NetDisconnectFrameCommandMsg : public NetCommandMsg UnsignedInt getDisconnectFrame(); void setDisconnectFrame(UnsignedInt disconnectFrame); + virtual size_t getPackedByteCount() const; + protected: UnsignedInt m_disconnectFrame; }; @@ -497,6 +545,8 @@ class NetDisconnectScreenOffCommandMsg : public NetCommandMsg UnsignedInt getNewFrame(); void setNewFrame(UnsignedInt newFrame); + virtual size_t getPackedByteCount() const; + protected: UnsignedInt m_newFrame; }; @@ -511,6 +561,28 @@ class NetFrameResendRequestCommandMsg : public NetCommandMsg UnsignedInt getFrameToResend(); void setFrameToResend(UnsignedInt frame); + virtual size_t getPackedByteCount() const; + protected: UnsignedInt m_frameToResend; }; + +class NetLoadCompleteCommandMsg : public NetCommandMsg +{ + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(NetLoadCompleteCommandMsg, "NetLoadCompleteCommandMsg") +public: + NetLoadCompleteCommandMsg(); + //virtual ~NetLoadCompleteCommandMsg(); + + virtual size_t getPackedByteCount() const; +}; + +class NetTimeOutGameStartCommandMsg : public NetCommandMsg +{ + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(NetTimeOutGameStartCommandMsg, "NetTimeOutGameStartCommandMsg") +public: + NetTimeOutGameStartCommandMsg(); + //virtual ~NetTimeOutGameStartCommandMsg(); + + virtual size_t getPackedByteCount() const; +}; diff --git a/Core/GameEngine/Include/GameNetwork/NetPacket.h b/Core/GameEngine/Include/GameNetwork/NetPacket.h index f117df083a..d4980a9eef 100644 --- a/Core/GameEngine/Include/GameNetwork/NetPacket.h +++ b/Core/GameEngine/Include/GameNetwork/NetPacket.h @@ -69,10 +69,11 @@ class NetPacket : public MemoryPoolObject UnsignedInt getAddr(); UnsignedShort getPort(); -protected: static UnsignedInt GetBufferSizeNeededForCommand(NetCommandMsg *msg); static void FillBufferWithCommand(UnsignedByte *buffer, NetCommandRef *msg); +protected: + // These functions return the size of the command without any compression, repetition, etc. // i.e. All of the required fields are taken into account when returning the size. static UnsignedInt GetGameCommandSize(NetCommandMsg *msg); diff --git a/Core/GameEngine/Include/GameNetwork/NetPacketStructs.h b/Core/GameEngine/Include/GameNetwork/NetPacketStructs.h new file mode 100644 index 0000000000..35f5ce997a --- /dev/null +++ b/Core/GameEngine/Include/GameNetwork/NetPacketStructs.h @@ -0,0 +1,420 @@ +/* +** 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 @refactor BobTista 07/10/2025 +// Packed struct definitions for network packet serialization/deserialization. +// +//////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "GameNetwork/NetworkDefs.h" + +// Ensure structs are packed to 1-byte alignment for network protocol compatibility +#pragma pack(push, 1) + +//////////////////////////////////////////////////////////////////////////////// +// Network packet field type definitions +//////////////////////////////////////////////////////////////////////////////// + +// Network packet field type definitions +typedef UnsignedByte NetPacketFieldType; + +namespace NetPacketFieldTypes { + constexpr const NetPacketFieldType CommandType = 'T'; // NetCommandType field + constexpr const NetPacketFieldType Relay = 'R'; // Relay field + constexpr const NetPacketFieldType PlayerId = 'P'; // Player ID field + constexpr const NetPacketFieldType CommandId = 'C'; // Command ID field + constexpr const NetPacketFieldType Frame = 'F'; // Frame field + constexpr const NetPacketFieldType Data = 'D'; // Data payload field +} + +//////////////////////////////////////////////////////////////////////////////// +// Common packet field structures +//////////////////////////////////////////////////////////////////////////////// + +// Command Type field: 'T' + UnsignedByte +struct NetPacketCommandTypeField { + char header; + UnsignedByte commandType; +}; + +// Relay field: 'R' + UnsignedByte +struct NetPacketRelayField { + char header; + UnsignedByte relay; +}; + +// Player ID field: 'P' + UnsignedByte +struct NetPacketPlayerIdField { + char header; + UnsignedByte playerId; +}; + +// Frame field: 'F' + UnsignedInt +struct NetPacketFrameField { + char header; + UnsignedInt frame; +}; + +// Command ID field: 'C' + UnsignedShort +struct NetPacketCommandIdField { + char header; + UnsignedShort commandId; +}; + +// Data field header: 'D' (followed by variable-length data) +struct NetPacketDataFieldHeader { + char header; +}; + +//////////////////////////////////////////////////////////////////////////////// +// Acknowledgment Command Packets +//////////////////////////////////////////////////////////////////////////////// + +// ACK command packet structure +// Fields: T + type, P + playerID, D + commandID + originalPlayerID +struct NetPacketAckCommand { + NetPacketCommandTypeField commandType; + NetPacketPlayerIdField playerId; + NetPacketDataFieldHeader dataHeader; + UnsignedShort commandId; // Command ID being acknowledged + UnsignedByte originalPlayerId; // Original player who sent the command +}; + +//////////////////////////////////////////////////////////////////////////////// +// Frame Info Command Packet +//////////////////////////////////////////////////////////////////////////////// + +// Frame info command packet structure +// Fields: T + type, F + frame, R + relay, P + playerID, C + commandID, D + commandCount +struct NetPacketFrameCommand { + NetPacketCommandTypeField commandType; + NetPacketFrameField frame; + NetPacketRelayField relay; + NetPacketPlayerIdField playerId; + NetPacketCommandIdField commandId; + NetPacketDataFieldHeader dataHeader; + UnsignedShort commandCount; +}; + +//////////////////////////////////////////////////////////////////////////////// +// Player Leave Command Packet +//////////////////////////////////////////////////////////////////////////////// + +// Player leave command packet structure +// Fields: T + type, R + relay, F + frame, P + playerID, C + commandID, D + leavingPlayerID +struct NetPacketPlayerLeaveCommand { + NetPacketCommandTypeField commandType; + NetPacketRelayField relay; + NetPacketFrameField frame; + NetPacketPlayerIdField playerId; + NetPacketCommandIdField commandId; + NetPacketDataFieldHeader dataHeader; + UnsignedByte leavingPlayerId; +}; + +//////////////////////////////////////////////////////////////////////////////// +// Run Ahead Metrics Command Packet +//////////////////////////////////////////////////////////////////////////////// + +// Run ahead metrics command packet structure +// Fields: T + type, R + relay, P + playerID, C + commandID, D + averageLatency + averageFps +// TODO: averageFps should be UnsignedShort to match FillBufferWithRunAheadMetricsCommand, but +// original GetRunAheadMetricsCommandSize incorrectly counted it as UnsignedByte +struct NetPacketRunAheadMetricsCommand { + NetPacketCommandTypeField commandType; + NetPacketRelayField relay; + NetPacketPlayerIdField playerId; + NetPacketCommandIdField commandId; + NetPacketDataFieldHeader dataHeader; + Real averageLatency; + UnsignedByte averageFps; +}; + +//////////////////////////////////////////////////////////////////////////////// +// Run Ahead Command Packet +//////////////////////////////////////////////////////////////////////////////// + +// Run ahead command packet structure +// Fields: T + type, R + relay, F + frame, P + playerID, C + commandID, D + runAhead + frameRate +struct NetPacketRunAheadCommand { + NetPacketCommandTypeField commandType; + NetPacketRelayField relay; + NetPacketFrameField frame; + NetPacketPlayerIdField playerId; + NetPacketCommandIdField commandId; + NetPacketDataFieldHeader dataHeader; + UnsignedShort runAhead; + UnsignedByte frameRate; +}; + +//////////////////////////////////////////////////////////////////////////////// +// Destroy Player Command Packet +//////////////////////////////////////////////////////////////////////////////// + +// Destroy player command packet structure +// Fields: T + type, R + relay, F + frame, P + playerID, C + commandID, D + playerIndex +struct NetPacketDestroyPlayerCommand { + NetPacketCommandTypeField commandType; + NetPacketRelayField relay; + NetPacketFrameField frame; + NetPacketPlayerIdField playerId; + NetPacketCommandIdField commandId; + NetPacketDataFieldHeader dataHeader; + UnsignedInt playerIndex; +}; + +//////////////////////////////////////////////////////////////////////////////// +// Keep Alive Command Packet +//////////////////////////////////////////////////////////////////////////////// + +// Keep alive command packet structure +// Fields: T + type, R + relay, P + playerID, D +struct NetPacketKeepAliveCommand { + NetPacketCommandTypeField commandType; + NetPacketRelayField relay; + NetPacketPlayerIdField playerId; + NetPacketDataFieldHeader dataHeader; +}; + +//////////////////////////////////////////////////////////////////////////////// +// Disconnect Keep Alive Command Packet +//////////////////////////////////////////////////////////////////////////////// + +// Disconnect keep alive command packet structure +// Fields: T + type, R + relay, P + playerID, D +struct NetPacketDisconnectKeepAliveCommand { + NetPacketCommandTypeField commandType; + NetPacketRelayField relay; + NetPacketPlayerIdField playerId; + NetPacketDataFieldHeader dataHeader; +}; + +//////////////////////////////////////////////////////////////////////////////// +// Disconnect Player Command Packet +//////////////////////////////////////////////////////////////////////////////// + +// Disconnect player command packet structure +// Fields: T + type, R + relay, P + playerID, C + commandID, D + slot + disconnectFrame +struct NetPacketDisconnectPlayerCommand { + NetPacketCommandTypeField commandType; + NetPacketRelayField relay; + NetPacketPlayerIdField playerId; + NetPacketCommandIdField commandId; + NetPacketDataFieldHeader dataHeader; + UnsignedByte slot; + UnsignedInt disconnectFrame; +}; + +//////////////////////////////////////////////////////////////////////////////// +// Packet Router Command Packets +//////////////////////////////////////////////////////////////////////////////// + +// Packet router query command packet +// Fields: T + type, R + relay, P + playerID, D +struct NetPacketRouterQueryCommand { + NetPacketCommandTypeField commandType; + NetPacketRelayField relay; + NetPacketPlayerIdField playerId; + NetPacketDataFieldHeader dataHeader; +}; + +// Packet router ack command packet +// Fields: T + type, R + relay, P + playerID, D +struct NetPacketRouterAckCommand { + NetPacketCommandTypeField commandType; + NetPacketRelayField relay; + NetPacketPlayerIdField playerId; + NetPacketDataFieldHeader dataHeader; +}; + +//////////////////////////////////////////////////////////////////////////////// +// Disconnect Vote Command Packet +//////////////////////////////////////////////////////////////////////////////// + +// Disconnect vote command +// Fields: T + type, R + relay, P + playerID, C + commandID, D + slot + voteFrame +struct NetPacketDisconnectVoteCommand { + NetPacketCommandTypeField commandType; + NetPacketRelayField relay; + NetPacketPlayerIdField playerId; + NetPacketCommandIdField commandId; + NetPacketDataFieldHeader dataHeader; + UnsignedByte slot; + UnsignedInt voteFrame; +}; + +//////////////////////////////////////////////////////////////////////////////// +// Packed Structs for getPackedByteCount() calculations +// These structs represent the fixed portion of variable-length command messages +//////////////////////////////////////////////////////////////////////////////// + +// Chat command packed struct +// Fixed fields: T + type, F + frame, R + relay, P + playerID, C + commandID, D +struct NetPacketChatCommand { + NetPacketCommandTypeField commandType; + NetPacketFrameField frame; + NetPacketRelayField relay; + NetPacketPlayerIdField playerId; + NetPacketCommandIdField commandId; + NetPacketDataFieldHeader dataHeader; + // Variable fields: UnsignedByte textLength + UnsignedShort text[textLength] + Int playerMask +}; + +// Disconnect chat command packed struct +// Fixed fields: T + type, R + relay, P + playerID, D +struct NetPacketDisconnectChatCommand { + NetPacketCommandTypeField commandType; + NetPacketRelayField relay; + NetPacketPlayerIdField playerId; + NetPacketDataFieldHeader dataHeader; + // Variable fields: UnsignedByte textLength + UnsignedShort text[textLength] +}; + +// Game command packed struct +// Fixed fields: T + type, F + frame, R + relay, P + playerID, C + commandID, D +struct NetPacketGameCommand { + NetPacketCommandTypeField commandType; + NetPacketFrameField frame; + NetPacketRelayField relay; + NetPacketPlayerIdField playerId; + NetPacketCommandIdField commandId; + NetPacketDataFieldHeader dataHeader; + // Variable fields: game message arguments +}; + +// Wrapper command packet (fixed size - contains metadata about wrapped command) +// Fields: T + type, R + relay, P + playerID, C + commandID, D + metadata +struct NetPacketWrapperCommand { + NetPacketCommandTypeField commandType; + NetPacketRelayField relay; + NetPacketPlayerIdField playerId; + NetPacketCommandIdField commandId; + NetPacketDataFieldHeader dataHeader; + UnsignedShort wrappedCommandId; + UnsignedInt chunkNumber; + UnsignedInt numChunks; + UnsignedInt totalDataLength; + UnsignedInt dataLength; + UnsignedInt dataOffset; +}; + +// File command packed struct +// Fixed fields: T + type, R + relay, P + playerID, C + commandID, D +struct NetPacketFileCommand { + NetPacketCommandTypeField commandType; + NetPacketRelayField relay; + NetPacketPlayerIdField playerId; + NetPacketCommandIdField commandId; + NetPacketDataFieldHeader dataHeader; + // Variable fields: null-terminated filename + UnsignedInt fileDataLength + file data +}; + +// File announce command packed struct +// Fixed fields: T + type, R + relay, P + playerID, C + commandID, D +struct NetPacketFileAnnounceCommand { + NetPacketCommandTypeField commandType; + NetPacketRelayField relay; + NetPacketPlayerIdField playerId; + NetPacketCommandIdField commandId; + NetPacketDataFieldHeader dataHeader; + // Variable fields: null-terminated filename + UnsignedShort fileID + UnsignedByte playerMask +}; + +// File progress command packet +// Fields: T + type, R + relay, P + playerID, C + commandID, D + fileID + progress +struct NetPacketFileProgressCommand { + NetPacketCommandTypeField commandType; + NetPacketRelayField relay; + NetPacketPlayerIdField playerId; + NetPacketCommandIdField commandId; + NetPacketDataFieldHeader dataHeader; + UnsignedShort fileId; + Int progress; +}; + +// Progress message packet +// Fields: T + type, R + relay, P + playerID, D + percentage +struct NetPacketProgressMessage { + NetPacketCommandTypeField commandType; + NetPacketRelayField relay; + NetPacketPlayerIdField playerId; + NetPacketDataFieldHeader dataHeader; + UnsignedByte percentage; +}; + +// Load complete message packet +// Fields: T + type, R + relay, P + playerID, D +// TODO: commandId field is missing. FillBufferWithLoadCompleteMessage writes it, but +// original GetLoadCompleteMessageSize did not count it +struct NetPacketLoadCompleteMessage { + NetPacketCommandTypeField commandType; + NetPacketRelayField relay; + NetPacketPlayerIdField playerId; + NetPacketDataFieldHeader dataHeader; +}; + +// Timeout game start message packet +// Fields: T + type, R + relay, P + playerID, D +// TODO: commandId field is missing. FillBufferWithTimeOutGameStartMessage writes it, but +// original GetTimeOutGameStartMessageSize did not count it +struct NetPacketTimeOutGameStartMessage { + NetPacketCommandTypeField commandType; + NetPacketRelayField relay; + NetPacketPlayerIdField playerId; + NetPacketDataFieldHeader dataHeader; +}; + +// Disconnect frame command packet +// Fields: T + type, P + playerID, C + commandID, R + relay, D + disconnectFrame +struct NetPacketDisconnectFrameCommand { + NetPacketCommandTypeField commandType; + NetPacketPlayerIdField playerId; + NetPacketCommandIdField commandId; + NetPacketRelayField relay; + NetPacketDataFieldHeader dataHeader; + UnsignedInt disconnectFrame; +}; + +// Disconnect screen off command packet +// Fields: T + type, P + playerID, C + commandID, R + relay, D + newFrame +struct NetPacketDisconnectScreenOffCommand { + NetPacketCommandTypeField commandType; + NetPacketPlayerIdField playerId; + NetPacketCommandIdField commandId; + NetPacketRelayField relay; + NetPacketDataFieldHeader dataHeader; + UnsignedInt newFrame; +}; + +// Frame resend request command packet +// Fields: T + type, P + playerID, C + commandID, R + relay, D + frameToResend +struct NetPacketFrameResendRequestCommand { + NetPacketCommandTypeField commandType; + NetPacketPlayerIdField playerId; + NetPacketCommandIdField commandId; + NetPacketRelayField relay; + NetPacketDataFieldHeader dataHeader; + UnsignedInt frameToResend; +}; + +// Restore normal struct packing +#pragma pack(pop) diff --git a/Core/GameEngine/Source/Common/System/GameMemoryInitPools_Generals.inl b/Core/GameEngine/Source/Common/System/GameMemoryInitPools_Generals.inl index b049809df1..d8177c459d 100644 --- a/Core/GameEngine/Source/Common/System/GameMemoryInitPools_Generals.inl +++ b/Core/GameEngine/Source/Common/System/GameMemoryInitPools_Generals.inl @@ -553,6 +553,8 @@ static PoolSizeRec PoolSizes[] = { "NetChatCommandMsg", 32, 32 }, { "NetDisconnectVoteCommandMsg", 32, 32 }, { "NetProgressCommandMsg", 32, 32 }, + { "NetLoadCompleteCommandMsg", 32, 32 }, + { "NetTimeOutGameStartCommandMsg", 32, 32 }, { "NetWrapperCommandMsg", 32, 32 }, { "NetFileCommandMsg", 32, 32 }, { "NetFileAnnounceCommandMsg", 32, 32 }, diff --git a/Core/GameEngine/Source/Common/System/GameMemoryInitPools_GeneralsMD.inl b/Core/GameEngine/Source/Common/System/GameMemoryInitPools_GeneralsMD.inl index 2bf2e64c15..f9f5b5a0a1 100644 --- a/Core/GameEngine/Source/Common/System/GameMemoryInitPools_GeneralsMD.inl +++ b/Core/GameEngine/Source/Common/System/GameMemoryInitPools_GeneralsMD.inl @@ -549,6 +549,8 @@ static PoolSizeRec PoolSizes[] = { "NetChatCommandMsg", 32, 32 }, { "NetDisconnectVoteCommandMsg", 32, 32 }, { "NetProgressCommandMsg", 32, 32 }, + { "NetLoadCompleteCommandMsg", 32, 32 }, + { "NetTimeOutGameStartCommandMsg", 32, 32 }, { "NetWrapperCommandMsg", 32, 32 }, { "NetFileCommandMsg", 32, 32 }, { "NetFileAnnounceCommandMsg", 32, 32 }, diff --git a/Core/GameEngine/Source/GameNetwork/ConnectionManager.cpp b/Core/GameEngine/Source/GameNetwork/ConnectionManager.cpp index cef851a74a..49d4676ffb 100644 --- a/Core/GameEngine/Source/GameNetwork/ConnectionManager.cpp +++ b/Core/GameEngine/Source/GameNetwork/ConnectionManager.cpp @@ -2270,12 +2270,11 @@ void ConnectionManager::updateLoadProgress( Int progress ) void ConnectionManager::loadProgressComplete() { - NetCommandMsg *msg = newInstance(NetCommandMsg); + NetLoadCompleteCommandMsg *msg = newInstance(NetLoadCompleteCommandMsg); msg->setPlayerID( m_localSlot ); if (DoesCommandRequireACommandID(msg->getNetCommandType()) == TRUE) { msg->setID(GenerateNextCommandID()); } - msg->setNetCommandType(NETCOMMANDTYPE_LOADCOMPLETE); processLoadComplete(msg); sendLocalCommand(msg, 0xff ^ (1 << m_localSlot)); @@ -2284,9 +2283,8 @@ void ConnectionManager::loadProgressComplete() void ConnectionManager::sendTimeOutGameStart() { - NetCommandMsg *msg = newInstance(NetCommandMsg); + NetTimeOutGameStartCommandMsg *msg = newInstance(NetTimeOutGameStartCommandMsg); msg->setPlayerID( m_localSlot ); - msg->setNetCommandType(NETCOMMANDTYPE_TIMEOUTSTART); if (DoesCommandRequireACommandID(msg->getNetCommandType()) == TRUE) { msg->setID(GenerateNextCommandID()); } diff --git a/Core/GameEngine/Source/GameNetwork/NetCommandMsg.cpp b/Core/GameEngine/Source/GameNetwork/NetCommandMsg.cpp index ea6d56b728..951f3c8cf6 100644 --- a/Core/GameEngine/Source/GameNetwork/NetCommandMsg.cpp +++ b/Core/GameEngine/Source/GameNetwork/NetCommandMsg.cpp @@ -26,6 +26,8 @@ #include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine #include "GameNetwork/NetCommandMsg.h" +#include "GameNetwork/NetPacketStructs.h" +#include "GameNetwork/GameMessageParser.h" #include "Common/GameState.h" #include "Common/PlayerList.h" #include "Common/Player.h" @@ -161,7 +163,7 @@ static Int indexFromMask(UnsignedInt mask) /** * Construct a new GameMessage object from the data in this object. */ -GameMessage *NetGameCommandMsg::constructGameMessage() +GameMessage *NetGameCommandMsg::constructGameMessage() const { GameMessage *retval = newInstance(GameMessage)(m_type); @@ -222,6 +224,72 @@ void NetGameCommandMsg::setGameMessageType(GameMessage::Type type) { m_type = type; } +size_t NetGameCommandMsg::getPackedByteCount() const { + UnsignedShort msglen = sizeof(NetPacketGameCommand); + + // Variable data portion + GameMessage *gmsg = constructGameMessage(); + GameMessageParser *parser = newInstance(GameMessageParser)(gmsg); + + msglen += sizeof(GameMessage::Type); + msglen += sizeof(UnsignedByte); + + GameMessageParserArgumentType *arg = parser->getFirstArgumentType(); + while (arg != NULL) { + msglen += sizeof(UnsignedByte); // argument type + msglen += sizeof(UnsignedByte); // argument count + GameMessageArgumentDataType type = arg->getType(); + + switch (type) { + + case ARGUMENTDATATYPE_INTEGER: + msglen += arg->getArgCount() * sizeof(Int); + break; + case ARGUMENTDATATYPE_REAL: + msglen += arg->getArgCount() * sizeof(Real); + break; + case ARGUMENTDATATYPE_BOOLEAN: + msglen += arg->getArgCount() * sizeof(Bool); + break; + case ARGUMENTDATATYPE_OBJECTID: + msglen += arg->getArgCount() * sizeof(ObjectID); + break; + case ARGUMENTDATATYPE_DRAWABLEID: + msglen += arg->getArgCount() * sizeof(DrawableID); + break; + case ARGUMENTDATATYPE_TEAMID: + msglen += arg->getArgCount() * sizeof(UnsignedInt); + break; + case ARGUMENTDATATYPE_LOCATION: + msglen += arg->getArgCount() * sizeof(Coord3D); + break; + case ARGUMENTDATATYPE_PIXEL: + msglen += arg->getArgCount() * sizeof(ICoord2D); + break; + case ARGUMENTDATATYPE_PIXELREGION: + msglen += arg->getArgCount() * sizeof(IRegion2D); + break; + case ARGUMENTDATATYPE_TIMESTAMP: + msglen += arg->getArgCount() * sizeof(UnsignedInt); + break; + case ARGUMENTDATATYPE_WIDECHAR: + msglen += arg->getArgCount() * sizeof(WideChar); + break; + + } + + arg = arg->getNext(); + } + + deleteInstance(parser); + parser = NULL; + + deleteInstance(gmsg); + gmsg = NULL; + + return msglen; +} + //------------------------- // NetAckBothCommandMsg //------------------------- @@ -279,6 +347,10 @@ Int NetAckBothCommandMsg::getSortNumber() { return m_commandID; } +size_t NetAckBothCommandMsg::getPackedByteCount() const { + return sizeof(NetPacketAckCommand); +} + //------------------------- // NetAckStage1CommandMsg //------------------------- @@ -336,6 +408,10 @@ Int NetAckStage1CommandMsg::getSortNumber() { return m_commandID; } +size_t NetAckStage1CommandMsg::getPackedByteCount() const { + return sizeof(NetPacketAckCommand); +} + //------------------------- // NetAckStage2CommandMsg //------------------------- @@ -393,6 +469,10 @@ Int NetAckStage2CommandMsg::getSortNumber() { return m_commandID; } +size_t NetAckStage2CommandMsg::getPackedByteCount() const { + return sizeof(NetPacketAckCommand); +} + //------------------------- // NetFrameCommandMsg //------------------------- @@ -424,6 +504,10 @@ UnsignedShort NetFrameCommandMsg::getCommandCount() { return m_commandCount; } +size_t NetFrameCommandMsg::getPackedByteCount() const { + return sizeof(NetPacketFrameCommand); +} + //------------------------- // NetPlayerLeaveCommandMsg //------------------------- @@ -455,6 +539,10 @@ void NetPlayerLeaveCommandMsg::setLeavingPlayerID(UnsignedByte id) { m_leavingPlayerID = id; } +size_t NetPlayerLeaveCommandMsg::getPackedByteCount() const { + return sizeof(NetPacketPlayerLeaveCommand); +} + //------------------------- // NetRunAheadMetricsCommandMsg //------------------------- @@ -501,6 +589,10 @@ Int NetRunAheadMetricsCommandMsg::getAverageFps() { return m_averageFps; } +size_t NetRunAheadMetricsCommandMsg::getPackedByteCount() const { + return sizeof(NetPacketRunAheadMetricsCommand); +} + //------------------------- // NetRunAheadCommandMsg //------------------------- @@ -529,6 +621,10 @@ void NetRunAheadCommandMsg::setFrameRate(UnsignedByte frameRate) { m_frameRate = frameRate; } +size_t NetRunAheadCommandMsg::getPackedByteCount() const { + return sizeof(NetPacketRunAheadCommand); +} + //------------------------- // NetDestroyPlayerCommandMsg //------------------------- @@ -564,6 +660,10 @@ UnsignedInt NetDestroyPlayerCommandMsg::getPlayerIndex( void ) return m_playerIndex; } +size_t NetDestroyPlayerCommandMsg::getPackedByteCount() const { + return sizeof(NetPacketDestroyPlayerCommand); +} + //------------------------- // NetKeepAliveCommandMsg //------------------------- @@ -577,6 +677,10 @@ NetKeepAliveCommandMsg::NetKeepAliveCommandMsg() : NetCommandMsg() { NetKeepAliveCommandMsg::~NetKeepAliveCommandMsg() { } +size_t NetKeepAliveCommandMsg::getPackedByteCount() const { + return sizeof(NetPacketKeepAliveCommand); +} + //------------------------- // NetDisconnectKeepAliveCommandMsg //------------------------- @@ -590,6 +694,10 @@ NetDisconnectKeepAliveCommandMsg::NetDisconnectKeepAliveCommandMsg() : NetComman NetDisconnectKeepAliveCommandMsg::~NetDisconnectKeepAliveCommandMsg() { } +size_t NetDisconnectKeepAliveCommandMsg::getPackedByteCount() const { + return sizeof(NetPacketDisconnectKeepAliveCommand); +} + //------------------------- // NetDisconnectPlayerCommandMsg //------------------------- @@ -635,6 +743,10 @@ UnsignedInt NetDisconnectPlayerCommandMsg::getDisconnectFrame() { return m_disconnectFrame; } +size_t NetDisconnectPlayerCommandMsg::getPackedByteCount() const { + return sizeof(NetPacketDisconnectPlayerCommand); +} + //------------------------- // NetPacketRouterQueryCommandMsg //------------------------- @@ -651,6 +763,10 @@ NetPacketRouterQueryCommandMsg::NetPacketRouterQueryCommandMsg() : NetCommandMsg NetPacketRouterQueryCommandMsg::~NetPacketRouterQueryCommandMsg() { } +size_t NetPacketRouterQueryCommandMsg::getPackedByteCount() const { + return sizeof(NetPacketRouterQueryCommand); +} + //------------------------- // NetPacketRouterAckCommandMsg //------------------------- @@ -667,6 +783,10 @@ NetPacketRouterAckCommandMsg::NetPacketRouterAckCommandMsg() : NetCommandMsg() { NetPacketRouterAckCommandMsg::~NetPacketRouterAckCommandMsg() { } +size_t NetPacketRouterAckCommandMsg::getPackedByteCount() const { + return sizeof(NetPacketRouterAckCommand); +} + //------------------------- // NetDisconnectChatCommandMsg //------------------------- @@ -748,6 +868,24 @@ void NetChatCommandMsg::setPlayerMask( Int playerMask ) m_playerMask = playerMask; } +size_t NetChatCommandMsg::getPackedByteCount() const +{ + return sizeof(NetPacketChatCommand) + + sizeof(UnsignedByte) // text length byte + + m_text.getByteCount() + + sizeof(m_playerMask); +} + +//------------------------- +// NetDisconnectChatCommandMsg +//------------------------- +size_t NetDisconnectChatCommandMsg::getPackedByteCount() const +{ + return sizeof(NetPacketDisconnectChatCommand) + + sizeof(UnsignedByte) // text length byte + + m_text.getByteCount(); +} + //------------------------- // NetDisconnectVoteCommandMsg //------------------------- @@ -793,6 +931,10 @@ void NetDisconnectVoteCommandMsg::setVoteFrame(UnsignedInt voteFrame) { m_voteFrame = voteFrame; } +size_t NetDisconnectVoteCommandMsg::getPackedByteCount() const { + return sizeof(NetPacketDisconnectVoteCommand); +} + //------------------------- // NetProgressCommandMsg //------------------------- @@ -814,6 +956,10 @@ void NetProgressCommandMsg::setPercentage( UnsignedByte percent ) m_percent = percent; } +size_t NetProgressCommandMsg::getPackedByteCount() const { + return sizeof(NetPacketProgressMessage); +} + //------------------------- // NetWrapperCommandMsg //------------------------- @@ -889,6 +1035,10 @@ void NetWrapperCommandMsg::setWrappedCommandID(UnsignedShort wrappedCommandID) { m_wrappedCommandID = wrappedCommandID; } +size_t NetWrapperCommandMsg::getPackedByteCount() const { + return sizeof(NetPacketWrapperCommand) + m_dataLength; +} + //------------------------- // NetFileCommandMsg //------------------------- @@ -929,6 +1079,14 @@ void NetFileCommandMsg::setFileData(UnsignedByte *data, UnsignedInt dataLength) memcpy(m_data, data, dataLength); } +size_t NetFileCommandMsg::getPackedByteCount() const +{ + return sizeof(NetPacketFileCommand) + + m_portableFilename.getLength() + 1 + + sizeof(m_dataLength) + + m_dataLength; +} + //------------------------- // NetFileAnnounceCommandMsg //------------------------- @@ -968,6 +1126,13 @@ void NetFileAnnounceCommandMsg::setPlayerMask(UnsignedByte playerMask) { m_playerMask = playerMask; } +size_t NetFileAnnounceCommandMsg::getPackedByteCount() const +{ + return sizeof(NetPacketFileAnnounceCommand) + + m_portableFilename.getLength() + 1 + + sizeof(m_fileID) + + sizeof(m_playerMask); +} //------------------------- // NetFileProgressCommandMsg @@ -997,6 +1162,10 @@ void NetFileProgressCommandMsg::setProgress(Int val) { m_progress = val; } +size_t NetFileProgressCommandMsg::getPackedByteCount() const { + return sizeof(NetPacketFileProgressCommand); +} + //------------------------- // NetDisconnectFrameCommandMsg //------------------------- @@ -1016,6 +1185,10 @@ void NetDisconnectFrameCommandMsg::setDisconnectFrame(UnsignedInt disconnectFram m_disconnectFrame = disconnectFrame; } +size_t NetDisconnectFrameCommandMsg::getPackedByteCount() const { + return sizeof(NetPacketDisconnectFrameCommand); +} + //------------------------- // NetDisconnectScreenOffCommandMsg //------------------------- @@ -1035,6 +1208,10 @@ void NetDisconnectScreenOffCommandMsg::setNewFrame(UnsignedInt newFrame) { m_newFrame = newFrame; } +size_t NetDisconnectScreenOffCommandMsg::getPackedByteCount() const { + return sizeof(NetPacketDisconnectScreenOffCommand); +} + //------------------------- // NetFrameResendRequestCommandMsg //------------------------- @@ -1053,3 +1230,35 @@ UnsignedInt NetFrameResendRequestCommandMsg::getFrameToResend() { void NetFrameResendRequestCommandMsg::setFrameToResend(UnsignedInt frame) { m_frameToResend = frame; } + +size_t NetFrameResendRequestCommandMsg::getPackedByteCount() const { + return sizeof(NetPacketFrameResendRequestCommand); +} + +//------------------------- +// NetLoadCompleteCommandMsg +//------------------------- +NetLoadCompleteCommandMsg::NetLoadCompleteCommandMsg() : NetCommandMsg() { + m_commandType = NETCOMMANDTYPE_LOADCOMPLETE; +} + +NetLoadCompleteCommandMsg::~NetLoadCompleteCommandMsg() { +} + +size_t NetLoadCompleteCommandMsg::getPackedByteCount() const { + return sizeof(NetPacketLoadCompleteMessage); +} + +//------------------------- +// NetTimeOutGameStartCommandMsg +//------------------------- +NetTimeOutGameStartCommandMsg::NetTimeOutGameStartCommandMsg() : NetCommandMsg() { + m_commandType = NETCOMMANDTYPE_TIMEOUTSTART; +} + +NetTimeOutGameStartCommandMsg::~NetTimeOutGameStartCommandMsg() { +} + +size_t NetTimeOutGameStartCommandMsg::getPackedByteCount() const { + return sizeof(NetPacketTimeOutGameStartMessage); +} diff --git a/Core/GameEngine/Source/GameNetwork/NetPacket.cpp b/Core/GameEngine/Source/GameNetwork/NetPacket.cpp index be74404bae..92ec192859 100644 --- a/Core/GameEngine/Source/GameNetwork/NetPacket.cpp +++ b/Core/GameEngine/Source/GameNetwork/NetPacket.cpp @@ -31,18 +31,8 @@ #include "GameNetwork/NetworkDefs.h" #include "GameNetwork/networkutil.h" #include "GameNetwork/GameMessageParser.h" +#include "GameNetwork/NetPacketStructs.h" -// TheSuperHackers @refactor BobTista 10/06/2025 Extract magic character literals into named constants for improved readability -typedef UnsignedByte NetPacketFieldType; - -namespace NetPacketFieldTypes { - constexpr const NetPacketFieldType CommandType = 'T'; // NetCommandType field - constexpr const NetPacketFieldType Relay = 'R'; // Relay field - constexpr const NetPacketFieldType PlayerId = 'P'; // Player ID field - constexpr const NetPacketFieldType CommandId = 'C'; // Command ID field - constexpr const NetPacketFieldType Frame = 'F'; // Frame field - constexpr const NetPacketFieldType Data = 'D'; // Data payload field -} // This function assumes that all of the fields are either of default value or are // present in the raw data. @@ -287,520 +277,11 @@ UnsignedInt NetPacket::GetBufferSizeNeededForCommand(NetCommandMsg *msg) { if (msg == NULL) { return TRUE; // There was nothing to add, so it was successful. } - - switch(msg->getNetCommandType()) - { - case NETCOMMANDTYPE_GAMECOMMAND: - return GetGameCommandSize(msg); - case NETCOMMANDTYPE_ACKSTAGE1: - case NETCOMMANDTYPE_ACKSTAGE2: - case NETCOMMANDTYPE_ACKBOTH: - return GetAckCommandSize(msg); - case NETCOMMANDTYPE_FRAMEINFO: - return GetFrameCommandSize(msg); - case NETCOMMANDTYPE_PLAYERLEAVE: - return GetPlayerLeaveCommandSize(msg); - case NETCOMMANDTYPE_RUNAHEADMETRICS: - return GetRunAheadMetricsCommandSize(msg); - case NETCOMMANDTYPE_RUNAHEAD: - return GetRunAheadCommandSize(msg); - case NETCOMMANDTYPE_DESTROYPLAYER: - return GetDestroyPlayerCommandSize(msg); - case NETCOMMANDTYPE_KEEPALIVE: - return GetKeepAliveCommandSize(msg); - case NETCOMMANDTYPE_DISCONNECTKEEPALIVE: - return GetDisconnectKeepAliveCommandSize(msg); - case NETCOMMANDTYPE_DISCONNECTPLAYER: - return GetDisconnectPlayerCommandSize(msg); - case NETCOMMANDTYPE_PACKETROUTERQUERY: - return GetPacketRouterQueryCommandSize(msg); - case NETCOMMANDTYPE_PACKETROUTERACK: - return GetPacketRouterAckCommandSize(msg); - case NETCOMMANDTYPE_DISCONNECTCHAT: - return GetDisconnectChatCommandSize(msg); - case NETCOMMANDTYPE_DISCONNECTVOTE: - return GetDisconnectVoteCommandSize(msg); - case NETCOMMANDTYPE_CHAT: - return GetChatCommandSize(msg); - case NETCOMMANDTYPE_PROGRESS: - return GetProgressMessageSize(msg); - case NETCOMMANDTYPE_LOADCOMPLETE: - return GetLoadCompleteMessageSize(msg); - case NETCOMMANDTYPE_TIMEOUTSTART: - return GetTimeOutGameStartMessageSize(msg); - case NETCOMMANDTYPE_WRAPPER: - return GetWrapperCommandSize(msg); - case NETCOMMANDTYPE_FILE: - return GetFileCommandSize(msg); - case NETCOMMANDTYPE_FILEANNOUNCE: - return GetFileAnnounceCommandSize(msg); - case NETCOMMANDTYPE_FILEPROGRESS: - return GetFileProgressCommandSize(msg); - case NETCOMMANDTYPE_DISCONNECTFRAME: - return GetDisconnectFrameCommandSize(msg); - case NETCOMMANDTYPE_DISCONNECTSCREENOFF: - return GetDisconnectScreenOffCommandSize(msg); - case NETCOMMANDTYPE_FRAMERESENDREQUEST: - return GetFrameResendRequestCommandSize(msg); - default: - DEBUG_CRASH(("Unknown NETCOMMANDTYPE %d", msg->getNetCommandType())); - break; - } - - return 0; -} - -UnsignedInt NetPacket::GetGameCommandSize(NetCommandMsg *msg) { - NetGameCommandMsg *cmdMsg = (NetGameCommandMsg *)msg; - - UnsignedShort msglen = 0; - msglen += sizeof(UnsignedInt) + sizeof(UnsignedByte); // frame number - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // player ID - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // relay - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // command type - msglen += sizeof(UnsignedShort) + sizeof(UnsignedByte); // command ID - msglen += sizeof(UnsignedByte); // the NetPacketFieldTypes::Data for the data section. - - GameMessage *gmsg = cmdMsg->constructGameMessage(); - GameMessageParser *parser = newInstance(GameMessageParser)(gmsg); - - msglen += sizeof(GameMessage::Type); - msglen += sizeof(UnsignedByte); -// Int numTypes = parser->getNumTypes(); - GameMessageParserArgumentType *arg = parser->getFirstArgumentType(); - while (arg != NULL) { - msglen += 2 * sizeof(UnsignedByte); // for the type and number of args of that type declaration. - GameMessageArgumentDataType type = arg->getType(); - - switch (type) { - - case ARGUMENTDATATYPE_INTEGER: - msglen += arg->getArgCount() * sizeof(Int); - break; - case ARGUMENTDATATYPE_REAL: - msglen += arg->getArgCount() * sizeof(Real); - break; - case ARGUMENTDATATYPE_BOOLEAN: - msglen += arg->getArgCount() * sizeof(Bool); - break; - case ARGUMENTDATATYPE_OBJECTID: - msglen += arg->getArgCount() * sizeof(ObjectID); - break; - case ARGUMENTDATATYPE_DRAWABLEID: - msglen += arg->getArgCount() * sizeof(DrawableID); - break; - case ARGUMENTDATATYPE_TEAMID: - msglen += arg->getArgCount() * sizeof(UnsignedInt); - break; - case ARGUMENTDATATYPE_LOCATION: - msglen += arg->getArgCount() * sizeof(Coord3D); - break; - case ARGUMENTDATATYPE_PIXEL: - msglen += arg->getArgCount() * sizeof(ICoord2D); - break; - case ARGUMENTDATATYPE_PIXELREGION: - msglen += arg->getArgCount() * sizeof(IRegion2D); - break; - case ARGUMENTDATATYPE_TIMESTAMP: - msglen += arg->getArgCount() * sizeof(UnsignedInt); - break; - case ARGUMENTDATATYPE_WIDECHAR: - msglen += arg->getArgCount() * sizeof(WideChar); - break; - - } - - arg = arg->getNext(); - } - - deleteInstance(parser); - parser = NULL; - - deleteInstance(gmsg); - gmsg = NULL; - - return msglen; + // Use the virtual function for all command message types + return msg->getPackedByteCount(); } -UnsignedInt NetPacket::GetAckCommandSize(NetCommandMsg *msg) { - Int msglen = 0; - ++msglen; - msglen += sizeof(UnsignedByte); - ++msglen; - msglen += sizeof(UnsignedByte); - ++msglen; - msglen += sizeof(UnsignedShort); - msglen += sizeof(UnsignedByte); - - return msglen; -} - -UnsignedInt NetPacket::GetFrameCommandSize(NetCommandMsg *msg) { - Int msglen = 0; - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedInt) + sizeof(UnsignedByte); - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedShort) + sizeof(UnsignedByte); - - ++msglen; - msglen += sizeof(UnsignedShort); - - return msglen; -} - -UnsignedInt NetPacket::GetPlayerLeaveCommandSize(NetCommandMsg *msg) { - Int msglen = 0; - - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); - msglen += sizeof(UnsignedInt) + sizeof(UnsignedByte); - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedShort) + sizeof(UnsignedByte); - - ++msglen; - msglen += sizeof(UnsignedByte); - - return msglen; -} - -UnsignedInt NetPacket::GetRunAheadMetricsCommandSize(NetCommandMsg *msg) { - Int msglen = 0; - - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedShort) + sizeof(UnsignedByte); - - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(Real); - - return msglen; -} - -UnsignedInt NetPacket::GetRunAheadCommandSize(NetCommandMsg *msg) { - Int msglen = 0; - - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); - msglen += sizeof(UnsignedInt) + sizeof(UnsignedByte); - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedShort) + sizeof(UnsignedByte); - - ++msglen; - msglen += sizeof(UnsignedShort); - msglen += sizeof(UnsignedByte); - - return msglen; -} - -UnsignedInt NetPacket::GetDestroyPlayerCommandSize(NetCommandMsg *msg) { - Int msglen = 0; - - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); - msglen += sizeof(UnsignedInt) + sizeof(UnsignedByte); - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedShort) + sizeof(UnsignedByte); - - ++msglen; - msglen += sizeof(UnsignedInt); - - return msglen; -} - -UnsignedInt NetPacket::GetKeepAliveCommandSize(NetCommandMsg *msg) { - Int msglen = 0; - - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); - ++msglen; - msglen += sizeof(UnsignedByte); - - ++msglen; // For the NetPacketFieldTypes::Data - - return msglen; -} - -UnsignedInt NetPacket::GetDisconnectKeepAliveCommandSize(NetCommandMsg *msg) { - Int msglen = 0; - - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); - ++msglen; - msglen += sizeof(UnsignedByte); - - ++msglen; // For the NetPacketFieldTypes::Data - - return msglen; -} - -UnsignedInt NetPacket::GetDisconnectPlayerCommandSize(NetCommandMsg *msg) { - Int msglen = 0; - - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedShort) + sizeof(UnsignedByte); - - ++msglen; // the NetPacketFieldTypes::Data - msglen += sizeof(UnsignedByte); // slot number - msglen += sizeof(UnsignedInt); // disconnect frame - - return msglen; -} - -UnsignedInt NetPacket::GetPacketRouterQueryCommandSize(NetCommandMsg *msg) { - Int msglen = 0; - - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); - ++msglen; - msglen += sizeof(UnsignedByte); - - ++msglen; // the NetPacketFieldTypes::Data - - return msglen; -} - -UnsignedInt NetPacket::GetPacketRouterAckCommandSize(NetCommandMsg *msg) { - Int msglen = 0; - - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); - ++msglen; - msglen += sizeof(UnsignedByte); - - ++msglen; // the NetPacketFieldTypes::Data - - return msglen; -} - -UnsignedInt NetPacket::GetDisconnectChatCommandSize(NetCommandMsg *msg) { - Int msglen = 0; - NetDisconnectChatCommandMsg *cmdMsg = (NetDisconnectChatCommandMsg *)(msg); - - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); - ++msglen; - msglen += sizeof(UnsignedByte); - - ++msglen; // the NetPacketFieldTypes::Data - msglen += sizeof(UnsignedByte); // string msglength - UnsignedByte textmsglen = cmdMsg->getText().getLength(); - msglen += textmsglen * sizeof(UnsignedShort); - - return msglen; -} - -UnsignedInt NetPacket::GetDisconnectVoteCommandSize(NetCommandMsg *msg) { - Int msglen = 0; - - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedShort) + sizeof(UnsignedByte); - - ++msglen; // the NetPacketFieldTypes::Data - msglen += sizeof(UnsignedByte); // slot number - msglen += sizeof(UnsignedInt); // vote frame. - - return msglen; -} - -UnsignedInt NetPacket::GetChatCommandSize(NetCommandMsg *msg) { - Int msglen = 0; - NetChatCommandMsg *cmdMsg = (NetChatCommandMsg *)(msg); - - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedInt) + sizeof(UnsignedByte); - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedShort) + sizeof(UnsignedByte); - - ++msglen; // the NetPacketFieldTypes::Data - msglen += sizeof(UnsignedByte); // string msglength - UnsignedByte textmsglen = cmdMsg->getText().getLength(); - msglen += textmsglen * sizeof(UnsignedShort); - msglen += sizeof(Int); // playerMask - - return msglen; -} - -UnsignedInt NetPacket::GetProgressMessageSize(NetCommandMsg *msg) { - Int msglen = 0; - - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); - ++msglen; - msglen += sizeof(UnsignedByte); - - ++msglen; // For the NetPacketFieldTypes::Data - ++msglen; // percentage - - return msglen; -} - -UnsignedInt NetPacket::GetLoadCompleteMessageSize(NetCommandMsg *msg) { - Int msglen = 0; - - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); - ++msglen; - msglen += sizeof(UnsignedByte); - - ++msglen; // For the NetPacketFieldTypes::Data - - return msglen; -} - -UnsignedInt NetPacket::GetTimeOutGameStartMessageSize(NetCommandMsg *msg) { - Int msglen = 0; - - ++msglen; - msglen += sizeof(UnsignedByte); - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); - ++msglen; - msglen += sizeof(UnsignedByte); - - ++msglen; // For the NetPacketFieldTypes::Data - - return msglen; -} - -// type, player, ID, relay, Data -UnsignedInt NetPacket::GetWrapperCommandSize(NetCommandMsg *msg) { - UnsignedInt msglen = 0; - - ++msglen; // NetPacketFieldTypes::CommandType - msglen += sizeof(UnsignedByte); // command type - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // NetPacketFieldTypes::PlayerId and player ID - msglen += sizeof(UnsignedByte) + sizeof(UnsignedShort); // NetPacketFieldTypes::CommandId and command ID - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // NetPacketFieldTypes::Relay and relay - ++msglen; // NetPacketFieldTypes::Data - - msglen += sizeof(UnsignedShort); // m_wrappedCommandID - msglen += sizeof(UnsignedInt); // m_chunkNumber - msglen += sizeof(UnsignedInt); // m_numChunks - msglen += sizeof(UnsignedInt); // m_totalDataLength - msglen += sizeof(UnsignedInt); // m_dataLength - msglen += sizeof(UnsignedInt); // m_dataOffset - - return msglen; -} - -UnsignedInt NetPacket::GetFileCommandSize(NetCommandMsg *msg) { - NetFileCommandMsg *filemsg = (NetFileCommandMsg *)msg; - UnsignedInt msglen = 0; - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // NetPacketFieldTypes::CommandType and command type - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // NetPacketFieldTypes::PlayerId and player ID - msglen += sizeof(UnsignedByte) + sizeof(UnsignedShort); // NetPacketFieldTypes::CommandId and command ID - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // NetPacketFieldTypes::Relay and relay - - ++msglen; // NetPacketFieldTypes::Data - - msglen += filemsg->getPortableFilename().getLength() + 1; // PORTABLE filename and the terminating 0 - msglen += sizeof(UnsignedInt); // file data length - msglen += filemsg->getFileLength(); // the file data - - return msglen; -} - -UnsignedInt NetPacket::GetFileAnnounceCommandSize(NetCommandMsg *msg) { - NetFileAnnounceCommandMsg *filemsg = (NetFileAnnounceCommandMsg *)msg; - UnsignedInt msglen = 0; - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // NetPacketFieldTypes::CommandType and command type - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // NetPacketFieldTypes::PlayerId and player ID - msglen += sizeof(UnsignedByte) + sizeof(UnsignedShort); // NetPacketFieldTypes::CommandId and command ID - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // NetPacketFieldTypes::Relay and relay - - ++msglen; // NetPacketFieldTypes::Data - - msglen += filemsg->getPortableFilename().getLength() + 1; // PORTABLE filename and the terminating 0 - msglen += sizeof(UnsignedShort); // m_fileID - msglen += sizeof(UnsignedByte); // m_playerMask - - return msglen; -} - -UnsignedInt NetPacket::GetFileProgressCommandSize(NetCommandMsg *msg) { - UnsignedInt msglen = 0; - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // NetPacketFieldTypes::CommandType and command type - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // NetPacketFieldTypes::PlayerId and player ID - msglen += sizeof(UnsignedByte) + sizeof(UnsignedShort); // NetPacketFieldTypes::CommandId and command ID - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // NetPacketFieldTypes::Relay and relay - - ++msglen; // NetPacketFieldTypes::Data - - msglen += sizeof(UnsignedShort); // m_fileID - msglen += sizeof(Int); // m_progress - - return msglen; -} - -UnsignedInt NetPacket::GetDisconnectFrameCommandSize(NetCommandMsg *msg) { - UnsignedInt msglen = 0; - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // NetPacketFieldTypes::CommandType and command type - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // NetPacketFieldTypes::PlayerId and player ID - msglen += sizeof(UnsignedByte) + sizeof(UnsignedShort); // NetPacketFieldTypes::CommandId and command ID - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // NetPacketFieldTypes::Relay and relay - - ++msglen; // NetPacketFieldTypes::Data - msglen += sizeof(UnsignedInt); // disconnect frame - - return msglen; -} - -UnsignedInt NetPacket::GetDisconnectScreenOffCommandSize(NetCommandMsg *msg) { - UnsignedInt msglen = 0; - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // NetPacketFieldTypes::CommandType and command type - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // NetPacketFieldTypes::PlayerId and player ID - msglen += sizeof(UnsignedByte) + sizeof(UnsignedShort); // NetPacketFieldTypes::CommandId and command ID - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // NetPacketFieldTypes::Relay and relay - - ++msglen; // NetPacketFieldTypes::Data - msglen += sizeof(UnsignedInt); // new frame - - return msglen; -} - -UnsignedInt NetPacket::GetFrameResendRequestCommandSize(NetCommandMsg *msg) { - UnsignedInt msglen = 0; - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // NetPacketFieldTypes::CommandType and command type - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // NetPacketFieldTypes::PlayerId and player ID - msglen += sizeof(UnsignedByte) + sizeof(UnsignedShort); // NetPacketFieldTypes::CommandId and command ID - msglen += sizeof(UnsignedByte) + sizeof(UnsignedByte); // NetPacketFieldTypes::Relay and relay - - ++msglen; // NetPacketFieldTypes::Data - msglen += sizeof(UnsignedInt); // frame to resend - - return msglen; -} // this function assumes that buffer is already the correct size. void NetPacket::FillBufferWithCommand(UnsignedByte *buffer, NetCommandRef *ref) { @@ -889,7 +370,7 @@ void NetPacket::FillBufferWithCommand(UnsignedByte *buffer, NetCommandRef *ref) } void NetPacket::FillBufferWithGameCommand(UnsignedByte *buffer, NetCommandRef *msg) { - NetGameCommandMsg *cmdMsg = (NetGameCommandMsg *)(msg->getCommand()); + NetGameCommandMsg *cmdMsg = static_cast(msg->getCommand()); UnsignedShort offset = 0; // get the game message from the NetCommandMsg GameMessage *gmsg = cmdMsg->constructGameMessage(); @@ -1078,7 +559,7 @@ void NetPacket::FillBufferWithAckCommand(UnsignedByte *buffer, NetCommandRef *ms } void NetPacket::FillBufferWithFrameCommand(UnsignedByte *buffer, NetCommandRef *msg) { - NetFrameCommandMsg *cmdMsg = (NetFrameCommandMsg *)(msg->getCommand()); + NetFrameCommandMsg *cmdMsg = static_cast(msg->getCommand()); UnsignedShort offset = 0; // DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("NetPacket::addFrameCommand - adding frame command for frame %d, command count = %d, command id = %d", cmdMsg->getExecutionFrame(), cmdMsg->getCommandCount(), cmdMsg->getID())); @@ -1131,7 +612,7 @@ void NetPacket::FillBufferWithFrameCommand(UnsignedByte *buffer, NetCommandRef * } void NetPacket::FillBufferWithPlayerLeaveCommand(UnsignedByte *buffer, NetCommandRef *msg) { - NetPlayerLeaveCommandMsg *cmdMsg = (NetPlayerLeaveCommandMsg *)(msg->getCommand()); + NetPlayerLeaveCommandMsg *cmdMsg = static_cast(msg->getCommand()); UnsignedShort offset = 0; // DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("NetPacket::addPlayerLeaveCommand - adding player leave command for player %d", cmdMsg->getLeavingPlayerID())); @@ -1181,7 +662,7 @@ void NetPacket::FillBufferWithPlayerLeaveCommand(UnsignedByte *buffer, NetComman } void NetPacket::FillBufferWithRunAheadMetricsCommand(UnsignedByte *buffer, NetCommandRef *msg) { - NetRunAheadMetricsCommandMsg *cmdMsg = (NetRunAheadMetricsCommandMsg *)(msg->getCommand()); + NetRunAheadMetricsCommandMsg *cmdMsg = static_cast(msg->getCommand()); UnsignedShort offset = 0; // DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("NetPacket::addRunAheadMetricsCommand - adding run ahead metrics for player %d, fps = %d, latency = %f", cmdMsg->getPlayerID(), cmdMsg->getAverageFps(), cmdMsg->getAverageLatency())); @@ -1229,7 +710,7 @@ void NetPacket::FillBufferWithRunAheadMetricsCommand(UnsignedByte *buffer, NetCo } void NetPacket::FillBufferWithRunAheadCommand(UnsignedByte *buffer, NetCommandRef *msg) { - NetRunAheadCommandMsg *cmdMsg = (NetRunAheadCommandMsg *)(msg->getCommand()); + NetRunAheadCommandMsg *cmdMsg = static_cast(msg->getCommand()); UnsignedShort offset = 0; //DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("NetPacket::FillBufferWithRunAheadCommand - adding run ahead command")); @@ -1285,7 +766,7 @@ void NetPacket::FillBufferWithRunAheadCommand(UnsignedByte *buffer, NetCommandRe } void NetPacket::FillBufferWithDestroyPlayerCommand(UnsignedByte *buffer, NetCommandRef *msg) { - NetDestroyPlayerCommandMsg *cmdMsg = (NetDestroyPlayerCommandMsg *)(msg->getCommand()); + NetDestroyPlayerCommandMsg *cmdMsg = static_cast(msg->getCommand()); UnsignedShort offset = 0; // DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("NetPacket::addRunAheadCommand - adding run ahead command")); @@ -1335,7 +816,7 @@ void NetPacket::FillBufferWithDestroyPlayerCommand(UnsignedByte *buffer, NetComm } void NetPacket::FillBufferWithKeepAliveCommand(UnsignedByte *buffer, NetCommandRef *msg) { - NetKeepAliveCommandMsg *cmdMsg = (NetKeepAliveCommandMsg *)(msg->getCommand()); + NetKeepAliveCommandMsg *cmdMsg = static_cast(msg->getCommand()); UnsignedShort offset = 0; // If necessary, put the NetCommandType into the packet. @@ -1361,7 +842,7 @@ void NetPacket::FillBufferWithKeepAliveCommand(UnsignedByte *buffer, NetCommandR } void NetPacket::FillBufferWithDisconnectKeepAliveCommand(UnsignedByte *buffer, NetCommandRef *msg) { - NetDisconnectKeepAliveCommandMsg *cmdMsg = (NetDisconnectKeepAliveCommandMsg *)(msg->getCommand()); + NetDisconnectKeepAliveCommandMsg *cmdMsg = static_cast(msg->getCommand()); UnsignedShort offset = 0; // Put the NetCommandType into the packet. @@ -1388,7 +869,7 @@ void NetPacket::FillBufferWithDisconnectKeepAliveCommand(UnsignedByte *buffer, N } void NetPacket::FillBufferWithDisconnectPlayerCommand(UnsignedByte *buffer, NetCommandRef *msg) { - NetDisconnectPlayerCommandMsg *cmdMsg = (NetDisconnectPlayerCommandMsg *)(msg->getCommand()); + NetDisconnectPlayerCommandMsg *cmdMsg = static_cast(msg->getCommand()); UnsignedShort offset = 0; // DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("NetPacket::addDisconnectPlayerCommand - adding run ahead command")); @@ -1435,7 +916,7 @@ void NetPacket::FillBufferWithDisconnectPlayerCommand(UnsignedByte *buffer, NetC } void NetPacket::FillBufferWithPacketRouterQueryCommand(UnsignedByte *buffer, NetCommandRef *msg) { - NetPacketRouterQueryCommandMsg *cmdMsg = (NetPacketRouterQueryCommandMsg *)(msg->getCommand()); + NetPacketRouterQueryCommandMsg *cmdMsg = static_cast(msg->getCommand()); UnsignedShort offset = 0; // DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("NetPacket::addPacketRouterQueryCommand - adding packet router query command")); @@ -1581,7 +1062,7 @@ void NetPacket::FillBufferWithDisconnectVoteCommand(UnsignedByte *buffer, NetCom } void NetPacket::FillBufferWithChatCommand(UnsignedByte *buffer, NetCommandRef *msg) { - NetChatCommandMsg *cmdMsg = (NetChatCommandMsg *)(msg->getCommand()); + NetChatCommandMsg *cmdMsg = static_cast(msg->getCommand()); UnsignedShort offset = 0; // DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("NetPacket::addDisconnectChatCommand - adding run ahead command")); @@ -1669,7 +1150,7 @@ void NetPacket::FillBufferWithProgressMessage(UnsignedByte *buffer, NetCommandRe } void NetPacket::FillBufferWithLoadCompleteMessage(UnsignedByte *buffer, NetCommandRef *msg) { - NetCommandMsg *cmdMsg = (NetCommandMsg *)(msg->getCommand()); + NetCommandMsg *cmdMsg = static_cast(msg->getCommand()); UnsignedShort offset = 0; // If necessary, put the NetCommandType into the packet. @@ -1702,7 +1183,7 @@ void NetPacket::FillBufferWithLoadCompleteMessage(UnsignedByte *buffer, NetComma } void NetPacket::FillBufferWithTimeOutGameStartMessage(UnsignedByte *buffer, NetCommandRef *msg) { - NetCommandMsg *cmdMsg = (NetCommandMsg *)(msg->getCommand()); + NetCommandMsg *cmdMsg = static_cast(msg->getCommand()); UnsignedShort offset = 0; // If necessary, put the NetCommandType into the packet. @@ -1734,7 +1215,7 @@ void NetPacket::FillBufferWithTimeOutGameStartMessage(UnsignedByte *buffer, NetC } void NetPacket::FillBufferWithFileMessage(UnsignedByte *buffer, NetCommandRef *msg) { - NetFileCommandMsg *cmdMsg = (NetFileCommandMsg *)(msg->getCommand()); + NetFileCommandMsg *cmdMsg = static_cast(msg->getCommand()); UnsignedInt offset = 0; // command type @@ -1783,7 +1264,7 @@ void NetPacket::FillBufferWithFileMessage(UnsignedByte *buffer, NetCommandRef *m } void NetPacket::FillBufferWithFileAnnounceMessage(UnsignedByte *buffer, NetCommandRef *msg) { - NetFileAnnounceCommandMsg *cmdMsg = (NetFileAnnounceCommandMsg *)(msg->getCommand()); + NetFileAnnounceCommandMsg *cmdMsg = static_cast(msg->getCommand()); UnsignedInt offset = 0; // command type @@ -2466,7 +1947,7 @@ Bool NetPacket::isRoomForDisconnectFrameMessage(NetCommandRef *msg) { Bool NetPacket::addFileCommand(NetCommandRef *msg) { Bool needNewCommandID = FALSE; if (isRoomForFileMessage(msg)) { - NetFileCommandMsg *cmdMsg = (NetFileCommandMsg *)(msg->getCommand()); + NetFileCommandMsg *cmdMsg = static_cast(msg->getCommand()); // If necessary, put the NetCommandType into the packet. if (m_lastCommandType != cmdMsg->getNetCommandType()) { @@ -2538,7 +2019,7 @@ Bool NetPacket::addFileCommand(NetCommandRef *msg) { Bool NetPacket::isRoomForFileMessage(NetCommandRef *msg) { Int len = 0; Bool needNewCommandID = FALSE; - NetFileCommandMsg *cmdMsg = (NetFileCommandMsg *)(msg->getCommand()); + NetFileCommandMsg *cmdMsg = static_cast(msg->getCommand()); if (m_lastCommandType != cmdMsg->getNetCommandType()) { len += sizeof(UnsignedByte) + sizeof(UnsignedByte); } @@ -2553,7 +2034,7 @@ Bool NetPacket::isRoomForFileMessage(NetCommandRef *msg) { len += sizeof(UnsignedByte) + sizeof(UnsignedShort); } - ++len; // NetPacketFieldTypes::Data + ++len; // for NetPacketFieldTypes::Data len += cmdMsg->getPortableFilename().getLength() + 1; // PORTABLE filename + the terminating 0 len += sizeof(UnsignedInt); // filedata length len += cmdMsg->getFileLength(); @@ -2568,7 +2049,7 @@ Bool NetPacket::isRoomForFileMessage(NetCommandRef *msg) { Bool NetPacket::addFileAnnounceCommand(NetCommandRef *msg) { Bool needNewCommandID = FALSE; if (isRoomForFileAnnounceMessage(msg)) { - NetFileAnnounceCommandMsg *cmdMsg = (NetFileAnnounceCommandMsg *)(msg->getCommand()); + NetFileAnnounceCommandMsg *cmdMsg = static_cast(msg->getCommand()); // If necessary, put the NetCommandType into the packet. if (m_lastCommandType != cmdMsg->getNetCommandType()) { @@ -2645,7 +2126,7 @@ Bool NetPacket::addFileAnnounceCommand(NetCommandRef *msg) { Bool NetPacket::isRoomForFileAnnounceMessage(NetCommandRef *msg) { Int len = 0; Bool needNewCommandID = FALSE; - NetFileAnnounceCommandMsg *cmdMsg = (NetFileAnnounceCommandMsg *)(msg->getCommand()); + NetFileAnnounceCommandMsg *cmdMsg = static_cast(msg->getCommand()); if (m_lastCommandType != cmdMsg->getNetCommandType()) { len += sizeof(UnsignedByte) + sizeof(UnsignedByte); } @@ -2660,7 +2141,7 @@ Bool NetPacket::isRoomForFileAnnounceMessage(NetCommandRef *msg) { len += sizeof(UnsignedByte) + sizeof(UnsignedShort); } - ++len; // NetPacketFieldTypes::Data + ++len; // for NetPacketFieldTypes::Data len += cmdMsg->getPortableFilename().getLength() + 1; // PORTABLE filename + the terminating 0 len += sizeof(UnsignedShort); // m_fileID len += sizeof(UnsignedByte); // m_playerMask @@ -2760,7 +2241,7 @@ Bool NetPacket::isRoomForFileProgressMessage(NetCommandRef *msg) { len += sizeof(UnsignedByte) + sizeof(UnsignedShort); } - ++len; // NetPacketFieldTypes::Data + ++len; // for NetPacketFieldTypes::Data len += sizeof(UnsignedShort); // m_fileID len += sizeof(Int); // m_progress @@ -2890,7 +2371,7 @@ Bool NetPacket::isRoomForWrapperMessage(NetCommandRef *msg) { len += sizeof(UnsignedByte) + sizeof(UnsignedShort); } - ++len; // NetPacketFieldTypes::Data + ++len; // for NetPacketFieldTypes::Data len += sizeof(UnsignedShort); // wrapped command ID len += sizeof(UnsignedInt); // chunk number len += sizeof(UnsignedInt); // number of chunks @@ -2912,7 +2393,7 @@ Bool NetPacket::isRoomForWrapperMessage(NetCommandRef *msg) { Bool NetPacket::addTimeOutGameStartMessage(NetCommandRef *msg) { Bool needNewCommandID = FALSE; if (isRoomForLoadCompleteMessage(msg)) { - NetCommandMsg *cmdMsg = (NetCommandMsg *)(msg->getCommand()); + NetCommandMsg *cmdMsg = static_cast(msg->getCommand()); // If necessary, put the NetCommandType into the packet. if (m_lastCommandType != cmdMsg->getNetCommandType()) { @@ -2976,7 +2457,7 @@ Bool NetPacket::addTimeOutGameStartMessage(NetCommandRef *msg) { */ Bool NetPacket::isRoomForTimeOutGameStartMessage(NetCommandRef *msg) { Int len = 0; - NetCommandMsg *cmdMsg = (NetCommandMsg *)(msg->getCommand()); + NetCommandMsg *cmdMsg = static_cast(msg->getCommand()); if (m_lastCommandType != cmdMsg->getNetCommandType()) { ++len; len += sizeof(UnsignedByte); @@ -2989,7 +2470,7 @@ Bool NetPacket::isRoomForTimeOutGameStartMessage(NetCommandRef *msg) { len += sizeof(UnsignedByte); } - ++len; // For the NetPacketFieldTypes::Data + ++len; // for NetPacketFieldTypes::Data if ((len + m_packetLen) > MAX_PACKET_SIZE) { return FALSE; } @@ -3004,7 +2485,7 @@ Bool NetPacket::isRoomForTimeOutGameStartMessage(NetCommandRef *msg) { Bool NetPacket::addLoadCompleteMessage(NetCommandRef *msg) { Bool needNewCommandID = FALSE; if (isRoomForLoadCompleteMessage(msg)) { - NetCommandMsg *cmdMsg = (NetCommandMsg *)(msg->getCommand()); + NetCommandMsg *cmdMsg = static_cast(msg->getCommand()); // If necessary, put the NetCommandType into the packet. if (m_lastCommandType != cmdMsg->getNetCommandType()) { @@ -3068,7 +2549,7 @@ Bool NetPacket::addLoadCompleteMessage(NetCommandRef *msg) { */ Bool NetPacket::isRoomForLoadCompleteMessage(NetCommandRef *msg) { Int len = 0; - NetCommandMsg *cmdMsg = (NetCommandMsg *)(msg->getCommand()); + NetCommandMsg *cmdMsg = static_cast(msg->getCommand()); if (m_lastCommandType != cmdMsg->getNetCommandType()) { ++len; len += sizeof(UnsignedByte); @@ -3081,7 +2562,7 @@ Bool NetPacket::isRoomForLoadCompleteMessage(NetCommandRef *msg) { len += sizeof(UnsignedByte); } - ++len; // For the NetPacketFieldTypes::Data + ++len; // for NetPacketFieldTypes::Data if ((len + m_packetLen) > MAX_PACKET_SIZE) { return FALSE; } @@ -3165,7 +2646,7 @@ Bool NetPacket::isRoomForProgressMessage(NetCommandRef *msg) { len += sizeof(UnsignedByte); } - ++len; // For the NetPacketFieldTypes::Data + ++len; // for NetPacketFieldTypes::Data ++len; // percentage if ((len + m_packetLen) > MAX_PACKET_SIZE) { return FALSE; @@ -3276,7 +2757,7 @@ Bool NetPacket::isRoomForDisconnectVoteMessage(NetCommandRef *msg) { len += sizeof(UnsignedShort) + sizeof(UnsignedByte); } - ++len; // the NetPacketFieldTypes::Data + ++len; // for NetPacketFieldTypes::Data len += sizeof(UnsignedByte); // slot number len += sizeof(UnsignedInt); // vote frame @@ -3365,7 +2846,7 @@ Bool NetPacket::isRoomForDisconnectChatMessage(NetCommandRef *msg) { len += sizeof(UnsignedByte); } - ++len; // the NetPacketFieldTypes::Data + ++len; // for NetPacketFieldTypes::Data len += sizeof(UnsignedByte); // string length UnsignedByte textLen = cmdMsg->getText().getLength(); len += textLen * sizeof(UnsignedShort); @@ -3378,7 +2859,7 @@ Bool NetPacket::isRoomForDisconnectChatMessage(NetCommandRef *msg) { Bool NetPacket::addChatCommand(NetCommandRef *msg) { Bool needNewCommandID = FALSE; if (isRoomForChatMessage(msg)) { - NetChatCommandMsg *cmdMsg = (NetChatCommandMsg *)(msg->getCommand()); + NetChatCommandMsg *cmdMsg = static_cast(msg->getCommand()); // DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("NetPacket::addDisconnectChatCommand - adding run ahead command")); // If necessary, put the NetCommandType into the packet. @@ -3468,7 +2949,7 @@ Bool NetPacket::addChatCommand(NetCommandRef *msg) { Bool NetPacket::isRoomForChatMessage(NetCommandRef *msg) { Bool needNewCommandID = FALSE; Int len = 0; - NetChatCommandMsg *cmdMsg = (NetChatCommandMsg *)(msg->getCommand()); + NetChatCommandMsg *cmdMsg = static_cast(msg->getCommand()); if (m_lastCommandType != cmdMsg->getNetCommandType()) { ++len; len += sizeof(UnsignedByte); @@ -3488,7 +2969,7 @@ Bool NetPacket::isRoomForChatMessage(NetCommandRef *msg) { len += sizeof(UnsignedShort) + sizeof(UnsignedByte); } - ++len; // the NetPacketFieldTypes::Data + ++len; // for NetPacketFieldTypes::Data len += sizeof(UnsignedByte); // string length UnsignedByte textLen = cmdMsg->getText().getLength(); len += textLen * sizeof(UnsignedShort); @@ -3572,7 +3053,7 @@ Bool NetPacket::isRoomForPacketRouterAckMessage(NetCommandRef *msg) { len += sizeof(UnsignedByte); } - ++len; // the NetPacketFieldTypes::Data + ++len; // for NetPacketFieldTypes::Data if ((len + m_packetLen) > MAX_PACKET_SIZE) { return FALSE; } @@ -3582,7 +3063,7 @@ Bool NetPacket::isRoomForPacketRouterAckMessage(NetCommandRef *msg) { Bool NetPacket::addPacketRouterQueryCommand(NetCommandRef *msg) { // need type, player id, relay, command id, slot number if (isRoomForPacketRouterQueryMessage(msg)) { - NetPacketRouterQueryCommandMsg *cmdMsg = (NetPacketRouterQueryCommandMsg *)(msg->getCommand()); + NetPacketRouterQueryCommandMsg *cmdMsg = static_cast(msg->getCommand()); // DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("NetPacket::addPacketRouterQueryCommand - adding packet router query command")); // If necessary, put the NetCommandType into the packet. @@ -3639,7 +3120,7 @@ Bool NetPacket::addPacketRouterQueryCommand(NetCommandRef *msg) { */ Bool NetPacket::isRoomForPacketRouterQueryMessage(NetCommandRef *msg) { Int len = 0; - NetPacketRouterQueryCommandMsg *cmdMsg = (NetPacketRouterQueryCommandMsg *)(msg->getCommand()); + NetPacketRouterQueryCommandMsg *cmdMsg = static_cast(msg->getCommand()); if (m_lastCommandType != cmdMsg->getNetCommandType()) { ++len; len += sizeof(UnsignedByte); @@ -3652,7 +3133,7 @@ Bool NetPacket::isRoomForPacketRouterQueryMessage(NetCommandRef *msg) { len += sizeof(UnsignedByte); } - ++len; // the NetPacketFieldTypes::Data + ++len; // for NetPacketFieldTypes::Data if ((len + m_packetLen) > MAX_PACKET_SIZE) { return FALSE; } @@ -3665,7 +3146,7 @@ Bool NetPacket::addDisconnectPlayerCommand(NetCommandRef *msg) { // DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("NetPacket::addDisconnectPlayerCommand - entering...")); // need type, player id, relay, command id, slot number if (isRoomForDisconnectPlayerMessage(msg)) { - NetDisconnectPlayerCommandMsg *cmdMsg = (NetDisconnectPlayerCommandMsg *)(msg->getCommand()); + NetDisconnectPlayerCommandMsg *cmdMsg = static_cast(msg->getCommand()); // DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("NetPacket::addDisconnectPlayerCommand - adding run ahead command")); // If necessary, put the NetCommandType into the packet. @@ -3743,7 +3224,7 @@ Bool NetPacket::addDisconnectPlayerCommand(NetCommandRef *msg) { Bool NetPacket::isRoomForDisconnectPlayerMessage(NetCommandRef *msg) { Int len = 0; Bool needNewCommandID = FALSE; - NetDisconnectPlayerCommandMsg *cmdMsg = (NetDisconnectPlayerCommandMsg *)(msg->getCommand()); + NetDisconnectPlayerCommandMsg *cmdMsg = static_cast(msg->getCommand()); if (m_lastCommandType != cmdMsg->getNetCommandType()) { ++len; len += sizeof(UnsignedByte); @@ -3760,7 +3241,7 @@ Bool NetPacket::isRoomForDisconnectPlayerMessage(NetCommandRef *msg) { len += sizeof(UnsignedShort) + sizeof(UnsignedByte); } - ++len; // the NetPacketFieldTypes::Data + ++len; // for NetPacketFieldTypes::Data len += sizeof(UnsignedByte); // slot number len += sizeof(UnsignedInt); // disconnectFrame if ((len + m_packetLen) > MAX_PACKET_SIZE) { @@ -3775,7 +3256,7 @@ Bool NetPacket::isRoomForDisconnectPlayerMessage(NetCommandRef *msg) { */ Bool NetPacket::addDisconnectKeepAliveCommand(NetCommandRef *msg) { if (isRoomForDisconnectKeepAliveMessage(msg)) { - NetDisconnectKeepAliveCommandMsg *cmdMsg = (NetDisconnectKeepAliveCommandMsg *)(msg->getCommand()); + NetDisconnectKeepAliveCommandMsg *cmdMsg = static_cast(msg->getCommand()); // If necessary, put the NetCommandType into the packet. if (m_lastCommandType != cmdMsg->getNetCommandType()) { @@ -3828,7 +3309,7 @@ Bool NetPacket::addDisconnectKeepAliveCommand(NetCommandRef *msg) { */ Bool NetPacket::isRoomForDisconnectKeepAliveMessage(NetCommandRef *msg) { Int len = 0; - NetDisconnectKeepAliveCommandMsg *cmdMsg = (NetDisconnectKeepAliveCommandMsg *)(msg->getCommand()); + NetDisconnectKeepAliveCommandMsg *cmdMsg = static_cast(msg->getCommand()); if (m_lastCommandType != cmdMsg->getNetCommandType()) { ++len; len += sizeof(UnsignedByte); @@ -3841,7 +3322,7 @@ Bool NetPacket::isRoomForDisconnectKeepAliveMessage(NetCommandRef *msg) { len += sizeof(UnsignedByte); } - ++len; // For the NetPacketFieldTypes::Data + ++len; // for NetPacketFieldTypes::Data if ((len + m_packetLen) > MAX_PACKET_SIZE) { return FALSE; } @@ -3853,7 +3334,7 @@ Bool NetPacket::isRoomForDisconnectKeepAliveMessage(NetCommandRef *msg) { */ Bool NetPacket::addKeepAliveCommand(NetCommandRef *msg) { if (isRoomForKeepAliveMessage(msg)) { - NetKeepAliveCommandMsg *cmdMsg = (NetKeepAliveCommandMsg *)(msg->getCommand()); + NetKeepAliveCommandMsg *cmdMsg = static_cast(msg->getCommand()); // If necessary, put the NetCommandType into the packet. if (m_lastCommandType != cmdMsg->getNetCommandType()) { @@ -3906,7 +3387,7 @@ Bool NetPacket::addKeepAliveCommand(NetCommandRef *msg) { */ Bool NetPacket::isRoomForKeepAliveMessage(NetCommandRef *msg) { Int len = 0; - NetKeepAliveCommandMsg *cmdMsg = (NetKeepAliveCommandMsg *)(msg->getCommand()); + NetKeepAliveCommandMsg *cmdMsg = static_cast(msg->getCommand()); if (m_lastCommandType != cmdMsg->getNetCommandType()) { ++len; len += sizeof(UnsignedByte); @@ -3919,7 +3400,7 @@ Bool NetPacket::isRoomForKeepAliveMessage(NetCommandRef *msg) { len += sizeof(UnsignedByte); } - ++len; // For the NetPacketFieldTypes::Data + ++len; // for NetPacketFieldTypes::Data if ((len + m_packetLen) > MAX_PACKET_SIZE) { return FALSE; } @@ -3932,7 +3413,7 @@ Bool NetPacket::isRoomForKeepAliveMessage(NetCommandRef *msg) { Bool NetPacket::addRunAheadCommand(NetCommandRef *msg) { Bool needNewCommandID = FALSE; if (isRoomForRunAheadMessage(msg)) { - NetRunAheadCommandMsg *cmdMsg = (NetRunAheadCommandMsg *)(msg->getCommand()); + NetRunAheadCommandMsg *cmdMsg = static_cast(msg->getCommand()); //DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("NetPacket::addRunAheadCommand - adding run ahead command")); // If necessary, put the NetCommandType into the packet. @@ -4021,7 +3502,7 @@ Bool NetPacket::addRunAheadCommand(NetCommandRef *msg) { Bool NetPacket::isRoomForRunAheadMessage(NetCommandRef *msg) { Int len = 0; Bool needNewCommandID = FALSE; - NetRunAheadCommandMsg *cmdMsg = (NetRunAheadCommandMsg *)(msg->getCommand()); + NetRunAheadCommandMsg *cmdMsg = static_cast(msg->getCommand()); if (m_lastCommandType != cmdMsg->getNetCommandType()) { ++len; len += sizeof(UnsignedByte); @@ -4056,7 +3537,7 @@ Bool NetPacket::isRoomForRunAheadMessage(NetCommandRef *msg) { Bool NetPacket::addDestroyPlayerCommand(NetCommandRef *msg) { Bool needNewCommandID = FALSE; if (isRoomForDestroyPlayerMessage(msg)) { - NetDestroyPlayerCommandMsg *cmdMsg = (NetDestroyPlayerCommandMsg *)(msg->getCommand()); + NetDestroyPlayerCommandMsg *cmdMsg = static_cast(msg->getCommand()); // If necessary, put the NetCommandType into the packet. if (m_lastCommandType != cmdMsg->getNetCommandType()) { @@ -4140,7 +3621,7 @@ Bool NetPacket::addDestroyPlayerCommand(NetCommandRef *msg) { Bool NetPacket::isRoomForDestroyPlayerMessage(NetCommandRef *msg) { Int len = 0; Bool needNewCommandID = FALSE; - NetDestroyPlayerCommandMsg *cmdMsg = (NetDestroyPlayerCommandMsg *)(msg->getCommand()); + NetDestroyPlayerCommandMsg *cmdMsg = static_cast(msg->getCommand()); if (m_lastCommandType != cmdMsg->getNetCommandType()) { ++len; len += sizeof(UnsignedByte); @@ -4174,7 +3655,7 @@ Bool NetPacket::isRoomForDestroyPlayerMessage(NetCommandRef *msg) { Bool NetPacket::addRunAheadMetricsCommand(NetCommandRef *msg) { Bool needNewCommandID = FALSE; if (isRoomForRunAheadMetricsMessage(msg)) { - NetRunAheadMetricsCommandMsg *cmdMsg = (NetRunAheadMetricsCommandMsg *)(msg->getCommand()); + NetRunAheadMetricsCommandMsg *cmdMsg = static_cast(msg->getCommand()); // DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("NetPacket::addRunAheadMetricsCommand - adding run ahead metrics for player %d, fps = %d, latency = %f", cmdMsg->getPlayerID(), cmdMsg->getAverageFps(), cmdMsg->getAverageLatency())); // If necessary, put the NetCommandType into the packet. @@ -4251,7 +3732,7 @@ Bool NetPacket::addRunAheadMetricsCommand(NetCommandRef *msg) { Bool NetPacket::isRoomForRunAheadMetricsMessage(NetCommandRef *msg) { Int len = 0; Bool needNewCommandID = FALSE; - NetRunAheadMetricsCommandMsg *cmdMsg = (NetRunAheadMetricsCommandMsg *)(msg->getCommand()); + NetRunAheadMetricsCommandMsg *cmdMsg = static_cast(msg->getCommand()); if (m_lastCommandType != cmdMsg->getNetCommandType()) { ++len; len += sizeof(UnsignedByte); @@ -4268,7 +3749,7 @@ Bool NetPacket::isRoomForRunAheadMetricsMessage(NetCommandRef *msg) { len += sizeof(UnsignedShort) + sizeof(UnsignedByte); } - ++len; // NetPacketFieldTypes::Data + ++len; // for NetPacketFieldTypes::Data len += sizeof(UnsignedShort); len += sizeof(Real); if ((len + m_packetLen) > MAX_PACKET_SIZE) { @@ -4284,7 +3765,7 @@ Bool NetPacket::isRoomForRunAheadMetricsMessage(NetCommandRef *msg) { Bool NetPacket::addPlayerLeaveCommand(NetCommandRef *msg) { Bool needNewCommandID = FALSE; if (isRoomForPlayerLeaveMessage(msg)) { - NetPlayerLeaveCommandMsg *cmdMsg = (NetPlayerLeaveCommandMsg *)(msg->getCommand()); + NetPlayerLeaveCommandMsg *cmdMsg = static_cast(msg->getCommand()); // DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("NetPacket::addPlayerLeaveCommand - adding player leave command for player %d", cmdMsg->getLeavingPlayerID())); // If necessary, put the NetCommandType into the packet. @@ -4367,7 +3848,7 @@ Bool NetPacket::addPlayerLeaveCommand(NetCommandRef *msg) { Bool NetPacket::isRoomForPlayerLeaveMessage(NetCommandRef *msg) { Int len = 0; Bool needNewCommandID = FALSE; - NetPlayerLeaveCommandMsg *cmdMsg = (NetPlayerLeaveCommandMsg *)(msg->getCommand()); + NetPlayerLeaveCommandMsg *cmdMsg = static_cast(msg->getCommand()); if (m_lastCommandType != cmdMsg->getNetCommandType()) { ++len; len += sizeof(UnsignedByte); @@ -4417,7 +3898,7 @@ Bool NetPacket::addFrameCommand(NetCommandRef *msg) { return TRUE; } if (isRoomForFrameMessage(msg)) { - NetFrameCommandMsg *cmdMsg = (NetFrameCommandMsg *)(msg->getCommand()); + NetFrameCommandMsg *cmdMsg = static_cast(msg->getCommand()); // DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("NetPacket::addFrameCommand - adding frame command for frame %d, command count = %d, command id = %d", cmdMsg->getExecutionFrame(), cmdMsg->getCommandCount(), cmdMsg->getID())); // If necessary, put the NetCommandType into the packet. @@ -4503,7 +3984,7 @@ Bool NetPacket::addFrameCommand(NetCommandRef *msg) { Bool NetPacket::isRoomForFrameMessage(NetCommandRef *msg) { Int len = 0; Bool needNewCommandID = FALSE; - NetFrameCommandMsg *cmdMsg = (NetFrameCommandMsg *)(msg->getCommand()); + NetFrameCommandMsg *cmdMsg = static_cast(msg->getCommand()); if (m_lastCommandType != cmdMsg->getNetCommandType()) { ++len; len += sizeof(UnsignedByte); @@ -4937,7 +4418,8 @@ Bool NetPacket::isRoomForGameMessage(NetCommandRef *msg, GameMessage *gmsg) { // Int numTypes = parser->getNumTypes(); GameMessageParserArgumentType *arg = parser->getFirstArgumentType(); while (arg != NULL) { - msglen += 2 * sizeof(UnsignedByte); // for the type and number of args of that type declaration. + msglen += sizeof(UnsignedByte); // argument type + msglen += sizeof(UnsignedByte); // argument count GameMessageArgumentDataType type = arg->getType(); switch (type) { @@ -5746,12 +5228,12 @@ NetCommandMsg * NetPacket::readProgressMessage(UnsignedByte *data, Int &i) { } NetCommandMsg * NetPacket::readLoadCompleteMessage(UnsignedByte *data, Int &i) { - NetCommandMsg *msg = newInstance(NetCommandMsg); + NetLoadCompleteCommandMsg *msg = newInstance(NetLoadCompleteCommandMsg); return msg; } NetCommandMsg * NetPacket::readTimeOutGameStartMessage(UnsignedByte *data, Int &i) { - NetCommandMsg *msg = newInstance(NetCommandMsg); + NetTimeOutGameStartCommandMsg *msg = newInstance(NetTimeOutGameStartCommandMsg); return msg; } From ae2280930346e96576aca58cd2b75b75b0ca2bb4 Mon Sep 17 00:00:00 2001 From: stm <14291421+stephanmeesters@users.noreply.github.com> Date: Fri, 2 Jan 2026 10:45:48 +0100 Subject: [PATCH 58/70] refactor(logic): Simplify code in GameLogic's init, reset, startNewGame (#2027) --- .../GameEngine/Include/GameLogic/GameLogic.h | 1 - .../Source/GameLogic/System/GameLogic.cpp | 141 ++++++----------- .../GameEngine/Include/GameLogic/GameLogic.h | 1 - .../Source/GameLogic/System/GameLogic.cpp | 144 ++++++------------ 4 files changed, 99 insertions(+), 188 deletions(-) diff --git a/Generals/Code/GameEngine/Include/GameLogic/GameLogic.h b/Generals/Code/GameEngine/Include/GameLogic/GameLogic.h index 0993841d0a..5a138b5c19 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/GameLogic.h +++ b/Generals/Code/GameEngine/Include/GameLogic/GameLogic.h @@ -329,7 +329,6 @@ class GameLogic : public SubsystemInterface, public Snapshot ObjectID m_nextObjID; ///< For allocating object id's - void setDefaults( Bool saveGame ); ///< Set default values of class object void processDestroyList( void ); ///< Destroy all pending objects on the destroy list void destroyAllObjectsImmediate(); ///< destroy, and process destroy list immediately diff --git a/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp index dbfb226078..1b2fa9b864 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp @@ -249,36 +249,6 @@ GameLogic::GameLogic( void ) #endif } -// ------------------------------------------------------------------------------------------------ -/** Utility function to set class variables to default values. */ -// ------------------------------------------------------------------------------------------------ -void GameLogic::setDefaults( Bool saveGame ) -{ - m_frame = 0; - m_hasUpdated = FALSE; - m_width = DEFAULT_WORLD_WIDTH; - m_height = DEFAULT_WORLD_HEIGHT; - m_objList = NULL; -#ifdef ALLOW_NONSLEEPY_UPDATES - m_normalUpdates.clear(); -#endif - for (std::vector::iterator it = m_sleepyUpdates.begin(); it != m_sleepyUpdates.end(); ++it) - { - (*it)->friend_setIndexInLogic(-1); - } - m_sleepyUpdates.clear(); - m_curUpdateModule = NULL; - - // - // only reset the next object ID allocater counter when we're not loading a save game. - // for save games, we read this value out of the save game file and it is important - // that we preserve it as we load and execute the game - // - if( saveGame == FALSE ) - m_nextObjID = (ObjectID)1; - -} - //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- Bool GameLogic::isInSinglePlayerGame( void ) @@ -370,9 +340,6 @@ void GameLogic::init( void ) setFPMode(); - /// @todo Clear object and destroy lists - setDefaults( FALSE ); - // create the partition manager ThePartitionManager = NEW PartitionManager; ThePartitionManager->init(); @@ -400,32 +367,8 @@ void GameLogic::init( void ) //DEBUG_ASSERTCRASH(ThePlayerList, ("null ThePlayerList")); //ThePlayerList->setLocalPlayer(0); - m_CRC = 0; - m_pauseFrame = 0; - m_gamePaused = FALSE; - m_pauseSound = FALSE; - m_pauseMusic = FALSE; - m_pauseInput = FALSE; - m_inputEnabledMemory = TRUE; - m_mouseVisibleMemory = TRUE; - m_logicTimeScaleEnabledMemory = FALSE; - - for(Int i = 0; i < MAX_SLOTS; ++i) - { - m_progressComplete[i] = FALSE; - m_progressCompleteTimeout[i] = 0; - } - m_forceGameStartByTimeOut = FALSE; - - m_isScoringEnabled = TRUE; - m_showBehindBuildingMarkers = TRUE; - m_drawIconUI = TRUE; - m_showDynamicLOD = TRUE; - m_scriptHulkMaxLifetimeOverride = -1; - + reset(); m_isInUpdate = FALSE; - - m_rankPointsToAddAtGameStart = 0; } //------------------------------------------------------------------------------------------------- @@ -482,7 +425,20 @@ void GameLogic::reset( void ) // clear any table of contents we have m_objectTOC.clear(); - setDefaults( FALSE ); + m_frame = 0; + m_hasUpdated = FALSE; + m_width = DEFAULT_WORLD_WIDTH; + m_height = DEFAULT_WORLD_HEIGHT; + m_objList = NULL; +#ifdef ALLOW_NONSLEEPY_UPDATES + m_normalUpdates.clear(); +#endif + for (std::vector::iterator it = m_sleepyUpdates.begin(); it != m_sleepyUpdates.end(); ++it) + { + (*it)->friend_setIndexInLogic(-1); + } + m_sleepyUpdates.clear(); + m_curUpdateModule = NULL; m_isScoringEnabled = TRUE; m_showBehindBuildingMarkers = TRUE; @@ -1076,17 +1032,19 @@ void GameLogic::startNewGame( Bool saveGame ) } m_rankLevelLimit = 1000; // this is reset every game. - setDefaults( saveGame ); + + // + // only reset the next object ID allocater counter when we're not loading a save game. + // for save games, we read this value out of the save game file and it is important + // that we preserve it as we load and execute the game + // + if( saveGame == FALSE ) + m_nextObjID = (ObjectID)1; + 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; - m_showDynamicLOD = TRUE; - m_scriptHulkMaxLifetimeOverride = -1; - // Fill in the game color and Factions before we do the Load Screen - GameInfo *game = NULL; TheGameInfo = NULL; Int localSlot = 0; if (TheNetwork) @@ -1094,41 +1052,40 @@ void GameLogic::startNewGame( Bool saveGame ) if (TheLAN) { DEBUG_LOG(("Starting network game")); - TheGameInfo = game = TheLAN->GetMyGame(); + TheGameInfo = TheLAN->GetMyGame(); } else { DEBUG_LOG(("Starting gamespy game")); - TheGameInfo = game = TheGameSpyGame; /// @todo: MDC add back in after demo + TheGameInfo = TheGameSpyGame; /// @todo: MDC add back in after demo } } else { if (TheRecorder && TheRecorder->isPlaybackMode()) { - TheGameInfo = game = TheRecorder->getGameInfo(); + TheGameInfo = TheRecorder->getGameInfo(); } else if(m_gameMode == GAME_SKIRMISH) { - TheGameInfo = game = TheSkirmishGameInfo; + TheGameInfo = TheSkirmishGameInfo; } } - checkForDuplicateColors( game ); + checkForDuplicateColors( TheGameInfo ); Bool isSkirmishOrSkirmishReplay = FALSE; - if (game) + if (TheGameInfo) { for (Int i=0; igetSlot(i); + GameSlot *slot = TheGameInfo->getSlot(i); if (!saveGame) { slot->saveOffOriginalInfo(); } if (slot->isAI()) { isSkirmishOrSkirmishReplay = TRUE; - continue; } } } else { @@ -1138,8 +1095,8 @@ void GameLogic::startNewGame( Bool saveGame ) } } - populateRandomSideAndColor( game ); - populateRandomStartPosition( game ); + populateRandomSideAndColor( TheGameInfo ); + populateRandomStartPosition( TheGameInfo ); //****************************// // Start the LoadScreen Now! // @@ -1152,7 +1109,7 @@ void GameLogic::startNewGame( Bool saveGame ) if(m_loadScreen && !TheGlobalData->m_headless) { TheMouse->setVisibility(FALSE); - m_loadScreen->init(game); + m_loadScreen->init(TheGameInfo); updateLoadProgress( LOAD_PROGRESS_START ); } @@ -1194,7 +1151,7 @@ void GameLogic::startNewGame( Bool saveGame ) #endif Int progressCount = LOAD_PROGRESS_SIDE_POPULATION; - if (game) + if (TheGameInfo) { if (TheGameEngine->isMultiplayerSession() || isSkirmishOrSkirmishReplay) @@ -1203,12 +1160,12 @@ void GameLogic::startNewGame( Bool saveGame ) TheSidesList->prepareForMP_or_Skirmish(); } - //DEBUG_LOG(("Starting LAN game with %d players", game->getNumPlayers())); + //DEBUG_LOG(("Starting LAN game with %d players", TheGameInfo->getNumPlayers())); Dict d; for (int i=0; igetSlot(i); + GameSlot *slot = TheGameInfo->getSlot(i); if (!slot || !slot->isHuman()) { @@ -1235,7 +1192,7 @@ void GameLogic::startNewGame( Bool saveGame ) d.setAsciiString(TheKey_playerFaction, KEYNAME(pt->getNameKey())); } - if (game->isPlayerPreorder(i)) + if (TheGameInfo->isPlayerPreorder(i)) { d.setBool(TheKey_playerIsPreorder, TRUE); } @@ -1245,7 +1202,7 @@ void GameLogic::startNewGame( Bool saveGame ) DEBUG_LOG(("Looking for allies of player %d, team %d", i, team)); for(int j=0; j < MAX_SLOTS; ++j) { - GameSlot *teamSlot = game->getSlot(j); + GameSlot *teamSlot = TheGameInfo->getSlot(j); // for check to see if we're trying to add ourselves if(i == j || !teamSlot->isOccupied()) continue; @@ -1299,7 +1256,7 @@ void GameLogic::startNewGame( Bool saveGame ) d.setInt(TheKey_multiplayerStartIndex, slot->getStartPos()); // d.setBool(TheKey_multiplayerIsLocal, slot->isLocalPlayer()); // d.setBool(TheKey_multiplayerIsLocal, slot->getIP() == game->getLocalIP()); - d.setBool(TheKey_multiplayerIsLocal, slot->isHuman() && (slot->getName().compare(game->getSlot(game->getLocalSlotNum())->getName().str()) == 0)); + d.setBool(TheKey_multiplayerIsLocal, slot->isHuman() && (slot->getName().compare(TheGameInfo->getSlot(TheGameInfo->getLocalSlotNum())->getName().str()) == 0)); /* if (slot->getIP() == game->getLocalIP()) @@ -1322,7 +1279,7 @@ void GameLogic::startNewGame( Bool saveGame ) AsciiString slotNameAscii; slotNameAscii.translate(slot->getName()); - if (slot->isHuman() && game->getSlotNum(slotNameAscii) == game->getLocalSlotNum()) { + if (slot->isHuman() && TheGameInfo->getSlotNum(slotNameAscii) == TheGameInfo->getLocalSlotNum()) { localSlot = i; } TheSidesList->addSide(&d); @@ -1392,11 +1349,11 @@ void GameLogic::startNewGame( Bool saveGame ) // if there are no other teams (happens for debugging) don't end the game immediately Int numTeams = 0; // this can be higher than expected, but is accurate for determining 0, 1, 2+ Int lastTeam = -1; - if (game) + if (TheGameInfo) { for (int i=0; igetConstSlot(i); + const GameSlot *slot = TheGameInfo->getConstSlot(i); if (slot->isOccupied() && slot->getPlayerTemplate() != PLAYERTEMPLATE_OBSERVER) { if (slot->getTeamNumber() == -1 || slot->getTeamNumber() != lastTeam) @@ -1625,11 +1582,11 @@ void GameLogic::startNewGame( Bool saveGame ) ThePartitionManager->revealMapForPlayerPermanently( observerPlayer->getPlayerIndex() ); DEBUG_LOG(("Reveal shroud for %ls whose index is %d", observerPlayer->getPlayerDisplayName().str(), observerPlayer->getPlayerIndex())); - if (game) + if (TheGameInfo) { for (int i=0; igetSlot(i); + GameSlot *slot = TheGameInfo->getSlot(i); if (!slot || !slot->isOccupied()) continue; @@ -1763,11 +1720,11 @@ void GameLogic::startNewGame( Bool saveGame ) progressCount = LOAD_PROGRESS_LOOP_INITIAL_NETWORK_BUILDINGS; // place initial network buildings/units - if (game && !saveGame) + if (TheGameInfo && !saveGame) { for (int i=0; igetSlot(i); + GameSlot *slot = TheGameInfo->getSlot(i); if (!slot || !slot->isOccupied()) continue; @@ -1842,9 +1799,9 @@ void GameLogic::startNewGame( Bool saveGame ) // Note - We construct the multiplayer start spot name manually here, so change this if you // change TheKey_Player_1_Start etc. mdc AsciiString startingCamName = TheNameKeyGenerator->keyToName(TheKey_InitialCameraPosition); - if (game) + if (TheGameInfo) { - GameSlot *slot = game->getSlot(localSlot); + GameSlot *slot = TheGameInfo->getSlot(localSlot); DEBUG_ASSERTCRASH(slot, ("Starting a LAN game without ourselves!")); if (slot->isHuman()) diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h index 420142129b..c4f7e13073 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h @@ -353,7 +353,6 @@ class GameLogic : public SubsystemInterface, public Snapshot ObjectID m_nextObjID; ///< For allocating object id's - void setDefaults( Bool loadSaveGame ); ///< Set default values of class object void processDestroyList( void ); ///< Destroy all pending objects on the destroy list void destroyAllObjectsImmediate(); ///< destroy, and process destroy list immediately diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp index c729fb81cd..67a23d92c0 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp @@ -264,36 +264,6 @@ GameLogic::GameLogic( void ) m_clearingGameData = FALSE; } -// ------------------------------------------------------------------------------------------------ -/** Utility function to set class variables to default values. */ -// ------------------------------------------------------------------------------------------------ -void GameLogic::setDefaults( Bool loadingSaveGame ) -{ - m_frame = 0; - m_hasUpdated = FALSE; - m_width = DEFAULT_WORLD_WIDTH; - m_height = DEFAULT_WORLD_HEIGHT; - m_objList = NULL; -#ifdef ALLOW_NONSLEEPY_UPDATES - m_normalUpdates.clear(); -#endif - for (std::vector::iterator it = m_sleepyUpdates.begin(); it != m_sleepyUpdates.end(); ++it) - { - (*it)->friend_setIndexInLogic(-1); - } - m_sleepyUpdates.clear(); - m_curUpdateModule = NULL; - - // - // only reset the next object ID allocater counter when we're not loading a save game. - // for save games, we read this value out of the save game file and it is important - // that we preserve it as we load and execute the game - // - if( loadingSaveGame == FALSE ) - m_nextObjID = (ObjectID)1; - -} - //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- Bool GameLogic::isInSinglePlayerGame( void ) @@ -385,9 +355,6 @@ void GameLogic::init( void ) setFPMode(); - /// @todo Clear object and destroy lists - setDefaults( FALSE ); - // create the partition manager ThePartitionManager = NEW PartitionManager; ThePartitionManager->init(); @@ -414,33 +381,8 @@ void GameLogic::init( void ) // create a team for the player //DEBUG_ASSERTCRASH(ThePlayerList, ("null ThePlayerList")); //ThePlayerList->setLocalPlayer(0); - - m_CRC = 0; - m_pauseFrame = 0; - m_gamePaused = FALSE; - m_pauseSound = FALSE; - m_pauseMusic = FALSE; - m_pauseInput = FALSE; - m_inputEnabledMemory = TRUE; - m_mouseVisibleMemory = TRUE; - m_logicTimeScaleEnabledMemory = FALSE; - - for(Int i = 0; i < MAX_SLOTS; ++i) - { - m_progressComplete[i] = FALSE; - m_progressCompleteTimeout[i] = 0; - } - m_forceGameStartByTimeOut = FALSE; - - m_isScoringEnabled = TRUE; - m_showBehindBuildingMarkers = TRUE; - m_drawIconUI = TRUE; - m_showDynamicLOD = TRUE; - m_scriptHulkMaxLifetimeOverride = -1; - + reset(); m_isInUpdate = FALSE; - - m_rankPointsToAddAtGameStart = 0; } //------------------------------------------------------------------------------------------------- @@ -495,7 +437,20 @@ void GameLogic::reset( void ) // clear any table of contents we have m_objectTOC.clear(); - setDefaults( FALSE ); + m_frame = 0; + m_hasUpdated = FALSE; + m_width = DEFAULT_WORLD_WIDTH; + m_height = DEFAULT_WORLD_HEIGHT; + m_objList = NULL; +#ifdef ALLOW_NONSLEEPY_UPDATES + m_normalUpdates.clear(); +#endif + for (std::vector::iterator it = m_sleepyUpdates.begin(); it != m_sleepyUpdates.end(); ++it) + { + (*it)->friend_setIndexInLogic(-1); + } + m_sleepyUpdates.clear(); + m_curUpdateModule = NULL; m_isScoringEnabled = TRUE; m_showBehindBuildingMarkers = TRUE; @@ -1215,20 +1170,22 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) } m_rankLevelLimit = 1000; // this is reset every game. - setDefaults( loadingSaveGame ); + + // + // only reset the next object ID allocater counter when we're not loading a save game. + // for save games, we read this value out of the save game file and it is important + // that we preserve it as we load and execute the game + // + if( loadingSaveGame == FALSE ) + m_nextObjID = (ObjectID)1; + 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; - m_showDynamicLOD = TRUE; - m_scriptHulkMaxLifetimeOverride = -1; - Campaign* currentCampaign = TheCampaignManager->getCurrentCampaign(); Bool isChallengeCampaign = m_gameMode == GAME_SINGLE_PLAYER && currentCampaign && currentCampaign->m_isChallengeCampaign; // Fill in the game color and Factions before we do the Load Screen - GameInfo *game = NULL; TheGameInfo = NULL; Int localSlot = 0; if (TheNetwork) @@ -1236,27 +1193,27 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) if (TheLAN) { DEBUG_LOG(("Starting network game")); - TheGameInfo = game = TheLAN->GetMyGame(); + TheGameInfo = TheLAN->GetMyGame(); } else { DEBUG_LOG(("Starting gamespy game")); - TheGameInfo = game = TheGameSpyGame; /// @todo: MDC add back in after demo + TheGameInfo = TheGameSpyGame; /// @todo: MDC add back in after demo } } else { if (TheRecorder && TheRecorder->isPlaybackMode()) { - TheGameInfo = game = TheRecorder->getGameInfo(); + TheGameInfo = TheRecorder->getGameInfo(); } else if(m_gameMode == GAME_SKIRMISH) { - TheGameInfo = game = TheSkirmishGameInfo; + TheGameInfo = TheSkirmishGameInfo; } else if(isChallengeCampaign) { - TheGameInfo = game = TheChallengeGameInfo; + TheGameInfo = TheChallengeGameInfo; } } @@ -1276,21 +1233,20 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) } } - checkForDuplicateColors( game ); + checkForDuplicateColors( TheGameInfo ); Bool isSkirmishOrSkirmishReplay = FALSE; - if (game) + if (TheGameInfo) { for (Int i=0; igetSlot(i); + GameSlot *slot = TheGameInfo->getSlot(i); if (!loadingSaveGame) { slot->saveOffOriginalInfo(); } if (slot->isAI()) { isSkirmishOrSkirmishReplay = TRUE; - continue; } } } else { @@ -1300,8 +1256,8 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) } } - populateRandomSideAndColor( game ); - populateRandomStartPosition( game ); + populateRandomSideAndColor( TheGameInfo ); + populateRandomStartPosition( TheGameInfo ); //****************************// // Start the LoadScreen Now! // @@ -1314,7 +1270,7 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) if(m_loadScreen) { TheMouse->setVisibility(FALSE); - m_loadScreen->init(game); + m_loadScreen->init(TheGameInfo); updateLoadProgress( LOAD_PROGRESS_START ); } @@ -1356,7 +1312,7 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) #endif Int progressCount = LOAD_PROGRESS_SIDE_POPULATION; - if (game) + if (TheGameInfo) { if (TheGameEngine->isMultiplayerSession() || isSkirmishOrSkirmishReplay) @@ -1370,7 +1326,7 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) for (int i=0; igetSlot(i); + GameSlot *slot = TheGameInfo->getSlot(i); if (!slot || !slot->isHuman()) { @@ -1397,7 +1353,7 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) d.setAsciiString(TheKey_playerFaction, KEYNAME(pt->getNameKey())); } - if (game->isPlayerPreorder(i)) + if (TheGameInfo->isPlayerPreorder(i)) { d.setBool(TheKey_playerIsPreorder, TRUE); } @@ -1407,7 +1363,7 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) DEBUG_LOG(("Looking for allies of player %d, team %d", i, team)); for(int j=0; j < MAX_SLOTS; ++j) { - GameSlot *teamSlot = game->getSlot(j); + GameSlot *teamSlot = TheGameInfo->getSlot(j); // for check to see if we're trying to add ourselves if(i == j || !teamSlot->isOccupied()) continue; @@ -1461,7 +1417,7 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) d.setInt(TheKey_multiplayerStartIndex, slot->getStartPos()); // d.setBool(TheKey_multiplayerIsLocal, slot->isLocalPlayer()); // d.setBool(TheKey_multiplayerIsLocal, slot->getIP() == game->getLocalIP()); - d.setBool(TheKey_multiplayerIsLocal, slot->isHuman() && (slot->getName().compare(game->getSlot(game->getLocalSlotNum())->getName().str()) == 0)); + d.setBool(TheKey_multiplayerIsLocal, slot->isHuman() && (slot->getName().compare(TheGameInfo->getSlot(TheGameInfo->getLocalSlotNum())->getName().str()) == 0)); /* if (slot->getIP() == game->getLocalIP()) @@ -1484,7 +1440,7 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) AsciiString slotNameAscii; slotNameAscii.translate(slot->getName()); - if (slot->isHuman() && game->getSlotNum(slotNameAscii) == game->getLocalSlotNum()) { + if (slot->isHuman() && TheGameInfo->getSlotNum(slotNameAscii) == TheGameInfo->getLocalSlotNum()) { localSlot = i; } TheSidesList->addSide(&d); @@ -1554,11 +1510,11 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) // if there are no other teams (happens for debugging) don't end the game immediately Int numTeams = 0; // this can be higher than expected, but is accurate for determining 0, 1, 2+ Int lastTeam = -1; - if (game) + if (TheGameInfo) { for (int i=0; igetConstSlot(i); + const GameSlot *slot = TheGameInfo->getConstSlot(i); if (slot->isOccupied() && slot->getPlayerTemplate() != PLAYERTEMPLATE_OBSERVER) { if (slot->getTeamNumber() == -1 || slot->getTeamNumber() != lastTeam) @@ -1787,11 +1743,11 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) ThePartitionManager->revealMapForPlayerPermanently( observerPlayer->getPlayerIndex() ); DEBUG_LOG(("Reveal shroud for %ls whose index is %d", observerPlayer->getPlayerDisplayName().str(), observerPlayer->getPlayerIndex())); - if (game) + if (TheGameInfo) { for (int i=0; igetSlot(i); + GameSlot *slot = TheGameInfo->getSlot(i); if (!slot || !slot->isOccupied()) continue; @@ -1977,11 +1933,11 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) progressCount = LOAD_PROGRESS_LOOP_INITIAL_NETWORK_BUILDINGS; // place initial network buildings/units - if (game && !loadingSaveGame) + if (TheGameInfo && !loadingSaveGame) { for (int i=0; igetSlot(i); + GameSlot *slot = TheGameInfo->getSlot(i); if (!slot || !slot->isOccupied()) continue; @@ -2032,7 +1988,7 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) // Trouble was that skirmish games would get no command centers upon start, if this was set true in a GameSpyMenu if ( isInInternetGame() ) { - if ( game->oldFactionsOnly() && !pt->isOldFaction() ) + if ( TheGameInfo->oldFactionsOnly() && !pt->isOldFaction() ) continue; } @@ -2083,9 +2039,9 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) // Note - We construct the multiplayer start spot name manually here, so change this if you // change TheKey_Player_1_Start etc. mdc AsciiString startingCamName = TheNameKeyGenerator->keyToName(TheKey_InitialCameraPosition); - if (game) + if (TheGameInfo) { - GameSlot *slot = game->getSlot(localSlot); + GameSlot *slot = TheGameInfo->getSlot(localSlot); DEBUG_ASSERTCRASH(slot, ("Starting a LAN game without ourselves!")); if (slot->isHuman()) From 224017e223a072c37a1ca3f278315af0bdab475d Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Fri, 2 Jan 2026 11:06:21 +0100 Subject: [PATCH 59/70] bugfix(heightmap): Disable old uv adjument for cliffs (#2038) --- .../Source/W3DDevice/GameClient/WorldHeightMap.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Core/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp index 52384dfed5..18d134fb53 100644 --- a/Core/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp +++ b/Core/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp @@ -1742,7 +1742,11 @@ Bool WorldHeightMap::getUVForTileIndex(Int ndx, Short tileNdx, float U[4], float return info.flip; } } -#define DO_OLD_UV + +// TheSuperHackers @bugfix xezon 11/12/2025 Disables the old uv adjustment for cliffs, +// because it produces bad uv tiles on steep terrain and is also not helping performance. +// @todo Delete this code when we are certain we never need this again. +//#define DO_OLD_UV #ifdef DO_OLD_UV // old uv adjustment for cliffs static Real STRETCH_LIMIT = 1.5f; // If it is stretching less than this, don't adjust. From 5deddce8fba8f4bd5995e2bf3d3f56ed33655222 Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Fri, 2 Jan 2026 11:06:52 +0100 Subject: [PATCH 60/70] bugfix(heightmap): Fix dynamic lights on terrain (#2039) --- .../Source/W3DDevice/GameClient/HeightMap.cpp | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/Core/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp b/Core/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp index 55f228a81d..57d0decba1 100644 --- a/Core/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp +++ b/Core/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp @@ -1387,7 +1387,10 @@ Int HeightMapRenderObjClass::initHeightData(Int x, Int y, WorldHeightMap *pMap, //============================================================================= // HeightMapRenderObjClass::On_Frame_Update //============================================================================= -/** Updates the diffuse color values in the vertices as affected by the dynamic lights.*/ +// Updates the diffuse color values in the vertices as affected by the dynamic +// lights. +// TheSuperHackers @bugfix xezon 15/12/2025 Now draws the dynamic lights +// properly on the entirety of the drawable map region. //============================================================================= void HeightMapRenderObjClass::On_Frame_Update(void) { @@ -1418,10 +1421,10 @@ void HeightMapRenderObjClass::On_Frame_Update(void) Int numDynaLights=0; W3DDynamicLight *enabledLights[MAX_ENABLED_DYNAMIC_LIGHTS]; - Int yCoordMin = m_map->getDrawOrgY(); - Int yCoordMax = m_y+m_map->getDrawOrgY(); - Int xCoordMin = m_map->getDrawOrgX(); - Int xCoordMax = m_x+m_map->getDrawOrgX(); + const Int xCoordMin = m_map->getDrawOrgX() - m_map->getBorderSizeInline(); + const Int yCoordMin = m_map->getDrawOrgY() - m_map->getBorderSizeInline(); + const Int xCoordMax = xCoordMin + m_map->getDrawWidth(); + const Int yCoordMax = yCoordMin + m_map->getDrawHeight(); for (pDynamicLightsIterator.First(); !pDynamicLightsIterator.Is_Done(); pDynamicLightsIterator.Next()) { From 13de4270f8ccd088369bc66f2a02d9185c6f77fb Mon Sep 17 00:00:00 2001 From: IamInnocent3X Date: Sat, 3 Jan 2026 00:14:31 +0800 Subject: [PATCH 61/70] perf(weaponstore): Optimize WeaponStore::findWeaponTemplatePrivate with hash map lookup (#2042) --- Generals/Code/GameEngine/Include/GameLogic/Weapon.h | 5 +++++ .../Code/GameEngine/Source/GameLogic/Object/Weapon.cpp | 8 +++++--- GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h | 5 +++++ .../Code/GameEngine/Source/GameLogic/Object/Weapon.cpp | 8 +++++--- 4 files changed, 20 insertions(+), 6 deletions(-) diff --git a/Generals/Code/GameEngine/Include/GameLogic/Weapon.h b/Generals/Code/GameEngine/Include/GameLogic/Weapon.h index d75cb276f5..6895677ba1 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Weapon.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Weapon.h @@ -862,6 +862,11 @@ class WeaponStore : public SubsystemInterface }; std::vector m_weaponTemplateVector; + + // TheSuperHackers @performance IamInnocent 01/01/2026 - Now additionally stores the same weapon templates in a hash map to optimize lookups by name key + typedef std::hash_map, rts::equal_to > WeaponTemplateMap; + WeaponTemplateMap m_weaponTemplateHashMap; + std::list m_weaponDDI; }; diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp index ff1dbf4ed1..86835e3872 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp @@ -1438,6 +1438,7 @@ WeaponStore::~WeaponStore() deleteInstance(wt); } m_weaponTemplateVector.clear(); + m_weaponTemplateHashMap.clear(); } //------------------------------------------------------------------------------------------------- @@ -1496,9 +1497,9 @@ const WeaponTemplate *WeaponStore::findWeaponTemplate( const char* name ) const WeaponTemplate *WeaponStore::findWeaponTemplatePrivate( NameKeyType key ) const { // search weapon list for name - for (size_t i = 0; i < m_weaponTemplateVector.size(); i++) - if( m_weaponTemplateVector[ i ]->getNameKey() == key ) - return m_weaponTemplateVector[i]; + WeaponTemplateMap::const_iterator it = m_weaponTemplateHashMap.find(key); + if(it != m_weaponTemplateHashMap.end()) + return it->second; return NULL; @@ -1517,6 +1518,7 @@ WeaponTemplate *WeaponStore::newWeaponTemplate(AsciiString name) wt->m_name = name; wt->m_nameKey = TheNameKeyGenerator->nameToKey( name ); m_weaponTemplateVector.push_back(wt); + m_weaponTemplateHashMap[wt->m_nameKey] = wt; return wt; } diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h index 6b39c95758..3afebed868 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h @@ -887,6 +887,11 @@ class WeaponStore : public SubsystemInterface }; std::vector m_weaponTemplateVector; + + // TheSuperHackers @performance IamInnocent 01/01/2026 - Now additionally stores the same weapon templates in a hash map to optimize lookups by name key + typedef std::hash_map, rts::equal_to > WeaponTemplateMap; + WeaponTemplateMap m_weaponTemplateHashMap; + std::list m_weaponDDI; }; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp index 7720c5cc71..473f284ab4 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp @@ -1583,6 +1583,7 @@ WeaponStore::~WeaponStore() deleteInstance(wt); } m_weaponTemplateVector.clear(); + m_weaponTemplateHashMap.clear(); } //------------------------------------------------------------------------------------------------- @@ -1641,9 +1642,9 @@ const WeaponTemplate *WeaponStore::findWeaponTemplate( const char* name ) const WeaponTemplate *WeaponStore::findWeaponTemplatePrivate( NameKeyType key ) const { // search weapon list for name - for (size_t i = 0; i < m_weaponTemplateVector.size(); i++) - if( m_weaponTemplateVector[ i ]->getNameKey() == key ) - return m_weaponTemplateVector[i]; + WeaponTemplateMap::const_iterator it = m_weaponTemplateHashMap.find(key); + if(it != m_weaponTemplateHashMap.end()) + return it->second; return NULL; @@ -1662,6 +1663,7 @@ WeaponTemplate *WeaponStore::newWeaponTemplate(AsciiString name) wt->m_name = name; wt->m_nameKey = TheNameKeyGenerator->nameToKey( name ); m_weaponTemplateVector.push_back(wt); + m_weaponTemplateHashMap[wt->m_nameKey] = wt; return wt; } From 409fed26fcfc3ca9b5298f282d4669ef94cc3b8a Mon Sep 17 00:00:00 2001 From: Caball009 <82909616+Caball009@users.noreply.github.com> Date: Sat, 3 Jan 2026 10:29:09 +0100 Subject: [PATCH 62/70] bugfix(thingfactory): Reset next ThingTemplate ID after clearing custom map template overrides to avoid CRC mismatch in the next multiplayer game session (#2034) --- .../Code/GameEngine/Source/Common/Thing/ThingFactory.cpp | 6 ++++++ .../Code/GameEngine/Source/Common/Thing/ThingFactory.cpp | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/Generals/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp b/Generals/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp index 22db98ea19..42b9e4a120 100644 --- a/Generals/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp +++ b/Generals/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp @@ -236,8 +236,14 @@ void ThingFactory::reset( void ) m_templateHashMap.erase(templateName); } + DEBUG_ASSERTCRASH(!nextT || t->getTemplateID() == nextT->getTemplateID() + 1, ("Next template ID is unexpected")); + t = nextT; } + + // TheSuperHackers @bugfix Caball009 25/12/2025 Avoid mismatches by making m_nextTemplateID unique for a single match instead of unique since game launch. + DEBUG_ASSERTCRASH(m_firstTemplate && m_firstTemplate->getTemplateID() == m_templateHashMap.size(), ("Template ID is unexpected after deleting overrides")); + m_nextTemplateID = static_cast(m_firstTemplate->getTemplateID() + 1); } //------------------------------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp index 1aa09afad2..71a9e724fb 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp @@ -236,8 +236,14 @@ void ThingFactory::reset( void ) m_templateHashMap.erase(templateName); } + DEBUG_ASSERTCRASH(!nextT || t->getTemplateID() == nextT->getTemplateID() + 1, ("Next template ID is unexpected")); + t = nextT; } + + // TheSuperHackers @bugfix Caball009 25/12/2025 Avoid mismatches by making m_nextTemplateID unique for a single match instead of unique since game launch. + DEBUG_ASSERTCRASH(m_firstTemplate && m_firstTemplate->getTemplateID() == m_templateHashMap.size(), ("Template ID is unexpected after deleting overrides")); + m_nextTemplateID = static_cast(m_firstTemplate->getTemplateID() + 1); } //------------------------------------------------------------------------------------------------- From f2da2b6e13841de7f429c70a6c2a70ef4a1d53a1 Mon Sep 17 00:00:00 2001 From: Caball009 <82909616+Caball009@users.noreply.github.com> Date: Sat, 3 Jan 2026 10:30:52 +0100 Subject: [PATCH 63/70] tweak(drawable): Set correct model tint color after loading a save game (#2025) --- .../GameEngine/Source/GameClient/Drawable.cpp | 16 +++++++++++++-- .../GameEngine/Source/GameClient/Drawable.cpp | 20 +++++++++++++++---- 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/Generals/Code/GameEngine/Source/GameClient/Drawable.cpp b/Generals/Code/GameEngine/Source/GameClient/Drawable.cpp index 10e680001b..b7284e0c45 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Drawable.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Drawable.cpp @@ -4248,13 +4248,18 @@ void Drawable::xferDrawableModules( Xfer *xfer ) * during the module xfer (CBD) * 4: Added m_ambientSoundEnabled flag * 5: save full mtx, not pos+orient. + * 6: TheSuperHackers @bugfix Removed m_prevTintStatus because loading its value is unnecessary and undesirable */ // ------------------------------------------------------------------------------------------------ void Drawable::xfer( Xfer *xfer ) { // version +#if RETAIL_COMPATIBLE_XFER_SAVE const XferVersion currentVersion = 5; +#else + const XferVersion currentVersion = 6; +#endif XferVersion version = currentVersion; xfer->xferVersion( &version, currentVersion ); @@ -4414,8 +4419,15 @@ void Drawable::xfer( Xfer *xfer ) // tint status xfer->xferUnsignedInt( &m_tintStatus ); - // prev tint status - xfer->xferUnsignedInt( &m_prevTintStatus ); + if (version <= 5) + { + // prev tint status + xfer->xferUnsignedInt( &m_prevTintStatus ); + + // TheSuperHackers @bugfix Caball009 21/12/2025 Trigger tinting after loading a save game. + if (xfer->getXferMode() == XFER_LOAD) + m_prevTintStatus = 0; + } // fading mode xfer->xferUser( &m_fadeMode, sizeof( FadingMode ) ); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp index 9f1f5f7eaf..f5dd995db0 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp @@ -4904,15 +4904,20 @@ void Drawable::xferDrawableModules( Xfer *xfer ) * during the module xfer (CBD) * 4: Added m_ambientSoundEnabled flag * 5: save full mtx, not pos+orient. - * 6: Added m_ambientSoundEnabledFromScript flag - * 7: Save the customize ambient sound info + * 6: Added m_ambientSoundEnabledFromScript flag + * 7: Save the customize ambient sound info + * 8: TheSuperHackers @bugfix Removed m_prevTintStatus because loading its value is unnecessary and undesirable */ // ------------------------------------------------------------------------------------------------ void Drawable::xfer( Xfer *xfer ) { // version +#if RETAIL_COMPATIBLE_XFER_SAVE const XferVersion currentVersion = 7; +#else + const XferVersion currentVersion = 8; +#endif XferVersion version = currentVersion; xfer->xferVersion( &version, currentVersion ); @@ -5072,8 +5077,15 @@ void Drawable::xfer( Xfer *xfer ) // tint status xfer->xferUnsignedInt( &m_tintStatus ); - // prev tint status - xfer->xferUnsignedInt( &m_prevTintStatus ); + if (version <= 7) + { + // prev tint status + xfer->xferUnsignedInt( &m_prevTintStatus ); + + // TheSuperHackers @bugfix Caball009 21/12/2025 Trigger tinting after loading a save game. + if (xfer->getXferMode() == XFER_LOAD) + m_prevTintStatus = 0; + } // fading mode xfer->xferUser( &m_fadeMode, sizeof( FadingMode ) ); From ae05f11ad104533ec167b7c4a4e3465e374dc813 Mon Sep 17 00:00:00 2001 From: Stubbjax Date: Sun, 4 Jan 2026 03:56:58 +1100 Subject: [PATCH 64/70] bugfix(aiupdate): Prevent manually ejecting rappelling Rangers during Chinook Combat Drop (#1789) --- .../Object/Update/AIUpdate/ChinookAIUpdate.cpp | 14 ++++++++++++++ .../Object/Update/AIUpdate/ChinookAIUpdate.cpp | 14 ++++++++++++++ 2 files changed, 28 insertions(+) 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 60dbd2361e..cf48a89f97 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp @@ -587,6 +587,7 @@ class ChinookCombatDropState : public State Object* rappeller = getPotentialRappeller(obj); if (rappeller != NULL) { +#if RETAIL_COMPATIBLE_CRC ExitInterface *exitInterface = obj->getObjectExitInterface(); ExitDoorType exitDoor = exitInterface ? exitInterface->reserveDoorForExit(rappeller->getTemplate(), rappeller) : DOOR_NONE_AVAILABLE; if(exitDoor != DOOR_NONE_AVAILABLE) @@ -597,6 +598,15 @@ class ChinookCombatDropState : public State { DEBUG_CRASH(("rappeller is not free to exit... what?")); } +#else + // TheSuperHackers @bugfix 03/01/2026 Bypass door reservation as rappellers are always + // expected to be free to exit. This avoids prior rappel conditions in getAiFreeToExit + // from allowing rappellers to be freely 'dropped' from the Chinook during this state. + if (ExitInterface* exitInterface = obj->getObjectExitInterface()) + { + exitInterface->exitObjectViaDoor(rappeller, DOOR_1); + } +#endif rappeller->setTransformMatrix(&it->dropStartMtx); @@ -983,8 +993,12 @@ ObjectID ChinookAIUpdate::getBuildingToNotPathAround() const //------------------------------------------------------------------------------------------------- AIFreeToExitType ChinookAIUpdate::getAiFreeToExit(const Object* exiter) const { +#if RETAIL_COMPATIBLE_CRC if (m_flightStatus == CHINOOK_LANDED || (m_flightStatus == CHINOOK_DOING_COMBAT_DROP && exiter->isKindOf(KINDOF_CAN_RAPPEL))) +#else + if (m_flightStatus == CHINOOK_LANDED) +#endif return FREE_TO_EXIT; return WAIT_TO_EXIT; 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 dd33e54cbd..afed828003 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp @@ -588,6 +588,7 @@ class ChinookCombatDropState : public State Object* rappeller = getPotentialRappeller(obj); if (rappeller != NULL) { +#if RETAIL_COMPATIBLE_CRC ExitInterface *exitInterface = obj->getObjectExitInterface(); ExitDoorType exitDoor = exitInterface ? exitInterface->reserveDoorForExit(rappeller->getTemplate(), rappeller) : DOOR_NONE_AVAILABLE; if(exitDoor != DOOR_NONE_AVAILABLE) @@ -598,6 +599,15 @@ class ChinookCombatDropState : public State { DEBUG_CRASH(("rappeller is not free to exit... what?")); } +#else + // TheSuperHackers @bugfix 03/01/2026 Bypass door reservation as rappellers are always + // expected to be free to exit. This avoids prior rappel conditions in getAiFreeToExit + // from allowing rappellers to be freely 'dropped' from the Chinook during this state. + if (ExitInterface* exitInterface = obj->getObjectExitInterface()) + { + exitInterface->exitObjectViaDoor(rappeller, DOOR_1); + } +#endif rappeller->setTransformMatrix(&it->dropStartMtx); @@ -1045,8 +1055,12 @@ ObjectID ChinookAIUpdate::getBuildingToNotPathAround() const //------------------------------------------------------------------------------------------------- AIFreeToExitType ChinookAIUpdate::getAiFreeToExit(const Object* exiter) const { +#if RETAIL_COMPATIBLE_CRC if (m_flightStatus == CHINOOK_LANDED || (m_flightStatus == CHINOOK_DOING_COMBAT_DROP && exiter->isKindOf(KINDOF_CAN_RAPPEL))) +#else + if (m_flightStatus == CHINOOK_LANDED) +#endif return FREE_TO_EXIT; return WAIT_TO_EXIT; From afa8aa357c0890bd8d77303e0eba2adc34da79dc Mon Sep 17 00:00:00 2001 From: Stubbjax Date: Sun, 4 Jan 2026 03:57:32 +1100 Subject: [PATCH 65/70] bugfix(ai): Undetected mines can now be approached when using a disarm weapon (#1883) --- .../Code/GameEngine/Source/GameLogic/AI/AIStates.cpp | 12 +++++++++++- .../Code/GameEngine/Source/GameLogic/AI/AIStates.cpp | 12 +++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp index 05ce1ea359..9207bb5f34 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp @@ -2596,7 +2596,17 @@ StateReturnType AIAttackApproachTargetState::updateInternal() { if( victim->testStatus( OBJECT_STATUS_STEALTHED ) && !victim->testStatus( OBJECT_STATUS_DETECTED ) ) { - return STATE_FAILURE; // If obj is stealthed, can no longer approach. + // If obj is stealthed, can no longer approach. + // TheSuperHackers @bugfix Stubbjax 19/11/2025 Except when disarming stealthed mines. +#if RETAIL_COMPATIBLE_CRC + return STATE_FAILURE; +#else + const Bool isTargetingMine = weapon && weapon->getDamageType() == DAMAGE_DISARM && + (victim->isKindOf(KINDOF_MINE)); + + if (!isTargetingMine) + return STATE_FAILURE; +#endif } ai->setCurrentVictim(victim); // Attacking an object. diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp index 63b3474662..c2468cbfcd 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp @@ -2682,7 +2682,17 @@ StateReturnType AIAttackApproachTargetState::updateInternal() } if( victim->testStatus( OBJECT_STATUS_STEALTHED ) && !victim->testStatus( OBJECT_STATUS_DETECTED ) && !victim->testStatus( OBJECT_STATUS_DISGUISED ) ) { - return STATE_FAILURE; // If obj is stealthed, can no longer approach. + // If obj is stealthed, can no longer approach. + // TheSuperHackers @bugfix Stubbjax 19/11/2025 Except when disarming stealthed mines or traps. +#if RETAIL_COMPATIBLE_CRC + return STATE_FAILURE; +#else + const Bool isTargetingMine = weapon && weapon->getDamageType() == DAMAGE_DISARM && + (victim->isKindOf(KINDOF_MINE) || victim->isKindOf(KINDOF_BOOBY_TRAP) || victim->isKindOf(KINDOF_DEMOTRAP)); + + if (!isTargetingMine) + return STATE_FAILURE; +#endif } ai->setCurrentVictim(victim); // Attacking an object. From 0d6c77621a76faeb3e7f9e78fdbf890adb975eea Mon Sep 17 00:00:00 2001 From: Bobby Battista Date: Sun, 4 Jan 2026 01:25:54 -0800 Subject: [PATCH 66/70] bugfix(lobby): Properly sort CRC mismatched game rooms to the bottom of the lobby (#1845) --- Core/GameEngine/Source/GameNetwork/GameSpy/LobbyUtils.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Core/GameEngine/Source/GameNetwork/GameSpy/LobbyUtils.cpp b/Core/GameEngine/Source/GameNetwork/GameSpy/LobbyUtils.cpp index 7ac0d39b85..1b72be479c 100644 --- a/Core/GameEngine/Source/GameNetwork/GameSpy/LobbyUtils.cpp +++ b/Core/GameEngine/Source/GameNetwork/GameSpy/LobbyUtils.cpp @@ -474,8 +474,8 @@ struct GameSortStruct bool operator()(GameSpyStagingRoom *g1, GameSpyStagingRoom *g2) const { // sort CRC mismatches to the bottom - Bool g1Good = (g1->getExeCRC() != TheGlobalData->m_exeCRC || g1->getIniCRC() != TheGlobalData->m_iniCRC); - Bool g2Good = (g1->getExeCRC() != TheGlobalData->m_exeCRC || g1->getIniCRC() != TheGlobalData->m_iniCRC); + Bool g1Good = (g1->getExeCRC() == TheGlobalData->m_exeCRC && g1->getIniCRC() == TheGlobalData->m_iniCRC); + Bool g2Good = (g2->getExeCRC() == TheGlobalData->m_exeCRC && g2->getIniCRC() == TheGlobalData->m_iniCRC); if ( g1Good ^ g2Good ) { return g1Good; From 925ecf1bc83253d7e9f7242ccbaee009dacf83e5 Mon Sep 17 00:00:00 2001 From: Bobby Battista Date: Sun, 4 Jan 2026 01:26:23 -0800 Subject: [PATCH 67/70] perf(ai): Avoid a few std::vector copies when passing ai paths to functions (#1895) --- Dependencies/Utility/Utility/CppMacros.h | 24 +++++++++++++++++++ .../Code/GameEngine/Include/GameLogic/AI.h | 8 +++---- .../Include/GameLogic/AIStateMachine.h | 2 +- .../Include/GameLogic/Module/AIUpdate.h | 4 ++-- .../Include/GameLogic/Module/JetAIUpdate.h | 4 ++-- .../Source/GameLogic/AI/AIStates.cpp | 4 ++-- .../GameLogic/Object/Update/AIUpdate.cpp | 14 +++++++---- .../Object/Update/AIUpdate/JetAIUpdate.cpp | 2 +- .../Code/GameEngine/Include/GameLogic/AI.h | 8 +++---- .../Include/GameLogic/AIStateMachine.h | 2 +- .../Include/GameLogic/Module/AIUpdate.h | 4 ++-- .../Include/GameLogic/Module/JetAIUpdate.h | 4 ++-- .../Source/GameLogic/AI/AIStates.cpp | 4 ++-- .../GameLogic/Object/Update/AIUpdate.cpp | 14 +++++++---- .../Object/Update/AIUpdate/JetAIUpdate.cpp | 2 +- 15 files changed, 68 insertions(+), 32 deletions(-) diff --git a/Dependencies/Utility/Utility/CppMacros.h b/Dependencies/Utility/Utility/CppMacros.h index 8bfb0297f2..02ab1c0d09 100644 --- a/Dependencies/Utility/Utility/CppMacros.h +++ b/Dependencies/Utility/Utility/CppMacros.h @@ -19,6 +19,10 @@ // This file contains macros to help upgrade the code for newer cpp standards. #pragma once +#if __cplusplus >= 201103L +#include +#endif + #if __cplusplus >= 201703L #define NOEXCEPT_17 noexcept #define REGISTER @@ -44,3 +48,23 @@ #define constexpr #define nullptr 0 #endif + +namespace stl +{ + +// Helper to move-assign from reference: uses std::move in C++11, swap in C++98 +template +inline void move_or_swap(T& dest, T& src) +{ +#if __cplusplus >= 201103L + dest = std::move(src); +#else + // C++03 fallback: mimic move semantics + // dest gets src's value, src becomes empty + T empty; + dest.swap(src); + src.swap(empty); +#endif +} + +} // namespace stl diff --git a/Generals/Code/GameEngine/Include/GameLogic/AI.h b/Generals/Code/GameEngine/Include/GameLogic/AI.h index dc2053d4cc..8d3646c268 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/AI.h +++ b/Generals/Code/GameEngine/Include/GameLogic/AI.h @@ -536,18 +536,18 @@ class AICommandInterface aiDoCommand(&parms); } - void aiFollowExitProductionPath( const std::vector* path, Object *ignoreObject, CommandSourceType cmdSource ) + void aiFollowExitProductionPath( std::vector* path, Object *ignoreObject, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_FOLLOW_EXITPRODUCTION_PATH, cmdSource); - parms.m_coords = *path; + stl::move_or_swap(parms.m_coords, *path); parms.m_obj = ignoreObject; aiDoCommand(&parms); } - void aiFollowPath( const std::vector* path, Object *ignoreObject, CommandSourceType cmdSource ) + void aiFollowPath( std::vector* path, Object *ignoreObject, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_FOLLOW_PATH, cmdSource); - parms.m_coords = *path; + stl::move_or_swap(parms.m_coords, *path); parms.m_obj = ignoreObject; aiDoCommand(&parms); } diff --git a/Generals/Code/GameEngine/Include/GameLogic/AIStateMachine.h b/Generals/Code/GameEngine/Include/GameLogic/AIStateMachine.h index 03f0de0e73..7e39c8ec7c 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/AIStateMachine.h +++ b/Generals/Code/GameEngine/Include/GameLogic/AIStateMachine.h @@ -138,7 +138,7 @@ class AIStateMachine : public StateMachine virtual StateReturnType setState( StateID newStateID ); /// @todo Rethink state parameter passing. Continuing in this fashion will have a pile of params in the machine (MSB) - void setGoalPath( const std::vector* path ); + void setGoalPath( std::vector* path ); void addToGoalPath( const Coord3D *pathPoint ); const Coord3D *getGoalPathPosition( Int i ) const; ///< return path position at index "i" Int getGoalPathSize() const { return m_goalPath.size(); } diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h b/Generals/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h index 0482f737aa..b47f353ecf 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h @@ -244,7 +244,7 @@ class AIUpdateInterface : public UpdateModule, public AICommandInterface virtual void privateFollowWaypointPathAsTeam( const Waypoint *way, CommandSourceType cmdSource );///< start following the path from the given point virtual void privateFollowWaypointPathExact( const Waypoint *way, CommandSourceType cmdSource );///< start following the path from the given point virtual void privateFollowWaypointPathAsTeamExact( const Waypoint *way, CommandSourceType cmdSource );///< start following the path from the given point - virtual void privateFollowPath( const std::vector* path, Object *ignoreObject, CommandSourceType cmdSource, Bool exitProduction );///< follow the path defined by the given array of points + virtual void privateFollowPath( std::vector* path, Object *ignoreObject, CommandSourceType cmdSource, Bool exitProduction );///< follow the path defined by the given array of points virtual void privateFollowPathAppend( const Coord3D *pos, CommandSourceType cmdSource ); virtual void privateAttackObject( Object *victim, Int maxShotsToFire, CommandSourceType cmdSource ); ///< attack given object virtual void privateForceAttackObject( Object *victim, Int maxShotsToFire, CommandSourceType cmdSource ); ///< attack given object @@ -338,7 +338,7 @@ class AIUpdateInterface : public UpdateModule, public AICommandInterface virtual Bool isBusy() const; virtual void onObjectCreated(); - virtual void doQuickExit( const std::vector* path ); ///< get out of this Object + virtual void doQuickExit( std::vector* path ); ///< get out of this Object virtual void aiDoCommand(const AICommandParms* parms); diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/JetAIUpdate.h b/Generals/Code/GameEngine/Include/GameLogic/Module/JetAIUpdate.h index cc6f8c4e72..3c8579ebf1 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/JetAIUpdate.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/JetAIUpdate.h @@ -104,7 +104,7 @@ class JetAIUpdate : public AIUpdateInterface Real friend_getMinHeight() const { return getJetAIUpdateModuleData()->m_minHeight; } Real friend_getParkingOffset() const { return getJetAIUpdateModuleData()->m_parkingOffset; } UnsignedInt friend_getTakeoffPause() const { return getJetAIUpdateModuleData()->m_takeoffPause; } - void friend_setGoalPath( const std::vector* path ) { getStateMachine()->setGoalPath(path); } + void friend_setGoalPath( std::vector* path ) { getStateMachine()->setGoalPath(path); } void friend_setTakeoffInProgress(Bool v) { setFlag(TAKEOFF_IN_PROGRESS, v); } void friend_setLandingInProgress(Bool v) { setFlag(LANDING_IN_PROGRESS, v); } void friend_setTaxiInProgress(Bool v) { setFlag(TAXI_IN_PROGRESS, v); } @@ -122,7 +122,7 @@ class JetAIUpdate : public AIUpdateInterface virtual AIStateMachine* makeStateMachine(); - virtual void privateFollowPath( const std::vector* path, Object *ignoreObject, CommandSourceType cmdSource, Bool exitProduction );///< follow the path defined by the given array of points + virtual void privateFollowPath( std::vector* path, Object *ignoreObject, CommandSourceType cmdSource, Bool exitProduction );///< follow the path defined by the given array of points virtual void privateFollowPathAppend( const Coord3D *pos, CommandSourceType cmdSource ); virtual void privateEnter( Object *obj, CommandSourceType cmdSource ); ///< enter the given object virtual void privateGetRepaired( Object *repairDepot, CommandSourceType cmdSource );///< get repaired at repair depot diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp index 9207bb5f34..e27d1e08fd 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp @@ -816,9 +816,9 @@ void AIStateMachine::loadPostProcess( void ) /** * Define a simple path */ -void AIStateMachine::setGoalPath( const std::vector* path ) +void AIStateMachine::setGoalPath( std::vector* path ) { - m_goalPath = *path; + stl::move_or_swap(m_goalPath, *path); } #ifdef STATE_MACHINE_DEBUG diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp index 67cedc7f37..2f09a4ff27 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp @@ -2619,14 +2619,20 @@ void AIUpdateInterface::aiDoCommand(const AICommandParms* parms) privateFollowWaypointPathAsTeamExact(parms->m_waypoint, parms->m_cmdSource); break; case AICMD_FOLLOW_PATH: - privateFollowPath(&parms->m_coords, parms->m_obj, parms->m_cmdSource, FALSE); + { + std::vector coords = parms->m_coords; + privateFollowPath(&coords, parms->m_obj, parms->m_cmdSource, FALSE); break; + } case AICMD_FOLLOW_PATH_APPEND: privateFollowPathAppend(&parms->m_pos, parms->m_cmdSource); break; case AICMD_FOLLOW_EXITPRODUCTION_PATH: - privateFollowPath(&parms->m_coords, parms->m_obj, parms->m_cmdSource, TRUE); + { + std::vector coords = parms->m_coords; + privateFollowPath(&coords, parms->m_obj, parms->m_cmdSource, TRUE); break; + } case AICMD_ATTACK_OBJECT: privateAttackObject(parms->m_obj, parms->m_intValue, parms->m_cmdSource); break; @@ -3240,7 +3246,7 @@ void AIUpdateInterface::privateFollowPathAppend( const Coord3D *pos, CommandSour /** * Follow the path defined by the given array of points */ -void AIUpdateInterface::privateFollowPath( const std::vector* path, Object *ignoreObject, CommandSourceType cmdSource, Bool exitProduction ) +void AIUpdateInterface::privateFollowPath( std::vector* path, Object *ignoreObject, CommandSourceType cmdSource, Bool exitProduction ) { if (getObject()->isMobile() == FALSE) return; @@ -3681,7 +3687,7 @@ void AIUpdateInterface::privateExit( Object *objectToExit, CommandSourceType cmd /** * Get out of whatever it is inside of */ -void AIUpdateInterface::doQuickExit( const std::vector* path ) +void AIUpdateInterface::doQuickExit( std::vector* path ) { Bool locked = getStateMachine()->isLocked(); 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 f264228618..1ce63cffc5 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp @@ -2172,7 +2172,7 @@ Bool JetAIUpdate::getTreatAsAircraftForLocoDistToGoal() const /** * Follow the path defined by the given array of points */ -void JetAIUpdate::privateFollowPath( const std::vector* path, Object *ignoreObject, CommandSourceType cmdSource, Bool exitProduction ) +void JetAIUpdate::privateFollowPath( std::vector* path, Object *ignoreObject, CommandSourceType cmdSource, Bool exitProduction ) { if (exitProduction) { diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h index 23cf4f94f8..fc4a0be12d 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h @@ -550,18 +550,18 @@ class AICommandInterface aiDoCommand(&parms); } - void aiFollowExitProductionPath( const std::vector* path, Object *ignoreObject, CommandSourceType cmdSource ) + void aiFollowExitProductionPath( std::vector* path, Object *ignoreObject, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_FOLLOW_EXITPRODUCTION_PATH, cmdSource); - parms.m_coords = *path; + stl::move_or_swap(parms.m_coords, *path); parms.m_obj = ignoreObject; aiDoCommand(&parms); } - void aiFollowPath( const std::vector* path, Object *ignoreObject, CommandSourceType cmdSource ) + void aiFollowPath( std::vector* path, Object *ignoreObject, CommandSourceType cmdSource ) { AICommandParms parms(AICMD_FOLLOW_PATH, cmdSource); - parms.m_coords = *path; + stl::move_or_swap(parms.m_coords, *path); parms.m_obj = ignoreObject; aiDoCommand(&parms); } diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIStateMachine.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIStateMachine.h index 3171df36bc..8d96e65997 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIStateMachine.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIStateMachine.h @@ -141,7 +141,7 @@ class AIStateMachine : public StateMachine virtual StateReturnType setState( StateID newStateID ); /// @todo Rethink state parameter passing. Continuing in this fashion will have a pile of params in the machine (MSB) - void setGoalPath( const std::vector* path ); + void setGoalPath( std::vector* path ); void addToGoalPath( const Coord3D *pathPoint ); const Coord3D *getGoalPathPosition( Int i ) const; ///< return path position at index "i" Int getGoalPathSize() const { return m_goalPath.size(); } diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h index 423977192c..32e562d23a 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h @@ -249,7 +249,7 @@ class AIUpdateInterface : public UpdateModule, public AICommandInterface virtual void privateFollowWaypointPathAsTeam( const Waypoint *way, CommandSourceType cmdSource );///< start following the path from the given point virtual void privateFollowWaypointPathExact( const Waypoint *way, CommandSourceType cmdSource );///< start following the path from the given point virtual void privateFollowWaypointPathAsTeamExact( const Waypoint *way, CommandSourceType cmdSource );///< start following the path from the given point - virtual void privateFollowPath( const std::vector* path, Object *ignoreObject, CommandSourceType cmdSource, Bool exitProduction );///< follow the path defined by the given array of points + virtual void privateFollowPath( std::vector* path, Object *ignoreObject, CommandSourceType cmdSource, Bool exitProduction );///< follow the path defined by the given array of points virtual void privateFollowPathAppend( const Coord3D *pos, CommandSourceType cmdSource ); virtual void privateAttackObject( Object *victim, Int maxShotsToFire, CommandSourceType cmdSource ); ///< attack given object virtual void privateForceAttackObject( Object *victim, Int maxShotsToFire, CommandSourceType cmdSource ); ///< attack given object @@ -351,7 +351,7 @@ class AIUpdateInterface : public UpdateModule, public AICommandInterface virtual Bool isBusy() const; virtual void onObjectCreated(); - virtual void doQuickExit( const std::vector* path ); ///< get out of this Object + virtual void doQuickExit( std::vector* path ); ///< get out of this Object virtual void aiDoCommand(const AICommandParms* parms); diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/JetAIUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/JetAIUpdate.h index 1840d30a4b..a7cd1157aa 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/JetAIUpdate.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/JetAIUpdate.h @@ -110,7 +110,7 @@ class JetAIUpdate : public AIUpdateInterface Real friend_getMinHeight() const { return getJetAIUpdateModuleData()->m_minHeight; } Real friend_getParkingOffset() const { return getJetAIUpdateModuleData()->m_parkingOffset; } UnsignedInt friend_getTakeoffPause() const { return getJetAIUpdateModuleData()->m_takeoffPause; } - void friend_setGoalPath( const std::vector* path ) { getStateMachine()->setGoalPath(path); } + void friend_setGoalPath( std::vector* path ) { getStateMachine()->setGoalPath(path); } void friend_setTakeoffInProgress(Bool v) { setFlag(TAKEOFF_IN_PROGRESS, v); } void friend_setLandingInProgress(Bool v) { setFlag(LANDING_IN_PROGRESS, v); } void friend_setTaxiInProgress(Bool v) { setFlag(TAXI_IN_PROGRESS, v); } @@ -131,7 +131,7 @@ class JetAIUpdate : public AIUpdateInterface virtual AIStateMachine* makeStateMachine(); - virtual void privateFollowPath( const std::vector* path, Object *ignoreObject, CommandSourceType cmdSource, Bool exitProduction );///< follow the path defined by the given array of points + virtual void privateFollowPath( std::vector* path, Object *ignoreObject, CommandSourceType cmdSource, Bool exitProduction );///< follow the path defined by the given array of points virtual void privateFollowPathAppend( const Coord3D *pos, CommandSourceType cmdSource ); virtual void privateEnter( Object *obj, CommandSourceType cmdSource ); ///< enter the given object virtual void privateGetRepaired( Object *repairDepot, CommandSourceType cmdSource );///< get repaired at repair depot diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp index c2468cbfcd..019025d012 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp @@ -821,9 +821,9 @@ void AIStateMachine::loadPostProcess( void ) /** * Define a simple path */ -void AIStateMachine::setGoalPath( const std::vector* path ) +void AIStateMachine::setGoalPath( std::vector* path ) { - m_goalPath = *path; + stl::move_or_swap(m_goalPath, *path); } #ifdef STATE_MACHINE_DEBUG diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp index 7bc310b7d6..821a56e7eb 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp @@ -2681,14 +2681,20 @@ void AIUpdateInterface::aiDoCommand(const AICommandParms* parms) privateFollowWaypointPathAsTeamExact(parms->m_waypoint, parms->m_cmdSource); break; case AICMD_FOLLOW_PATH: - privateFollowPath(&parms->m_coords, parms->m_obj, parms->m_cmdSource, FALSE); + { + std::vector coords = parms->m_coords; + privateFollowPath(&coords, parms->m_obj, parms->m_cmdSource, FALSE); break; + } case AICMD_FOLLOW_PATH_APPEND: privateFollowPathAppend(&parms->m_pos, parms->m_cmdSource); break; case AICMD_FOLLOW_EXITPRODUCTION_PATH: - privateFollowPath(&parms->m_coords, parms->m_obj, parms->m_cmdSource, TRUE); + { + std::vector coords = parms->m_coords; + privateFollowPath(&coords, parms->m_obj, parms->m_cmdSource, TRUE); break; + } case AICMD_ATTACK_OBJECT: privateAttackObject(parms->m_obj, parms->m_intValue, parms->m_cmdSource); break; @@ -3377,7 +3383,7 @@ void AIUpdateInterface::privateFollowPathAppend( const Coord3D *pos, CommandSour /** * Follow the path defined by the given array of points */ -void AIUpdateInterface::privateFollowPath( const std::vector* path, Object *ignoreObject, CommandSourceType cmdSource, Bool exitProduction ) +void AIUpdateInterface::privateFollowPath( std::vector* path, Object *ignoreObject, CommandSourceType cmdSource, Bool exitProduction ) { if (getObject()->isMobile() == FALSE) return; @@ -3869,7 +3875,7 @@ void AIUpdateInterface::privateExitInstantly( Object *objectToExit, CommandSourc /** * Get out of whatever it is inside of */ -void AIUpdateInterface::doQuickExit( const std::vector* path ) +void AIUpdateInterface::doQuickExit( std::vector* path ) { Bool locked = getStateMachine()->isLocked(); 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 4e3b24a426..dc2a4162b7 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp @@ -2399,7 +2399,7 @@ Bool JetAIUpdate::getTreatAsAircraftForLocoDistToGoal() const /** * Follow the path defined by the given array of points */ -void JetAIUpdate::privateFollowPath( const std::vector* path, Object *ignoreObject, CommandSourceType cmdSource, Bool exitProduction ) +void JetAIUpdate::privateFollowPath( std::vector* path, Object *ignoreObject, CommandSourceType cmdSource, Bool exitProduction ) { if (exitProduction) { From 8cbcd7874ac52986e326399888626098abedd778 Mon Sep 17 00:00:00 2001 From: xezon <4720891+xezon@users.noreply.github.com> Date: Sun, 4 Jan 2026 11:01:45 +0100 Subject: [PATCH 68/70] tweak(drawable): Decouple stealth detected opacity fade time step from render update (#2047) --- .../GameEngine/Source/GameClient/Drawable.cpp | 22 ++++++++++---- .../GameEngine/Source/GameClient/Drawable.cpp | 30 +++++++++++++------ 2 files changed, 37 insertions(+), 15 deletions(-) diff --git a/Generals/Code/GameEngine/Source/GameClient/Drawable.cpp b/Generals/Code/GameEngine/Source/GameClient/Drawable.cpp index b7284e0c45..4d322225af 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Drawable.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Drawable.cpp @@ -2163,15 +2163,25 @@ void Drawable::setStealthLook(StealthLookType look) //------------------------------------------------------------------------------------------------- void Drawable::draw() { - if ( getObject() && getObject()->isEffectivelyDead() ) - m_heatVisionOpacity = 0.0f;//dead folks don't stealth anyway - else if ( m_heatVisionOpacity > VERY_TRANSPARENT_HEATVISION )// keep fading any heatvision unless something has set it to zero - m_heatVisionOpacity *= HEATVISION_FADE_SCALAR; - else + { + //dead folks don't stealth anyway m_heatVisionOpacity = 0.0f; + } + else if ( m_heatVisionOpacity > VERY_TRANSPARENT_HEATVISION ) + { + // keep fading any added material unless something has set it to zero + // TheSuperHackers @tweak The stealth opacity fade time step is now decoupled from the render update. + static_assert(HEATVISION_FADE_SCALAR > 0.0f && HEATVISION_FADE_SCALAR < 1.0f, "HEATVISION_FADE_SCALAR must be between 0 and 1"); - + const Real timeScale = TheFramePacer->getActualLogicTimeScaleOverFpsRatio(); + const Real fadeScalar = 1.0f - (1.0f - HEATVISION_FADE_SCALAR) * timeScale; + m_heatVisionOpacity *= fadeScalar; + } + else + { + m_heatVisionOpacity = 0.0f; + } if (m_hidden || m_hiddenByStealth || getFullyObscuredByShroud()) return; // my, that was easy diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp index f5dd995db0..5071dcfa29 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp @@ -2607,16 +2607,28 @@ void Drawable::setStealthLook(StealthLookType look) //------------------------------------------------------------------------------------------------- void Drawable::draw() { - if ( testTintStatus( TINT_STATUS_FRENZY ) == FALSE ) - { - if ( getObject() && getObject()->isEffectivelyDead() ) - m_secondMaterialPassOpacity = 0.0f;//dead folks don't stealth anyway - else if ( m_secondMaterialPassOpacity > VERY_TRANSPARENT_MATERIAL_PASS_OPACITY )// keep fading any add'l material unless something has set it to zero - m_secondMaterialPassOpacity *= MATERIAL_PASS_OPACITY_FADE_SCALAR; - else - m_secondMaterialPassOpacity = 0.0f; - } + if ( testTintStatus( TINT_STATUS_FRENZY ) == FALSE ) + { + if ( getObject() && getObject()->isEffectivelyDead() ) + { + //dead folks don't stealth anyway + m_secondMaterialPassOpacity = 0.0f; + } + else if ( m_secondMaterialPassOpacity > VERY_TRANSPARENT_MATERIAL_PASS_OPACITY ) + { + // keep fading any added material unless something has set it to zero + // TheSuperHackers @tweak The stealth opacity fade time step is now decoupled from the render update. + static_assert(MATERIAL_PASS_OPACITY_FADE_SCALAR > 0.0f && MATERIAL_PASS_OPACITY_FADE_SCALAR < 1.0f, "MATERIAL_PASS_OPACITY_FADE_SCALAR must be between 0 and 1"); + const Real timeScale = TheFramePacer->getActualLogicTimeScaleOverFpsRatio(); + const Real fadeScalar = 1.0f - (1.0f - MATERIAL_PASS_OPACITY_FADE_SCALAR) * timeScale; + m_secondMaterialPassOpacity *= fadeScalar; + } + else + { + m_secondMaterialPassOpacity = 0.0f; + } + } if (m_hidden || m_hiddenByStealth || getFullyObscuredByShroud()) return; // my, that was easy From 20adf33d4594bdd18e4d776a83f9d0e68cd81119 Mon Sep 17 00:00:00 2001 From: Stubbjax Date: Sun, 4 Jan 2026 21:33:21 +1100 Subject: [PATCH 69/70] bugfix(audio): UI audio no longer plays at maximum volume for a single frame when navigating between shell map menus (#2019) --- .../Source/MilesAudioDevice/MilesAudioManager.cpp | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/Core/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp b/Core/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp index 5a47735ca7..53b4480aef 100644 --- a/Core/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp +++ b/Core/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp @@ -2107,9 +2107,8 @@ void MilesAudioManager::adjustVolumeOfPlayingAudio(AsciiString eventName, Real n if (playing && playing->m_audioEventRTS->getEventName() == eventName) { // Adjust it playing->m_audioEventRTS->setVolume(newVolume); - Real desiredVolume = playing->m_audioEventRTS->getVolume() * playing->m_audioEventRTS->getVolumeShift(); AIL_sample_volume_pan(playing->m_sample, NULL, &pan); - AIL_set_sample_volume_pan(playing->m_sample, desiredVolume, pan); + AIL_set_sample_volume_pan(playing->m_sample, getEffectiveVolume(playing->m_audioEventRTS), pan); } } @@ -2118,8 +2117,7 @@ void MilesAudioManager::adjustVolumeOfPlayingAudio(AsciiString eventName, Real n if (playing && playing->m_audioEventRTS->getEventName() == eventName) { // Adjust it playing->m_audioEventRTS->setVolume(newVolume); - Real desiredVolume = playing->m_audioEventRTS->getVolume() * playing->m_audioEventRTS->getVolumeShift(); - AIL_set_3D_sample_volume(playing->m_3DSample, desiredVolume); + AIL_set_3D_sample_volume(playing->m_3DSample, getEffectiveVolume(playing->m_audioEventRTS)); } } @@ -2128,9 +2126,8 @@ void MilesAudioManager::adjustVolumeOfPlayingAudio(AsciiString eventName, Real n if (playing && playing->m_audioEventRTS->getEventName() == eventName) { // Adjust it playing->m_audioEventRTS->setVolume(newVolume); - Real desiredVolume = playing->m_audioEventRTS->getVolume() * playing->m_audioEventRTS->getVolumeShift(); AIL_stream_volume_pan(playing->m_stream, NULL, &pan); - AIL_set_stream_volume_pan(playing->m_stream, desiredVolume, pan); + AIL_set_stream_volume_pan(playing->m_stream, getEffectiveVolume(playing->m_audioEventRTS), pan); } } } From 3eea7151eef2380b1d5f7dd96fe2231885d3d4bd Mon Sep 17 00:00:00 2001 From: Stubbjax Date: Sun, 4 Jan 2026 21:49:14 +1100 Subject: [PATCH 70/70] bugfix(object): Do not apply veterancy bonuses and animations for dead units (#1968) --- .../GameEngine/Include/GameLogic/Object.h | 1 + .../Source/GameLogic/Object/Object.cpp | 20 +++++++++++++++++-- .../GameEngine/Include/GameLogic/Object.h | 1 + .../Source/GameLogic/Object/Object.cpp | 20 +++++++++++++++++-- 4 files changed, 38 insertions(+), 4 deletions(-) diff --git a/Generals/Code/GameEngine/Include/GameLogic/Object.h b/Generals/Code/GameEngine/Include/GameLogic/Object.h index 9f0f0869b3..48dd754520 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Object.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Object.h @@ -213,6 +213,7 @@ class Object : public Thing, public Snapshot 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 + void createVeterancyLevelFX(VeterancyLevel oldLevel, VeterancyLevel newLevel); ExperienceTracker* getExperienceTracker() {return m_experienceTracker;} const ExperienceTracker* getExperienceTracker() const {return m_experienceTracker;} VeterancyLevel getVeterancyLevel() const; diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp index 7634db8058..c426213d17 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp @@ -2802,6 +2802,12 @@ Bool Object::hasSpecialPower( SpecialPowerType type ) const //------------------------------------------------------------------------------------------------- void Object::onVeterancyLevelChanged( VeterancyLevel oldLevel, VeterancyLevel newLevel, Bool provideFeedback ) { +#if !RETAIL_COMPATIBLE_CRC + // TheSuperHackers @bugfix Stubbjax 10/12/2025 Do not apply veterancy bonuses and animations for dead units. + if (isEffectivelyDead()) + return; +#endif + updateUpgradeModules(); const UpgradeTemplate* up = TheUpgradeCenter->findVeterancyUpgrade(newLevel); @@ -2853,7 +2859,18 @@ void Object::onVeterancyLevelChanged( VeterancyLevel oldLevel, VeterancyLevel ne && !isKindOf(KINDOF_IGNORED_IN_GUI) && isLogicallyVisible(); - if( doAnimation && TheGameLogic->getDrawIconUI() ) + if (doAnimation) + createVeterancyLevelFX(oldLevel, newLevel); +} + +void Object::createVeterancyLevelFX(VeterancyLevel oldLevel, VeterancyLevel newLevel) +{ +#if RETAIL_COMPATIBLE_CRC + if (isEffectivelyDead()) + return; +#endif + + if (TheGameLogic->getDrawIconUI()) { if( TheAnim2DCollection && TheGlobalData->m_levelGainAnimationName.isEmpty() == FALSE ) { @@ -2873,7 +2890,6 @@ void Object::onVeterancyLevelChanged( VeterancyLevel oldLevel, VeterancyLevel ne soundToPlay.setObjectID( getID() ); TheAudio->addAudioEvent( &soundToPlay ); } - } //------------------------------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h index 9c601848f6..01d2d26af7 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h @@ -229,6 +229,7 @@ class Object : public Thing, public Snapshot 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 + void createVeterancyLevelFX(VeterancyLevel oldLevel, VeterancyLevel newLevel); ExperienceTracker* getExperienceTracker() {return m_experienceTracker;} const ExperienceTracker* getExperienceTracker() const {return m_experienceTracker;} VeterancyLevel getVeterancyLevel() const; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp index 7052147358..7505e85e37 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp @@ -3118,6 +3118,12 @@ Bool Object::hasAnySpecialPower() const //------------------------------------------------------------------------------------------------- void Object::onVeterancyLevelChanged( VeterancyLevel oldLevel, VeterancyLevel newLevel, Bool provideFeedback ) { +#if !RETAIL_COMPATIBLE_CRC + // TheSuperHackers @bugfix Stubbjax 10/12/2025 Do not apply veterancy bonuses and animations for dead units. + if (isEffectivelyDead()) + return; +#endif + updateUpgradeModules(); const UpgradeTemplate* up = TheUpgradeCenter->findVeterancyUpgrade(newLevel); @@ -3169,7 +3175,18 @@ void Object::onVeterancyLevelChanged( VeterancyLevel oldLevel, VeterancyLevel ne && !isKindOf(KINDOF_IGNORED_IN_GUI) && isLogicallyVisible(); - if( doAnimation && TheGameLogic->getDrawIconUI() ) + if (doAnimation) + createVeterancyLevelFX(oldLevel, newLevel); +} + +void Object::createVeterancyLevelFX(VeterancyLevel oldLevel, VeterancyLevel newLevel) +{ +#if RETAIL_COMPATIBLE_CRC + if (isEffectivelyDead()) + return; +#endif + + if (TheGameLogic->getDrawIconUI()) { if( TheAnim2DCollection && TheGlobalData->m_levelGainAnimationName.isEmpty() == FALSE ) { @@ -3189,7 +3206,6 @@ void Object::onVeterancyLevelChanged( VeterancyLevel oldLevel, VeterancyLevel ne soundToPlay.setObjectID( getID() ); TheAudio->addAudioEvent( &soundToPlay ); } - } //-------------------------------------------------------------------------------------------------