From c0ed95065735f6b7b6e6bc4ae5bb8a522a602490 Mon Sep 17 00:00:00 2001 From: janwas Date: Sun, 11 May 2008 18:48:32 +0000 Subject: [PATCH] had to remove uint and ulong from lib/types.h due to conflict with other library. this snowballed into a massive search+destroy of the hodgepodge of mostly equivalent types we had in use (int, uint, unsigned, unsigned int, i32, u32, ulong, uintN). it is more efficient to use 64-bit types in 64-bit mode, so the preferred default is size_t (for anything remotely resembling a size or index). tile coordinates are ssize_t to allow more efficient conversion to/from floating point. flags are int because we almost never need more than 15 distinct bits, bit test/set is not slower and int is fastest to type. finally, some data that is pretty much directly passed to OpenGL is now typed accordingly. after several hours, the code now requires fewer casts and less guesswork. other changes: - unit and player IDs now have an "invalid id" constant in the respective class to avoid casting and -1 - fix some endian/64-bit bugs in the map (un)packing. added a convenience function to write/read a size_t. - ia32: change CPUID interface to allow passing in ecx (required for cache topology detection, which I need at work). remove some unneeded functions from asm, replace with intrinsics where possible. This was SVN commit r5942. --- source/graphics/Camera.cpp | 4 +- source/graphics/Camera.h | 10 +- source/graphics/Frustum.cpp | 12 +- source/graphics/Frustum.h | 10 +- source/graphics/GameView.cpp | 20 +- source/graphics/HFTracer.h | 2 +- source/graphics/MapReader.cpp | 28 +-- source/graphics/MapReader.h | 6 +- source/graphics/MapWriter.cpp | 27 +- source/graphics/Material.cpp | 12 +- source/graphics/Material.h | 24 +- source/graphics/MiniPatch.cpp | 4 +- source/graphics/MiniPatch.h | 2 +- source/graphics/Model.cpp | 12 +- source/graphics/Model.h | 10 +- source/graphics/ModelDef.cpp | 37 +-- source/graphics/ModelDef.h | 10 +- source/graphics/ObjectBase.cpp | 2 +- source/graphics/ObjectEntry.cpp | 2 +- source/graphics/ParticleEmitter.h | 2 +- source/graphics/ParticleEngine.cpp | 2 +- source/graphics/Patch.cpp | 10 +- source/graphics/Patch.h | 6 +- source/graphics/RenderableObject.h | 2 +- source/graphics/SkeletonAnimDef.cpp | 22 +- source/graphics/SkeletonAnimDef.h | 8 +- source/graphics/Terrain.cpp | 105 ++++---- source/graphics/Terrain.h | 44 ++-- source/graphics/TextureEntry.h | 2 +- source/graphics/TextureManager.cpp | 4 +- source/graphics/TextureManager.h | 8 +- source/graphics/Unit.cpp | 7 +- source/graphics/Unit.h | 17 +- source/graphics/UnitManager.cpp | 9 +- source/graphics/UnitManager.h | 8 +- .../graphics/scripting/JSInterface_Camera.cpp | 2 +- .../graphics/scripting/JSInterface_Camera.h | 6 +- source/gui/GUIRenderer.cpp | 6 +- source/gui/MiniMap.cpp | 39 ++- source/gui/MiniMap.h | 16 +- source/gui/scripting/JSInterface_GUITypes.cpp | 6 +- source/gui/scripting/JSInterface_GUITypes.h | 6 +- .../gui/scripting/JSInterface_IGUIObject.cpp | 4 +- source/gui/scripting/JSInterface_IGUIObject.h | 6 +- source/lib/adts.h | 19 +- source/lib/allocators/allocators.cpp | 4 +- source/lib/allocators/allocators.h | 2 +- source/lib/allocators/bucket.h | 2 +- source/lib/allocators/headerless.cpp | 16 +- source/lib/allocators/string_pool.cpp | 2 +- source/lib/app_hooks.cpp | 4 +- source/lib/app_hooks.h | 4 +- source/lib/base32.cpp | 4 +- source/lib/bits.cpp | 45 ---- source/lib/bits.h | 74 +++--- source/lib/byte_order.cpp | 4 +- source/lib/cache_adt.h | 6 +- source/lib/config2.h | 7 - source/lib/debug.cpp | 22 +- source/lib/debug.h | 8 +- source/lib/debug_stl.cpp | 2 +- source/lib/fat_time.cpp | 4 +- source/lib/file/archive/archive_builder.cpp | 6 +- source/lib/file/archive/archive_zip.cpp | 22 +- source/lib/file/common/file_loader.h | 2 +- source/lib/file/common/file_stats.cpp | 22 +- source/lib/file/common/real_directory.cpp | 4 +- source/lib/file/common/real_directory.h | 12 +- .../lib/file/disabled_tests/test_file_cache.h | 2 +- source/lib/file/file_system_util.cpp | 8 +- source/lib/file/file_system_util.h | 6 +- source/lib/file/io/io.cpp | 2 +- source/lib/file/io/write_buffer.cpp | 2 +- source/lib/file/vfs/file_cache.cpp | 4 +- source/lib/file/vfs/file_cache.h | 2 +- source/lib/file/vfs/vfs.cpp | 2 +- source/lib/file/vfs/vfs.h | 2 +- source/lib/file/vfs/vfs_lookup.cpp | 4 +- source/lib/file/vfs/vfs_lookup.h | 2 +- source/lib/file/vfs/vfs_tree.cpp | 8 +- source/lib/file/vfs/vfs_tree.h | 4 +- source/lib/input.cpp | 4 +- source/lib/lib.cpp | 2 +- source/lib/lib.h | 6 +- source/lib/lockfree.cpp | 4 +- source/lib/lockfree.h | 2 +- source/lib/path_util.cpp | 2 +- source/lib/path_util.h | 2 +- source/lib/posix/posix.cpp | 4 +- source/lib/posix/posix.h | 4 +- source/lib/rand.cpp | 20 +- source/lib/rand.h | 2 +- source/lib/res/graphics/cursor.cpp | 19 +- source/lib/res/graphics/ogl_tex.cpp | 56 ++--- source/lib/res/graphics/ogl_tex.h | 20 +- source/lib/res/graphics/tests/test_tex.h | 10 +- source/lib/res/graphics/unifont.cpp | 4 +- source/lib/res/graphics/unifont.h | 2 +- source/lib/res/h_mgr.cpp | 60 ++--- source/lib/res/h_mgr.h | 4 +- source/lib/res/sound/snd_mgr.cpp | 28 +-- source/lib/res/sound/snd_mgr.h | 2 +- source/lib/self_test.h | 2 +- source/lib/sysdep/amd64/amd64.cpp | 4 +- source/lib/sysdep/amd64/amd64_asm.h | 25 ++ source/lib/sysdep/cpu.h | 8 +- source/lib/sysdep/cursor.h | 3 +- source/lib/sysdep/ia32/ia32.cpp | 237 ++++++++++-------- source/lib/sysdep/ia32/ia32.h | 41 +-- source/lib/sysdep/ia32/ia32_asm.asm | 94 +------ source/lib/sysdep/ia32/ia32_asm.h | 40 +-- source/lib/sysdep/linux/lcpu.cpp | 4 +- source/lib/sysdep/linux/ldbg.cpp | 18 +- source/lib/sysdep/osx/ocpu.cpp | 2 +- source/lib/sysdep/osx/odbg.cpp | 4 +- source/lib/sysdep/stl.h | 2 +- source/lib/sysdep/sysdep.h | 2 +- source/lib/sysdep/unix/udbg.cpp | 4 +- source/lib/sysdep/unix/unix.cpp | 6 +- source/lib/sysdep/win/tests/test_wdbg_sym.h | 6 +- source/lib/sysdep/win/wcpu.cpp | 4 +- source/lib/sysdep/win/wcursor.cpp | 6 +- source/lib/sysdep/win/wdbg_heap.cpp | 48 ++-- source/lib/sysdep/win/wdbg_sym.cpp | 23 +- source/lib/sysdep/win/wdbg_sym.h | 2 +- source/lib/sysdep/win/wdll_ver.cpp | 4 +- source/lib/sysdep/win/whrt/counter.cpp | 4 +- source/lib/sysdep/win/whrt/counter.h | 4 +- source/lib/sysdep/win/whrt/hpet.cpp | 6 +- source/lib/sysdep/win/whrt/hpet.h | 2 +- source/lib/sysdep/win/whrt/pmt.cpp | 4 +- source/lib/sysdep/win/whrt/pmt.h | 2 +- source/lib/sysdep/win/whrt/qpc.cpp | 2 +- source/lib/sysdep/win/whrt/qpc.h | 2 +- source/lib/sysdep/win/whrt/tgt.cpp | 2 +- source/lib/sysdep/win/whrt/tgt.h | 2 +- source/lib/sysdep/win/whrt/tsc.cpp | 16 +- source/lib/sysdep/win/whrt/tsc.h | 2 +- source/lib/sysdep/win/whrt/whrt.cpp | 8 +- source/lib/sysdep/win/wposix/waio.cpp | 4 +- source/lib/sysdep/win/wposix/wposix.h | 2 +- source/lib/sysdep/win/wposix/wpthread.cpp | 8 +- source/lib/sysdep/win/wposix/wtime.cpp | 6 +- source/lib/sysdep/win/wposix/wtime.h | 2 +- source/lib/sysdep/win/wsdl.cpp | 46 ++-- source/lib/sysdep/win/wseh.cpp | 4 +- source/lib/sysdep/win/wsysdep.cpp | 16 +- source/lib/sysdep/win/wutil.cpp | 6 +- source/lib/sysdep/win/wutil.h | 10 +- source/lib/tests/test_adts.h | 4 +- source/lib/tests/test_bits.h | 10 - source/lib/tests/test_cache_adt.h | 4 +- source/lib/tests/test_lockfree.h | 24 +- source/lib/tests/test_rand.h | 12 +- source/lib/tex/tex.cpp | 73 +++--- source/lib/tex/tex.h | 18 +- source/lib/tex/tex_bmp.cpp | 4 +- source/lib/tex/tex_codec.cpp | 6 +- source/lib/tex/tex_codec.h | 8 +- source/lib/tex/tex_dds.cpp | 112 ++++----- source/lib/tex/tex_internal.h | 4 +- source/lib/tex/tex_jpg.cpp | 4 +- source/lib/tex/tex_png.cpp | 4 +- source/lib/tex/tex_tga.cpp | 10 +- source/lib/timer.cpp | 2 +- source/lib/timer.h | 2 +- source/lib/types.h | 7 - source/main.cpp | 2 +- source/maths/Brush.cpp | 48 ++-- source/maths/Brush.h | 4 +- source/maths/MathUtil.h | 10 - source/network/Client.cpp | 8 +- source/network/NMTCreator.h | 10 +- source/network/NetLog.cpp | 27 +- source/network/NetLog.h | 6 +- source/network/NetMessage.cpp | 6 +- source/network/NetMessage.h | 6 +- source/network/Network.cpp | 6 +- source/network/Network.h | 4 +- source/network/NetworkInternal.h | 4 +- source/network/Serialization.h | 2 +- source/network/Server.cpp | 10 +- source/network/Server.h | 2 +- source/network/SocketBase.cpp | 16 +- source/network/SocketBase.h | 10 +- source/network/StreamSocket.cpp | 8 +- source/network/StreamSocket.h | 8 +- source/ps/CConsole.cpp | 8 +- source/ps/CConsole.h | 4 +- source/ps/CStr.cpp | 12 +- source/ps/CStr.h | 2 +- source/ps/ConfigDB.cpp | 10 +- source/ps/FileIo.cpp | 21 +- source/ps/FileIo.h | 15 +- source/ps/Game.cpp | 6 +- source/ps/Game.h | 8 +- source/ps/GameAttributes.cpp | 30 +-- source/ps/GameAttributes.h | 19 +- source/ps/GameSetup/GameSetup.cpp | 18 +- source/ps/GameSetup/GameSetup.h | 4 +- source/ps/Globals.cpp | 2 +- source/ps/Hotkey.cpp | 8 +- source/ps/Interact.cpp | 14 +- source/ps/Loader.h | 4 +- source/ps/Player.cpp | 6 +- source/ps/Player.h | 13 +- source/ps/ProfileViewer.cpp | 18 +- source/ps/ProfileViewer.h | 4 +- source/ps/Pyrogenesis.h | 1 - source/ps/Util.cpp | 10 +- source/ps/XML/Xeromyces.cpp | 8 +- source/ps/scripting/JSInterface_Console.cpp | 2 +- source/ps/scripting/JSInterface_Console.h | 2 +- source/ps/scripting/JSInterface_Selection.h | 2 +- source/ps/scripting/JSInterface_VFS.cpp | 2 +- source/renderer/BlendShapes.h | 4 +- .../renderer/FixedFunctionModelRenderer.cpp | 10 +- source/renderer/FixedFunctionModelRenderer.h | 10 +- source/renderer/HWLightingModelRenderer.cpp | 10 +- source/renderer/HWLightingModelRenderer.h | 10 +- source/renderer/InstancingModelRenderer.cpp | 10 +- source/renderer/InstancingModelRenderer.h | 10 +- source/renderer/ModelRenderer.cpp | 32 +-- source/renderer/ModelRenderer.h | 4 +- source/renderer/ModelVertexRenderer.h | 10 +- source/renderer/PatchRData.cpp | 153 ++++++----- source/renderer/PatchRData.h | 8 +- source/renderer/PlayerRenderer.cpp | 26 +- source/renderer/PlayerRenderer.h | 26 +- source/renderer/RenderModifiers.cpp | 34 +-- source/renderer/RenderModifiers.h | 40 +-- source/renderer/Renderer.cpp | 40 +-- source/renderer/Renderer.h | 2 +- source/renderer/Scene.cpp | 2 +- source/renderer/ShadowMap.cpp | 5 +- source/renderer/SkyManager.cpp | 6 +- source/renderer/SkyManager.h | 2 +- source/renderer/TerrainOverlay.cpp | 14 +- source/renderer/TerrainOverlay.h | 36 +-- source/renderer/TerrainRenderer.cpp | 18 +- source/renderer/TransparencyRenderer.cpp | 52 ++-- source/renderer/TransparencyRenderer.h | 46 ++-- source/renderer/VertexBuffer.cpp | 2 +- source/renderer/WaterManager.cpp | 19 +- source/renderer/WaterManager.h | 8 +- source/scripting/DOMEvent.cpp | 6 +- source/scripting/DOMEvent.h | 10 +- source/scripting/GameEvents.h | 6 +- source/scripting/JSConversions.cpp | 63 ++++- source/scripting/JSConversions.h | 18 +- source/scripting/JSSerialization.h | 2 +- source/scripting/ScriptCustomTypes.cpp | 2 +- source/scripting/ScriptCustomTypes.h | 2 +- source/scripting/ScriptGlue.cpp | 159 ++++++------ source/scripting/ScriptableComplex.cpp | 2 +- source/scripting/ScriptableComplex.inl | 2 +- source/scripting/ScriptableObject.h | 2 +- source/scripting/ScriptingHost.cpp | 3 +- source/scripting/SynchedJSObject.cpp | 6 +- source/scripting/SynchedJSObject.h | 2 +- source/simulation/Aura.cpp | 4 +- source/simulation/Aura.h | 8 +- source/simulation/Entity.cpp | 10 +- source/simulation/Entity.h | 53 ++-- source/simulation/EntityFormation.cpp | 40 +-- source/simulation/EntityFormation.h | 16 +- source/simulation/EntityHandles.cpp | 6 +- source/simulation/EntityHandles.h | 4 +- source/simulation/EntityManager.cpp | 4 +- source/simulation/EntityManager.h | 2 +- source/simulation/EntityScriptInterface.cpp | 6 +- source/simulation/EntityStateProcessing.cpp | 24 +- source/simulation/EntitySupport.h | 4 +- source/simulation/EntityTemplate.cpp | 8 +- .../simulation/EntityTemplateCollection.cpp | 6 +- source/simulation/EntityTemplateCollection.h | 2 +- source/simulation/Formation.cpp | 12 +- source/simulation/Formation.h | 14 +- source/simulation/FormationManager.cpp | 6 +- source/simulation/FormationManager.h | 8 +- source/simulation/LOSManager.cpp | 62 +++-- source/simulation/LOSManager.h | 24 +- source/simulation/ProductionQueue.cpp | 4 +- source/simulation/ProductionQueue.h | 4 +- source/simulation/Projectile.cpp | 10 +- source/simulation/Projectile.h | 10 +- source/simulation/Scheduler.cpp | 24 +- source/simulation/Scheduler.h | 34 +-- source/simulation/Simulation.cpp | 6 +- source/simulation/Simulation.h | 4 +- source/simulation/Technology.cpp | 4 +- source/simulation/Technology.h | 2 +- source/simulation/TechnologyCollection.cpp | 4 +- source/simulation/TerritoryManager.cpp | 16 +- source/simulation/TerritoryManager.h | 2 +- source/simulation/TriggerManager.cpp | 6 +- source/simulation/TriggerManager.h | 6 +- source/simulation/TurnManager.cpp | 26 +- source/simulation/TurnManager.h | 34 +-- source/sound/CPlayList.cpp | 2 +- source/sound/JSI_Sound.cpp | 2 +- source/sound/JSI_Sound.h | 2 +- source/sound/SoundGroup.cpp | 2 +- source/tools/atlas/GameInterface/Brushes.cpp | 18 +- source/tools/atlas/GameInterface/Brushes.h | 12 +- source/tools/atlas/GameInterface/DeltaArray.h | 18 +- source/tools/atlas/GameInterface/GameLoop.cpp | 2 +- .../Handlers/ElevationHandlers.cpp | 36 +-- .../Handlers/GraphicsSetupHandlers.cpp | 4 +- .../GameInterface/Handlers/MapHandlers.cpp | 2 +- .../GameInterface/Handlers/ObjectHandlers.cpp | 18 +- .../Handlers/TerrainHandlers.cpp | 30 +-- source/tools/atlas/GameInterface/Messages.h | 2 +- source/tools/atlas/GameInterface/Shareable.h | 9 + .../tools/atlas/GameInterface/SharedTypes.h | 4 +- source/tools/atlas/GameInterface/SimState.h | 6 +- 316 files changed, 2142 insertions(+), 2170 deletions(-) create mode 100644 source/lib/sysdep/amd64/amd64_asm.h diff --git a/source/graphics/Camera.cpp b/source/graphics/Camera.cpp index 83f350576e..d2ba721819 100644 --- a/source/graphics/Camera.cpp +++ b/source/graphics/Camera.cpp @@ -316,7 +316,7 @@ void CCamera::LookAlong( CVector3D camera, CVector3D orientation, CVector3D up ) /////////////////////////////////////////////////////////////////////////////////// // Render the camera's frustum -void CCamera::Render(uint intermediates) const +void CCamera::Render(int intermediates) const { CVector3D nearPoints[4]; CVector3D farPoints[4]; @@ -361,7 +361,7 @@ void CCamera::Render(uint intermediates) const // intermediate planes CVector3D intermediatePoints[4]; - for(uint i = 0; i < intermediates; ++i) + for(int i = 0; i < intermediates; ++i) { float t = (i+1.0)/(intermediates+1.0); diff --git a/source/graphics/Camera.h b/source/graphics/Camera.h index d7b26482c4..4423e06171 100644 --- a/source/graphics/Camera.h +++ b/source/graphics/Camera.h @@ -18,10 +18,10 @@ extern int g_mouse_x, g_mouse_y; // view port struct SViewPort { - unsigned int m_X; - unsigned int m_Y; - unsigned int m_Width; - unsigned int m_Height; + size_t m_X; + size_t m_Y; + size_t m_Width; + size_t m_Height; }; @@ -97,7 +97,7 @@ class CCamera * @param intermediates determines how many intermediate distance planes should * be hinted at between the near and far planes */ - void Render(uint intermediates = 0) const; + void Render(int intermediates = 0) const; public: // This is the orientation matrix. The inverse of this diff --git a/source/graphics/Frustum.cpp b/source/graphics/Frustum.cpp index dccd66b55c..1d165957d0 100644 --- a/source/graphics/Frustum.cpp +++ b/source/graphics/Frustum.cpp @@ -28,22 +28,20 @@ CFrustum::~CFrustum () { } -void CFrustum::SetNumPlanes (int num) +void CFrustum::SetNumPlanes (size_t num) { m_NumPlanes = num; //clip it if (m_NumPlanes >= MAX_NUM_FRUSTUM_PLANES) m_NumPlanes = MAX_NUM_FRUSTUM_PLANES-1; - else if (m_NumPlanes < 0) - m_NumPlanes = 0; } bool CFrustum::IsPointVisible (const CVector3D &point) const { PLANESIDE Side; - for (int i=0; i 0.0f) { diff --git a/source/graphics/Frustum.h b/source/graphics/Frustum.h index b9e8fb5b4f..ff3ee8cd9d 100644 --- a/source/graphics/Frustum.h +++ b/source/graphics/Frustum.h @@ -32,9 +32,9 @@ public: //Set the number of planes to use for //calculations. This is clipped to //[0,MAX_NUM_FRUSTUM_PLANES] - void SetNumPlanes (int num); + void SetNumPlanes (size_t num); - uint GetNumPlanes() const { return m_NumPlanes; } + size_t GetNumPlanes() const { return m_NumPlanes; } //The following methods return true if the shape is //partially or completely in front of the frustum planes @@ -43,15 +43,15 @@ public: bool IsSphereVisible (const CVector3D ¢er, float radius) const; bool IsBoxVisible (const CVector3D &position,const CBound &bounds) const; - CPlane& operator[](uint idx) { return m_aPlanes[idx]; } - const CPlane& operator[](uint idx) const { return m_aPlanes[idx]; } + CPlane& operator[](size_t idx) { return m_aPlanes[idx]; } + const CPlane& operator[](size_t idx) const { return m_aPlanes[idx]; } public: //make the planes public for ease of use CPlane m_aPlanes[MAX_NUM_FRUSTUM_PLANES]; private: - int m_NumPlanes; + size_t m_NumPlanes; }; #endif diff --git a/source/graphics/GameView.cpp b/source/graphics/GameView.cpp index 6f620d2422..6894e6d4f3 100644 --- a/source/graphics/GameView.cpp +++ b/source/graphics/GameView.cpp @@ -306,11 +306,11 @@ void CGameView::EnumerateObjects(const CFrustum& frustum, SceneCollector* c) { PROFILE_START( "submit terrain" ); CTerrain* pTerrain = m->Game->GetWorld()->GetTerrain(); - u32 patchesPerSide = pTerrain->GetPatchesPerSide(); + const ssize_t patchesPerSide = pTerrain->GetPatchesPerSide(); - // findout, which patches will be drawn - for (uint j=0; jGetPatch(i,j); // If the patch is underwater, calculate a bounding box that also contains the water plane @@ -357,9 +357,9 @@ void CGameView::EnumerateObjects(const CFrustum& frustum, SceneCollector* c) } // draw the patches - for (uint j=0; jGetPatch(i,j); if(patch->getDrawState() == true) @@ -378,7 +378,7 @@ void CGameView::EnumerateObjects(const CFrustum& frustum, SceneCollector* c) CLOSManager* losMgr = world->GetLOSManager(); const std::vector& units = unitMan.GetUnits(); - for (uint i=0;iSetDirty(RENDERDATA_UPDATE_COLOR); const std::vector& props = model->GetProps(); - for(uint i = 0; i < props.size(); ++i) { + for(size_t i = 0; i < props.size(); ++i) { MarkUpdateColorRecursive(props[i].m_Model); } } @@ -928,14 +928,14 @@ InReaction CGameView::HandleEvent(const SDL_Event_* ev) } bool CGameViewImpl::JSI_StartCustomSelection( - JSContext* UNUSED(context), uint UNUSED(argc), jsval* UNUSED(argv)) + JSContext* UNUSED(context), size_t UNUSED(argc), jsval* UNUSED(argv)) { StartCustomSelection(); return true; } bool CGameViewImpl::JSI_EndCustomSelection( - JSContext* UNUSED(context), uint UNUSED(argc), jsval* UNUSED(argv)) + JSContext* UNUSED(context), size_t UNUSED(argc), jsval* UNUSED(argv)) { ResetInteraction(); return true; diff --git a/source/graphics/HFTracer.h b/source/graphics/HFTracer.h index 7cf1d03610..b447f7c81a 100644 --- a/source/graphics/HFTracer.h +++ b/source/graphics/HFTracer.h @@ -39,7 +39,7 @@ private: // the heightfield were tracing const u16* m_Heightfield; // size of the heightfield - u32 m_MapSize; + size_t m_MapSize; // cell size - size of each cell in x and z float m_CellSize; // vertical scale - size of each cell in y diff --git a/source/graphics/MapReader.cpp b/source/graphics/MapReader.cpp index 2ac0563c1d..cdf2dd0724 100644 --- a/source/graphics/MapReader.cpp +++ b/source/graphics/MapReader.cpp @@ -113,16 +113,13 @@ void CMapReader::UnpackLightEnv() void CMapReader::UnpackObjects() { // unpack object types - u32 numObjTypes; - unpacker.UnpackRaw(&numObjTypes, sizeof(numObjTypes)); + const size_t numObjTypes = unpacker.UnpackSize(); m_ObjectTypes.resize(numObjTypes); - for (u32 i=0; iGetPatch(i,j)->m_MiniPatches[m][k]; mp.Tex1 = m_TerrainTextures[tileptr->m_Tex1Index]; diff --git a/source/graphics/MapReader.h b/source/graphics/MapReader.h index 15e01d115b..85ba1553fc 100644 --- a/source/graphics/MapReader.h +++ b/source/graphics/MapReader.h @@ -54,7 +54,7 @@ private: int DelayLoadFinished(); // size of map - u32 m_MapSize; + ssize_t m_MapSize; // heightmap for map std::vector m_Heightmap; // list of terrain textures used by map @@ -81,8 +81,8 @@ private: CStr filename_xml; // UnpackTerrain generator state - u32 cur_terrain_tex; - u32 num_terrain_tex; + size_t cur_terrain_tex; + size_t num_terrain_tex; CXMLReader* xml_reader; }; diff --git a/source/graphics/MapWriter.cpp b/source/graphics/MapWriter.cpp index 427934f876..aea6e2008c 100644 --- a/source/graphics/MapWriter.cpp +++ b/source/graphics/MapWriter.cpp @@ -59,8 +59,8 @@ void CMapWriter::SaveMap(const char* filename, CTerrain* pTerrain, // handle isn't in list static u16 GetHandleIndex(const Handle handle, const std::vector& handles) { - const uint limit = std::min((uint)handles.size(), 0xFFFEu); // paranoia - for (uint i=0;iGetPatchesPerSide(); - for (u32 j=0;jGetPatchesPerSide(); + for (ssize_t j=0;jGetPatch(i,j)->m_MiniPatches[m][k]; @@ -106,7 +106,7 @@ void CMapWriter::EnumTerrainTextures(CTerrain *pTerrain, } // now find the texture names for each handle - for (uint i=0;i<(uint)handles.size();i++) { + for (size_t i=0;iGetPatchesPerSide(); - packer.PackRaw(&mapsize,sizeof(mapsize)); + const ssize_t mapsize = pTerrain->GetPatchesPerSide(); + packer.PackSize(mapsize); // pack heightmap packer.PackRaw(pTerrain->GetHeightMap(),sizeof(u16)*SQR(pTerrain->GetVerticesPerSide())); @@ -148,14 +148,13 @@ void CMapWriter::PackTerrain(CFilePacker& packer, CTerrain* pTerrain) EnumTerrainTextures(pTerrain, terrainTextures, tiles); // pack texture names - u32 numTextures=(u32)terrainTextures.size(); - packer.PackRaw(&numTextures,sizeof(numTextures)); - for (uint i=0;im_Switch); } - for ( int j=(int)nodes.size()-1; j >= 0; --j ) + for ( size_t j=nodes.size()-1; j >= 0; --j ) { XML_Element("Node"); diff --git a/source/graphics/Material.cpp b/source/graphics/Material.cpp index abfd5faf9f..43f9ff923d 100644 --- a/source/graphics/Material.cpp +++ b/source/graphics/Material.cpp @@ -34,7 +34,7 @@ CMaterial::CMaterial() m_Emissive(IdentityEmissive), m_SpecularPower(0.0f), m_Alpha(false), - m_PlayerID(PLAYER_NONE), + m_PlayerID(PLAYER_ID_NONE), m_TextureColor(BrokenColor) { ComputeHash(); @@ -115,13 +115,13 @@ SMaterialColor CMaterial::GetEmissive() SMaterialColor CMaterial::GetPlayerColor() { - debug_assert(m_PlayerID != PLAYER_NONE); + debug_assert(m_PlayerID != PLAYER_ID_NONE); // because this should never be called unless IsPlayer returned true - if (m_PlayerID == PLAYER_OTHER /* TODO: or if player-colour is globally disabled */ ) + if (m_PlayerID == PLAYER_ID_OTHER /* TODO: or if player-colour is globally disabled */ ) return m_TextureColor; - if (m_PlayerID >= 0) + if (m_PlayerID <= PLAYER_ID_LAST_VALID) { CPlayer* player = g_Game->GetPlayer(m_PlayerID); if (player) @@ -135,9 +135,9 @@ SMaterialColor CMaterial::GetPlayerColor() return BrokenColor; } -void CMaterial::SetPlayerColor(int id) +void CMaterial::SetPlayerColor(size_t id) { - if (m_PlayerID == PLAYER_COMINGSOON || m_PlayerID >= 0) + if (m_PlayerID == PLAYER_ID_COMING_SOON || m_PlayerID <= PLAYER_ID_LAST_VALID) m_PlayerID = id; } diff --git a/source/graphics/Material.h b/source/graphics/Material.h index 9cd6011a5d..5badc30534 100644 --- a/source/graphics/Material.h +++ b/source/graphics/Material.h @@ -67,15 +67,15 @@ public: bool UsesAlpha() { return m_Alpha; } // Determines whether or not the model goes into the PlayerRenderer - bool IsPlayer() { return (m_PlayerID != PLAYER_NONE); } + bool IsPlayer() { return (m_PlayerID != PLAYER_ID_NONE); } // Get the player colour (in a non-zero amount of time, so don't call it // an unreasonable number of times. But it's fairly close to zero, so // don't worry too much about it.) SMaterialColor GetPlayerColor(); - void SetPlayerColor_PerPlayer() { m_PlayerID = PLAYER_COMINGSOON; } - void SetPlayerColor_PerObject() { m_PlayerID = PLAYER_OTHER; } - void SetPlayerColor(int id); + void SetPlayerColor_PerPlayer() { m_PlayerID = PLAYER_ID_COMING_SOON; } + void SetPlayerColor_PerObject() { m_PlayerID = PLAYER_ID_OTHER; } + void SetPlayerColor(size_t id); void SetPlayerColor(CColor &colour); void SetTexture(const CStr& texture); @@ -113,16 +113,20 @@ protected: bool m_Alpha; // Player-colour settings. - // If m_PlayerID >= 0, the colour is retrieved from g_Game whenever it's needed. + // If m_PlayerID <= PLAYER_ID_LAST_VALID, the colour is retrieved from + // g_Game whenever it's needed. // (It's not cached, because the player might change colour.) - // If m_PlayerID == PLAYER_OTHER, or if player-colouring has been globally + // If m_PlayerID == PLAYER_ID_OTHER, or if player-colouring has been globally // disabled, m_TextureColor is used instead. This allows per-model colours to // be specified, instead of only a single colour per player. - // If m_PlayerID == PLAYER_NONE, there's no player colour at all. - // If m_PlayerID == PLAYER_COMINGSOON, it's going to be linked to a player, + // If m_PlayerID == PLAYER_ID_NONE, there's no player colour at all. + // If m_PlayerID == PLAYER_ID_COMING_SOON, it's going to be linked to a player, // but hasn't yet. - enum { PLAYER_NONE = -1, PLAYER_OTHER = -2, PLAYER_COMINGSOON = -3 }; - int m_PlayerID; + static const size_t PLAYER_ID_NONE = SIZE_MAX-1; + static const size_t PLAYER_ID_OTHER = SIZE_MAX-2; + static const size_t PLAYER_ID_COMING_SOON = SIZE_MAX-3; + static const size_t PLAYER_ID_LAST_VALID = SIZE_MAX-4; + size_t m_PlayerID; SMaterialColor m_TextureColor; // used as an alternative to the per-player colour }; diff --git a/source/graphics/MiniPatch.cpp b/source/graphics/MiniPatch.cpp index 6972c5e9bc..db16d9680d 100644 --- a/source/graphics/MiniPatch.cpp +++ b/source/graphics/MiniPatch.cpp @@ -28,12 +28,10 @@ CMiniPatch::~CMiniPatch() /////////////////////////////////////////////////////////////////////////////// // GetTileIndex: get the index of this tile in the root terrain object; // on return, parameters x,y contain index in [0,MapSize) -void CMiniPatch::GetTileIndex(u32& x,u32& z) +void CMiniPatch::GetTileIndex(ssize_t& x,ssize_t& z) { const ptrdiff_t tindex = this - &m_Parent->m_MiniPatches[0][0]; x=(m_Parent->m_X*PATCH_SIZE)+tindex%PATCH_SIZE; z=(m_Parent->m_Z*PATCH_SIZE)+tindex/PATCH_SIZE; } - - diff --git a/source/graphics/MiniPatch.h b/source/graphics/MiniPatch.h index 923db8aee3..cb33315431 100644 --- a/source/graphics/MiniPatch.h +++ b/source/graphics/MiniPatch.h @@ -24,7 +24,7 @@ public: ~CMiniPatch(); // get the index of this tile in the root terrain object; x,y in [0,MapSize) - void GetTileIndex(u32& x,u32& z); + void GetTileIndex(ssize_t& x,ssize_t& z); public: // texture applied to tile diff --git a/source/graphics/Model.cpp b/source/graphics/Model.cpp index 5c519cd471..742fd7421c 100644 --- a/source/graphics/Model.cpp +++ b/source/graphics/Model.cpp @@ -295,7 +295,7 @@ void CModel::InvalidatePosition() { m_PositionValid = false; - for (uint i = 0; i < m_Props.size(); ++i) + for (size_t i = 0; i < m_Props.size(); ++i) m_Props[i].m_Model->InvalidatePosition(); } @@ -430,8 +430,7 @@ void CModel::AddProp(SPropPoint* point, CModel* model, CObjectEntry* objectentry // check if we're already using this point, and remove it if so // (when a prop is removed it will also remove the prop point) - uint i; - for (i = 0; i < m_Props.size(); i++) { + for (size_t i = 0; i < m_Props.size(); i++) { if (m_Props[i].m_Point == point) { delete m_Props[i].m_Model; break; @@ -450,8 +449,7 @@ void CModel::AddProp(SPropPoint* point, CModel* model, CObjectEntry* objectentry // RemoveProp: remove a prop from the given point void CModel::RemoveProp(SPropPoint* point) { - uint i; - for (i=0;iSetMaterial(m_Material); clone->SetAnimation(m_Anim); clone->SetFlags(m_Flags); - for (uint i=0;iAddProp(m_Props[i].m_Point, m_Props[i].m_Model->Clone(), m_Props[i].m_ObjectEntry); } @@ -502,7 +500,7 @@ void CModel::SetMaterial(const CMaterial &material) } } -void CModel::SetPlayerID(int id) +void CModel::SetPlayerID(size_t id) { m_Material.SetPlayerColor(id); for (std::vector::iterator it = m_Props.begin(); it != m_Props.end(); ++it) diff --git a/source/graphics/Model.h b/source/graphics/Model.h index 0c9832c081..900d30d588 100644 --- a/source/graphics/Model.h +++ b/source/graphics/Model.h @@ -68,7 +68,7 @@ public: void SetMaterial(const CMaterial &material); // set the model's player ID, recursively through props. CUnit::SetPlayerID // should normally be used instead. - void SetPlayerID(int id); + void SetPlayerID(size_t id); // set the model's player colour void SetPlayerColor(CColor& colour); // set the models mod color @@ -91,12 +91,12 @@ public: void CopyAnimationFrom(CModel* source); // set object flags - void SetFlags(u32 flags) { m_Flags=flags; } + void SetFlags(int flags) { m_Flags=flags; } // get object flags - u32 GetFlags() const { return m_Flags; } + int GetFlags() const { return m_Flags; } // recurse down tree setting dirty bits - void SetDirtyRec(u32 dirtyflags) { + void SetDirtyRec(int dirtyflags) { SetDirty(dirtyflags); for (size_t i=0;iSetDirtyRec(dirtyflags); @@ -169,7 +169,7 @@ private: CModel* m_Parent; // object flags - u32 m_Flags; + int m_Flags; // texture used by model CTexture m_Texture; // model's material diff --git a/source/graphics/ModelDef.cpp b/source/graphics/ModelDef.cpp index e454ad5bec..ed4a460bf7 100644 --- a/source/graphics/ModelDef.cpp +++ b/source/graphics/ModelDef.cpp @@ -98,7 +98,7 @@ CModelDef::~CModelDef() // return null if no match (case insensitive search) SPropPoint* CModelDef::FindPropPoint(const char* name) const { - for (u32 i = 0; i < m_NumPropPoints; ++i) + for (size_t i = 0; i < m_NumPropPoints; ++i) if (m_PropPoints[i].m_Name == name) return &m_PropPoints[i]; @@ -122,15 +122,15 @@ CModelDef* CModelDef::Load(const VfsPath& filename, const char* name) mdef->m_Name = name; // now unpack everything - unpacker.UnpackRaw(&mdef->m_NumVertices,sizeof(mdef->m_NumVertices)); + mdef->m_NumVertices = unpacker.UnpackSize(); mdef->m_pVertices=new SModelVertex[mdef->m_NumVertices]; unpacker.UnpackRaw(mdef->m_pVertices,sizeof(SModelVertex)*mdef->m_NumVertices); - unpacker.UnpackRaw(&mdef->m_NumFaces,sizeof(mdef->m_NumFaces)); + mdef->m_NumFaces = unpacker.UnpackSize(); mdef->m_pFaces=new SModelFace[mdef->m_NumFaces]; unpacker.UnpackRaw(mdef->m_pFaces,sizeof(SModelFace)*mdef->m_NumFaces); - unpacker.UnpackRaw(&mdef->m_NumBones,sizeof(mdef->m_NumBones)); + mdef->m_NumBones = unpacker.UnpackSize(); if (mdef->m_NumBones) { mdef->m_Bones=new CBoneState[mdef->m_NumBones]; @@ -140,10 +140,10 @@ CModelDef* CModelDef::Load(const VfsPath& filename, const char* name) if (unpacker.GetVersion() >= 2) { // versions >=2 also have prop point data - unpacker.UnpackRaw(&mdef->m_NumPropPoints,sizeof(mdef->m_NumPropPoints)); + mdef->m_NumPropPoints = unpacker.UnpackSize(); if (mdef->m_NumPropPoints) { mdef->m_PropPoints=new SPropPoint[mdef->m_NumPropPoints]; - for (u32 i=0;im_NumPropPoints;i++) { + for (size_t i=0;im_NumPropPoints;i++) { unpacker.UnpackString(mdef->m_PropPoints[i].m_Name); unpacker.UnpackRaw(&mdef->m_PropPoints[i].m_Position.X,sizeof(mdef->m_PropPoints[i].m_Position)); unpacker.UnpackRaw(&mdef->m_PropPoints[i].m_Rotation.m_V.X,sizeof(mdef->m_PropPoints[i].m_Rotation)); @@ -172,14 +172,14 @@ CModelDef* CModelDef::Load(const VfsPath& filename, const char* name) std::vector bindPose (mdef->m_NumBones); - for (u32 i = 0; i < mdef->m_NumBones; ++i) + for (size_t i = 0; i < mdef->m_NumBones; ++i) { bindPose[i].SetIdentity(); bindPose[i].Rotate(mdef->m_Bones[i].m_Rotation); bindPose[i].Translate(mdef->m_Bones[i].m_Translation); } - for (u32 i = 0; i < mdef->m_NumVertices; ++i) + for (size_t i = 0; i < mdef->m_NumVertices; ++i) { mdef->m_pVertices[i].m_Coords = SkinPoint(mdef->m_pVertices[i], &bindPose[0], &identityBones[0]); mdef->m_pVertices[i].m_Norm = SkinNormal(mdef->m_pVertices[i], &bindPose[0], &identityBones[0]); @@ -196,21 +196,22 @@ void CModelDef::Save(const VfsPath& filename,const CModelDef* mdef) CFilePacker packer(FILE_VERSION, "PSMD"); // pack everything up - u32 numVertices=(u32)mdef->GetNumVertices(); - packer.PackRaw(&numVertices,sizeof(numVertices)); + const size_t numVertices = mdef->GetNumVertices(); + packer.PackSize(numVertices); packer.PackRaw(mdef->GetVertices(),sizeof(SModelVertex)*numVertices); - u32 numFaces=(u32)mdef->GetNumFaces(); - packer.PackRaw(&numFaces,sizeof(numFaces)); + const size_t numFaces = mdef->GetNumFaces(); + packer.PackSize(numFaces); packer.PackRaw(mdef->GetFaces(),sizeof(SModelFace)*numFaces); - packer.PackRaw(&mdef->m_NumBones,sizeof(mdef->m_NumBones)); - if (mdef->m_NumBones) { - packer.PackRaw(mdef->m_Bones,sizeof(CBoneState)*mdef->m_NumBones); - } + const size_t numBones = mdef->m_NumBones; + packer.PackSize(numBones); + if (numBones) + packer.PackRaw(mdef->m_Bones,sizeof(CBoneState)*numBones); - packer.PackRaw(&mdef->m_NumPropPoints,sizeof(mdef->m_NumPropPoints)); - for (u32 i=0;im_NumPropPoints;i++) { + const size_t numPropPoints = mdef->m_NumPropPoints; + packer.PackSize(numPropPoints); + for (size_t i=0;im_NumPropPoints;i++) { packer.PackString(mdef->m_PropPoints[i].m_Name); packer.PackRaw(&mdef->m_PropPoints[i].m_Position.X,sizeof(mdef->m_PropPoints[i].m_Position)); packer.PackRaw(&mdef->m_PropPoints[i].m_Rotation.m_V.X,sizeof(mdef->m_PropPoints[i].m_Rotation)); diff --git a/source/graphics/ModelDef.h b/source/graphics/ModelDef.h index 2536a999e1..d24b159161 100644 --- a/source/graphics/ModelDef.h +++ b/source/graphics/ModelDef.h @@ -122,7 +122,7 @@ public: CBoneState* GetBones() const { return m_Bones; } // accessor: get prop data - int GetNumPropPoints() const { return m_NumPropPoints; } + size_t GetNumPropPoints() const { return m_NumPropPoints; } SPropPoint* GetPropPoints() const { return m_PropPoints; } // find and return pointer to prop point matching given name; return @@ -169,16 +169,16 @@ public: public: // vertex data - u32 m_NumVertices; + size_t m_NumVertices; SModelVertex* m_pVertices; // face data - u32 m_NumFaces; + size_t m_NumFaces; SModelFace* m_pFaces; // bone data - default model pose - u32 m_NumBones; + size_t m_NumBones; CBoneState* m_Bones; // prop point data - u32 m_NumPropPoints; + size_t m_NumPropPoints; SPropPoint* m_PropPoints; private: diff --git a/source/graphics/ObjectBase.cpp b/source/graphics/ObjectBase.cpp index 4c77631410..1faed63f8f 100644 --- a/source/graphics/ObjectBase.cpp +++ b/source/graphics/ObjectBase.cpp @@ -440,7 +440,7 @@ std::set CObjectBase::CalculateRandomVariation(const std::set& initi // Choose a random number in the interval [0..totalFreq). // (It shouldn't be necessary to use a network-synchronised RNG, // since actors are meant to have purely visual manifestations.) - int randNum = rand(0, totalFreq); + int randNum = (int)rand(0, (size_t)totalFreq); // and use that to choose one of the variants for (size_t i = 0; i < grp->size(); ++i) diff --git a/source/graphics/ObjectEntry.cpp b/source/graphics/ObjectEntry.cpp index 21803d6525..1b2959320c 100644 --- a/source/graphics/ObjectEntry.cpp +++ b/source/graphics/ObjectEntry.cpp @@ -229,7 +229,7 @@ CSkeletonAnim* CObjectEntry::GetRandomAnimation(const CStr& animationName) else { // TODO: Do we care about network synchronisation of random animations? - int id = rand(0, (int)count); + size_t id = rand(0, count); std::advance(lower, id); return lower->second; } diff --git a/source/graphics/ParticleEmitter.h b/source/graphics/ParticleEmitter.h index 141aab940a..b012a9d10c 100644 --- a/source/graphics/ParticleEmitter.h +++ b/source/graphics/ParticleEmitter.h @@ -35,7 +35,7 @@ public: short life; // How long it will last 2 // particle text stuff - CVector3D endPos; // For particle texture 12 + CVector3D endPos; // For particle texture 12 bool inPos; // 1 tParticle* next; // pointer for link lists 4 diff --git a/source/graphics/ParticleEngine.cpp b/source/graphics/ParticleEngine.cpp index 3ee310f072..a5cb5d6410 100644 --- a/source/graphics/ParticleEngine.cpp +++ b/source/graphics/ParticleEngine.cpp @@ -66,7 +66,7 @@ bool CParticleEngine::InitParticleSystem() CTexture pTex; pTex.SetName("art/textures/particles/sprite.tga"); - u32 flags = 0; + int flags = 0; if(!(g_Renderer.LoadTexture(&pTex, flags))) return false; diff --git a/source/graphics/Patch.cpp b/source/graphics/Patch.cpp index f154423b23..1f2bf92e61 100644 --- a/source/graphics/Patch.cpp +++ b/source/graphics/Patch.cpp @@ -28,7 +28,7 @@ CPatch::~CPatch() /////////////////////////////////////////////////////////////////////////////// // Initialize: setup patch data -void CPatch::Initialize(CTerrain* parent,u32 x,u32 z) +void CPatch::Initialize(CTerrain* parent,ssize_t x,ssize_t z) { delete m_RenderData; m_RenderData=0; @@ -38,9 +38,9 @@ void CPatch::Initialize(CTerrain* parent,u32 x,u32 z) m_Z=z; // set parent of each patch - for (int j=0;jCalcPosition(m_X*PATCH_SIZE+i,m_Z*PATCH_SIZE+j,pos); diff --git a/source/graphics/Patch.h b/source/graphics/Patch.h index 5a71b3df60..396527cffd 100644 --- a/source/graphics/Patch.h +++ b/source/graphics/Patch.h @@ -18,7 +18,7 @@ class CTerrain; // Terrain Constants: // // PATCH_SIZE: number of tiles in each patch -const int PATCH_SIZE = 16; +const ssize_t PATCH_SIZE = 16; /// neighbor IDs for CPatch enum CPatchNeighbors @@ -44,7 +44,7 @@ public: ~CPatch(); // initialize the patch - void Initialize(CTerrain* parent,u32 x,u32 z); + void Initialize(CTerrain* parent,ssize_t x,ssize_t z); // calculate and store bounds of this patch void CalcBounds(); @@ -55,7 +55,7 @@ public: // minipatches (tiles) making up the patch CMiniPatch m_MiniPatches[PATCH_SIZE][PATCH_SIZE]; // position of patch in parent terrain grid - u32 m_X,m_Z; + int m_X,m_Z; // parent terrain CTerrain* m_Parent; diff --git a/source/graphics/RenderableObject.h b/source/graphics/RenderableObject.h index f888fa2a6f..7d63059dc8 100644 --- a/source/graphics/RenderableObject.h +++ b/source/graphics/RenderableObject.h @@ -31,7 +31,7 @@ public: CRenderData() : m_UpdateFlags(0) {} virtual ~CRenderData() {} - u32 m_UpdateFlags; + int m_UpdateFlags; }; /////////////////////////////////////////////////////////////////////////////// diff --git a/source/graphics/SkeletonAnimDef.cpp b/source/graphics/SkeletonAnimDef.cpp index 638e4c794e..622376e72f 100644 --- a/source/graphics/SkeletonAnimDef.cpp +++ b/source/graphics/SkeletonAnimDef.cpp @@ -32,12 +32,12 @@ CSkeletonAnimDef::~CSkeletonAnimDef() void CSkeletonAnimDef::BuildBoneMatrices(float time, CMatrix3D* matrices, bool loop) const { float fstartframe = time/m_FrameTime; - u32 startframe = u32(time/m_FrameTime); + size_t startframe = (size_t)(int)(time/m_FrameTime); float deltatime = fstartframe-startframe; startframe %= m_NumFrames; - u32 endframe = startframe + 1; + size_t endframe = startframe + 1; endframe %= m_NumFrames; if (!loop && endframe == 0) @@ -46,7 +46,7 @@ void CSkeletonAnimDef::BuildBoneMatrices(float time, CMatrix3D* matrices, bool l // between the final frame and the initial frame is wrong, because they're // totally different. So if we've looped around to endframe==0, just display // the animation's final frame with no interpolation. - for (u32 i = 0; i < m_NumKeys; i++) + for (size_t i = 0; i < m_NumKeys; i++) { const Key& key = GetKey(startframe, i); matrices[i].SetIdentity(); @@ -56,7 +56,7 @@ void CSkeletonAnimDef::BuildBoneMatrices(float time, CMatrix3D* matrices, bool l } else { - for (u32 i = 0; i < m_NumKeys; i++) + for (size_t i = 0; i < m_NumKeys; i++) { const Key& startkey = GetKey(startframe, i); const Key& endkey = GetKey(endframe, i); @@ -90,8 +90,8 @@ CSkeletonAnimDef* CSkeletonAnimDef::Load(const VfsPath& filename) CStr name; // unused - just here to maintain compatibility with the animation files unpacker.UnpackString(name); unpacker.UnpackRaw(&anim->m_FrameTime,sizeof(anim->m_FrameTime)); - unpacker.UnpackRaw(&anim->m_NumKeys,sizeof(anim->m_NumKeys)); - unpacker.UnpackRaw(&anim->m_NumFrames,sizeof(anim->m_NumFrames)); + anim->m_NumKeys = unpacker.UnpackSize(); + anim->m_NumFrames = unpacker.UnpackSize(); anim->m_Keys=new Key[anim->m_NumKeys*anim->m_NumFrames]; unpacker.UnpackRaw(anim->m_Keys,anim->m_NumKeys*anim->m_NumFrames*sizeof(Key)); } catch (PSERROR_File&) { @@ -111,12 +111,12 @@ void CSkeletonAnimDef::Save(const char* filename,const CSkeletonAnimDef* anim) // pack up all the data packer.PackString(""); packer.PackRaw(&anim->m_FrameTime,sizeof(anim->m_FrameTime)); - packer.PackRaw(&anim->m_NumKeys,sizeof(anim->m_NumKeys)); - packer.PackRaw(&anim->m_NumFrames,sizeof(anim->m_NumFrames)); - packer.PackRaw(anim->m_Keys,anim->m_NumKeys*anim->m_NumFrames*sizeof(Key)); + const size_t numKeys = anim->m_NumKeys; + packer.PackSize(numKeys); + const size_t numFrames = anim->m_NumFrames; + packer.PackSize(numFrames); + packer.PackRaw(anim->m_Keys,numKeys*numFrames*sizeof(Key)); // now write it packer.Write(filename); } - - diff --git a/source/graphics/SkeletonAnimDef.h b/source/graphics/SkeletonAnimDef.h index 9ee5f2ac49..70874e8e60 100644 --- a/source/graphics/SkeletonAnimDef.h +++ b/source/graphics/SkeletonAnimDef.h @@ -50,8 +50,8 @@ public: size_t GetNumKeys() const { return (size_t)m_NumKeys; } // accessors: get a key for given bone at given time - Key& GetKey(u32 frame, u32 bone) { return m_Keys[frame*m_NumKeys+bone]; } - const Key& GetKey(u32 frame, u32 bone) const { return m_Keys[frame*m_NumKeys+bone]; } + Key& GetKey(size_t frame, size_t bone) { return m_Keys[frame*m_NumKeys+bone]; } + const Key& GetKey(size_t frame, size_t bone) const { return m_Keys[frame*m_NumKeys+bone]; } // get duration of this anim, in ms float GetDuration() const { return m_NumFrames*m_FrameTime; } @@ -72,9 +72,9 @@ public: // frame time - time between successive frames, in ms float m_FrameTime; // number of keys in each frame - should match number of bones in the skeleton - u32 m_NumKeys; + size_t m_NumKeys; // number of frames in the animation - u32 m_NumFrames; + size_t m_NumFrames; // animation data - m_NumKeys*m_NumFrames total keys Key* m_Keys; }; diff --git a/source/graphics/Terrain.cpp b/source/graphics/Terrain.cpp index 357818a478..f9dba0d465 100644 --- a/source/graphics/Terrain.cpp +++ b/source/graphics/Terrain.cpp @@ -52,13 +52,13 @@ void CTerrain::ReleaseData() /////////////////////////////////////////////////////////////////////////////// // Initialise: initialise this terrain to the given size (in patches per side); // using given heightmap to setup elevation data -bool CTerrain::Initialize(u32 size,const u16* data) +bool CTerrain::Initialize(ssize_t size,const u16* data) { // clean up any previous terrain ReleaseData(); // store terrain size - m_MapSize=(size*PATCH_SIZE)+1; + m_MapSize=size*PATCH_SIZE+1; m_MapSizePatches=size; // allocate data for new terrain m_Heightmap=new u16[m_MapSize*m_MapSize]; @@ -106,10 +106,10 @@ bool CTerrain::IsPassable(const CVector2D &loc/*tile space*/, HEntity entity) co /////////////////////////////////////////////////////////////////////////////// // CalcPosition: calculate the world space position of the vertex at (i,j) -void CTerrain::CalcPosition(i32 i, i32 j, CVector3D& pos) const +void CTerrain::CalcPosition(ssize_t i, ssize_t j, CVector3D& pos) const { u16 height; - if ((u32)i < m_MapSize && (u32)j < m_MapSize) // will reject negative coordinates + if ((size_t)i < (size_t)m_MapSize && (size_t)j < (size_t)m_MapSize) // will reject negative coordinates height = m_Heightmap[j*m_MapSize + i]; else height = 0; @@ -121,7 +121,7 @@ void CTerrain::CalcPosition(i32 i, i32 j, CVector3D& pos) const /////////////////////////////////////////////////////////////////////////////// // CalcNormal: calculate the world space normal of the vertex at (i,j) -void CTerrain::CalcNormal(u32 i, u32 j, CVector3D& normal) const +void CTerrain::CalcNormal(ssize_t i, ssize_t j, CVector3D& normal) const { CVector3D left, right, up, down; @@ -169,10 +169,10 @@ void CTerrain::CalcNormal(u32 i, u32 j, CVector3D& normal) const /////////////////////////////////////////////////////////////////////////////// // GetPatch: return the patch at (i,j) in patch space, or null if the patch is // out of bounds -CPatch* CTerrain::GetPatch(i32 i, i32 j) const +CPatch* CTerrain::GetPatch(ssize_t i, ssize_t j) const { // range check: >= 0 and < m_MapSizePatches - if( (unsigned)i >= m_MapSizePatches || (unsigned)j >= m_MapSizePatches ) + if( (size_t)i >= (size_t)m_MapSizePatches || (size_t)j >= (size_t)m_MapSizePatches ) return 0; return &m_Patches[(j*m_MapSizePatches)+i]; @@ -182,26 +182,26 @@ CPatch* CTerrain::GetPatch(i32 i, i32 j) const /////////////////////////////////////////////////////////////////////////////// // GetPatch: return the tile at (i,j) in tile space, or null if the tile is out // of bounds -CMiniPatch* CTerrain::GetTile(i32 i, i32 j) const +CMiniPatch* CTerrain::GetTile(ssize_t i, ssize_t j) const { // see above - if( (unsigned)i >= m_MapSize-1 || (unsigned)j >= m_MapSize-1 ) + if( (size_t)i >= (size_t)(m_MapSize-1) || (size_t)j >= (size_t)(m_MapSize-1) ) return 0; CPatch* patch=GetPatch(i/PATCH_SIZE, j/PATCH_SIZE); return &patch->m_MiniPatches[j%PATCH_SIZE][i%PATCH_SIZE]; } -float CTerrain::GetVertexGroundLevel(int i, int j) const +float CTerrain::GetVertexGroundLevel(ssize_t i, ssize_t j) const { if (i < 0) i = 0; - else if (i >= (int) m_MapSize) + else if ((size_t)i >= (size_t)m_MapSize) i = m_MapSize - 1; if (j < 0) j = 0; - else if (j >= (int) m_MapSize) + else if ((size_t)j >= (size_t)m_MapSize) j = m_MapSize - 1; return HEIGHT_SCALE * m_Heightmap[j*m_MapSize + i]; @@ -287,7 +287,7 @@ float CTerrain::GetExactGroundLevel(float x, float z) const /////////////////////////////////////////////////////////////////////////////// // Resize: resize this terrain to the given size (in patches per side) -void CTerrain::Resize(u32 size) +void CTerrain::Resize(ssize_t size) { if (size==m_MapSizePatches) { // inexplicable request to resize terrain to the same size .. ignore it @@ -301,7 +301,7 @@ void CTerrain::Resize(u32 size) } // allocate data for new terrain - u32 newMapSize=(size*PATCH_SIZE)+1; + ssize_t newMapSize=size*PATCH_SIZE+1; u16* newHeightmap=new u16[newMapSize*newMapSize]; CPatch* newPatches=new CPatch[size*size]; @@ -312,17 +312,16 @@ void CTerrain::Resize(u32 size) } // now copy over rows of data - u32 j; u16* src=m_Heightmap; u16* dst=newHeightmap; - u32 copysize=newMapSize>m_MapSize ? m_MapSize : newMapSize; - for (j=0;jm_MapSize ? m_MapSize : newMapSize; + for (ssize_t j=0;jm_MapSize) { // entend the last height to the end of the row - for (u32 i=0;im_MapSizePatches) { // copy over the last tile from each column - for (u32 n=0;nm_MiniPatches[15][k]; CMiniPatch& dst=dstpatch->m_MiniPatches[m][k]; dst.Tex1=src.Tex1; @@ -390,8 +389,8 @@ void CTerrain::Resize(u32 size) // store new data m_Heightmap=newHeightmap; m_Patches=newPatches; - m_MapSize=newMapSize; - m_MapSizePatches=size; + m_MapSize=(ssize_t)newMapSize; + m_MapSizePatches=(ssize_t)size; // initialise all the new patches InitialisePatches(); @@ -401,8 +400,8 @@ void CTerrain::Resize(u32 size) // InitialisePatches: initialise patch data void CTerrain::InitialisePatches() { - for (u32 j=0;jInitialize(this,i,j); } @@ -418,8 +417,8 @@ void CTerrain::SetHeightMap(u16* heightmap) cpu_memcpy(m_Heightmap,heightmap,m_MapSize*m_MapSize*sizeof(u16)); // recalculate patch bounds, invalidate vertices - for (u32 j=0;jInvalidateBounds(); patch->SetDirty(RENDERDATA_UPDATE_VERTICES); @@ -433,23 +432,23 @@ void CTerrain::SetHeightMap(u16* heightmap) // coords); return the average height of the flattened area float CTerrain::FlattenArea(float x0, float x1, float z0, float z1) { - u32 tx0=u32(clamp(int(float(x0/CELL_SIZE)), 0, int(m_MapSize))); - u32 tx1=u32(clamp(int(float(x1/CELL_SIZE)+1.0f), 0, int(m_MapSize))); - u32 tz0=u32(clamp(int(float(z0/CELL_SIZE)), 0, int(m_MapSize))); - u32 tz1=u32(clamp(int(float(z1/CELL_SIZE)+1.0f), 0, int(m_MapSize))); + ssize_t tx0=clamp(ssize_t((x0/CELL_SIZE)), ssize_t(0), m_MapSize); + ssize_t tx1=clamp(ssize_t((x1/CELL_SIZE)+1.0f), ssize_t(0), m_MapSize); + ssize_t tz0=clamp(ssize_t((z0/CELL_SIZE)), ssize_t(0), m_MapSize); + ssize_t tz1=clamp(ssize_t((z1/CELL_SIZE)+1.0f), ssize_t(0), m_MapSize); - u32 count=0; - u32 y=0; - for (u32 x=tx0;x<=tx1;x++) { - for (u32 z=tz0;z<=tz1;z++) { + size_t count=0; + size_t y=0; + for (ssize_t x=tx0;x<=tx1;x++) { + for (ssize_t z=tz0;z<=tz1;z++) { y+=m_Heightmap[z*m_MapSize + x]; count++; } } y/=count; - for (u32 x=tx0;x<=tx1;x++) { - for (u32 z=tz0;z<=tz1;z++) { + for (ssize_t x=tx0;x<=tx1;x++) { + for (ssize_t z=tz0;z<=tz1;z++) { m_Heightmap[z*m_MapSize + x]=(u16)y; CPatch* patch=GetPatch(x/PATCH_SIZE,z/PATCH_SIZE); patch->SetDirty(RENDERDATA_UPDATE_VERTICES); @@ -461,15 +460,15 @@ float CTerrain::FlattenArea(float x0, float x1, float z0, float z1) /////////////////////////////////////////////////////////////////////////////// -void CTerrain::MakeDirty(int i0, int j0, int i1, int j1, int dirtyFlags) +void CTerrain::MakeDirty(ssize_t i0, ssize_t j0, ssize_t i1, ssize_t j1, int dirtyFlags) { // flag vertex data as dirty for affected patches, and rebuild bounds of these patches - int pi0 = clamp((i0/PATCH_SIZE)-1, 0, (int)m_MapSizePatches); - int pi1 = clamp((i1/PATCH_SIZE)+1, 0, (int)m_MapSizePatches); - int pj0 = clamp((j0/PATCH_SIZE)-1, 0, (int)m_MapSizePatches); - int pj1 = clamp((j1/PATCH_SIZE)+1, 0, (int)m_MapSizePatches); - for (int j = pj0; j < pj1; j++) { - for (int i = pi0; i < pi1; i++) { + ssize_t pi0 = clamp((i0/PATCH_SIZE)-1, ssize_t(0), m_MapSizePatches); + ssize_t pi1 = clamp((i1/PATCH_SIZE)+1, ssize_t(0), m_MapSizePatches); + ssize_t pj0 = clamp((j0/PATCH_SIZE)-1, ssize_t(0), m_MapSizePatches); + ssize_t pj1 = clamp((j1/PATCH_SIZE)+1, ssize_t(0), m_MapSizePatches); + for (ssize_t j = pj0; j < pj1; j++) { + for (ssize_t i = pi0; i < pi1; i++) { CPatch* patch = GetPatch(i,j); if (dirtyFlags & RENDERDATA_UPDATE_VERTICES) patch->CalcBounds(); @@ -480,8 +479,8 @@ void CTerrain::MakeDirty(int i0, int j0, int i1, int j1, int dirtyFlags) void CTerrain::MakeDirty(int dirtyFlags) { - for (u32 j = 0; j < m_MapSizePatches; j++) { - for (u32 i = 0; i < m_MapSizePatches; i++) { + for (ssize_t j = 0; j < m_MapSizePatches; j++) { + for (ssize_t i = 0; i < m_MapSizePatches; i++) { CPatch* patch = GetPatch(i,j); if (dirtyFlags & RENDERDATA_UPDATE_VERTICES) patch->CalcBounds(); diff --git a/source/graphics/Terrain.h b/source/graphics/Terrain.h index ec6bf5d4d5..32e816ba5b 100644 --- a/source/graphics/Terrain.h +++ b/source/graphics/Terrain.h @@ -24,7 +24,7 @@ class CVector2D; // Terrain Constants: // // CELL_SIZE: size of each tile in x and z -const int CELL_SIZE = 4; +const ssize_t CELL_SIZE = 4; // HEIGHT_SCALE: vertical scale of terrain - terrain has a coordinate range of // 0 to 65536*HEIGHT_SCALE const float HEIGHT_SCALE = 0.35f/256.0f; @@ -39,16 +39,18 @@ public: ~CTerrain(); // Coordinate naming convention: world-space coordinates are float x,z; - // tile-space coordinates are int i,j. + // tile-space coordinates are ssize_t i,j. rationale: signed types can + // more efficiently be converted to/from floating point. use ssize_t + // instead of int/long because these are sizes. - bool Initialize(u32 size, const u16* ptr); + bool Initialize(ssize_t size, const u16* ptr); // return number of vertices along edge of the terrain - u32 GetVerticesPerSide() const { return m_MapSize; } + ssize_t GetVerticesPerSide() const { return m_MapSize; } // return number of tiles along edge of the terrain - u32 GetTilesPerSide() const { return GetVerticesPerSide()-1; } + ssize_t GetTilesPerSide() const { return GetVerticesPerSide()-1; } // return number of patches along edge of the terrain - u32 GetPatchesPerSide() const { return m_MapSizePatches; } + ssize_t GetPatchesPerSide() const { return m_MapSizePatches; } bool IsOnMap(float x, float z) const { @@ -68,7 +70,7 @@ public: index = m_MapSize - 2; } - float GetVertexGroundLevel(int i, int j) const; + float GetVertexGroundLevel(ssize_t i, ssize_t j) const; float GetExactGroundLevel(float x, float z) const; float GetExactGroundLevel(const CVector2D& v) const; @@ -76,7 +78,7 @@ public: //Find the slope of in X and Z axes depending on the way the entity is facing CVector2D GetSlopeAngleFace(CEntity* entity) const; // resize this terrain such that each side has given number of patches - void Resize(u32 size); + void Resize(ssize_t size); // set up a new heightmap from 16 bit data; assumes heightmap matches current terrain size void SetHeightMap(u16* heightmap); @@ -85,34 +87,34 @@ public: // get patch at given coordinates, expressed in patch-space; return 0 if // coordinates represent patch off the edge of the map - CPatch* GetPatch(i32 i, i32 j) const; + CPatch* GetPatch(ssize_t i, ssize_t j) const; // get tile at given coordinates, expressed in tile-space; return 0 if // coordinates represent tile off the edge of the map - CMiniPatch* GetTile(i32 i, i32 j) const; + CMiniPatch* GetTile(ssize_t i, ssize_t j) const; // calculate the position of a given vertex - void CalcPosition(i32 i, i32 j, CVector3D& pos) const; + void CalcPosition(ssize_t i, ssize_t j, CVector3D& pos) const; // calculate the vertex under a given position (rounding down coordinates) - static void CalcFromPosition(const CVector3D& pos, i32& i, i32& j) + static void CalcFromPosition(const CVector3D& pos, ssize_t& i, ssize_t& j) { - i = cpu_i32FromFloat(pos.X/CELL_SIZE); - j = cpu_i32FromFloat(pos.Z/CELL_SIZE); + i = (ssize_t)(pos.X/CELL_SIZE); + j = (ssize_t)(pos.Z/CELL_SIZE); } // calculate the vertex under a given position (rounding down coordinates) - static void CalcFromPosition(float x, float z, i32& i, i32& j) + static void CalcFromPosition(float x, float z, ssize_t& i, ssize_t& j) { - i = cpu_i32FromFloat(x/CELL_SIZE); - j = cpu_i32FromFloat(z/CELL_SIZE); + i = (ssize_t)(x/CELL_SIZE); + j = (ssize_t)(z/CELL_SIZE); } // calculate the normal at a given vertex - void CalcNormal(u32 i, u32 j, CVector3D& normal) const; + void CalcNormal(ssize_t i, ssize_t j, CVector3D& normal) const; // flatten out an area of terrain (specified in world space coords); return // the average height of the flattened area float FlattenArea(float x0, float x1, float z0, float z1); // mark a specific square of tiles as dirty - use this after modifying the heightmap - void MakeDirty(int i0, int j0, int i1, int j1, int dirtyFlags); + void MakeDirty(ssize_t i0, ssize_t j0, ssize_t i1, ssize_t j1, int dirtyFlags); // mark the entire map as dirty void MakeDirty(int dirtyFlags); @@ -129,9 +131,9 @@ private: void InitialisePatches(); // size of this map in each direction, in vertices; ie. total tiles = sqr(m_MapSize-1) - u32 m_MapSize; + ssize_t m_MapSize; // size of this map in each direction, in patches; total patches = sqr(m_MapSizePatches) - u32 m_MapSizePatches; + ssize_t m_MapSizePatches; // the patches comprising this terrain CPatch* m_Patches; // 16-bit heightmap data diff --git a/source/graphics/TextureEntry.h b/source/graphics/TextureEntry.h index c9064ce377..e1d7848214 100644 --- a/source/graphics/TextureEntry.h +++ b/source/graphics/TextureEntry.h @@ -79,7 +79,7 @@ public: } // ScEd wants to sort textures by their group's index. - int GetType() const + size_t GetType() const { return m_Groups[0]->GetIndex(); } const GroupVector &GetGroups() const { return m_Groups; } diff --git a/source/graphics/TextureManager.cpp b/source/graphics/TextureManager.cpp index 31e974bcc3..fbd98ad22c 100644 --- a/source/graphics/TextureManager.cpp +++ b/source/graphics/TextureManager.cpp @@ -50,7 +50,7 @@ CTextureEntry* CTextureManager::FindTexture(CStr tag) { tag = tag.substr(0, pos); } - for (uint i=0;iGetTag() == tag) return m_TextureEntries[i]; @@ -158,7 +158,7 @@ void CTextureManager::RecurseDirectory(CTerrainPropertiesPtr parentProps, const // Recurse once for each subdirectory DirectoryNames subdirectoryNames; g_VFS->GetDirectoryEntries(cur_dir_path, 0, &subdirectoryNames); - for (uint i=0;i m_Terrains; public: - CTerrainGroup(CStr name, int index): + CTerrainGroup(CStr name, size_t index): m_Name(name), m_Index(index) {} @@ -40,7 +40,7 @@ public: // Remove a texture entry void RemoveTerrain(CTextureEntry *); - int GetIndex() const + size_t GetIndex() const { return m_Index; } CStr GetName() const { return m_Name; } @@ -63,7 +63,7 @@ private: TerrainGroupMap m_TerrainGroups; - uint m_LastGroupIndex; + size_t m_LastGroupIndex; // Find+load all textures in directory; check if // there's an override XML with the same basename (if there is, load it) diff --git a/source/graphics/Unit.cpp b/source/graphics/Unit.cpp index ec49036132..df01db0b7d 100644 --- a/source/graphics/Unit.cpp +++ b/source/graphics/Unit.cpp @@ -10,12 +10,13 @@ #include "UnitAnimation.h" #include "ps/Game.h" +#include "ps/Player.h" #include "simulation/Entity.h" CUnit::CUnit(CObjectEntry* object, CEntity* entity, CObjectManager& objectManager, const std::set& actorSelections) : m_Object(object), m_Model(object->m_Model->Clone()), m_Entity(entity), - m_ID(-1), m_ActorSelections(actorSelections), m_PlayerID(-1), +m_ID(invalidId), m_ActorSelections(actorSelections), m_PlayerID(CPlayer::invalidId), m_ObjectManager(objectManager) { m_Animation = new CUnitAnimation(*this); @@ -158,7 +159,7 @@ void CUnit::UpdateModel(float frameTime) } -void CUnit::SetPlayerID(int id) +void CUnit::SetPlayerID(size_t id) { m_PlayerID = id; m_Model->SetPlayerID(m_PlayerID); @@ -204,7 +205,7 @@ void CUnit::ReloadObject() // Copy the old instance-specific settings from the old model to the new instance newModel->SetTransform(m_Model->GetTransform()); - if (m_PlayerID != -1) + if (m_PlayerID != CPlayer::invalidId) newModel->SetPlayerID(m_PlayerID); newModel->CopyAnimationFrom(m_Model); diff --git a/source/graphics/Unit.h b/source/graphics/Unit.h index 2efc5534d8..edf17a87d2 100644 --- a/source/graphics/Unit.h +++ b/source/graphics/Unit.h @@ -66,16 +66,17 @@ public: bool IsPlayingAnimation(const CStr& name); // Set player ID of this unit (and the attached entity and actor) - void SetPlayerID(int id); + void SetPlayerID(size_t id); // Get player ID of this unit - int GetPlayerID() { return m_PlayerID; } + size_t GetPlayerID() { return m_PlayerID; } // Most units have a hopefully-unique ID number, so they can be referred to // persistently despite saving/loading maps. Default for new units is -1; should // usually be set to CUnitManager::GetNewID() after creation. - int GetID() const { return m_ID; } - void SetID(int id) { m_ID = id; } + static const size_t invalidId = ~(size_t)0; + size_t GetID() const { return m_ID; } + void SetID(size_t id) { m_ID = id; } const std::set& GetActorSelections() const { return m_ActorSelections; } @@ -88,14 +89,14 @@ private: CModel* m_Model; // the entity that this actor represents, if any CEntity* m_Entity; - // player id of this unit (only read for graphical effects), or -1 if unspecified - int m_PlayerID; + // player id of this unit (only read for graphical effects), or ~0 if unspecified + size_t m_PlayerID; CUnitAnimation* m_Animation; // unique (per map) ID number for units created in the editor, as a - // permanent way of referencing them. -1 for non-editor units. - int m_ID; + // permanent way of referencing them. ~0 for non-editor units. + size_t m_ID; // actor-level selections for this unit std::set m_ActorSelections; diff --git a/source/graphics/UnitManager.cpp b/source/graphics/UnitManager.cpp index 57cc79f1b3..10e8d41491 100644 --- a/source/graphics/UnitManager.cpp +++ b/source/graphics/UnitManager.cpp @@ -68,8 +68,7 @@ void CUnitManager::DeleteUnit(CUnit* unit) // DeleteAll: remove and delete all units void CUnitManager::DeleteAll() { - uint i; - for (i=0;i m_Units; // next ID number to be assigned to a unit created in the editor - int m_NextID; + size_t m_NextID; // graphical object manager; may be NULL if not set up CObjectManager* m_ObjectManager; }; diff --git a/source/graphics/scripting/JSInterface_Camera.cpp b/source/graphics/scripting/JSInterface_Camera.cpp index 93e9e3c0ec..071126557b 100644 --- a/source/graphics/scripting/JSInterface_Camera.cpp +++ b/source/graphics/scripting/JSInterface_Camera.cpp @@ -214,7 +214,7 @@ JSBool JSI_Camera::setProperty( JSContext* cx, JSObject* obj, jsval id, jsval* v #define GETVECTOR( jv ) ( ( JSVAL_IS_OBJECT( jv ) && NULL != ( v = (JSI_Vector3D::Vector3D_Info*)JS_GetInstancePrivate( g_ScriptingHost.getContext(), JSVAL_TO_OBJECT( jv ), &JSI_Vector3D::JSI_class, NULL ) ) ) ? *(v->vector) : CVector3D() ) -JSBool JSI_Camera::lookAt( JSContext* cx, JSObject* obj, uint argc, jsval* argv, jsval* rval ) +JSBool JSI_Camera::lookAt( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval ) { JSI_Vector3D::Vector3D_Info* v = NULL; Camera_Info* cameraInfo = (Camera_Info*)JS_GetPrivate( cx, obj ); diff --git a/source/graphics/scripting/JSInterface_Camera.h b/source/graphics/scripting/JSInterface_Camera.h index c5b7e0e189..4a87d12017 100644 --- a/source/graphics/scripting/JSInterface_Camera.h +++ b/source/graphics/scripting/JSInterface_Camera.h @@ -72,11 +72,11 @@ namespace JSI_Camera JSBool getCamera( JSContext* cx, JSObject* obj, jsval id, jsval* vp ); JSBool setCamera( JSContext* cx, JSObject* obj, jsval id, jsval* vp ); - JSBool construct( JSContext* cx, JSObject* obj, uint argc, jsval* argv, jsval* rval ); + JSBool construct( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval ); void finalize( JSContext* cx, JSObject* obj ); - JSBool lookAt( JSContext* cx, JSObject* obj, uint argc, jsval* argv, jsval* rval ); - JSBool getFocus( JSContext* cx, JSObject* obj, uint argc, jsval* argv, jsval* rval ); + JSBool lookAt( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval ); + JSBool getFocus( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval ); void init(); } diff --git a/source/gui/GUIRenderer.cpp b/source/gui/GUIRenderer.cpp index a5e2e2558d..f94e300874 100644 --- a/source/gui/GUIRenderer.cpp +++ b/source/gui/GUIRenderer.cpp @@ -406,11 +406,11 @@ void GUIRenderer::UpdateDrawCallCache(DrawCalls &Calls, CStr& SpriteName, CRect Call.m_TexHandle = h; - uint t_w = 0, t_h = 0; + size_t t_w = 0, t_h = 0; (void)ogl_tex_get_size(h, &t_w, &t_h, 0); float TexWidth = t_w, TexHeight = t_h; - uint flags = 0; // assume no alpha on failure + int flags = 0; // assume no alpha on failure (void)ogl_tex_get_format(h, &flags, 0); Call.m_EnableBlending = (flags & TEX_ALPHA) != 0; @@ -434,7 +434,7 @@ void GUIRenderer::UpdateDrawCallCache(DrawCalls &Calls, CStr& SpriteName, CRect // Check whether this sprite has "cell_size" set else if (cit->m_CellSize != CSize()) { - int cols = t_w / (int)cit->m_CellSize.cx; + int cols = (int)t_w / (int)cit->m_CellSize.cx; int col = CellID % cols; int row = CellID / cols; BlockTex = CRect(cit->m_CellSize.cx*col, cit->m_CellSize.cy*row, diff --git a/source/gui/MiniMap.cpp b/source/gui/MiniMap.cpp index a30e8c716d..5619179345 100644 --- a/source/gui/MiniMap.cpp +++ b/source/gui/MiniMap.cpp @@ -42,9 +42,9 @@ static float m_scaleX, m_scaleY; static unsigned int ScaleColor(unsigned int color, float x) { - unsigned int r = uint(float(color & 0xff) * x); - unsigned int g = uint(float((color>>8) & 0xff) * x); - unsigned int b = uint(float((color>>16) & 0xff) * x); + unsigned int r = unsigned int(float(color & 0xff) * x); + unsigned int g = unsigned int(float((color>>8) & 0xff) * x); + unsigned int b = unsigned int(float((color>>16) & 0xff) * x); return (0xff000000 | r | g<<8 | b<<16); } @@ -151,7 +151,7 @@ void CMiniMap::SetCameraPos() } m_Camera->UpdateFrustum(); } -void CMiniMap::FireWorldClickEvent(uint button, int clicks) +void CMiniMap::FireWorldClickEvent(int button, int clicks) { //debug_printf("FireWorldClickEvent: button %d, clicks %d\n", button, clicks); @@ -269,7 +269,7 @@ void CMiniMap::Draw() last_time = cur_time; CLOSManager* losMgr = g_Game->GetWorld()->GetLOSManager(); - if(losMgr->m_LOSSetting != CLOSManager::ALL_VISIBLE) + if(losMgr->m_LOSSetting != LOS_SETTING_ALL_VISIBLE) RebuildLOSTexture(); } @@ -457,7 +457,7 @@ void CMiniMap::CreateTextures() Destroy(); // Create terrain texture - glGenTextures(1, (GLuint *)&m_TerrainTexture); + glGenTextures(1, &m_TerrainTexture); g_Renderer.BindTexture(0, m_TerrainTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_TextureSize, m_TextureSize, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, 0); m_TerrainData = new u32[(m_MapSize - 1) * (m_MapSize - 1)]; @@ -467,7 +467,7 @@ void CMiniMap::CreateTextures() glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP); // Create LOS texture - glGenTextures(1, (GLuint *)&m_LOSTexture); + glGenTextures(1, &m_LOSTexture); g_Renderer.BindTexture(0, m_LOSTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA8, m_TextureSize, m_TextureSize, 0, GL_ALPHA, GL_UNSIGNED_BYTE, 0); m_LOSData = new u8[(m_MapSize - 1) * (m_MapSize - 1)]; @@ -541,28 +541,23 @@ void CMiniMap::RebuildLOSTexture() CLOSManager* losMgr = g_Game->GetWorld()->GetLOSManager(); CPlayer* player = g_Game->GetLocalPlayer(); - u32 x = 0; - u32 y = 0; - u32 w = m_MapSize - 1; - u32 h = m_MapSize - 1; + ssize_t x = 0; + ssize_t y = 0; + ssize_t w = m_MapSize - 1; + ssize_t h = m_MapSize - 1; - for(u32 j = 0; j < h; j++) + for(ssize_t j = 0; j < h; j++) { u8 *dataPtr = m_LOSData + ((y + j) * (m_MapSize - 1)) + x; - for(u32 i = 0; i < w; i++) + for(ssize_t i = 0; i < w; i++) { - ELOSStatus status = losMgr->GetStatus((int) i, (int) j, player); + ELOSStatus status = losMgr->GetStatus(i, j, player); if(status == LOS_UNEXPLORED) - { *dataPtr++ = 0xff; - } else if(status == LOS_EXPLORED) - { *dataPtr++ = (u8) (0xff * 0.3f); - } - else { + else *dataPtr++ = 0; - } } } @@ -576,10 +571,10 @@ void CMiniMap::RebuildLOSTexture() void CMiniMap::Destroy() { if(m_TerrainTexture) - glDeleteTextures(1, (GLuint *)&m_TerrainTexture); + glDeleteTextures(1, &m_TerrainTexture); if(m_LOSTexture) - glDeleteTextures(1, (GLuint *)&m_LOSTexture); + glDeleteTextures(1, &m_LOSTexture); delete[] m_TerrainData; m_TerrainData = 0; delete[] m_LOSData; m_LOSData = 0; diff --git a/source/gui/MiniMap.h b/source/gui/MiniMap.h index 0f26e8f9d1..6b52d94e80 100644 --- a/source/gui/MiniMap.h +++ b/source/gui/MiniMap.h @@ -36,7 +36,7 @@ protected: void SetCameraPos(); - void FireWorldClickEvent(uint button, int clicks); + void FireWorldClickEvent(int button, int clicks); // calculate the relative heightmap space coordinates // for a units world position @@ -55,20 +55,20 @@ protected: bool m_Clicking; // minimap texture handles - u32 m_TerrainTexture; - u32 m_LOSTexture; + GLuint m_TerrainTexture; + GLuint m_LOSTexture; // texture data - u32 *m_TerrainData; - u8 *m_LOSData; + u32* m_TerrainData; + u8* m_LOSData; - u32 m_Width, m_Height; + ssize_t m_Width, m_Height; // map size - u32 m_MapSize; + ssize_t m_MapSize; // texture size - u32 m_TextureSize; + GLsizei m_TextureSize; void DrawViewRect(); // split out of Draw }; diff --git a/source/gui/scripting/JSInterface_GUITypes.cpp b/source/gui/scripting/JSInterface_GUITypes.cpp index 3453463920..9aa5feb82f 100644 --- a/source/gui/scripting/JSInterface_GUITypes.cpp +++ b/source/gui/scripting/JSInterface_GUITypes.cpp @@ -33,7 +33,7 @@ JSFunctionSpec JSI_GUISize::JSI_methods[] = { 0 } }; -JSBool JSI_GUISize::construct(JSContext* cx, JSObject* obj, uint argc, jsval* argv, jsval* UNUSED(rval)) +JSBool JSI_GUISize::construct(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* UNUSED(rval)) { if (argc == 8) { @@ -137,7 +137,7 @@ JSFunctionSpec JSI_GUIColor::JSI_methods[] = { 0 } }; -JSBool JSI_GUIColor::construct(JSContext* cx, JSObject* obj, uint argc, jsval* argv, jsval* UNUSED(rval)) +JSBool JSI_GUIColor::construct(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* UNUSED(rval)) { if (argc == 4) { @@ -201,7 +201,7 @@ JSFunctionSpec JSI_GUIMouse::JSI_methods[] = { 0 } }; -JSBool JSI_GUIMouse::construct(JSContext* cx, JSObject* obj, uint argc, jsval* argv, jsval* UNUSED(rval)) +JSBool JSI_GUIMouse::construct(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* UNUSED(rval)) { if (argc == 3) { diff --git a/source/gui/scripting/JSInterface_GUITypes.h b/source/gui/scripting/JSInterface_GUITypes.h index 12464d76df..d8c4ee19b6 100644 --- a/source/gui/scripting/JSInterface_GUITypes.h +++ b/source/gui/scripting/JSInterface_GUITypes.h @@ -9,9 +9,9 @@ extern JSClass JSI_class; \ extern JSPropertySpec JSI_props[]; \ extern JSFunctionSpec JSI_methods[]; \ - JSBool construct( JSContext* cx, JSObject* obj, uint argc, jsval* argv, jsval* rval ); \ - JSBool getByName( JSContext* cx, JSObject* obj, uint argc, jsval* argv, jsval* rval ); \ - JSBool toString( JSContext* cx, JSObject* obj, uint argc, jsval* argv, jsval* rval ); \ + JSBool construct( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval ); \ + JSBool getByName( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval ); \ + JSBool toString( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval ); \ } GUISTDTYPE(Size) diff --git a/source/gui/scripting/JSInterface_IGUIObject.cpp b/source/gui/scripting/JSInterface_IGUIObject.cpp index 095834fe91..863fdc951b 100644 --- a/source/gui/scripting/JSInterface_IGUIObject.cpp +++ b/source/gui/scripting/JSInterface_IGUIObject.cpp @@ -522,7 +522,7 @@ JSBool JSI_IGUIObject::setProperty(JSContext* cx, JSObject* obj, jsval id, jsval } -JSBool JSI_IGUIObject::construct(JSContext* cx, JSObject* obj, uint argc, jsval* argv, jsval* UNUSED(rval)) +JSBool JSI_IGUIObject::construct(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* UNUSED(rval)) { if (argc == 0) { @@ -540,7 +540,7 @@ JSBool JSI_IGUIObject::construct(JSContext* cx, JSObject* obj, uint argc, jsval* } -JSBool JSI_IGUIObject::getByName(JSContext* cx, JSObject* UNUSED(obj), uint argc, jsval* argv, jsval* rval) +JSBool JSI_IGUIObject::getByName(JSContext* cx, JSObject* UNUSED(obj), uintN argc, jsval* argv, jsval* rval) { debug_assert(argc == 1); diff --git a/source/gui/scripting/JSInterface_IGUIObject.h b/source/gui/scripting/JSInterface_IGUIObject.h index cd85060e80..b3926bbc61 100644 --- a/source/gui/scripting/JSInterface_IGUIObject.h +++ b/source/gui/scripting/JSInterface_IGUIObject.h @@ -12,9 +12,9 @@ namespace JSI_IGUIObject JSBool delProperty(JSContext* cx, JSObject* obj, jsval id, jsval* vp); JSBool getProperty(JSContext* cx, JSObject* obj, jsval id, jsval* vp); JSBool setProperty(JSContext* cx, JSObject* obj, jsval id, jsval* vp); - JSBool construct(JSContext* cx, JSObject* obj, uint argc, jsval* argv, jsval* rval); - JSBool getByName(JSContext* cx, JSObject* obj, uint argc, jsval* argv, jsval* rval); - JSBool toString(JSContext* cx, JSObject* obj, uint argc, jsval* argv, jsval* rval); + JSBool construct(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval); + JSBool getByName(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval); + JSBool toString(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval); void init(); } diff --git a/source/lib/adts.h b/source/lib/adts.h index 1d6fc1425f..f871e8eded 100644 --- a/source/lib/adts.h +++ b/source/lib/adts.h @@ -12,6 +12,7 @@ #define INCLUDED_ADTS #include "lib/fnv_hash.h" +#include "lib/bits.h" //----------------------------------------------------------------------------- @@ -59,7 +60,7 @@ class DynHashTbl { size_t hash = tr.hash(key); debug_assert(max_entries != 0); // otherwise, mask will be incorrect - const uint mask = max_entries-1; + const size_t mask = max_entries-1; for(;;) { T& t = tbl[hash & mask]; @@ -228,9 +229,9 @@ public: struct BitBuf { - ulong buf; - ulong cur; // bit to be appended (toggled by add()) - ulong len; // |buf| [bits] + uintptr_t buf; + uintptr_t cur; // bit to be appended (toggled by add()) + size_t len; // |buf| [bits] void reset() { @@ -240,7 +241,7 @@ struct BitBuf } // toggle current bit if desired, and add to buffer (new bit is LSB) - void add(ulong toggle) + void add(uintptr_t toggle) { cur ^= toggle; buf <<= 1; @@ -249,12 +250,12 @@ struct BitBuf } // extract LS n bits - uint extract(ulong n) + size_t extract(uintptr_t n) { - ulong i = buf & ((1ul << n) - 1); + const uintptr_t bits = buf & bit_mask(n); buf >>= n; - return i; + return bits; } }; @@ -475,7 +476,7 @@ class MateiHashTbl { size_t hash = hashFunc(key); //debug_assert(max_entries != 0); // otherwise, mask will be incorrect - const uint mask = max_entries-1; + const size_t mask = max_entries-1; int stride = 1; // for quadratic probing for(;;) { diff --git a/source/lib/allocators/allocators.cpp b/source/lib/allocators/allocators.cpp index afbb327948..29a4f70fc1 100644 --- a/source/lib/allocators/allocators.cpp +++ b/source/lib/allocators/allocators.cpp @@ -45,7 +45,7 @@ void page_aligned_free(void* p, size_t unaligned_size) // matrix allocator //----------------------------------------------------------------------------- -void** matrix_alloc(uint cols, uint rows, size_t el_size) +void** matrix_alloc(size_t cols, size_t rows, size_t el_size) { const size_t initial_align = 64; // note: no provision for padding rows. this is a bit more work and @@ -68,7 +68,7 @@ void** matrix_alloc(uint cols, uint rows, size_t el_size) debug_assert(data_addr >= (uintptr_t)p+ptr_array_size); void** ptr_array = (void**)p; - for(uint i = 0; i < cols; i++) + for(size_t i = 0; i < cols; i++) { ptr_array[i] = (void*)data_addr; data_addr += row_size; diff --git a/source/lib/allocators/allocators.h b/source/lib/allocators/allocators.h index a911ad16ad..bfdcccaf89 100644 --- a/source/lib/allocators/allocators.h +++ b/source/lib/allocators/allocators.h @@ -65,7 +65,7 @@ LIB_API void page_aligned_free(void* p, size_t unaligned_size); * @return 0 if out of memory, otherwise matrix that should be cast to * type** (sizeof(type) == el_size). must be freed via matrix_free. **/ -extern void** matrix_alloc(uint cols, uint rows, size_t el_size); +extern void** matrix_alloc(size_t cols, size_t rows, size_t el_size); /** * free the given matrix. diff --git a/source/lib/allocators/bucket.h b/source/lib/allocators/bucket.h index 3b53b891a3..9ece4355b0 100644 --- a/source/lib/allocators/bucket.h +++ b/source/lib/allocators/bucket.h @@ -46,7 +46,7 @@ struct LIB_API Bucket /** * records # buckets allocated; verifies the list of buckets is correct. **/ - uint num_buckets; + size_t num_buckets; }; diff --git a/source/lib/allocators/headerless.cpp b/source/lib/allocators/headerless.cpp index 4af1c04848..01d726c2a8 100644 --- a/source/lib/allocators/headerless.cpp +++ b/source/lib/allocators/headerless.cpp @@ -270,7 +270,7 @@ public: void Insert(FreedBlock* freedBlock) { - const uint sizeClass = SizeClass(freedBlock->Size()); + const size_t sizeClass = SizeClass(freedBlock->Size()); m_rangeLists[sizeClass].Insert(freedBlock); m_bitmap |= BIT(sizeClass); @@ -283,13 +283,13 @@ public: { // iterate over all large enough, non-empty size classes // (zero overhead for empty size classes) - const uint minSizeClass = SizeClass(minSize); - uint sizeClassBits = m_bitmap & (~0u << minSizeClass); + const size_t minSizeClass = SizeClass(minSize); + size_t sizeClassBits = m_bitmap & (~0u << minSizeClass); while(sizeClassBits) { - const uint size = ValueOfLeastSignificantOneBit(sizeClassBits); + const size_t size = ValueOfLeastSignificantOneBit(sizeClassBits); sizeClassBits &= ~size; // remove from sizeClassBits - const uint sizeClass = SizeClass(size); + const size_t sizeClass = SizeClass(size); FreedBlock* freedBlock = m_rangeLists[sizeClass].Find(minSize); if(freedBlock) @@ -304,7 +304,7 @@ public: void Remove(FreedBlock* freedBlock) { - const uint sizeClass = SizeClass(freedBlock->Size()); + const size_t sizeClass = SizeClass(freedBlock->Size()); m_rangeLists[sizeClass].Remove(freedBlock); // (masking with !IsEmpty() << sizeClass would probably be faster) @@ -344,9 +344,9 @@ private: * @return "size class" of a given size. * class i > 0 contains blocks of size (2**(i-1), 2**i]. **/ - static uint SizeClass(size_t size) + static size_t SizeClass(size_t size) { - return ceil_log2((uint)size); + return ceil_log2((size_t)size); } static uintptr_t ValueOfLeastSignificantOneBit(uintptr_t x) diff --git a/source/lib/allocators/string_pool.cpp b/source/lib/allocators/string_pool.cpp index 1c8cce035a..c8ab89efaf 100644 --- a/source/lib/allocators/string_pool.cpp +++ b/source/lib/allocators/string_pool.cpp @@ -68,7 +68,7 @@ const char* StringPool::RandomString() const debug_assert(m_pool.da.pos != 0); again: - const size_t start_ofs = (size_t)rand(0, (uint)m_pool.da.pos); + const size_t start_ofs = (size_t)rand(0, (size_t)m_pool.da.pos); // scan back to start of string (don't scan ahead; this must // work even if m_pool only contains one entry). diff --git a/source/lib/app_hooks.cpp b/source/lib/app_hooks.cpp index a6cf98ba94..c21503a49f 100644 --- a/source/lib/app_hooks.cpp +++ b/source/lib/app_hooks.cpp @@ -59,7 +59,7 @@ static void def_log(const wchar_t* text) } -static ErrorReaction def_display_error(const wchar_t* UNUSED(text), uint UNUSED(flags)) +static ErrorReaction def_display_error(const wchar_t* UNUSED(text), int UNUSED(flags)) { return ER_NOT_IMPLEMENTED; } @@ -153,7 +153,7 @@ void ah_log(const wchar_t* text) ah.log(text); } -ErrorReaction ah_display_error(const wchar_t* text, uint flags) +ErrorReaction ah_display_error(const wchar_t* text, int flags) { return ah.display_error(text, flags); } diff --git a/source/lib/app_hooks.h b/source/lib/app_hooks.h index 44db5a6a7d..11fa6c9377 100644 --- a/source/lib/app_hooks.h +++ b/source/lib/app_hooks.h @@ -154,7 +154,7 @@ extern void ah_log(const wchar_t* text); * the default implementation just returns ER_NOT_IMPLEMENTED, which * causes the normal sys_display_error to be used. **/ -extern ErrorReaction ah_display_error(const wchar_t* text, uint flags); +extern ErrorReaction ah_display_error(const wchar_t* text, int flags); /** @@ -169,7 +169,7 @@ struct AppHooks const wchar_t* (*translate)(const wchar_t* text); void (*translate_free)(const wchar_t* text); void (*log)(const wchar_t* text); - ErrorReaction (*display_error)(const wchar_t* text, uint flags); + ErrorReaction (*display_error)(const wchar_t* text, int flags); }; /** diff --git a/source/lib/base32.cpp b/source/lib/base32.cpp index 9e6d2b609d..97a6bf9546 100644 --- a/source/lib/base32.cpp +++ b/source/lib/base32.cpp @@ -15,7 +15,7 @@ void base32(const size_t in_len, const u8* in, u8* out) { u32 pool = 0; // of bits from buffer - uint pool_bits = 0; // # bits currently in buffer + size_t pool_bits = 0; // # bits currently in buffer static const u8 tbl[33] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; @@ -32,7 +32,7 @@ void base32(const size_t in_len, const u8* in, u8* out) } pool_bits -= 5; - const uint c = (pool >> pool_bits) & 31; + const size_t c = (pool >> pool_bits) & 31; *out++ = tbl[c]; } diff --git a/source/lib/bits.cpp b/source/lib/bits.cpp index ff41a09cfb..bae207bad6 100644 --- a/source/lib/bits.cpp +++ b/source/lib/bits.cpp @@ -11,54 +11,9 @@ #include "precompiled.h" #include "bits.h" -#if ARCH_IA32 -# include "lib/sysdep/ia32/ia32_asm.h" // ia32_asm_log2_of_pow2 -#endif - - -int log2_of_pow2(uint n) -{ - int bit_index; - -#if ARCH_IA32 - bit_index = ia32_asm_log2_of_pow2(n); -#else - if(!is_pow2(n)) - bit_index = -1; - else - { - bit_index = 0; - // note: compare against n directly because it is known to be a POT. - for(uint bit_value = 1; bit_value != n; bit_value *= 2) - bit_index++; - } -#endif - - debug_assert(-1 <= bit_index && bit_index < (int)sizeof(int)*CHAR_BIT); - debug_assert(bit_index == -1 || n == (1u << bit_index)); - return bit_index; -} - - int floor_log2(const float x) { const u32 i = *(u32*)&x; u32 biased_exp = (i >> 23) & 0xFF; return (int)biased_exp - 127; } - - -uint round_up_to_pow2(uint x) -{ - // fold upper bit into lower bits; leaves same MSB set but - // everything below it 1. adding 1 yields next POT. - x |= (x >> 1); - x |= (x >> 2); - x |= (x >> 4); - x |= (x >> 8); - x |= (x >> 16); - // if ints are 64 bits, add "x |= (x >> 32);" - cassert(sizeof(int)*CHAR_BIT == 32); - - return x+1; -} diff --git a/source/lib/bits.h b/source/lib/bits.h index 7cc960b01e..0f5a164240 100644 --- a/source/lib/bits.h +++ b/source/lib/bits.h @@ -36,15 +36,12 @@ * * @param num_bits number of bits in mask **/ -inline uint bit_mask(uint num_bits) +template +T bit_mask(size_t num_bits) { - return (1u << num_bits)-1; + return (T)(T(1) << num_bits)-1; } -inline u64 bit_mask64(uint num_bits) -{ - return (1ull << num_bits)-1; -} /** * extract the value of bits hi_idx:lo_idx within num @@ -56,57 +53,64 @@ inline u64 bit_mask64(uint num_bits) * @param hi_idx bit index of highest bit to include * @return value of extracted bits. **/ -inline uint bits(uint num, uint lo_idx, uint hi_idx) +template +inline T bits(T num, size_t lo_idx, size_t hi_idx) { - const uint count = (hi_idx - lo_idx)+1; // # bits to return - uint result = num >> lo_idx; - result &= bit_mask(count); + const size_t count = (hi_idx - lo_idx)+1; // # bits to return + T result = num >> lo_idx; + result &= bit_mask(count); return result; } -inline u64 bits64(u64 num, uint lo_idx, uint hi_idx) +/** + * @return number of 1-bits in mask + **/ +template +size_t PopulationCount(T mask) { - const uint count = (hi_idx - lo_idx)+1; // # bits to return - u64 result = num >> lo_idx; - result &= bit_mask64(count); - return result; + // note: a more complex but probably faster method is given at + // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel + + size_t num1Bits = 0; + while(mask) + { + mask &= mask-1; // clear least significant 1-bit + num1Bits++; + } + + return num1Bits; } /** * @return whether the given number is a power of two. **/ -inline bool is_pow2(uint n) +template +bool is_pow2(T n) { // 0 would pass the test below but isn't a POT. if(n == 0) return false; - return (n & (n-1ul)) == 0; + return (n & (n-1)) == 0; } - -/** - * @return the (integral) base 2 logarithm, or -1 if the number - * is not a power-of-two. - **/ -extern int log2_of_pow2(uint n); - /** * ceil(log2(n)) * * @param n (integer) input; MUST be > 0, else results are undefined. * @return ceiling of the base-2 logarithm (i.e. rounded up). **/ -inline uint ceil_log2(uint x) +template +size_t ceil_log2(T x) { - uint bit = 1; - uint l = 0; + T bit = 1; + size_t log = 0; while(bit < x && bit != 0) // must detect overflow { - l++; - bit += bit; + log++; + bit *= 2; } - return l; + return log; } @@ -122,7 +126,11 @@ extern int floor_log2(const float x); /** * round up to next larger power of two. **/ -extern uint round_up_to_pow2(uint x); +template +T round_up_to_pow2(T x) +{ + return T(1) << ceil_log2(x); +} /** * round number up/down to the next given multiple. @@ -132,7 +140,7 @@ extern uint round_up_to_pow2(uint x); template T round_up(T n, T multiple) { - debug_assert(is_pow2((uint)multiple)); + debug_assert(is_pow2(multiple)); const T result = (n + multiple-1) & ~(multiple-1); debug_assert(n <= result && result < n+multiple); return result; @@ -141,7 +149,7 @@ T round_up(T n, T multiple) template T round_down(T n, T multiple) { - debug_assert(is_pow2((uint)multiple)); + debug_assert(is_pow2(multiple)); const T result = n & ~(multiple-1); debug_assert(result <= n && n < result+multiple); return result; diff --git a/source/lib/byte_order.cpp b/source/lib/byte_order.cpp index ca7c67891a..2f423008f7 100644 --- a/source/lib/byte_order.cpp +++ b/source/lib/byte_order.cpp @@ -167,7 +167,7 @@ void write_be64(void* p, u64 x) u64 movzx_le64(const u8* p, size_t size_bytes) { u64 number = 0; - for(uint i = 0; i < std::min(size_bytes, (size_t)8u); i++) + for(size_t i = 0; i < std::min(size_bytes, (size_t)8u); i++) number |= ((u64)p[i]) << (i*8); return number; @@ -176,7 +176,7 @@ u64 movzx_le64(const u8* p, size_t size_bytes) u64 movzx_be64(const u8* p, size_t size_bytes) { u64 number = 0; - for(uint i = 0; i < std::min(size_bytes, (size_t)8u); i++) + for(size_t i = 0; i < std::min(size_bytes, (size_t)8u); i++) { number <<= 8; number |= p[i]; diff --git a/source/lib/cache_adt.h b/source/lib/cache_adt.h index 2ecb24fc31..c21dcd19c0 100644 --- a/source/lib/cache_adt.h +++ b/source/lib/cache_adt.h @@ -603,7 +603,7 @@ template struct CacheEntry { Item item; size_t size; - uint cost; + size_t cost; float credit; Divider divider; @@ -613,7 +613,7 @@ template struct CacheEntry { } - CacheEntry(Item item_, size_t size_, uint cost_) + CacheEntry(Item item_, size_t size_, size_t cost_) : item(item_), divider((float)size_) { size = size_; @@ -647,7 +647,7 @@ class Cache public: Cache() : mgr() {} - void add(Key key, Item item, size_t size, uint cost) + void add(Key key, Item item, size_t size, size_t cost) { return mgr.add(key, Entry(item, size, cost)); } diff --git a/source/lib/config2.h b/source/lib/config2.h index cd3a46dafe..21388758bf 100644 --- a/source/lib/config2.h +++ b/source/lib/config2.h @@ -16,13 +16,6 @@ // configuration choices, so rebuilding them all is acceptable. // use config.h when settings must apply to the entire project. -// (only applicable if ARCH_IA32) 64-bit values will be returned in EDX:EAX. -// this chiefly affects ia32_rdtsc. if not set, a safer but slower fallback -// will be used that doesn't assume anything about return convention. -#ifndef CONFIG2_IA32_RETURN64_EDX_EAX -# define CONFIG2_IA32_RETURN64_EDX_EAX 1 -#endif - // allow use of RDTSC for raw tick counts (otherwise, the slower but // more reliable on MP systems wall-clock will be used). #ifndef CONFIG2_TIMER_ALLOW_RDTSC diff --git a/source/lib/debug.cpp b/source/lib/debug.cpp index bfd996b9fe..d2d649dd88 100644 --- a/source/lib/debug.cpp +++ b/source/lib/debug.cpp @@ -86,16 +86,16 @@ void debug_wprintf_mem(const wchar_t* fmt, ...) // rationale: static data instead of std::set to allow setting at any time. // we store FNV hash of tag strings for fast comparison; collisions are // extremely unlikely and can only result in displaying more/less text. -static const uint MAX_TAGS = 20; +static const size_t MAX_TAGS = 20; static u32 tags[MAX_TAGS]; -static uint num_tags; +static size_t num_tags; void debug_filter_add(const char* tag) { const u32 hash = fnv_hash(tag); // make sure it isn't already in the list - for(uint i = 0; i < MAX_TAGS; i++) + for(size_t i = 0; i < MAX_TAGS; i++) if(tags[i] == hash) return; @@ -113,7 +113,7 @@ void debug_filter_remove(const char* tag) { const u32 hash = fnv_hash(tag); - for(uint i = 0; i < MAX_TAGS; i++) + for(size_t i = 0; i < MAX_TAGS; i++) // found it if(tags[i] == hash) { @@ -133,7 +133,7 @@ void debug_filter_clear() bool debug_filter_allows(const char* text) { - uint i; + size_t i; for(i = 0; ; i++) { // no | found => no tag => should always be displayed @@ -252,7 +252,7 @@ void debug_error_message_free(ErrorMessageMem* emm) const wchar_t* debug_error_message_build( const wchar_t* description, const char* fn_only, int line, const char* func, - uint skip, void* context, + size_t skip, void* context, ErrorMessageMem* emm) { // rationale: see ErrorMessageMem @@ -324,7 +324,7 @@ fail: return buf; } -static ErrorReaction call_display_error(const wchar_t* text, uint flags) +static ErrorReaction call_display_error(const wchar_t* text, int flags) { // first try app hook implementation ErrorReaction er = ah_display_error(text, flags); @@ -335,7 +335,7 @@ static ErrorReaction call_display_error(const wchar_t* text, uint flags) return er; } -static ErrorReaction carry_out_ErrorReaction(ErrorReaction er, uint flags, u8* suppress) +static ErrorReaction carry_out_ErrorReaction(ErrorReaction er, int flags, u8* suppress) { const bool manual_break = (flags & DE_MANUAL_BREAK) != 0; @@ -372,7 +372,7 @@ static ErrorReaction carry_out_ErrorReaction(ErrorReaction er, uint flags, u8* s } ErrorReaction debug_display_error(const wchar_t* description, - uint flags, uint skip, void* context, + int flags, size_t skip, void* context, const char* file, int line, const char* func, u8* suppress) { @@ -471,7 +471,7 @@ ErrorReaction debug_assert_failed(const char* expr, u8* suppress, { if(should_skip_this_assert()) return ER_CONTINUE; - uint skip = 1; void* context = 0; + size_t skip = 1; void* context = 0; wchar_t buf[400]; swprintf(buf, ARRAY_SIZE(buf), L"Assertion failed: \"%hs\"", expr); return debug_display_error(buf, DE_MANUAL_BREAK, skip,context, file,line,func, suppress); @@ -484,7 +484,7 @@ ErrorReaction debug_warn_err(LibError err, u8* suppress, if(should_skip_this_error(err)) return ER_CONTINUE; - uint skip = 1; void* context = 0; + size_t skip = 1; void* context = 0; wchar_t buf[400]; char err_buf[200]; error_description_r(err, err_buf, ARRAY_SIZE(err_buf)); swprintf(buf, ARRAY_SIZE(buf), L"Function call failed: return value was %d (%hs)", err, err_buf); diff --git a/source/lib/debug.h b/source/lib/debug.h index babf6d44ff..a99c249b6a 100644 --- a/source/lib/debug.h +++ b/source/lib/debug.h @@ -147,7 +147,7 @@ enum ErrorReaction * @return ErrorReaction (user's choice: continue running or stop?) **/ LIB_API ErrorReaction debug_display_error(const wchar_t* description, - uint flags, uint skip, void* context, + int flags, size_t skip, void* context, const char* file, int line, const char* func, u8* suppress); @@ -436,7 +436,7 @@ LIB_API LibError debug_resolve_symbol(void* ptr_of_interest, char* sym_name, cha * @return LibError; ERR::REENTERED if reentered via recursion or * multithreading (not allowed since static data is used). **/ -LIB_API LibError debug_dump_stack(wchar_t* buf, size_t max_chars, uint skip, void* context); +LIB_API LibError debug_dump_stack(wchar_t* buf, size_t max_chars, size_t skip, void* context); //----------------------------------------------------------------------------- @@ -461,7 +461,7 @@ LIB_API void debug_puts(const char* text); * * note: this does not access debug symbols and is therefore quite fast. **/ -LIB_API void* debug_get_nth_caller(uint skip, void* context); +LIB_API void* debug_get_nth_caller(size_t skip, void* context); /** * check if a pointer appears to be totally invalid. @@ -532,7 +532,7 @@ LIB_API void debug_error_message_free(ErrorMessageMem* emm); LIB_API const wchar_t* debug_error_message_build( const wchar_t* description, const char* fn_only, int line, const char* func, - uint skip, void* context, + size_t skip, void* context, ErrorMessageMem* emm); #endif // #ifndef INCLUDED_DEBUG diff --git a/source/lib/debug_stl.cpp b/source/lib/debug_stl.cpp index 01a0ca034d..dad281ac34 100644 --- a/source/lib/debug_stl.cpp +++ b/source/lib/debug_stl.cpp @@ -109,7 +109,7 @@ char* debug_stl_simplify_name(char* name) src += 7; } REPLACE("unsigned short", "u16") - REPLACE("unsigned int", "uint") + REPLACE("unsigned int", "size_t") REPLACE("unsigned __int64", "u64") STRIP(",0> ") // early out: all tests after this start with s, so skip them diff --git a/source/lib/fat_time.cpp b/source/lib/fat_time.cpp index bbac911dcb..d92c1af8fb 100644 --- a/source/lib/fat_time.cpp +++ b/source/lib/fat_time.cpp @@ -18,8 +18,8 @@ time_t time_t_from_FAT(u32 fat_timedate) { - const uint fat_time = bits(fat_timedate, 0, 15); - const uint fat_date = bits(fat_timedate, 16, 31); + const u32 fat_time = bits(fat_timedate, 0, 15); + const u32 fat_date = bits(fat_timedate, 16, 31); struct tm t; // struct tm format: t.tm_sec = bits(fat_time, 0,4) * 2; // [0,59] diff --git a/source/lib/file/archive/archive_builder.cpp b/source/lib/file/archive/archive_builder.cpp index 648edbc9ab..3580e6152a 100644 --- a/source/lib/file/archive/archive_builder.cpp +++ b/source/lib/file/archive/archive_builder.cpp @@ -187,7 +187,7 @@ struct Connection // repeated edges ("connections") are reflected in // the 'occurrences' count; we optimize the ordering so that // files with frequent connections are nearby. - uint occurrences; + size_t occurrences; Connection(ConnectionId id_) : id(id_), occurrences(1) {} @@ -267,7 +267,7 @@ class ConnectionBuilder for(size_t r = 0; r < t.num_runs; r++) { const TraceRun& run = t.runs[r]; - for(uint i = 0; i < run.num_ents; i++) + for(size_t i = 0; i < run.num_ents; i++) { const TraceEntry* te = &run.ents[i]; // improvement: postprocess the trace and remove all IOs that would be @@ -1090,7 +1090,7 @@ LibError trace_run(const char* osPathname) { Trace trace; RETURN_ERR(trace.Load(osPathname)); - for(uint i = 0; i < trace.NumEntries(); i++) + for(size_t i = 0; i < trace.NumEntries(); i++) trace.Entries()[i]->Run(); return INFO::OK; } diff --git a/source/lib/file/archive/archive_zip.cpp b/source/lib/file/archive/archive_zip.cpp index 407c0e3820..cc2d2bdff4 100644 --- a/source/lib/file/archive/archive_zip.cpp +++ b/source/lib/file/archive/archive_zip.cpp @@ -111,7 +111,7 @@ public: m_usize = to_le32(u32_from_larger(fileInfo.Size())); m_fn_len = to_le16(u16_from_larger(pathnameString.length())); m_e_len = to_le16(0); - m_c_len = to_le16(u16_from_larger((uint)slack)); + m_c_len = to_le16(u16_from_larger((size_t)slack)); m_x2 = to_le32(0); m_x3 = to_le32(0); m_lfh_ofs = to_le32(ofs); @@ -189,7 +189,7 @@ cassert(sizeof(CDFH) == 46); class ECDR { public: - void Init(uint cd_numEntries, off_t cd_ofs, off_t cd_size) + void Init(size_t cd_numEntries, off_t cd_ofs, off_t cd_size) { m_magic = ecdr_magic; memset(m_x1, 0, sizeof(m_x1)); @@ -199,9 +199,9 @@ public: m_comment_len = to_le16(0); } - void Decompose(uint& cd_numEntries, off_t& cd_ofs, off_t& cd_size) const + void Decompose(size_t& cd_numEntries, off_t& cd_ofs, off_t& cd_size) const { - cd_numEntries = (uint)read_le16(&m_cd_numEntries); + cd_numEntries = (size_t)read_le16(&m_cd_numEntries); cd_ofs = (off_t)read_le32(&m_cd_ofs); cd_size = (off_t)read_le32(&m_cd_size); } @@ -234,7 +234,7 @@ public: { } - virtual unsigned Precedence() const + virtual size_t Precedence() const { return 2u; } @@ -370,7 +370,7 @@ public: virtual LibError ReadEntries(ArchiveEntryCallback cb, uintptr_t cbData) { // locate and read Central Directory - off_t cd_ofs; uint cd_numEntries; off_t cd_size; + off_t cd_ofs; size_t cd_numEntries; off_t cd_size; RETURN_ERR(LocateCentralDirectory(m_file, m_fileSize, cd_ofs, cd_numEntries, cd_size)); shared_ptr buf = io_Allocate(cd_size, cd_ofs); u8* cd; @@ -378,7 +378,7 @@ public: // iterate over Central Directory const u8* pos = cd; - for(uint i = 0; i < cd_numEntries; i++) + for(size_t i = 0; i < cd_numEntries; i++) { // scan for next CDFH CDFH* cdfh = (CDFH*)FindRecord(cd, cd_size, pos, cdfh_magic, sizeof(CDFH)); @@ -435,7 +435,7 @@ private: // search for ECDR in the last bytes of the file. // if found, fill with a copy of the (little-endian) ECDR and // return INFO::OK, otherwise IO error or ERR::CORRUPTED. - static LibError ScanForEcdr(PIFile file, off_t fileSize, u8* buf, off_t maxScanSize, uint& cd_numEntries, off_t& cd_ofs, off_t& cd_size) + static LibError ScanForEcdr(PIFile file, off_t fileSize, u8* buf, off_t maxScanSize, size_t& cd_numEntries, off_t& cd_ofs, off_t& cd_size) { // don't scan more than the entire file const off_t scanSize = std::min(maxScanSize, fileSize); @@ -454,7 +454,7 @@ private: return INFO::OK; } - static LibError LocateCentralDirectory(PIFile file, off_t fileSize, off_t& cd_ofs, uint& cd_numEntries, off_t& cd_size) + static LibError LocateCentralDirectory(PIFile file, off_t fileSize, off_t& cd_ofs, size_t& cd_numEntries, off_t& cd_size) { const off_t maxScanSize = 66000u; // see below shared_ptr buf = io_Allocate(maxScanSize, BLOCK_SIZE-1); // assume worst-case for alignment @@ -616,7 +616,7 @@ private: "ogg", "mp3" }; - for(uint i = 0; i < ARRAY_SIZE(incompressibleExtensions); i++) + for(size_t i = 0; i < ARRAY_SIZE(incompressibleExtensions); i++) { if(!strcasecmp(extension, incompressibleExtensions[i])) return true; @@ -630,7 +630,7 @@ private: UnalignedWriter m_unalignedWriter; Pool m_cdfhPool; - uint m_numEntries; + size_t m_numEntries; }; PIArchiveWriter CreateArchiveWriter_Zip(const Path& archivePathname) diff --git a/source/lib/file/common/file_loader.h b/source/lib/file/common/file_loader.h index 0276c0a4fb..90e084362b 100644 --- a/source/lib/file/common/file_loader.h +++ b/source/lib/file/common/file_loader.h @@ -5,7 +5,7 @@ struct IFileLoader { virtual ~IFileLoader(); - virtual unsigned Precedence() const = 0; + virtual size_t Precedence() const = 0; virtual char LocationCode() const = 0; virtual LibError Load(const std::string& name, shared_ptr buf, size_t size) const = 0; diff --git a/source/lib/file/common/file_stats.cpp b/source/lib/file/common/file_stats.cpp index f3d8bc09b5..78ceb16a25 100644 --- a/source/lib/file/common/file_stats.cpp +++ b/source/lib/file/common/file_stats.cpp @@ -17,37 +17,37 @@ // vfs -static uint vfs_files; +static size_t vfs_files; static size_t vfs_size_total; static double vfs_init_elapsed_time; // file -static uint unique_names; +static size_t unique_names; static size_t unique_name_len_total; -static uint open_files_cur, open_files_max; // total = opened_files.size() +static size_t open_files_cur, open_files_max; // total = opened_files.size() // file_buf -static uint extant_bufs_cur, extant_bufs_max, extant_bufs_total; +static size_t extant_bufs_cur, extant_bufs_max, extant_bufs_total; static double buf_size_total, buf_aligned_size_total; // file_io -static uint user_ios; +static size_t user_ios; static double user_io_size_total; static double io_actual_size_total[FI_MAX_IDX][2]; static double io_elapsed_time[FI_MAX_IDX][2]; static double io_process_time_total; -static uint io_seeks; +static size_t io_seeks; // file_cache -static uint cache_count[2]; +static size_t cache_count[2]; static double cache_size_total[2]; -static uint conflict_misses; +static size_t conflict_misses; static double conflict_miss_size_total; -static uint block_cache_count[2]; +static size_t block_cache_count[2]; // archive builder -static uint ab_connection_attempts; // total number of trace entries -static uint ab_repeated_connections; // how many of these were not unique +static size_t ab_connection_attempts; // total number of trace entries +static size_t ab_repeated_connections; // how many of these were not unique // convenience functions for measuring elapsed time in an interval. diff --git a/source/lib/file/common/real_directory.cpp b/source/lib/file/common/real_directory.cpp index 686dc22e6b..d5e89e1cf6 100644 --- a/source/lib/file/common/real_directory.cpp +++ b/source/lib/file/common/real_directory.cpp @@ -6,13 +6,13 @@ #include "lib/file/io/io.h" -RealDirectory::RealDirectory(const Path& path, unsigned priority, unsigned flags) +RealDirectory::RealDirectory(const Path& path, size_t priority, int flags) : m_path(path), m_priority(priority), m_flags(flags) { } -/*virtual*/ unsigned RealDirectory::Precedence() const +/*virtual*/ size_t RealDirectory::Precedence() const { return 1u; } diff --git a/source/lib/file/common/real_directory.h b/source/lib/file/common/real_directory.h index a6a813e698..639b2971c7 100644 --- a/source/lib/file/common/real_directory.h +++ b/source/lib/file/common/real_directory.h @@ -7,25 +7,25 @@ class RealDirectory : public IFileLoader { public: - RealDirectory(const Path& path, unsigned priority, unsigned flags); + RealDirectory(const Path& path, size_t priority, int flags); const Path& GetPath() const { return m_path; } - unsigned Priority() const + size_t Priority() const { return m_priority; } - unsigned Flags() const + int Flags() const { return m_flags; } // IFileLoader - virtual unsigned Precedence() const; + virtual size_t Precedence() const; virtual char LocationCode() const; virtual LibError Load(const std::string& name, shared_ptr buf, size_t size) const; @@ -42,9 +42,9 @@ private: // is not all too wasteful. const Path m_path; - const unsigned m_priority; + const size_t m_priority; - const unsigned m_flags; + const int m_flags; // note: watches are needed in each directory because some APIs // (e.g. FAM) cannot watch entire trees with one call. diff --git a/source/lib/file/disabled_tests/test_file_cache.h b/source/lib/file/disabled_tests/test_file_cache.h index 82407dd0c1..8069b26bca 100644 --- a/source/lib/file/disabled_tests/test_file_cache.h +++ b/source/lib/file/disabled_tests/test_file_cache.h @@ -30,7 +30,7 @@ public: break; // out of room - remove a previous allocation // .. choose one at random - size_t chosen_idx = (size_t)rand(0, (uint)allocations.size()); + size_t chosen_idx = (size_t)rand(0, (size_t)allocations.size()); AllocMap::iterator it = allocations.begin(); for(; chosen_idx != 0; chosen_idx--) ++it; diff --git a/source/lib/file/file_system_util.cpp b/source/lib/file/file_system_util.cpp index 5f7dab1a45..be20614206 100644 --- a/source/lib/file/file_system_util.cpp +++ b/source/lib/file/file_system_util.cpp @@ -63,7 +63,7 @@ void fs_SortDirectories(DirectoryNames& directories) } -LibError fs_ForEachFile(PIVFS fs, const VfsPath& path, FileCallback cb, uintptr_t cbData, const char* pattern, unsigned flags) +LibError fs_ForEachFile(PIVFS fs, const VfsPath& path, FileCallback cb, uintptr_t cbData, const char* pattern, int flags) { debug_assert(vfs_path_IsDirectory(path)); @@ -102,7 +102,7 @@ LibError fs_ForEachFile(PIVFS fs, const VfsPath& path, FileCallback cb, uintptr_ } -void fs_NextNumberedFilename(PIVFS fs, const VfsPath& pathnameFormat, unsigned& nextNumber, VfsPath& nextPathname) +void fs_NextNumberedFilename(PIVFS fs, const VfsPath& pathnameFormat, size_t& nextNumber, VfsPath& nextPathname) { // (first call only:) scan directory and set nextNumber according to // highest matching filename found. this avoids filling "holes" in @@ -114,12 +114,12 @@ void fs_NextNumberedFilename(PIVFS fs, const VfsPath& pathnameFormat, unsigned& const std::string nameFormat = pathnameFormat.leaf(); const VfsPath path = pathnameFormat.branch_path()/"/"; - unsigned maxNumber = 0; + size_t maxNumber = 0; FileInfos files; fs->GetDirectoryEntries(path, &files, 0); for(size_t i = 0; i < files.size(); i++) { - unsigned number; + size_t number; if(sscanf(files[i].Name().c_str(), nameFormat.c_str(), &number) == 1) maxNumber = std::max(number, maxNumber); } diff --git a/source/lib/file/file_system_util.h b/source/lib/file/file_system_util.h index 5462a85257..98426381a4 100644 --- a/source/lib/file/file_system_util.h +++ b/source/lib/file/file_system_util.h @@ -47,7 +47,7 @@ enum DirFlags * @param flags see DirFlags * @param LibError **/ -extern LibError fs_ForEachFile(PIVFS fs, const VfsPath& path, FileCallback cb, uintptr_t cbData, const char* pattern = 0, uint flags = 0); +extern LibError fs_ForEachFile(PIVFS fs, const VfsPath& path, FileCallback cb, uintptr_t cbData, const char* pattern = 0, int flags = 0); /** @@ -56,12 +56,12 @@ extern LibError fs_ForEachFile(PIVFS fs, const VfsPath& path, FileCallback cb, u * ones (screenshots are a good example). * * @param pathnameFormat format string for the pathname; must contain one - * format specifier for an (unsigned) int. + * format specifier for a size_t. * example: "screenshots/screenshot%04d.png" * @param nextNumber in: the first number to try; out: the next number. * if 0, numbers corresponding to existing files are skipped. * @param nextPathname receives the output. **/ -extern void fs_NextNumberedFilename(PIVFS fs, const VfsPath& pathnameFormat, unsigned& nextNumber, VfsPath& nextPathname); +extern void fs_NextNumberedFilename(PIVFS fs, const VfsPath& pathnameFormat, size_t& nextNumber, VfsPath& nextPathname); #endif // #ifndef INCLUDED_FILE_SYSTEM_UTIL diff --git a/source/lib/file/io/io.cpp b/source/lib/file/io/io.cpp index b962e0b73c..bdb61b2ec8 100644 --- a/source/lib/file/io/io.cpp +++ b/source/lib/file/io/io.cpp @@ -18,7 +18,7 @@ #include "block_cache.h" #include "io_align.h" -static const unsigned ioDepth = 8; +static const size_t ioDepth = 8; // the underlying aio implementation likes buffer and offset to be diff --git a/source/lib/file/io/write_buffer.cpp b/source/lib/file/io/write_buffer.cpp index 9183449036..7bed880b05 100644 --- a/source/lib/file/io/write_buffer.cpp +++ b/source/lib/file/io/write_buffer.cpp @@ -17,7 +17,7 @@ void WriteBuffer::Append(const void* data, size_t size) { if(m_size + size > m_capacity) { - m_capacity = round_up_to_pow2((uint)(m_size + size)); + m_capacity = round_up_to_pow2((size_t)(m_size + size)); shared_ptr newData = io_Allocate(m_capacity); cpu_memcpy(newData.get(), m_data.get(), m_size); m_data = newData; diff --git a/source/lib/file/vfs/file_cache.cpp b/source/lib/file/vfs/file_cache.cpp index e0b95dc25f..df7a8a6657 100644 --- a/source/lib/file/vfs/file_cache.cpp +++ b/source/lib/file/vfs/file_cache.cpp @@ -171,7 +171,7 @@ public: } } - void Add(const VfsPath& pathname, shared_ptr data, size_t size, uint cost) + void Add(const VfsPath& pathname, shared_ptr data, size_t size, size_t cost) { // zero-copy cache => all users share the contents => must not // allow changes. this will be reverted when deallocating. @@ -217,7 +217,7 @@ shared_ptr FileCache::Reserve(size_t size) return impl->Reserve(size); } -void FileCache::Add(const VfsPath& pathname, shared_ptr data, size_t size, uint cost) +void FileCache::Add(const VfsPath& pathname, shared_ptr data, size_t size, size_t cost) { impl->Add(pathname, data, size, cost); } diff --git a/source/lib/file/vfs/file_cache.h b/source/lib/file/vfs/file_cache.h index 7b514c1a5e..bc9239a523 100644 --- a/source/lib/file/vfs/file_cache.h +++ b/source/lib/file/vfs/file_cache.h @@ -61,7 +61,7 @@ public: * @param cost is the expected cost of retrieving the file again and * influences how/when it is evicted from the cache. **/ - void Add(const VfsPath& pathname, shared_ptr data, size_t size, uint cost = 1); + void Add(const VfsPath& pathname, shared_ptr data, size_t size, size_t cost = 1); /** * Remove a file's contents from the cache (if it exists). diff --git a/source/lib/file/vfs/vfs.cpp b/source/lib/file/vfs/vfs.cpp index 206e7e106d..b4de26f8f2 100644 --- a/source/lib/file/vfs/vfs.cpp +++ b/source/lib/file/vfs/vfs.cpp @@ -31,7 +31,7 @@ public: { } - virtual LibError Mount(const VfsPath& mountPoint, const Path& path, uint flags /* = 0 */, uint priority /* = 0 */) + virtual LibError Mount(const VfsPath& mountPoint, const Path& path, int flags /* = 0 */, size_t priority /* = 0 */) { debug_assert(vfs_path_IsDirectory(mountPoint)); // note: mounting subdirectories is now allowed. diff --git a/source/lib/file/vfs/vfs.h b/source/lib/file/vfs/vfs.h index d1c900850e..b7a27bf78e 100644 --- a/source/lib/file/vfs/vfs.h +++ b/source/lib/file/vfs/vfs.h @@ -67,7 +67,7 @@ struct IVFS * if files with archive extensions are seen, their contents are added * as well. **/ - virtual LibError Mount(const VfsPath& mountPoint, const Path& path, uint flags = 0, uint priority = 0) = 0; + virtual LibError Mount(const VfsPath& mountPoint, const Path& path, int flags = 0, size_t priority = 0) = 0; virtual LibError GetFileInfo(const VfsPath& pathname, FileInfo* pfileInfo) const = 0; diff --git a/source/lib/file/vfs/vfs_lookup.cpp b/source/lib/file/vfs/vfs_lookup.cpp index bd0e745421..ae2c1922af 100644 --- a/source/lib/file/vfs/vfs_lookup.cpp +++ b/source/lib/file/vfs/vfs_lookup.cpp @@ -68,7 +68,7 @@ private: // (we have to create missing subdirectoryNames because archivers // don't always place directory entries before their files) - const unsigned flags = VFS_LOOKUP_ADD; + const int flags = VFS_LOOKUP_ADD; VfsDirectory* directory; WARN_ERR(vfs_Lookup(pathname, this_->m_directory, directory, 0, flags)); const VfsFile file(fileInfo.Name(), fileInfo.Size(), fileInfo.MTime(), this_->m_realDirectory->Priority(), archiveFile); @@ -135,7 +135,7 @@ static LibError Populate(VfsDirectory* directory) //----------------------------------------------------------------------------- -LibError vfs_Lookup(const VfsPath& pathname, VfsDirectory* startDirectory, VfsDirectory*& directory, VfsFile** pfile, unsigned flags) +LibError vfs_Lookup(const VfsPath& pathname, VfsDirectory* startDirectory, VfsDirectory*& directory, VfsFile** pfile, int flags) { TIMER_ACCRUE(tc_lookup); diff --git a/source/lib/file/vfs/vfs_lookup.h b/source/lib/file/vfs/vfs_lookup.h index 1527a37cc3..f15b9938d3 100644 --- a/source/lib/file/vfs/vfs_lookup.h +++ b/source/lib/file/vfs/vfs_lookup.h @@ -42,6 +42,6 @@ enum VfsLookupFlags * * to allow noiseless file-existence queries, this does not raise warnings. **/ -extern LibError vfs_Lookup(const VfsPath& pathname, VfsDirectory* startDirectory, VfsDirectory*& directory, VfsFile** pfile, unsigned flags = 0); +extern LibError vfs_Lookup(const VfsPath& pathname, VfsDirectory* startDirectory, VfsDirectory*& directory, VfsFile** pfile, int flags = 0); #endif // #ifndef INCLUDED_VFS_LOOKUP diff --git a/source/lib/file/vfs/vfs_tree.cpp b/source/lib/file/vfs/vfs_tree.cpp index 9813d0ab34..8323cb1ab0 100644 --- a/source/lib/file/vfs/vfs_tree.cpp +++ b/source/lib/file/vfs/vfs_tree.cpp @@ -17,7 +17,7 @@ //----------------------------------------------------------------------------- -VfsFile::VfsFile(const std::string& name, off_t size, time_t mtime, unsigned priority, PIFileLoader loader) +VfsFile::VfsFile(const std::string& name, off_t size, time_t mtime, size_t priority, PIFileLoader loader) : m_name(name), m_size(size), m_mtime(mtime), m_priority(priority), m_loader(loader) { } @@ -135,7 +135,7 @@ void VfsDirectory::GetEntries(FileInfos* files, DirectoryNames* subdirectoryName } -void VfsDirectory::DisplayR(unsigned depth) const +void VfsDirectory::DisplayR(size_t depth) const { static const char indent[] = " "; @@ -151,7 +151,7 @@ void VfsDirectory::DisplayR(unsigned depth) const char description[100]; file.GenerateDescription(description, ARRAY_SIZE(description)); - for(unsigned i = 0; i < depth+1; i++) + for(size_t i = 0; i < depth+1; i++) printf(indent); printf(fmt, name.c_str(), description); } @@ -161,7 +161,7 @@ void VfsDirectory::DisplayR(unsigned depth) const const std::string& name = it->first; const VfsDirectory& directory = it->second; - for(unsigned i = 0; i < depth+1; i++) + for(size_t i = 0; i < depth+1; i++) printf(indent); printf("[%s/]\n", name.c_str()); diff --git a/source/lib/file/vfs/vfs_tree.h b/source/lib/file/vfs/vfs_tree.h index adad8c9ce2..72787106f9 100644 --- a/source/lib/file/vfs/vfs_tree.h +++ b/source/lib/file/vfs/vfs_tree.h @@ -18,7 +18,7 @@ class VfsFile { public: - VfsFile(const std::string& name, off_t size, time_t mtime, unsigned priority, PIFileLoader provider); + VfsFile(const std::string& name, off_t size, time_t mtime, size_t priority, PIFileLoader provider); const std::string& Name() const { @@ -74,7 +74,7 @@ public: void GetEntries(FileInfos* files, DirectoryNames* subdirectories) const; - void DisplayR(unsigned depth) const; + void DisplayR(size_t depth) const; void ClearR(); diff --git a/source/lib/input.cpp b/source/lib/input.cpp index a686115d28..ad28dcdd15 100644 --- a/source/lib/input.cpp +++ b/source/lib/input.cpp @@ -17,9 +17,9 @@ #include "lib/external_libraries/sdl.h" -const uint MAX_HANDLERS = 8; +const size_t MAX_HANDLERS = 8; static InHandler handler_stack[MAX_HANDLERS]; -static uint handler_stack_top = 0; +static size_t handler_stack_top = 0; void in_add_handler(InHandler handler) { diff --git a/source/lib/lib.cpp b/source/lib/lib.cpp index 4258429729..989fc49b74 100644 --- a/source/lib/lib.cpp +++ b/source/lib/lib.cpp @@ -86,7 +86,7 @@ u8 u8_from_double(double in) } int l = (int)(in * 255.0); - debug_assert((unsigned int)l <= 255u); + debug_assert((unsigned)l <= 255u); return (u8)l; } diff --git a/source/lib/lib.h b/source/lib/lib.h index e6d8066efc..121feb1c84 100644 --- a/source/lib/lib.h +++ b/source/lib/lib.h @@ -52,9 +52,9 @@ scope #include "config.h" -const size_t KiB = 1ul << 10; -const size_t MiB = 1ul << 20; -const size_t GiB = 1ul << 30; +const size_t KiB = size_t(1) << 10; +const size_t MiB = size_t(1) << 20; +const size_t GiB = size_t(1) << 30; // diff --git a/source/lib/lockfree.cpp b/source/lib/lockfree.cpp index 1c9ab682cf..c6b893da97 100644 --- a/source/lib/lockfree.cpp +++ b/source/lib/lockfree.cpp @@ -46,7 +46,7 @@ todo: // total number of hazard pointers needed by each thread. // determined by the algorithms using SMR; the LF list requires 2. -static const uint NUM_HPS = 2; +static const size_t NUM_HPS = 2; // number of slots for the per-thread node freelist. // this is a reasonable size and pads struct TLS to 64 bytes. @@ -631,7 +631,7 @@ LibError lfh_init(LFHash* hash, size_t num_entries) hash->tbl = (LFList*)malloc(sizeof(LFList) * num_entries); if(!hash->tbl) return ERR::NO_MEM; - hash->mask = (uint)num_entries-1; + hash->mask = (size_t)num_entries-1; for(int i = 0; i < (int)num_entries; i++) { diff --git a/source/lib/lockfree.h b/source/lib/lockfree.h index 943e542fae..6b07f5a7b7 100644 --- a/source/lib/lockfree.h +++ b/source/lib/lockfree.h @@ -131,7 +131,7 @@ extern LibError lfl_erase(LFList* list, uintptr_t key); struct LFHash { LFList* tbl; - uint mask; + size_t mask; }; // make ready a previously unused(!) hash object. table size will be diff --git a/source/lib/path_util.cpp b/source/lib/path_util.cpp index 60326ec0be..4da93361c9 100644 --- a/source/lib/path_util.cpp +++ b/source/lib/path_util.cpp @@ -160,7 +160,7 @@ void path_copy(char* dst, const char* src) // if necessary, a directory separator is added between the paths. // each may be empty, filenames, or full paths. // total path length (including '\0') must not exceed PATH_MAX. -LibError path_append(char* dst, const char* path1, const char* path2, uint flags) +LibError path_append(char* dst, const char* path1, const char* path2, int flags) { const size_t len1 = strlen(path1); const size_t len2 = strlen(path2); diff --git a/source/lib/path_util.h b/source/lib/path_util.h index 8e9e45dc6f..4070d99aa3 100644 --- a/source/lib/path_util.h +++ b/source/lib/path_util.h @@ -106,7 +106,7 @@ enum PathAppendFlags * @param flags see PathAppendFlags. * @return LibError **/ -extern LibError path_append(char* dst, const char* path1, const char* path2, uint flags = 0); +extern LibError path_append(char* dst, const char* path1, const char* path2, int flags = 0); /** * get the name component of a path. diff --git a/source/lib/posix/posix.cpp b/source/lib/posix/posix.cpp index b20cb26b5c..2e56098882 100644 --- a/source/lib/posix/posix.cpp +++ b/source/lib/posix/posix.cpp @@ -46,7 +46,7 @@ float fmaxf(float a, float b) } -uint fpclassifyd(double d) +size_t fpclassifyd(double d) { #if ARCH_IA32 return ia32_asm_fpclassifyd(d); @@ -60,7 +60,7 @@ uint fpclassifyd(double d) #endif } -uint fpclassifyf(float f) +size_t fpclassifyf(float f) { #if ARCH_IA32 return ia32_asm_fpclassifyf(f); diff --git a/source/lib/posix/posix.h b/source/lib/posix/posix.h index babe1cb29f..f0bcadb042 100644 --- a/source/lib/posix/posix.h +++ b/source/lib/posix/posix.h @@ -108,8 +108,8 @@ extern double rint(double d); extern float fminf(float a, float b); extern float fmaxf(float a, float b); -extern uint fpclassifyf(float f); -extern uint fpclassifyd(double d); +extern size_t fpclassifyf(float f); +extern size_t fpclassifyd(double d); #define fpclassify(x) ( (sizeof(x) == sizeof(float))? fpclassifyf(x) : fpclassifyd(x) ) // these definitions "happen" to match IA32_FP_* and allow using diff --git a/source/lib/rand.cpp b/source/lib/rand.cpp index 57cd37c065..9823244cc0 100644 --- a/source/lib/rand.cpp +++ b/source/lib/rand.cpp @@ -20,23 +20,23 @@ // folded down to a much smaller interval anyway. instead, a larger XRAND_MAX // decreases the probability of having to repeat the loop. #if RAND_MAX < 65536 -static const uint XRAND_MAX = (RAND_MAX+1)*(RAND_MAX+1) - 1; -static uint xrand() +static const size_t XRAND_MAX = (RAND_MAX+1)*(RAND_MAX+1) - 1; +static size_t xrand() { return rand()*(RAND_MAX+1) + rand(); } // rand() is already ok; no need to do anything. #else -static const uint XRAND_MAX = RAND_MAX; -static uint xrand() +static const size_t XRAND_MAX = RAND_MAX; +static size_t xrand() { return rand(); } #endif -uint rand(uint min_inclusive, uint max_exclusive) +size_t rand(size_t min_inclusive, size_t max_exclusive) { - const uint range = (max_exclusive-min_inclusive); + const size_t range = (max_exclusive-min_inclusive); // huge interval or min >= max if(range == 0 || range > XRAND_MAX) { @@ -44,15 +44,17 @@ uint rand(uint min_inclusive, uint max_exclusive) return 0; } - const uint inv_range = XRAND_MAX / range; + const size_t inv_range = XRAND_MAX / range; // generate random number in [0, range) // idea: avoid skewed distributions when doesn't evenly divide // XRAND_MAX by simply discarding values in the "remainder". // not expected to run often since XRAND_MAX is large. - uint x; + size_t x; do - x = xrand(); + { + x = xrand(); + } while(x >= range * inv_range); x /= inv_range; diff --git a/source/lib/rand.h b/source/lib/rand.h index 3d3d9e248e..7c6fdf40cf 100644 --- a/source/lib/rand.h +++ b/source/lib/rand.h @@ -16,6 +16,6 @@ * avoids several common pitfalls; see discussion at * http://www.azillionmonkeys.com/qed/random.html **/ -extern uint rand(uint min_inclusive, uint max_exclusive); +extern size_t rand(size_t min_inclusive, size_t max_exclusive); #endif // #ifndef INCLUDED_RAND diff --git a/source/lib/res/graphics/cursor.cpp b/source/lib/res/graphics/cursor.cpp index f0b2ee29e4..ea4a54d978 100644 --- a/source/lib/res/graphics/cursor.cpp +++ b/source/lib/res/graphics/cursor.cpp @@ -71,7 +71,7 @@ static void* load_sys_cursor(const VfsPath& pathname, int hx, int hy) void* sys_cursor = 0; // return value // convert to required BGRA format. - const uint flags = (t.flags | TEX_BGR) & ~TEX_DXT; + const int flags = (t.flags | TEX_BGR) & ~TEX_DXT; if(tex_transform_to(&t, flags) < 0) goto fail; void* bgra_img = tex_get_data(&t); @@ -99,16 +99,19 @@ class GLCursor { Handle ht; - uint w, h; - uint hotspotx, hotspoty; + GLint w, h; + int hotspotx, hotspoty; public: - LibError create(const VfsPath& pathname, uint hotspotx_, uint hotspoty_) + LibError create(const VfsPath& pathname, int hotspotx_, int hotspoty_) { ht = ogl_tex_load(pathname); RETURN_ERR(ht); - (void)ogl_tex_get_size(ht, &w, &h, 0); + size_t width, height; + (void)ogl_tex_get_size(ht, &width, &height, 0); + w = (GLint)width; + h = (GLint)height; hotspotx = hotspotx_; hotspoty = hotspoty_; @@ -124,7 +127,7 @@ public: (void)ogl_tex_free(ht); } - void draw(uint x, uint y) const + void draw(int x, int y) const { (void)ogl_tex_bind(ht); glEnable(GL_TEXTURE_2D); @@ -146,7 +149,7 @@ public: LibError validate() const { - const uint A = 128; // no cursor is expected to get this big + const size_t A = 128; // no cursor is expected to get this big if(w > A || h > A || hotspotx > A || hotspoty > A) WARN_RETURN(ERR::_1); if(ht < 0) @@ -189,7 +192,7 @@ static LibError Cursor_reload(Cursor* c, const VfsPath& name, Handle) // read pixel offset of the cursor's hotspot [the bit of it that's // drawn at (g_mouse_x,g_mouse_y)] from file. - uint hotspotx = 0, hotspoty = 0; + int hotspotx = 0, hotspoty = 0; { const VfsPath pathname(path / (basename + ".txt")); shared_ptr buf; size_t size; diff --git a/source/lib/res/graphics/ogl_tex.cpp b/source/lib/res/graphics/ogl_tex.cpp index 60dce2bcaa..cea606cd0d 100644 --- a/source/lib/res/graphics/ogl_tex.cpp +++ b/source/lib/res/graphics/ogl_tex.cpp @@ -92,12 +92,12 @@ static bool fmt_is_s3tc(GLenum fmt) // determine OpenGL texture format, given and Tex . -static GLint choose_fmt(uint bpp, uint flags) +static GLint choose_fmt(size_t bpp, int flags) { const bool alpha = (flags & TEX_ALPHA) != 0; const bool bgr = (flags & TEX_BGR ) != 0; const bool grey = (flags & TEX_GREY ) != 0; - const uint dxt = flags & TEX_DXT; + const size_t dxt = flags & TEX_DXT; // S3TC if(dxt != 0) @@ -144,11 +144,11 @@ static GLint choose_fmt(uint bpp, uint flags) //---------------------------------------------------------------------------- static GLint default_filter = GL_LINEAR; // one of the GL *minify* filters -static uint default_q_flags = OGL_TEX_FULL_QUALITY; // OglTexQualityFlags +static int default_q_flags = OGL_TEX_FULL_QUALITY; // OglTexQualityFlags -static bool q_flags_valid(uint q_flags) +static bool q_flags_valid(int q_flags) { - const uint bits = OGL_TEX_FULL_QUALITY|OGL_TEX_HALF_BPP|OGL_TEX_HALF_RES; + const size_t bits = OGL_TEX_FULL_QUALITY|OGL_TEX_HALF_BPP|OGL_TEX_HALF_RES; // unrecognized bits are set - invalid if((q_flags & ~bits) != 0) return false; @@ -166,7 +166,7 @@ static bool q_flags_valid(uint q_flags) // pass 0 to keep the current setting; defaults and legal values are: // - q_flags: OGL_TEX_FULL_QUALITY; combination of OglTexQualityFlags // - filter: GL_LINEAR; any valid OpenGL minification filter -void ogl_tex_set_defaults(uint q_flags, GLint filter) +void ogl_tex_set_defaults(int q_flags, GLint filter) { if(q_flags) { @@ -183,7 +183,7 @@ void ogl_tex_set_defaults(uint q_flags, GLint filter) // choose an internal format for based on the given q_flags. -static GLint choose_int_fmt(GLenum fmt, uint q_flags) +static GLint choose_int_fmt(GLenum fmt, int q_flags) { // true => 4 bits per component; otherwise, 8 const bool half_bpp = (q_flags & OGL_TEX_HALF_BPP) != 0; @@ -330,7 +330,7 @@ enum OglTexFlags // "the enclosed Tex object is valid and holds a texture"; // reset in dtor and after ogl_tex_upload's tex_free. OT_TEX_VALID = 2, - //uint tex_valid : 1; + //size_t tex_valid : 1; // "reload() should automatically re-upload the texture" (because // it had been uploaded before the reload); never reset. @@ -357,12 +357,12 @@ struct OglTex OglTexState state; // OglTexQualityFlags - uint q_flags : 8; + int q_flags : 8; // to which Texture Mapping Unit was this bound? - uint tmu : 8; + size_t tmu : 8; - uint flags : 16; + int flags : 16; }; H_TYPE_DEFINE(OglTex); @@ -475,7 +475,7 @@ static LibError OglTex_to_string(const OglTex* ot, char* buf) // load and return a handle to the texture given in . // for a list of supported formats, see tex.h's tex_load. -Handle ogl_tex_load(const VfsPath& pathname, uint flags) +Handle ogl_tex_load(const VfsPath& pathname, int flags) { Tex* wrapped_tex = 0; // we're loading from file return h_alloc(H_OglTex, pathname, flags, wrapped_tex); @@ -503,7 +503,7 @@ Handle ogl_tex_find(const VfsPath& pathname) // note: because we cannot guarantee that callers will pass distinct // "filenames", caching is disabled for the created object. this avoids // mistakenly reusing previous objects that share the same comment. -Handle ogl_tex_wrap(Tex* t, const char* fn, uint flags) +Handle ogl_tex_wrap(Tex* t, const char* fn, int flags) { // this object may not be backed by a file ("may", because // someone could do tex_load and then ogl_tex_wrap). @@ -694,7 +694,7 @@ static void detect_gl_upload_caps() // whether mipmaps are needed and the quality settings). // returns 0 to indicate success; otherwise, caller must disable // mipmapping by switching filter to e.g. GL_LINEAR. -static LibError get_mipmaps(Tex* t, GLint filter, uint q_flags, int* plevels_to_skip) +static LibError get_mipmaps(Tex* t, GLint filter, int q_flags, int* plevels_to_skip) { // decisions: // .. does filter call for uploading mipmaps? @@ -748,8 +748,8 @@ static LibError get_mipmaps(Tex* t, GLint filter, uint q_flags, int* plevels_to_ // note: we don't just use GL_TEXTURE_BASE_LEVEL because it would // require uploading unused levels, which is wasteful. // .. can be expanded to reduce to 1/4, 1/8 by encoding factor in q_flags. - const uint reduce = (q_flags & OGL_TEX_HALF_RES)? 2 : 1; - *plevels_to_skip = ceil_log2(reduce); + const size_t reduce = (q_flags & OGL_TEX_HALF_RES)? 2 : 1; + *plevels_to_skip = (int)ceil_log2(reduce); } return INFO::OK; @@ -764,18 +764,16 @@ struct UploadParams GLint int_fmt; }; -static void upload_level(uint level, uint level_w, uint level_h, const u8* RESTRICT level_data, size_t UNUSED(level_data_size), void* RESTRICT cbData) +static void upload_level(size_t level, size_t level_w, size_t level_h, const u8* RESTRICT level_data, size_t UNUSED(level_data_size), void* RESTRICT cbData) { const UploadParams* up = (const UploadParams*)cbData; - glTexImage2D(GL_TEXTURE_2D, level, up->int_fmt, level_w, level_h, 0, - up->fmt, GL_UNSIGNED_BYTE, level_data); + glTexImage2D(GL_TEXTURE_2D, (GLint)level, up->int_fmt, (GLsizei)level_w, (GLsizei)level_h, 0, up->fmt, GL_UNSIGNED_BYTE, level_data); } -static void upload_compressed_level(uint level, uint level_w, uint level_h, const u8* RESTRICT level_data, size_t level_data_size, void* RESTRICT cbData) +static void upload_compressed_level(size_t level, size_t level_w, size_t level_h, const u8* RESTRICT level_data, size_t level_data_size, void* RESTRICT cbData) { const UploadParams* up = (const UploadParams*)cbData; - pglCompressedTexImage2DARB(GL_TEXTURE_2D, level, up->fmt, - (GLsizei)level_w, (GLsizei)level_h, 0, (GLsizei)level_data_size, level_data); + pglCompressedTexImage2DARB(GL_TEXTURE_2D, (GLint)level, up->fmt, (GLsizei)level_w, (GLsizei)level_h, 0, (GLsizei)level_data_size, level_data); } // upload the texture in the specified (internal) format. @@ -786,7 +784,7 @@ static void upload_impl(Tex* t, GLenum fmt, GLint int_fmt, int levels_to_skip) { const GLsizei w = (GLsizei)t->w; const GLsizei h = (GLsizei)t->h; - const uint bpp = t->bpp; + const size_t bpp = t->bpp; const u8* data = (const u8*)tex_get_data(t); const UploadParams up = { fmt, int_fmt }; @@ -806,7 +804,7 @@ static void upload_impl(Tex* t, GLenum fmt, GLint int_fmt, int levels_to_skip) // side effects: // - enables texturing on TMU 0 and binds the texture to it; // - frees the texel data! see ogl_tex_get_data. -LibError ogl_tex_upload(const Handle ht, GLenum fmt_ovr, uint q_flags_ovr, GLint int_fmt_ovr) +LibError ogl_tex_upload(const Handle ht, GLenum fmt_ovr, int q_flags_ovr, GLint int_fmt_ovr) { ONCE(detect_gl_upload_caps()); @@ -873,7 +871,7 @@ LibError ogl_tex_upload(const Handle ht, GLenum fmt_ovr, uint q_flags_ovr, GLint // retrieve texture dimensions and bits per pixel. // all params are optional and filled if non-NULL. -LibError ogl_tex_get_size(Handle ht, uint* w, uint* h, uint* bpp) +LibError ogl_tex_get_size(Handle ht, size_t* w, size_t* h, size_t* bpp) { H_DEREF(ht, OglTex, ot); @@ -890,7 +888,7 @@ LibError ogl_tex_get_size(Handle ht, uint* w, uint* h, uint* bpp) // retrieve TexFlags and the corresponding OpenGL format. // the latter is determined during ogl_tex_upload and is 0 before that. // all params are optional and filled if non-NULL. -LibError ogl_tex_get_format(Handle ht, uint* flags, GLenum* fmt) +LibError ogl_tex_get_format(Handle ht, int* flags, GLenum* fmt) { H_DEREF(ht, OglTex, ot); @@ -936,7 +934,7 @@ LibError ogl_tex_get_data(Handle ht, void** p) // - assumes multitexturing is available. // - not necessary before calling ogl_tex_upload! // - on error, the unit's texture state is unchanged; see implementation. -LibError ogl_tex_bind(Handle ht, uint unit) +LibError ogl_tex_bind(Handle ht, size_t unit) { // note: there are many call sites of glActiveTextureARB, so caching // those and ignoring redundant sets isn't feasible. @@ -968,7 +966,7 @@ LibError ogl_tex_bind(Handle ht, uint unit) // apply the specified transforms (as in tex_transform) to the image. // must be called before uploading (raises a warning if called afterwards). -LibError ogl_tex_transform(Handle ht, uint transforms) +LibError ogl_tex_transform(Handle ht, size_t transforms) { H_DEREF(ht, OglTex, ot); LibError ret = tex_transform(&ot->t, transforms); @@ -978,7 +976,7 @@ LibError ogl_tex_transform(Handle ht, uint transforms) // change the pixel format to that specified by . // (note: this is equivalent to ogl_tex_transform(ht, ht_flags^new_flags). -LibError ogl_tex_transform_to(Handle ht, uint new_flags) +LibError ogl_tex_transform_to(Handle ht, size_t new_flags) { H_DEREF(ht, OglTex, ot); LibError ret = tex_transform_to(&ot->t, new_flags); diff --git a/source/lib/res/graphics/ogl_tex.h b/source/lib/res/graphics/ogl_tex.h index cce9200384..09d3f3f148 100644 --- a/source/lib/res/graphics/ogl_tex.h +++ b/source/lib/res/graphics/ogl_tex.h @@ -108,7 +108,7 @@ the next function to fail, but real apps should check and report errors. specify internal_format and use multitexturing. Tex t; - const uint flags = 0; * image is plain RGB, default orientation + const int flags = 0; * image is plain RGB, default orientation void* data = [pre-existing image] (void)tex_wrap(w, h, 24, flags, data, &t); Handle hCompositeAlphaMap = ogl_tex_wrap(&t, "(alpha map composite)"); @@ -189,7 +189,7 @@ enum OglTexQualityFlags * @param filter mag/minification filter. Pass 0 to keep the current setting * (initially GL_LINEAR), or any valid OpenGL minification filter. */ -extern void ogl_tex_set_defaults(uint q_flags, GLint filter); +extern void ogl_tex_set_defaults(int q_flags, GLint filter); // @@ -203,7 +203,7 @@ extern void ogl_tex_set_defaults(uint q_flags, GLint filter); * @return Handle to texture or negative LibError * for a list of supported formats, see tex.h's tex_load. */ -extern Handle ogl_tex_load(const VfsPath& pathname, uint flags = 0); +extern Handle ogl_tex_load(const VfsPath& pathname, int flags = 0); /** * Find and return an existing texture object, if it has already been @@ -232,7 +232,7 @@ extern Handle ogl_tex_find(const VfsPath& pathname); * we need only add bookkeeping information and "wrap" it in * a resource object (accessed via Handle), hence the name. */ -extern Handle ogl_tex_wrap(Tex* t, const char* fn = 0, uint flags = 0); +extern Handle ogl_tex_wrap(Tex* t, const char* fn = 0, int flags = 0); /** * Release this texture reference. When the count reaches zero, all of @@ -316,7 +316,7 @@ extern void ogl_tex_override(OglTexOverrides what, OglTexAllow allow); *
  • frees the texel data! see ogl_tex_get_data. * */ -extern LibError ogl_tex_upload(const Handle ht, GLenum fmt_ovr = 0, uint q_flags_ovr = 0, GLint int_fmt_ovr = 0); +extern LibError ogl_tex_upload(const Handle ht, GLenum fmt_ovr = 0, int q_flags_ovr = 0, GLint int_fmt_ovr = 0); // @@ -332,7 +332,7 @@ extern LibError ogl_tex_upload(const Handle ht, GLenum fmt_ovr = 0, uint q_flags * @param bpp optional; will be filled with bits per pixel * @return LibError */ -extern LibError ogl_tex_get_size(Handle ht, uint* w, uint* h, uint* bpp); +extern LibError ogl_tex_get_size(Handle ht, size_t* w, size_t* h, size_t* bpp); /** * Retrieve pixel format of the texture. @@ -343,7 +343,7 @@ extern LibError ogl_tex_get_size(Handle ht, uint* w, uint* h, uint* bpp); * (it is determined during ogl_tex_upload and 0 before then) * @return LibError */ -extern LibError ogl_tex_get_format(Handle ht, uint* flags, GLenum* fmt); +extern LibError ogl_tex_get_format(Handle ht, int* flags, GLenum* fmt); /** * Retrieve pixel data of the texture. @@ -382,7 +382,7 @@ extern LibError ogl_tex_get_data(Handle ht, void** p); * - not necessary before calling ogl_tex_upload! * - on error, the unit's texture state is unchanged; see implementation. */ -extern LibError ogl_tex_bind(Handle ht, uint unit = 0); +extern LibError ogl_tex_bind(Handle ht, size_t unit = 0); /** * (partially) Transform pixel format of the texture. @@ -394,7 +394,7 @@ extern LibError ogl_tex_bind(Handle ht, uint unit = 0); * * Must be called before uploading (raises a warning if called afterwards). */ -extern LibError ogl_tex_transform(Handle ht, uint flags); +extern LibError ogl_tex_transform(Handle ht, int flags); /** * Transform pixel format of the texture. @@ -408,6 +408,6 @@ extern LibError ogl_tex_transform(Handle ht, uint flags); * * Note: this is equivalent to ogl_tex_transform(ht, ht_flags^new_flags). */ -extern LibError ogl_tex_transform_to(Handle ht, uint new_flags); +extern LibError ogl_tex_transform_to(Handle ht, size_t new_flags); #endif // #ifndef INCLUDED_OGL_TEX diff --git a/source/lib/res/graphics/tests/test_tex.h b/source/lib/res/graphics/tests/test_tex.h index db875ef835..4b583beb6d 100644 --- a/source/lib/res/graphics/tests/test_tex.h +++ b/source/lib/res/graphics/tests/test_tex.h @@ -6,7 +6,7 @@ class TestTex : public CxxTest::TestSuite { - void generate_encode_decode_compare(uint w, uint h, uint flags, uint bpp, const std::string& extension) + void generate_encode_decode_compare(size_t w, size_t h, int flags, size_t bpp, const std::string& extension) { // generate test data const size_t size = w*h*bpp/8; @@ -60,14 +60,14 @@ public: TS_ASSERT_EQUALS(c, correct_c); // for each test width/height combination - const uint widths [] = { 4, 5, 4, 256, 384 }; - const uint heights[] = { 4, 4, 5, 256, 256 }; + const size_t widths [] = { 4, 5, 4, 256, 384 }; + const size_t heights[] = { 4, 4, 5, 256, 256 }; for(size_t i = 0; i < ARRAY_SIZE(widths); i++) { // for each bit depth - for(uint bpp = 8; bpp <= 32; bpp += 8) + for(size_t bpp = 8; bpp <= 32; bpp += 8) { - uint flags = 0; + int flags = 0; if(!strcmp(extension, ".dds")) flags |= (TEX_DXT&3); // DXT3 if(bpp == 8) diff --git a/source/lib/res/graphics/unifont.cpp b/source/lib/res/graphics/unifont.cpp index 840bb69481..a9fdb9cf4a 100644 --- a/source/lib/res/graphics/unifont.cpp +++ b/source/lib/res/graphics/unifont.cpp @@ -35,7 +35,7 @@ struct UniFont glyphmap_id* glyphs_id; // Stored as pointers to keep the struct's size down. (sizeof(std::map)==12, though that's probably not enough to matter) glyphmap_size* glyphs_size; - uint ListBase; + GLuint ListBase; int LineSpacing; int Height; // of a capital letter, roughly }; @@ -188,7 +188,7 @@ static LibError UniFont_to_string(const UniFont* f, char* buf) } -Handle unifont_load(const VfsPath& pathname, uint flags) +Handle unifont_load(const VfsPath& pathname, int flags) { return h_alloc(H_UniFont, pathname, flags); } diff --git a/source/lib/res/graphics/unifont.h b/source/lib/res/graphics/unifont.h index 97af27545a..90b76d498e 100644 --- a/source/lib/res/graphics/unifont.h +++ b/source/lib/res/graphics/unifont.h @@ -15,7 +15,7 @@ // Load and return a handle to the font defined // in fn+".fnt" with texture fn+".tga" -extern Handle unifont_load(const VfsPath& pathname, uint flags = 0); +extern Handle unifont_load(const VfsPath& pathname, int flags = 0); // Release a handle to a previously loaded font extern LibError unifont_unload(Handle& h); diff --git a/source/lib/res/h_mgr.cpp b/source/lib/res/h_mgr.cpp index a79dde79b9..9f8d8619ed 100644 --- a/source/lib/res/h_mgr.cpp +++ b/source/lib/res/h_mgr.cpp @@ -21,7 +21,7 @@ #include "lib/module_init.h" -static const uint MAX_EXTANT_HANDLES = 10000; +static const size_t MAX_EXTANT_HANDLES = 10000; // rationale // @@ -54,13 +54,13 @@ static const uint MAX_EXTANT_HANDLES = 10000; // - tag (1-based) ensures the handle references a certain resource instance. // (field width determines maximum unambiguous resource allocs) #define TAG_BITS 32 -const uint TAG_SHIFT = 0; +const size_t TAG_SHIFT = 0; const u32 TAG_MASK = 0xFFFFFFFF; // safer than (1 << 32) - 1 // - index (0-based) of control block in our array. // (field width determines maximum currently open handles) #define IDX_BITS 16 -const uint IDX_SHIFT = 32; +const size_t IDX_SHIFT = 32; const u32 IDX_MASK = (1l << IDX_BITS) - 1; // make sure both fields fit within a Handle variable @@ -103,10 +103,10 @@ static inline Handle handle(const u32 _idx, const u32 tag) // determines maximum number of references to a resource. -static const uint REF_BITS = 16; +static const size_t REF_BITS = 16; static const u32 REF_MAX = (1ul << REF_BITS)-1; -static const uint TYPE_BITS = 8; +static const size_t TYPE_BITS = 8; // chosen so that all current resource structs are covered, @@ -137,7 +137,7 @@ struct HDATA H_Type type; // for statistics - uint num_derefs; + size_t num_derefs; VfsPath pathname; @@ -146,20 +146,20 @@ struct HDATA // max data array entries. compared to last_in_use => signed. -static const i32 hdata_cap = 1ul << IDX_BITS; +static const ssize_t hdata_cap = 1ul << IDX_BITS; // allocate entries as needed so as not to waste memory // (hdata_cap may be large). deque-style array of pages // to balance locality, fragmentation, and waste. static const size_t PAGE_SIZE = 4096; -static const uint hdata_per_page = PAGE_SIZE / sizeof(HDATA); -static const uint num_pages = hdata_cap / hdata_per_page; +static const size_t hdata_per_page = PAGE_SIZE / sizeof(HDATA); +static const size_t num_pages = hdata_cap / hdata_per_page; static HDATA* pages[num_pages]; // these must be signed, because there won't always be a valid // first or last element. -static i32 first_free = -1; // don't want to scan array every h_alloc -static i32 last_in_use = -1; // don't search unused entries +static ssize_t first_free = -1; // don't want to scan array every h_alloc +static ssize_t last_in_use = -1; // don't search unused entries // error checking strategy: @@ -172,7 +172,7 @@ static i32 last_in_use = -1; // don't search unused entries // for the first time, and there's not enough memory to allocate it. // // also used by h_data, and alloc_idx to find a free entry. -static HDATA* h_data_from_idx(const i32 idx) +static HDATA* h_data_from_idx(const ssize_t idx) { // don't compare against last_in_use - this is called before allocating // new entries, and to check if the next (but possibly not yet valid) @@ -187,7 +187,7 @@ static HDATA* h_data_from_idx(const i32 idx) return 0; // Initialise all the VfsPath members - for(uint i = 0; i < hdata_per_page; ++i) + for(size_t i = 0; i < hdata_per_page; ++i) new (&page[i].pathname) VfsPath; } @@ -204,7 +204,7 @@ static HDATA* h_data_from_idx(const i32 idx) // used by h_force_close (which must work regardless of tag). static inline HDATA* h_data_no_tag(const Handle h) { - i32 idx = (i32)h_idx(h); + ssize_t idx = (ssize_t)h_idx(h); // need to verify it's in range - h_data_from_idx can only verify that // it's < maximum allowable index. if(0 > idx || idx > last_in_use) @@ -252,7 +252,7 @@ static HDATA* h_data_tag_type(const Handle h, const H_Type type) // idx and hd are undefined if we fail. // called by h_alloc only. -static LibError alloc_idx(i32& idx, HDATA*& hd) +static LibError alloc_idx(ssize_t& idx, HDATA*& hd) { // we already know the first free entry if(first_free != -1) @@ -305,7 +305,7 @@ have_idx:; } -static LibError free_idx(i32 idx) +static LibError free_idx(ssize_t idx) { if(first_free == -1 || idx < first_free) first_free = idx; @@ -329,7 +329,7 @@ static LibError free_idx(i32 idx) // that wasn't forseen here, so we'll just refrain from adding to the index. // that means they won't be found via h_find - no biggie. -typedef STL_HASH_MULTIMAP Key2Idx; +typedef STL_HASH_MULTIMAP Key2Idx; typedef Key2Idx::iterator It; static OverrunProtector key2idx_wrapper; @@ -350,7 +350,7 @@ static Handle key_find(uintptr_t key, H_Type type, KeyRemoveFlag remove_option = std::pair range = key2idx->equal_range(key); for(It it = range.first; it != range.second; ++it) { - i32 idx = it->second; + ssize_t idx = it->second; HDATA* hd = h_data_from_idx(idx); // found match if(hd && hd->type == type && hd->key == key) @@ -373,7 +373,7 @@ static void key_add(uintptr_t key, Handle h) if(!key2idx) return; - const i32 idx = h_idx(h); + const ssize_t idx = h_idx(h); // note: MSDN documentation of stdext::hash_multimap is incorrect; // there is no overload of insert() that returns pair. (void)key2idx->insert(std::make_pair(key, idx)); @@ -444,7 +444,7 @@ static u32 gen_tag() } -static Handle reuse_existing_handle(uintptr_t key, H_Type type, uint flags) +static Handle reuse_existing_handle(uintptr_t key, H_Type type, int flags) { if(flags & RES_NO_CACHE) return 0; @@ -506,9 +506,9 @@ static LibError call_init_and_reload(Handle h, H_Type type, HDATA* hd, const Vfs } -static Handle alloc_new_handle(H_Type type, const VfsPath& pathname, uintptr_t key, uint flags, va_list* init_args) +static Handle alloc_new_handle(H_Type type, const VfsPath& pathname, uintptr_t key, int flags, va_list* init_args) { - i32 idx; + ssize_t idx; HDATA* hd; RETURN_ERR(alloc_idx(idx, hd)); @@ -549,7 +549,7 @@ fail: // any further params are passed to type's init routine -Handle h_alloc(H_Type type, const VfsPath& pathname, uint flags, ...) +Handle h_alloc(H_Type type, const VfsPath& pathname, int flags, ...) { RETURN_ERR(type_validate(type)); @@ -575,7 +575,7 @@ Handle h_alloc(H_Type type, const VfsPath& pathname, uint flags, ...) //----------------------------------------------------------------------------- // currently cannot fail. -static LibError h_free_idx(i32 idx, HDATA* hd) +static LibError h_free_idx(ssize_t idx, HDATA* hd) { // debug_printf("free %s %s\n", type->name, hd->fn); @@ -623,7 +623,7 @@ static LibError h_free_idx(i32 idx, HDATA* hd) LibError h_free(Handle& h, H_Type type) { - i32 idx = h_idx(h); + ssize_t idx = h_idx(h); HDATA* hd = h_data_tag_type(h, type); // wipe out the handle to prevent reuse but keep a copy for below. @@ -690,7 +690,7 @@ LibError h_reload(const VfsPath& pathname) // do this before reloading any of them, because we don't specify reload // order (the parent resource may be reloaded first, and load the child, // whose original data would leak). - for(i32 i = 0; i <= last_in_use; i++) + for(ssize_t i = 0; i <= last_in_use; i++) { HDATA* hd = h_data_from_idx(i); if(!hd || hd->key != key || hd->disallow_reload) @@ -701,7 +701,7 @@ LibError h_reload(const VfsPath& pathname) LibError ret = INFO::OK; // now reload all affected handles - for(i32 i = 0; i <= last_in_use; i++) + for(ssize_t i = 0; i <= last_in_use; i++) { HDATA* hd = h_data_from_idx(i); if(!hd || hd->key != key || hd->disallow_reload) @@ -805,7 +805,7 @@ void h_mgr_shutdown() debug_printf("H_MGR| shutdown. any handle frees after this are leaks!\n"); // forcibly close all open handles - for(i32 i = 0; i <= last_in_use; i++) + for(ssize_t i = 0; i <= last_in_use; i++) { HDATA* hd = h_data_from_idx(i); // can't fail - i is in bounds by definition, and @@ -829,10 +829,10 @@ void h_mgr_shutdown() } // free HDATA array - for(uint j = 0; j < num_pages; j++) + for(size_t j = 0; j < num_pages; j++) { if (pages[j]) - for(uint k = 0; k < hdata_per_page; ++k) + for(size_t k = 0; k < hdata_per_page; ++k) pages[j][k].pathname.~VfsPath(); // FIXME: ugly hack, but necessary to reclaim std::string memory free(pages[j]); pages[j] = 0; diff --git a/source/lib/res/h_mgr.h b/source/lib/res/h_mgr.h index 3c5d5c7252..fcea057322 100644 --- a/source/lib/res/h_mgr.h +++ b/source/lib/res/h_mgr.h @@ -67,7 +67,7 @@ your actual definition must match. struct Res1 { void* data; // data loaded from file - uint flags; // set when resource is created + int flags; // set when resource is created }; Note that all control blocks are stored in fixed-size slots @@ -376,7 +376,7 @@ const size_t H_STRING_LEN = 256; //// user_size is checked to make sure the user data fits in the handle data space. // dtor is associated with type and called when the object is freed. // handle data is initialized to 0; optionally, a pointer to it is returned. -extern Handle h_alloc(H_Type type, const VfsPath& pathname, uint flags = 0, ...); +extern Handle h_alloc(H_Type type, const VfsPath& pathname, int flags = 0, ...); extern LibError h_free(Handle& h, H_Type type); diff --git a/source/lib/res/sound/snd_mgr.cpp b/source/lib/res/sound/snd_mgr.cpp index 25e570eb27..6e735f0ba6 100644 --- a/source/lib/res/sound/snd_mgr.cpp +++ b/source/lib/res/sound/snd_mgr.cpp @@ -454,15 +454,15 @@ static void al_buf_shutdown() // regardless of sound card caps, we won't use more than this ("enough"). // necessary in case OpenAL doesn't limit #sources (e.g. if SW mixing). -static const uint AL_SRC_MAX = 64; +static const size_t AL_SRC_MAX = 64; // stack of sources (first allocated is [0]) static ALuint al_srcs[AL_SRC_MAX]; // number of valid sources in al_srcs[] (set by al_src_init) -static uint al_src_allocated; +static size_t al_src_allocated; // number of sources currently in use -static uint al_src_used = 0; +static size_t al_src_used = 0; // user-set limit on how many sources may be used -static uint al_src_cap = AL_SRC_MAX; +static size_t al_src_cap = AL_SRC_MAX; /** @@ -472,7 +472,7 @@ static uint al_src_cap = AL_SRC_MAX; static void al_src_init() { // grab as many sources as possible and count how many we get. - for(uint i = 0; i < AL_SRC_MAX; i++) + for(size_t i = 0; i < AL_SRC_MAX; i++) { alGenSources(1, &al_srcs[i]); // we've reached the limit, no more are available. @@ -503,7 +503,7 @@ static void al_src_shutdown() AL_CHECK; - alDeleteSources(al_src_allocated, al_srcs); + alDeleteSources((ALsizei)al_src_allocated, al_srcs); AL_CHECK; @@ -551,7 +551,7 @@ static void al_src_free(ALuint al_src) * @param limit max. number of sources * @return LibError */ -LibError snd_set_max_voices(uint limit) +LibError snd_set_max_voices(size_t limit) { // valid if cap is legit (less than what we allocated in al_src_init), // or if al_src_init hasn't been called yet. note: we accept anything @@ -729,7 +729,7 @@ struct SndData ALuint al_buf; - uint is_valid : 1; + size_t is_valid : 1; #ifdef OGG_HACK // pointer to Ogg instance @@ -824,7 +824,7 @@ static LibError SndData_validate(const SndData * sd) { if(sd->al_fmt == 0) WARN_RETURN(ERR::_11); - if((uint)sd->al_freq > 100000) // suspicious + if((size_t)sd->al_freq > 100000) // suspicious WARN_RETURN(ERR::_12); if(sd->al_buf == 0) WARN_RETURN(ERR::_13); @@ -1163,7 +1163,7 @@ struct VSrc ALfloat cone_gain; /// controls vsrc_update behavior (VSrcFlags) - uint flags; + int flags; ALuint al_src; @@ -1178,7 +1178,7 @@ H_TYPE_DEFINE(VSrc); static void VSrc_init(VSrc* vs, va_list args) { - vs->flags = va_arg(args, uint); + vs->flags = va_arg(args, int); vs->fade.type = FT_NONE; } @@ -1284,7 +1284,7 @@ static LibError VSrc_to_string(const VSrc* vs, char * buf) */ Handle snd_open(const VfsPath& pathname, bool is_stream) { - uint flags = 0; + int flags = 0; if(is_stream) flags |= VS_IS_STREAM; // note: RES_UNIQUE forces each instance to get a new resource @@ -1338,7 +1338,7 @@ static void list_add(VSrc* vs) * @param skip number of entries to skip (default 0) * @param end_idx if not the default value of 0, stop before that entry. */ -static void list_foreach(void (*cb)(VSrc*), uint skip = 0, uint end_idx = 0) +static void list_foreach(void (*cb)(VSrc*), size_t skip = 0, size_t end_idx = 0) { It begin = vsrcs.begin() + skip; It end = vsrcs.end(); @@ -1979,7 +1979,7 @@ static LibError vm_update() // partition list; the first al_src_cap will be granted a source // (if they don't have one already), after reclaiming all sources from // the remainder of the VSrc list entries. - uint first_unimportant = std::min((uint)vsrcs.size(), al_src_cap); + size_t first_unimportant = std::min((size_t)vsrcs.size(), al_src_cap); list_foreach(reclaim, first_unimportant, 0); list_foreach(grant, 0, first_unimportant); diff --git a/source/lib/res/sound/snd_mgr.h b/source/lib/res/sound/snd_mgr.h index 3fdb4d3a58..047de5289d 100644 --- a/source/lib/res/sound/snd_mgr.h +++ b/source/lib/res/sound/snd_mgr.h @@ -132,7 +132,7 @@ extern LibError snd_dev_set(const char* alc_new_dev_name); * an implementation-defined limit anyway. * @return LibError **/ -extern LibError snd_set_max_voices(uint cap); +extern LibError snd_set_max_voices(size_t cap); /** * set amplitude modifier, which is effectively applied to all sounds. diff --git a/source/lib/self_test.h b/source/lib/self_test.h index 46ced39c10..703fd28891 100644 --- a/source/lib/self_test.h +++ b/source/lib/self_test.h @@ -27,7 +27,7 @@ Guidelines What makes a good self-test? - They belong in the module being tested to ensure they are kept in sync with it. -- It is easiest to attach them to low-level functions, e.g. log2_of_pow2, +- It is easiest to attach them to low-level functions, e.g. ceil_log2, rather than verifying the module's final result (e.g. checking renderer output by comparing pictures). - You should cover all cases: expected failures ("does it fail as expected?"), diff --git a/source/lib/sysdep/amd64/amd64.cpp b/source/lib/sysdep/amd64/amd64.cpp index 953e02babf..a4afe95d51 100644 --- a/source/lib/sysdep/amd64/amd64.cpp +++ b/source/lib/sysdep/amd64/amd64.cpp @@ -30,12 +30,12 @@ void cpu_AtomicAdd(volatile intptr_t* location, intptr_t increment) // note: ACPI processor detection not yet implemented here, so we treat // dual-core systems as multiprocessors. -uint cpu_NumPackages() +size_t cpu_NumPackages() { return cpu_NumProcessors(); } -uint cpu_CoresPerPackage() +size_t cpu_CoresPerPackage() { return 1; } diff --git a/source/lib/sysdep/amd64/amd64_asm.h b/source/lib/sysdep/amd64/amd64_asm.h new file mode 100644 index 0000000000..24bf8cf58a --- /dev/null +++ b/source/lib/sysdep/amd64/amd64_asm.h @@ -0,0 +1,25 @@ +/** + * ========================================================================= + * File : amd64_asm.h + * Project : 0 A.D. + * Description : interface to various AMD64 functions (written in asm) + * ========================================================================= + */ + +// license: GPL; see lib/license.txt + +#ifndef INCLUDED_AMD64_ASM +#define INCLUDED_AMD64_ASM + +#ifdef __cplusplus +extern "C" { +#endif + +struct Ia32CpuidRegs; +extern void CALL_CONV amd64_asm_cpuid(Ia32CpuidRegs* reg); + +#ifdef __cplusplus +} +#endif + +#endif // #ifndef INCLUDED_AMD64_ASM diff --git a/source/lib/sysdep/cpu.h b/source/lib/sysdep/cpu.h index f63ce9c60b..41aece8848 100644 --- a/source/lib/sysdep/cpu.h +++ b/source/lib/sysdep/cpu.h @@ -54,24 +54,24 @@ LIB_API double cpu_ClockFrequency(); * note: this function is necessary because POSIX sysconf _SC_NPROCESSORS_CONF * is not suppored on MacOSX, else we would use that. **/ -LIB_API uint cpu_NumProcessors(); +LIB_API size_t cpu_NumProcessors(); /** * @return number of *enabled* CPU packages / sockets. **/ -LIB_API uint cpu_NumPackages(); +LIB_API size_t cpu_NumPackages(); /** * @return number of *enabled* CPU cores per package. * (2 on dual-core systems) **/ -LIB_API uint cpu_CoresPerPackage(); +LIB_API size_t cpu_CoresPerPackage(); /** * @return number of *enabled* hyperthreading units per core. * (2 on P4 EE) **/ -LIB_API uint cpu_LogicalPerCore(); +LIB_API size_t cpu_LogicalPerCore(); /** * @return the size [bytes] of a MMU page. diff --git a/source/lib/sysdep/cursor.h b/source/lib/sysdep/cursor.h index 48c17931d0..fce2b1255c 100644 --- a/source/lib/sysdep/cursor.h +++ b/source/lib/sysdep/cursor.h @@ -10,8 +10,7 @@ // position where mouse clicks are registered. // cursor is only valid when INFO::OK is returned; in that case, it must be // sys_cursor_free-ed when no longer needed. -extern LibError sys_cursor_create(uint w, uint h, void* bgra_img, - uint hx, uint hy, void** cursor); +extern LibError sys_cursor_create(int w, int h, void* bgra_img, int hx, int hy, void** cursor); // create a fully transparent cursor (i.e. one that when passed to set hides // the system cursor) diff --git a/source/lib/sysdep/ia32/ia32.cpp b/source/lib/sysdep/ia32/ia32.cpp index e93a4d033f..576e325669 100644 --- a/source/lib/sysdep/ia32/ia32.cpp +++ b/source/lib/sysdep/ia32/ia32.cpp @@ -22,27 +22,69 @@ #include "lib/timer.h" #include "lib/sysdep/cpu.h" #include "ia32_memcpy.h" +#include "ia32_asm.h" +#include "../amd64/amd64_asm.h" +#include #if !MSC_VERSION && !GCC_VERSION -#error ia32.cpp needs inline assembly support! +# error we currently only support MSC/ICC or GCC #endif +// note: unfortunately the MSC __cpuid intrinsic does not allow passing +// additional inputs (e.g. ecx = count), so we need to implement this +// in assembly for both IA-32 and AMD64. +static void cpuid_impl(Ia32CpuidRegs* regs) +{ +#if ARCH_IA32 + ia32_asm_cpuid(regs); +#else // i.e. ARCH_AMD64 + amd64_asm_cpuid(regs); +#endif +} + +bool ia32_cpuid(Ia32CpuidRegs* regs) +{ + static u32 maxFunction; + static u32 maxExtendedFunction; + if(!maxFunction) + { + regs->eax = 0; + cpuid_impl(regs); + maxFunction = regs->eax; + regs->eax = 0x80000000; + cpuid_impl(regs); + maxExtendedFunction = regs->eax; + } + + const u32 function = regs->eax; + if(function > maxExtendedFunction) + return false; + if(function < 0x80000000 && function > maxFunction) + return false; + + cpuid_impl(regs); + return true; +} + + //----------------------------------------------------------------------------- // capability bits static void DetectFeatureFlags(u32 caps[4]) { - u32 regs[4]; - if(ia32_asm_cpuid(1, regs)) + Ia32CpuidRegs regs; + regs.eax = 1; + if(ia32_cpuid(®s)) { - caps[0] = regs[ECX]; - caps[1] = regs[EDX]; + caps[0] = regs.ecx; + caps[1] = regs.edx; } - if(ia32_asm_cpuid(0x80000001, regs)) + regs.eax = 0x80000001; + if(ia32_cpuid(®s)) { - caps[2] = regs[ECX]; - caps[3] = regs[EDX]; + caps[2] = regs.ecx; + caps[3] = regs.edx; } } @@ -57,8 +99,8 @@ bool ia32_cap(IA32Cap cap) if(!ia32_caps[1]) DetectFeatureFlags(ia32_caps); - const uint tbl_idx = cap >> 5; - const uint bit_idx = cap & 0x1f; + const size_t tbl_idx = cap >> 5; + const size_t bit_idx = cap & 0x1f; if(tbl_idx > 3) { DEBUG_WARN_ERR(ERR::INVALID_PARAM); @@ -73,17 +115,18 @@ bool ia32_cap(IA32Cap cap) static Ia32Vendor DetectVendor() { - u32 regs[4]; - if(!ia32_asm_cpuid(0, regs)) + Ia32CpuidRegs regs; + regs.eax = 0; + if(!ia32_cpuid(®s)) DEBUG_WARN_ERR(ERR::CPU_FEATURE_MISSING); // copy regs to string // note: 'strange' ebx,edx,ecx reg order is due to ModR/M encoding order. char vendor_str[13]; u32* vendor_str_u32 = (u32*)vendor_str; - vendor_str_u32[0] = regs[EBX]; - vendor_str_u32[1] = regs[EDX]; - vendor_str_u32[2] = regs[ECX]; + vendor_str_u32[0] = regs.ebx; + vendor_str_u32[1] = regs.edx; + vendor_str_u32[2] = regs.ecx; vendor_str[12] = '\0'; // 0-terminate if(!strcmp(vendor_str, "AuthenticAMD")) @@ -106,19 +149,20 @@ Ia32Vendor ia32_Vendor() } -static void DetectSignature(uint* model, uint* family) +static void DetectSignature(size_t* model, size_t* family) { - u32 regs[4]; - if(!ia32_asm_cpuid(1, regs)) + Ia32CpuidRegs regs; + regs.eax = 1; + if(!ia32_cpuid(®s)) DEBUG_WARN_ERR(ERR::CPU_FEATURE_MISSING); - *model = bits(regs[EAX], 4, 7); - *family = bits(regs[EAX], 8, 11); + *model = bits(regs.eax, 4, 7); + *family = bits(regs.eax, 8, 11); } -static uint DetectGeneration() +static size_t DetectGeneration() { - uint model, family; + size_t model, family; DetectSignature(&model, &family); switch(ia32_Vendor()) @@ -163,9 +207,9 @@ static uint DetectGeneration() return family; } -uint ia32_Generation() +size_t ia32_Generation() { - static uint generation; + static size_t generation; if(!generation) generation = DetectGeneration(); return generation; @@ -206,14 +250,16 @@ public: static void DetectIdentifierString(char* identifierString, size_t maxChars) { // get brand string (if available) - // note: ia32_asm_cpuid writes 4 u32s directly to identifierString - - // be very careful with pointer arithmetic! - u32* u32_string = (u32*)identifierString; - bool have_brand_string = false; - if(ia32_asm_cpuid(0x80000002, u32_string+0 ) && - ia32_asm_cpuid(0x80000003, u32_string+4) && - ia32_asm_cpuid(0x80000004, u32_string+8)) - have_brand_string = true; + char* pos = identifierString; + bool have_brand_string = true; + for(u32 function = 0x80000002; function <= 0x80000004; function++) + { + Ia32CpuidRegs regs; + regs.eax = function; + have_brand_string &= ia32_cpuid(®s); + memcpy(pos, ®s, 16); + pos += 16; + } // fall back to manual detect of CPU type because either: // - CPU doesn't support brand string (we use a flag to indicate this @@ -223,7 +269,7 @@ static void DetectIdentifierString(char* identifierString, size_t maxChars) // doesn't recognize. if(!have_brand_string || strncmp(identifierString, "Unknow", 6) == 0) { - uint model, family; + size_t model, family; DetectSignature(&model, &family); switch(ia32_Vendor()) @@ -399,12 +445,13 @@ double ia32_ClockFrequency() //----------------------------------------------------------------------------- // processor topology -uint ia32_ApicId() +u8 ia32_ApicId() { - u32 regs[4]; - if(!ia32_asm_cpuid(1, regs)) + Ia32CpuidRegs regs; + regs.eax = 1; + if(!ia32_cpuid(®s)) DEBUG_WARN_ERR(ERR::CPU_FEATURE_MISSING); - const uint apicId = bits(regs[EBX], 24, 31); + const u8 apicId = (u8)bits(regs.ebx, 24, 31); return apicId; } @@ -415,28 +462,30 @@ uint ia32_ApicId() // note: Intel Appnote 485 (CPUID) assures uniformity of coresPerPackage and // logicalPerCore. -static uint DetectCoresPerPackage() +static size_t DetectCoresPerPackage() { - u32 regs[4]; + Ia32CpuidRegs regs; switch(ia32_Vendor()) { case IA32_VENDOR_INTEL: - if(ia32_asm_cpuid(4, regs)) - return bits(regs[EAX], 26, 31)+1; + regs.eax = 4; + if(ia32_cpuid(®s)) + return bits(regs.eax, 26, 31)+1; break; case IA32_VENDOR_AMD: - if(ia32_asm_cpuid(0x80000008, regs)) - return bits(regs[ECX], 0, 7)+1; + regs.eax = 0x80000008; + if(ia32_cpuid(®s)) + return bits(regs.ecx, 0, 7)+1; break; } return 1; // else: the CPU is single-core. } -static uint CoresPerPackage() +static size_t CoresPerPackage() { - static uint coresPerPackage = 0; + static size_t coresPerPackage = 0; if(!coresPerPackage) coresPerPackage = DetectCoresPerPackage(); return coresPerPackage; @@ -457,15 +506,16 @@ static bool IsHyperthreadingCapable() return true; } -static uint DetectLogicalPerCore() +static size_t DetectLogicalPerCore() { if(!IsHyperthreadingCapable()) return 1; - u32 regs[4]; - if(!ia32_asm_cpuid(1, regs)) + Ia32CpuidRegs regs; + regs.eax = 1; + if(!ia32_cpuid(®s)) DEBUG_WARN_ERR(ERR::CPU_FEATURE_MISSING); - const uint logicalPerPackage = bits(regs[EBX], 16, 23); + const size_t logicalPerPackage = bits(regs.ebx, 16, 23); // cores ought to be uniform WRT # logical processors debug_assert(logicalPerPackage % CoresPerPackage() == 0); @@ -473,9 +523,9 @@ static uint DetectLogicalPerCore() return logicalPerPackage / CoresPerPackage(); } -static uint LogicalPerCore() +static size_t LogicalPerCore() { - static uint logicalPerCore = 0; + static size_t logicalPerCore = 0; if(!logicalPerCore) logicalPerCore = DetectLogicalPerCore(); return logicalPerCore; @@ -490,9 +540,9 @@ static uint LogicalPerCore() // determining the exact topology as well as number of packages. // these are set by DetectProcessorTopology. -static uint numPackages = 0; // i.e. sockets; > 1 => true SMP system -static uint enabledCoresPerPackage = 0; -static uint enabledLogicalPerCore = 0; // hyperthreading units +static size_t numPackages = 0; // i.e. sockets; > 1 => true SMP system +static size_t enabledCoresPerPackage = 0; +static size_t enabledLogicalPerCore = 0; // hyperthreading units typedef std::vector Ids; typedef std::set IdSet; @@ -509,18 +559,18 @@ static void StoreApicId(void* param) // for each id in apicIds: extract the value of the field at offset bit_pos // and insert it into ids. afterwards, adjust bit_pos to the next field. // used to gather e.g. all core IDs from all APIC IDs. -static void ExtractFieldsIntoSet(const Ids& apicIds, uint& bit_pos, uint num_values, IdSet& ids) +static void ExtractFieldsIntoSet(const Ids& apicIds, size_t& bit_pos, size_t num_values, IdSet& ids) { - const uint id_bits = ceil_log2(num_values); + const size_t id_bits = ceil_log2(num_values); if(id_bits == 0) return; - const uint mask = bit_mask(id_bits); + const u8 mask = bit_mask(id_bits); for(size_t i = 0; i < apicIds.size(); i++) { const u8 apic_id = apicIds[i]; - const u8 field = (apic_id >> bit_pos) & mask; + const u8 field = u8(apic_id >> bit_pos) & mask; ids.insert(field); } @@ -545,7 +595,7 @@ static bool DetectProcessorTopologyViaApicIds() debug_assert(std::unique(apicIds.begin(), apicIds.end()) == apicIds.end()); // extract values from all 3 ID bitfields into separate sets - uint bit_pos = 0; + size_t bit_pos = 0; IdSet logicalIds; ExtractFieldsIntoSet(apicIds, bit_pos, LogicalPerCore(), logicalIds); IdSet coreIds; @@ -555,9 +605,9 @@ static bool DetectProcessorTopologyViaApicIds() // (the set cardinality is representative of all packages/cores since // their numbers are uniform across the system.) - numPackages = std::max((uint)packageIds.size(), 1u); - enabledCoresPerPackage = std::max((uint)coreIds .size(), 1u); - enabledLogicalPerCore = std::max((uint)logicalIds.size(), 1u); + numPackages = std::max((size_t)packageIds.size(), 1u); + enabledCoresPerPackage = std::max((size_t)coreIds .size(), 1u); + enabledLogicalPerCore = std::max((size_t)logicalIds.size(), 1u); // note: even though APIC IDs are assigned sequentially, we can't make any // assumptions about the values/ordering because we get them according to @@ -569,7 +619,7 @@ static bool DetectProcessorTopologyViaApicIds() static void GuessProcessorTopologyViaOsCount() { - const int numProcessors = cpu_NumProcessors(); + const size_t numProcessors = cpu_NumProcessors(); // note: we cannot hope to always return correct results since disabled // cores/logical units cannot be distinguished from the situation of the @@ -583,7 +633,7 @@ static void GuessProcessorTopologyViaOsCount() enabledCoresPerPackage = CoresPerPackage(); enabledLogicalPerCore = LogicalPerCore(); - const long numPackagesTimesLogical = numProcessors / CoresPerPackage(); + const size_t numPackagesTimesLogical = numProcessors / CoresPerPackage(); debug_assert(numPackagesTimesLogical != 0); // otherwise processors didn't include cores, which would be stupid numPackages = numPackagesTimesLogical / LogicalPerCore(); @@ -604,68 +654,52 @@ static void DetectProcessorTopology() } -uint cpu_NumPackages() +size_t cpu_NumPackages() { if(!numPackages) DetectProcessorTopology(); - return (uint)numPackages; + return (size_t)numPackages; } -uint cpu_CoresPerPackage() +size_t cpu_CoresPerPackage() { if(!enabledCoresPerPackage) DetectProcessorTopology(); - return (uint)enabledCoresPerPackage; + return (size_t)enabledCoresPerPackage; } -uint cpu_LogicalPerCore() +size_t cpu_LogicalPerCore() { if(!enabledLogicalPerCore) DetectProcessorTopology(); - return (uint)enabledLogicalPerCore; + return (size_t)enabledLogicalPerCore; } //----------------------------------------------------------------------------- // misc stateless functions -// this RDTSC implementation writes edx:eax to a temporary and returns that. -// rationale: this insulates against changing compiler calling conventions, -// at the cost of some efficiency. -// use ia32_asm_rdtsc_edx_eax instead if the return convention is known to be -// edx:eax (should be the case on all 32-bit x86). -u64 ia32_rdtsc_safe() +u64 ia32_rdtsc() { - u64 c; #if MSC_VERSION - __asm - { - cpuid - rdtsc - mov dword ptr [c], eax - mov dword ptr [c+4], edx - } + return (u64)__rdtsc(); #elif GCC_VERSION - // note: we save+restore EBX to avoid xcode complaining about a - // "PIC register" being clobbered, whatever that means. - __asm__ __volatile__ ( - "pushl %%ebx; cpuid; popl %%ebx; rdtsc" - : "=A" (c) - : /* no input */ - : "ecx" /* cpuid clobbers eax..edx, but the rest are covered */); + // GCC supports "portable" assembly for both x86 and x86_64 + volatile u32 lo, hi; + asm volatile ("rdtsc" : "=a" (lo), "=d" (hi)); + return u64_from_u32(hi, lo); #endif - return c; } void ia32_DebugBreak() { #if MSC_VERSION - __asm int 3 - // note: this probably isn't necessary, since unix_debug_break - // (SIGTRAP) is most probably available if GCC_VERSION. - // we include it for completeness, though. + __debugbreak(); #elif GCC_VERSION + // note: this probably isn't necessary, since unix_debug_break + // (SIGTRAP) is most probably available if GCC_VERSION. + // we include it for completeness, though. __asm__ __volatile__ ("int $3"); #endif } @@ -674,13 +708,8 @@ void ia32_DebugBreak() // enforce strong memory ordering. void cpu_MemoryFence() { - // Pentium IV if(ia32_cap(IA32_CAP_SSE2)) -#if MSC_VERSION - __asm mfence -#elif GCC_VERSION - __asm__ __volatile__ ("mfence"); -#endif + _mm_mfence(); } @@ -785,7 +814,9 @@ bool cpu_CAS(volatile uintptr_t* location, uintptr_t expected, uintptr_t new_val void cpu_Serialize() { - return ia32_asm_Serialize(); + Ia32CpuidRegs regs; + regs.eax = 1; + ia32_cpuid(®s); // CPUID serializes execution. } void* cpu_memcpy(void* RESTRICT dst, const void* RESTRICT src, size_t size) diff --git a/source/lib/sysdep/ia32/ia32.h b/source/lib/sysdep/ia32/ia32.h index 0990386386..344080015d 100644 --- a/source/lib/sysdep/ia32/ia32.h +++ b/source/lib/sysdep/ia32/ia32.h @@ -11,13 +11,32 @@ #ifndef INCLUDED_IA32 #define INCLUDED_IA32 -#if !ARCH_IA32 -#error "including ia32.h without ARCH_IA32=1" +#if !ARCH_IA32 && !ARCH_AMD64 +#error "including ia32.h without ARCH_IA32=1 or ARCH_AMD64=1" #endif -#include "ia32_asm.h" -#include "lib/config2.h" // CONFIG2_IA32_RETURN64_EDX_EAX +/** + * registers used/returned by ia32_cpuid + **/ +struct Ia32CpuidRegs +{ + u32 eax; + u32 ebx; + u32 ecx; + u32 edx; +}; +/** + * invoke CPUID instruction. + * @param regs input/output registers. + * regs->eax must be set to the desired function. + * some functions (e.g. 4) require regs->ecx to be set as well. + * rationale: this interface (input/output structure vs. function parameters) + * avoids unnecessary copying/initialization if some inputs aren't needed + * and allows graceful expansion to functions that require further inputs. + * @return true on success or false if the sub-function isn't supported. + **/ +extern bool ia32_cpuid(Ia32CpuidRegs* regs); /** * CPU vendor. @@ -38,7 +57,7 @@ LIB_API Ia32Vendor ia32_Vendor(); * @return the colloquial processor generation * (5 = Pentium, 6 = Pentium Pro/II/III / K6, 7 = Pentium4 / Athlon, 8 = Core / Opteron) **/ -LIB_API uint ia32_Generation(); +LIB_API size_t ia32_Generation(); /** @@ -89,7 +108,7 @@ LIB_API bool ia32_cap(IA32Cap cap); * reliably on WinXP. also, the OS already has the APIC registers mapped and * in constant use, and we don't want to interfere. **/ -LIB_API uint ia32_ApicId(); +LIB_API u8 ia32_ApicId(); /** @@ -105,20 +124,12 @@ LIB_API uint ia32_ApicId(); LIB_API LibError ia32_GetCallTarget(void* ret_addr, void** target); -/// safe but slow inline-asm version -LIB_API u64 ia32_rdtsc_safe(void); - /** * @return the current value of the TimeStampCounter (a counter of * CPU cycles since power-on, which is useful for high-resolution timing * but potentially differs between multiple CPUs) **/ -LIB_API u64 ia32_rdtsc(); // only for CppDoc's benefit -#if CONFIG2_IA32_RETURN64_EDX_EAX -# define ia32_rdtsc ia32_asm_rdtsc_edx_eax -#else -# define ia32_rdtsc ia32_rdtsc_safe -#endif +LIB_API u64 ia32_rdtsc(); /** * trigger a breakpoint inside this function when it is called. diff --git a/source/lib/sysdep/ia32/ia32_asm.asm b/source/lib/sysdep/ia32/ia32_asm.asm index 38b1f35e54..0644a21be7 100644 --- a/source/lib/sysdep/ia32/ia32_asm.asm +++ b/source/lib/sysdep/ia32/ia32_asm.asm @@ -17,47 +17,16 @@ ; CPUID support ;------------------------------------------------------------------------------- -[section .data] - -max_func dd 0 -max_ext_func dd 0 - -__SECT__ - -; extern "C" bool __cdecl ia32_asm_cpuid(u32 func, u32* regs) +; extern "C" void __cdecl ia32_asm_cpuid(Ia32CpuidRegs* regs); global sym(ia32_asm_cpuid) sym(ia32_asm_cpuid): - push ebx - push edi + push ebx ; (clobbered by CPUID) + push edi ; (need a register other than eax..edx) - cmp dword [max_func], 0 - ja .already_initialized + mov edi, [esp+8+4] ; -> regs - ; determine max supported CPUID function - xor eax, eax - cpuid - mov [max_func], eax - mov eax, 0x80000000 - cpuid - mov [max_ext_func], eax -.already_initialized: - - mov edx, [esp+8+4+0] ; func - mov edi, [esp+8+4+4] ; -> regs - - ; compare against max supported func and fail if above - mov ebx, [max_ext_func] - xor eax, eax ; return value on failure - test edx, edx - js .is_ext_func - mov ebx, [max_func] -.is_ext_func: - cmp edx, ebx - ja .ret - - ; issue CPUID and store result registers in array - mov eax, edx - xor ecx, ecx ; CPUID.4 requires ECX = 0..2 + mov eax, [edi+0] ; eax (function) + mov ecx, [edi+8] ; ecx (count) cpuid stosd xchg eax, ebx @@ -67,10 +36,6 @@ sym(ia32_asm_cpuid): xchg eax, edx stosd - ; success - xor eax, eax - inc eax -.ret: pop edi pop ebx ret @@ -112,13 +77,6 @@ db 0xf0 ; LOCK prefix ret -; extern "C" bool __cdecl ia32_asm_Serialize(); -global sym(ia32_asm_Serialize) -sym(ia32_asm_Serialize): - cpuid - ret - - ;------------------------------------------------------------------------------- ; FPU ;------------------------------------------------------------------------------- @@ -132,7 +90,7 @@ round_bias dd 0.4999999 __SECT__ -; extern "C" uint __cdecl ia32_asm_control87(uint new_cw, uint mask); +; extern "C" size_t __cdecl ia32_asm_control87(size_t new_cw, size_t mask); global sym(ia32_asm_control87) sym(ia32_asm_control87): push eax @@ -154,7 +112,7 @@ sym(ia32_asm_control87): ; possible IA-32 FPU control word flags after FXAM: NAN|NORMAL|ZERO FP_CLASSIFY_MASK equ 0x4500 -; extern "C" uint __cdecl ia32_asm_fpclassifyd(double d); +; extern "C" size_t __cdecl ia32_asm_fpclassifyd(double d); global sym(ia32_asm_fpclassifyd) sym(ia32_asm_fpclassifyd): fld qword [esp+4] @@ -164,7 +122,7 @@ sym(ia32_asm_fpclassifyd): and eax, FP_CLASSIFY_MASK ret -; extern "C" uint __cdecl ia32_asm_fpclassifyf(float f); +; extern "C" size_t __cdecl ia32_asm_fpclassifyf(float f); global sym(ia32_asm_fpclassifyf) sym(ia32_asm_fpclassifyf): fld dword [esp+4] @@ -250,40 +208,6 @@ sym(ia32_asm_i64FromDouble): ; misc ;------------------------------------------------------------------------------- -; rationale: the common return convention for 64-bit values is in edx:eax. -; with inline asm, we'd have to MOV data to a temporary and return that; -; this is less efficient (-> important for low-overhead profiling) than -; making use of the convention. -; -; however, speed is not the main reason for providing this routine. -; xcode complains about CPUID clobbering ebx, so we use external asm -; where possible (IA-32 CPUs). -; -; extern "C" u64 ia32_asm_rdtsc_edx_eax(); -global sym(ia32_asm_rdtsc_edx_eax) -sym(ia32_asm_rdtsc_edx_eax): - push ebx - cpuid - pop ebx - rdtsc - ret - - -; extern "C" int ia32_asm_log2_of_pow2(uint n); -global sym(ia32_asm_log2_of_pow2) -sym(ia32_asm_log2_of_pow2): - mov ecx, [esp+4] ; n - or eax, -1 ; return value if not a POT - test ecx, ecx - jz .not_pot - lea edx, [ecx-1] - test ecx, edx - jnz .not_pot - bsf eax, ecx -.not_pot: - ret - - ; write the current execution state (e.g. all register values) into ; (Win32::CONTEXT*)pcontext (defined as void* to avoid dependency). ; optimized for size; this must be straight asm because ; extern "C" diff --git a/source/lib/sysdep/ia32/ia32_asm.h b/source/lib/sysdep/ia32/ia32_asm.h index 9275e62e5b..39fa309578 100644 --- a/source/lib/sysdep/ia32/ia32_asm.h +++ b/source/lib/sysdep/ia32/ia32_asm.h @@ -15,29 +15,11 @@ extern "C" { #endif - -/** - * order in which ia32_asm_cpuid stores register values - **/ -enum IA32Regs -{ - EAX, - EBX, - ECX, - EDX -}; - -/** - * try to call the specified CPUID sub-function. - * (note: ECX is set to 0 beforehand as required by sub-function 4) - * fills register array according to IA32Regs. - * @return true on success or false if the sub-function isn't supported. - **/ -extern bool CALL_CONV ia32_asm_cpuid(u32 func, u32* regs); +struct Ia32CpuidRegs; +extern void CALL_CONV ia32_asm_cpuid(Ia32CpuidRegs* regs); extern void CALL_CONV ia32_asm_AtomicAdd(volatile intptr_t* location, intptr_t increment); extern bool CALL_CONV ia32_asm_CAS(volatile uintptr_t* location, uintptr_t expected, uintptr_t new_value); -extern void CALL_CONV ia32_asm_Serialize(); /** @@ -45,11 +27,11 @@ extern void CALL_CONV ia32_asm_Serialize(); * with the bit values in new_val. * @return 0 to indicate success. **/ -extern uint CALL_CONV ia32_asm_control87(uint new_val, uint mask); +extern size_t CALL_CONV ia32_asm_control87(size_t new_val, size_t mask); /// see POSIX fpclassify -extern uint CALL_CONV ia32_asm_fpclassifyd(double d); -extern uint CALL_CONV ia32_asm_fpclassifyf(float f); +extern size_t CALL_CONV ia32_asm_fpclassifyd(double d); +extern size_t CALL_CONV ia32_asm_fpclassifyf(float f); /// see POSIX rintf extern float CALL_CONV ia32_asm_rintf(float); @@ -64,18 +46,6 @@ extern i32 CALL_CONV ia32_asm_i32FromDouble(double d); extern i64 CALL_CONV ia32_asm_i64FromDouble(double d); -/** - * @return the current value of the TimeStampCounter in edx:eax - * (interpretable as a u64 when using the standard Win32 calling convention) - **/ -extern u64 CALL_CONV ia32_asm_rdtsc_edx_eax(void); - -/** - * @return the (integral) base 2 logarithm, or -1 if the number - * is not a power-of-two. - **/ -extern int CALL_CONV ia32_asm_log2_of_pow2(uint n); - /** * write the current execution state (e.g. all register values) into * (Win32::CONTEXT*)pcontext (defined as void* to avoid dependency). diff --git a/source/lib/sysdep/linux/lcpu.cpp b/source/lib/sysdep/linux/lcpu.cpp index 0e293a3f1e..b031a610f1 100644 --- a/source/lib/sysdep/linux/lcpu.cpp +++ b/source/lib/sysdep/linux/lcpu.cpp @@ -13,13 +13,13 @@ double cpu_ClockFrequency() } -uint cpu_NumProcessors() +size_t cpu_NumProcessors() { long res = sysconf(_SC_NPROCESSORS_CONF); if (res == -1) return 0; else - return (uint)res; + return (size_t)res; } diff --git a/source/lib/sysdep/linux/ldbg.cpp b/source/lib/sysdep/linux/ldbg.cpp index 06eaeb3ee3..2fbd22a092 100644 --- a/source/lib/sysdep/linux/ldbg.cpp +++ b/source/lib/sysdep/linux/ldbg.cpp @@ -54,12 +54,12 @@ struct symbol_lookup_context bfd_vma address; const char* symbol; const char* filename; - uint line; + size_t line; bool found; }; -void* debug_get_nth_caller(uint n, void *UNUSED(context)) +void* debug_get_nth_caller(size_t n, void *UNUSED(context)) { // bt[0] == debug_get_nth_caller // bt[1] == caller of get_nth_caller @@ -72,13 +72,13 @@ void* debug_get_nth_caller(uint n, void *UNUSED(context)) return bt[n+1]; // n==1 => bt[2], and so forth } -LibError debug_dump_stack(wchar_t* buf, size_t max_chars, uint skip, void* UNUSED(context)) +LibError debug_dump_stack(wchar_t* buf, size_t max_chars, size_t skip, void* UNUSED(context)) { ++skip; // Skip ourselves too // bt[0..skip] == skipped // bt[skip..N_FRAMES+skip] == print - static const uint N_FRAMES = 16; + static const size_t N_FRAMES = 16; void *bt[skip+N_FRAMES]; int bt_size=0; wchar_t *bufpos = buf; @@ -89,9 +89,9 @@ LibError debug_dump_stack(wchar_t* buf, size_t max_chars, uint skip, void* UNUSE assert((bt_size >= (int)skip) && "Need at least frames in the backtrace"); // Assumed max length of a single print-out - static const uint MAX_OUT_CHARS=1024; + static const size_t MAX_OUT_CHARS=1024; - for (uint i=skip;(int)i l_nested_empty; std::map m_double_empty; std::multimap mm_int_empty; - std::set s_uint_empty; + std::set s_uint_empty; std::multiset ms_char_empty; std::vector v_double_empty; std::queue q_double_empty; @@ -191,7 +191,7 @@ class TestWdbgSym : public CxxTest::TestSuite std::list l_nested_uninit; std::map m_double_uninit; std::multimap mm_int_uninit; - std::set s_uint_uninit; + std::set s_uint_uninit; std::multiset ms_char_uninit; std::vector v_double_uninit; std::queue q_double_uninit; @@ -216,7 +216,7 @@ class TestWdbgSym : public CxxTest::TestSuite { debug_printf("\nTEST_ADDRS\n"); - uint l_uint = 0x1234; + size_t l_uint = 0x1234; bool l_bool = true; UNUSED2(l_bool); wchar_t l_wchars[] = L"wchar string"; enum TestEnum { VAL1=1, VAL2=2 } l_enum = VAL1; diff --git a/source/lib/sysdep/win/wcpu.cpp b/source/lib/sysdep/win/wcpu.cpp index cdb0c190d2..1fb297d02a 100644 --- a/source/lib/sysdep/win/wcpu.cpp +++ b/source/lib/sysdep/win/wcpu.cpp @@ -43,11 +43,11 @@ double cpu_ClockFrequency() } -uint cpu_NumProcessors() +size_t cpu_NumProcessors() { SYSTEM_INFO si; GetSystemInfo(&si); // can't fail - const uint numProcessors = (uint)si.dwNumberOfProcessors; + const size_t numProcessors = (size_t)si.dwNumberOfProcessors; return numProcessors; } diff --git a/source/lib/sysdep/win/wcursor.cpp b/source/lib/sysdep/win/wcursor.cpp index 834bb81b85..dcf78ca2ed 100644 --- a/source/lib/sysdep/win/wcursor.cpp +++ b/source/lib/sysdep/win/wcursor.cpp @@ -35,7 +35,7 @@ static HCURSOR HCURSOR_from_ptr(void* p) // position where mouse clicks are registered. // cursor is only valid when INFO::OK is returned; in that case, it must be // sys_cursor_free-ed when no longer needed. -LibError sys_cursor_create(uint w, uint h, void* bgra_img, uint hx, uint hy, void** cursor) +LibError sys_cursor_create(int w, int h, void* bgra_img, int hx, int hy, void** cursor) { // MSDN says selecting this HBITMAP into a DC is slower since we use // CreateBitmap; bpp/format must be checked against those of the DC. @@ -51,8 +51,8 @@ LibError sys_cursor_create(uint w, uint h, void* bgra_img, uint hx, uint hy, voi // fIcon and the hotspot definitions). ICONINFO ii; ii.fIcon = FALSE; // cursor - ii.xHotspot = hx; - ii.yHotspot = hy; + ii.xHotspot = (DWORD)hx; + ii.yHotspot = (DWORD)hy; ii.hbmMask = hbmMask; ii.hbmColor = hbmColour; HICON hIcon = CreateIconIndirect(&ii); diff --git a/source/lib/sysdep/win/wdbg_heap.cpp b/source/lib/sysdep/win/wdbg_heap.cpp index 9c86ce526a..daf084b43b 100644 --- a/source/lib/sysdep/win/wdbg_heap.cpp +++ b/source/lib/sysdep/win/wdbg_heap.cpp @@ -17,7 +17,7 @@ WINIT_REGISTER_EARLY_INIT2(wdbg_heap_Init); // wutil -> wdbg_heap void wdbg_heap_Enable(bool enable) { - uint flags = 0; + int flags = 0; if(enable) { flags |= _CRTDBG_ALLOC_MEM_DF; // enable checks at deallocation time @@ -403,12 +403,12 @@ static uintptr_t Expand(uintptr_t pc) } -static const uint numEncodedLengthBits = 2; +static const size_t numEncodedLengthBits = 2; static const size_t maxCallers = (sizeof(char*)+sizeof(int))*CHAR_BIT / (2+14); -static uint NumBitsForEncodedLength(uint encodedLength) +static size_t NumBitsForEncodedLength(size_t encodedLength) { - static const uint numBitsForEncodedLength[1u << numEncodedLengthBits] = + static const size_t numBitsForEncodedLength[1u << numEncodedLengthBits] = { 8, // 1K 14, // 64K @@ -418,11 +418,11 @@ static uint NumBitsForEncodedLength(uint encodedLength) return numBitsForEncodedLength[encodedLength]; } -static uint EncodedLength(uintptr_t quantizedOffset) +static size_t EncodedLength(uintptr_t quantizedOffset) { - for(uint encodedLength = 0; encodedLength < 1u << numEncodedLengthBits; encodedLength++) + for(size_t encodedLength = 0; encodedLength < 1u << numEncodedLengthBits; encodedLength++) { - const uint numBits = NumBitsForEncodedLength(encodedLength); + const size_t numBits = NumBitsForEncodedLength(encodedLength); const uintptr_t maxValue = (1u << numBits)-1; if(quantizedOffset <= maxValue) return encodedLength; @@ -450,26 +450,26 @@ static void FindCodeSegment() class BitStream { public: - BitStream(u8* storage, uint storageSize) + BitStream(u8* storage, size_t storageSize) : m_remainderBits(0), m_numRemainderBits(0) - , m_pos(storage), m_bitsLeft((uint)storageSize*8) + , m_pos(storage), m_bitsLeft((size_t)storageSize*8) { } - uint BitsLeft() const + size_t BitsLeft() const { return m_bitsLeft; } - void Write(const uint numOutputBits, uintptr_t outputValue) + void Write(const size_t numOutputBits, uintptr_t outputValue) { wdbg_assert(numOutputBits <= m_bitsLeft); wdbg_assert(outputValue < ((uintptr_t)1u << numOutputBits)); - uint outputBitsLeft = numOutputBits; + size_t outputBitsLeft = numOutputBits; while(outputBitsLeft > 0) { - const uint numBits = std::min(outputBitsLeft, 8u); + const size_t numBits = std::min(outputBitsLeft, 8u); m_bitsLeft -= numBits; // (NB: there is no need to extract exactly numBits because @@ -493,7 +493,7 @@ public: void Finish() { - const uint partialBits = m_numRemainderBits % 8; + const size_t partialBits = m_numRemainderBits % 8; if(partialBits) { m_bitsLeft -= 8-partialBits; @@ -515,20 +515,20 @@ public: } } - uintptr_t Read(const uint numInputBits) + uintptr_t Read(const size_t numInputBits) { wdbg_assert(numInputBits <= m_bitsLeft); uintptr_t inputValue = 0; - uint inputBitsLeft = numInputBits; + size_t inputBitsLeft = numInputBits; while(inputBitsLeft > 0) { - const uint numBits = std::min(inputBitsLeft, 8u); + const size_t numBits = std::min(inputBitsLeft, 8u); m_bitsLeft -= numBits; if(m_numRemainderBits < numBits) { - const uint inputByte = *m_pos++; + const size_t inputByte = *m_pos++; m_remainderBits |= inputByte << m_numRemainderBits; m_numRemainderBits += 8; } @@ -546,9 +546,9 @@ public: private: uintptr_t m_remainderBits; - uint m_numRemainderBits; + size_t m_numRemainderBits; u8* m_pos; - uint m_bitsLeft; + size_t m_bitsLeft; }; @@ -580,8 +580,8 @@ static void StashCallers(_CrtMemBlockHeader* header, const uintptr_t* callers, s for(size_t i = 0; i < quantizedPcSetSize; i++) { const uintptr_t quantizedOffset = quantizedOffsets[i]; - const uint encodedLength = EncodedLength(quantizedOffset); - const uint numBits = NumBitsForEncodedLength(encodedLength); + const size_t encodedLength = EncodedLength(quantizedOffset); + const size_t numBits = NumBitsForEncodedLength(encodedLength); if(bitStream.BitsLeft() < numEncodedLengthBits+numBits) break; bitStream.Write(numEncodedLengthBits, encodedLength); @@ -602,8 +602,8 @@ static void RetrieveCallers(_CrtMemBlockHeader* header, uintptr_t* callers, size { if(bitStream.BitsLeft() < numEncodedLengthBits) break; - const uint encodedLength = bitStream.Read(numEncodedLengthBits); - const uint numBits = NumBitsForEncodedLength(encodedLength); + const size_t encodedLength = bitStream.Read(numEncodedLengthBits); + const size_t numBits = NumBitsForEncodedLength(encodedLength); if(bitStream.BitsLeft() < numBits) break; const uintptr_t quantizedOffset = bitStream.Read(numBits); diff --git a/source/lib/sysdep/win/wdbg_sym.cpp b/source/lib/sysdep/win/wdbg_sym.cpp index 6164d13202..092646a8d4 100644 --- a/source/lib/sysdep/win/wdbg_sym.cpp +++ b/source/lib/sysdep/win/wdbg_sym.cpp @@ -24,6 +24,7 @@ #include "lib/path_util.h" #if ARCH_IA32 # include "lib/sysdep/ia32/ia32.h" +# include "lib/sysdep/ia32/ia32_asm.h" #endif #include "lib/external_libraries/dbghelp.h" #include "winit.h" @@ -270,7 +271,7 @@ static LibError ia32_walk_stack(_tagSTACKFRAME64* sf) #endif // #if ARCH_IA32 && !CONFIG_OMIT_FP -static void skip_this_frame(uint& skip, void* context) +static void skip_this_frame(size_t& skip, void* context) { if(!context) skip++; @@ -280,7 +281,7 @@ static void skip_this_frame(uint& skip, void* context) typedef VOID (*PRtlCaptureContext)(PCONTEXT); static PRtlCaptureContext s_RtlCaptureContext; -LibError wdbg_sym_WalkStack(StackFrameCallback cb, uintptr_t cbData, uint skip, const CONTEXT* pcontext) +LibError wdbg_sym_WalkStack(StackFrameCallback cb, uintptr_t cbData, size_t skip, const CONTEXT* pcontext) { // to function properly, StackWalk64 requires a CONTEXT on // non-x86 systems (documented) or when in release mode (observed). @@ -413,7 +414,7 @@ static LibError nth_caller_cb(const _tagSTACKFRAME64* sf, uintptr_t cbData) return INFO::OK; } -void* debug_get_nth_caller(uint skip, void* pcontext) +void* debug_get_nth_caller(size_t skip, void* pcontext) { void* func; skip_this_frame(skip, pcontext); @@ -429,14 +430,14 @@ void* debug_get_nth_caller(uint skip, void* pcontext) // overflow is impossible in practice, but check for robustness. // keep in sync with DumpState. -static const uint MAX_INDIRECTION = 255; -static const uint MAX_LEVEL = 255; +static const size_t MAX_INDIRECTION = 255; +static const size_t MAX_LEVEL = 255; struct DumpState { // keep in sync with MAX_* above - uint level : 8; - uint indirection : 8; + size_t level : 8; + size_t indirection : 8; DumpState() { @@ -561,7 +562,7 @@ static LibError out_check_limit() //---------------------------------------------------------------------------- -#define INDENT STMT(for(uint i = 0; i <= state.level; i++) out(L" ");) +#define INDENT STMT(for(size_t i = 0; i <= state.level; i++) out(L" ");) #define UNINDENT STMT(out_erase((state.level+1)*4);) @@ -1034,7 +1035,7 @@ display_as_hex: else if(size == 8) fmt = L"0x%016I64X"; else - debug_assert(0); // invalid uint size + debug_assert(0); // invalid size_t size break; // character @@ -1168,7 +1169,7 @@ static LibError dump_sym_enum(DWORD type_id, const u8* p, DumpState UNUSED(state const DWORD* children = fcp.p.ChildId; // for each child (enumerant): - for(uint i = 0; i < num_children; i++) + for(size_t i = 0; i < num_children; i++) { DWORD child_data_id = children[i]; @@ -1785,7 +1786,7 @@ static LibError dump_frame_cb(const _tagSTACKFRAME64* sf, uintptr_t UNUSED(cbDat } -LibError debug_dump_stack(wchar_t* buf, size_t max_chars, uint skip, void* pcontext) +LibError debug_dump_stack(wchar_t* buf, size_t max_chars, size_t skip, void* pcontext) { static uintptr_t already_in_progress; if(!cpu_CAS(&already_in_progress, 0, 1)) diff --git a/source/lib/sysdep/win/wdbg_sym.h b/source/lib/sysdep/win/wdbg_sym.h index cdf46e2239..9f35f0beba 100644 --- a/source/lib/sysdep/win/wdbg_sym.h +++ b/source/lib/sysdep/win/wdbg_sym.h @@ -37,7 +37,7 @@ typedef LibError (*StackFrameCallback)(const _tagSTACKFRAME64* frame, uintptr_t * stack trace (which is triggered by debug_assert et al. in app code) because * nested stack traces are ignored and only the error is displayed. **/ -extern LibError wdbg_sym_WalkStack(StackFrameCallback cb, uintptr_t cbData = 0, uint skip = 0, const _CONTEXT* pcontext = 0); +extern LibError wdbg_sym_WalkStack(StackFrameCallback cb, uintptr_t cbData = 0, size_t skip = 0, const _CONTEXT* pcontext = 0); extern void wdbg_sym_WriteMinidump(_EXCEPTION_POINTERS* ep); diff --git a/source/lib/sysdep/win/wdll_ver.cpp b/source/lib/sysdep/win/wdll_ver.cpp index 174c7f2adf..ac86de8df3 100644 --- a/source/lib/sysdep/win/wdll_ver.cpp +++ b/source/lib/sysdep/win/wdll_ver.cpp @@ -52,7 +52,7 @@ static LibError ReadVersionString(const OsPath& modulePathname_, char* out_ver, WARN_RETURN(ERR::FAIL); u16* lang; // -> 16 bit language ID, 16 bit codepage - uint lang_len; + size_t lang_len; const BOOL ok = VerQueryValue(mem.get(), "\\VarFileInfo\\Translation", (void**)&lang, &lang_len); if(!ok || !lang || lang_len != 4) WARN_RETURN(ERR::FAIL); @@ -60,7 +60,7 @@ static LibError ReadVersionString(const OsPath& modulePathname_, char* out_ver, char subblock[64]; sprintf(subblock, "\\StringFileInfo\\%04X%04X\\FileVersion", lang[0], lang[1]); const char* in_ver; - uint in_ver_len; + size_t in_ver_len; if(!VerQueryValue(mem.get(), subblock, (void**)&in_ver, &in_ver_len)) WARN_RETURN(ERR::FAIL); diff --git a/source/lib/sysdep/win/whrt/counter.cpp b/source/lib/sysdep/win/whrt/counter.cpp index 8bf9333cd7..9d99854d6a 100644 --- a/source/lib/sysdep/win/whrt/counter.cpp +++ b/source/lib/sysdep/win/whrt/counter.cpp @@ -31,7 +31,7 @@ * the given address, or 0 iff the ID is invalid. * @param size maximum allowable size [bytes] of the subclass instance **/ -static ICounter* ConstructCounterAt(uint id, void* address, size_t size) +static ICounter* ConstructCounterAt(size_t id, void* address, size_t size) { // rationale for placement new: see call site. @@ -66,7 +66,7 @@ static ICounter* ConstructCounterAt(uint id, void* address, size_t size) static volatile uintptr_t isCounterAllocated; -ICounter* CreateCounter(uint id) +ICounter* CreateCounter(size_t id) { // we placement-new the Counter classes in a static buffer. // this is dangerous, but we are careful to ensure alignment. it is diff --git a/source/lib/sysdep/win/whrt/counter.h b/source/lib/sysdep/win/whrt/counter.h index e675312d7e..c13ce4b773 100644 --- a/source/lib/sysdep/win/whrt/counter.h +++ b/source/lib/sysdep/win/whrt/counter.h @@ -42,7 +42,7 @@ public: * WHRT uses this to ensure the counter (running at nominal frequency) * doesn't overflow more than once during CALIBRATION_INTERVAL_MS. **/ - virtual uint CounterBits() const = 0; + virtual size_t CounterBits() const = 0; /** * initial measurement of the tick rate. not necessarily correct @@ -68,7 +68,7 @@ public: * there can only be one active counter at a time; the previous one must * have been destroyed before creating another! **/ -extern ICounter* CreateCounter(uint id); +extern ICounter* CreateCounter(size_t id); /** * shut down the counter, free its resources and zero its pointer. diff --git a/source/lib/sysdep/win/whrt/hpet.cpp b/source/lib/sysdep/win/whrt/hpet.cpp index 2141546dc5..a4db07dd11 100644 --- a/source/lib/sysdep/win/whrt/hpet.cpp +++ b/source/lib/sysdep/win/whrt/hpet.cpp @@ -104,10 +104,10 @@ u64 CounterHPET::Counter() const * WHRT uses this to ensure the counter (running at nominal frequency) * doesn't overflow more than once during CALIBRATION_INTERVAL_MS. **/ -uint CounterHPET::CounterBits() const +size_t CounterHPET::CounterBits() const { const u64 caps = m_hpetRegisters->capabilities; - const uint counterBits = (caps & CAP_SIZE64)? 64 : 32; + const size_t counterBits = (caps & CAP_SIZE64)? 64 : 32; return counterBits; } @@ -118,7 +118,7 @@ uint CounterHPET::CounterBits() const double CounterHPET::NominalFrequency() const { const u64 caps = m_hpetRegisters->capabilities; - const u32 timerPeriod_fs = bits64(caps, 32, 63); + const u32 timerPeriod_fs = (u32)bits(caps, 32, 63); const double frequency = 1e15 / timerPeriod_fs; return frequency; } diff --git a/source/lib/sysdep/win/whrt/hpet.h b/source/lib/sysdep/win/whrt/hpet.h index f85c922ec2..7971ec709b 100644 --- a/source/lib/sysdep/win/whrt/hpet.h +++ b/source/lib/sysdep/win/whrt/hpet.h @@ -38,7 +38,7 @@ public: * WHRT uses this to ensure the counter (running at nominal frequency) * doesn't overflow more than once during CALIBRATION_INTERVAL_MS. **/ - virtual uint CounterBits() const; + virtual size_t CounterBits() const; /** * initial measurement of the tick rate. not necessarily correct diff --git a/source/lib/sysdep/win/whrt/pmt.cpp b/source/lib/sysdep/win/whrt/pmt.cpp index 0702e71c1e..daeee75258 100644 --- a/source/lib/sysdep/win/whrt/pmt.cpp +++ b/source/lib/sysdep/win/whrt/pmt.cpp @@ -73,12 +73,12 @@ u64 CounterPMT::Counter() const * WHRT uses this to ensure the counter (running at nominal frequency) * doesn't overflow more than once during CALIBRATION_INTERVAL_MS. **/ -uint CounterPMT::CounterBits() const +size_t CounterPMT::CounterBits() const { // (see previous acpi_GetTable call) const FADT* fadt = (const FADT*)acpi_GetTable("FACP"); debug_assert(fadt); // Activate made sure FADT is available - const uint counterBits = (fadt->flags & TMR_VAL_EXT)? 32 : 24; + const size_t counterBits = (fadt->flags & TMR_VAL_EXT)? 32 : 24; return counterBits; } diff --git a/source/lib/sysdep/win/whrt/pmt.h b/source/lib/sysdep/win/whrt/pmt.h index 4dc7b7b48d..740afe189c 100644 --- a/source/lib/sysdep/win/whrt/pmt.h +++ b/source/lib/sysdep/win/whrt/pmt.h @@ -39,7 +39,7 @@ public: * WHRT uses this to ensure the counter (running at nominal frequency) * doesn't overflow more than once during CALIBRATION_INTERVAL_MS. **/ - virtual uint CounterBits() const; + virtual size_t CounterBits() const; /** * initial measurement of the tick rate. not necessarily correct diff --git a/source/lib/sysdep/win/whrt/qpc.cpp b/source/lib/sysdep/win/whrt/qpc.cpp index f99f1b6446..a51d0561e3 100644 --- a/source/lib/sysdep/win/whrt/qpc.cpp +++ b/source/lib/sysdep/win/whrt/qpc.cpp @@ -97,7 +97,7 @@ u64 CounterQPC::Counter() const * WHRT uses this to ensure the counter (running at nominal frequency) * doesn't overflow more than once during CALIBRATION_INTERVAL_MS. **/ -uint CounterQPC::CounterBits() const +size_t CounterQPC::CounterBits() const { // there are reports of incorrect rollover handling in the PMT // implementation of QPC (see CounterPMT::IsSafe). however, other diff --git a/source/lib/sysdep/win/whrt/qpc.h b/source/lib/sysdep/win/whrt/qpc.h index 3221b86a6d..f6050a9447 100644 --- a/source/lib/sysdep/win/whrt/qpc.h +++ b/source/lib/sysdep/win/whrt/qpc.h @@ -37,7 +37,7 @@ public: * WHRT uses this to ensure the counter (running at nominal frequency) * doesn't overflow more than once during CALIBRATION_INTERVAL_MS. **/ - virtual uint CounterBits() const; + virtual size_t CounterBits() const; /** * initial measurement of the tick rate. not necessarily correct diff --git a/source/lib/sysdep/win/whrt/tgt.cpp b/source/lib/sysdep/win/whrt/tgt.cpp index b3b2aaee72..a8d5f9493e 100644 --- a/source/lib/sysdep/win/whrt/tgt.cpp +++ b/source/lib/sysdep/win/whrt/tgt.cpp @@ -62,7 +62,7 @@ u64 CounterTGT::Counter() const * WHRT uses this to ensure the counter (running at nominal frequency) * doesn't overflow more than once during CALIBRATION_INTERVAL_MS. **/ -uint CounterTGT::CounterBits() const +size_t CounterTGT::CounterBits() const { return 32; } diff --git a/source/lib/sysdep/win/whrt/tgt.h b/source/lib/sysdep/win/whrt/tgt.h index 14845ef4c6..bb3076025c 100644 --- a/source/lib/sysdep/win/whrt/tgt.h +++ b/source/lib/sysdep/win/whrt/tgt.h @@ -32,7 +32,7 @@ public: * WHRT uses this to ensure the counter (running at nominal frequency) * doesn't overflow more than once during CALIBRATION_INTERVAL_MS. **/ - virtual uint CounterBits() const; + virtual size_t CounterBits() const; /** * initial measurement of the tick rate. not necessarily correct diff --git a/source/lib/sysdep/win/whrt/tsc.cpp b/source/lib/sysdep/win/whrt/tsc.cpp index 981fbbe717..428e329716 100644 --- a/source/lib/sysdep/win/whrt/tsc.cpp +++ b/source/lib/sysdep/win/whrt/tsc.cpp @@ -39,7 +39,7 @@ enum AmdPowerNowFlags static bool IsThrottlingPossible() { #if ARCH_IA32 - u32 regs[4]; + Ia32CpuidRegs regs; switch(ia32_Vendor()) { case IA32_VENDOR_INTEL: @@ -48,9 +48,10 @@ static bool IsThrottlingPossible() break; case IA32_VENDOR_AMD: - if(ia32_asm_cpuid(0x80000007, regs)) + regs.eax = 0x80000007; + if(ia32_cpuid(®s)) { - if(regs[EDX] & (PN_FREQ_ID_CTRL|PN_SW_THERMAL_CTRL)) + if(regs.edx & (PN_FREQ_ID_CTRL|PN_SW_THERMAL_CTRL)) return true; } break; @@ -113,11 +114,12 @@ bool CounterTSC::IsSafe() const // note: 8th generation CPUs support C1-clock ramping, which causes // drift on multi-core systems, but those were excluded above. - u32 regs[4]; - if(ia32_asm_cpuid(0x80000007, regs)) + Ia32CpuidRegs regs; + regs.eax = 0x80000007; + if(ia32_cpuid(®s)) { // TSC is invariant WRT P-state, C-state and STPCLK => safe. - if(regs[EDX] & PN_INVARIANT_TSC) + if(regs.edx & PN_INVARIANT_TSC) return true; } @@ -157,7 +159,7 @@ u64 CounterTSC::Counter() const * WHRT uses this to ensure the counter (running at nominal frequency) * doesn't overflow more than once during CALIBRATION_INTERVAL_MS. **/ -uint CounterTSC::CounterBits() const +size_t CounterTSC::CounterBits() const { return 64; } diff --git a/source/lib/sysdep/win/whrt/tsc.h b/source/lib/sysdep/win/whrt/tsc.h index bbbdf4673c..f6f38619f3 100644 --- a/source/lib/sysdep/win/whrt/tsc.h +++ b/source/lib/sysdep/win/whrt/tsc.h @@ -32,7 +32,7 @@ public: * WHRT uses this to ensure the counter (running at nominal frequency) * doesn't overflow more than once during CALIBRATION_INTERVAL_MS. **/ - virtual uint CounterBits() const; + virtual size_t CounterBits() const; /** * initial measurement of the tick rate. not necessarily correct diff --git a/source/lib/sysdep/win/whrt/whrt.cpp b/source/lib/sysdep/win/whrt/whrt.cpp index bea5ee9d3c..43849a53ab 100644 --- a/source/lib/sysdep/win/whrt/whrt.cpp +++ b/source/lib/sysdep/win/whrt/whrt.cpp @@ -54,7 +54,7 @@ static ICounter* GetNextBestSafeCounter() { for(;;) { - static uint nextCounterId = 0; + static size_t nextCounterId = 0; ICounter* counter = CreateCounter(nextCounterId++); if(!counter) return 0; // tried all, none were safe @@ -82,7 +82,7 @@ static ICounter* counter; // (these counter properties are cached for efficiency and convenience:) static double nominalFrequency; static double resolution; -static uint counterBits; +static size_t counterBits; static u64 counterMask; static void InitCounter() @@ -97,7 +97,7 @@ static void InitCounter() resolution = counter->Resolution(); counterBits = counter->CounterBits(); - counterMask = bit_mask64(counterBits); + counterMask = bit_mask(counterBits); // sanity checks debug_assert(nominalFrequency >= 500.0-DBL_EPSILON); @@ -244,7 +244,7 @@ static inline LibError InitUpdateThread() // make sure our interval isn't too long // (counterBits can be 64 => BIT64 would overflow => calculate period/2) const double period_2 = BIT64(counterBits-1) / nominalFrequency; - const uint rolloversPerInterval = UPDATE_INTERVAL_MS / cpu_i64FromDouble(period_2*2.0*1000.0); + const size_t rolloversPerInterval = UPDATE_INTERVAL_MS / cpu_i64FromDouble(period_2*2.0*1000.0); debug_assert(rolloversPerInterval <= 1); hExitEvent = CreateEvent(0, TRUE, FALSE, 0); // manual reset, initially false diff --git a/source/lib/sysdep/win/wposix/waio.cpp b/source/lib/sysdep/win/wposix/waio.cpp index e0336652aa..5e2138e4b4 100644 --- a/source/lib/sysdep/win/wposix/waio.cpp +++ b/source/lib/sysdep/win/wposix/waio.cpp @@ -389,7 +389,7 @@ int aio_suspend(const struct aiocb* const cbs[], int n, const struct timespec* t // build array of event handles HANDLE hEvents[MAXIMUM_WAIT_OBJECTS]; - unsigned numPendingIos = 0; + size_t numPendingIos = 0; for(int i = 0; i < n; i++) { if(!cbs[i]) // SUSv3 says NULL entries are to be ignored @@ -407,7 +407,7 @@ int aio_suspend(const struct aiocb* const cbs[], int n, const struct timespec* t const DWORD timeout = ts? (DWORD)(ts->tv_sec*1000 + ts->tv_nsec/1000000) : INFINITE; DWORD result = WaitForMultipleObjects(numPendingIos, hEvents, waitAll, timeout); - for(unsigned i = 0; i < numPendingIos; i++) + for(size_t i = 0; i < numPendingIos; i++) ResetEvent(hEvents[i]); switch(result) diff --git a/source/lib/sysdep/win/wposix/wposix.h b/source/lib/sysdep/win/wposix/wposix.h index 6d35eca880..80f2de7e48 100644 --- a/source/lib/sysdep/win/wposix/wposix.h +++ b/source/lib/sysdep/win/wposix/wposix.h @@ -13,7 +13,7 @@ /** * rationale: the Windows headers declare many POSIX functions (e.g. read). - * unfortunately, these are often slightly incorrect (size_t vs. uint). + * unfortunately, these are often slightly incorrect (size_t vs. size_t). * to avert trouble in user code caused by these differences, we declare * all functions ourselves according to SUSv3 and do not use the headers. * diff --git a/source/lib/sysdep/win/wposix/wpthread.cpp b/source/lib/sysdep/win/wposix/wpthread.cpp index 179cd5f1ff..a8cf8d450d 100644 --- a/source/lib/sysdep/win/wposix/wpthread.cpp +++ b/source/lib/sysdep/win/wposix/wpthread.cpp @@ -93,13 +93,13 @@ int pthread_setschedparam(pthread_t thread, int policy, const struct sched_param // minimum amount of TLS slots every Windows version provides; // used to validate indices. -static const uint TLS_LIMIT = 64; +static const size_t TLS_LIMIT = 64; // rationale: don't use an array of dtors for every possible TLS slot. // other DLLs may allocate any number of them in their DllMain, so the // array would have to be quite large. instead, store both key and dtor - // we are thus limited only by pthread_key_create calls (which we control). -static const uint MAX_DTORS = 4; +static const size_t MAX_DTORS = 4; static struct { pthread_key_t key; @@ -118,7 +118,7 @@ int pthread_key_create(pthread_key_t* key, void (*dtor)(void*)) *key = (pthread_key_t)idx; // acquire a free dtor slot - uint i; + size_t i; for(i = 0; i < MAX_DTORS; i++) { if(cpu_CAS((volatile uintptr_t*)&dtors[i].dtor, 0, (uintptr_t)dtor)) @@ -189,7 +189,7 @@ again: bool had_valid_tls = false; // for each registered dtor: (call order unspecified by SUSv3) - for(uint i = 0; i < MAX_DTORS; i++) + for(size_t i = 0; i < MAX_DTORS; i++) { // is slot #i in use? void (*dtor)(void*) = dtors[i].dtor; diff --git a/source/lib/sysdep/win/wposix/wtime.cpp b/source/lib/sysdep/win/wposix/wtime.cpp index 2796689c6d..d3264d3e8a 100644 --- a/source/lib/sysdep/win/wposix/wtime.cpp +++ b/source/lib/sysdep/win/wposix/wtime.cpp @@ -92,7 +92,7 @@ static timespec TimespecFromNs(i64 ns) return ts; } -static uint MsFromTimespec(const timespec& ts) +static size_t MsFromTimespec(const timespec& ts) { i64 ms = ts.tv_sec; // avoid overflow ms *= _1e3; @@ -132,11 +132,11 @@ int nanosleep(const struct timespec* rqtp, struct timespec* /* rmtp */) } -uint sleep(uint sec) +unsigned sleep(unsigned sec) { // warn if overflow would result (it would be insane to ask for // such lengthy sleep timeouts, but still) - debug_assert(sec < std::numeric_limits::max()/1000); + debug_assert(sec < std::numeric_limits::max()/1000); const DWORD ms = sec * 1000; if(ms) diff --git a/source/lib/sysdep/win/wposix/wtime.h b/source/lib/sysdep/win/wposix/wtime.h index c6db98799b..5646c67fdb 100644 --- a/source/lib/sysdep/win/wposix/wtime.h +++ b/source/lib/sysdep/win/wposix/wtime.h @@ -24,7 +24,7 @@ typedef long suseconds_t; // // -extern unsigned int sleep(unsigned int sec); +extern unsigned sleep(unsigned sec); extern int usleep(useconds_t us); diff --git a/source/lib/sysdep/win/wsdl.cpp b/source/lib/sysdep/win/wsdl.cpp index d6b51b1d52..7a0fff7b7b 100644 --- a/source/lib/sysdep/win/wsdl.cpp +++ b/source/lib/sysdep/win/wsdl.cpp @@ -380,7 +380,7 @@ static bool dequeue_event(SDL_Event* ev) enum SdlActivationType { LOSE = 0, GAIN = 1 }; -static inline void queue_active_event(SdlActivationType type, uint changed_app_state) +static inline void queue_active_event(SdlActivationType type, size_t changed_app_state) { // SDL says this event is not generated when the window is created, // but skipping the first event may confuse things. @@ -396,11 +396,11 @@ static inline void queue_active_event(SdlActivationType type, uint changed_app_s // SDL_APP* bitflags indicating whether we are active. // note: responsibility for yielding lies with SDL apps - // they control the main loop. -static uint app_state; +static Uint8 app_state; -static void active_change_state(SdlActivationType type, uint changed_app_state) +static void active_change_state(SdlActivationType type, size_t changed_app_state) { - uint old_app_state = app_state; + size_t old_app_state = app_state; if(type == GAIN) app_state |= changed_app_state; @@ -417,7 +417,7 @@ static void reset_all_keys(); static LRESULT OnActivate(HWND hWnd, UINT state, HWND UNUSED(hWndActDeact), BOOL fMinimized) { SdlActivationType type; - uint changed_app_state; + size_t changed_app_state; // went active and not minimized if(state != WA_INACTIVE && !fMinimized) @@ -471,12 +471,12 @@ static void queue_quit_event() // keyboard // note: keysym.unicode is only returned for SDL_KEYDOWN, and is otherwise 0. -static void queue_key_event(uint type, uint sdlk, WCHAR unicode_char) +static void queue_key_event(Uint8 type, SDLKey sdlk, WCHAR unicode_char) { SDL_Event ev; ev.type = type; - ev.key.keysym.sym = (SDLKey)sdlk; - ev.key.keysym.unicode = (u16)unicode_char; + ev.key.keysym.sym = sdlk; + ev.key.keysym.unicode = (Uint16)unicode_char; queue_event(ev); } @@ -602,7 +602,7 @@ static LRESULT OnKey(HWND UNUSED(hWnd), UINT vk, BOOL fDown, int UNUSED(cRepeat) // TODO Mappings for left/right modifier keys // TODO Modifier statekeeping - const uint sdlk = vkmap(vk); + const SDLKey sdlk = vkmap(vk); if(sdlk != SDLK_UNKNOWN) keys[sdlk] = (Uint8)fDown; @@ -667,10 +667,10 @@ int SDL_EnableUNICODE(int UNUSED(enable)) // - "idealized" client coords are what the app sees. these are from // 0..window dimensions-1. they are derived from client coords that // pass the is_in_window() test. unfortunately, these carry different -// types: we treat them exclusively as uint, while SDL API provides for +// types: we treat them exclusively as size_t, while SDL API provides for // passing them around as int and packages them into Uint16 in events. -static void queue_mouse_event(uint x, uint y) +static void queue_mouse_event(int x, int y) { SDL_Event ev; ev.type = SDL_MOUSEMOTION; @@ -680,7 +680,7 @@ static void queue_mouse_event(uint x, uint y) queue_event(ev); } -static void queue_button_event(uint button, uint state, uint x, uint y) +static void queue_button_event(int button, int state, int x, int y) { SDL_Event ev; ev.type = (state == SDL_PRESSED)? SDL_MOUSEBUTTONDOWN : SDL_MOUSEBUTTONUP; @@ -693,14 +693,14 @@ static void queue_button_event(uint button, uint state, uint x, uint y) } -static uint mouse_x, mouse_y; +static int mouse_x, mouse_y; // generate a mouse move message and update our notion of the mouse position. // x, y are client pixel coordinates. // notes: // - does not actually move the OS cursor; // - called from mouse_update and SDL_WarpMouse. -static void mouse_moved(uint x, uint y) +static void mouse_moved(int x, int y) { // nothing to do if it hasn't changed since last time if(mouse_x == x && mouse_y == y) @@ -725,7 +725,7 @@ static void screen_to_client(int screen_x, int screen_y, int& client_x, int& cli // are the given coords in our window? // parameters are client coords as returned by screen_to_client. -// postcondition: it is safe to cast coords to uint and treat them +// postcondition: it is safe to cast coords to size_t and treat them // as idealized client coords. static bool is_in_window(int client_x, int client_y) { @@ -761,7 +761,7 @@ static void mouse_update() if(is_in_window(client_x, client_y)) { - const uint x = (uint)client_x, y = (uint)client_y; + const int x = client_x, y = client_y; active_change_state(GAIN, SDL_APPMOUSEFOCUS); mouse_moved(x, y); @@ -771,14 +771,14 @@ static void mouse_update() active_change_state(LOSE, SDL_APPMOUSEFOCUS); } -static uint mouse_buttons; +static size_t mouse_buttons; // (we define a new function signature since the windowsx.h message crackers // don't provide for passing uMsg) static LRESULT OnMouseButton(HWND UNUSED(hWnd), UINT uMsg, int screen_x, int screen_y, UINT UNUSED(flags)) { - uint button; - uint state; + int button; + int state; switch(uMsg) { case WM_LBUTTONDOWN: @@ -839,7 +839,7 @@ static LRESULT OnMouseButton(HWND UNUSED(hWnd), UINT uMsg, int screen_x, int scr // false due to its window-on-top check, so we better not // ignore messages based on that. it is safest to clamp coords to // what the app can handle. - uint x = std::max(client_x, 0), y = std::max(client_y, 0); + int x = std::max(client_x, 0), y = std::max(client_y, 0); queue_button_event(button, state, x, y); return 0; } @@ -854,9 +854,9 @@ static LRESULT OnMouseWheel(HWND UNUSED(hWnd), int screen_x, int screen_y, int z // to prevent the app from seeing invalid coords, we ignore such messages. if(is_in_window(client_x, client_y)) { - const uint x = (uint)client_x, y = (uint)client_y; + const int x = client_x, y = client_y; - uint button = (zDelta < 0)? SDL_BUTTON_WHEELDOWN : SDL_BUTTON_WHEELUP; + int button = (zDelta < 0)? SDL_BUTTON_WHEELDOWN : SDL_BUTTON_WHEELUP; // SDL says this sends a down message followed by up. queue_button_event(button, SDL_PRESSED , x, y); queue_button_event(button, SDL_RELEASED, x, y); @@ -880,7 +880,7 @@ inline void SDL_WarpMouse(int x, int y) // SDL interface provides for int, but the values should be // idealized client coords (>= 0) debug_assert(x >= 0 && y >= 0); - mouse_moved((uint)x, (uint)y); + mouse_moved(x, y); POINT screen_pt; screen_pt.x = x; diff --git a/source/lib/sysdep/win/wseh.cpp b/source/lib/sysdep/win/wseh.cpp index befa7f455a..3efd58a580 100644 --- a/source/lib/sysdep/win/wseh.cpp +++ b/source/lib/sysdep/win/wseh.cpp @@ -203,7 +203,7 @@ static void GetExceptionLocus(const EXCEPTION_POINTERS* ep, // points to kernel32!RaiseException. we use debug_get_nth_caller to // determine the real location. - const uint skip = 1; // skip RaiseException + const size_t skip = 1; // skip RaiseException void* func_addr = debug_get_nth_caller(skip, ep->ContextRecord); (void)debug_resolve_symbol(func_addr, func, file, line); } @@ -264,7 +264,7 @@ long __stdcall wseh_ExceptionFilter(struct _EXCEPTION_POINTERS* ep) L"Details: unhandled exception (%s)\r\n"; swprintf(message, ARRAY_SIZE(message), messageFormat, description); - uint flags = 0; + int flags = 0; if(ep->ExceptionRecord->ExceptionFlags & EXCEPTION_NONCONTINUABLE) flags = DE_NO_CONTINUE; ErrorReaction er = debug_display_error(message, flags, 1,ep->ContextRecord, file,line,func, 0); diff --git a/source/lib/sysdep/win/wsysdep.cpp b/source/lib/sysdep/win/wsysdep.cpp index 6c9f4e9bc1..192e148223 100644 --- a/source/lib/sysdep/win/wsysdep.cpp +++ b/source/lib/sysdep/win/wsysdep.cpp @@ -46,13 +46,13 @@ void sys_display_msgw(const wchar_t* caption, const wchar_t* msg) static POINTS dlg_client_origin; static POINTS dlg_prev_client_size; -static const uint ANCHOR_LEFT = 0x01; -static const uint ANCHOR_RIGHT = 0x02; -static const uint ANCHOR_TOP = 0x04; -static const uint ANCHOR_BOTTOM = 0x08; -static const uint ANCHOR_ALL = 0x0f; +static const size_t ANCHOR_LEFT = 0x01; +static const size_t ANCHOR_RIGHT = 0x02; +static const size_t ANCHOR_TOP = 0x04; +static const size_t ANCHOR_BOTTOM = 0x08; +static const size_t ANCHOR_ALL = 0x0f; -static void dlg_resize_control(HWND hDlg, int dlg_item, int dx,int dy, uint anchors) +static void dlg_resize_control(HWND hDlg, int dlg_item, int dx,int dy, size_t anchors) { HWND hControl = GetDlgItem(hDlg, dlg_item); RECT r; @@ -120,7 +120,7 @@ static void dlg_resize(HWND hDlg, WPARAM wParam, LPARAM lParam) struct DialogParams { const wchar_t* text; - uint flags; + int flags; }; @@ -227,7 +227,7 @@ static INT_PTR CALLBACK error_dialog_proc(HWND hDlg, unsigned int msg, WPARAM wP // show error dialog with the given text and return user's reaction. // exits directly if 'exit' is clicked. -ErrorReaction sys_display_error(const wchar_t* text, uint flags) +ErrorReaction sys_display_error(const wchar_t* text, int flags) { // note: other threads might still be running, crash and take down the // process before we have a chance to display this error message. diff --git a/source/lib/sysdep/win/wutil.cpp b/source/lib/sysdep/win/wutil.cpp index 2bec83ff13..5b15d32e03 100644 --- a/source/lib/sysdep/win/wutil.cpp +++ b/source/lib/sysdep/win/wutil.cpp @@ -289,7 +289,7 @@ static void EnableLowFragmentationHeap() // version static char windowsVersionString[20]; -static uint windowsVersion; // see WUTIL_VERSION_* +static size_t windowsVersion; // see WUTIL_VERSION_* static void DetectWindowsVersion() { @@ -301,7 +301,7 @@ static void DetectWindowsVersion() DWORD size = ARRAY_SIZE(windowsVersionString); (void)RegQueryValueEx(hKey, "CurrentVersion", 0, 0, (LPBYTE)windowsVersionString, &size); - uint major = 0, minor = 0; + size_t major = 0, minor = 0; int ret = sscanf(windowsVersionString, "%d.%d", &major, &minor); debug_assert(ret == 2); debug_assert(major <= 0xFF && minor <= 0xFF); @@ -339,7 +339,7 @@ const char* wutil_WindowsVersionString() return windowsVersionString; } -uint wutil_WindowsVersion() +size_t wutil_WindowsVersion() { debug_assert(windowsVersion != 0); return windowsVersion; diff --git a/source/lib/sysdep/win/wutil.h b/source/lib/sysdep/win/wutil.h index 4dca9b5adf..020e0e1956 100644 --- a/source/lib/sysdep/win/wutil.h +++ b/source/lib/sysdep/win/wutil.h @@ -135,17 +135,17 @@ extern char win_exe_dir[MAX_PATH+1]; extern const char* wutil_WindowsVersionString(); // (same format as WINVER) -const uint WUTIL_VERSION_2K = 0x0500; -const uint WUTIL_VERSION_XP = 0x0501; -const uint WUTIL_VERSION_XP64 = 0x0502; -const uint WUTIL_VERSION_VISTA = 0x0600; +const size_t WUTIL_VERSION_2K = 0x0500; +const size_t WUTIL_VERSION_XP = 0x0501; +const size_t WUTIL_VERSION_XP64 = 0x0502; +const size_t WUTIL_VERSION_VISTA = 0x0600; /** * @return short textual representation of the appropriate WUTIL_VERSION **/ extern const char* wutil_WindowsFamily(); -extern uint wutil_WindowsVersion(); +extern size_t wutil_WindowsVersion(); // diff --git a/source/lib/tests/test_adts.h b/source/lib/tests/test_adts.h index b76d696359..c7a818e7d7 100644 --- a/source/lib/tests/test_adts.h +++ b/source/lib/tests/test_adts.h @@ -42,9 +42,9 @@ public: srand(1); RingBuf buf; std::deque deq; - for(uint rep = 0; rep < 1000; rep++) + for(size_t rep = 0; rep < 1000; rep++) { - uint rnd_op = rand(0, 10); + size_t rnd_op = rand(0, 10); // 70% - insert if(rnd_op >= 3) { diff --git a/source/lib/tests/test_bits.h b/source/lib/tests/test_bits.h index 91a1d2d58d..27e65d2d0a 100644 --- a/source/lib/tests/test_bits.h +++ b/source/lib/tests/test_bits.h @@ -14,16 +14,6 @@ public: TS_ASSERT_EQUALS(is_pow2(1u << 31), true); } - void test_log2_of_pow2() - { - TS_ASSERT_EQUALS(log2_of_pow2(0u), -1); - TS_ASSERT_EQUALS(log2_of_pow2(3u), -1); - TS_ASSERT_EQUALS(log2_of_pow2(0xffffffffu), -1); - TS_ASSERT_EQUALS(log2_of_pow2(1u), 0); - TS_ASSERT_EQUALS(log2_of_pow2(256u), 8); - TS_ASSERT_EQUALS(log2_of_pow2(0x80000000u), 31); - } - void test_ceil_log2() { TS_ASSERT_EQUALS(ceil_log2(3u), 2u); diff --git a/source/lib/tests/test_cache_adt.h b/source/lib/tests/test_cache_adt.h index 4f1c179bba..7a1bee3e8d 100644 --- a/source/lib/tests/test_cache_adt.h +++ b/source/lib/tests/test_cache_adt.h @@ -37,7 +37,7 @@ public: int key = cnt++;\ int val = cnt++;\ size_t size = (size_t)rand(1,100);\ - uint cost = (uint)rand(1,100);\ + size_t cost = (size_t)rand(1,100);\ c.add(key, val, size, cost);\ }\ else\ @@ -81,7 +81,7 @@ public: int key = cnt++; int val = cnt++; size_t size = (size_t)rand(1,100); - uint cost = (uint)rand(1,100); + size_t cost = (size_t)rand(1,100); c1.add(key, val, size, cost); c2.add(key, val, size, cost); c3.add(key, val, size, cost); diff --git a/source/lib/tests/test_lockfree.h b/source/lib/tests/test_lockfree.h index 39bbf7b9da..f99df2f040 100644 --- a/source/lib/tests/test_lockfree.h +++ b/source/lib/tests/test_lockfree.h @@ -22,10 +22,10 @@ public: void test_basic_single_threaded() { void* user_data; - const uint ENTRIES = 50; + const size_t ENTRIES = 50; // should be more than max # retired nodes to test release..() code uintptr_t key = 0x1000; - uint sig = 10; + size_t sig = 10; LFList list; TS_ASSERT_OK(lfl_init(&list)); @@ -34,29 +34,29 @@ public: TS_ASSERT_OK(lfh_init(&hash, 8)); // add some entries; store "signatures" (ascending int values) - for(uint i = 0; i < ENTRIES; i++) + for(size_t i = 0; i < ENTRIES; i++) { int was_inserted; user_data = lfl_insert(&list, key+i, sizeof(int), &was_inserted); TS_ASSERT(user_data != 0 && was_inserted); - *(uint*)user_data = sig+i; + *(size_t*)user_data = sig+i; user_data = lfh_insert(&hash, key+i, sizeof(int), &was_inserted); TS_ASSERT(user_data != 0 && was_inserted); - *(uint*)user_data = sig+i; + *(size_t*)user_data = sig+i; } // make sure all "signatures" are present in list - for(uint i = 0; i < ENTRIES; i++) + for(size_t i = 0; i < ENTRIES; i++) { user_data = lfl_find(&list, key+i); TS_ASSERT(user_data != 0); - TS_ASSERT_EQUALS(*(uint*)user_data, sig+i); + TS_ASSERT_EQUALS(*(size_t*)user_data, sig+i); user_data = lfh_find(&hash, key+i); TS_ASSERT(user_data != 0); - TS_ASSERT_EQUALS(*(uint*)user_data, sig+i); + TS_ASSERT_EQUALS(*(size_t*)user_data, sig+i); } lfl_free(&list); @@ -126,9 +126,9 @@ class TestMultithread : public CxxTest::TestSuite { void* user_data; - const int action = rand(0, 4); - const uintptr_t key = rand(0, 100); - const int sleep_duration_ms = rand(0, 100); + const size_t action = rand(0, 4); + const uintptr_t key = (uintptr_t)rand(0, 100); + const size_t sleep_duration_ms = rand(0, 100); debug_printf("thread %d: %s\n", thread_number, action_strings[action]); // @@ -225,7 +225,7 @@ public: TS_ASSERT_OK(pthread_mutex_init(&mutex, 0)); // spin off test threads (many, to force preemption) - const uint NUM_THREADS = 16; + const size_t NUM_THREADS = 16; for(uintptr_t i = 0; i < NUM_THREADS; i++) { ThreadFuncParam* param = new ThreadFuncParam(this, i); diff --git a/source/lib/tests/test_rand.h b/source/lib/tests/test_rand.h index a0c635f755..b7b8ab5bc8 100644 --- a/source/lib/tests/test_rand.h +++ b/source/lib/tests/test_rand.h @@ -9,9 +9,9 @@ public: void TestParam() { debug_skip_next_err(ERR::INVALID_PARAM); - TS_ASSERT_EQUALS(rand(1, 0), 0); + TS_ASSERT_EQUALS(rand(1, 0), size_t(0)); debug_skip_next_err(ERR::INVALID_PARAM); - TS_ASSERT_EQUALS(rand(2, ~0u), 0); + TS_ASSERT_EQUALS(rand(2, ~0u), size_t(0)); } // returned number must be in [min, max) @@ -19,8 +19,8 @@ public: { for(int i = 0; i < 100; i++) { - uint min = rand(), max = min+rand(); - uint x = rand(min, max); + size_t min = rand(), max = min+rand(); + size_t x = rand(min, max); TS_ASSERT(min <= x && x < max); } } @@ -28,10 +28,10 @@ public: // make sure both possible values are hit void TestTwoValues() { - uint ones = 0, twos = 0; + size_t ones = 0, twos = 0; for(int i = 0; i < 100; i++) { - uint x = rand(1, 3); + size_t x = rand(1, 3); // paranoia: don't use array (x might not be 1 or 2 - checked below) if(x == 1) ones++; if(x == 2) twos++; diff --git a/source/lib/tex/tex.cpp b/source/lib/tex/tex.cpp index b45dae3956..f828605e26 100644 --- a/source/lib/tex/tex.cpp +++ b/source/lib/tex/tex.cpp @@ -60,11 +60,11 @@ LibError tex_validate(const Tex* t) // flags // .. DXT value - const uint dxt = t->flags & TEX_DXT; + const size_t dxt = t->flags & TEX_DXT; if(dxt != 0 && dxt != 1 && dxt != DXT1A && dxt != 3 && dxt != 5) WARN_RETURN(ERR::_4); // .. orientation - const uint orientation = t->flags & TEX_ORIENTATION; + const size_t orientation = t->flags & TEX_ORIENTATION; if(orientation == (TEX_BOTTOM_UP|TEX_TOP_DOWN)) WARN_RETURN(ERR::_5); @@ -78,7 +78,7 @@ LibError tex_validate(const Tex* t) // 24bpp color or 32bpp color+alpha (BGR / upside down are permitted). // basically, this is the "plain" format understood by all codecs and // tex_codec_plain_transform. -LibError tex_validate_plain_format(uint bpp, uint flags) +LibError tex_validate_plain_format(size_t bpp, int flags) { const bool alpha = (flags & TEX_ALPHA ) != 0; const bool grey = (flags & TEX_GREY ) != 0; @@ -109,11 +109,11 @@ LibError tex_validate_plain_format(uint bpp, uint flags) // mipmaps //----------------------------------------------------------------------------- -void tex_util_foreach_mipmap(uint w, uint h, uint bpp, const u8* pixels, int levels_to_skip, uint data_padding, MipmapCB cb, void* RESTRICT cbData) +void tex_util_foreach_mipmap(size_t w, size_t h, size_t bpp, const u8* pixels, int levels_to_skip, size_t data_padding, MipmapCB cb, void* RESTRICT cbData) { debug_assert(levels_to_skip >= 0 || levels_to_skip == TEX_BASE_LEVEL_ONLY); - uint level_w = w, level_h = h; + size_t level_w = w, level_h = h; const u8* level_data = pixels; // we iterate through the loop (necessary to skip over image data), @@ -128,7 +128,7 @@ void tex_util_foreach_mipmap(uint w, uint h, uint bpp, const u8* pixels, int lev const size_t level_data_size = (size_t)(round_up(level_w, data_padding) * round_up(level_h, data_padding) * bpp/8); if(level >= 0) - cb((uint)level, level_w, level_h, level_data, level_data_size, cbData); + cb((size_t)level, level_w, level_h, level_data, level_data_size, cbData); level_data += level_data_size; @@ -154,16 +154,16 @@ void tex_util_foreach_mipmap(uint w, uint h, uint bpp, const u8* pixels, int lev struct CreateLevelData { - uint num_components; + size_t num_components; - uint prev_level_w; - uint prev_level_h; + size_t prev_level_w; + size_t prev_level_h; const u8* prev_level_data; size_t prev_level_data_size; }; // uses 2x2 box filter -static void create_level(uint level, uint level_w, uint level_h, const u8* RESTRICT level_data, size_t level_data_size, void* RESTRICT cbData) +static void create_level(size_t level, size_t level_w, size_t level_h, const u8* RESTRICT level_data, size_t level_data_size, void* RESTRICT cbData) { CreateLevelData* cld = (CreateLevelData*)cbData; const size_t src_w = cld->prev_level_w; @@ -179,7 +179,7 @@ static void create_level(uint level, uint level_w, uint level_h, const u8* RESTR } else { - const uint num_components = cld->num_components; + const size_t num_components = cld->num_components; const size_t dx = num_components, dy = dx*src_w; // special case: image is too small for 2x2 filter @@ -188,9 +188,9 @@ static void create_level(uint level, uint level_w, uint level_h, const u8* RESTR // image is either a horizontal or vertical line. // their memory layout is the same (packed pixels), so no special // handling is needed; just pick max dimension. - for(uint y = 0; y < std::max(src_w, src_h); y += 2) + for(size_t y = 0; y < std::max(src_w, src_h); y += 2) { - for(uint i = 0; i < num_components; i++) + for(size_t i = 0; i < num_components; i++) { *dst++ = (src[0]+src[dx]+1)/2; src += 1; @@ -202,11 +202,11 @@ static void create_level(uint level, uint level_w, uint level_h, const u8* RESTR // normal else { - for(uint y = 0; y < src_h; y += 2) + for(size_t y = 0; y < src_h; y += 2) { - for(uint x = 0; x < src_w; x += 2) + for(size_t x = 0; x < src_w; x += 2) { - for(uint i = 0; i < num_components; i++) + for(size_t i = 0; i < num_components; i++) { *dst++ = (src[0]+src[dx]+src[dy]+src[dx+dy]+2)/4; src += 1; @@ -230,7 +230,7 @@ static void create_level(uint level, uint level_w, uint level_h, const u8* RESTR } -static LibError add_mipmaps(Tex* t, uint w, uint h, uint bpp, void* newData, size_t data_size) +static LibError add_mipmaps(Tex* t, size_t w, size_t h, size_t bpp, void* newData, size_t data_size) { // this code assumes the image is of POT dimension; we don't // go to the trouble of implementing image scaling because @@ -263,7 +263,7 @@ TIMER_ADD_CLIENT(tc_plain_transform); // but is much easier to maintain than providing all<->all conversion paths. // // somewhat optimized (loops are hoisted, cache associativity accounted for) -static LibError plain_transform(Tex* t, uint transforms) +static LibError plain_transform(Tex* t, size_t transforms) { TIMER_ACCRUE(tc_plain_transform); @@ -272,7 +272,8 @@ TIMER_ACCRUE(tc_plain_transform); CHECK_TEX(t); // extract texture info - const uint w = t->w, h = t->h, bpp = t->bpp, flags = t->flags; + const size_t w = t->w, h = t->h, bpp = t->bpp; + const int flags = t->flags; u8* const data = tex_get_data(t); const size_t data_size = tex_img_size(t); @@ -313,7 +314,7 @@ TIMER_ACCRUE(tc_plain_transform); // no BGR convert necessary if(!(transforms & TEX_BGR)) { - for(uint y = 0; y < h; y++) + for(size_t y = 0; y < h; y++) { cpu_memcpy(dst, src, pitch); dst += pitch; @@ -323,9 +324,9 @@ TIMER_ACCRUE(tc_plain_transform); // RGB <-> BGR else if(bpp == 24) { - for(uint y = 0; y < h; y++) + for(size_t y = 0; y < h; y++) { - for(uint x = 0; x < w; x++) + for(size_t x = 0; x < w; x++) { // need temporaries in case src == dst (i.e. not flipping) const u8 b = src[0], g = src[1], r = src[2]; @@ -339,9 +340,9 @@ TIMER_ACCRUE(tc_plain_transform); // RGBA <-> BGRA else if(bpp == 32) { - for(uint y = 0; y < h; y++) + for(size_t y = 0; y < h; y++) { - for(uint x = 0; x < w; x++) + for(size_t x = 0; x < w; x++) { // need temporaries in case src == dst (i.e. not flipping) const u8 b = src[0], g = src[1], r = src[2], a = src[3]; @@ -369,13 +370,13 @@ TIMER_ADD_CLIENT(tc_transform); // change 's pixel format by flipping the state of all TEX_* flags // that are set in transforms. -LibError tex_transform(Tex* t, uint transforms) +LibError tex_transform(Tex* t, size_t transforms) { TIMER_ACCRUE(tc_transform); CHECK_TEX(t); - const uint target_flags = t->flags ^ transforms; - uint remaining_transforms; + const size_t target_flags = t->flags ^ transforms; + size_t remaining_transforms; for(;;) { remaining_transforms = target_flags ^ t->flags; @@ -396,10 +397,10 @@ LibError tex_transform(Tex* t, uint transforms) // change 's pixel format to the new format specified by . // (note: this is equivalent to tex_transform(t, t->flags^new_flags). -LibError tex_transform_to(Tex* t, uint new_flags) +LibError tex_transform_to(Tex* t, size_t new_flags) { // tex_transform takes care of validating - const uint transforms = t->flags ^ new_flags; + const size_t transforms = t->flags ^ new_flags; return tex_transform(t, transforms); } @@ -427,12 +428,12 @@ static void flip_to_global_orientation(Tex* t) // (can't use normal CHECK_TEX due to void return) WARN_ERR(tex_validate(t)); - uint orientation = t->flags & TEX_ORIENTATION; + size_t orientation = t->flags & TEX_ORIENTATION; // if codec knows which way around the image is (i.e. not DDS): if(orientation) { // flip image if necessary - uint transforms = orientation ^ global_orientation; + size_t transforms = orientation ^ global_orientation; WARN_ERR(plain_transform(t, transforms)); } @@ -450,9 +451,9 @@ static void flip_to_global_orientation(Tex* t) // dst_orientation (if the latter is 0, then the global_orientation). // (we ask for src_flags instead of src_orientation so callers don't // have to mask off TEX_ORIENTATION) -bool tex_orientations_match(uint src_flags, uint dst_orientation) +bool tex_orientations_match(size_t src_flags, size_t dst_orientation) { - const uint src_orientation = src_flags & TEX_ORIENTATION; + const size_t src_orientation = src_flags & TEX_ORIENTATION; if(dst_orientation == 0) dst_orientation = global_orientation; return (src_orientation == dst_orientation); @@ -495,7 +496,7 @@ bool tex_is_known_extension(const char* filename) // // we need only add bookkeeping information and "wrap" it in // our Tex struct, hence the name. -LibError tex_wrap(uint w, uint h, uint bpp, uint flags, shared_ptr data, size_t ofs, Tex* t) +LibError tex_wrap(size_t w, size_t h, size_t bpp, int flags, shared_ptr data, size_t ofs, Tex* t) { t->w = w; t->h = h; @@ -543,7 +544,7 @@ u8* tex_get_data(const Tex* t) } -static void add_level_size(uint UNUSED(level), uint UNUSED(level_w), uint UNUSED(level_h), const u8* RESTRICT UNUSED(level_data), size_t level_data_size, void* RESTRICT cbData) +static void add_level_size(size_t UNUSED(level), size_t UNUSED(level_w), size_t UNUSED(level_h), const u8* RESTRICT UNUSED(level_data), size_t level_data_size, void* RESTRICT cbData) { size_t* ptotal_size = (size_t*)cbData; *ptotal_size += level_data_size; @@ -558,7 +559,7 @@ size_t tex_img_size(const Tex* t) WARN_ERR(tex_validate(t)); const int levels_to_skip = (t->flags & TEX_MIPMAPS)? 0 : TEX_BASE_LEVEL_ONLY; - const uint data_padding = (t->flags & TEX_DXT)? 4 : 1; + const size_t data_padding = (t->flags & TEX_DXT)? 4 : 1; size_t out_size = 0; tex_util_foreach_mipmap(t->w, t->h, t->bpp, 0, levels_to_skip, data_padding, add_level_size, &out_size); return out_size; diff --git a/source/lib/tex/tex.h b/source/lib/tex/tex.h index 376638a142..043d1ad436 100644 --- a/source/lib/tex/tex.h +++ b/source/lib/tex/tex.h @@ -208,12 +208,12 @@ struct Tex **/ size_t ofs; - uint w : 16; - uint h : 16; - uint bpp : 16; + size_t w : 16; + size_t h : 16; + size_t bpp : 16; /// see TexFlags and "Format Conversion" in docs. - uint flags : 16; + int flags : 16; }; @@ -291,7 +291,7 @@ extern LibError tex_encode(Tex* t, const std::string& extension, DynArray* da); * @param t output texture object. * @return LibError **/ -extern LibError tex_wrap(uint w, uint h, uint bpp, uint flags, shared_ptr data, size_t ofs, Tex* t); +extern LibError tex_wrap(size_t w, size_t h, size_t bpp, int flags, shared_ptr data, size_t ofs, Tex* t); /** * free all resources associated with the image and make further @@ -313,7 +313,7 @@ extern void tex_free(Tex* t); * @param transforms TexFlags that are to be flipped. * @return LibError **/ -extern LibError tex_transform(Tex* t, uint transforms); +extern LibError tex_transform(Tex* t, size_t transforms); /** * change 's pixel format (2nd version) @@ -322,7 +322,7 @@ extern LibError tex_transform(Tex* t, uint transforms); * @param new_flags desired new value of TexFlags. * @return LibError **/ -extern LibError tex_transform_to(Tex* t, uint new_flags); +extern LibError tex_transform_to(Tex* t, size_t new_flags); // @@ -372,7 +372,7 @@ const int TEX_BASE_LEVEL_ONLY = -1; * @param level_data_size [bytes] * @param cbData passed through from tex_util_foreach_mipmap. **/ -typedef void (*MipmapCB)(uint level, uint level_w, uint level_h, const u8* RESTRICT level_data, size_t level_data_size, void* RESTRICT cbData); +typedef void (*MipmapCB)(size_t level, size_t level_w, size_t level_h, const u8* RESTRICT level_data, size_t level_data_size, void* RESTRICT cbData); /** * for a series of mipmaps stored from base to highest, call back for @@ -391,7 +391,7 @@ typedef void (*MipmapCB)(uint level, uint level_w, uint level_h, const u8* RESTR * @param cb MipmapCB to call * @param cbData extra data to pass to cb **/ -extern void tex_util_foreach_mipmap(uint w, uint h, uint bpp, const u8* data, int levels_to_skip, uint data_padding, MipmapCB cb, void* RESTRICT cbData); +extern void tex_util_foreach_mipmap(size_t w, size_t h, size_t bpp, const u8* data, int levels_to_skip, size_t data_padding, MipmapCB cb, void* RESTRICT cbData); // diff --git a/source/lib/tex/tex_bmp.cpp b/source/lib/tex/tex_bmp.cpp index 43f74f735b..85c6b14d3f 100644 --- a/source/lib/tex/tex_bmp.cpp +++ b/source/lib/tex/tex_bmp.cpp @@ -44,7 +44,7 @@ struct BmpHeader #define BI_RGB 0 // biCompression -static LibError bmp_transform(Tex* UNUSED(t), uint UNUSED(transforms)) +static LibError bmp_transform(Tex* UNUSED(t), size_t UNUSED(transforms)) { return INFO::TEX_CODEC_CANNOT_HANDLE; } @@ -91,7 +91,7 @@ static LibError bmp_decode(DynArray* RESTRICT da, Tex* RESTRICT t) const long h = abs(h_); - uint flags = 0; + int flags = 0; flags |= (h_ < 0)? TEX_TOP_DOWN : TEX_BOTTOM_UP; if(bpp > 16) flags |= TEX_BGR; diff --git a/source/lib/tex/tex_codec.cpp b/source/lib/tex/tex_codec.cpp index e88ac8d651..af2d69d474 100644 --- a/source/lib/tex/tex_codec.cpp +++ b/source/lib/tex/tex_codec.cpp @@ -84,7 +84,7 @@ const TexCodecVTbl* tex_codec_next(const TexCodecVTbl* prev_codec) } -LibError tex_codec_transform(Tex* t, uint transforms) +LibError tex_codec_transform(Tex* t, size_t transforms) { LibError ret = INFO::TEX_CODEC_CANNOT_HANDLE; @@ -131,7 +131,7 @@ void tex_codec_register_all() // // note: we don't allocate the data param ourselves because this function is // needed for encoding, too (where data is already present). -shared_ptr tex_codec_alloc_rows(const u8* data, size_t h, size_t pitch, uint src_flags, uint dst_orientation) +shared_ptr tex_codec_alloc_rows(const u8* data, size_t h, size_t pitch, size_t src_flags, size_t dst_orientation) { const bool flip = !tex_orientations_match(src_flags, dst_orientation); @@ -153,7 +153,7 @@ shared_ptr tex_codec_alloc_rows(const u8* data, size_t h, size_t pitch, } -LibError tex_codec_write(Tex* t, uint transforms, const void* hdr, size_t hdr_size, DynArray* da) +LibError tex_codec_write(Tex* t, size_t transforms, const void* hdr, size_t hdr_size, DynArray* da) { RETURN_ERR(tex_transform(t, transforms)); diff --git a/source/lib/tex/tex_codec.h b/source/lib/tex/tex_codec.h index 3dc8be48ee..07f1b7b27d 100644 --- a/source/lib/tex/tex_codec.h +++ b/source/lib/tex/tex_codec.h @@ -58,7 +58,7 @@ struct TexCodecVTbl * to its format; generic pixel format transforms are handled by * the caller. **/ - LibError (*transform)(Tex* t, uint transforms); + LibError (*transform)(Tex* t, size_t transforms); /** * indicate if the data appears to be an instance of this codec's header, @@ -188,7 +188,7 @@ extern const TexCodecVTbl* tex_codec_next(const TexCodecVTbl* prev_codec); * be changed. * @return LibError **/ -extern LibError tex_codec_transform(Tex* t, uint transforms); +extern LibError tex_codec_transform(Tex* t, size_t transforms); /** * allocate an array of row pointers that point into the given texture data. @@ -212,7 +212,7 @@ extern LibError tex_codec_transform(Tex* t, uint transforms); * @return LibError **/ typedef const u8* RowPtr; -extern shared_ptr tex_codec_alloc_rows(const u8* data, size_t h, size_t pitch, uint src_flags, uint dst_orientation); +extern shared_ptr tex_codec_alloc_rows(const u8* data, size_t h, size_t pitch, size_t src_flags, size_t dst_orientation); /** * apply transforms and then copy header and image into output buffer. @@ -224,6 +224,6 @@ extern shared_ptr tex_codec_alloc_rows(const u8* data, size_t h, size_t * @param da output data array (will be expanded as necessary) * @return LibError **/ -extern LibError tex_codec_write(Tex* t, uint transforms, const void* hdr, size_t hdr_size, DynArray* da); +extern LibError tex_codec_write(Tex* t, size_t transforms, const void* hdr, size_t hdr_size, DynArray* da); #endif // #ifndef INCLUDED_TEX_CODEC diff --git a/source/lib/tex/tex_dds.cpp b/source/lib/tex/tex_dds.cpp index 42255733dc..325b400741 100644 --- a/source/lib/tex/tex_dds.cpp +++ b/source/lib/tex/tex_dds.cpp @@ -25,33 +25,33 @@ // emulate hardware S3TC support - if that isn't available, everything will // be dog-slow anyway due to increased vmem usage. -// pixel colors are stored as uint[4]. uint rather than u8 protects from +// pixel colors are stored as size_t[4]. size_t rather than u8 protects from // overflow during calculations, and padding to an even size is a bit // more efficient (even though we don't need the alpha component). enum RGBA { R, G, B, A }; -static inline void mix_2_3(uint dst[4], uint c0[4], uint c1[4]) +static inline void mix_2_3(size_t dst[4], size_t c0[4], size_t c1[4]) { for(int i = 0; i < 3; i++) dst[i] = (c0[i]*2 + c1[i] + 1)/3; } -static inline void mix_avg(uint dst[4], uint c0[4], uint c1[4]) +static inline void mix_avg(size_t dst[4], size_t c0[4], size_t c1[4]) { for(int i = 0; i < 3; i++) dst[i] = (c0[i]+c1[i])/2; } -static inline uint access_bit_tbl(u32 tbl, uint idx, uint bit_width) +static inline size_t access_bit_tbl(u32 tbl, size_t idx, size_t bit_width) { - uint val = tbl >> (idx*bit_width); - val &= (1u << bit_width)-1; + size_t val = tbl >> (idx*bit_width); + val &= bit_mask(bit_width); return val; } -static inline uint access_bit_tbl64(u64 tbl, uint idx, uint bit_width) +static inline size_t access_bit_tbl64(u64 tbl, size_t idx, size_t bit_width) { - uint val = (uint)(tbl >> (idx*bit_width)); - val &= (1u << bit_width)-1; + size_t val = (size_t)(tbl >> (idx*bit_width)); + val &= bit_mask(bit_width); return val; } @@ -59,11 +59,11 @@ static inline uint access_bit_tbl64(u64 tbl, uint idx, uint bit_width) // MS bits - see http://www.mindcontrol.org/~hplus/graphics/expand-bits.html ; // this is also the algorithm used by graphics cards when decompressing S3TC). // used to convert 565 to 32bpp RGB. -static inline uint unpack_to_8(u16 c, uint bits_below, uint num_bits) +static inline size_t unpack_to_8(u16 c, size_t bits_below, size_t num_bits) { - const uint num_filler_bits = 8-num_bits; - const uint field = bits(c, bits_below, bits_below+num_bits-1); - const uint filler = field >> (8-num_bits); + const size_t num_filler_bits = 8-num_bits; + const size_t field = (size_t)bits(c, bits_below, bits_below+num_bits-1); + const size_t filler = field >> (8-num_bits); return (field << num_filler_bits) | filler; } @@ -73,7 +73,7 @@ static inline uint unpack_to_8(u16 c, uint bits_below, uint num_bits) struct S3tcBlock { // the 4 color choices for each pixel (RGBA) - uint c[4][4]; // c[i][RGBA_component] + size_t c[4][4]; // c[i][RGBA_component] // (DXT5 only) the 8 alpha choices u8 dxt5_a_tbl[8]; @@ -84,14 +84,14 @@ struct S3tcBlock // table of 2-bit color selectors u32 c_selectors; - uint dxt; + size_t dxt; }; -static void s3tc_precalc_alpha(uint dxt, const u8* RESTRICT a_block, S3tcBlock* RESTRICT b) +static void s3tc_precalc_alpha(size_t dxt, const u8* RESTRICT a_block, S3tcBlock* RESTRICT b) { // read block contents - const uint a0 = a_block[0], a1 = a_block[1]; + const u8 a0 = a_block[0], a1 = a_block[1]; b->a_bits = read_le64(a_block); // see below if(dxt == 5) @@ -127,7 +127,7 @@ static void s3tc_precalc_alpha(uint dxt, const u8* RESTRICT a_block, S3tcBlock* } -static void s3tc_precalc_color(uint dxt, const u8* RESTRICT c_block, S3tcBlock* RESTRICT b) +static void s3tc_precalc_color(size_t dxt, const u8* RESTRICT c_block, S3tcBlock* RESTRICT b) { // read block contents // .. S3TC reference colors (565 format). the color table is generated @@ -164,7 +164,7 @@ static void s3tc_precalc_color(uint dxt, const u8* RESTRICT c_block, S3tcBlock* } -static void s3tc_precalc_block(uint dxt, const u8* RESTRICT block, S3tcBlock* RESTRICT b) +static void s3tc_precalc_block(size_t dxt, const u8* RESTRICT block, S3tcBlock* RESTRICT b) { b->dxt = dxt; @@ -177,21 +177,21 @@ static void s3tc_precalc_block(uint dxt, const u8* RESTRICT block, S3tcBlock* RE } -static void s3tc_write_pixel(const S3tcBlock* RESTRICT b, uint pixel_idx, u8* RESTRICT out) +static void s3tc_write_pixel(const S3tcBlock* RESTRICT b, size_t pixel_idx, u8* RESTRICT out) { debug_assert(pixel_idx < 16); // pixel index -> color selector (2 bit) -> color - const uint c_selector = access_bit_tbl(b->c_selectors, pixel_idx, 2); - const uint* c = b->c[c_selector]; + const size_t c_selector = access_bit_tbl(b->c_selectors, pixel_idx, 2); + const size_t* c = b->c[c_selector]; for(int i = 0; i < 3; i++) - out[i] = c[i]; + out[i] = (u8)c[i]; // if no alpha, done if(b->dxt == 1) return; - uint a; + size_t a; if(b->dxt == 3) { // table of 4-bit alpha entries @@ -201,47 +201,47 @@ static void s3tc_write_pixel(const S3tcBlock* RESTRICT b, uint pixel_idx, u8* RE else if(b->dxt == 5) { // pixel index -> alpha selector (3 bit) -> alpha - const uint a_selector = access_bit_tbl64(b->a_bits, pixel_idx, 3); + const size_t a_selector = access_bit_tbl64(b->a_bits, pixel_idx, 3); a = b->dxt5_a_tbl[a_selector]; } // (dxt == DXT1A) else a = c[A]; - out[A] = a; + out[A] = (u8)a; } struct S3tcDecompressInfo { - uint dxt; - uint s3tc_block_size; - uint out_Bpp; + size_t dxt; + size_t s3tc_block_size; + size_t out_Bpp; u8* out; }; -static void s3tc_decompress_level(uint UNUSED(level), uint level_w, uint level_h, +static void s3tc_decompress_level(size_t UNUSED(level), size_t level_w, size_t level_h, const u8* RESTRICT level_data, size_t level_data_size, void* RESTRICT cbData) { S3tcDecompressInfo* di = (S3tcDecompressInfo*)cbData; - const uint dxt = di->dxt; - const uint s3tc_block_size = di->s3tc_block_size; + const size_t dxt = di->dxt; + const size_t s3tc_block_size = di->s3tc_block_size; // note: 1x1 images are legitimate (e.g. in mipmaps). they report their // width as such for glTexImage, but the S3TC data is padded to // 4x4 pixel block boundaries. - const uint blocks_w = round_up(level_w, 4u) / 4u; - const uint blocks_h = round_up(level_h, 4u) / 4u; + const size_t blocks_w = round_up(level_w, 4u) / 4u; + const size_t blocks_h = round_up(level_h, 4u) / 4u; const u8* s3tc_data = level_data; debug_assert(level_data_size % s3tc_block_size == 0); - for(uint block_y = 0; block_y < blocks_h; block_y++) - for(uint block_x = 0; block_x < blocks_w; block_x++) + for(size_t block_y = 0; block_y < blocks_h; block_y++) + for(size_t block_x = 0; block_x < blocks_w; block_x++) { S3tcBlock b; s3tc_precalc_block(dxt, s3tc_data, &b); s3tc_data += s3tc_block_size; - uint pixel_idx = 0; + size_t pixel_idx = 0; for(int y = 0; y < 4; y++) { // this is ugly, but advancing after x, y and block_y loops @@ -271,12 +271,12 @@ static LibError s3tc_decompress(Tex* t) // - adding or stripping alpha channels during transform is not // our job; we merely output the same pixel format as given // (tex.cpp's plain transform could cover it, if ever needed). - const uint dxt = t->flags & TEX_DXT; - const uint out_bpp = (dxt != 1)? 32 : 24; + const size_t dxt = t->flags & TEX_DXT; + const size_t out_bpp = (dxt != 1)? 32 : 24; const size_t out_size = tex_img_size(t) * out_bpp / t->bpp; shared_ptr decompressedData = io_Allocate(out_size); - const uint s3tc_block_size = (dxt == 3 || dxt == 5)? 16 : 8; + const size_t s3tc_block_size = (dxt == 3 || dxt == 5)? 16 : 8; S3tcDecompressInfo di = { dxt, s3tc_block_size, out_bpp/8, decompressedData.get() }; const u8* s3tc_data = tex_get_data(t); const int levels_to_skip = (t->flags & TEX_MIPMAPS)? 0 : TEX_BASE_LEVEL_ONLY; @@ -374,7 +374,7 @@ DDSURFACEDESC2; #pragma pack(pop) -static bool is_valid_dxt(uint dxt) +static bool is_valid_dxt(size_t dxt) { switch(dxt) { @@ -394,10 +394,10 @@ static bool is_valid_dxt(uint dxt) // pf points to the DDS file's header; all fields must be endian-converted // before use. // output parameters invalid on failure. -static LibError decode_pf(const DDPIXELFORMAT* pf, uint* bpp_, uint* flags_) +static LibError decode_pf(const DDPIXELFORMAT* pf, size_t& bpp, size_t& flags) { - uint bpp = 0; - uint flags = 0; + bpp = 0; + flags = 0; // check struct size if(read_le32(&pf->dwSize) != sizeof(DDPIXELFORMAT)) @@ -475,8 +475,6 @@ static LibError decode_pf(const DDPIXELFORMAT* pf, uint* bpp_, uint* flags_) else WARN_RETURN(ERR::TEX_FMT_INVALID); - *bpp_ = bpp; - *flags_ = flags; return INFO::OK; } @@ -485,8 +483,8 @@ static LibError decode_pf(const DDPIXELFORMAT* pf, uint* bpp_, uint* flags_) // sd points to the DDS file's header; all fields must be endian-converted // before use. // output parameters invalid on failure. -static LibError decode_sd(const DDSURFACEDESC2* sd, uint* w_, uint* h_, - uint* bpp_, uint* flags_) +static LibError decode_sd(const DDSURFACEDESC2* sd, size_t* w_, size_t* h_, + size_t* bpp_, size_t* flags_) { // check header size if(read_le32(&sd->dwSize) != sizeof(*sd)) @@ -505,8 +503,8 @@ static LibError decode_sd(const DDSURFACEDESC2* sd, uint* w_, uint* h_, const size_t w = (size_t)read_le32(&sd->dwWidth); // pixel format - uint bpp, flags; - RETURN_ERR(decode_pf(&sd->ddpfPixelFormat, &bpp, &flags)); + size_t bpp, flags; + RETURN_ERR(decode_pf(&sd->ddpfPixelFormat, bpp, flags)); // if the image is not aligned with the S3TC block size, it is stored // with extra pixels on the bottom left to fill up the space, so we need @@ -514,8 +512,8 @@ static LibError decode_sd(const DDSURFACEDESC2* sd, uint* w_, uint* h_, size_t stored_h, stored_w; if(flags & TEX_DXT) { - stored_h = round_up(h, 4u); - stored_w = round_up(w, 4u); + stored_h = round_up(h, size_t(4)); + stored_w = round_up(w, size_t(4)); } else { @@ -606,8 +604,8 @@ static LibError dds_decode(DynArray* RESTRICT da, Tex* RESTRICT t) u8* file = da->base; const DDSURFACEDESC2* sd = (const DDSURFACEDESC2*)(file+4); - uint w, h; - uint bpp, flags; + size_t w, h; + size_t bpp, flags; RETURN_ERR(decode_sd(sd, &w, &h, &bpp, &flags)); // note: cannot pass address of these directly to decode_sd because // they are bitfields. @@ -627,12 +625,12 @@ static LibError dds_encode(Tex* RESTRICT UNUSED(t), DynArray* RESTRICT UNUSED(da } -static LibError dds_transform(Tex* t, uint transforms) +static LibError dds_transform(Tex* t, size_t transforms) { - uint dxt = t->flags & TEX_DXT; + size_t dxt = t->flags & TEX_DXT; debug_assert(is_valid_dxt(dxt)); - const uint transform_dxt = transforms & TEX_DXT; + const size_t transform_dxt = transforms & TEX_DXT; // requesting decompression if(dxt && transform_dxt) { diff --git a/source/lib/tex/tex_internal.h b/source/lib/tex/tex_internal.h index cbb5f835b9..93302f7370 100644 --- a/source/lib/tex/tex_internal.h +++ b/source/lib/tex/tex_internal.h @@ -23,7 +23,7 @@ * @param flags TexFlags * @return LibError **/ -extern LibError tex_validate_plain_format(uint bpp, uint flags); +extern LibError tex_validate_plain_format(size_t bpp, int flags); /** @@ -39,6 +39,6 @@ extern LibError tex_validate_plain_format(uint bpp, uint flags); * "global orientation". * @return bool **/ -extern bool tex_orientations_match(uint src_flags, uint dst_orientation); +extern bool tex_orientations_match(size_t src_flags, size_t dst_orientation); #endif // #ifndef INCLUDED_TEX_INTERNAL diff --git a/source/lib/tex/tex_jpg.cpp b/source/lib/tex/tex_jpg.cpp index 69db3050a2..b56a7c10b1 100644 --- a/source/lib/tex/tex_jpg.cpp +++ b/source/lib/tex/tex_jpg.cpp @@ -392,7 +392,7 @@ JpgErrorMgr::JpgErrorMgr(j_common_ptr cinfo) //----------------------------------------------------------------------------- -static LibError jpg_transform(Tex* UNUSED(t), uint UNUSED(transforms)) +static LibError jpg_transform(Tex* UNUSED(t), size_t UNUSED(transforms)) { return INFO::TEX_CODEC_CANNOT_HANDLE; } @@ -420,7 +420,7 @@ static LibError jpg_decode_impl(DynArray* da, jpeg_decompress_struct* cinfo, Tex // set libjpg output format. we cannot go with the default because // Photoshop writes non-standard CMYK files that must be converted to RGB. - uint flags = 0; + int flags = 0; cinfo->out_color_space = JCS_RGB; if(cinfo->num_components == 1) { diff --git a/source/lib/tex/tex_png.cpp b/source/lib/tex/tex_png.cpp index 30a2f172a0..4372c42602 100644 --- a/source/lib/tex/tex_png.cpp +++ b/source/lib/tex/tex_png.cpp @@ -59,7 +59,7 @@ static void io_flush(png_structp UNUSED(png_ptr)) //----------------------------------------------------------------------------- -static LibError png_transform(Tex* UNUSED(t), uint UNUSED(transforms)) +static LibError png_transform(Tex* UNUSED(t), size_t UNUSED(transforms)) { return INFO::TEX_CODEC_CANNOT_HANDLE; } @@ -82,7 +82,7 @@ static LibError png_decode_impl(DynArray* da, png_structp png_ptr, png_infop inf const size_t pitch = png_get_rowbytes(png_ptr, info_ptr); const u32 bpp = (u32)(pitch/w * 8); - uint flags = 0; + int flags = 0; if(bpp == 32) flags |= TEX_ALPHA; if(colour_type == PNG_COLOR_TYPE_GRAY) diff --git a/source/lib/tex/tex_tga.cpp b/source/lib/tex/tex_tga.cpp index 8be7af24d9..81fb709f6b 100644 --- a/source/lib/tex/tex_tga.cpp +++ b/source/lib/tex/tex_tga.cpp @@ -51,7 +51,7 @@ TgaHeader; #pragma pack(pop) -static LibError tga_transform(Tex* UNUSED(t), uint UNUSED(transforms)) +static LibError tga_transform(Tex* UNUSED(t), size_t UNUSED(transforms)) { return INFO::TEX_CODEC_CANNOT_HANDLE; } @@ -102,12 +102,12 @@ static LibError tga_decode(DynArray* RESTRICT da, Tex* RESTRICT t) TgaHeader* hdr = (TgaHeader*)file; const u8 type = hdr->img_type; - const uint w = read_le16(&hdr->w); - const uint h = read_le16(&hdr->h); - const uint bpp = hdr->bpp; + const size_t w = read_le16(&hdr->w); + const size_t h = read_le16(&hdr->h); + const size_t bpp = hdr->bpp; const u8 desc = hdr->img_desc; - uint flags = 0; + int flags = 0; flags |= (desc & TGA_TOP_DOWN)? TEX_TOP_DOWN : TEX_BOTTOM_UP; if(desc & 0x0F) // alpha bits flags |= TEX_ALPHA; diff --git a/source/lib/timer.cpp b/source/lib/timer.cpp index 46118ffbb3..7a8237094d 100644 --- a/source/lib/timer.cpp +++ b/source/lib/timer.cpp @@ -262,7 +262,7 @@ std::string TimerUnit::ToString() const // // do not use std::list et al. for this! we must be callable at any time, // especially before NLSO ctors run or before heap init. -static uint num_clients; +static size_t num_clients; static TimerClient* clients; diff --git a/source/lib/timer.h b/source/lib/timer.h index 9defde908d..8d1cfe22af 100644 --- a/source/lib/timer.h +++ b/source/lib/timer.h @@ -119,7 +119,7 @@ struct TimerClient // how often timer_BillClient was called (helps measure relative // performance of something that is done indeterminately often). - uint num_calls; + size_t num_calls; }; /** diff --git a/source/lib/types.h b/source/lib/types.h index 4133ef5039..52f5d53c04 100644 --- a/source/lib/types.h +++ b/source/lib/types.h @@ -15,13 +15,6 @@ // defines instead of typedefs so we can #undef conflicting decls -// Workaround: GCC won't parse constructor-casts with multi-word types, while -// visual studio will. Define uint/long to a namespaced one-word typedef. -typedef unsigned long PS_ulong; -typedef unsigned int PS_uint; -#define ulong PS_ulong -#define uint PS_uint - #define i8 int8_t #define i16 int16_t #define i32 int32_t diff --git a/source/main.cpp b/source/main.cpp index 286afcd9a8..3eb64c8e8b 100644 --- a/source/main.cpp +++ b/source/main.cpp @@ -280,7 +280,7 @@ static void Frame() { // CSimulation would do this with the proper turn length if we were in // a game. This is basically just to keep script timers running. - uint ms_elapsed = (uint)(TimeSinceLastFrame*1000); + int ms_elapsed = (int)(TimeSinceLastFrame*1000); g_Scheduler.Update(ms_elapsed); if(snd_update(0, 0, 0) < 0) debug_printf("snd_update (pos=0 version) failed\n"); diff --git a/source/maths/Brush.cpp b/source/maths/Brush.cpp index b577020e40..a580e05ebc 100644 --- a/source/maths/Brush.cpp +++ b/source/maths/Brush.cpp @@ -23,7 +23,7 @@ CBrush::CBrush(const CBound& bounds) { m_Vertices.resize(8); - for(uint i = 0; i < 8; ++i) + for(size_t i = 0; i < 8; ++i) { m_Vertices[i][0] = bounds[(i & 1) ? 1 : 0][0]; m_Vertices[i][1] = bounds[(i & 2) ? 1 : 0][1]; @@ -49,7 +49,7 @@ void CBrush::Bounds(CBound& result) const { result.SetEmpty(); - for(uint i = 0; i < m_Vertices.size(); ++i) + for(size_t i = 0; i < m_Vertices.size(); ++i) result += m_Vertices[i]; } @@ -58,34 +58,34 @@ void CBrush::Bounds(CBound& result) const // Cut the brush according to a given plane struct SliceVertexInfo { float d; // distance - uint res; // index in result brush (or no_vertex if cut away) + size_t res; // index in result brush (or no_vertex if cut away) }; struct NewVertexInfo { - uint v1, v2; // adjacent vertices in original brush - uint res; // index in result brush + size_t v1, v2; // adjacent vertices in original brush + size_t res; // index in result brush - uint neighb1, neighb2; // index into newv + size_t neighb1, neighb2; // index into newv }; struct SliceInfo { std::vector v; std::vector newv; - uint thisFaceNewVertex; // index into newv + size_t thisFaceNewVertex; // index into newv const CBrush* original; CBrush* result; }; struct CBrush::Helper { - static uint SliceNewVertex(SliceInfo& si, uint v1, uint v2); + static size_t SliceNewVertex(SliceInfo& si, size_t v1, size_t v2); }; // create a new vertex between the given two vertices (index into original brush) // returns the index of the new vertex in the resulting brush -uint CBrush::Helper::SliceNewVertex(SliceInfo& si, uint v1, uint v2) +size_t CBrush::Helper::SliceNewVertex(SliceInfo& si, size_t v1, size_t v2) { - uint idx; + size_t idx; for(idx = 0; idx < si.newv.size(); ++idx) { @@ -105,7 +105,7 @@ uint CBrush::Helper::SliceNewVertex(SliceInfo& si, uint v1, uint v2) nvi.v1 = v1; nvi.v2 = v2; - nvi.res = (uint)si.result->m_Vertices.size(); + nvi.res = si.result->m_Vertices.size(); nvi.neighb1 = no_vertex; nvi.neighb2 = no_vertex; si.result->m_Vertices.push_back(newpos); @@ -153,12 +153,12 @@ void CBrush::Slice(const CPlane& plane, CBrush& result) const // Classify and copy vertices si.v.resize(m_Vertices.size()); - for(uint i = 0; i < m_Vertices.size(); ++i) + for(size_t i = 0; i < m_Vertices.size(); ++i) { si.v[i].d = plane.DistanceToPlane(m_Vertices[i]); if (si.v[i].d >= 0.0) { - si.v[i].res = (uint)result.m_Vertices.size(); + si.v[i].res = result.m_Vertices.size(); result.m_Vertices.push_back(m_Vertices[i]); } else @@ -168,22 +168,22 @@ void CBrush::Slice(const CPlane& plane, CBrush& result) const } // Transfer faces - uint firstInFace = no_vertex; // in original brush - uint startInResultFaceArray = ~0u; + size_t firstInFace = no_vertex; // in original brush + size_t startInResultFaceArray = ~0u; - for(uint i = 0; i < m_Faces.size(); ++i) + for(size_t i = 0; i < m_Faces.size(); ++i) { if (firstInFace == no_vertex) { debug_assert(si.thisFaceNewVertex == no_vertex); firstInFace = m_Faces[i]; - startInResultFaceArray = (uint)result.m_Faces.size(); + startInResultFaceArray = result.m_Faces.size(); continue; } - uint prev = m_Faces[i-1]; - uint cur = m_Faces[i]; + size_t prev = m_Faces[i-1]; + size_t cur = m_Faces[i]; if (si.v[prev].res == no_vertex) { @@ -221,8 +221,8 @@ void CBrush::Slice(const CPlane& plane, CBrush& result) const // Create the face that lies in the slicing plane if (si.newv.size()) { - uint prev = 0; - uint idx; + size_t prev = 0; + size_t idx; result.m_Faces.push_back(si.newv[0].res); idx = si.newv[0].neighb2; @@ -277,7 +277,7 @@ void CBrush::Intersect(const CFrustum& frustum, CBrush& result) const else next = &buf; - for(uint i = 0; i < frustum.GetNumPlanes(); ++i) + for(size_t i = 0; i < frustum.GetNumPlanes(); ++i) { prev->Slice(frustum[i], *next); prev = next; @@ -295,9 +295,9 @@ void CBrush::Intersect(const CFrustum& frustum, CBrush& result) const // Dump the faces to OpenGL void CBrush::Render() const { - uint firstInFace = no_vertex; + size_t firstInFace = no_vertex; - for(uint i = 0; i < m_Faces.size(); ++i) + for(size_t i = 0; i < m_Faces.size(); ++i) { if (firstInFace == no_vertex) { diff --git a/source/maths/Brush.h b/source/maths/Brush.h index b240e525e2..2108f587c7 100644 --- a/source/maths/Brush.h +++ b/source/maths/Brush.h @@ -71,10 +71,10 @@ public: void Render() const; private: - static const uint no_vertex = ~0u; + static const size_t no_vertex = ~0u; typedef std::vector Vertices; - typedef std::vector FaceIndices; + typedef std::vector FaceIndices; Vertices m_Vertices; FaceIndices m_Faces; diff --git a/source/maths/MathUtil.h b/source/maths/MathUtil.h index 3de9f81a29..6aa29ec87d 100644 --- a/source/maths/MathUtil.h +++ b/source/maths/MathUtil.h @@ -23,16 +23,6 @@ inline T clamp(T value, T min, T max) else return value; } -static inline int RoundUpToPowerOf2(int x) -{ - if ((x & (x-1)) == 0) - return x; - int d = x; - while (d & (d-1)) - d &= (d-1); - return d << 1; -} - inline float sgn(float a) { if (a > 0.0f) return 1.0f; diff --git a/source/network/Client.cpp b/source/network/Client.cpp index 6ead732937..eaa95ec57d 100644 --- a/source/network/Client.cpp +++ b/source/network/Client.cpp @@ -81,7 +81,7 @@ void CNetClient::ScriptingInit() bool CNetClient::JSI_BeginConnect(JSContext* UNUSED(cx), uintN argc, jsval *argv) { CStr connectHostName; - uint connectPort=PS_DEFAULT_PORT; + unsigned connectPort=PS_DEFAULT_PORT; if (argc >= 1) { connectHostName=g_ScriptingHost.ValueToString(argv[0]); @@ -258,7 +258,7 @@ bool CNetClient::PreGameHandler(CNetMessage *pMsg, CNetSession *pSession) case NMT_ClientConnect: { CClientConnect *msg=(CClientConnect *)pMsg; - for (uint i=0;im_Clients.size();i++) + for (size_t i=0;im_Clients.size();i++) { pClient->OnClientConnect(msg->m_Clients[i].m_SessionID, msg->m_Clients[i].m_Name); @@ -274,7 +274,7 @@ bool CNetClient::PreGameHandler(CNetMessage *pMsg, CNetSession *pSession) case NMT_SetGameConfig: { CSetGameConfig *msg=(CSetGameConfig *)pMsg; - for (uint i=0;im_Values.size();i++) + for (size_t i=0;im_Values.size();i++) { pClient->m_pGameAttributes->SetValue(msg->m_Values[i].m_Name, msg->m_Values[i].m_Value); } @@ -310,7 +310,7 @@ bool CNetClient::PreGameHandler(CNetMessage *pMsg, CNetSession *pSession) CSetPlayerConfig *msg=(CSetPlayerConfig *)pMsg; // FIXME Check player ID CPlayer *pPlayer=pClient->m_pGameAttributes->GetPlayer(msg->m_PlayerID); - for (uint i=0;im_Values.size();i++) + for (size_t i=0;im_Values.size();i++) { pPlayer->SetValue(msg->m_Values[i].m_Name, msg->m_Values[i].m_Value); } diff --git a/source/network/NMTCreator.h b/source/network/NMTCreator.h index f3e66b6db2..06f4d68c12 100644 --- a/source/network/NMTCreator.h +++ b/source/network/NMTCreator.h @@ -45,7 +45,7 @@ * have several classes with the same value of _tp in the same executable */ #define START_NMT_CLASS_DERIVED(_base, _nm, _tp) \ -CNetMessage *Deserialize##_nm(const u8 *, uint); \ +CNetMessage *Deserialize##_nm(const u8 *, size_t); \ class _nm: public _base \ { \ protected: \ @@ -56,7 +56,7 @@ protected: \ CStr GetStringRaw() const;\ public: \ _nm(): _base(_tp) {} \ - virtual uint GetSerializedLength() const; \ + virtual size_t GetSerializedLength() const; \ virtual u8 *Serialize(u8 *buffer) const; \ virtual const u8 *Deserialize(const u8 *pos, const u8 *end); \ virtual CStr GetString() const; \ @@ -117,9 +117,9 @@ public: \ #define START_NMT_CLASS(_nm, _tp) \ START_NMT_CLASS_DERIVED(CNetMessage, _nm, _tp) #define START_NMT_CLASS_DERIVED(_base, _nm, _tp) \ -uint _nm::GetSerializedLength() const \ +size_t _nm::GetSerializedLength() const \ { \ - uint ret=_base::GetSerializedLength(); \ + size_t ret=_base::GetSerializedLength(); \ const _nm *thiz=this;\ UNUSED2(thiz); // preempt any "unused" warning @@ -203,7 +203,7 @@ u8 *_nm::Serialize(u8 *buffer) const \ #define START_NMT_CLASS(_nm, _tp) \ START_NMT_CLASS_DERIVED(CNetMessage, _nm, _tp) #define START_NMT_CLASS_DERIVED(_base, _nm, _tp) \ -CNetMessage *Deserialize##_nm(const u8 *buffer, uint length) \ +CNetMessage *Deserialize##_nm(const u8 *buffer, size_t length) \ { \ _nm *ret=new _nm(); \ if (ret->Deserialize(buffer, buffer+length)) \ diff --git a/source/network/NetLog.cpp b/source/network/NetLog.cpp index d35f54f756..5919de48c5 100644 --- a/source/network/NetLog.cpp +++ b/source/network/NetLog.cpp @@ -139,11 +139,11 @@ void CNetLogSink::DoSink( const CNetLogEvent& event ) // Name: DoBulkSink() // Desc: Perform logging for a list of events //----------------------------------------------------------------------------- -void CNetLogSink::DoBulkSink( const CNetLogEvent* pEvents, uint eventCount ) +void CNetLogSink::DoBulkSink( const CNetLogEvent* pEvents, size_t eventCount ) { - uint* pIndices = NULL; - uint indexCount = 0; - uint i; + unsigned* pIndices = NULL; + size_t indexCount = 0; + size_t i; CScopeLock lock( m_Mutex ); @@ -154,7 +154,7 @@ void CNetLogSink::DoBulkSink( const CNetLogEvent* pEvents, uint eventCount ) if ( m_Closed ) return; // Allocate new array which will store the events that will be logged - pIndices = new uint[ eventCount ]; + pIndices = new unsigned[ eventCount ]; if ( !pIndices ) { throw std::bad_alloc(); @@ -827,7 +827,7 @@ void CNetLogger::WarnFormat( const char* pFormat, ... ) //----------------------------------------------------------------------------- void CNetLogger::AddSink( CNetLogSink* pSink ) { - uint i; + size_t i; CScopeLock lock( m_Mutex ); assert( pSink ); @@ -922,19 +922,19 @@ void CNetLogger::RemoveAllSinks( void ) // Name: GetSinkCount() // Desc: Retrive the number of attached sinks //----------------------------------------------------------------------------- -uint CNetLogger::GetSinkCount( void ) +size_t CNetLogger::GetSinkCount( void ) { - return ( uint )m_Sinks.size(); + return m_Sinks.size(); } //----------------------------------------------------------------------------- // Name: GetSink() // Desc: Retrieves the sink by index //----------------------------------------------------------------------------- -CNetLogSink* CNetLogger::GetSink( uint index ) +CNetLogSink* CNetLogger::GetSink( size_t index ) { // Validate parameter - if ( index > ( uint )m_Sinks.size() ) return NULL; + if ( index > m_Sinks.size() ) return NULL; return m_Sinks[ index ]; } @@ -945,7 +945,7 @@ CNetLogSink* CNetLogger::GetSink( uint index ) //----------------------------------------------------------------------------- CNetLogSink* CNetLogger::GetSink( const CStr& name ) { - for ( uint i = 0; i < GetSinkCount(); i++ ) + for ( size_t i = 0; i < GetSinkCount(); i++ ) { CNetLogSink* pCurrSink = GetSink( i ); if ( !pCurrSink ) continue; @@ -964,7 +964,7 @@ CNetLogSink* CNetLogger::GetSink( const CStr& name ) //----------------------------------------------------------------------------- void CNetLogger::CallSinks( const CNetLogEvent& event ) { - for ( uint i = 0; i < GetSinkCount(); i++ ) + for ( size_t i = 0; i < GetSinkCount(); i++ ) { CNetLogSink* pCurrSink = GetSink( i ); if ( !pCurrSink ) continue; @@ -1040,7 +1040,8 @@ void CNetLogger::GetStringTime( CStr& str ) void CNetLogger::GetStringTimeStamp( CStr& str ) { char buffer[ 128 ] = { 0 }; - sprintf( buffer, "[%3u.%03u]", ( uint )timer_Time(), ( ( uint )( timer_Time() * 1000 ) % 1000 ) ); + double timestamp = timer_Time(); + sprintf( buffer, "[%3u.%03u]", ( unsigned )timestamp, ( ( unsigned )( timestamp * 1000 ) % 1000 ) ); str = buffer; } diff --git a/source/network/NetLog.h b/source/network/NetLog.h index 6aa1f7c1bf..191c5ab557 100644 --- a/source/network/NetLog.h +++ b/source/network/NetLog.h @@ -191,7 +191,7 @@ public: * @param pEvents List of events to log * @param eventCount The number of events in pEvents list */ - void DoBulkSink( const CNetLogEvent* pEvents, uint eventCount ); + void DoBulkSink( const CNetLogEvent* pEvents, size_t eventCount ); /** * Check if the sink can log the specified event @@ -480,7 +480,7 @@ public: * * @return The number of sink objects */ - uint GetSinkCount( void ); + size_t GetSinkCount( void ); /** * Retrieves the sink by its index @@ -489,7 +489,7 @@ public: * @return NULL if index is out of boundaries or * the sink at the specified index */ - CNetLogSink* GetSink( uint index ); + CNetLogSink* GetSink( size_t index ); /** * Retrieves a sink by its name diff --git a/source/network/NetMessage.cpp b/source/network/NetMessage.cpp index bc5b0ec2f9..c9a9304d91 100644 --- a/source/network/NetMessage.cpp +++ b/source/network/NetMessage.cpp @@ -25,7 +25,7 @@ CNetMessage::~CNetMessage() u8 *CNetMessage::Serialize(u8 *pos) const { return pos; } -uint CNetMessage::GetSerializedLength() const +size_t CNetMessage::GetSerializedLength() const { return 0; } @@ -49,7 +49,7 @@ CNetMessage *CNetMessage::Copy() const return new CNetMessage(NMT_NONE); } -CNetMessage *CNetMessage::DeserializeMessage(ENetMessageType type, u8 *buffer, uint length) +CNetMessage *CNetMessage::DeserializeMessage(ENetMessageType type, u8 *buffer, size_t length) { { ONCE( @@ -214,7 +214,7 @@ CNetCommand *CNetMessage::CommandFromJSArgs(const CEntityList &entities, JSConte // argIndex, incremented by reading macros. We have already "eaten" the // first argument (message type) - uint argIndex = 1; + size_t argIndex = 1; switch (msgType) { // NMT_Goto, targetX, targetY diff --git a/source/network/NetMessage.h b/source/network/NetMessage.h index 945b0cbffa..ccc411838b 100644 --- a/source/network/NetMessage.h +++ b/source/network/NetMessage.h @@ -34,7 +34,7 @@ public: /** * @returns The length of the message when serialized. */ - virtual uint GetSerializedLength() const; + virtual size_t GetSerializedLength() const; /** * Serialize the message into the buffer. The buffer will have the size * returned from the last call to GetSerializedLength() @@ -65,7 +65,7 @@ public: * @returns a pointer to a newly created CNetMessage subclass, or NULL if * there was an error in data format. */ - static CNetMessage *DeserializeMessage(ENetMessageType type, u8 *buffer, uint length); + static CNetMessage *DeserializeMessage(ENetMessageType type, u8 *buffer, size_t length); /** * Register a selection of message types as JS constants. @@ -81,7 +81,7 @@ public: static CNetMessage *CreateProduceMessage( const CEntityList& entities, const int type, int proType, const CStrW& name ); }; -typedef CNetMessage * (*NetMessageDeserializer) (const u8 *buffer, uint length); +typedef CNetMessage * (*NetMessageDeserializer) (const u8 *buffer, size_t length); #include "simulation/EntityHandles.h" diff --git a/source/network/Network.cpp b/source/network/Network.cpp index 710773c98d..2972534a64 100644 --- a/source/network/Network.cpp +++ b/source/network/Network.cpp @@ -159,10 +159,10 @@ void CMessageSocket::StartWriteNextMessage() // Prepare the header SNetHeader hdr; hdr.m_MsgType=pMsg->GetType(); - hdr.m_MsgLength=pMsg->GetSerializedLength(); + hdr.m_MsgLength=(u16)pMsg->GetSerializedLength(); // Allocate buffer space - if ((uint)(hdr.m_MsgLength+HEADER_LENGTH) > m_WrBufferSize) + if ((size_t)(hdr.m_MsgLength+HEADER_LENGTH) > m_WrBufferSize) { m_WrBufferSize = BUFFER_SIZE(hdr.m_MsgLength+HEADER_LENGTH); if (m_pWrBuffer) @@ -258,7 +258,7 @@ void CMessageSocket::StartReadMessage() SNetHeader hdr; hdr.Deserialize(m_pRdBuffer); - uint reqBufSize=HEADER_LENGTH+hdr.m_MsgLength; + size_t reqBufSize=HEADER_LENGTH+hdr.m_MsgLength; if (m_RdBufferSize < reqBufSize) { m_RdBufferSize=BUFFER_SIZE(reqBufSize); diff --git a/source/network/Network.h b/source/network/Network.h index 87120e7fc0..b02fe2f183 100644 --- a/source/network/Network.h +++ b/source/network/Network.h @@ -235,10 +235,10 @@ class CMessageSocket: protected CStreamSocket, public IMessagePipeEnd { bool m_IsWriting; u8 *m_pWrBuffer; - uint m_WrBufferSize; + size_t m_WrBufferSize; bool m_ReadingData; u8 *m_pRdBuffer; - uint m_RdBufferSize; + size_t m_RdBufferSize; CLockedMessageDeque m_InQ; // Messages read from socket CLockedMessageDeque m_OutQ;// Messages to write to socket diff --git a/source/network/NetworkInternal.h b/source/network/NetworkInternal.h index 7ab8453b4a..f8098c7a53 100644 --- a/source/network/NetworkInternal.h +++ b/source/network/NetworkInternal.h @@ -37,7 +37,7 @@ public: // Bitwise OR of all operations to listen for. // See READ and WRITE - uint m_Ops; + int m_Ops; char *m_pConnectHost; int m_ConnectPort; @@ -63,7 +63,7 @@ struct CSocketSetInternal pthread_mutex_t m_Mutex; pthread_t m_Thread; - uint m_NumSockets; + size_t m_NumSockets; std::map m_HandleMap; #if OS_WIN diff --git a/source/network/Serialization.h b/source/network/Serialization.h index d0caa40128..c8fe5d6823 100644 --- a/source/network/Serialization.h +++ b/source/network/Serialization.h @@ -61,7 +61,7 @@ public: /** * Return the length of the serialized form of this object */ - virtual uint GetSerializedLength() const = 0; + virtual size_t GetSerializedLength() const = 0; /** * Serialize the object into the passed buffer. * diff --git a/source/network/Server.cpp b/source/network/Server.cpp index f21f0e29b8..cf4ba168e6 100644 --- a/source/network/Server.cpp +++ b/source/network/Server.cpp @@ -152,7 +152,7 @@ void FillSetPlayerConfigCB(const CStrW& name, ISynchedJSProperty *prop, void *us void CNetServer::FillSetPlayerConfig(CSetPlayerConfig *pMsg, CPlayer *pPlayer) { - pMsg->m_PlayerID=pPlayer->GetPlayerID(); + pMsg->m_PlayerID=(u32)pPlayer->GetPlayerID(); pPlayer->IterateSynchedProperties(FillSetPlayerConfigCB, pMsg); } @@ -196,7 +196,7 @@ void CNetServer::AddSession(CNetServerSession *pSession) pSession->Push(pMsg); // Sync player slot assignments and player attributes - for (uint i=0;iGetSlotCount();i++) + for (size_t i=0;iGetSlotCount();i++) { CPlayerSlot *pSlot=m_pGameAttributes->GetSlot(i); @@ -232,7 +232,7 @@ void CNetServer::PlayerAttributeUpdate(const CStrW& name, const CStrW& newValue, g_Console->InsertMessage(L"PlayerAttributeUpdate(%d): %ls = \"%ls\"", pPlayer->GetPlayerID(), name.c_str(), newValue.c_str()); CSetPlayerConfig *pMsg=new CSetPlayerConfig; - pMsg->m_PlayerID=pPlayer->GetPlayerID(); + pMsg->m_PlayerID=(u32)pPlayer->GetPlayerID(); pMsg->m_Values.resize(1); pMsg->m_Values[0].m_Name=name; pMsg->m_Values[0].m_Value=newValue; @@ -243,7 +243,7 @@ void CNetServer::PlayerAttributeUpdate(const CStrW& name, const CStrW& newValue, CNetMessage *CNetServer::CreatePlayerSlotAssignmentMessage(CPlayerSlot *pSlot) { CAssignPlayerSlot *pMsg=new CAssignPlayerSlot(); - pMsg->m_SlotID=pSlot->GetSlotID(); + pMsg->m_SlotID=(u32)pSlot->GetSlotID(); pMsg->m_SessionID=pSlot->GetSessionID(); switch (pSlot->GetAssignment()) { @@ -348,7 +348,7 @@ int CNetServer::StartGame() else { CTurnManager::Initialize(m_pGameAttributes->GetSlotCount()); - for (uint i=0;iGetSlotCount();i++) + for (size_t i=0;iGetSlotCount();i++) { CPlayerSlot *pSlot=m_pGameAttributes->GetSlot(i); if (pSlot->GetAssignment() == SLOT_SESSION) diff --git a/source/network/Server.h b/source/network/Server.h index cb6ed415a6..360a64216b 100644 --- a/source/network/Server.h +++ b/source/network/Server.h @@ -54,7 +54,7 @@ private: CGame *m_pGame; CGameAttributes *m_pGameAttributes; - uint m_MaxObservers; + size_t m_MaxObservers; int m_LastSessionID; CPlayer *m_pServerPlayer; diff --git a/source/network/SocketBase.cpp b/source/network/SocketBase.cpp index f07483411c..3c28456f49 100644 --- a/source/network/SocketBase.cpp +++ b/source/network/SocketBase.cpp @@ -326,7 +326,7 @@ void CSocketBase::SetTcpNoDelay(bool tcpNoDelay) setsockopt(m_pInternal->m_fd, SOL_SOCKET, TCP_NODELAY, (const char *)&data, sizeof(data)); } -PS_RESULT CSocketBase::Read(void *buf, uint len, uint *bytesRead) +PS_RESULT CSocketBase::Read(void *buf, size_t len, size_t *bytesRead) { int res; char errbuf[256]; @@ -376,7 +376,7 @@ PS_RESULT CSocketBase::Read(void *buf, uint len, uint *bytesRead) return PS_OK; } -PS_RESULT CSocketBase::Write(void *buf, uint len, uint *bytesWritten) +PS_RESULT CSocketBase::Write(void *buf, size_t len, size_t *bytesWritten) { int res; char errbuf[256]; @@ -547,7 +547,7 @@ void CSocketBase::Reject() bool CSocketBase::ConnectError(CSocketBase *pSocket) { CSocketInternal *pInt=pSocket->m_pInternal; - uint buf; + size_t buf; int res; if (pSocket->m_State==SS_CONNECT_STARTED) @@ -617,7 +617,7 @@ void CSocketBase::SocketReadable(CSocketBase *pSock) } else if (pSock->m_State != SS_UNCONNECTED) { - uint nRead; + size_t nRead; errno=0; int res=ioctl(pSock->m_pInternal->m_fd, FIONREAD, &nRead); // failure, errno=EINVAL means server socket @@ -679,7 +679,7 @@ void CSocketBase::RunWaitLoop() it=g_SocketSetInternal.m_HandleMap.begin(); while (it != g_SocketSetInternal.m_HandleMap.end()) { - uint ops=it->second->m_pInternal->m_Ops; + size_t ops=it->second->m_pInternal->m_Ops; if (ops && it->first > fd_max) fd_max=it->first; @@ -780,7 +780,7 @@ void CSocketBase::SendWaitLoopUpdate() // Windows WindowProc for async event notification #else // i.e. #if OS_WIN -void WaitLoop_SocketUpdateProc(int fd, int error, uint event) +void WaitLoop_SocketUpdateProc(int fd, int error, int event) { GLOBAL_LOCK(); CSocketBase *pSock=g_SocketSetInternal.m_HandleMap[fd]; @@ -957,12 +957,12 @@ void CSocketBase::AbortWaitLoop() // pthread_join(g_SocketSetInternal.m_Thread); } -uint CSocketBase::GetOpMask() +int CSocketBase::GetOpMask() { return m_pInternal->m_Ops; } -void CSocketBase::SetOpMask(uint ops) +void CSocketBase::SetOpMask(int ops) { GLOBAL_LOCK(); g_SocketSetInternal.m_HandleMap[m_pInternal->m_fd]=this; diff --git a/source/network/SocketBase.h b/source/network/SocketBase.h index 7bdde18e09..a4a07f9a59 100644 --- a/source/network/SocketBase.h +++ b/source/network/SocketBase.h @@ -205,7 +205,7 @@ private: /** * Used by the winsock AsyncSelect windowproc */ - friend void WaitLoop_SocketUpdateProc(int fd, int error, uint eventmask); + friend void WaitLoop_SocketUpdateProc(int fd, int error, int eventmask); #else // These are utility functions for the unix select loop. Dox can be found in @@ -239,7 +239,7 @@ protected: /** * Get the op mask for the socket. */ - uint GetOpMask(); + int GetOpMask(); /** * Set the op mask for the socket, specifying which callbacks should be @@ -254,7 +254,7 @@ protected: * called when appropriate, but does not make the opposite guarantee for * unset bits; i.e. any callback may be called even with a zero op mask. */ - void SetOpMask(uint ops); + void SetOpMask(int ops); public: /** @@ -437,7 +437,7 @@ public: * @retval PS_OK Some or all data was successfully read. * @retval CONNECTION_BROKEN The socket is not connected or a server socket */ - PS_RESULT Read(void *buf, uint len, uint *bytesRead); + PS_RESULT Read(void *buf, size_t len, size_t *bytesRead); /** * Attempt to write data to the socket. All data that can be sent without @@ -451,7 +451,7 @@ public: * @retval PS_OK Some or all data was successfully read. * @retval CONNECTION_BROKEN The socket is not connected or a server socket */ - PS_RESULT Write(void *buf, uint len, uint *bytesWritten); + PS_RESULT Write(void *buf, size_t len, size_t *bytesWritten); //@} /** @name Callbacks */ diff --git a/source/network/StreamSocket.cpp b/source/network/StreamSocket.cpp index 068ff69bab..16f523440c 100644 --- a/source/network/StreamSocket.cpp +++ b/source/network/StreamSocket.cpp @@ -68,7 +68,7 @@ PS_RESULT CStreamSocket::BeginConnect(const char *hostname, int port) return PS_OK; } -PS_RESULT CStreamSocket::Read(void *buf, uint len) +PS_RESULT CStreamSocket::Read(void *buf, size_t len) { // Check socket status if (GetState() != SS_CONNECTED) @@ -89,7 +89,7 @@ PS_RESULT CStreamSocket::Read(void *buf, uint len) return PS_OK; } -PS_RESULT CStreamSocket::Write(void *buf, uint len) +PS_RESULT CStreamSocket::Write(void *buf, size_t len) { // Check status if (GetState() != SS_CONNECTED) @@ -125,7 +125,7 @@ void CStreamSocket::OnWrite() SetOpMask(GetOpMask() & (~WRITE)); return; } - uint bytes=0; + size_t bytes=0; PS_RESULT res=CSocketBase::Write( ((char *)m_WriteContext.m_pBuffer)+m_WriteContext.m_Completed, m_WriteContext.m_Length-m_WriteContext.m_Completed, @@ -151,7 +151,7 @@ void CStreamSocket::OnRead() NET_LOG("CStreamSocket::OnRead(): No Read request in progress"); return; } - uint bytes=0; + size_t bytes=0; PS_RESULT res=CSocketBase::Read( ((u8 *)m_ReadContext.m_pBuffer)+m_ReadContext.m_Completed, m_ReadContext.m_Length-m_ReadContext.m_Completed, diff --git a/source/network/StreamSocket.h b/source/network/StreamSocket.h index f5cea2dd36..83c6ffa939 100644 --- a/source/network/StreamSocket.h +++ b/source/network/StreamSocket.h @@ -19,8 +19,8 @@ class CStreamSocket: public CSocketBase { bool m_Valid; void *m_pBuffer; - uint m_Length; - uint m_Completed; + size_t m_Length; + size_t m_Completed; inline SOperationContext(): m_Valid(false) @@ -94,7 +94,7 @@ public: * CONFLICTING_OP_IN_PROGRESS Another Read operation is alread in progress * CONNECTION_BROKEN The socket is not connected or a server socket */ - PS_RESULT Read(void *buf, uint len); + PS_RESULT Read(void *buf, size_t len); /** * Start a Write operation. The function call will return immediately and @@ -110,7 +110,7 @@ public: * CONFLICTING_OP_IN_PROGRESS Another Write operation is in progress * CONNECTION_BROKEN The socket is not connected or a server socket */ - PS_RESULT Write(void *buf, uint len); + PS_RESULT Write(void *buf, size_t len); // The default implementation of these methods are no-ops virtual void ConnectComplete(PS_RESULT errorCode); diff --git a/source/ps/CConsole.cpp b/source/ps/CConsole.cpp index 449b3d7585..9d557ddfa5 100644 --- a/source/ps/CConsole.cpp +++ b/source/ps/CConsole.cpp @@ -113,20 +113,20 @@ void CConsole::FlushBuffer(void) } -void CConsole::ToLower(wchar_t* szMessage, uint iSize) +void CConsole::ToLower(wchar_t* szMessage, size_t iSize) { - uint L = (uint)wcslen(szMessage); + size_t L = (size_t)wcslen(szMessage); if (L <= 0) return; if (iSize && iSize < L) L = iSize; - for(uint i = 0; i < L; i++) + for(size_t i = 0; i < L; i++) szMessage[i] = towlower(szMessage[i]); } -void CConsole::Trim(wchar_t* szMessage, const wchar_t cChar, uint iSize) +void CConsole::Trim(wchar_t* szMessage, const wchar_t cChar, size_t iSize) { size_t L = wcslen(szMessage); if(!L) diff --git a/source/ps/CConsole.h b/source/ps/CConsole.h index db6adcd9ad..712a6f8e20 100644 --- a/source/ps/CConsole.h +++ b/source/ps/CConsole.h @@ -95,8 +95,8 @@ private: bool m_bVisible; // console is to be drawn bool m_bToggle; // show/hide animation is currently active - void ToLower(wchar_t* szMessage, uint iSize = 0); - void Trim(wchar_t* szMessage, const wchar_t cChar = 32, uint iSize = 0); + void ToLower(wchar_t* szMessage, size_t iSize = 0); + void Trim(wchar_t* szMessage, const wchar_t cChar = 32, size_t iSize = 0); void DrawHistory(void); void DrawWindow(void); diff --git a/source/ps/CStr.cpp b/source/ps/CStr.cpp index a00afb7f84..a8feae43c6 100644 --- a/source/ps/CStr.cpp +++ b/source/ps/CStr.cpp @@ -234,7 +234,7 @@ int CStr::ToInt() const unsigned int CStr::ToUInt() const { - return uint(_ttoi(c_str())); + return (unsigned int)_ttoi(c_str()); } long CStr::ToLong() const @@ -244,7 +244,7 @@ long CStr::ToLong() const unsigned long CStr::ToULong() const { - return ulong(_ttol(c_str())); + return (unsigned long)_ttol(c_str()); } float CStr::ToFloat() const @@ -586,9 +586,9 @@ const u8* CStrW::Deserialize(const u8* buffer, const u8* bufferend) return (const u8 *)(strend+1); } -uint CStr::GetSerializedLength() const +size_t CStr::GetSerializedLength() const { - return uint(length()*2 + 2); + return size_t(length()*2 + 2); } #else @@ -618,9 +618,9 @@ const u8* CStr8::Deserialize(const u8* buffer, const u8* bufferend) return strend+1; } -uint CStr::GetSerializedLength() const +size_t CStr::GetSerializedLength() const { - return uint(length() + 1); + return size_t(length() + 1); } #endif // _UNICODE diff --git a/source/ps/CStr.h b/source/ps/CStr.h index cbd3cc7d87..62d966357d 100644 --- a/source/ps/CStr.h +++ b/source/ps/CStr.h @@ -487,7 +487,7 @@ public: // Serialization functions // (These are not virtual or inherited from ISerializable, to avoid // adding a vtable and making the strings larger than std::string) - uint GetSerializedLength() const; + size_t GetSerializedLength() const; u8* Serialize(u8* buffer) const; const u8* Deserialize(const u8* buffer, const u8* bufferend); }; diff --git a/source/ps/ConfigDB.cpp b/source/ps/ConfigDB.cpp index eca4455035..5ab17667f7 100644 --- a/source/ps/ConfigDB.cpp +++ b/source/ps/ConfigDB.cpp @@ -60,7 +60,7 @@ namespace ConfigNamespace_JS JS_ConvertStub, JS_FinalizeStub }; - JSBool Construct( JSContext* cx, JSObject* obj, uint argc, jsval* UNUSED(argv), jsval* rval ) + JSBool Construct( JSContext* cx, JSObject* obj, uintN argc, jsval* UNUSED(argv), jsval* rval ) { if (argc != 0) return JS_FALSE; @@ -75,7 +75,7 @@ namespace ConfigNamespace_JS JS_SetPrivate(cx, obj, (void *)cfgNs); } - JSBool WriteFile( JSContext* cx, JSObject* obj, uint argc, jsval* argv, jsval* rval ) + JSBool WriteFile( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval ) { EConfigNamespace cfgNs=(EConfigNamespace)(intptr_t)JS_GetPrivate(cx, obj); if (cfgNs < 0 || cfgNs >= CFG_LAST) @@ -96,7 +96,7 @@ namespace ConfigNamespace_JS return JS_FALSE; } - JSBool Reload( JSContext* cx, JSObject* obj, uint argc, jsval* UNUSED(argv), jsval* rval ) + JSBool Reload( JSContext* cx, JSObject* obj, uintN argc, jsval* UNUSED(argv), jsval* rval ) { if (argc != 0) return JS_FALSE; @@ -110,7 +110,7 @@ namespace ConfigNamespace_JS return JS_TRUE; } - JSBool SetFile( JSContext* cx, JSObject* obj, uint argc, jsval* argv, jsval* UNUSED(rval) ) + JSBool SetFile( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* UNUSED(rval) ) { if (argc != 0) return JS_FALSE; @@ -156,7 +156,7 @@ namespace ConfigDB_JS {0} }; - JSBool Construct( JSContext* cx, JSObject* obj, uint argc, jsval* UNUSED(argv), jsval* rval ) + JSBool Construct( JSContext* cx, JSObject* obj, uintN argc, jsval* UNUSED(argv), jsval* rval ) { if (argc != 0) return JS_FALSE; diff --git a/source/ps/FileIo.cpp b/source/ps/FileIo.cpp index f020c265cf..357e19654f 100644 --- a/source/ps/FileIo.cpp +++ b/source/ps/FileIo.cpp @@ -62,12 +62,16 @@ void CFilePacker::PackRaw(const void* rawData, size_t rawSize) m_writeBuffer.Append(rawData, rawSize); } +void CFilePacker::PackSize(size_t value) +{ + const u32 value_le32 = to_le32(u32_from_larger(value)); + PackRaw(&value_le32, sizeof(value_le32)); +} void CFilePacker::PackString(const CStr& str) { const size_t length = str.length(); - const u32 length_le = to_le32(u32_from_larger(length)); - PackRaw(&length_le, sizeof(length_le)); + PackSize(length); PackRaw((const char*)str, length); } @@ -137,12 +141,17 @@ void CFileUnpacker::UnpackRaw(void* rawData, size_t rawDataSize) } +size_t CFileUnpacker::UnpackSize() +{ + u32 value_le32; + UnpackRaw(&value_le32, sizeof(value_le32)); + return (size_t)to_le32(value_le32); +} + + void CFileUnpacker::UnpackString(CStr& result) { - // get string length - u32 length_le; - UnpackRaw(&length_le, sizeof(length_le)); - const size_t length = (size_t)to_le32(length_le); + const size_t length = UnpackSize(); // fail if reading past end of stream if (m_unpackPos+length > m_bufSize) diff --git a/source/ps/FileIo.h b/source/ps/FileIo.h index 5a9efb3e0d..23ab29771f 100644 --- a/source/ps/FileIo.h +++ b/source/ps/FileIo.h @@ -11,7 +11,8 @@ // so marked. // all > 8-bit integers are stored in little-endian format // (hence the _le suffix). however, the caller is responsible for -// swapping their raw data before passing it to PackRaw. +// swapping their raw data before passing it to PackRaw. a convenience +// routine is provided for the common case of storing size_t. #ifndef INCLUDED_FILEPACKER #define INCLUDED_FILEPACKER @@ -59,6 +60,12 @@ public: **/ void PackRaw(const void* rawData, size_t rawDataSize); + /** + * convenience: convert a number (almost always a size type) to + * little-endian u32 and pack that. + **/ + void PackSize(size_t value); + /** * pack a string onto the end of the data stream * (encoded as a 32-bit length followed by the characters) @@ -104,6 +111,12 @@ public: **/ void UnpackRaw(void* rawData, size_t rawDataSize); + /** + * use UnpackRaw to retrieve 32-bits; returns their value as size_t + * after converting from little endian to native byte order. + **/ + size_t UnpackSize(); + /** * unpack a string from the raw data stream. * @param result is assigned a newly constructed CStr8 holding the diff --git a/source/ps/Game.cpp b/source/ps/Game.cpp index a95b3db607..dba9306c4d 100644 --- a/source/ps/Game.cpp +++ b/source/ps/Game.cpp @@ -173,7 +173,7 @@ PSRETURN CGame::StartGame(CGameAttributes *pAttribs) // Player 0 = Gaia - allocate one extra m_Players.resize(m_NumPlayers + 1); - for (uint i=0;i <= m_NumPlayers;i++) + for (size_t i=0;i <= m_NumPlayers;i++) m_Players[i]=pAttribs->GetPlayer(i); if (g_NetClient) @@ -304,10 +304,10 @@ void CGame::EndGame() /** * Get the player object from the players list at the provided index. * - * @param PS_uint idx sequential position in the list. + * @param idx sequential position in the list. * @return CPlayer * pointer to player requested. **/ -CPlayer *CGame::GetPlayer(uint idx) +CPlayer *CGame::GetPlayer(size_t idx) { if (idx > m_NumPlayers) { diff --git a/source/ps/Game.h b/source/ps/Game.h index 02f5298796..7711df85f4 100644 --- a/source/ps/Game.h +++ b/source/ps/Game.h @@ -54,7 +54,7 @@ class CGame : boost::noncopyable /** * number of players operating on the game world(not including gaia). **/ - uint m_NumPlayers; + size_t m_NumPlayers; /** * the game has been initialized and ready for use if true. **/ @@ -119,7 +119,7 @@ public: // PT: No longer inline, because it does too much error checking. When // everything stops trying to access players before they're loaded, feel // free to put the inline version back. - CPlayer *GetPlayer(uint idx); + CPlayer *GetPlayer(size_t idx); /** * Get a reference to the m_Players vector. @@ -132,9 +132,9 @@ public: /** * Get m_NumPlayers. * - * @return PS_uint the value of m_NumPlayers. + * @return the number of players (not including gaia) **/ - inline uint GetNumPlayers() const + inline size_t GetNumPlayers() const { return m_NumPlayers; } /** diff --git a/source/ps/GameAttributes.cpp b/source/ps/GameAttributes.cpp index d7c8c64fc2..9297ed8ca8 100644 --- a/source/ps/GameAttributes.cpp +++ b/source/ps/GameAttributes.cpp @@ -8,10 +8,11 @@ #include "network/ServerSession.h" #include "CLogger.h" #include "ps/XML/Xeromyces.h" +#include "simulation/LOSManager.h" using namespace std; -CPlayerSlot::CPlayerSlot(int slotID, CPlayer *pPlayer): +CPlayerSlot::CPlayerSlot(size_t slotID, CPlayer *pPlayer): m_SlotID(slotID), m_Assignment(SLOT_OPEN), m_pSession(NULL), @@ -144,7 +145,7 @@ namespace PlayerSlotArray_JS CGameAttributes *pInstance=(CGameAttributes *)JS_GetPrivate(cx, obj); if (!JSVAL_IS_INT(id)) return JS_FALSE; - uint index=ToPrimitive(id); + size_t index=ToPrimitive(id); if (index >= pInstance->m_NumSlots) return JS_FALSE; @@ -166,7 +167,7 @@ namespace PlayerSlotArray_JS JS_ConvertStub, JS_FinalizeStub }; - JSBool Construct( JSContext* cx, JSObject* obj, uint argc, jsval* UNUSED(argv), jsval* rval ) + JSBool Construct( JSContext* cx, JSObject* obj, uintN argc, jsval* UNUSED(argv), jsval* rval ) { if (argc != 0) return JS_FALSE; @@ -181,7 +182,7 @@ CGameAttributes::CGameAttributes(): m_MapFile("test01.pmp"), m_ResourceLevel("default"), m_StartingPhase("default"), - m_LOSSetting(0), + m_LOSSetting(LOS_SETTING_NORMAL), m_FogOfWar(true), m_GameMode("default"), m_ScreenshotMode(false), @@ -198,7 +199,8 @@ CGameAttributes::CGameAttributes(): AddSynchedProperty(L"resourceLevel", &m_ResourceLevel); AddSynchedProperty(L"startingPhase", &m_StartingPhase); AddSynchedProperty(L"numSlots", &m_NumSlots, &CGameAttributes::OnNumSlotsUpdate); - AddSynchedProperty(L"losSetting", &m_LOSSetting); + cassert(sizeof(int) == sizeof(ELOSSetting)); + AddSynchedProperty(L"losSetting", (int*)&m_LOSSetting); AddSynchedProperty(L"fogOfWar", &m_FogOfWar); AddSynchedProperty(L"gameMode", &m_GameMode); AddSynchedProperty(L"screenshotMode", &m_ScreenshotMode); @@ -300,7 +302,7 @@ void CGameAttributes::OnNumSlotsUpdate(CSynchedJSObjectBase *owner) // Clamp to a preset upper bound. CConfigValue *val=g_ConfigDB.GetValue(CFG_MOD, "max_players"); - uint maxPlayers=PS_MAX_PLAYERS; + size_t maxPlayers=PS_MAX_PLAYERS; if (val) val->GetUnsignedInt(maxPlayers); if (pInstance->m_NumSlots > maxPlayers) @@ -314,12 +316,12 @@ void CGameAttributes::OnNumSlotsUpdate(CSynchedJSObjectBase *owner) { for (size_t i=pInstance->m_PlayerSlots.size();i<=pInstance->m_NumSlots;i++) { - CPlayer *pNewPlayer=new CPlayer((uint)i+1); + CPlayer *pNewPlayer=new CPlayer(i+1); pNewPlayer->SetUpdateCallback(pInstance->m_PlayerUpdateCB, pInstance->m_PlayerUpdateCBData); pInstance->m_Players.push_back(pNewPlayer); - CPlayerSlot *pNewSlot=new CPlayerSlot((uint)i, pNewPlayer); + CPlayerSlot *pNewSlot=new CPlayerSlot(i, pNewPlayer); pNewSlot->SetCallback(pInstance->m_PlayerSlotAssignmentCB, pInstance->m_PlayerSlotAssignmentCBData); pInstance->m_PlayerSlots.push_back(pNewSlot); @@ -327,12 +329,10 @@ void CGameAttributes::OnNumSlotsUpdate(CSynchedJSObjectBase *owner) } } -CPlayer *CGameAttributes::GetPlayer(int id) +CPlayer *CGameAttributes::GetPlayer(size_t id) { - if (id >= 0 && id < (int)m_Players.size()) - { + if (id < m_Players.size()) return m_Players[id]; - } else { LOG(CLogger::Error, "", "CGameAttributes::GetPlayer(): Attempt to get player %d (while there only are %d players)", id, m_Players.size()); @@ -340,9 +340,9 @@ CPlayer *CGameAttributes::GetPlayer(int id) } } -CPlayerSlot *CGameAttributes::GetSlot(int index) +CPlayerSlot *CGameAttributes::GetSlot(size_t index) { - if (index >= 0 && index < (int)m_PlayerSlots.size()) + if (index < m_PlayerSlots.size()) return m_PlayerSlots[index]; else { @@ -361,7 +361,7 @@ void CGameAttributes::FinalizeSlots() m_Players.push_back(oldPlayers[0]); // Gaia // Copy over the slots we want - uint assignedSlots=0; + size_t assignedSlots=0; for (size_t i=0;i { - int m_SlotID; + size_t m_SlotID; EPlayerSlotAssignment m_Assignment; CNetServerSession *m_pSession; @@ -51,18 +52,18 @@ class CPlayerSlot: public CJSObject protected: friend class CGameAttributes; - inline void SetSlotID(int slotID) + inline void SetSlotID(size_t slotID) { m_SlotID=slotID; } public: - CPlayerSlot(int slotID, CPlayer *pPlayer); + CPlayerSlot(size_t slotID, CPlayer *pPlayer); ~CPlayerSlot(); inline CPlayer *GetPlayer() { return m_pPlayer; } inline int GetSessionID() { return m_SessionID; } - inline int GetSlotID() + inline size_t GetSlotID() { return m_SlotID; } // Only applicable on the server host, and may return NULL if the slot @@ -119,7 +120,7 @@ public: CStrW m_ResourceLevel; CStrW m_StartingPhase; CStrW m_GameMode; - uint m_LOSSetting; + ELOSSetting m_LOSSetting; bool m_FogOfWar; bool m_ScreenshotMode; @@ -128,7 +129,7 @@ public: private: friend JSBool PlayerSlotArray_JS::GetProperty( JSContext* cx, JSObject* obj, jsval id, jsval* vp ); - uint m_NumSlots; + size_t m_NumSlots; // All players in the game. m_Players[0] is the Gaia Player, like in CGame. // m_Players[1..n] have a corresponding player slot in m_PlayerSlots[0..n-1] @@ -164,7 +165,7 @@ public: m_UpdateCBData=userdata; } - inline uint GetSlotCount() + inline size_t GetSlotCount() { return m_NumSlots; } inline CStrW GetGameMode() @@ -176,9 +177,9 @@ public: void FinalizeSlots(); // Get the player object for the passed Player ID - CPlayer *GetPlayer(int id); + CPlayer *GetPlayer(size_t id); // Get the slot object with the specified index - CPlayerSlot *GetSlot(int index); + CPlayerSlot *GetSlot(size_t index); void SetPlayerUpdateCallback(CPlayer::UpdateCallback *cb, void *userdata); void SetPlayerSlotAssignmentCallback(PlayerSlotAssignmentCB *cb, void *userdata); diff --git a/source/ps/GameSetup/GameSetup.cpp b/source/ps/GameSetup/GameSetup.cpp index 469eebb57a..8a3f53e27d 100644 --- a/source/ps/GameSetup/GameSetup.cpp +++ b/source/ps/GameSetup/GameSetup.cpp @@ -99,7 +99,7 @@ static int SetVideoMode(int w, int h, int bpp, bool fullscreen) SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); - ulong flags = SDL_OPENGL; + Uint32 flags = SDL_OPENGL; if(fullscreen) flags |= SDL_FULLSCREEN; if(!SDL_SetVideoMode(w, h, bpp, flags)) @@ -129,11 +129,11 @@ static int SetVideoMode(int w, int h, int bpp, bool fullscreen) return 0; } -static const uint SANE_TEX_QUALITY_DEFAULT = 5; // keep in sync with code +static const int SANE_TEX_QUALITY_DEFAULT = 5; // keep in sync with code -static void SetTextureQuality(uint quality) +static void SetTextureQuality(int quality) { - uint q_flags; + int q_flags; GLint filter; retry: @@ -600,8 +600,8 @@ static void InitVfs(const CmdLineArgs& args) for (size_t i = 0; i < mods.size(); ++i) { CStr path = "mods/" + mods[i]; - uint priority = (uint)i; - uint flags = VFS_MOUNT_WATCH; + size_t priority = i; + int flags = VFS_MOUNT_WATCH; // TODO: currently only archive 'official' - probably ought to archive // all mods instead? @@ -776,7 +776,7 @@ void EndGame() } -void Shutdown(uint flags) +void Shutdown(int flags) { MICROLOG(L"Shutdown"); @@ -906,7 +906,7 @@ void EarlyInit() srand(time(NULL)); // NOTE: this rand should *not* be used for simulation! } -void Init(const CmdLineArgs& args, uint flags) +void Init(const CmdLineArgs& args, int flags) { const bool setup_vmode = (flags & INIT_HAVE_VMODE) == 0; @@ -989,7 +989,7 @@ void Init(const CmdLineArgs& args, uint flags) tex_codec_register_all(); - uint quality = SANE_TEX_QUALITY_DEFAULT; // TODO: set value from config file + const int quality = SANE_TEX_QUALITY_DEFAULT; // TODO: set value from config file SetTextureQuality(quality); // needed by ogl_tex to detect broken gfx card/driver combos, diff --git a/source/ps/GameSetup/GameSetup.h b/source/ps/GameSetup/GameSetup.h index e533820d13..510522d02b 100644 --- a/source/ps/GameSetup/GameSetup.h +++ b/source/ps/GameSetup/GameSetup.h @@ -41,5 +41,5 @@ enum InitFlags }; class CmdLineArgs; -extern void Init(const CmdLineArgs& args, uint flags); -extern void Shutdown(uint flags); +extern void Init(const CmdLineArgs& args, int flags); +extern void Shutdown(int flags); diff --git a/source/ps/Globals.cpp b/source/ps/Globals.cpp index f71b0e37f2..b37ee8f541 100644 --- a/source/ps/Globals.cpp +++ b/source/ps/Globals.cpp @@ -19,7 +19,7 @@ PIFrequencyFilter g_frequencyFilter; // updates the state of the above; never swallows messages. InReaction GlobalsInputHandler(const SDL_Event_* ev) { - uint c; + size_t c; switch(ev->ev.type) { diff --git a/source/ps/Hotkey.cpp b/source/ps/Hotkey.cpp index 4cbf749b72..5069504c06 100644 --- a/source/ps/Hotkey.cpp +++ b/source/ps/Hotkey.cpp @@ -423,7 +423,7 @@ InReaction HotkeyInputHandler( const SDL_Event_* ev ) // SDL-events bit - uint closestMap = 0; // avoid "uninitialized" warning + size_t closestMap = 0; // avoid "uninitialized" warning size_t closestMapMatch = 0; for( it = hotkeyMap[keycode].begin(); it < hotkeyMap[keycode].end(); it++ ) @@ -454,7 +454,7 @@ InReaction HotkeyInputHandler( const SDL_Event_* ev ) { if( g_mouse_buttons[keyCode-SDLK_LAST] != rqdState ) accept = false; } - else if( (uint)(keyCode-UNIFIED_SHIFT) < ARRAY_SIZE(unified) ) + else if( (size_t)(keyCode-UNIFIED_SHIFT) < ARRAY_SIZE(unified) ) { if( unified[keyCode-UNIFIED_SHIFT] != rqdState ) accept = false; } @@ -489,7 +489,7 @@ InReaction HotkeyInputHandler( const SDL_Event_* ev ) if( closestMapMatch ) { hotkeyNotification.type = SDL_HOTKEYDOWN; - hotkeyNotification.user.code = closestMap; + hotkeyNotification.user.code = (int)closestMap; SDL_PushEvent( &hotkeyNotification ); } // GUI bit... could do with some optimization later. @@ -523,7 +523,7 @@ InReaction HotkeyInputHandler( const SDL_Event_* ev ) { if( g_mouse_buttons[keyCode-SDLK_LAST] != rqdState ) accept = false; } - else if( (uint)(keyCode-UNIFIED_SHIFT) < ARRAY_SIZE(unified) ) + else if( (size_t)(keyCode-UNIFIED_SHIFT) < ARRAY_SIZE(unified) ) { if( unified[keyCode-UNIFIED_SHIFT] != rqdState ) accept = false; } diff --git a/source/ps/Interact.cpp b/source/ps/Interact.cpp index 2ee3b80445..a781d2458b 100644 --- a/source/ps/Interact.cpp +++ b/source/ps/Interact.cpp @@ -220,7 +220,7 @@ void CSelectedEntities::RenderOverlays() glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); glTranslatef( x, g_Renderer.GetHeight() - y, 0.0f ); glScalef( 1.0f, -1.0f, 1.0f ); - glwprintf( L"%d", (i32) (*it)->m_grouped ); + glwprintf( L"%d", (*it)->m_grouped ); } } @@ -244,7 +244,7 @@ void CSelectedEntities::RenderOverlays() glColor4f( 1.0f, 1.0f, 1.0f, 0.5f ); glTranslatef( x, g_Renderer.GetHeight() - y, 0.0f ); glScalef( 1.0f, -1.0f, 1.0f ); - glwprintf( L"%d", (i32) (*it)->m_grouped ); + glwprintf( L"%d", (*it)->m_grouped ); } glDisable( GL_BLEND ); @@ -441,7 +441,7 @@ void CSelectedEntities::AddGroup( i8 groupid ) void CSelectedEntities::ChangeGroup( HEntity entity, i8 groupid ) { // Remove from current group - i32 current = entity->m_grouped; + ssize_t current = entity->m_grouped; if( current != -1 ) { std::vector::iterator it; @@ -1024,7 +1024,7 @@ void CMouseoverEntities::RenderOverlays() glColor4f( 1.0f, 1.0f, 1.0f, it->fade ); glTranslatef( x, g_Renderer.GetHeight() - y, 0.0f ); glScalef( 1.0f, -1.0f, 1.0f ); - glwprintf( L"%d", (i32) it->entity->m_grouped ); + glwprintf( L"%d", it->entity->m_grouped ); glDisable( GL_TEXTURE_2D ); glPopMatrix(); } @@ -1042,7 +1042,7 @@ void CMouseoverEntities::StopBandbox() m_bandbox = false; } -void FireWorldClickEvent(uint button, int clicks) +void FireWorldClickEvent(int button, int clicks) { //debug_printf("FireWorldClickEvent: button %d, clicks %d\n", button, clicks); //If we're clicking on the minimap, use its world click handler @@ -1058,8 +1058,8 @@ void FireWorldClickEvent(uint button, int clicks) g_Selection.m_secondaryCommand, // FIXME Secondary order, depends entity scripts etc g_Selection.m_secondaryAction, // FIXME Secondary action, depends entity scripts etc g_Mouseover.m_target, - (uint)g_Mouseover.m_worldposition.x, - (uint)g_Mouseover.m_worldposition.y); + g_Mouseover.m_worldposition.x, + g_Mouseover.m_worldposition.y); //Reset duplication flag- after this, it isn't the same order std::vector::iterator it=g_Selection.m_selected.begin(); diff --git a/source/ps/Loader.h b/source/ps/Loader.h index 40d5c3db36..06898569c8 100644 --- a/source/ps/Loader.h +++ b/source/ps/Loader.h @@ -155,12 +155,12 @@ extern LibError LDR_NonprogressiveLoad(); #define LDR_CHECK_TIMEOUT(completed_jobs, total_jobs)\ if(timer_Time() > end_time)\ {\ - int progress_percent = ((completed_jobs)*100 / (total_jobs));\ + size_t progress_percent = ((completed_jobs)*100 / (total_jobs));\ /* 0 means "finished", so don't return that! */\ if(progress_percent == 0)\ progress_percent = 1;\ debug_assert(0 < progress_percent && progress_percent <= 100);\ - return progress_percent;\ + return (int)progress_percent;\ } #endif // #ifndef INCLUDED_LOADER diff --git a/source/ps/Player.cpp b/source/ps/Player.cpp index 1d0377ac72..caa4e78a4b 100644 --- a/source/ps/Player.cpp +++ b/source/ps/Player.cpp @@ -7,9 +7,9 @@ #include "ps/scripting/JSCollection.h" #include "simulation/LOSManager.h" -CPlayer::CPlayer(uint playerID): +CPlayer::CPlayer(size_t playerID): m_PlayerID(playerID), - m_Name(CStrW(L"Player #")+CStrW(playerID)), + m_Name(CStrW(L"Player #")+CStrW((unsigned)playerID)), m_Civilization(L""), m_Colour(0.7f, 0.7f, 0.7f), m_UpdateCB(0) @@ -154,7 +154,7 @@ void CPlayer::JSI_SetDiplomaticStance(JSContext *cx, uintN UNUSED(argc), jsval * m_DiplomaticStance[player->m_PlayerID] = (EDiplomaticStance) stance; - CStrW name = CStrW(L"diplomaticStance_") + CStrW(player->m_PlayerID); + CStrW name = CStrW(L"diplomaticStance_") + CStrW((unsigned)player->m_PlayerID); ISynchedJSProperty *prop=GetSynchedProperty(name); Update(name, prop); } diff --git a/source/ps/Player.h b/source/ps/Player.h index 9889d7f126..fc04c8bfa7 100644 --- a/source/ps/Player.h +++ b/source/ps/Player.h @@ -29,8 +29,8 @@ public: private: CStrW m_Name; CStrW m_Civilization; // Note: this must be the un-internationalized name of the civ - PS_uint m_PlayerID; - PS_uint m_LOSToken; + size_t m_PlayerID; + size_t m_LOSToken; SPlayerColour m_Colour; int /*EDiplomaticStance*/ m_DiplomaticStance[PS_MAX_PLAYERS+1]; std::vector m_ActiveTechs; @@ -41,17 +41,18 @@ private: virtual void Update(const CStrW& name, ISynchedJSProperty *prop); public: - CPlayer( uint playerID ); + CPlayer( size_t playerID ); ~CPlayer(); bool ValidateCommand(CNetMessage *pMsg); - inline PS_uint GetPlayerID() const + static const size_t invalidId = ~(size_t)0; + inline size_t GetPlayerID() const { return m_PlayerID; } - inline void SetPlayerID(PS_uint id) + inline void SetPlayerID(size_t id) { m_PlayerID=id; } - inline PS_uint GetLOSToken() const + inline size_t GetLOSToken() const { return m_LOSToken; } inline const CStrW& GetName() const diff --git a/source/ps/ProfileViewer.cpp b/source/ps/ProfileViewer.cpp index ca59f2c78a..e54b5197cb 100644 --- a/source/ps/ProfileViewer.cpp +++ b/source/ps/ProfileViewer.cpp @@ -151,14 +151,14 @@ void CProfileViewer::RenderProfile() size_t numrows = table->GetNumberRows(); // Render background - uint estimate_height; - uint estimate_width; + GLint estimate_height; + GLint estimate_width; estimate_width = 50; - for(uint i = 0; i < columns.size(); ++i) - estimate_width += columns[i].width; + for(size_t i = 0; i < columns.size(); ++i) + estimate_width += (GLint)columns[i].width; - estimate_height = 3 + (uint)numrows; + estimate_height = 3 + (GLint)numrows; if (m->path.size() > 1) estimate_height += 2; estimate_height = 20*estimate_height; @@ -185,7 +185,7 @@ void CProfileViewer::RenderProfile() glTranslatef( 20.0f, 20.0f, 0.0f ); glPushMatrix(); - for(uint col = 0; col < columns.size(); ++col) + for(size_t col = 0; col < columns.size(); ++col) { glPushMatrix(); glwprintf(L"%hs", columns[col].title.c_str()); @@ -198,7 +198,7 @@ void CProfileViewer::RenderProfile() // Print rows int currentExpandId = 1; - for(uint row = 0; row < numrows; ++row) + for(size_t row = 0; row < numrows; ++row) { glPushMatrix(); @@ -216,7 +216,7 @@ void CProfileViewer::RenderProfile() currentExpandId++; } - for(uint col = 0; col < columns.size(); ++col) + for(size_t col = 0; col < columns.size(); ++col) { glPushMatrix(); glwprintf(L"%hs", table->GetCellText(row, col).c_str()); @@ -278,7 +278,7 @@ InReaction CProfileViewer::Input(const SDL_Event_* ev) } else { - uint i; + size_t i; for(i = 0; i < m->rootTables.size(); ++i) { diff --git a/source/ps/ProfileViewer.h b/source/ps/ProfileViewer.h index 57b62f0814..b8acafece5 100644 --- a/source/ps/ProfileViewer.h +++ b/source/ps/ProfileViewer.h @@ -23,9 +23,9 @@ struct ProfileColumn CStr title; /// Recommended width of the column, in pixels. - uint width; + size_t width; - ProfileColumn(const CStr& t, uint w) : title(t), width(w) { } + ProfileColumn(const CStr& t, size_t w) : title(t), width(w) { } }; diff --git a/source/ps/Pyrogenesis.h b/source/ps/Pyrogenesis.h index 263334cd66..f4724310e8 100644 --- a/source/ps/Pyrogenesis.h +++ b/source/ps/Pyrogenesis.h @@ -7,7 +7,6 @@ Standard declarations which are included in all projects. #ifndef INCLUDED_PYROGENESIS #define INCLUDED_PYROGENESIS - typedef const char * PS_RESULT; #define DEFINE_ERROR(x, y) PS_RESULT x=y diff --git a/source/ps/Util.cpp b/source/ps/Util.cpp index c92bbb4f66..dba98c4aeb 100644 --- a/source/ps/Util.cpp +++ b/source/ps/Util.cpp @@ -122,7 +122,7 @@ void WriteSystemInfo() // output all IPs (> 1 if using VMware or dual ethernet) fprintf(f, " ("); - for(uint i = 0; i < 256 && ips[i]; i++) // safety + for(size_t i = 0; i < 256 && ips[i]; i++) // safety { // separate entries but avoid trailing comma if(i != 0) @@ -194,7 +194,7 @@ static LibError tex_write(Tex* t, const VfsPath& filename) } -static unsigned s_nextScreenshotNumber; +static size_t s_nextScreenshotNumber; // identifies the file format that is to be written // (case-insensitive). examples: "bmp", "png", "jpg". @@ -208,8 +208,8 @@ void WriteScreenshot(const char* extension) VfsPath filename; fs_NextNumberedFilename(g_VFS, filenameFormat, s_nextScreenshotNumber, filename); - const int w = g_xres, h = g_yres; - const int bpp = 24; + const size_t w = (size_t)g_xres, h = (size_t)g_yres; + const size_t bpp = 24; GLenum fmt = GL_RGB; int flags = TEX_BOTTOM_UP; // we want writing BMP to be as fast as possible, @@ -227,7 +227,7 @@ void WriteScreenshot(const char* extension) Tex t; if(tex_wrap(w, h, bpp, flags, buf, hdr_size, &t) < 0) return; - glReadPixels(0, 0, w, h, fmt, GL_UNSIGNED_BYTE, img); + glReadPixels(0, 0, (GLsizei)w, (GLsizei)h, fmt, GL_UNSIGNED_BYTE, img); (void)tex_write(&t, filename); tex_free(&t); } diff --git a/source/ps/XML/Xeromyces.cpp b/source/ps/XML/Xeromyces.cpp index c806e6a515..80d2316ea8 100644 --- a/source/ps/XML/Xeromyces.cpp +++ b/source/ps/XML/Xeromyces.cpp @@ -278,9 +278,9 @@ void XeroHandler::endDocument() std::string lowercase_ascii(const XMLCh *a) { std::string b; - uint len=XMLString::stringLen(a); + size_t len=XMLString::stringLen(a); b.resize(len); - for (uint i = 0; i < len; ++i) + for (size_t i = 0; i < len; ++i) b[i] = (char)towlower(a[i]); return b; } @@ -296,9 +296,9 @@ std::string lowercase_ascii(const XMLCh *a) std::string toAscii( const XMLCh* a ) { std::string b; - uint len=XMLString::stringLen(a); + size_t len=XMLString::stringLen(a); b.reserve(len); - for (uint i = 0; i < len; ++i) + for (size_t i = 0; i < len; ++i) { if(a[i] < 0x80) b += (char) a[i]; diff --git a/source/ps/scripting/JSInterface_Console.cpp b/source/ps/scripting/JSInterface_Console.cpp index 662339d8ec..d8593ca2a8 100644 --- a/source/ps/scripting/JSInterface_Console.cpp +++ b/source/ps/scripting/JSInterface_Console.cpp @@ -79,7 +79,7 @@ JSBool JSI_Console::getConsole( JSContext* cx, JSObject* UNUSED(obj), jsval UNUS return( JS_TRUE ); } -JSBool JSI_Console::writeConsole( JSContext* UNUSED(context), JSObject* UNUSED(globalObject), uint argc, jsval* argv, jsval* UNUSED(rval) ) +JSBool JSI_Console::writeConsole( JSContext* UNUSED(context), JSObject* UNUSED(globalObject), uintN argc, jsval* argv, jsval* UNUSED(rval) ) { debug_assert( argc >= 1 ); CStrW output; diff --git a/source/ps/scripting/JSInterface_Console.h b/source/ps/scripting/JSInterface_Console.h index ce53dbe217..9073d68e91 100644 --- a/source/ps/scripting/JSInterface_Console.h +++ b/source/ps/scripting/JSInterface_Console.h @@ -24,7 +24,7 @@ namespace JSI_Console void init(); - JSBool writeConsole( JSContext* context, JSObject* obj, uint argc, jsval* argv, jsval* rval ); + JSBool writeConsole( JSContext* context, JSObject* obj, uintN argc, jsval* argv, jsval* rval ); } #endif diff --git a/source/ps/scripting/JSInterface_Selection.h b/source/ps/scripting/JSInterface_Selection.h index 49e5512112..5803b704e4 100644 --- a/source/ps/scripting/JSInterface_Selection.h +++ b/source/ps/scripting/JSInterface_Selection.h @@ -18,7 +18,7 @@ namespace JSI_Selection JSBool getGroups( JSContext* context, JSObject* obj, jsval id, jsval* vp ); JSBool setGroups( JSContext* context, JSObject* obj, jsval id, jsval* vp ); - JSBool IsValidContextOrder( JSContext* context, JSObject* obj, uint argc, jsval* argv, jsval* rval ); + JSBool IsValidContextOrder( JSContext* context, JSObject* obj, uintN argc, jsval* argv, jsval* rval ); JSBool getContextOrder( JSContext* context, JSObject* obj, jsval id, jsval* vp ); JSBool setContextOrder( JSContext* context, JSObject* obj, jsval id, jsval* vp ); diff --git a/source/ps/scripting/JSInterface_VFS.cpp b/source/ps/scripting/JSInterface_VFS.cpp index 6adbaf3c0f..693bd18b76 100644 --- a/source/ps/scripting/JSInterface_VFS.cpp +++ b/source/ps/scripting/JSInterface_VFS.cpp @@ -144,7 +144,7 @@ JSBool JSI_VFS::GetFileSize( JSContext* cx, JSObject* UNUSED(obj), uintN argc, j LibError err = g_VFS->GetFileInfo(filename.c_str(), &fileInfo); JS_CHECK_FILE_ERR(err); - *rval = ToJSVal( (uint)fileInfo.Size() ); + *rval = ToJSVal( (unsigned)fileInfo.Size() ); return( JS_TRUE ); } diff --git a/source/renderer/BlendShapes.h b/source/renderer/BlendShapes.h index b9c7ccac28..e76dd41ee3 100644 --- a/source/renderer/BlendShapes.h +++ b/source/renderer/BlendShapes.h @@ -73,8 +73,8 @@ public: m_Data[4]=e; m_Data[5]=f; m_Data[6]=g; m_Data[7]=h; } - int& operator[](int index) { return m_Data[index]; } - const int& operator[](int index) const { return m_Data[index]; } + int& operator[](size_t index) { return m_Data[index]; } + const int& operator[](size_t index) const { return m_Data[index]; } bool operator==(const BlendShape8& lhs) const { return memcmp(m_Data,lhs.m_Data,sizeof(BlendShape8))==0; diff --git a/source/renderer/FixedFunctionModelRenderer.cpp b/source/renderer/FixedFunctionModelRenderer.cpp index 6da16f007e..f06d95ec1a 100644 --- a/source/renderer/FixedFunctionModelRenderer.cpp +++ b/source/renderer/FixedFunctionModelRenderer.cpp @@ -141,7 +141,7 @@ void* FixedFunctionModelRenderer::CreateModelData(CModel* model) // Fill in and upload dynamic vertex array -void FixedFunctionModelRenderer::UpdateModelData(CModel* model, void* data, u32 updateflags) +void FixedFunctionModelRenderer::UpdateModelData(CModel* model, void* data, int updateflags) { FFModel* ffmodel = (FFModel*)data; @@ -180,7 +180,7 @@ void FixedFunctionModelRenderer::DestroyModelData(CModel* UNUSED(model), void* d // Setup one rendering pass -void FixedFunctionModelRenderer::BeginPass(uint streamflags, const CMatrix3D* texturematrix) +void FixedFunctionModelRenderer::BeginPass(int streamflags, const CMatrix3D* texturematrix) { debug_assert(streamflags == (streamflags & (STREAM_POS|STREAM_UV0|STREAM_COLOR|STREAM_TEXGENTOUV1))); @@ -206,7 +206,7 @@ void FixedFunctionModelRenderer::BeginPass(uint streamflags, const CMatrix3D* te // Cleanup one rendering pass -void FixedFunctionModelRenderer::EndPass(uint streamflags) +void FixedFunctionModelRenderer::EndPass(int streamflags) { if (streamflags & STREAM_UV0) glDisableClientState(GL_TEXTURE_COORD_ARRAY); if (streamflags & STREAM_COLOR) glDisableClientState(GL_COLOR_ARRAY); @@ -230,7 +230,7 @@ void FixedFunctionModelRenderer::EndPass(uint streamflags) // Prepare UV coordinates for this modeldef -void FixedFunctionModelRenderer::PrepareModelDef(uint streamflags, CModelDefPtr def) +void FixedFunctionModelRenderer::PrepareModelDef(int streamflags, CModelDefPtr def) { m->ffmodeldef = (FFModelDef*)def->GetRenderData(m); @@ -247,7 +247,7 @@ void FixedFunctionModelRenderer::PrepareModelDef(uint streamflags, CModelDefPtr // Render one model -void FixedFunctionModelRenderer::RenderModel(uint streamflags, CModel* model, void* data) +void FixedFunctionModelRenderer::RenderModel(int streamflags, CModel* model, void* data) { CModelDefPtr mdldef = model->GetModelDef(); FFModel* ffmodel = (FFModel*)data; diff --git a/source/renderer/FixedFunctionModelRenderer.h b/source/renderer/FixedFunctionModelRenderer.h index e93cbe2f9e..de20d41896 100644 --- a/source/renderer/FixedFunctionModelRenderer.h +++ b/source/renderer/FixedFunctionModelRenderer.h @@ -32,13 +32,13 @@ public: // Implementations void* CreateModelData(CModel* model); - void UpdateModelData(CModel* model, void* data, u32 updateflags); + void UpdateModelData(CModel* model, void* data, int updateflags); void DestroyModelData(CModel* model, void* data); - void BeginPass(uint streamflags, const CMatrix3D* texturematrix); - void EndPass(uint streamflags); - void PrepareModelDef(uint streamflags, CModelDefPtr def); - void RenderModel(uint streamflags, CModel* model, void* data); + void BeginPass(int streamflags, const CMatrix3D* texturematrix); + void EndPass(int streamflags); + void PrepareModelDef(int streamflags, CModelDefPtr def); + void RenderModel(int streamflags, CModel* model, void* data); private: FixedFunctionModelRendererInternals* m; diff --git a/source/renderer/HWLightingModelRenderer.cpp b/source/renderer/HWLightingModelRenderer.cpp index 9ec82af6bf..d0e999a4aa 100644 --- a/source/renderer/HWLightingModelRenderer.cpp +++ b/source/renderer/HWLightingModelRenderer.cpp @@ -141,7 +141,7 @@ void* HWLightingModelRenderer::CreateModelData(CModel* model) // Fill in and upload dynamic vertex array -void HWLightingModelRenderer::UpdateModelData(CModel* model, void* data, u32 updateflags) +void HWLightingModelRenderer::UpdateModelData(CModel* model, void* data, int updateflags) { HWLModel* hwlmodel = (HWLModel*)data; @@ -170,7 +170,7 @@ void HWLightingModelRenderer::DestroyModelData(CModel* UNUSED(model), void* data // Setup one rendering pass -void HWLightingModelRenderer::BeginPass(uint streamflags, const CMatrix3D* texturematrix) +void HWLightingModelRenderer::BeginPass(int streamflags, const CMatrix3D* texturematrix) { debug_assert(streamflags == (streamflags & (STREAM_POS|STREAM_UV0|STREAM_COLOR|STREAM_TEXGENTOUV1))); @@ -244,7 +244,7 @@ void HWLightingModelRenderer::BeginPass(uint streamflags, const CMatrix3D* textu // Cleanup one rendering pass -void HWLightingModelRenderer::EndPass(uint streamflags) +void HWLightingModelRenderer::EndPass(int streamflags) { if (streamflags & STREAM_UV0) glDisableClientState(GL_TEXTURE_COORD_ARRAY); if (streamflags & STREAM_COLOR) @@ -272,7 +272,7 @@ void HWLightingModelRenderer::EndPass(uint streamflags) // Prepare UV coordinates for this modeldef -void HWLightingModelRenderer::PrepareModelDef(uint UNUSED(streamflags), CModelDefPtr def) +void HWLightingModelRenderer::PrepareModelDef(int UNUSED(streamflags), CModelDefPtr def) { m->hwlmodeldef = (HWLModelDef*)def->GetRenderData(m); @@ -281,7 +281,7 @@ void HWLightingModelRenderer::PrepareModelDef(uint UNUSED(streamflags), CModelDe // Render one model -void HWLightingModelRenderer::RenderModel(uint streamflags, CModel* model, void* data) +void HWLightingModelRenderer::RenderModel(int streamflags, CModel* model, void* data) { CModelDefPtr mdldef = model->GetModelDef(); HWLModel* hwlmodel = (HWLModel*)data; diff --git a/source/renderer/HWLightingModelRenderer.h b/source/renderer/HWLightingModelRenderer.h index a0b3e2135f..87e73275fa 100644 --- a/source/renderer/HWLightingModelRenderer.h +++ b/source/renderer/HWLightingModelRenderer.h @@ -35,13 +35,13 @@ public: // Implementations void* CreateModelData(CModel* model); - void UpdateModelData(CModel* model, void* data, u32 updateflags); + void UpdateModelData(CModel* model, void* data, int updateflags); void DestroyModelData(CModel* model, void* data); - void BeginPass(uint streamflags, const CMatrix3D* texturematrix); - void EndPass(uint streamflags); - void PrepareModelDef(uint streamflags, CModelDefPtr def); - void RenderModel(uint streamflags, CModel* model, void* data); + void BeginPass(int streamflags, const CMatrix3D* texturematrix); + void EndPass(int streamflags); + void PrepareModelDef(int streamflags, CModelDefPtr def); + void RenderModel(int streamflags, CModel* model, void* data); /** * IsAvailable: Determines whether this model renderer can be used diff --git a/source/renderer/InstancingModelRenderer.cpp b/source/renderer/InstancingModelRenderer.cpp index 0dbd1648e5..82d813804e 100644 --- a/source/renderer/InstancingModelRenderer.cpp +++ b/source/renderer/InstancingModelRenderer.cpp @@ -142,7 +142,7 @@ void* InstancingModelRenderer::CreateModelData(CModel* model) } -void InstancingModelRenderer::UpdateModelData(CModel* UNUSED(model), void* UNUSED(data), u32 UNUSED(updateflags)) +void InstancingModelRenderer::UpdateModelData(CModel* UNUSED(model), void* UNUSED(data), int UNUSED(updateflags)) { // We have no per-CModel data } @@ -155,7 +155,7 @@ void InstancingModelRenderer::DestroyModelData(CModel* UNUSED(model), void* UNUS // Setup one rendering pass. -void InstancingModelRenderer::BeginPass(uint streamflags, const CMatrix3D* texturematrix) +void InstancingModelRenderer::BeginPass(int streamflags, const CMatrix3D* texturematrix) { debug_assert(streamflags == (streamflags & (STREAM_POS|STREAM_UV0|STREAM_COLOR|STREAM_TEXGENTOUV1))); @@ -211,7 +211,7 @@ void InstancingModelRenderer::BeginPass(uint streamflags, const CMatrix3D* textu } // Cleanup rendering pass. -void InstancingModelRenderer::EndPass(uint streamflags) +void InstancingModelRenderer::EndPass(int streamflags) { if (streamflags & STREAM_UV0) glDisableClientState(GL_TEXTURE_COORD_ARRAY); if (streamflags & STREAM_COLOR) glDisableClientState(GL_NORMAL_ARRAY); @@ -222,7 +222,7 @@ void InstancingModelRenderer::EndPass(uint streamflags) // Prepare UV coordinates for this modeldef -void InstancingModelRenderer::PrepareModelDef(uint streamflags, CModelDefPtr def) +void InstancingModelRenderer::PrepareModelDef(int streamflags, CModelDefPtr def) { m->imodeldef = (IModelDef*)def->GetRenderData(m); @@ -244,7 +244,7 @@ void InstancingModelRenderer::PrepareModelDef(uint streamflags, CModelDefPtr def // Render one model -void InstancingModelRenderer::RenderModel(uint streamflags, CModel* model, void* UNUSED(data)) +void InstancingModelRenderer::RenderModel(int streamflags, CModel* model, void* UNUSED(data)) { CModelDefPtr mdldef = model->GetModelDef(); const CMatrix3D& mat = model->GetTransform(); diff --git a/source/renderer/InstancingModelRenderer.h b/source/renderer/InstancingModelRenderer.h index b323e473db..c8458c78f1 100644 --- a/source/renderer/InstancingModelRenderer.h +++ b/source/renderer/InstancingModelRenderer.h @@ -35,13 +35,13 @@ public: // Implementations void* CreateModelData(CModel* model); - void UpdateModelData(CModel* model, void* data, u32 updateflags); + void UpdateModelData(CModel* model, void* data, int updateflags); void DestroyModelData(CModel* model, void* data); - void BeginPass(uint streamflags, const CMatrix3D* texturematrix); - void EndPass(uint streamflags); - void PrepareModelDef(uint streamflags, CModelDefPtr def); - void RenderModel(uint streamflags, CModel* model, void* data); + void BeginPass(int streamflags, const CMatrix3D* texturematrix); + void EndPass(int streamflags); + void PrepareModelDef(int streamflags, CModelDefPtr def); + void RenderModel(int streamflags, CModel* model, void* data); /** * IsAvailable: Determines whether this model renderer can be used diff --git a/source/renderer/ModelRenderer.cpp b/source/renderer/ModelRenderer.cpp index 5643b1bdaf..920cb414ce 100644 --- a/source/renderer/ModelRenderer.cpp +++ b/source/renderer/ModelRenderer.cpp @@ -84,7 +84,7 @@ void ModelRenderer::BuildPositionAndNormals( // just copy regular positions, transform normals to world space const CMatrix3D& transform = model->GetTransform(); const CMatrix3D& invtransform = model->GetInvTransform(); - for (uint j=0; jGetNumVertices(); SModelVertex* vertices = mdef->GetVertices(); - for (uint j=0; j < numVertices; ++j, ++UV) + for (size_t j=0; j < numVertices; ++j, ++UV) { (*UV)[0] = vertices[j].m_U; (*UV)[1] = 1.0-vertices[j].m_V; @@ -154,7 +154,7 @@ void ModelRenderer::BuildIndices( CModelDefPtr mdef, u16* Indices) { - u32 idxidx = 0; + size_t idxidx = 0; SModelFace* faces = mdef->GetFaces(); for (size_t j = 0; j < mdef->GetNumFaces(); ++j) { @@ -219,7 +219,7 @@ struct BMRModelDefTracker : public CModelDefRPrivate BMRModelDefTracker* m_Next; /// Number of slots used in m_ModelSlots - uint m_Slots; + size_t m_Slots; /// Each slot contains a linked list of model data objects, up to m_Slots-1 // At the end of the frame, m_Slots is reset to 0, but m_ModelSlots stays @@ -258,7 +258,7 @@ struct BatchModelRendererInternals vertexRenderer->DestroyModelData(model, data); } - void RenderAllModels(RenderModifierPtr modifier, u32 filterflags, uint pass, uint streamflags); + void RenderAllModels(RenderModifierPtr modifier, int filterflags, int pass, int streamflags); }; BMRModelData::~BMRModelData() @@ -323,7 +323,7 @@ void BatchModelRenderer::Submit(CModel* model) // Add the bmrdata to the modeldef list Handle htex = model->GetTexture()->GetHandle(); - uint idx; + size_t idx; for(idx = 0; idx < mdeftracker->m_Slots; ++idx) { @@ -358,7 +358,7 @@ void BatchModelRenderer::PrepareModels() for(BMRModelDefTracker* mdeftracker = m->submissions; mdeftracker; mdeftracker = mdeftracker->m_Next) { - for(uint idx = 0; idx < mdeftracker->m_Slots; ++idx) + for(size_t idx = 0; idx < mdeftracker->m_Slots; ++idx) { for(BMRModelData* bmrdata = mdeftracker->m_ModelSlots[idx]; bmrdata; bmrdata = bmrdata->m_Next) { @@ -381,7 +381,7 @@ void BatchModelRenderer::PrepareModels() // Clear the submissions list void BatchModelRenderer::EndFrame() { - static uint mostslots = 1; + static size_t mostslots = 1; for(BMRModelDefTracker* mdeftracker = m->submissions; mdeftracker; mdeftracker = mdeftracker->m_Next) { @@ -406,18 +406,18 @@ bool BatchModelRenderer::HaveSubmissions() // Render models, outer loop for multi-passing -void BatchModelRenderer::Render(RenderModifierPtr modifier, u32 flags) +void BatchModelRenderer::Render(RenderModifierPtr modifier, int flags) { debug_assert(m->phase == BMRRender); if (!HaveSubmissions()) return; - uint pass = 0; + int pass = 0; do { - uint streamflags = modifier->BeginPass(pass); + int streamflags = modifier->BeginPass(pass); const CMatrix3D* texturematrix = 0; if (streamflags & STREAM_TEXGENTOUV1) @@ -434,14 +434,14 @@ void BatchModelRenderer::Render(RenderModifierPtr modifier, u32 flags) // Render one frame worth of models void BatchModelRendererInternals::RenderAllModels( - RenderModifierPtr modifier, u32 filterflags, - uint pass, uint streamflags) + RenderModifierPtr modifier, int filterflags, + int pass, int streamflags) { for(BMRModelDefTracker* mdeftracker = submissions; mdeftracker; mdeftracker = mdeftracker->m_Next) { vertexRenderer->PrepareModelDef(streamflags, mdeftracker->m_ModelDef.lock()); - for(uint idx = 0; idx < mdeftracker->m_Slots; ++idx) + for(size_t idx = 0; idx < mdeftracker->m_Slots; ++idx) { BMRModelData* bmrdata = mdeftracker->m_ModelSlots[idx]; diff --git a/source/renderer/ModelRenderer.h b/source/renderer/ModelRenderer.h index 0efd1bdd86..841e678fbf 100644 --- a/source/renderer/ModelRenderer.h +++ b/source/renderer/ModelRenderer.h @@ -153,7 +153,7 @@ public: * If flags is non-zero, only models that contain flags in their * CModel::GetFlags() are rendered. */ - virtual void Render(RenderModifierPtr modifier, u32 flags) = 0; + virtual void Render(RenderModifierPtr modifier, int flags) = 0; /** * CopyPositionAndNormals: Copy unanimated object-space vertices and @@ -257,7 +257,7 @@ public: virtual void PrepareModels(); virtual void EndFrame(); virtual bool HaveSubmissions(); - virtual void Render(RenderModifierPtr modifier, u32 flags); + virtual void Render(RenderModifierPtr modifier, int flags); private: BatchModelRendererInternals* m; diff --git a/source/renderer/ModelVertexRenderer.h b/source/renderer/ModelVertexRenderer.h index 306c0367dd..c0aea48338 100644 --- a/source/renderer/ModelVertexRenderer.h +++ b/source/renderer/ModelVertexRenderer.h @@ -67,7 +67,7 @@ public: * the frame. The value is the same as the value of the model's * CRenderData::m_UpdateFlags. */ - virtual void UpdateModelData(CModel* model, void* data, u32 updateflags) = 0; + virtual void UpdateModelData(CModel* model, void* data, int updateflags) = 0; /** @@ -107,7 +107,7 @@ public: * texture matrix that must be used to transform vertex positions into texture * coordinates */ - virtual void BeginPass(uint streamflags, const CMatrix3D* texturematrix) = 0; + virtual void BeginPass(int streamflags, const CMatrix3D* texturematrix) = 0; /** @@ -120,7 +120,7 @@ public: * This equals the streamflags parameter passed on the last call to * BeginPass. */ - virtual void EndPass(uint streamflags) = 0; + virtual void EndPass(int streamflags) = 0; /** @@ -137,7 +137,7 @@ public: * BeginPass. * @param def The model definition. */ - virtual void PrepareModelDef(uint streamflags, CModelDefPtr def) = 0; + virtual void PrepareModelDef(int streamflags, CModelDefPtr def) = 0; /** @@ -159,7 +159,7 @@ public: * that use the same CModelDef object and the same texture must * succeed. */ - virtual void RenderModel(uint streamflags, CModel* model, void* data) = 0; + virtual void RenderModel(int streamflags, CModel* model, void* data) = 0; }; diff --git a/source/renderer/PatchRData.cpp b/source/renderer/PatchRData.cpp index 55bf43061d..830e27a6f8 100644 --- a/source/renderer/PatchRData.cpp +++ b/source/renderer/PatchRData.cpp @@ -18,7 +18,7 @@ #include "graphics/Patch.h" #include "graphics/Terrain.h" -const int BlendOffsets[8][2] = { +const ssize_t BlendOffsets[8][2] = { { 0, -1 }, { -1, -1 }, { -1, 0 }, @@ -53,14 +53,14 @@ CPatchRData::~CPatchRData() } -static Handle GetTerrainTileTexture(CTerrain* terrain,int gx,int gz) +static Handle GetTerrainTileTexture(CTerrain* terrain,ssize_t gx,ssize_t gz) { CMiniPatch* mp=terrain->GetTile(gx,gz); return mp ? mp->Tex1 : 0; } const float uvFactor = 0.125f / sqrt(2.f); -static void CalculateUV(float uv[2], int x, int z) +static void CalculateUV(float uv[2], ssize_t x, ssize_t z) { // The UV axes are offset 45 degrees from XZ uv[0] = ( x-z)*uvFactor; @@ -87,9 +87,9 @@ void CPatchRData::BuildBlends() std::set splatTextures; // for each tile in patch .. - for (int j=0;jm_MiniPatches[j][i]; mp->GetTileIndex(gx,gz); @@ -115,15 +115,15 @@ void CPatchRData::BuildBlends() std::sort(neighbourTextures.begin(),neighbourTextures.end()); // for each of the neighbouring textures .. - uint count=(uint)neighbourTextures.size(); - for (uint k=0;km_Index < 65536); unsigned short base = (unsigned short)m_VBBlends->m_Index; @@ -256,10 +256,10 @@ void CPatchRData::BuildBlends() Handle tex=*iter; SSplat& splat=m_BlendSplats[splatCount]; - splat.m_IndexStart=(u32)m_BlendIndices.size(); + splat.m_IndexStart=m_BlendIndices.size(); splat.m_Texture=tex; - for (uint k=0;k<(uint)splats.size();k++) { + for (size_t k=0;k textures; Handle texgrid[PATCH_SIZE][PATCH_SIZE]; - for (int j=0;jm_MiniPatches[j][i].Tex1; texgrid[j][i]=h; if (std::find(textures.begin(),textures.end(),h)==textures.end()) { @@ -302,34 +302,34 @@ void CPatchRData::BuildIndices() // now build base splats from interior textures m_Splats.resize(textures.size()); // build indices for base splats - u32 base=(u32)m_VBBase->m_Index; - for (uint i=0;i<(uint)m_Splats.size();i++) { + size_t base=m_VBBase->m_Index; + for (size_t i=0;im_X; - u32 pz=m_Patch->m_Z; + ssize_t px=m_Patch->m_X; + ssize_t pz=m_Patch->m_Z; CTerrain* terrain=m_Patch->m_Parent; const CLightEnv& lightEnv = g_Renderer.GetLightEnv(); // build vertices - for (int j=0;jCalcPosition(ix,iz,vertices[v].m_Position); @@ -409,12 +409,12 @@ void CPatchRData::Update() // Update vertex colors, which are affected by LOS - u32 px=m_Patch->m_X; - u32 pz=m_Patch->m_Z; + ssize_t px=m_Patch->m_X; + ssize_t pz=m_Patch->m_Z; CTerrain* terrain=m_Patch->m_Parent; - int mapSize=terrain->GetVerticesPerSide(); - int vsize=PATCH_SIZE+1; + ssize_t mapSize=terrain->GetVerticesPerSide(); + ssize_t vsize=PATCH_SIZE+1; SColor4ub baseColour = terrain->GetBaseColour(); if (g_Game) @@ -422,20 +422,20 @@ void CPatchRData::Update() CLOSManager* losMgr = g_Game->GetWorld()->GetLOSManager(); // this is very similar to BuildVertices(), but just for color - for (int j=0;j= 0 && tz >= 0 && tx <= mapSize-2 && tz <= mapSize-2) { @@ -453,11 +453,11 @@ void CPatchRData::Update() } else { - for (int j = 0; j < vsize; ++j) + for (ssize_t j = 0; j < vsize; ++j) { - for (int i = 0; i < vsize; ++i) + for (ssize_t i = 0; i < vsize; ++i) { - int v = (j*vsize)+i; + ssize_t v = (j*vsize)+i; m_Vertices[v].m_LOSColor = baseColour; } } @@ -468,7 +468,7 @@ void CPatchRData::Update() m_VBBase->m_Owner->UpdateChunkVertices(m_VBBase,m_Vertices); // update blend colors by copying them from vertex colors - for(uint i=0; im_Owner->Bind(); // setup data pointers - u32 stride=sizeof(SBaseVertex); + GLsizei stride=sizeof(SBaseVertex); glVertexPointer(3,GL_FLOAT,stride,&base->m_Position[0]); glColorPointer(4,GL_UNSIGNED_BYTE,stride,losColor ? &base->m_LOSColor : &base->m_DiffuseColor); glTexCoordPointer(2,GL_FLOAT,stride,&base->m_UVs[0]); // render each splat - for (uint i=0;i<(uint)m_Splats.size();i++) { + for (size_t i=0;im_Owner->Bind(); // setup data pointers - u32 stride=sizeof(SBaseVertex); + GLsizei stride=sizeof(SBaseVertex); glVertexPointer(3, GL_FLOAT, stride, &base->m_Position); if (streamflags & STREAM_UV0) { glTexCoordPointer(2, GL_FLOAT, stride, &base->m_UVs); @@ -534,7 +534,7 @@ void CPatchRData::RenderStreams(u32 streamflags, bool losColor) // bump stats g_Renderer.m_Stats.m_DrawCalls++; - g_Renderer.m_Stats.m_TerrainTris+=(u32)m_Indices.size()/2; + g_Renderer.m_Stats.m_TerrainTris+=m_Indices.size()/2; } @@ -547,7 +547,7 @@ void CPatchRData::RenderBlends() u8* base=m_VBBlends->m_Owner->Bind(); // setup data pointers - u32 stride=sizeof(SBlendVertex); + GLsizei stride=sizeof(SBlendVertex); // ((GCC warns about offsetof: SBlendVertex contains a CVector3D which has // a constructor, and so is not a POD type, and so offsetof is theoretically // invalid - see http://gcc.gnu.org/ml/gcc/2003-11/msg00281.html - but it @@ -561,12 +561,12 @@ void CPatchRData::RenderBlends() pglClientActiveTextureARB(GL_TEXTURE1); glTexCoordPointer(2,GL_FLOAT,stride,base+offsetof(SBlendVertex,m_AlphaUVs[0])); - for (uint i=0;i<(uint)m_BlendSplats.size();i++) { + for (size_t i=0;i m_BlendVertexIndices; + std::vector m_BlendVertexIndices; // indices into blend vertices for the blend splats std::vector m_BlendIndices; diff --git a/source/renderer/PlayerRenderer.cpp b/source/renderer/PlayerRenderer.cpp index 2365b2675a..b5758d32c2 100644 --- a/source/renderer/PlayerRenderer.cpp +++ b/source/renderer/PlayerRenderer.cpp @@ -37,7 +37,7 @@ bool FastPlayerColorRender::IsAvailable() return (ogl_max_tex_units >= 3); } -u32 FastPlayerColorRender::BeginPass(uint pass) +int FastPlayerColorRender::BeginPass(int pass) { debug_assert(pass == 0); @@ -98,7 +98,7 @@ u32 FastPlayerColorRender::BeginPass(uint pass) } -bool FastPlayerColorRender::EndPass(uint UNUSED(pass)) +bool FastPlayerColorRender::EndPass(int UNUSED(pass)) { // Restore state pglActiveTextureARB(GL_TEXTURE1); @@ -110,14 +110,14 @@ bool FastPlayerColorRender::EndPass(uint UNUSED(pass)) return true; } -void FastPlayerColorRender::PrepareTexture(uint UNUSED(pass), CTexture* texture) +void FastPlayerColorRender::PrepareTexture(int UNUSED(pass), CTexture* texture) { g_Renderer.SetTexture(2, texture); g_Renderer.SetTexture(1, texture); g_Renderer.SetTexture(0, texture); } -void FastPlayerColorRender::PrepareModel(uint UNUSED(pass), CModel* model) +void FastPlayerColorRender::PrepareModel(int UNUSED(pass), CModel* model) { // Get the player color SMaterialColor colour = model->GetMaterial().GetPlayerColor(); @@ -139,7 +139,7 @@ SlowPlayerColorRender::~SlowPlayerColorRender() { } -u32 SlowPlayerColorRender::BeginPass(uint pass) +int SlowPlayerColorRender::BeginPass(int pass) { // We calculate: Result = (Color*Texture)*Texture.a + (Color*Texture*PlayerColor)*(1-Texture.a) // Modulation is done via texture environments, the final interpolation is done via blending @@ -205,7 +205,7 @@ u32 SlowPlayerColorRender::BeginPass(uint pass) } } -bool SlowPlayerColorRender::EndPass(uint pass) +bool SlowPlayerColorRender::EndPass(int pass) { if (pass == 0) return false; // need two passes @@ -221,7 +221,7 @@ bool SlowPlayerColorRender::EndPass(uint pass) return true; } -void SlowPlayerColorRender::PrepareTexture(uint pass, CTexture* texture) +void SlowPlayerColorRender::PrepareTexture(int pass, CTexture* texture) { if (pass == 1) g_Renderer.SetTexture(1, texture); @@ -229,7 +229,7 @@ void SlowPlayerColorRender::PrepareTexture(uint pass, CTexture* texture) } -void SlowPlayerColorRender::PrepareModel(uint pass, CModel* model) +void SlowPlayerColorRender::PrepareModel(int pass, CModel* model) { if (pass == 1) { @@ -254,7 +254,7 @@ LitPlayerColorRender::~LitPlayerColorRender() { } -u32 LitPlayerColorRender::BeginPass(uint pass) +int LitPlayerColorRender::BeginPass(int pass) { debug_assert(GetShadowMap() && GetShadowMap()->GetUseDepthTexture()); @@ -355,7 +355,7 @@ u32 LitPlayerColorRender::BeginPass(uint pass) } -bool LitPlayerColorRender::EndPass(uint pass) +bool LitPlayerColorRender::EndPass(int pass) { if (pass == 0) { @@ -375,18 +375,18 @@ bool LitPlayerColorRender::EndPass(uint pass) } } -const CMatrix3D* LitPlayerColorRender::GetTexGenMatrix(uint UNUSED(pass)) +const CMatrix3D* LitPlayerColorRender::GetTexGenMatrix(int UNUSED(pass)) { return &GetShadowMap()->GetTextureMatrix(); } -void LitPlayerColorRender::PrepareTexture(uint pass, CTexture* texture) +void LitPlayerColorRender::PrepareTexture(int pass, CTexture* texture) { if (pass == 0) g_Renderer.SetTexture(0, texture); } -void LitPlayerColorRender::PrepareModel(uint pass, CModel* model) +void LitPlayerColorRender::PrepareModel(int pass, CModel* model) { if (pass == 0) { diff --git a/source/renderer/PlayerRenderer.h b/source/renderer/PlayerRenderer.h index b2312c9b52..fe26419700 100644 --- a/source/renderer/PlayerRenderer.h +++ b/source/renderer/PlayerRenderer.h @@ -25,10 +25,10 @@ public: ~FastPlayerColorRender(); // Implementation - u32 BeginPass(uint pass); - bool EndPass(uint pass); - void PrepareTexture(uint pass, CTexture* texture); - void PrepareModel(uint pass, CModel* model); + int BeginPass(int pass); + bool EndPass(int pass); + void PrepareTexture(int pass, CTexture* texture); + void PrepareModel(int pass, CModel* model); /** * IsAvailable: Determines whether this RenderModifier can be used @@ -58,10 +58,10 @@ public: ~SlowPlayerColorRender(); // Implementation - u32 BeginPass(uint pass); - bool EndPass(uint pass); - void PrepareTexture(uint pass, CTexture* texture); - void PrepareModel(uint pass, CModel* model); + int BeginPass(int pass); + bool EndPass(int pass); + void PrepareTexture(int pass, CTexture* texture); + void PrepareModel(int pass, CModel* model); }; @@ -79,11 +79,11 @@ public: ~LitPlayerColorRender(); // Implementation - u32 BeginPass(uint pass); - bool EndPass(uint pass); - const CMatrix3D* GetTexGenMatrix(uint pass); - void PrepareTexture(uint pass, CTexture* texture); - void PrepareModel(uint pass, CModel* model); + int BeginPass(int pass); + bool EndPass(int pass); + const CMatrix3D* GetTexGenMatrix(int pass); + void PrepareTexture(int pass, CTexture* texture); + void PrepareModel(int pass, CModel* model); }; diff --git a/source/renderer/RenderModifiers.cpp b/source/renderer/RenderModifiers.cpp index 73246101f2..61237d0f4e 100644 --- a/source/renderer/RenderModifiers.cpp +++ b/source/renderer/RenderModifiers.cpp @@ -30,13 +30,13 @@ /////////////////////////////////////////////////////////////////////////////////////////////// // RenderModifier implementation -const CMatrix3D* RenderModifier::GetTexGenMatrix(uint UNUSED(pass)) +const CMatrix3D* RenderModifier::GetTexGenMatrix(int UNUSED(pass)) { debug_warn("GetTexGenMatrix not implemented by a derived RenderModifier"); return 0; } -void RenderModifier::PrepareModel(uint UNUSED(pass), CModel* UNUSED(model)) +void RenderModifier::PrepareModel(int UNUSED(pass), CModel* UNUSED(model)) { } @@ -77,7 +77,7 @@ PlainRenderModifier::~PlainRenderModifier() { } -u32 PlainRenderModifier::BeginPass(uint pass) +int PlainRenderModifier::BeginPass(int pass) { debug_assert(pass == 0); @@ -105,7 +105,7 @@ u32 PlainRenderModifier::BeginPass(uint pass) return STREAM_POS|STREAM_COLOR|STREAM_UV0; } -bool PlainRenderModifier::EndPass(uint UNUSED(pass)) +bool PlainRenderModifier::EndPass(int UNUSED(pass)) { // We didn't modify blend state or higher texenvs, so we don't have // to reset OpenGL state here. @@ -113,7 +113,7 @@ bool PlainRenderModifier::EndPass(uint UNUSED(pass)) return true; } -void PlainRenderModifier::PrepareTexture(uint UNUSED(pass), CTexture* texture) +void PlainRenderModifier::PrepareTexture(int UNUSED(pass), CTexture* texture) { g_Renderer.SetTexture(0, texture); } @@ -130,7 +130,7 @@ PlainLitRenderModifier::~PlainLitRenderModifier() { } -u32 PlainLitRenderModifier::BeginPass(uint pass) +int PlainLitRenderModifier::BeginPass(int pass) { debug_assert(pass == 0); debug_assert(GetShadowMap() && GetShadowMap()->GetUseDepthTexture()); @@ -181,12 +181,12 @@ u32 PlainLitRenderModifier::BeginPass(uint pass) return STREAM_POS|STREAM_COLOR|STREAM_UV0|STREAM_TEXGENTOUV1; } -const CMatrix3D* PlainLitRenderModifier::GetTexGenMatrix(uint UNUSED(pass)) +const CMatrix3D* PlainLitRenderModifier::GetTexGenMatrix(int UNUSED(pass)) { return &GetShadowMap()->GetTextureMatrix(); } -bool PlainLitRenderModifier::EndPass(uint UNUSED(pass)) +bool PlainLitRenderModifier::EndPass(int UNUSED(pass)) { g_Renderer.BindTexture(1, 0); g_Renderer.BindTexture(2, 0); @@ -196,7 +196,7 @@ bool PlainLitRenderModifier::EndPass(uint UNUSED(pass)) return true; } -void PlainLitRenderModifier::PrepareTexture(uint UNUSED(pass), CTexture* texture) +void PlainLitRenderModifier::PrepareTexture(int UNUSED(pass), CTexture* texture) { g_Renderer.SetTexture(0, texture); } @@ -215,7 +215,7 @@ WireframeRenderModifier::~WireframeRenderModifier() { } -u32 WireframeRenderModifier::BeginPass(uint pass) +int WireframeRenderModifier::BeginPass(int pass) { debug_assert(pass == 0); @@ -235,7 +235,7 @@ u32 WireframeRenderModifier::BeginPass(uint pass) } -bool WireframeRenderModifier::EndPass(uint UNUSED(pass)) +bool WireframeRenderModifier::EndPass(int UNUSED(pass)) { // .. restore the renderstates glDisable(GL_BLEND); @@ -248,12 +248,12 @@ bool WireframeRenderModifier::EndPass(uint UNUSED(pass)) } -void WireframeRenderModifier::PrepareTexture(uint UNUSED(pass), CTexture* UNUSED(texture)) +void WireframeRenderModifier::PrepareTexture(int UNUSED(pass), CTexture* UNUSED(texture)) { } -void WireframeRenderModifier::PrepareModel(uint UNUSED(pass), CModel* UNUSED(model)) +void WireframeRenderModifier::PrepareModel(int UNUSED(pass), CModel* UNUSED(model)) { } @@ -270,22 +270,22 @@ SolidColorRenderModifier::~SolidColorRenderModifier() { } -u32 SolidColorRenderModifier::BeginPass(uint UNUSED(pass)) +int SolidColorRenderModifier::BeginPass(int UNUSED(pass)) { g_Renderer.SetTexture(0,0); return STREAM_POS; } -bool SolidColorRenderModifier::EndPass(uint UNUSED(pass)) +bool SolidColorRenderModifier::EndPass(int UNUSED(pass)) { return true; } -void SolidColorRenderModifier::PrepareTexture(uint UNUSED(pass), CTexture* UNUSED(texture)) +void SolidColorRenderModifier::PrepareTexture(int UNUSED(pass), CTexture* UNUSED(texture)) { } -void SolidColorRenderModifier::PrepareModel(uint UNUSED(pass), CModel* UNUSED(model)) +void SolidColorRenderModifier::PrepareModel(int UNUSED(pass), CModel* UNUSED(model)) { } diff --git a/source/renderer/RenderModifiers.h b/source/renderer/RenderModifiers.h index eaf859cc77..6bc96b4aba 100644 --- a/source/renderer/RenderModifiers.h +++ b/source/renderer/RenderModifiers.h @@ -43,7 +43,7 @@ public: * @return The streamflags that indicate which vertex components * are required by the fragment stages (see STREAM_XYZ constants). */ - virtual u32 BeginPass(uint pass) = 0; + virtual int BeginPass(int pass) = 0; /** * GetTexGenMatrix: If BeginPass returns STREAM_TEXGENTOUVx, the caller must @@ -56,7 +56,7 @@ public: * * @return a pointer to the texture matrix for the given pass */ - virtual const CMatrix3D* GetTexGenMatrix(uint pass); + virtual const CMatrix3D* GetTexGenMatrix(int pass); /** * EndPass: Cleanup OpenGL state after the given pass. This function @@ -70,7 +70,7 @@ public: * is needed. If false is returned, BeginPass is then called with an * increased pass number. */ - virtual bool EndPass(uint pass) = 0; + virtual bool EndPass(int pass) = 0; /** * PrepareTexture: Called before rendering models that use the given @@ -81,7 +81,7 @@ public: * @param pass The current pass number (pass == 0 is the first pass) * @param texture The texture used by subsequent models */ - virtual void PrepareTexture(uint pass, CTexture* texture) = 0; + virtual void PrepareTexture(int pass, CTexture* texture) = 0; /** * PrepareModel: Called before rendering the given model. @@ -91,7 +91,7 @@ public: * @param pass The current pass number (pass == 0 is the first pass) * @param model The model that is about to be rendered. */ - virtual void PrepareModel(uint pass, CModel* model); + virtual void PrepareModel(int pass, CModel* model); }; @@ -157,9 +157,9 @@ public: ~PlainRenderModifier(); // Implementation - u32 BeginPass(uint pass); - bool EndPass(uint pass); - void PrepareTexture(uint pass, CTexture* texture); + int BeginPass(int pass); + bool EndPass(int pass); + void PrepareTexture(int pass, CTexture* texture); }; @@ -175,10 +175,10 @@ public: ~PlainLitRenderModifier(); // Implementation - u32 BeginPass(uint pass); - const CMatrix3D* GetTexGenMatrix(uint pass); - bool EndPass(uint pass); - void PrepareTexture(uint pass, CTexture* texture); + int BeginPass(int pass); + const CMatrix3D* GetTexGenMatrix(int pass); + bool EndPass(int pass); + void PrepareTexture(int pass, CTexture* texture); }; @@ -192,10 +192,10 @@ public: ~WireframeRenderModifier(); // Implementation - u32 BeginPass(uint pass); - bool EndPass(uint pass); - void PrepareTexture(uint pass, CTexture* texture); - void PrepareModel(uint pass, CModel* model); + int BeginPass(int pass); + bool EndPass(int pass); + void PrepareTexture(int pass, CTexture* texture); + void PrepareModel(int pass, CModel* model); }; @@ -212,10 +212,10 @@ public: ~SolidColorRenderModifier(); // Implementation - u32 BeginPass(uint pass); - bool EndPass(uint pass); - void PrepareTexture(uint pass, CTexture* texture); - void PrepareModel(uint pass, CModel* model); + int BeginPass(int pass); + bool EndPass(int pass); + void PrepareTexture(int pass, CTexture* texture); + void PrepareModel(int pass, CModel* model); }; #endif // INCLUDED_RENDERMODIFIERS diff --git a/source/renderer/Renderer.cpp b/source/renderer/Renderer.cpp index 8cb8428967..15688e7ddd 100644 --- a/source/renderer/Renderer.cpp +++ b/source/renderer/Renderer.cpp @@ -317,7 +317,7 @@ struct CRendererInternals : public boost::noncopyable glLoadMatrixf(&view._11); const SViewPort &vp = camera.GetViewPort(); - glViewport(vp.m_X,vp.m_Y,vp.m_Width,vp.m_Height); + glViewport((GLint)vp.m_X,(GLint)vp.m_Y,(GLsizei)vp.m_Width,(GLsizei)vp.m_Height); } }; @@ -357,7 +357,7 @@ CRenderer::CRenderer() m_ShadowZBias = 0.02f; m_ShadowMapSize = 0; - for (uint i=0;iGetHandle(); - uint flags = 0; // assume no alpha on failure + int flags = 0; // assume no alpha on failure (void)ogl_tex_get_format(h, &flags, 0); return (flags & TEX_ALPHA) != 0; } @@ -1542,11 +1542,11 @@ int CRenderer::LoadAlphaMaps() "blendushape.dds", "blendbad.dds" }; - uint base = 0; // texture width/height (see below) + size_t base = 0; // texture width/height (see below) // for convenience, we require all alpha maps to be of the same BPP // (avoids another ogl_tex_get_size call, and doesn't hurt) - uint bpp = 0; - for(uint i=0;i data = io_Allocate(total_w*total_h*3); // for each tile on row - for(uint i=0;i& props = model->GetProps(); - for (uint i=0;iGetWorld()->GetTerrain(); - int min_i, min_j, max_i, max_j; + ssize_t min_i, min_j, max_i, max_j; GetTileExtents(min_i, min_j, max_i, max_j); // Clamp the min to 0, but the max to -1 - so tile -1 can never be rendered, // but if unclamped_max<0 then no tiles at all will be rendered. And the same // for the upper limit. - min_i = clamp(min_i, 0, (int)m_Terrain->GetTilesPerSide()); - min_j = clamp(min_j, 0, (int)m_Terrain->GetTilesPerSide()); - max_i = clamp(max_i, -1, (int)m_Terrain->GetTilesPerSide()-1); - max_j = clamp(max_j, -1, (int)m_Terrain->GetTilesPerSide()-1); + min_i = clamp(min_i, ssize_t(0), m_Terrain->GetTilesPerSide()); + min_j = clamp(min_j, ssize_t(0), m_Terrain->GetTilesPerSide()); + max_i = clamp(max_i, ssize_t(-1), m_Terrain->GetTilesPerSide()-1); + max_j = clamp(max_j, ssize_t(-1), m_Terrain->GetTilesPerSide()-1); for (m_j = min_j; m_j <= max_j; ++m_j) for (m_i = min_i; m_i <= max_i; ++m_i) diff --git a/source/renderer/TerrainOverlay.h b/source/renderer/TerrainOverlay.h index 272aee9b56..3540498a9c 100644 --- a/source/renderer/TerrainOverlay.h +++ b/source/renderer/TerrainOverlay.h @@ -32,7 +32,7 @@ class CTerrain; /** * Base class for (relatively) simple drawing of - * data onto terrain tiles, intended for debugging purposes and for the Atlas + * data onto terrain tiles, ssize_tended for debugging purposes and for the Atlas * editor (hence not trying to be very efficient). *

    * To start drawing a terrain overlay, first create a subclass of TerrainOverlay. @@ -76,8 +76,8 @@ protected: * @param max_i_inclusive [output] largest i coordinate * @param max_j_inclusive [output] largest j coordinate */ - virtual void GetTileExtents(int& min_i_inclusive, int& min_j_inclusive, - int& max_i_inclusive, int& max_j_inclusive); + virtual void GetTileExtents(ssize_t& min_i_inclusive, ssize_t& min_j_inclusive, + ssize_t& max_i_inclusive, ssize_t& max_j_inclusive); /** * Override to perform processing of each tile. Typically calls @@ -86,7 +86,7 @@ protected: * @param i i coordinate of tile being processed * @param j j coordinate of tile being processed */ - virtual void ProcessTile(int i, int j) = 0; + virtual void ProcessTile(ssize_t i, ssize_t j) = 0; /** * Draw a filled quad on top of the current tile. @@ -134,7 +134,7 @@ private: // Temporary storage of tile coordinates, so ProcessTile doesn't need to // pass it to RenderTile/etc (and doesn't have a chance to get it wrong) - int m_i, m_j; + ssize_t m_i, m_j; CTerrain* m_Terrain; }; @@ -278,8 +278,8 @@ public: } virtual void GetTileExtents( - int& min_i_inclusive, int& min_j_inclusive, - int& max_i_inclusive, int& max_j_inclusive) + ssize_t& min_i_inclusive, ssize_t& min_j_inclusive, + ssize_t& max_i_inclusive, ssize_t& max_j_inclusive) { min_i_inclusive = 1; min_j_inclusive = 1; @@ -287,7 +287,7 @@ public: max_j_inclusive = 2; } - virtual void ProcessTile(int UNUSED(i), int UNUSED(j)) + virtual void ProcessTile(ssize_t UNUSED(i), ssize_t UNUSED(j)) { RenderConstrainedEdges(); @@ -320,7 +320,7 @@ public: { aPath =_aPath; - for(unsigned int k = 0 ; k< aPath.size();k++) + for(size_t k = 0 ; k< aPath.size();k++) { aPath[k] = WorldspaceToTilespace( aPath[k] ); } @@ -332,9 +332,9 @@ public: return CVector2D(floor(ws.x/CELL_SIZE), floor(ws.y/CELL_SIZE)); } - bool inPath(int i, int j) + bool inPath(ssize_t i, ssize_t j) { - for(unsigned int k = 0 ; kvisiblePatches.size(); ++i) + for(size_t i = 0; i < m->visiblePatches.size(); ++i) { CPatchRData* patchdata = (CPatchRData*)m->visiblePatches[i]->GetRenderData(); patchdata->RenderBase(true); // with LOS color @@ -197,7 +197,7 @@ void TerrainRenderer::RenderTerrain(ShadowMap* shadow) glDepthMask(0); // render blend passes for each patch - for(uint i = 0; i < m->visiblePatches.size(); ++i) + for(size_t i = 0; i < m->visiblePatches.size(); ++i) { CPatchRData* patchdata = (CPatchRData*)m->visiblePatches[i]->GetRenderData(); patchdata->RenderBlends(); @@ -328,7 +328,7 @@ void TerrainRenderer::RenderTerrain(ShadowMap* shadow) pglActiveTextureARB(GL_TEXTURE0); pglClientActiveTextureARB(GL_TEXTURE0); - for (uint i = 0; i < m->visiblePatches.size(); ++i) + for (size_t i = 0; i < m->visiblePatches.size(); ++i) { CPatchRData* patchdata = (CPatchRData*)m->visiblePatches[i]->GetRenderData(); patchdata->RenderStreams(STREAM_POS|STREAM_COLOR|STREAM_POSTOUV0, false); @@ -364,7 +364,7 @@ void TerrainRenderer::RenderPatches() debug_assert(m->phase == Phase_Render); glEnableClientState(GL_VERTEX_ARRAY); - for(uint i = 0; i < m->visiblePatches.size(); ++i) + for(size_t i = 0; i < m->visiblePatches.size(); ++i) { CPatchRData* patchdata = (CPatchRData*)m->visiblePatches[i]->GetRenderData(); patchdata->RenderStreams(STREAM_POS, true); @@ -378,7 +378,7 @@ void TerrainRenderer::RenderPatches() void TerrainRenderer::RenderOutlines() { glEnableClientState(GL_VERTEX_ARRAY); - for(uint i = 0; i < m->visiblePatches.size(); ++i) + for(size_t i = 0; i < m->visiblePatches.size(); ++i) { CPatchRData* patchdata = (CPatchRData*)m->visiblePatches[i]->GetRenderData(); patchdata->RenderOutline(); @@ -422,7 +422,7 @@ void TerrainRenderer::RenderWater() double time = WaterMgr->m_WaterTexTimer; double period = 1.6; - int curTex = (unsigned int)(time*60/period) % 60; + int curTex = (int)(time*60/period) % 60; if(fancy) { @@ -571,10 +571,10 @@ void TerrainRenderer::RenderWater() -100.0f, WaterMgr->m_WaterMaxAlpha); float losMod = 1.0f; - for(int k=0; k<4; k++) + for(size_t k=0; k<4; k++) { - int tx = ix - DX[k]; - int tz = iz - DZ[k]; + ssize_t tx = ix - DX[k]; + ssize_t tz = iz - DZ[k]; if(tx >= 0 && tz >= 0 && tx <= mapSize-2 && tz <= mapSize-2) { diff --git a/source/renderer/TransparencyRenderer.cpp b/source/renderer/TransparencyRenderer.cpp index 7450b7e069..74100132a6 100644 --- a/source/renderer/TransparencyRenderer.cpp +++ b/source/renderer/TransparencyRenderer.cpp @@ -163,7 +163,7 @@ float PSModel::BackToFrontIndexSort(const CMatrix3D& worldToCam) std::sort(IndexSorter.begin(),IndexSorter.begin()+numFaces,SortFacesByDist()); // now build index list - u32 idxidx = 0; + size_t idxidx = 0; for (size_t i = 0; i < numFaces; ++i) { const SModelFace& face = faces[IndexSorter[i].first]; m_Indices[idxidx++] = (u16)(face.m_Verts[0]); @@ -214,7 +214,7 @@ void* PolygonSortModelRenderer::CreateModelData(CModel* model) // Updated transforms -void PolygonSortModelRenderer::UpdateModelData(CModel* model, void* data, u32 updateflags) +void PolygonSortModelRenderer::UpdateModelData(CModel* model, void* data, int updateflags) { PSModel* psmdl = (PSModel*)data; @@ -265,7 +265,7 @@ void PolygonSortModelRenderer::DestroyModelData(CModel* UNUSED(model), void* dat // Prepare for one rendering pass -void PolygonSortModelRenderer::BeginPass(uint streamflags, const CMatrix3D* texturematrix) +void PolygonSortModelRenderer::BeginPass(int streamflags, const CMatrix3D* texturematrix) { debug_assert(streamflags == (streamflags & (STREAM_POS|STREAM_COLOR|STREAM_UV0|STREAM_TEXGENTOUV1))); @@ -291,7 +291,7 @@ void PolygonSortModelRenderer::BeginPass(uint streamflags, const CMatrix3D* text // Cleanup rendering -void PolygonSortModelRenderer::EndPass(uint streamflags) +void PolygonSortModelRenderer::EndPass(int streamflags) { if (streamflags & STREAM_UV0) glDisableClientState(GL_TEXTURE_COORD_ARRAY); if (streamflags & STREAM_COLOR) glDisableClientState(GL_COLOR_ARRAY); @@ -315,7 +315,7 @@ void PolygonSortModelRenderer::EndPass(uint streamflags) // Prepare for rendering models using this CModelDef -void PolygonSortModelRenderer::PrepareModelDef(uint streamflags, CModelDefPtr def) +void PolygonSortModelRenderer::PrepareModelDef(int streamflags, CModelDefPtr def) { if (streamflags & STREAM_UV0) { @@ -332,7 +332,7 @@ void PolygonSortModelRenderer::PrepareModelDef(uint streamflags, CModelDefPtr de // Render one model -void PolygonSortModelRenderer::RenderModel(uint streamflags, CModel* model, void* data) +void PolygonSortModelRenderer::RenderModel(int streamflags, CModel* model, void* data) { CModelDefPtr mdef = model->GetModelDef(); PSModel* psmdl = (PSModel*)data; @@ -510,16 +510,16 @@ bool SortModelRenderer::HaveSubmissions() // Render submitted models (filtered by flags) using the given modifier -void SortModelRenderer::Render(RenderModifierPtr modifier, u32 flags) +void SortModelRenderer::Render(RenderModifierPtr modifier, int flags) { - uint pass = 0; + int pass = 0; if (m->models.size() == 0) return; do { - u32 streamflags = modifier->BeginPass(pass); + int streamflags = modifier->BeginPass(pass); const CMatrix3D* texturematrix = 0; CModelDefPtr lastmdef; CTexture* lasttex = 0; @@ -579,7 +579,7 @@ TransparentRenderModifier::~TransparentRenderModifier() { } -u32 TransparentRenderModifier::BeginPass(uint pass) +int TransparentRenderModifier::BeginPass(int pass) { if (pass == 0) { @@ -635,7 +635,7 @@ u32 TransparentRenderModifier::BeginPass(uint pass) } } -bool TransparentRenderModifier::EndPass(uint pass) +bool TransparentRenderModifier::EndPass(int pass) { if (pass == 0) return false; // multi-pass @@ -647,12 +647,12 @@ bool TransparentRenderModifier::EndPass(uint pass) return true; } -void TransparentRenderModifier::PrepareTexture(uint UNUSED(pass), CTexture* texture) +void TransparentRenderModifier::PrepareTexture(int UNUSED(pass), CTexture* texture) { g_Renderer.SetTexture(0, texture); } -void TransparentRenderModifier::PrepareModel(uint UNUSED(pass), CModel* UNUSED(model)) +void TransparentRenderModifier::PrepareModel(int UNUSED(pass), CModel* UNUSED(model)) { // No per-model setup necessary } @@ -669,7 +669,7 @@ LitTransparentRenderModifier::~LitTransparentRenderModifier() { } -u32 LitTransparentRenderModifier::BeginPass(uint pass) +int LitTransparentRenderModifier::BeginPass(int pass) { debug_assert(GetShadowMap() && GetShadowMap()->GetUseDepthTexture()); @@ -761,7 +761,7 @@ u32 LitTransparentRenderModifier::BeginPass(uint pass) } } -bool LitTransparentRenderModifier::EndPass(uint pass) +bool LitTransparentRenderModifier::EndPass(int pass) { if (pass == 0) return false; // multi-pass @@ -779,17 +779,17 @@ bool LitTransparentRenderModifier::EndPass(uint pass) return true; } -const CMatrix3D* LitTransparentRenderModifier::GetTexGenMatrix(uint UNUSED(pass)) +const CMatrix3D* LitTransparentRenderModifier::GetTexGenMatrix(int UNUSED(pass)) { return &GetShadowMap()->GetTextureMatrix(); } -void LitTransparentRenderModifier::PrepareTexture(uint UNUSED(pass), CTexture* texture) +void LitTransparentRenderModifier::PrepareTexture(int UNUSED(pass), CTexture* texture) { g_Renderer.SetTexture(0, texture); } -void LitTransparentRenderModifier::PrepareModel(uint UNUSED(pass), CModel* UNUSED(model)) +void LitTransparentRenderModifier::PrepareModel(int UNUSED(pass), CModel* UNUSED(model)) { // No per-model setup necessary } @@ -806,7 +806,7 @@ TransparentShadowRenderModifier::~TransparentShadowRenderModifier() { } -u32 TransparentShadowRenderModifier::BeginPass(uint pass) +int TransparentShadowRenderModifier::BeginPass(int pass) { debug_assert(pass == 0); @@ -829,7 +829,7 @@ u32 TransparentShadowRenderModifier::BeginPass(uint pass) return STREAM_POS|STREAM_UV0; } -bool TransparentShadowRenderModifier::EndPass(uint UNUSED(pass)) +bool TransparentShadowRenderModifier::EndPass(int UNUSED(pass)) { glDepthMask(1); glDisable(GL_BLEND); @@ -837,12 +837,12 @@ bool TransparentShadowRenderModifier::EndPass(uint UNUSED(pass)) return true; } -void TransparentShadowRenderModifier::PrepareTexture(uint UNUSED(pass), CTexture* texture) +void TransparentShadowRenderModifier::PrepareTexture(int UNUSED(pass), CTexture* texture) { g_Renderer.SetTexture(0, texture); } -void TransparentShadowRenderModifier::PrepareModel(uint UNUSED(pass), CModel* UNUSED(model)) +void TransparentShadowRenderModifier::PrepareModel(int UNUSED(pass), CModel* UNUSED(model)) { // No per-model setup necessary } @@ -859,7 +859,7 @@ TransparentDepthShadowModifier::~TransparentDepthShadowModifier() { } -u32 TransparentDepthShadowModifier::BeginPass(uint pass) +int TransparentDepthShadowModifier::BeginPass(int pass) { debug_assert(pass == 0); @@ -880,19 +880,19 @@ u32 TransparentDepthShadowModifier::BeginPass(uint pass) return STREAM_POS|STREAM_UV0; } -bool TransparentDepthShadowModifier::EndPass(uint UNUSED(pass)) +bool TransparentDepthShadowModifier::EndPass(int UNUSED(pass)) { glDisable(GL_ALPHA_TEST); return true; } -void TransparentDepthShadowModifier::PrepareTexture(uint UNUSED(pass), CTexture* texture) +void TransparentDepthShadowModifier::PrepareTexture(int UNUSED(pass), CTexture* texture) { g_Renderer.SetTexture(0, texture); } -void TransparentDepthShadowModifier::PrepareModel(uint UNUSED(pass), CModel* UNUSED(model)) +void TransparentDepthShadowModifier::PrepareModel(int UNUSED(pass), CModel* UNUSED(model)) { // No per-model setup necessary } diff --git a/source/renderer/TransparencyRenderer.h b/source/renderer/TransparencyRenderer.h index 686e9bdced..e081268861 100644 --- a/source/renderer/TransparencyRenderer.h +++ b/source/renderer/TransparencyRenderer.h @@ -34,13 +34,13 @@ public: // Implementations void* CreateModelData(CModel* model); - void UpdateModelData(CModel* model, void* data, u32 updateflags); + void UpdateModelData(CModel* model, void* data, int updateflags); void DestroyModelData(CModel* model, void* data); - void BeginPass(uint streamflags, const CMatrix3D* texturematrix); - void EndPass(uint streamflags); - void PrepareModelDef(uint streamflags, CModelDefPtr def); - void RenderModel(uint streamflags, CModel* model, void* data); + void BeginPass(int streamflags, const CMatrix3D* texturematrix); + void EndPass(int streamflags); + void PrepareModelDef(int streamflags, CModelDefPtr def); + void RenderModel(int streamflags, CModel* model, void* data); private: PolygonSortModelRendererInternals* m; @@ -72,7 +72,7 @@ public: void PrepareModels(); void EndFrame(); bool HaveSubmissions(); - void Render(RenderModifierPtr modifier, u32 flags); + void Render(RenderModifierPtr modifier, int flags); private: SortModelRendererInternals* m; @@ -90,10 +90,10 @@ public: ~TransparentRenderModifier(); // Implementation - u32 BeginPass(uint pass); - bool EndPass(uint pass); - void PrepareTexture(uint pass, CTexture* texture); - void PrepareModel(uint pass, CModel* model); + int BeginPass(int pass); + bool EndPass(int pass); + void PrepareTexture(int pass, CTexture* texture); + void PrepareModel(int pass, CModel* model); }; @@ -112,11 +112,11 @@ public: ~LitTransparentRenderModifier(); // Implementation - u32 BeginPass(uint pass); - bool EndPass(uint pass); - const CMatrix3D* GetTexGenMatrix(uint pass); - void PrepareTexture(uint pass, CTexture* texture); - void PrepareModel(uint pass, CModel* model); + int BeginPass(int pass); + bool EndPass(int pass); + const CMatrix3D* GetTexGenMatrix(int pass); + void PrepareTexture(int pass, CTexture* texture); + void PrepareModel(int pass, CModel* model); }; @@ -132,10 +132,10 @@ public: ~TransparentShadowRenderModifier(); // Implementation - u32 BeginPass(uint pass); - bool EndPass(uint pass); - void PrepareTexture(uint pass, CTexture* texture); - void PrepareModel(uint pass, CModel* model); + int BeginPass(int pass); + bool EndPass(int pass); + void PrepareTexture(int pass, CTexture* texture); + void PrepareModel(int pass, CModel* model); }; /** @@ -150,10 +150,10 @@ public: ~TransparentDepthShadowModifier(); // Implementation - u32 BeginPass(uint pass); - bool EndPass(uint pass); - void PrepareTexture(uint pass, CTexture* texture); - void PrepareModel(uint pass, CModel* model); + int BeginPass(int pass); + bool EndPass(int pass); + void PrepareTexture(int pass, CTexture* texture); + void PrepareModel(int pass, CModel* model); }; #endif diff --git a/source/renderer/VertexBuffer.cpp b/source/renderer/VertexBuffer.cpp index 1ef909ac57..beaa30d81a 100644 --- a/source/renderer/VertexBuffer.cpp +++ b/source/renderer/VertexBuffer.cpp @@ -157,7 +157,7 @@ void CVertexBuffer::Release(VBChunk* chunk) // ClearBatchIndices: clear lists of all batches void CVertexBuffer::ClearBatchIndices() { - for (uint i=0;im_IndexData.clear(); m_FreeBatches.push_back(m_Batches[i]); } diff --git a/source/renderer/WaterManager.cpp b/source/renderer/WaterManager.cpp index e89c614e29..bfc3d4c1a3 100644 --- a/source/renderer/WaterManager.cpp +++ b/source/renderer/WaterManager.cpp @@ -8,6 +8,7 @@ #include "precompiled.h" +#include "lib/bits.h" #include "lib/timer.h" #include "lib/tex/tex.h" #include "lib/res/graphics/ogl_tex.h" @@ -59,10 +60,10 @@ WaterManager::WaterManager() m_Murkiness = 0.45f; m_RepeatPeriod = 16.0f; - for (uint i = 0; i < ARRAY_SIZE(m_WaterTexture); i++) + for (size_t i = 0; i < ARRAY_SIZE(m_WaterTexture); i++) m_WaterTexture[i] = 0; - for (uint i = 0; i < ARRAY_SIZE(m_NormalMap); i++) + for (size_t i = 0; i < ARRAY_SIZE(m_NormalMap); i++) m_NormalMap[i] = 0; cur_loading_water_tex = 0; @@ -80,8 +81,8 @@ WaterManager::~WaterManager() // Progressive load of water textures int WaterManager::LoadWaterTextures() { - const uint num_textures = ARRAY_SIZE(m_WaterTexture); - const uint num_normal_maps = ARRAY_SIZE(m_NormalMap); + const size_t num_textures = ARRAY_SIZE(m_WaterTexture); + const size_t num_normal_maps = ARRAY_SIZE(m_NormalMap); // TODO: add a member variable and setter for this. (can't make this // a parameter because this function is called via delay-load code) @@ -131,7 +132,7 @@ int WaterManager::LoadWaterTextures() // the reflection/reflaction images will fit within the window // (alternative: use FBO's, which can have arbitrary size - but do we need // the reflection/refraction textures to be that large?) - int size = RoundUpToPowerOf2(g_Renderer.GetHeight()); + int size = round_up_to_pow2(g_Renderer.GetHeight()); if(size > g_Renderer.GetHeight()) size /= 2; m_ReflectionTextureSize = size; m_RefractionTextureSize = size; @@ -140,7 +141,7 @@ int WaterManager::LoadWaterTextures() glGenTextures(1, &m_ReflectionTexture); glBindTexture(GL_TEXTURE_2D, m_ReflectionTexture); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, - m_ReflectionTextureSize, m_ReflectionTextureSize, + (GLsizei)m_ReflectionTextureSize, (GLsizei)m_ReflectionTextureSize, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); @@ -151,7 +152,7 @@ int WaterManager::LoadWaterTextures() glGenTextures(1, &m_RefractionTexture); glBindTexture(GL_TEXTURE_2D, m_RefractionTexture); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, - m_RefractionTextureSize, m_RefractionTextureSize, + (GLsizei)m_RefractionTextureSize, (GLsizei)m_RefractionTextureSize, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); @@ -169,14 +170,14 @@ int WaterManager::LoadWaterTextures() // Unload water textures void WaterManager::UnloadWaterTextures() { - for(uint i = 0; i < ARRAY_SIZE(m_WaterTexture); i++) + for(size_t i = 0; i < ARRAY_SIZE(m_WaterTexture); i++) { ogl_tex_free(m_WaterTexture[i]); m_WaterTexture[i] = 0; } - for(uint i = 0; i < ARRAY_SIZE(m_NormalMap); i++) + for(size_t i = 0; i < ARRAY_SIZE(m_NormalMap); i++) { ogl_tex_free(m_NormalMap[i]); m_NormalMap[i] = 0; diff --git a/source/renderer/WaterManager.h b/source/renderer/WaterManager.h index dabb86a676..0702e6afcf 100644 --- a/source/renderer/WaterManager.h +++ b/source/renderer/WaterManager.h @@ -45,8 +45,8 @@ public: // Reflection and refraction textures for fancy water GLuint m_ReflectionTexture; GLuint m_RefractionTexture; - uint m_ReflectionTextureSize; - uint m_RefractionTextureSize; + size_t m_ReflectionTextureSize; + size_t m_RefractionTextureSize; // Model-view-projection matrices for reflected & refracted cameras // (used to let the vertex shader do projective texturing) @@ -84,8 +84,8 @@ public: private: /// State of progressive loading (in # of loaded textures) - uint cur_loading_water_tex; - uint cur_loading_normal_map; + size_t cur_loading_water_tex; + size_t cur_loading_normal_map; }; diff --git a/source/scripting/DOMEvent.cpp b/source/scripting/DOMEvent.cpp index 9b819a69c1..cd4aa8850f 100644 --- a/source/scripting/DOMEvent.cpp +++ b/source/scripting/DOMEvent.cpp @@ -71,7 +71,7 @@ bool IEventTarget::DispatchEvent( CScriptEvent* evt ) return( !evt->m_Cancelled ); } -bool IEventTarget::AddHandler( int TypeCode, DOMEventHandler handler ) +bool IEventTarget::AddHandler( size_t TypeCode, DOMEventHandler handler ) { HandlerList::iterator it; for( it = m_Handlers_id[TypeCode].begin(); it != m_Handlers_id[TypeCode].end(); it++ ) @@ -90,7 +90,7 @@ bool IEventTarget::AddHandler( const CStrW& TypeString, DOMEventHandler handler return( true ); } -bool IEventTarget::RemoveHandler( int TypeCode, DOMEventHandler handler ) +bool IEventTarget::RemoveHandler( size_t TypeCode, DOMEventHandler handler ) { HandlerList::iterator it; for( it = m_Handlers_id[TypeCode].begin(); it != m_Handlers_id[TypeCode].end(); it++ ) @@ -153,7 +153,7 @@ bool IEventTarget::RemoveHandlerJS( JSContext* UNUSED(cx), uintN argc, jsval* ar return( true ); } -CScriptEvent::CScriptEvent( const CStrW& Type, unsigned int TypeCode, bool Cancelable, bool Blockable ) +CScriptEvent::CScriptEvent( const CStrW& Type, size_t TypeCode, bool Cancelable, bool Blockable ) { m_Type = Type; m_TypeCode = TypeCode; m_Cancelable = Cancelable; m_Cancelled = false; diff --git a/source/scripting/DOMEvent.h b/source/scripting/DOMEvent.h index 9e1e57ecfb..f360da5ad2 100644 --- a/source/scripting/DOMEvent.h +++ b/source/scripting/DOMEvent.h @@ -54,11 +54,11 @@ public: // Register a handler for the given event type. // Returns false if the handler was already present - bool AddHandler( int TypeCode, DOMEventHandler handler ); + bool AddHandler( size_t TypeCode, DOMEventHandler handler ); bool AddHandler( const CStrW& TypeString, DOMEventHandler handler ); // Remove a previously registered handler for the specified event. // Returns false if the handler was not present - bool RemoveHandler( int TypeCode, DOMEventHandler handler ); + bool RemoveHandler( size_t TypeCode, DOMEventHandler handler ); bool RemoveHandler( const CStrW& TypeString, DOMEventHandler handler ); // called by ScriptGlue.cpp for add|RemoveGlobalHandler @@ -105,13 +105,13 @@ public: bool m_Blockable; // Timestamp (milliseconds since epoch (start of game?)) - i32 m_Timestamp; + long m_Timestamp; // Event type string CStrW m_Type; // Type code (to speed lookups) - unsigned int m_TypeCode; + size_t m_TypeCode; // Has been cancelled? bool m_Cancelled; @@ -126,7 +126,7 @@ public: void StopPropagation( JSContext* cx, uintN argc, jsval* argv ); public: - CScriptEvent( const CStrW& Type, unsigned int TypeCode = (unsigned int)-1, bool Cancelable = true, bool Blockable = true ); + CScriptEvent( const CStrW& Type, size_t TypeCode = ~0, bool Cancelable = true, bool Blockable = true ); static void ScriptingInit(); }; diff --git a/source/scripting/GameEvents.h b/source/scripting/GameEvents.h index 0ba368222b..fb5c4d45c5 100644 --- a/source/scripting/GameEvents.h +++ b/source/scripting/GameEvents.h @@ -38,10 +38,10 @@ class CGameEvents : public IEventTarget, public Singleton int m_SecondaryOrder; int m_SecondaryAction; CEntity *m_Entity; - uint m_X, m_Y; + int m_X, m_Y; public: CEventWorldClick(int button, int clicks, int order, int action, - int secOrder, int secAction, CEntity *ent, uint x, uint y): + int secOrder, int secAction, CEntity *ent, int x, int y): CScriptEvent(L"worldClick", EVENT_WORLD_CLICK, false), m_Button(button), m_Clicks(clicks), @@ -76,7 +76,7 @@ public: } void FireWorldClick(int button, int clicks, int order, int action, - int secOrder, int secAction, CEntity *ent, uint x, uint y) + int secOrder, int secAction, CEntity *ent, int x, int y) { CEventWorldClick evt(button, clicks, order, action, secOrder, secAction, ent, x, y); DispatchEvent(&evt); diff --git a/source/scripting/JSConversions.cpp b/source/scripting/JSConversions.cpp index 1602f5a595..0f434813c8 100644 --- a/source/scripting/JSConversions.cpp +++ b/source/scripting/JSConversions.cpp @@ -101,41 +101,82 @@ template<> jsval ToJSVal( int& Native ) return( INT_TO_JSVAL( Native ) ); } - - - - - - template<> bool ToPrimitive( JSContext* cx, jsval v, int& Storage ) { JSBool ok = JS_ValueToInt32(cx, v, (int32*)&Storage); return ok == JS_TRUE; } -// uint +// unsigned -template<> jsval ToJSVal( const uint& Native ) +template<> jsval ToJSVal( const unsigned& Native ) { return( INT_TO_JSVAL( Native ) ); } -template<> jsval ToJSVal( uint& Native ) +template<> jsval ToJSVal( unsigned& Native ) { return( INT_TO_JSVAL( Native ) ); } -template<> bool ToPrimitive( JSContext* cx, jsval v, uint& Storage ) +template<> bool ToPrimitive( JSContext* cx, jsval v, unsigned& Storage ) { int temp; if(!ToPrimitive(cx, v, temp)) return false; if(temp < 0) return false; - Storage = temp; + Storage = (unsigned)temp; return true; } +// ssize_t + +template<> jsval ToJSVal( const ssize_t& Native ) +{ + return( INT_TO_JSVAL( (int)Native ) ); +} + +template<> jsval ToJSVal( ssize_t& Native ) +{ + return( INT_TO_JSVAL( (int)Native ) ); +} + +template<> bool ToPrimitive( JSContext* cx, jsval v, ssize_t& Storage ) +{ + int32 tmp; + JSBool ok = JS_ValueToInt32(cx, v, &tmp); + Storage = (ssize_t)tmp; + return ok == JS_TRUE; +} + +#if ARCH_AMD64 + +// size_t (= unsigned int on IA32) + +template<> jsval ToJSVal( const size_t& Native ) +{ + return( INT_TO_JSVAL( (int)Native ) ); +} + +template<> jsval ToJSVal( size_t& Native ) +{ + return( INT_TO_JSVAL( (int)Native ) ); +} + +template<> bool ToPrimitive( JSContext* cx, jsval v, size_t& Storage ) +{ + int temp; + if(!ToPrimitive(cx, v, temp)) + return false; + if(temp < 0) + return false; + Storage = (size_t)temp; + return true; +} + +#endif + // double template<> jsval ToJSVal( const double& Native ) diff --git a/source/scripting/JSConversions.h b/source/scripting/JSConversions.h index f14abc74c2..0042c276f3 100644 --- a/source/scripting/JSConversions.h +++ b/source/scripting/JSConversions.h @@ -119,10 +119,20 @@ template<> bool ToPrimitive( JSContext* cx, jsval v, int& Storage ); template<> jsval ToJSVal( const int& Native ); template<> jsval ToJSVal( int& Native ); -// uint -template<> bool ToPrimitive( JSContext* cx, jsval v, uint& Storage ); -template<> jsval ToJSVal( const uint& Native ); -template<> jsval ToJSVal( uint& Native ); +// unsigned +template<> bool ToPrimitive( JSContext* cx, jsval v, unsigned& Storage ); +template<> jsval ToJSVal( const unsigned& Native ); +template<> jsval ToJSVal( unsigned& Native ); + +// ssize_t +template<> bool ToPrimitive( JSContext* cx, jsval v, ssize_t& Storage ); +template<> jsval ToJSVal( const ssize_t& Native ); +template<> jsval ToJSVal( ssize_t& Native ); + +// size_t +template<> bool ToPrimitive( JSContext* cx, jsval v, size_t& Storage ); +template<> jsval ToJSVal( const size_t& Native ); +template<> jsval ToJSVal( size_t& Native ); // double template<> bool ToPrimitive( JSContext* cx, jsval v, double& Storage ); diff --git a/source/scripting/JSSerialization.h b/source/scripting/JSSerialization.h index 9910592603..c05c33cc19 100644 --- a/source/scripting/JSSerialization.h +++ b/source/scripting/JSSerialization.h @@ -44,7 +44,7 @@ public: { return( ToPrimitive( m_data ) ); } - uint GetSerializedLength() const + size_t GetSerializedLength() const { switch( m_tag ) { diff --git a/source/scripting/ScriptCustomTypes.cpp b/source/scripting/ScriptCustomTypes.cpp index 9ab9e970e5..8d9328792d 100644 --- a/source/scripting/ScriptCustomTypes.cpp +++ b/source/scripting/ScriptCustomTypes.cpp @@ -62,7 +62,7 @@ CStr SColour::ToString( JSContext* UNUSED(cx), uintN UNUSED(argc), jsval* UNUSED } -JSBool SColour::Construct( JSContext* UNUSED(cx), JSObject* UNUSED(obj), uint argc, jsval* argv, jsval* rval ) +JSBool SColour::Construct( JSContext* UNUSED(cx), JSObject* UNUSED(obj), uintN argc, jsval* argv, jsval* rval ) { debug_assert( argc >= 3 ); float alpha = 1.0; diff --git a/source/scripting/ScriptCustomTypes.h b/source/scripting/ScriptCustomTypes.h index 796821b334..b5455977f5 100644 --- a/source/scripting/ScriptCustomTypes.h +++ b/source/scripting/ScriptCustomTypes.h @@ -28,7 +28,7 @@ public: CStr ToString( JSContext* cx, uintN argc, jsval* argv ); static void ScriptingInit(); - static JSBool Construct( JSContext* cx, JSObject* obj, uint argc, jsval* argv, jsval* rval ); + static JSBool Construct( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval ); }; #endif diff --git a/source/scripting/ScriptGlue.cpp b/source/scripting/ScriptGlue.cpp index 570af0ee9c..cea20492c6 100644 --- a/source/scripting/ScriptGlue.cpp +++ b/source/scripting/ScriptGlue.cpp @@ -64,7 +64,7 @@ extern bool g_TerrainModified; // avoid the need for forward declarations for every function. // all normal function wrappers have the following signature: -// JSBool func(JSContext* cx, JSObject* globalObject, uint argc, jsval* argv, jsval* rval); +// JSBool func(JSContext* cx, JSObject* globalObject, uintN argc, jsval* argv, jsval* rval); // all property accessors have the following signature: // JSBool accessor(JSContext* cx, JSObject* globalObject, jsval id, jsval* vp); @@ -79,7 +79,7 @@ extern bool g_TerrainModified; // notes: // - Each argument is converted to a string and then written to the log. // - Output is in NORMAL style (see LOG). -JSBool WriteLog(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) +JSBool WriteLog(JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval) { JSU_REQUIRE_PARAMS(1); @@ -114,7 +114,7 @@ JSBool WriteLog(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) // Retrieve the entity currently occupying the specified handle. // params: handle [int] // returns: entity -JSBool GetEntityByUnitID( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval ) +JSBool GetEntityByUnitID( JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS(1); *rval = JSVAL_NULL; @@ -145,7 +145,7 @@ JSBool GetEntityByUnitID( JSContext* cx, JSObject*, uint argc, jsval* argv, jsva // Look up an EntityTemplate by name. // params: template name [wstring] // returns: entity template object -JSBool GetEntityTemplate( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval ) +JSBool GetEntityTemplate( JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAM_RANGE(1, 2); *rval = JSVAL_NULL; @@ -178,13 +178,13 @@ JSBool GetEntityTemplate( JSContext* cx, JSObject*, uint argc, jsval* argv, jsva return( JS_TRUE ); } -JSBool GetPlayerUnitCount( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval ) +JSBool GetPlayerUnitCount( JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS(2); - int unitCount, playerNum = ToPrimitive( argv[0] ); - CStrW unitName = ToPrimitive( argv[1] ); + const size_t playerNum = ToPrimitive( argv[0] ); + const CStrW unitName = ToPrimitive( argv[1] ); - unitCount = g_EntityManager.GetPlayerUnitCount((size_t)playerNum, unitName); + const int unitCount = g_EntityManager.GetPlayerUnitCount(playerNum, unitName); *rval = ToJSVal( unitCount ); return JS_TRUE; } @@ -225,7 +225,7 @@ void CreateFormationMessage( std::vector& msgList, CNetMessage* ms // params: either an entity- or entity collection object, message ID [int], // any further params needed by CNetMessage::CommandFromJSArgs // returns: command in serialized form [string] -JSBool IssueCommand( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval ) +JSBool IssueCommand( JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval ) { // at least one for target object, one for isQueued, and then 1 or more for the CommandFromJSArgs JSU_REQUIRE_MIN_PARAMS(3); @@ -240,7 +240,8 @@ JSBool IssueCommand( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rv else entities = *EntityCollection::RetrieveSet(cx, JSVAL_TO_OBJECT(argv[0])); - std::map entityStore; + typedef std::map EntityStore; + EntityStore entityStore; bool isQueued = ToPrimitive(argv[1]); @@ -279,7 +280,7 @@ JSBool IssueCommand( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rv } messages.push_back(msg); - for ( std::map::iterator it=entityStore.begin(); it!=entityStore.end(); it++) + for ( EntityStore::iterator it=entityStore.begin(); it!=entityStore.end(); it++) CreateFormationMessage(messages, msg, it->second); for ( std::vector::iterator it=messages.begin(); it != messages.end(); it++ ) @@ -294,7 +295,7 @@ JSBool IssueCommand( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rv // Get the state of a given hotkey (from the hotkeys file) -JSBool isOrderQueued( JSContext* cx, JSObject* UNUSED(obj), uint argc, jsval* argv, jsval* rval ) +JSBool isOrderQueued( JSContext* cx, JSObject* UNUSED(obj), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_NO_PARAMS(); @@ -307,7 +308,7 @@ JSBool isOrderQueued( JSContext* cx, JSObject* UNUSED(obj), uint argc, jsval* ar // formations //----------------------------------------------------------------------------- -JSBool CreateEntityFormation( JSContext* cx, JSObject* UNUSED(obj), uint argc, jsval* argv, jsval* rval ) +JSBool CreateEntityFormation( JSContext* cx, JSObject* UNUSED(obj), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS(2); @@ -319,7 +320,7 @@ JSBool CreateEntityFormation( JSContext* cx, JSObject* UNUSED(obj), uint argc, j } -JSBool RemoveFromFormation( JSContext* cx, JSObject* UNUSED(obj), uint argc, jsval* argv, jsval* rval ) +JSBool RemoveFromFormation( JSContext* cx, JSObject* UNUSED(obj), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS(1); @@ -333,7 +334,7 @@ JSBool RemoveFromFormation( JSContext* cx, JSObject* UNUSED(obj), uint argc, jsv return JS_TRUE; } -JSBool LockEntityFormation( JSContext* cx, JSObject* UNUSED(obj), uint argc, jsval* argv, jsval* rval ) +JSBool LockEntityFormation( JSContext* cx, JSObject* UNUSED(obj), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS(1); @@ -343,7 +344,7 @@ JSBool LockEntityFormation( JSContext* cx, JSObject* UNUSED(obj), uint argc, jsv return JS_TRUE; } -JSBool IsFormationLocked( JSContext* cx, JSObject* UNUSED(obj), uint argc, jsval* argv, jsval* rval ) +JSBool IsFormationLocked( JSContext* cx, JSObject* UNUSED(obj), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS(1); @@ -357,7 +358,7 @@ JSBool IsFormationLocked( JSContext* cx, JSObject* UNUSED(obj), uint argc, jsval // Techs //----------------------------------------------------------------------------- -JSBool GetTechnology( JSContext* cx, JSObject* UNUSED(obj), uint argc, jsval* argv, jsval* rval ) +JSBool GetTechnology( JSContext* cx, JSObject* UNUSED(obj), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS(2); @@ -393,7 +394,7 @@ JSBool GetTechnology( JSContext* cx, JSObject* UNUSED(obj), uint argc, jsval* ar // Register a global handler for the specified DOM event. // params: event type name [wstring], handler [fragment or function] // returns: whether it was actually newly registered [bool] -JSBool AddGlobalHandler( JSContext* cx, JSObject* UNUSED(obj), uint argc, jsval* argv, jsval* rval ) +JSBool AddGlobalHandler( JSContext* cx, JSObject* UNUSED(obj), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS(2); @@ -405,7 +406,7 @@ JSBool AddGlobalHandler( JSContext* cx, JSObject* UNUSED(obj), uint argc, jsval* // Remove a previously registered global handler for the specified DOM event. // params: event type name [wstring], handler [fragment or function] // returns: whether it was successfully removed [bool] -JSBool RemoveGlobalHandler( JSContext* cx, JSObject* UNUSED(obj), uint argc, jsval* argv, jsval* rval ) +JSBool RemoveGlobalHandler( JSContext* cx, JSObject* UNUSED(obj), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS(2); @@ -434,11 +435,11 @@ JSBool RemoveGlobalHandler( JSContext* cx, JSObject* UNUSED(obj), uint argc, jsv // The called function or script executes in the same scope as the // code that called SetTimeout (amongst other things, the // 'this' reference is usually maintained) -JSBool SetTimeout( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval ) +JSBool SetTimeout( JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAM_RANGE(2, 3); - size_t delay; + int delay; try { delay = ToPrimitive( argv[1] ); @@ -492,11 +493,11 @@ JSBool SetTimeout( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval // returns: // notes: // - SetTimeout's notes apply here as well. -JSBool SetInterval( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval ) +JSBool SetInterval( JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAM_RANGE(2, 3); - size_t first, interval; + int first, interval; try { first = ToPrimitive( argv[1] ); @@ -546,7 +547,7 @@ JSBool SetInterval( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rva // notes: // - Execution continues until the end of the triggered function or // script fragment, but is not triggered again. -JSBool CancelInterval( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval ) +JSBool CancelInterval( JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_NO_PARAMS(); @@ -561,7 +562,7 @@ JSBool CancelInterval( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* // notes: // - Execution continues until the end of the triggered function or // script fragment, but is not triggered again. -JSBool CancelTimer( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval ) +JSBool CancelTimer( JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS(1); @@ -581,7 +582,7 @@ JSBool CancelTimer( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rva //Set the simulation rate scalar-time becomes time * SimRate. //Params: rate [float] : sets SimRate -JSBool SetSimRate(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) +JSBool SetSimRate(JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval) { JSU_REQUIRE_PARAMS(1); @@ -590,7 +591,7 @@ JSBool SetSimRate(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) } //Generate a random float in [0, 1) using the simulation's random generator -JSBool SimRand(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) +JSBool SimRand(JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval) { JSU_REQUIRE_NO_PARAMS(); @@ -599,7 +600,7 @@ JSBool SimRand(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) } //Generate a random float int between 0 and the given number - 1 using the simulation's RNG -JSBool SimRandInt(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) +JSBool SimRandInt(JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval) { JSU_REQUIRE_PARAMS(1); JSU_ASSERT(JSVAL_IS_INT(argv[0]), "SimRandInt(): first parameter must be an int"); @@ -612,7 +613,7 @@ JSBool SimRandInt(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) // and stop timing with StopJsTimer(num). The results will be printed to stdout // when the game exits. -static const uint MAX_JS_TIMERS = 20; +static const size_t MAX_JS_TIMERS = 20; static TimerUnit js_start_times[MAX_JS_TIMERS]; static TimerUnit js_timer_overhead; static TimerClient js_timer_clients[MAX_JS_TIMERS]; @@ -621,7 +622,7 @@ static char js_timer_descriptions_buf[MAX_JS_TIMERS * 12]; // depends on MAX_JS_ static void InitJsTimers() { char* pos = js_timer_descriptions_buf; - for(uint i = 0; i < MAX_JS_TIMERS; i++) + for(size_t i = 0; i < MAX_JS_TIMERS; i++) { const char* description = pos; pos += sprintf(pos, "js_timer %d", i)+1; @@ -645,12 +646,12 @@ static void InitJsTimers() js_timer_clients[0].sum.SetToZero(); } -JSBool StartJsTimer(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) +JSBool StartJsTimer(JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval) { ONCE(InitJsTimers()); JSU_REQUIRE_PARAMS(1); - uint slot = ToPrimitive(argv[0]); + size_t slot = ToPrimitive(argv[0]); if (slot >= MAX_JS_TIMERS) return JS_FALSE; @@ -659,10 +660,10 @@ JSBool StartJsTimer(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rva } -JSBool StopJsTimer(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) +JSBool StopJsTimer(JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval) { JSU_REQUIRE_PARAMS(1); - uint slot = ToPrimitive(argv[0]); + size_t slot = ToPrimitive(argv[0]); if (slot >= MAX_JS_TIMERS) return JS_FALSE; @@ -682,7 +683,7 @@ JSBool StopJsTimer(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval // Create a new network server object. // params: // returns: net server object -JSBool CreateServer(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) +JSBool CreateServer(JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval) { JSU_REQUIRE_NO_PARAMS(); @@ -699,7 +700,7 @@ JSBool CreateServer(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rva // Create a new network client object. // params: // returns: net client object -JSBool CreateClient(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) +JSBool CreateClient(JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval) { JSU_REQUIRE_NO_PARAMS(); @@ -722,7 +723,7 @@ JSBool CreateClient(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rva // - When complete, the engine calls the reallyStartGame JS function. // TODO: Replace StartGame with Create(Game|Server|Client)/game.start() - // after merging CGame and CGameAttributes -JSBool StartGame(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) +JSBool StartGame(JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval) { JSU_REQUIRE_NO_PARAMS(); @@ -766,7 +767,7 @@ JSBool StartGame(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) // Immediately ends the current game (if any). // params: // returns: -JSBool EndGame(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) +JSBool EndGame(JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval) { JSU_REQUIRE_NO_PARAMS(); @@ -774,7 +775,7 @@ JSBool EndGame(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) return JS_TRUE; } -JSBool GetGameMode(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) +JSBool GetGameMode(JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval) { JSU_REQUIRE_NO_PARAMS(); @@ -794,7 +795,7 @@ JSBool GetGameMode(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval // Replaces the current language (locale) with a new one. // params: language id [string] as in I18n::LoadLanguage // returns: -JSBool LoadLanguage(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) +JSBool LoadLanguage(JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval) { JSU_REQUIRE_PARAMS(1); @@ -808,7 +809,7 @@ JSBool LoadLanguage(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rva // Return identifier of the current language (locale) in use. // params: // returns: language id [string] as in I18n::LoadLanguage -JSBool GetLanguageID(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) +JSBool GetLanguageID(JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval) { JSU_REQUIRE_NO_PARAMS(); *rval = JSVAL_NULL; @@ -835,7 +836,7 @@ JSBool GetLanguageID(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rv // notes: // - currently implemented via access violation (read of address 0) // - useful for testing the crashlog/stack trace code. -JSBool ProvokeCrash(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) +JSBool ProvokeCrash(JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval) { JSU_REQUIRE_NO_PARAMS(); @@ -849,7 +850,7 @@ JSBool ProvokeCrash(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rva // returns: true [bool] // notes: // - writes an indication of how long this took to the console. -JSBool ForceGarbageCollection(JSContext* cx, JSObject* UNUSED(obj), uint argc, jsval* argv, jsval* rval) +JSBool ForceGarbageCollection(JSContext* cx, JSObject* UNUSED(obj), uintN argc, jsval* argv, jsval* rval) { JSU_REQUIRE_NO_PARAMS(); @@ -872,7 +873,7 @@ JSBool ForceGarbageCollection(JSContext* cx, JSObject* UNUSED(obj), uint argc, j // returns: global object // notes: // - Useful for accessing an object from another scope. -JSBool GetGuiGlobal(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) +JSBool GetGuiGlobal(JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval) { JSU_REQUIRE_NO_PARAMS(); @@ -883,7 +884,7 @@ JSBool GetGuiGlobal(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rva // Resets the entire GUI state and reloads the XML files. // params: // returns: -JSBool ResetGui(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) +JSBool ResetGui(JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval) { JSU_REQUIRE_NO_PARAMS(); @@ -909,7 +910,7 @@ JSBool ResetGui(JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval) // notes: // - This value is recalculated once a frame. We take special care to // filter it, so it is both accurate and free of jitter. -JSBool GetFps( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval ) +JSBool GetFps( JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_NO_PARAMS(); *rval = INT_TO_JSVAL(g_frequencyFilter->StableFrequency()); @@ -923,7 +924,7 @@ JSBool GetFps( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval ) // notes: // - Exit happens after the current main loop iteration ends // (since this only sets a flag telling it to end) -JSBool ExitProgram( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval ) +JSBool ExitProgram( JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_NO_PARAMS(); @@ -939,7 +940,7 @@ JSBool ExitProgram( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rva // - May not be supported on all platforms. // - Only a rough approximation; do not base low-level decisions // ("should I allocate one more texture?") on this. -JSBool WriteVideoMemToConsole( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval ) +JSBool WriteVideoMemToConsole( JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_NO_PARAMS(); @@ -954,14 +955,14 @@ JSBool WriteVideoMemToConsole( JSContext* cx, JSObject*, uint argc, jsval* argv, // returns: // notes: // - Cursors are stored in "art\textures\cursors" -JSBool SetCursor( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval ) +JSBool SetCursor( JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS(1); g_CursorName = g_ScriptingHost.ValueToString(argv[0]); return JS_TRUE; } -JSBool GetCursorName( JSContext* UNUSED(cx), JSObject*, uint UNUSED(argc), jsval* UNUSED(argv), jsval* rval ) +JSBool GetCursorName( JSContext* UNUSED(cx), JSObject*, size_t UNUSED(argc), jsval* UNUSED(argv), jsval* rval ) { *rval = ToJSVal(g_CursorName); return JS_TRUE; @@ -972,7 +973,7 @@ JSBool GetCursorName( JSContext* UNUSED(cx), JSObject*, uint UNUSED(argc), jsval // returns: // notes: // - Usefulness is unclear. If you need it, consider renaming this and updating the docs. -JSBool _RewriteMaps( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval ) +JSBool _RewriteMaps( JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_NO_PARAMS(); @@ -987,7 +988,7 @@ JSBool _RewriteMaps( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rv // notes: // - value is as required by GL_TEXTURE_LOD_BIAS. // - useful for adjusting image "sharpness" (since it affects which mipmap level is chosen) -JSBool _LodBias( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval ) +JSBool _LodBias( JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS(1); @@ -999,7 +1000,7 @@ JSBool _LodBias( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval ) // Focus the game camera on a given position. // params: target position vector [CVector3D] // returns: success [bool] -JSBool SetCameraTarget( JSContext* cx, JSObject* UNUSED(obj), uint argc, jsval* argv, jsval* rval ) +JSBool SetCameraTarget( JSContext* cx, JSObject* UNUSED(obj), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS(1); *rval = JSVAL_NULL; @@ -1031,7 +1032,7 @@ JSBool SetCameraTarget( JSContext* cx, JSObject* UNUSED(obj), uint argc, jsval* // but that's a bit more trouble. // - To be exact, the date/time returned is when scriptglue.cpp was // last compiled; since the auto-build does full rebuilds, that is moot. -JSBool GetBuildTimestamp( JSContext* cx, JSObject*, uint argc, jsval* argv, jsval* rval ) +JSBool GetBuildTimestamp( JSContext* cx, JSObject*, uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAM_RANGE(0, 1); @@ -1051,7 +1052,7 @@ JSBool GetBuildTimestamp( JSContext* cx, JSObject*, uint argc, jsval* argv, jsva // Return distance between 2 points. // params: 2 position vectors [CVector3D] // returns: Euclidean distance [float] -JSBool ComputeDistanceBetweenTwoPoints( JSContext* cx, JSObject* UNUSED(obj), uint argc, jsval* argv, jsval* rval ) +JSBool ComputeDistanceBetweenTwoPoints( JSContext* cx, JSObject* UNUSED(obj), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS(2); @@ -1068,7 +1069,7 @@ JSBool ComputeDistanceBetweenTwoPoints( JSContext* cx, JSObject* UNUSED(obj), ui // returns: global object // notes: // - Useful for accessing an object from another scope. -JSBool GetGlobal( JSContext* cx, JSObject* globalObject, uint argc, jsval* argv, jsval* rval ) +JSBool GetGlobal( JSContext* cx, JSObject* globalObject, uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_NO_PARAMS(); @@ -1077,7 +1078,7 @@ JSBool GetGlobal( JSContext* cx, JSObject* globalObject, uint argc, jsval* argv, } // Saves the current profiling data to the logs/profile.txt file -JSBool SaveProfileData( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsval* argv, jsval* rval ) +JSBool SaveProfileData( JSContext* cx, JSObject* UNUSED(globalObject), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_NO_PARAMS(); g_ProfileViewer.SaveToFile(); @@ -1088,7 +1089,7 @@ JSBool SaveProfileData( JSContext* cx, JSObject* UNUSED(globalObject), uint argc // are then ordered to construct the building if it is placed. // params: templateName - the name of the entity to place. // returns: true if cursor was activated, false if cursor was already active. -JSBool StartPlacing( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsval* argv, jsval* rval ) +JSBool StartPlacing( JSContext* cx, JSObject* UNUSED(globalObject), uintN argc, jsval* argv, jsval* rval ) { CStrW name; if(argc == 0) { @@ -1109,7 +1110,7 @@ JSBool StartPlacing( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, j } // Toggles drawing the sky -JSBool ToggleSky( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsval* argv, jsval* rval ) +JSBool ToggleSky( JSContext* cx, JSObject* UNUSED(globalObject), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_NO_PARAMS(); g_Renderer.GetSkyManager()->m_RenderSky = !g_Renderer.GetSkyManager()->m_RenderSky; @@ -1118,7 +1119,7 @@ JSBool ToggleSky( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsva } // Toggles drawing territory outlines -JSBool ToggleTerritoryRendering( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsval* argv, jsval* rval ) +JSBool ToggleTerritoryRendering( JSContext* cx, JSObject* UNUSED(globalObject), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_NO_PARAMS(); g_Renderer.m_RenderTerritories = !g_Renderer.m_RenderTerritories; @@ -1131,7 +1132,7 @@ JSBool ToggleTerritoryRendering( JSContext* cx, JSObject* UNUSED(globalObject), // water // Toggles drawing the water plane -JSBool ToggleWater( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsval* argv, jsval* rval ) +JSBool ToggleWater( JSContext* cx, JSObject* UNUSED(globalObject), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_NO_PARAMS(); g_Renderer.GetWaterManager()->m_RenderWater = !g_Renderer.GetWaterManager()->m_RenderWater; @@ -1140,7 +1141,7 @@ JSBool ToggleWater( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, js } // Sets the water plane height -JSBool SetWaterHeight( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsval* argv, jsval* rval ) +JSBool SetWaterHeight( JSContext* cx, JSObject* UNUSED(globalObject), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS( 1 ); float newHeight; @@ -1157,7 +1158,7 @@ JSBool SetWaterHeight( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, } // Gets the water plane height -JSBool GetWaterHeight( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsval* argv, jsval* rval ) +JSBool GetWaterHeight( JSContext* cx, JSObject* UNUSED(globalObject), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_NO_PARAMS(); *rval = ToJSVal(g_Renderer.GetWaterManager()->m_WaterHeight); @@ -1165,7 +1166,7 @@ JSBool GetWaterHeight( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, } // Sets the water color -JSBool SetWaterColor( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsval* argv, jsval* rval ) +JSBool SetWaterColor( JSContext* cx, JSObject* UNUSED(globalObject), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS( 3 ); float r,g,b; @@ -1183,7 +1184,7 @@ JSBool SetWaterColor( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, } // Sets the water tint (used to tint reflections in fancy water) -JSBool SetWaterTint( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsval* argv, jsval* rval ) +JSBool SetWaterTint( JSContext* cx, JSObject* UNUSED(globalObject), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS( 3 ); float r,g,b; @@ -1201,7 +1202,7 @@ JSBool SetWaterTint( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, j } // Sets the water tint (used to tint reflections in fancy water) -JSBool SetReflectionTint( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsval* argv, jsval* rval ) +JSBool SetReflectionTint( JSContext* cx, JSObject* UNUSED(globalObject), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS( 3 ); float r,g,b; @@ -1219,7 +1220,7 @@ JSBool SetReflectionTint( JSContext* cx, JSObject* UNUSED(globalObject), uint ar } // Sets the max water alpha (achieved when it is at WaterFullDepth or deeper) -JSBool SetWaterMaxAlpha( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsval* argv, jsval* rval ) +JSBool SetWaterMaxAlpha( JSContext* cx, JSObject* UNUSED(globalObject), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS( 1 ); float val; @@ -1235,7 +1236,7 @@ JSBool SetWaterMaxAlpha( JSContext* cx, JSObject* UNUSED(globalObject), uint arg } // Sets the water full depth (when it is colored WaterMaxAlpha) -JSBool SetWaterFullDepth( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsval* argv, jsval* rval ) +JSBool SetWaterFullDepth( JSContext* cx, JSObject* UNUSED(globalObject), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS( 1 ); float val; @@ -1251,7 +1252,7 @@ JSBool SetWaterFullDepth( JSContext* cx, JSObject* UNUSED(globalObject), uint ar } // Sets the water alpha offset (added to tweak water alpha near the shore) -JSBool SetWaterAlphaOffset( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsval* argv, jsval* rval ) +JSBool SetWaterAlphaOffset( JSContext* cx, JSObject* UNUSED(globalObject), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS( 1 ); float val; @@ -1269,7 +1270,7 @@ JSBool SetWaterAlphaOffset( JSContext* cx, JSObject* UNUSED(globalObject), uint //----------------------------------------------------------------------------- // Is the game paused? -JSBool IsPaused( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsval* argv, jsval* rval ) +JSBool IsPaused( JSContext* cx, JSObject* UNUSED(globalObject), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_NO_PARAMS(); @@ -1284,7 +1285,7 @@ JSBool IsPaused( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsval } // Pause/unpause the game -JSBool SetPaused( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsval* argv, jsval* rval ) +JSBool SetPaused( JSContext* cx, JSObject* UNUSED(globalObject), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS( 1 ); @@ -1307,7 +1308,7 @@ JSBool SetPaused( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsva } // Get game time -JSBool GetGameTime( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsval* argv, jsval* rval ) +JSBool GetGameTime( JSContext* cx, JSObject* UNUSED(globalObject), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_NO_PARAMS(); @@ -1321,7 +1322,7 @@ JSBool GetGameTime( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, js return JS_TRUE; } -JSBool RegisterTrigger( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsval* argv, jsval* rval ) +JSBool RegisterTrigger( JSContext* cx, JSObject* UNUSED(globalObject), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS_CPP(1); CTrigger* trigger = ToNative( argv[0] ); @@ -1332,7 +1333,7 @@ JSBool RegisterTrigger( JSContext* cx, JSObject* UNUSED(globalObject), uint argc return JS_TRUE; } -JSBool GetTrigger( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsval* argv, jsval* rval ) +JSBool GetTrigger( JSContext* cx, JSObject* UNUSED(globalObject), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS_CPP(1); CStrW name = ToPrimitive( argv[0] ); @@ -1348,15 +1349,13 @@ JSBool GetTrigger( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsv } // Reveal map -JSBool RevealMap( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsval* argv, jsval* rval ) +JSBool RevealMap( JSContext* cx, JSObject* UNUSED(globalObject), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAM_RANGE(0, 1); - uint newValue; + int newValue; if(argc == 0) - { - newValue = 2; - } + newValue = LOS_SETTING_ALL_VISIBLE; else if(!ToPrimitive( g_ScriptingHost.GetContext(), argv[0], newValue ) || newValue > 2) { JS_ReportError( cx, "Invalid argument (should be 0, 1 or 2)" ); @@ -1364,7 +1363,7 @@ JSBool RevealMap( JSContext* cx, JSObject* UNUSED(globalObject), uint argc, jsva return( JS_FALSE ); } - g_Game->GetWorld()->GetLOSManager()->m_LOSSetting = newValue; + g_Game->GetWorld()->GetLOSManager()->m_LOSSetting = (ELOSSetting)newValue; *rval = JSVAL_VOID; return( JS_TRUE ); } diff --git a/source/scripting/ScriptableComplex.cpp b/source/scripting/ScriptableComplex.cpp index 856ddb340a..9b152b5a18 100644 --- a/source/scripting/ScriptableComplex.cpp +++ b/source/scripting/ScriptableComplex.cpp @@ -13,7 +13,7 @@ static Bucket bucket; // HACK: it needs to be created/destroyed; since there is no // global init/shutdown call here, we keep a refcnt. this assumes that // going to 0 <==> shutdown! if that proves wrong, bucket_alloc will warn. -static uint suballoc_refs; // initialized in suballoc_attach +static size_t suballoc_refs; // initialized in suballoc_attach void jscomplexproperty_suballoc_attach() { diff --git a/source/scripting/ScriptableComplex.inl b/source/scripting/ScriptableComplex.inl index fd9038f8d8..2a9da9f72c 100644 --- a/source/scripting/ScriptableComplex.inl +++ b/source/scripting/ScriptableComplex.inl @@ -690,7 +690,7 @@ template void CJSComplex::ScriptingInit( const char* ClassName, JSNative Constructor, uintN ConstructorMinArgs ) { JSFunctionSpec* JSI_methods = new JSFunctionSpec[ m_Methods.size() + 3 ]; - unsigned int MethodID; + size_t MethodID; for( MethodID = 0; MethodID < m_Methods.size(); MethodID++ ) JSI_methods[MethodID] = m_Methods[MethodID]; diff --git a/source/scripting/ScriptableObject.h b/source/scripting/ScriptableObject.h index 0183489550..804b9aa936 100644 --- a/source/scripting/ScriptableObject.h +++ b/source/scripting/ScriptableObject.h @@ -218,7 +218,7 @@ public: static void ScriptingInit( const char* ClassName, JSNative Constructor = NULL, uintN ConstructorMinArgs = 0 ) { JSFunctionSpec* JSI_methods = new JSFunctionSpec[ m_Methods.size() + 1 ]; - unsigned int MethodID; + size_t MethodID; for( MethodID = 0; MethodID < m_Methods.size(); MethodID++ ) JSI_methods[MethodID] = m_Methods[MethodID]; diff --git a/source/scripting/ScriptingHost.cpp b/source/scripting/ScriptingHost.cpp index c5c0f739dd..5311240ff6 100644 --- a/source/scripting/ScriptingHost.cpp +++ b/source/scripting/ScriptingHost.cpp @@ -103,8 +103,7 @@ void ScriptingHost::RunMemScript(const char* script, size_t size, const char* fi // Maybe TODO: support Unicode input formats? jsval rval; - JSBool ok = JS_EvaluateScript(m_Context, globalObject, script, - (uint)size, filename, line, &rval); + JSBool ok = JS_EvaluateScript(m_Context, globalObject, script, (uintN)size, filename, line, &rval); if (ok == JS_FALSE) throw PSERROR_Scripting_LoadFile_EvalErrors(); diff --git a/source/scripting/SynchedJSObject.cpp b/source/scripting/SynchedJSObject.cpp index a838bdfc98..6d5246893b 100644 --- a/source/scripting/SynchedJSObject.cpp +++ b/source/scripting/SynchedJSObject.cpp @@ -5,13 +5,13 @@ #include "ScriptCustomTypes.h" template <> -CStrW ToNetString(const uint &val) +CStrW ToNetString(const unsigned &val) { return CStrW(val); } template <> -void SetFromNetString(uint &val, const CStrW& string) +void SetFromNetString(unsigned &val, const CStrW& string) { val=string.ToUInt(); } @@ -71,7 +71,7 @@ void SetFromNetString(SColour &data, const CStrW& wstring) float values[4]; if (line.GetArgCount() != 4) return; - for (uint i=0; i<4; ++i) + for (size_t i=0; i<4; ++i) { if (!line.GetArgFloat(i, values[i])) { diff --git a/source/scripting/SynchedJSObject.h b/source/scripting/SynchedJSObject.h index 8cea7e85b0..5dc2e54de5 100644 --- a/source/scripting/SynchedJSObject.h +++ b/source/scripting/SynchedJSObject.h @@ -46,7 +46,7 @@ CStrW ToNetString(const T &data); template <> CStrW ToNetString(const type &data); \ template <> void SetFromNetString(type &data, const CStrW& string); -TYPE(uint) +TYPE(size_t) TYPE(CStrW) #undef TYPE diff --git a/source/simulation/Aura.cpp b/source/simulation/Aura.cpp index f78649b10e..54710adc70 100644 --- a/source/simulation/Aura.cpp +++ b/source/simulation/Aura.cpp @@ -7,7 +7,7 @@ #include -CAura::CAura( JSContext* cx, CEntity* source, CStrW& name, float radius, size_t tickRate, const CVector4D& color, JSObject* handler ) +CAura::CAura( JSContext* cx, CEntity* source, CStrW& name, float radius, int tickRate, const CVector4D& color, JSObject* handler ) : m_cx(cx), m_source(source), m_name(name), m_radius(radius), m_handler(handler), m_tickRate(tickRate), m_tickCyclePos(0), m_color(color) { @@ -19,7 +19,7 @@ CAura::~CAura() JS_RemoveRoot( m_cx, &m_handler ); } -void CAura::Update( size_t timestep ) +void CAura::Update( int timestep ) { std::vector inRange; CVector3D pos = m_source->m_position; diff --git a/source/simulation/Aura.h b/source/simulation/Aura.h index d12e2ef0d6..ae8a19828e 100644 --- a/source/simulation/Aura.h +++ b/source/simulation/Aura.h @@ -16,12 +16,12 @@ public: CStrW m_name; CVector4D m_color; float m_radius; // In graphics units - size_t m_tickRate; // In milliseconds + int m_tickRate; // In milliseconds JSObject* m_handler; std::vector m_influenced; - size_t m_tickCyclePos; // Add time to this until it's time to tick again + int m_tickCyclePos; // Add time to this until it's time to tick again - CAura( JSContext* cx, CEntity* source, CStrW& name, float radius, size_t tickRate, const CVector4D& color, JSObject* handler ); + CAura( JSContext* cx, CEntity* source, CStrW& name, float radius, int tickRate, const CVector4D& color, JSObject* handler ); ~CAura(); // Remove all entities from under our influence; this isn't done in the destructor since @@ -35,7 +35,7 @@ public: void Remove( CEntity* ent ); // Called to update the aura each simulation frame. - void Update( size_t timestep ); + void Update( int timestep ); }; #endif diff --git a/source/simulation/Entity.cpp b/source/simulation/Entity.cpp index 1c60e6431c..4de804c411 100644 --- a/source/simulation/Entity.cpp +++ b/source/simulation/Entity.cpp @@ -100,7 +100,7 @@ CEntity::CEntity( CEntityTemplate* base, CVector3D position, float orientation, m_currentRequest = 0; entf_set(ENTF_DESTROY_NOTIFIERS); - m_formationSlot = -1; + m_formationSlot = (size_t)-1; m_formation = -1; m_grouped = -1; @@ -152,7 +152,7 @@ CEntity::~CEntity() void CEntity::LoadBase() { - int previous_unit_id = -1; + size_t previous_unit_id = CUnit::invalidId; if( m_actor ) { @@ -394,7 +394,7 @@ void CEntity::RebuildClassSet() (*it)->RebuildClassSet(); } -void CEntity::Update( size_t timestep ) +void CEntity::Update( int timestep ) { if( !m_extant ) return; @@ -450,7 +450,7 @@ void CEntity::Update( size_t timestep ) ); } -void CEntity::UpdateOrders( size_t timestep ) +void CEntity::UpdateOrders( int timestep ) { // The process[...] functions return 'true' if the order at the top of the stack // still needs to be (re-)evaluated; else 'false' to terminate the processing of @@ -644,7 +644,7 @@ void CEntity::UpdateCollisionPatch() } #if AURA_TEST -void CEntity::UpdateAuras( size_t timestep_millis ) +void CEntity::UpdateAuras( int timestep_millis ) { std::vector::iterator it_a; for( it_a = m_Auras.begin(); it_a != m_Auras.end(); it_a++ ) diff --git a/source/simulation/Entity.h b/source/simulation/Entity.h index afe8e15f46..b5c5284b25 100644 --- a/source/simulation/Entity.h +++ b/source/simulation/Entity.h @@ -116,18 +116,18 @@ public: ActionTable m_actions; bool m_selected; - i32 m_grouped; - int m_formation; // Index of which formation we're in - int m_formationSlot; // The slot of the above formation + ssize_t m_grouped; // group index or -1 if not grouped + ssize_t m_formation; // Index of which formation we're in or -1 + ssize_t m_formationSlot; // The slot of the above formation - uint ent_flags; - bool entf_get(uint desired_flag) const { return (ent_flags & desired_flag) != 0; } - void entf_set(uint desired_flag) { ent_flags |= desired_flag; } - void entf_clear(uint desired_flag) { ent_flags &= ~desired_flag; } - void entf_set_to(uint desired_flag, bool value) + int ent_flags; + bool entf_get(int desired_flag) const { return (ent_flags & desired_flag) != 0; } + void entf_set(int desired_flag) { ent_flags |= desired_flag; } + void entf_clear(int desired_flag) { ent_flags &= ~desired_flag; } + void entf_set_to(int desired_flag, bool value) { ent_flags &= ~desired_flag; - const uint mask = value? ~0u : 0; + const int mask = value? ~0u : 0; ent_flags |= desired_flag & mask; } @@ -159,8 +159,8 @@ public: // Stance name CStr m_stanceName; - // LOS - int m_los; + // LOS distance/range + ssize_t m_los; // If the object is a territory centre, this points to its territory CTerritory* m_associatedTerritory; @@ -211,8 +211,8 @@ public: int m_lastState; // used in animation FSM // Position in the current state's cycle - static const size_t NOT_IN_CYCLE = (size_t)-1; - size_t m_fsm_cyclepos; // -cycle_length....cycle_length + static const int NOT_IN_CYCLE = -1; + int m_fsm_cyclepos; // -cycle_length....cycle_length CEntityOrders m_orderQueue; std::deque m_listeners; @@ -233,27 +233,28 @@ public: private: CEntity( CEntityTemplate* base, CVector3D position, float orientation, const std::set& actorSelections, const CStrW* building = 0 ); - uint ProcessGotoHelper( CEntityOrder* current, size_t timestep_millis, HEntity& collide, float& timeLeft ); + // (returns EGotoSituation, but we don't want to expose that) + int ProcessGotoHelper( CEntityOrder* current, int timestep_millis, HEntity& collide, float& timeLeft ); - bool ProcessContactAction( CEntityOrder* current, size_t timestep_millis, CEntityOrder::EOrderType transition, SEntityAction* action ); - bool ProcessContactActionNoPathing( CEntityOrder* current, size_t timestep_millis, const CStr& animation, CScriptEvent* contactEvent, SEntityAction* action ); + bool ProcessContactAction( CEntityOrder* current, int timestep_millis, CEntityOrder::EOrderType transition, SEntityAction* action ); + bool ProcessContactActionNoPathing( CEntityOrder* current, int timestep_millis, const CStr& animation, CScriptEvent* contactEvent, SEntityAction* action ); - bool ProcessGeneric( CEntityOrder* current, size_t timestep_millis ); - bool ProcessGenericNoPathing( CEntityOrder* current, size_t timestep_millis ); + bool ProcessGeneric( CEntityOrder* current, int timestep_millis ); + bool ProcessGenericNoPathing( CEntityOrder* current, int timestep_millis ); bool ProcessProduce( CEntityOrder* order ); - bool ProcessGotoNoPathing( CEntityOrder* current, size_t timestep_millis ); - bool ProcessGoto( CEntityOrder* current, size_t timestep_millis ); - bool ProcessGotoWaypoint( CEntityOrder* current, size_t timestep_millis, bool contact ); + bool ProcessGotoNoPathing( CEntityOrder* current, int timestep_millis ); + bool ProcessGoto( CEntityOrder* current, int timestep_millis ); + bool ProcessGotoWaypoint( CEntityOrder* current, int timestep_millis, bool contact ); - bool ProcessPatrol( CEntityOrder* current, size_t timestep_millis ); + bool ProcessPatrol( CEntityOrder* current, int timestep_millis ); float ChooseMovementSpeed( float distance ); bool ShouldRun( float distance ); // Given our distance to a target, can we be running? - void UpdateOrders( size_t timestep_millis ); + void UpdateOrders( int timestep_millis ); public: ~CEntity(); @@ -262,7 +263,7 @@ public: HEntity me; // Updates gameplay information for the specified timestep - void Update( size_t timestep_millis ); + void Update( int timestep_millis ); // Updates graphical information for a point between the last and current // simulation frame; should be 0 <= relativeoffset <= 1 (else it'll be // clamped) @@ -273,7 +274,7 @@ public: void InvalidateActor(); // Updates auras - void UpdateAuras( size_t timestep_millis ); + void UpdateAuras( int timestep_millis ); // Exit auras we're currently in (useful for example when we change state) void ExitAuras(); @@ -402,7 +403,7 @@ public: jsval_t FindSector( JSContext* cx, uintN argc, jsval* argv ); // Script constructor - static JSBool Construct( JSContext* cx, JSObject* obj, uint argc, jsval* argv, jsval* rval ); + static JSBool Construct( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval ); // Script-bound functions diff --git a/source/simulation/EntityFormation.cpp b/source/simulation/EntityFormation.cpp index 026a65c06b..6e9b1bdd70 100644 --- a/source/simulation/EntityFormation.cpp +++ b/source/simulation/EntityFormation.cpp @@ -24,23 +24,23 @@ CEntityFormation::CEntityFormation( CFormation*& base, size_t index ) m_duplication=false; m_entities.resize(m_base->m_numSlots); - m_index = (int)index; + m_index = index; } CEntityFormation::~CEntityFormation() { - for ( int i=0; im_numSlots; ++i ) + for ( size_t i=0; im_numSlots; ++i ) { if ( m_entities[i] ) { m_entities[i]->m_formation = -1; - m_entities[i]->m_formationSlot = -1; + m_entities[i]->m_formationSlot = (size_t)-1; m_entities[i] = NULL; } } } -int CEntityFormation::GetSlotCount() +size_t CEntityFormation::GetSlotCount() { return m_base->m_numSlots; } @@ -49,7 +49,7 @@ void CEntityFormation::SwitchBase( CFormation*& base ) { std::vector copy; copy.resize( m_base->m_numSlots ); - for ( int i=0; i < m_base->m_numSlots; ++i ) + for ( size_t i=0; i < m_base->m_numSlots; ++i ) { if ( !m_entities[i] ) continue; @@ -68,7 +68,7 @@ bool CEntityFormation::AddUnit( CEntity* entity ) { debug_assert( entity ); //Add the unit to the most appropriate slot - for (int i=0; im_numSlots; ++i) + for (size_t i=0; im_numSlots; ++i) { if ( IsBetterUnit( i, entity ) ) { @@ -82,8 +82,8 @@ bool CEntityFormation::AddUnit( CEntity* entity ) m_entities[i] = entity; ++m_numEntities; - entity->m_formation = m_index; - entity->m_formationSlot = i; + entity->m_formation = (ssize_t)m_index; + entity->m_formationSlot = (ssize_t)i; return true; } @@ -98,13 +98,13 @@ void CEntityFormation::RemoveUnit( CEntity* entity ) m_entities[entity->m_formationSlot] = NULL; entity->m_formation = -1; - entity->m_formationSlot = -1; + entity->m_formationSlot = (size_t)-1; --m_numEntities; //UpdateFormation(); } -bool CEntityFormation::IsSlotAppropriate( int order, CEntity* entity ) +bool CEntityFormation::IsSlotAppropriate( size_t order, CEntity* entity ) { debug_assert( entity ); if ( !IsValidOrder(order) ) @@ -119,7 +119,7 @@ bool CEntityFormation::IsSlotAppropriate( int order, CEntity* entity ) return false; } -bool CEntityFormation::IsBetterUnit( int order, CEntity* entity ) +bool CEntityFormation::IsBetterUnit( size_t order, CEntity* entity ) { if ( !( IsValidOrder(order) && entity ) ) return false; @@ -147,13 +147,13 @@ bool CEntityFormation::IsBetterUnit( int order, CEntity* entity ) void CEntityFormation::UpdateFormation() { //Get the entities in the right order (as in, ordered correctly and in the right order/slot) - for ( int i=1; im_numSlots; ++i ) + for ( size_t i=1; im_numSlots; ++i ) { if ( !m_entities[i] ) continue; //Go through slots with higher order - for ( int j=i-1; j > 0; --j ) + for ( size_t j=i-1; j != 0; --j ) { if ( IsBetterUnit( j, m_entities[i] ) ) { @@ -161,7 +161,7 @@ void CEntityFormation::UpdateFormation() m_entities[j] = m_entities[i]; m_entities[i] = temp; - int tmpSlot = m_entities[i]->m_formationSlot; + ssize_t tmpSlot = m_entities[i]->m_formationSlot; m_entities[i]->m_formationSlot = m_entities[j]->m_formationSlot; m_entities[j]->m_formationSlot = tmpSlot; --i; @@ -176,7 +176,7 @@ void CEntityFormation::UpdateFormation() void CEntityFormation::ResetAllEntities() { - for ( int i=0; im_numSlots; ++i ) + for ( size_t i=0; im_numSlots; ++i ) m_entities[i] = NULL; } @@ -188,7 +188,7 @@ void CEntityFormation::ResetAngleDivs() void CEntityFormation::SelectAllUnits() { - for ( int i=0; im_numSlots; ++i ) + for ( size_t i=0; im_numSlots; ++i ) { if ( m_entities[i] && !g_Selection.IsSelected(m_entities[i]->me) ) g_Selection.AddSelection( m_entities[i]->me ); @@ -198,7 +198,7 @@ void CEntityFormation::SelectAllUnits() CEntityList CEntityFormation::GetEntityList() { CEntityList ret; - for ( int i=0; im_numSlots; i++ ) + for ( size_t i=0; im_numSlots; i++ ) { if ( m_entities[i] ) ret.push_back( m_entities[i]->me); @@ -206,7 +206,7 @@ CEntityList CEntityFormation::GetEntityList() return ret; } -CVector2D CEntityFormation::GetSlotPosition( int order ) +CVector2D CEntityFormation::GetSlotPosition( size_t order ) { if ( IsValidOrder(order) ) return CVector2D ( m_base->m_slots[order].rankOff, m_base->m_slots[order].fileOff ); @@ -226,12 +226,12 @@ void CEntityFormation::BaseToMovement() void CEntityFormation::ResetIndex( size_t index ) { - m_index = (int)index; + m_index = index; for ( size_t i=0; i< m_entities.size(); ++i ) { if ( m_entities[i] ) - m_entities[i]->m_formation = m_index; + m_entities[i]->m_formation = (ssize_t)m_index; } } diff --git a/source/simulation/EntityFormation.h b/source/simulation/EntityFormation.h index 8d7c4ef227..ee98ffa036 100644 --- a/source/simulation/EntityFormation.h +++ b/source/simulation/EntityFormation.h @@ -20,12 +20,12 @@ public: CEntityFormation( CFormation*& base, size_t index ); ~CEntityFormation(); - int GetEntityCount() { return m_numEntities; } + size_t GetEntityCount() { return m_numEntities; } float GetSpeed() { return m_speed; } - int GetSlotCount(); + size_t GetSlotCount(); CEntityList GetEntityList(); - CVector2D GetSlotPosition( int order ); + CVector2D GetSlotPosition( size_t order ); CVector2D GetPosition() { return m_position; } CFormation* GetBase() { return m_base; } void BaseToMovement(); @@ -36,11 +36,11 @@ public: inline bool IsDuplication() { return m_duplication; } inline void SetLock( bool lock ){ m_locked=lock; } inline bool IsLocked() { return m_locked; } - inline bool IsValidOrder(int order) { return ( order >= 0 && order < GetSlotCount() ); } + inline bool IsValidOrder(size_t order) { return ( order < GetSlotCount() ); } private: - int m_numEntities; - int m_index; + size_t m_numEntities; + size_t m_index; float m_speed; //speed of slowest unit float m_orientation; //Our orientation angle. Used for rotation. CVector2D m_position; @@ -58,8 +58,8 @@ private: bool AddUnit( CEntity* entity ); void RemoveUnit( CEntity* entity ); - bool IsSlotAppropriate( int order, CEntity* entity ); //If empty, can we use this slot? - bool IsBetterUnit( int order, CEntity* entity ); + bool IsSlotAppropriate( size_t order, CEntity* entity ); //If empty, can we use this slot? + bool IsBetterUnit( size_t order, CEntity* entity ); void UpdateFormation(); void SwitchBase( CFormation*& base ); diff --git a/source/simulation/EntityHandles.cpp b/source/simulation/EntityHandles.cpp index 4589995ecf..ce05c17d2e 100644 --- a/source/simulation/EntityHandles.cpp +++ b/source/simulation/EntityHandles.cpp @@ -106,7 +106,7 @@ CEntity& HEntity::operator*() const return( *g_EntityManager.m_entities[m_handle].m_entity ); } -uint HEntity::GetSerializedLength() const +size_t HEntity::GetSerializedLength() const { return 2; } @@ -133,9 +133,9 @@ HEntity::operator CStr() const return CStr(buf); } -uint CEntityList::GetSerializedLength() const +size_t CEntityList::GetSerializedLength() const { - return (uint)(2*size()); + return (size_t)(2*size()); } u8 *CEntityList::Serialize(u8 *buffer) const diff --git a/source/simulation/EntityHandles.h b/source/simulation/EntityHandles.h index 501cee8a36..16a94bf0d8 100644 --- a/source/simulation/EntityHandles.h +++ b/source/simulation/EntityHandles.h @@ -76,7 +76,7 @@ public: // Same as !IsValid() bool operator!() const { return !IsValid(); }; - uint GetSerializedLength() const; + size_t GetSerializedLength() const; u8 *Serialize(u8 *buffer) const; const u8 *Deserialize(const u8 *buffer, const u8 *end); operator CStr8() const; @@ -107,7 +107,7 @@ struct CEntityList: public std::vector push_back(oneEntity); } - uint GetSerializedLength() const; + size_t GetSerializedLength() const; u8 *Serialize(u8 *buffer) const; const u8 *Deserialize(const u8 *buffer, const u8 *end); operator CStr8() const; diff --git a/source/simulation/EntityManager.cpp b/source/simulation/EntityManager.cpp index 9766236ff9..3eb87a4a32 100644 --- a/source/simulation/EntityManager.cpp +++ b/source/simulation/EntityManager.cpp @@ -397,7 +397,7 @@ void CEntityManager::TickAll() } */ -void CEntityManager::UpdateAll( size_t timestep ) +void CEntityManager::UpdateAll( int timestep ) { PROFILE_START( "reaper" ); std::vector::iterator it; @@ -467,7 +467,7 @@ void CEntityManager::InvalidateAll() void CEntityManager::RemoveUnitCount(CEntity* ent) { - size_t playerID = (size_t)ent->GetPlayer()->GetPlayerID(); + size_t playerID = ent->GetPlayer()->GetPlayerID(); CStrW className, classList = ent->m_classes.GetMemberList(); while ( (className = classList.BeforeFirst(L" ")) != classList ) diff --git a/source/simulation/EntityManager.h b/source/simulation/EntityManager.h index 8147dcaf51..9aebbd10ec 100644 --- a/source/simulation/EntityManager.h +++ b/source/simulation/EntityManager.h @@ -91,7 +91,7 @@ public: void RemoveUnitCount(CEntity* ent); //Removes unit from population count void AddEntityClassData(const HEntity& handle); - void UpdateAll( size_t timestep ); + void UpdateAll( int timestep ); void InterpolateAll( float relativeoffset ); void InitializeAll(); // void TickAll(); diff --git a/source/simulation/EntityScriptInterface.cpp b/source/simulation/EntityScriptInterface.cpp index 8c6d9f78e2..b7f05a8df2 100644 --- a/source/simulation/EntityScriptInterface.cpp +++ b/source/simulation/EntityScriptInterface.cpp @@ -130,7 +130,7 @@ void CEntity::ScriptingInit() // Script constructor -JSBool CEntity::Construct( JSContext* cx, JSObject* UNUSED(obj), uint argc, jsval* argv, jsval* rval ) +JSBool CEntity::Construct( JSContext* cx, JSObject* UNUSED(obj), uintN argc, jsval* argv, jsval* rval ) { debug_assert( argc >= 2 ); @@ -512,7 +512,7 @@ jsval_t CEntity::AddAura( JSContext* cx, uintN argc, jsval* argv ) CStrW name = ToPrimitive( argv[0] ); float radius = ToPrimitive( argv[1] ); - size_t tickRate = std::max( 0, ToPrimitive( argv[2] ) ); // since it's a size_t we don't want it to be negative + int tickRate = std::max( 0, ToPrimitive( argv[2] ) ); // since it's a size_t we don't want it to be negative float r = ToPrimitive( argv[3] ); float g = ToPrimitive( argv[4] ); float b = ToPrimitive( argv[5] ); @@ -553,7 +553,7 @@ jsval_t CEntity::SetActionParams( JSContext* UNUSED(cx), uintN argc, jsval* argv int id = ToPrimitive( argv[0] ); float minRange = ToPrimitive( argv[1] ); float maxRange = ToPrimitive( argv[2] ); - uint speed = ToPrimitive( argv[3] ); + int speed = ToPrimitive( argv[3] ); CStr8 animation = ToPrimitive( argv[4] ); m_actions[id] = SEntityAction( id, minRange, maxRange, speed, animation ); diff --git a/source/simulation/EntityStateProcessing.cpp b/source/simulation/EntityStateProcessing.cpp index 6b966ae603..dcd14ff816 100644 --- a/source/simulation/EntityStateProcessing.cpp +++ b/source/simulation/EntityStateProcessing.cpp @@ -87,7 +87,7 @@ float CEntity::ChooseMovementSpeed( float distance ) // Does all the shared processing for line-of-sight gotos -uint CEntity::ProcessGotoHelper( CEntityOrder* current, size_t timestep_millis, HEntity& collide, float& timeLeft ) +int CEntity::ProcessGotoHelper( CEntityOrder* current, int timestep_millis, HEntity& collide, float& timeLeft ) { float timestep=timestep_millis/1000.0f; @@ -259,7 +259,7 @@ uint CEntity::ProcessGotoHelper( CEntityOrder* current, size_t timestep_millis, } -bool CEntity::ProcessGotoNoPathing( CEntityOrder* current, size_t timestep_millis ) +bool CEntity::ProcessGotoNoPathing( CEntityOrder* current, int timestep_millis ) { HEntity collide; float timeLeft; @@ -286,8 +286,10 @@ bool CEntity::ProcessGotoNoPathing( CEntityOrder* current, size_t timestep_milli case CEntityOrder::ORDER_GOTO_NOPATHING: case CEntityOrder::ORDER_GOTO_COLLISION: case CEntityOrder::ORDER_GOTO_SMOOTHED: - size_t newTimestep = cpu_i32FromFloat(timeLeft * 1000.0f); + { + int newTimestep = int(timeLeft * 1000.0f); return( ProcessGotoNoPathing( newOrder, newTimestep ) ); + } } } return( false ); @@ -375,7 +377,7 @@ bool CEntity::ProcessGotoNoPathing( CEntityOrder* current, size_t timestep_milli } // Handles processing common to (at the moment) gather and melee attack actions -bool CEntity::ProcessContactAction( CEntityOrder* current, size_t UNUSED(timestep_millis), CEntityOrder::EOrderType transition, SEntityAction* action ) +bool CEntity::ProcessContactAction( CEntityOrder* current, int UNUSED(timestep_millis), CEntityOrder::EOrderType transition, SEntityAction* action ) { HEntity target = current->m_target_entity; @@ -425,13 +427,13 @@ bool CEntity::ProcessContactAction( CEntityOrder* current, size_t UNUSED(timeste } } -bool CEntity::ProcessContactActionNoPathing( CEntityOrder* current, size_t timestep_millis, const CStr& animation, CScriptEvent* contactEvent, SEntityAction* action ) +bool CEntity::ProcessContactActionNoPathing( CEntityOrder* current, int timestep_millis, const CStr& animation, CScriptEvent* contactEvent, SEntityAction* action ) { HEntity target = current->m_target_entity; if( m_fsm_cyclepos != NOT_IN_CYCLE ) { - size_t nextpos = m_fsm_cyclepos + timestep_millis * 2; + int nextpos = m_fsm_cyclepos + timestep_millis * 2; if( ( m_fsm_cyclepos <= action->m_Speed ) && ( nextpos > action->m_Speed ) ) { @@ -597,7 +599,7 @@ bool CEntity::ProcessContactActionNoPathing( CEntityOrder* current, size_t times return( false ); } -bool CEntity::ProcessGeneric( CEntityOrder* current, size_t timestep_millis ) +bool CEntity::ProcessGeneric( CEntityOrder* current, int timestep_millis ) { if( m_actions.find( current->m_action ) == m_actions.end() ) { @@ -607,7 +609,7 @@ bool CEntity::ProcessGeneric( CEntityOrder* current, size_t timestep_millis ) return( ProcessContactAction( current, timestep_millis, CEntityOrder::ORDER_GENERIC_NOPATHING, &action_obj ) ); } -bool CEntity::ProcessGenericNoPathing( CEntityOrder* current, size_t timestep_millis ) +bool CEntity::ProcessGenericNoPathing( CEntityOrder* current, int timestep_millis ) { if( m_actions.find( current->m_action ) == m_actions.end() ) { @@ -619,7 +621,7 @@ bool CEntity::ProcessGenericNoPathing( CEntityOrder* current, size_t timestep_mi return( ProcessContactActionNoPathing( current, timestep_millis, action_obj.m_Animation, &evt, &action_obj ) ); } -bool CEntity::ProcessGoto( CEntityOrder* current, size_t UNUSED(timestep_millis) ) +bool CEntity::ProcessGoto( CEntityOrder* current, int UNUSED(timestep_millis) ) { CVector2D pos( m_position.X, m_position.Z ); CVector2D path_to = current->m_target_location; @@ -646,7 +648,7 @@ bool CEntity::ProcessGoto( CEntityOrder* current, size_t UNUSED(timestep_millis) return( true ); } -bool CEntity::ProcessGotoWaypoint( CEntityOrder* current, size_t UNUSED(timestep_milli), bool contact ) +bool CEntity::ProcessGotoWaypoint( CEntityOrder* current, int UNUSED(timestep_milli), bool contact ) { CVector2D pos( m_position.X, m_position.Z ); CVector2D path_to = current->m_target_location; @@ -683,7 +685,7 @@ bool CEntity::ProcessGotoWaypoint( CEntityOrder* current, size_t UNUSED(timestep return( true ); } -bool CEntity::ProcessPatrol( CEntityOrder* current, size_t UNUSED(timestep_millis) ) +bool CEntity::ProcessPatrol( CEntityOrder* current, int UNUSED(timestep_millis) ) { CEntityOrder this_segment; CEntityOrder repeat_patrol; diff --git a/source/simulation/EntitySupport.h b/source/simulation/EntitySupport.h index 1c24c22db1..572d52faf1 100644 --- a/source/simulation/EntitySupport.h +++ b/source/simulation/EntitySupport.h @@ -10,11 +10,11 @@ struct SEntityAction int m_Id; float m_MaxRange; float m_MinRange; - size_t m_Speed; + int m_Speed; CStr8 m_Animation; SEntityAction() : m_Id(0), m_MinRange(0), m_MaxRange(0), m_Speed(1000), m_Animation("walk") {} - SEntityAction(int id, float minRange, float maxRange, size_t speed, CStr8& animation) + SEntityAction(int id, float minRange, float maxRange, int speed, CStr8& animation) : m_Id(id), m_MinRange(minRange), m_MaxRange(maxRange), m_Speed(speed), m_Animation(animation) {} }; diff --git a/source/simulation/EntityTemplate.cpp b/source/simulation/EntityTemplate.cpp index f158f19dce..261b4d97b1 100644 --- a/source/simulation/EntityTemplate.cpp +++ b/source/simulation/EntityTemplate.cpp @@ -287,7 +287,7 @@ bool CEntityTemplate::LoadXml( const CStr& filename ) // Does a property with this name already exist? - for( uint eventID = 0; eventID < EVENT_LAST; eventID++ ) + for( size_t eventID = 0; eventID < EVENT_LAST; eventID++ ) { if( CStrW( EventNames[eventID] ) == EventName ) { @@ -374,7 +374,7 @@ void CEntityTemplate::XMLLoadProperty( const CXeromyces& XeroFile, const XMBElem // Retrieve any attributes it has and add them as subproperties. XMBAttributeList AttributeSet = Source.GetAttributes(); - for( unsigned int AttributeID = 0; AttributeID < (unsigned int)AttributeSet.Count; AttributeID++ ) + for( int AttributeID = 0; AttributeID < AttributeSet.Count; AttributeID++ ) { XMBAttribute Attribute = AttributeSet.Item( AttributeID ); CStrW AttributeName = PropertyName + CStr8( toCamelCase( XeroFile.GetAttributeString( Attribute.Name ) ) ); @@ -391,7 +391,7 @@ void CEntityTemplate::XMLLoadProperty( const CXeromyces& XeroFile, const XMBElem // Retrieve any child nodes the property has and, similarly, add them as subproperties. XMBElementList NodeSet = Source.GetChildNodes(); - for( unsigned int NodeID = 0; NodeID < (unsigned int)NodeSet.Count; NodeID++ ) + for( int NodeID = 0; NodeID < NodeSet.Count; NodeID++ ) { XMBElement Node = NodeSet.Item( NodeID ); XMLLoadProperty( XeroFile, Node, PropertyName ); @@ -485,5 +485,5 @@ CStr CEntityTemplate::ToString( JSContext* UNUSED(cx), uintN UNUSED(argc), jsval if( m_player == 0 ) return "[object EntityTemplate: " + CStr(m_Tag) + " base]"; else - return "[object EntityTemplate: " + CStr(m_Tag) + " for player " + CStr(m_player->GetPlayerID()) + "]"; + return "[object EntityTemplate: " + CStr(m_Tag) + " for player " + CStr((unsigned)m_player->GetPlayerID()) + "]"; } diff --git a/source/simulation/EntityTemplateCollection.cpp b/source/simulation/EntityTemplateCollection.cpp index d65d904a52..f043d32d1a 100644 --- a/source/simulation/EntityTemplateCollection.cpp +++ b/source/simulation/EntityTemplateCollection.cpp @@ -42,7 +42,7 @@ int CEntityTemplateCollection::LoadTemplates() // Load the no-player version of this template (used by techs for base values) GetTemplate( it->first, 0 ); - for( uint i=0; i<=g_Game->GetNumPlayers(); i++ ) + for( size_t i=0; i<=g_Game->GetNumPlayers(); i++ ) { // TODO: Load the template just once and clone it to get these player templates GetTemplate( it->first, g_Game->GetPlayer(i) ); @@ -55,7 +55,7 @@ int CEntityTemplateCollection::LoadTemplates() CEntityTemplate* CEntityTemplateCollection::GetTemplate( const CStrW& name, CPlayer* player ) { // Find player ID - int id = ( player == 0 ? NULL_PLAYER : player->GetPlayerID() ); + size_t id = ( player == 0 ? NULL_PLAYER : player->GetPlayerID() ); // Check whether this template has already been loaded TemplateMap::iterator it = m_templates[id].find( name ); @@ -93,7 +93,7 @@ void CEntityTemplateCollection::GetEntityTemplateNames( std::vector& name void CEntityTemplateCollection::GetPlayerTemplates( CPlayer* player, std::vector& dest ) { - int id = ( player == 0 ? NULL_PLAYER : player->GetPlayerID() ); + size_t id = ( player == 0 ? NULL_PLAYER : player->GetPlayerID() ); for( TemplateMap::iterator it = m_templates[id].begin(); it != m_templates[id].end(); ++it ) { diff --git a/source/simulation/EntityTemplateCollection.h b/source/simulation/EntityTemplateCollection.h index 5cf378f02c..37244d3733 100644 --- a/source/simulation/EntityTemplateCollection.h +++ b/source/simulation/EntityTemplateCollection.h @@ -31,7 +31,7 @@ class CEntityTemplateCollection : public Singleton // TODO: PS_MAX_PLAYERS doesn't seem to be an upper limit - // "This may be overridden by system.cfg ("max_players")" // - so we shouldn't use it here - static const uint NULL_PLAYER = (PS_MAX_PLAYERS+1); + static const size_t NULL_PLAYER = (PS_MAX_PLAYERS+1); typedef STL_HASH_MAP TemplateMap; typedef STL_HASH_MAP TemplateFilenameMap; diff --git a/source/simulation/Formation.cpp b/source/simulation/Formation.cpp index dc69a996b0..2e876c14f4 100644 --- a/source/simulation/Formation.cpp +++ b/source/simulation/Formation.cpp @@ -110,9 +110,9 @@ bool CFormation::LoadXml(const CStr& filename) } XMBElementList RootChildren = Root.GetChildNodes(); - int file=0; - int rank=0; - int maxrank=0; + size_t file=0; + size_t rank=0; + size_t maxrank=0; //Read in files and ranks for (int i = 0; i < RootChildren.Count; ++i) @@ -142,7 +142,7 @@ bool CFormation::LoadXml(const CStr& filename) //error XMBAttributeList RankAttribList = Rank.GetAttributes(); - int order = CStr( RankAttribList.GetNamedItem(at_order) ).ToInt(); + size_t order = CStr( RankAttribList.GetNamedItem(at_order) ).ToInt(); CStr category = CStr( RankAttribList.GetNamedItem(at_category) ); if( order <= 0 ) @@ -175,7 +175,7 @@ bool CFormation::LoadXml(const CStr& filename) //Here we check to make sure no order was skipped over. If so, failure, because we rely //on a linearly accessible slots in entityformation.cpp. - for ( int i=0; i m_slots; + std::map m_slots; bool LoadXml(const CStr& filename); - void AssignCategory(int order, CStr category); //takes care of formatting strings + void AssignCategory(size_t order, CStr category); //takes care of formatting strings }; #endif - - diff --git a/source/simulation/FormationManager.cpp b/source/simulation/FormationManager.cpp index 2380b0b2af..8438b3e9cd 100644 --- a/source/simulation/FormationManager.cpp +++ b/source/simulation/FormationManager.cpp @@ -66,7 +66,7 @@ void CFormationManager::DestroyFormation( size_t form ) m_formations.erase( it ); UpdateIndexes( form ); } -bool CFormationManager::AddUnit( CEntity* entity, int& form ) +bool CFormationManager::AddUnit( CEntity* entity, size_t& form ) { if ( !IsValidFormation(form) ) return false; @@ -91,7 +91,7 @@ bool CFormationManager::AddUnit( CEntity* entity, int& form ) } return false; } -CEntityList CFormationManager::AddUnitList( CEntityList& entities, int form ) +CEntityList CFormationManager::AddUnitList( CEntityList& entities, size_t form ) { CEntityList accepted; for ( CEntityList::iterator it=entities.begin(); it != entities.end(); it++ ) @@ -132,7 +132,7 @@ bool CFormationManager::RemoveUnitList( CEntityList& entities ) } return true; } -CEntityFormation* CFormationManager::GetFormation(int form) +CEntityFormation* CFormationManager::GetFormation(size_t form) { if ( IsValidFormation(form) ) return m_formations[form]; diff --git a/source/simulation/FormationManager.h b/source/simulation/FormationManager.h index b0d6bba9d5..d39778c5ad 100644 --- a/source/simulation/FormationManager.h +++ b/source/simulation/FormationManager.h @@ -26,17 +26,17 @@ public: void CreateFormation( CEntityList& entities, CStrW& name ); //entity is any unit in the formation void DestroyFormation( size_t form ); - inline bool IsValidFormation( int index ) + inline bool IsValidFormation( size_t index ) { return ((size_t)index < m_formations.size() && index >= 0); } - bool AddUnit( CEntity* entity, int& form ); - CEntityList AddUnitList( CEntityList& entities, int form ); + bool AddUnit( CEntity* entity, size_t& form ); + CEntityList AddUnitList( CEntityList& entities, size_t form ); //Returns false if the formation is destroyed bool RemoveUnit( CEntity* entity ); bool RemoveUnitList( CEntityList& entities ); - CEntityFormation* GetFormation(int form); + CEntityFormation* GetFormation(size_t form); void UpdateIndexes( size_t update ); private: diff --git a/source/simulation/LOSManager.cpp b/source/simulation/LOSManager.cpp index fabf628ca8..9e69853eb2 100644 --- a/source/simulation/LOSManager.cpp +++ b/source/simulation/LOSManager.cpp @@ -15,7 +15,7 @@ #include "lib/timer.h" -CLOSManager::CLOSManager() : m_LOSSetting(0), m_FogOfWar(true) +CLOSManager::CLOSManager() : m_LOSSetting(LOS_SETTING_NORMAL), m_FogOfWar(true) { #ifdef _2_los m_Explored = 0; @@ -38,7 +38,7 @@ CLOSManager::~CLOSManager() #endif } -void CLOSManager::Initialize(uint losSetting, bool fogOfWar) +void CLOSManager::Initialize(ELOSSetting losSetting, bool fogOfWar) { // Set special LOS setting m_LOSSetting = losSetting; @@ -63,23 +63,23 @@ void CLOSManager::Initialize(uint losSetting, bool fogOfWar) // Set initial values #ifdef _2_los - uint explored_value = (m_LOSSetting == EXPLORED || m_LOSSetting == ALL_VISIBLE)? 0xFF : 0; - uint vis_value = (m_LOSSetting == ALL_VISIBLE)? 0xFF : 0; + int explored_value = (m_LOSSetting == LOS_SETTING_EXPLORED || m_LOSSetting == LOS_SETTING_ALL_VISIBLE)? 0xFF : 0; + int vis_value = (m_LOSSetting == LOS_SETTING_ALL_VISIBLE)? 0xFF : 0; #else u16 vis_value = 0; - if(m_LOSSetting == EXPLORED || m_LOSSetting == ALL_VISIBLE) + if(m_LOSSetting == LOS_SETTING_EXPLORED || m_LOSSetting == LOS_SETTING_ALL_VISIBLE) for(int i = 0; i < 8; i++) vis_value |= LOS_EXPLORED << (i*2); - if(m_LOSSetting == ALL_VISIBLE || (m_LOSSetting == EXPLORED && !m_FogOfWar) ) + if(m_LOSSetting == LOS_SETTING_ALL_VISIBLE || (m_LOSSetting == LOS_SETTING_EXPLORED && !m_FogOfWar) ) for(int i = 0; i < 8; i++) vis_value |= LOS_VISIBLE << (i*2); #endif - for(uint x=0; xm_los; + ssize_t los = e->m_los; if(los == 0) - { continue; - } #ifdef _2_los - int mask = (1 << e->GetPlayer()->GetPlayerID()); + size_t mask = (size_t(1) << e->GetPlayer()->GetPlayerID()); #else - uint shift = e->GetPlayer()->GetPlayerID()*2; + size_t shift = e->GetPlayer()->GetPlayerID()*2; #endif - int cx, cz; + ssize_t cx, cz; CTerrain::CalcFromPosition(e->m_position.X, e->m_position.Z, cx, cz); - int minX = std::max(cx-los, 0); - int minZ = std::max(cz-los, 0); - int maxX = std::min(cx+los, (int)m_TilesPerSide_1); - int maxZ = std::min(cz+los, (int)m_TilesPerSide_1); + ssize_t minX = std::max(cx-los, ssize_t(0)); + ssize_t minZ = std::max(cz-los, ssize_t(0)); + ssize_t maxX = std::min(cx+los, ssize_t(m_TilesPerSide_1)); + ssize_t maxZ = std::min(cz+los, ssize_t(m_TilesPerSide_1)); - for(int x=minX; x<=maxX; x++) + for(ssize_t x=minX; x<=maxX; x++) { - for(int z=minZ; z<=maxZ; z++) + for(ssize_t z=minZ; z<=maxZ; z++) { if((x-cx)*(x-cx) + (z-cz)*(z-cz) <= los*los) { @@ -162,10 +160,10 @@ void CLOSManager::Update() } -uint LOS_GetTokenFor(uint player_id) +size_t LOS_GetTokenFor(size_t player_id) { #ifdef _2_los - return 1u << player_id; + return size_t(1) << player_id; #else return player_id*2; #endif @@ -173,13 +171,13 @@ uint LOS_GetTokenFor(uint player_id) //TIMER_ADD_CLIENT(tc_getstatus); -ELOSStatus CLOSManager::GetStatus(int tx, int tz, CPlayer* player) +ELOSStatus CLOSManager::GetStatus(ssize_t tx, ssize_t tz, CPlayer* player) { //TIMER_ACCRUE(tc_getstatus); // Ensure that units off the map don't cause the visibility arrays to be // accessed out of bounds - if ((unsigned)tx >= m_TilesPerSide || (unsigned)tz >= m_TilesPerSide) + if ((size_t)tx >= m_TilesPerSide || (size_t)tz >= m_TilesPerSide) return LOS_VISIBLE; // because we don't want them to be permanently hidden // TODO: Make the mask depend on the player's diplomacy (just OR all his allies' masks) @@ -187,11 +185,11 @@ ELOSStatus CLOSManager::GetStatus(int tx, int tz, CPlayer* player) #ifdef _2_los const int mask = player->GetLOSToken(); - if((m_Visible[tx][tz] & mask) || m_LOSSetting == ALL_VISIBLE) + if((m_Visible[tx][tz] & mask) || m_LOSSetting == LOS_SETTING_ALL_VISIBLE) { return LOS_VISIBLE; } - else if((m_Explored[tx][tz] & mask) || m_LOSSetting == EXPLORED) + else if((m_Explored[tx][tz] & mask) || m_LOSSetting == LOS_SETTING_EXPLORED) { return LOS_EXPLORED; } @@ -200,7 +198,7 @@ ELOSStatus CLOSManager::GetStatus(int tx, int tz, CPlayer* player) return LOS_UNEXPLORED; } #else - const uint shift = player->GetLOSToken(); + const size_t shift = player->GetLOSToken(); return (ELOSStatus)((m_VisibilityMatrix[tx][tz] >> shift) & 3); #endif } @@ -208,7 +206,7 @@ ELOSStatus CLOSManager::GetStatus(int tx, int tz, CPlayer* player) ELOSStatus CLOSManager::GetStatus(float fx, float fz, CPlayer* player) { - int ix, iz; + ssize_t ix, iz; CTerrain::CalcFromPosition(fx, fz, ix, iz); return GetStatus(ix, iz, player); } diff --git a/source/simulation/LOSManager.h b/source/simulation/LOSManager.h index 7c0d6f3209..a9924363a4 100644 --- a/source/simulation/LOSManager.h +++ b/source/simulation/LOSManager.h @@ -27,6 +27,14 @@ enum ELOSStatus LOS_UNEXPLORED = 0 // tile is unexplored and therefore in Shroud of Darkness }; +// if changing these values, adapt ScriptGlue!RevealMap +enum ELOSSetting +{ + LOS_SETTING_NORMAL, + LOS_SETTING_EXPLORED, + LOS_SETTING_ALL_VISIBLE +}; + enum EUnitLOSStatus { UNIT_VISIBLE = 2, // unit is in LOS of one of the player's units @@ -34,7 +42,7 @@ enum EUnitLOSStatus UNIT_HIDDEN = 0 // unit is either not permanent or was never seen before }; -extern uint LOS_GetTokenFor(uint player_id); +extern size_t LOS_GetTokenFor(size_t player_id); class CLOSManager { @@ -48,25 +56,23 @@ class CLOSManager u16** m_VisibilityMatrix; #endif - uint m_TilesPerSide; - uint m_TilesPerSide_1; // as above, -1 + size_t m_TilesPerSide; + size_t m_TilesPerSide_1; // as above, -1 public: - static const int NORMAL = 0; - static const int EXPLORED = 1; - static const int ALL_VISIBLE = 2; - int m_LOSSetting; + + ELOSSetting m_LOSSetting; bool m_FogOfWar; CLOSManager(); ~CLOSManager(); - void Initialize(uint losSetting, bool fogOfWar); // 0 = normal, 1 = explored, 2 = all visible + void Initialize(ELOSSetting losSetting, bool fogOfWar); void Update(); // Get LOS status for a tile (in tile coordinates) - ELOSStatus GetStatus(int tx, int tz, CPlayer* player); + ELOSStatus GetStatus(ssize_t tx, ssize_t tz, CPlayer* player); // Get LOS status for a point (in game coordinates) ELOSStatus GetStatus(float fx, float fz, CPlayer* player); diff --git a/source/simulation/ProductionQueue.cpp b/source/simulation/ProductionQueue.cpp index 47a584bc6c..0dfc209820 100644 --- a/source/simulation/ProductionQueue.cpp +++ b/source/simulation/ProductionQueue.cpp @@ -16,7 +16,7 @@ CProductionItem::~CProductionItem() { } -void CProductionItem::Update( size_t timestep ) +void CProductionItem::Update( int timestep ) { m_elapsedTime = std::min( m_totalTime, m_elapsedTime + timestep/1000.0f ); } @@ -78,7 +78,7 @@ void CProductionQueue::CancelAll() m_items.clear(); } -void CProductionQueue::Update( size_t timestep ) +void CProductionQueue::Update( int timestep ) { if( !m_items.empty() ) { diff --git a/source/simulation/ProductionQueue.h b/source/simulation/ProductionQueue.h index bf48345454..19ada83fea 100644 --- a/source/simulation/ProductionQueue.h +++ b/source/simulation/ProductionQueue.h @@ -18,7 +18,7 @@ public: CProductionItem( int type, const CStrW& name, float totalTime ); ~CProductionItem(); - void Update( size_t timestep ); + void Update( int timestep ); bool IsComplete(); float GetProgress(); @@ -37,7 +37,7 @@ public: ~CProductionQueue(); void AddItem( int type, const CStrW& name, float totalTime ); - void Update( size_t timestep ); + void Update( int timestep ); void CancelAll(); jsval JSI_GetLength( JSContext* cx ); diff --git a/source/simulation/Projectile.cpp b/source/simulation/Projectile.cpp index cc86da97dd..ce63a74e5e 100644 --- a/source/simulation/Projectile.cpp +++ b/source/simulation/Projectile.cpp @@ -52,7 +52,7 @@ CProjectile::~CProjectile() delete( m_Actor ); } -bool CProjectile::Update( size_t timestep_millis ) +bool CProjectile::Update( int timestep_millis ) { m_Position_Previous = m_Position; m_Position.X += timestep_millis * m_Axis.x * m_Speed_H; @@ -90,7 +90,7 @@ bool CProjectile::Update( size_t timestep_millis ) return( true ); } -void CProjectile::Interpolate( size_t timestep_millis ) +void CProjectile::Interpolate( int timestep_millis ) { m_Position_Graphics.X = m_Position_Previous.X + timestep_millis * m_Speed_H * m_Axis.x; m_Position_Graphics.Z = m_Position_Previous.Z + timestep_millis * m_Speed_H * m_Axis.y; @@ -123,7 +123,7 @@ void CProjectile::ScriptingInit() CJSObject::ScriptingInit( "Projectile", Construct, 4 ); } -JSBool CProjectile::Construct( JSContext* cx, JSObject* UNUSED(obj), uint argc, jsval* argv, jsval* rval ) +JSBool CProjectile::Construct( JSContext* cx, JSObject* UNUSED(obj), uintN argc, jsval* argv, jsval* rval ) { debug_assert( argc >= 4 ); CStr ModelString; @@ -263,7 +263,7 @@ void CProjectileManager::DeleteProjectile( CProjectile* p ) delete p; } -void CProjectileManager::UpdateAll( size_t timestep ) +void CProjectileManager::UpdateAll( int timestep ) { m_LastTurnLength = timestep; @@ -289,7 +289,7 @@ void CProjectileManager::UpdateAll( size_t timestep ) void CProjectileManager::InterpolateAll( double relativeOffset ) { - size_t absoluteOffset = (size_t)( (double)m_LastTurnLength * relativeOffset ); + int absoluteOffset = (int)( m_LastTurnLength * relativeOffset ); std::list::iterator it; for( it = m_Projectiles.begin(); it != m_Projectiles.end(); ++it ) (*it)->Interpolate( absoluteOffset ); diff --git a/source/simulation/Projectile.h b/source/simulation/Projectile.h index dc0757ba10..bffcf428f9 100644 --- a/source/simulation/Projectile.h +++ b/source/simulation/Projectile.h @@ -44,14 +44,14 @@ class CProjectile : public CJSObject, public IEventTarget ~CProjectile(); // Updates gameplay information for the specified timestep. Returns 'false' if the projectile should be removed from the world. - bool Update( size_t timestep_millis ); + bool Update( int timestep_millis ); // Updates graphical information for a point timestep_millis after the previous simulation frame (and before the current one) - void Interpolate( size_t timestep_millis ); + void Interpolate( int timestep_millis ); // Scripty things. public: static void ScriptingInit(); - static JSBool Construct( JSContext* cx, JSObject* obj, uint argc, jsval* argv, jsval* rval ); + static JSBool Construct( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval ); JSObject* GetScriptExecContext( IEventTarget* UNUSED(target) ) { return( GetScript() ); } inline CModel* GetModel() const { return( m_Actor ); } @@ -87,7 +87,7 @@ public: void DeleteAll(); - void UpdateAll( size_t timestep ); + void UpdateAll( int timestep ); void InterpolateAll( double frametime ); inline const std::list& GetProjectiles() { return m_Projectiles; } @@ -98,7 +98,7 @@ public: void DeleteProjectile( CProjectile* p ); private: // Keep this so we can go from relative->absolute offsets in interpolate. - size_t m_LastTurnLength; + int m_LastTurnLength; // Maintain a list of the projectiles in the world std::list m_Projectiles; diff --git a/source/simulation/Scheduler.cpp b/source/simulation/Scheduler.cpp index 39162c7ae7..fab5cfc76c 100644 --- a/source/simulation/Scheduler.cpp +++ b/source/simulation/Scheduler.cpp @@ -2,16 +2,16 @@ #include "Scheduler.h" #include "Entity.h" -size_t simulationTime; -size_t frameCount; +int simulationTime; +int frameCount; /* -void CScheduler::PushTime( size_t delay, const HEntity& destination, const CMessage* message ) +void CScheduler::PushTime( int delay, const HEntity& destination, const CMessage* message ) { timeMessage.push( SDispatchObjectMessage( destination, simulationTime + delay, message ) ); } -void CScheduler::PushFrame( size_t delay, const HEntity& destination, const CMessage* message ) +void CScheduler::PushFrame( int delay, const HEntity& destination, const CMessage* message ) { frameMessage.push( SDispatchObjectMessage( destination, frameCount + delay, message ) ); } @@ -22,19 +22,19 @@ CScheduler::CScheduler() m_nextTaskId = 1; } -int CScheduler::PushTime( size_t delay, const CStrW& fragment, JSObject* operateOn ) +int CScheduler::PushTime( int delay, const CStrW& fragment, JSObject* operateOn ) { timeScript.push( SDispatchObjectScript( m_nextTaskId, fragment, simulationTime + delay, operateOn ) ); return m_nextTaskId++; } -int CScheduler::PushFrame( size_t delay, const CStrW& fragment, JSObject* operateOn ) +int CScheduler::PushFrame( int delay, const CStrW& fragment, JSObject* operateOn ) { frameScript.push( SDispatchObjectScript( m_nextTaskId, fragment, frameCount + delay, operateOn ) ); return m_nextTaskId++; } -int CScheduler::PushInterval( size_t first, size_t interval, const CStrW& fragment, JSObject* operateOn, int id ) +int CScheduler::PushInterval( int first, int interval, const CStrW& fragment, JSObject* operateOn, int id ) { if( !id ) id = m_nextTaskId++; @@ -42,19 +42,19 @@ int CScheduler::PushInterval( size_t first, size_t interval, const CStrW& fragme return id++; } -int CScheduler::PushTime( size_t delay, JSFunction* script, JSObject* operateOn ) +int CScheduler::PushTime( int delay, JSFunction* script, JSObject* operateOn ) { timeFunction.push( SDispatchObjectFunction( m_nextTaskId, script, simulationTime + delay, operateOn ) ); return m_nextTaskId++; } -int CScheduler::PushFrame( size_t delay, JSFunction* script, JSObject* operateOn ) +int CScheduler::PushFrame( int delay, JSFunction* script, JSObject* operateOn ) { frameFunction.push( SDispatchObjectFunction( m_nextTaskId, script, frameCount + delay, operateOn ) ); return m_nextTaskId++; } -int CScheduler::PushInterval( size_t first, size_t interval, JSFunction* function, JSObject* operateOn, int id ) +int CScheduler::PushInterval( int first, int interval, JSFunction* function, JSObject* operateOn, int id ) { if( !id ) id = m_nextTaskId++; @@ -72,7 +72,7 @@ void CScheduler::CancelTask( int id ) tasksToCancel.insert( id ); } -void CScheduler::Update(size_t simElapsed) +void CScheduler::Update(int simElapsed) { simulationTime += simElapsed; frameCount++; @@ -174,7 +174,7 @@ void CJSProgressTimer::ScriptingInit() CJSObject::ScriptingInit( "ProgressTimer", Construct, 2 ); } -JSBool CJSProgressTimer::Construct( JSContext* cx, JSObject* UNUSED(obj), uint argc, jsval* argv, jsval* rval ) +JSBool CJSProgressTimer::Construct( JSContext* cx, JSObject* UNUSED(obj), uintN argc, jsval* argv, jsval* rval ) { debug_assert( argc >= 2 ); double max = ToPrimitive( argv[0] ); diff --git a/source/simulation/Scheduler.h b/source/simulation/Scheduler.h index 7c21459482..57995ae5f7 100644 --- a/source/simulation/Scheduler.h +++ b/source/simulation/Scheduler.h @@ -21,11 +21,11 @@ class CJSProgressTimer; struct SDispatchObject { int id; - size_t deliveryTime; - bool isRecurrent; size_t delay; - SDispatchObject( int _id, const size_t _deliveryTime ) + int deliveryTime; + bool isRecurrent; int delay; + SDispatchObject( int _id, const int _deliveryTime ) : id(_id), deliveryTime( _deliveryTime ), isRecurrent( false ) {} - SDispatchObject( int _id, const size_t _deliveryTime, const size_t _recurrence ) + SDispatchObject( int _id, const int _deliveryTime, const int _recurrence ) : id(_id), deliveryTime( _deliveryTime ), isRecurrent( true ), delay( _recurrence ) {} inline bool operator<( const SDispatchObject& compare ) const { @@ -38,10 +38,10 @@ struct SDispatchObjectScript : public SDispatchObject CStrW script; JSObject* operateOn; inline SDispatchObjectScript( int _id, const CStrW& _script, - const size_t _deliveryTime, JSObject* _operateOn = NULL ) + const int _deliveryTime, JSObject* _operateOn = NULL ) : SDispatchObject( _id, _deliveryTime ), script( _script ), operateOn( _operateOn ) {} inline SDispatchObjectScript( int _id, const CStrW& _script, - const size_t _deliveryTime, JSObject* _operateOn, const size_t recurrence ) + const int _deliveryTime, JSObject* _operateOn, const int recurrence ) : SDispatchObject( _id, _deliveryTime, recurrence ), script( _script ), operateOn( _operateOn ) {} }; @@ -50,10 +50,10 @@ struct SDispatchObjectFunction : public SDispatchObject JSFunction* function; JSObject* operateOn; inline SDispatchObjectFunction( int _id, JSFunction* _function, - const size_t _deliveryTime, JSObject* _operateOn = NULL ) + const int _deliveryTime, JSObject* _operateOn = NULL ) : SDispatchObject( _id, _deliveryTime ), function( _function ), operateOn( _operateOn ) {} inline SDispatchObjectFunction( int _id, JSFunction* _function, - const size_t _deliveryTime, JSObject* _operateOn, const size_t recurrence ) + const int _deliveryTime, JSObject* _operateOn, const int recurrence ) : SDispatchObject( _id, _deliveryTime, recurrence ), function( _function ), operateOn( _operateOn ) {} }; @@ -67,15 +67,15 @@ struct CScheduler : public Singleton STL_HASH_SET tasksToCancel; CScheduler(); - int PushTime( size_t delay, const CStrW& fragment, JSObject* operateOn = NULL ); - int PushFrame( size_t delay, const CStrW& fragment, JSObject* operateOn = NULL ); - int PushInterval( size_t first, size_t interval, const CStrW& fragment, JSObject* operateOn = NULL, int id = 0 ); - int PushTime( size_t delay, JSFunction* function, JSObject* operateOn = NULL ); - int PushFrame( size_t delay, JSFunction* function, JSObject* operateOn = NULL ); - int PushInterval( size_t first, size_t interval, JSFunction* function, JSObject* operateOn = NULL, int id = 0 ); + int PushTime( int delay, const CStrW& fragment, JSObject* operateOn = NULL ); + int PushFrame( int delay, const CStrW& fragment, JSObject* operateOn = NULL ); + int PushInterval( int first, int interval, const CStrW& fragment, JSObject* operateOn = NULL, int id = 0 ); + int PushTime( int delay, JSFunction* function, JSObject* operateOn = NULL ); + int PushFrame( int delay, JSFunction* function, JSObject* operateOn = NULL ); + int PushInterval( int first, int interval, JSFunction* function, JSObject* operateOn = NULL, int id = 0 ); void PushProgressTimer( CJSProgressTimer* progressTimer ); void CancelTask( int id ); - void Update(size_t elapsedSimulationTime); + void Update(int elapsedSimulationTime); }; #define g_Scheduler CScheduler::GetSingleton() @@ -87,14 +87,14 @@ class CJSProgressTimer : public CJSObject JSFunction* m_Callback; JSObject* m_OperateOn; CJSProgressTimer( double Max, double Increment, JSFunction* Callback, JSObject* OperateOn ); - static JSBool Construct( JSContext* cx, JSObject* obj, uint argc, jsval* argv, jsval* rval ); + static JSBool Construct( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval ); public: static void ScriptingInit(); }; // made visible to main.cpp's Frame() so that it can abort after 100 frames // if g_FixedFrameTiming == true (allows measuring performance). -extern size_t frameCount; +extern int frameCount; extern const int ORDER_DELAY; diff --git a/source/simulation/Simulation.cpp b/source/simulation/Simulation.cpp index 1a4746c53b..6adf419eba 100644 --- a/source/simulation/Simulation.cpp +++ b/source/simulation/Simulation.cpp @@ -148,7 +148,7 @@ void CSimulation::Interpolate(double frameTime, double offset) void CSimulation::Simulate() { - uint time = m_pTurnManager->GetTurnLength(); + int time = m_pTurnManager->GetTurnLength(); m_Time += time / 1000.0f; #ifdef DEBUG_SYNCHRONIZATION @@ -275,7 +275,7 @@ void QueueOrder(CEntityOrder order, const std::vector &entities, bool i } } -uint CSimulation::TranslateMessage(CNetMessage* pMsg, uint clientMask, void* UNUSED(userdata)) +size_t CSimulation::TranslateMessage(CNetMessage* pMsg, size_t clientMask, void* UNUSED(userdata)) { CEntityOrder order; bool isQueued = true; @@ -410,7 +410,7 @@ uint CSimulation::TranslateMessage(CNetMessage* pMsg, uint clientMask, void* UNU return clientMask; } -uint CSimulation::GetMessageMask(CNetMessage* UNUSED(pMsg), uint UNUSED(oldMask), void* UNUSED(userdata)) +size_t CSimulation::GetMessageMask(CNetMessage* UNUSED(pMsg), size_t UNUSED(oldMask), void* UNUSED(userdata)) { //CSimulation *pSimulation=(CSimulation *)userdata; diff --git a/source/simulation/Simulation.h b/source/simulation/Simulation.h index 4879fa1862..ef69e27747 100644 --- a/source/simulation/Simulation.h +++ b/source/simulation/Simulation.h @@ -56,11 +56,11 @@ public: void Interpolate(double frameTime); // Calculate the message mask of a message to be queued - static uint GetMessageMask(CNetMessage *, uint oldMask, void *userdata); + static size_t GetMessageMask(CNetMessage *, size_t oldMask, void *userdata); // Translate the command message into an entity order and queue it // Returns oldMask - static uint TranslateMessage(CNetMessage *, uint oldMask, void *userdata); + static size_t TranslateMessage(CNetMessage *, size_t oldMask, void *userdata); void QueueLocalCommand(CNetMessage *pMsg); diff --git a/source/simulation/Technology.cpp b/source/simulation/Technology.cpp index 38fe975b48..f362e5948d 100644 --- a/source/simulation/Technology.cpp +++ b/source/simulation/Technology.cpp @@ -421,7 +421,7 @@ void CTechnology::ScriptingInit() AddMethod( "isExcluded", 0 ); AddMethod( "isValid", 0 ); AddMethod( "isResearched", 0 ); - AddMethod( "getPlayerID", 0 ); + AddMethod( "getPlayerID", 0 ); CJSComplex::ScriptingInit("Technology"); } @@ -483,7 +483,7 @@ bool CTechnology::IsResearched( JSContext* UNUSED(cx), uintN UNUSED(argc), jsval return IsResearched(); } -int CTechnology::GetPlayerID( JSContext* UNUSED(cx), uintN UNUSED(argc), jsval* UNUSED(argv) ) +size_t CTechnology::GetPlayerID( JSContext* UNUSED(cx), uintN UNUSED(argc), jsval* UNUSED(argv) ) { return m_player->GetPlayerID(); } diff --git a/source/simulation/Technology.h b/source/simulation/Technology.h index c22c5fcaa4..82c78678a6 100644 --- a/source/simulation/Technology.h +++ b/source/simulation/Technology.h @@ -46,7 +46,7 @@ public: bool IsValid( JSContext* cx, uintN argc, jsval* argv ); bool IsResearched( JSContext* cx, uintN argc, jsval* argv ); bool IsExcluded( JSContext* cx, uintN argc, jsval* argv ); - int GetPlayerID( JSContext* cx, uintN argc, jsval* argv ); + size_t GetPlayerID( JSContext* cx, uintN argc, jsval* argv ); void Apply( CEntity* entity ); diff --git a/source/simulation/TechnologyCollection.cpp b/source/simulation/TechnologyCollection.cpp index 61c29efc20..91ee0d7748 100644 --- a/source/simulation/TechnologyCollection.cpp +++ b/source/simulation/TechnologyCollection.cpp @@ -30,7 +30,7 @@ CTechnology* CTechnologyCollection::GetTechnology( const CStrW& name, CPlayer* p { // Find player ID debug_assert( player != 0 ); - int id = player->GetPlayerID(); + const size_t id = player->GetPlayerID(); // Check whether this template has already been loaded. //If previously loaded, all slots will be found, so any entry works. @@ -62,7 +62,7 @@ CTechnology* CTechnologyCollection::GetTechnology( const CStrW& name, CPlayer* p CTechnologyCollection::~CTechnologyCollection() { - for( uint id=0; idsecond ); } diff --git a/source/simulation/TerritoryManager.cpp b/source/simulation/TerritoryManager.cpp index 832e68b0c4..1d4f3f9102 100644 --- a/source/simulation/TerritoryManager.cpp +++ b/source/simulation/TerritoryManager.cpp @@ -72,7 +72,7 @@ void CTerritoryManager::Recalculate() centres.push_back(entities[i]); } - int mapSize = m_TilesPerSide * CELL_SIZE; + const size_t mapSize = m_TilesPerSide * CELL_SIZE; // If there aren't any centre objects, create one big Gaia territory which spans the whole map if( centres.empty() ) @@ -87,9 +87,9 @@ void CTerritoryManager::Recalculate() m_Territories.push_back(ter); - for( uint x=0; x& centres, size_t myIndex, std::vector& boundary ) { // Start with a boundary equal to the whole map - int mapSize = m_TilesPerSide * CELL_SIZE; + const size_t mapSize = m_TilesPerSide * CELL_SIZE; boundary.push_back( CVector2D(0, 0) ); boundary.push_back( CVector2D(0, mapSize) ); boundary.push_back( CVector2D(mapSize, mapSize) ); diff --git a/source/simulation/TerritoryManager.h b/source/simulation/TerritoryManager.h index 516e5a5d25..b9ede27dcd 100644 --- a/source/simulation/TerritoryManager.h +++ b/source/simulation/TerritoryManager.h @@ -42,7 +42,7 @@ class CTerritoryManager std::vector m_Territories; CTerritory*** m_TerritoryMatrix; // m_TerritoryMatrix[x][z] points to the territory for tile (x, z) - uint m_TilesPerSide; + size_t m_TilesPerSide; bool m_DelayedRecalculate; public: diff --git a/source/simulation/TriggerManager.cpp b/source/simulation/TriggerManager.cpp index 2d76ef0cae..43806dca87 100644 --- a/source/simulation/TriggerManager.cpp +++ b/source/simulation/TriggerManager.cpp @@ -46,7 +46,7 @@ CTrigger::CTrigger(const CStrW& name, bool active, float delay, int maxRuns, m_effectFunction = effectFunc; } -JSBool CTrigger::Construct( JSContext* cx, JSObject* UNUSED(obj), uint argc, jsval* argv, jsval* rval ) +JSBool CTrigger::Construct( JSContext* cx, JSObject* UNUSED(obj), uintN argc, jsval* argv, jsval* rval ) { JSU_REQUIRE_PARAMS_CPP(6); @@ -103,11 +103,11 @@ bool CTrigger::Fire() return (m_runCount < m_maxRunCount); } -void CTrigger::Activate(JSContext* UNUSED(cx), uint UNUSED(argc), jsval* UNUSED(argv)) +void CTrigger::Activate(JSContext* UNUSED(cx), size_t UNUSED(argc), jsval* UNUSED(argv)) { m_active = true; } -void CTrigger::Deactivate(JSContext* UNUSED(cx), uint UNUSED(argc), jsval* UNUSED(argv)) +void CTrigger::Deactivate(JSContext* UNUSED(cx), size_t UNUSED(argc), jsval* UNUSED(argv)) { m_active = false; } diff --git a/source/simulation/TriggerManager.h b/source/simulation/TriggerManager.h index 0e0accab8d..cd5e689b49 100644 --- a/source/simulation/TriggerManager.h +++ b/source/simulation/TriggerManager.h @@ -115,10 +115,10 @@ public: //Returns false if trigger exceeds run count bool Fire(); - void Activate(JSContext* cx, uint argc, jsval* argv); - void Deactivate(JSContext* cx, uint argc, jsval* argv); + void Activate(JSContext* cx, uintN argc, jsval* argv); + void Deactivate(JSContext* cx, uintN argc, jsval* argv); - static JSBool Construct( JSContext* cx, JSObject* obj, uint argc, jsval* argv, jsval* rval ); + static JSBool Construct( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval ); static void ScriptingInit(); JSContext* m_cx; diff --git a/source/simulation/TurnManager.cpp b/source/simulation/TurnManager.cpp index d47a58ae81..8377d32598 100644 --- a/source/simulation/TurnManager.cpp +++ b/source/simulation/TurnManager.cpp @@ -16,7 +16,7 @@ CTurnManager::CTurnManager() m_Batches[i].m_TurnLength = DEFAULT_TURN_LENGTH; } -void CTurnManager::ClearBatch(uint batch) +void CTurnManager::ClearBatch(uintptr_t batch) { typedef std::vector MsgVector; MsgVector &messages=m_Batches[batch].m_Messages; @@ -48,7 +48,7 @@ void CTurnManager::RotateBatches() m_Batches[1].Swap(m_Batches[2]); } -void CTurnManager::IterateBatch(uint batch, BatchIteratorFunc *fp, void *userdata) +void CTurnManager::IterateBatch(uintptr_t batch, BatchIteratorFunc *fp, void *userdata) { typedef std::vector MsgVector; MsgVector &messages=m_Batches[batch].m_Messages; @@ -60,7 +60,7 @@ void CTurnManager::IterateBatch(uint batch, BatchIteratorFunc *fp, void *userdat } } -void CTurnManager::SendBatch(uint batch) +void CTurnManager::SendBatch(uintptr_t batch) { typedef std::vector MsgVector; MsgVector &messages=m_Batches[batch].m_Messages; @@ -72,12 +72,12 @@ void CTurnManager::SendBatch(uint batch) } CEndCommandBatch *pMsg=new CEndCommandBatch(); pMsg->m_TurnLength=m_Batches[batch].m_TurnLength; - SendMessage(pMsg, (uint)-1); + SendMessage(pMsg, (size_t)-1); } -void CTurnManager::SendMessage(CNetMessage *pMsg, uint clientMask) +void CTurnManager::SendMessage(CNetMessage *pMsg, size_t clientMask) { - for (uint i=0;iWriteMessage(&msg); } -uint CTurnManager::RecordIterator(CNetMessage *pMsg, uint clientMask, void *userdata) +size_t CTurnManager::RecordIterator(CNetMessage *pMsg, uintptr_t clientMask, void *userdata) { CGameRecord *pRecord=(CGameRecord *)userdata; @@ -148,4 +148,4 @@ void CSinglePlayerTurnManager::QueueLocalCommand(CNetMessage *pMsg) bool CSinglePlayerTurnManager::NewTurnReady() { return true; -} \ No newline at end of file +} diff --git a/source/simulation/TurnManager.h b/source/simulation/TurnManager.h index 2cd1a8846a..ec996495ae 100644 --- a/source/simulation/TurnManager.h +++ b/source/simulation/TurnManager.h @@ -13,30 +13,30 @@ class CTurnManager { public: // Default turn length - static const uint DEFAULT_TURN_LENGTH = 150; + static const int DEFAULT_TURN_LENGTH = 150; // Used with IterateBatch() to iterate a command batch and set the sync mask // for each message. If the iterating function doesn't wish to change the // mask, it should return oldMask unchanged. - typedef uint (BatchIteratorFunc)(CNetMessage *pMsg, uint oldMask, void *userdata); + typedef uintptr_t (BatchIteratorFunc)(CNetMessage *pMsg, uintptr_t oldMask, void *userdata); // FIXME Should be in CNetServer instead struct SClientTimingData { // The maximum latency observed from this client - uint m_MaxLatency; + int m_MaxLatency; // Approximate current round-trip time in milliseconds - uint m_Latency; + int m_Latency; // Frames per Second - won't be used unless 1000/m_FPS > m_Latency (i.e. // framerate is too slow to handle [m_Latency] as the turn length) - uint m_FPS; + int m_FPS; }; private: struct SMessageSyncEntry { // A bitmask telling which clients to sync this message to - uint m_ClientMask; + uintptr_t m_ClientMask; // The message pointer CNetMessage *m_pMessage; @@ -49,7 +49,7 @@ private: struct SBatch { std::vector m_Messages; - uint m_TurnLength; + int m_TurnLength; void Swap(SBatch &other); }; @@ -72,22 +72,22 @@ protected: // Go through each message in the specified batch and send the message to // each of the clients whose bit in the message's mask is set - void SendBatch(uint batch); - void ClearBatch(uint batch); + void SendBatch(uintptr_t batch); + void ClearBatch(uintptr_t batch); - void SetClientPipe(uint client, IMessagePipeEnd *pipe); + void SetClientPipe(size_t client, IMessagePipeEnd *pipe); // FIXME Should be in CNetServer instead [and implemented] - // void UpdateTimingData(uint client, uint fps, uint currentLatency); - void SetTurnLength(uint batch, uint turnLength); + // void UpdateTimingData(size_t client, int fps, int currentLatency); + void SetTurnLength(uintptr_t batch, int turnLength); - void SendMessage(CNetMessage *pMsg, uint clientMask); + void SendMessage(CNetMessage *pMsg, uintptr_t clientMask); // Add the message to the specified batch. The message is assumed to be // validated before passed here, and will be blindly trusted. - void QueueMessage(uint batch, CNetMessage *pMsg); + void QueueMessage(uintptr_t batch, CNetMessage *pMsg); // Send the specified batch to CGameRecord for recording - void RecordBatch(uint batch); + void RecordBatch(uintptr_t batch); static BatchIteratorFunc RecordIterator; public: @@ -99,7 +99,7 @@ public: // Return the millisecond delay between the last frame and the next. // CSimulation will use this to determine when to perform the deterministic // update and call NewTurn() - uint GetTurnLength(); + int GetTurnLength(); // Called by CSimulation when the current turn time has passed. virtual void NewTurn() = 0; @@ -108,7 +108,7 @@ public: virtual bool NewTurnReady() = 0; // Apply a function to all messages in a given batch. - void IterateBatch(uint batch, BatchIteratorFunc *func, void *userdata); + void IterateBatch(uintptr_t batch, BatchIteratorFunc *func, void *userdata); // Queue a command originating from the local player. virtual void QueueLocalCommand(CNetMessage *pMsg) = 0; diff --git a/source/sound/CPlayList.cpp b/source/sound/CPlayList.cpp index 8fbbea2eaa..8f01a82525 100644 --- a/source/sound/CPlayList.cpp +++ b/source/sound/CPlayList.cpp @@ -38,7 +38,7 @@ void CPlayList::Load(const char* filename) void CPlayList::List() { - for(unsigned int i = 0; i < tracks.size(); i++) + for(size_t i = 0; i < tracks.size(); i++) { debug_printf("%s\n", tracks.at(i).c_str()); } diff --git a/source/sound/JSI_Sound.cpp b/source/sound/JSI_Sound.cpp index 1adb9d9896..4b236cb6f8 100644 --- a/source/sound/JSI_Sound.cpp +++ b/source/sound/JSI_Sound.cpp @@ -171,7 +171,7 @@ CStr JSI_Sound::ToString(JSContext* UNUSED(cx), uintN UNUSED(argc), jsval* UNUSE return "[object Sound: " + h_filename(m_Handle).string() + "]"; } -JSBool JSI_Sound::Construct(JSContext* cx, JSObject* UNUSED(obj), uint argc, jsval* argv, jsval* rval) +JSBool JSI_Sound::Construct(JSContext* cx, JSObject* UNUSED(obj), uintN argc, jsval* argv, jsval* rval) { debug_assert(argc >= 1); // FIXME CStrW filename; diff --git a/source/sound/JSI_Sound.h b/source/sound/JSI_Sound.h index 5308341cba..77d4438d69 100644 --- a/source/sound/JSI_Sound.h +++ b/source/sound/JSI_Sound.h @@ -53,7 +53,7 @@ public: bool Fade ( JSContext* cx, uintN argc, jsval* argv ); - static JSBool Construct( JSContext* cx, JSObject* obj, uint argc, jsval* argv, jsval* rval ); + static JSBool Construct( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval ); static void ScriptingInit(); diff --git a/source/sound/SoundGroup.cpp b/source/sound/SoundGroup.cpp index 5dc267891c..916e2d2a3f 100644 --- a/source/sound/SoundGroup.cpp +++ b/source/sound/SoundGroup.cpp @@ -73,7 +73,7 @@ void CSoundGroup::PlayNext() { // try loading on the fly only when we need the sound to see if that fixes release problems... if(TestFlag(eRandOrder)) - m_index = (size_t)rand(0, (uint)filenames.size()); + m_index = (size_t)rand(0, (size_t)filenames.size()); Handle temp; temp = snd_open(m_filepath + filenames[m_index]); snd_set_gain(temp, m_Gain); diff --git a/source/tools/atlas/GameInterface/Brushes.cpp b/source/tools/atlas/GameInterface/Brushes.cpp index ae5ef52048..5e1d799045 100644 --- a/source/tools/atlas/GameInterface/Brushes.cpp +++ b/source/tools/atlas/GameInterface/Brushes.cpp @@ -20,8 +20,8 @@ public: } void GetTileExtents( - int& min_i_inclusive, int& min_j_inclusive, - int& max_i_inclusive, int& max_j_inclusive) + ssize_t& min_i_inclusive, ssize_t& min_j_inclusive, + ssize_t& max_i_inclusive, ssize_t& max_j_inclusive) { m_Brush->GetBottomLeft(min_i_inclusive, min_j_inclusive); m_Brush->GetTopRight(max_i_inclusive, max_j_inclusive); @@ -32,9 +32,9 @@ public: --max_j_inclusive; } - void ProcessTile(int i, int j) + void ProcessTile(ssize_t i, ssize_t j) { - int i0, j0; + ssize_t i0, j0; m_Brush->GetBottomLeft(i0, j0); // Colour this tile based on the average of the surrounding vertices float avg = ( @@ -59,7 +59,7 @@ Brush::~Brush() delete m_TerrainOverlay; } -void Brush::SetData(int w, int h, const std::vector& data) +void Brush::SetData(ssize_t w, ssize_t h, const std::vector& data) { m_W = w; m_H = h; @@ -69,26 +69,26 @@ void Brush::SetData(int w, int h, const std::vector& data) debug_assert(data.size() == (size_t)(w*h)); } -void Brush::GetCentre(int& x, int& y) const +void Brush::GetCentre(ssize_t& x, ssize_t& y) const { CVector3D c = m_Centre; if (m_W % 2) c.X += CELL_SIZE/2.f; if (m_H % 2) c.Z += CELL_SIZE/2.f; - i32 cx, cy; + ssize_t cx, cy; CTerrain::CalcFromPosition(c, cx, cy); x = cx; y = cy; } -void Brush::GetBottomLeft(int& x, int& y) const +void Brush::GetBottomLeft(ssize_t& x, ssize_t& y) const { GetCentre(x, y); x -= (m_W-1)/2; y -= (m_H-1)/2; } -void Brush::GetTopRight(int& x, int& y) const +void Brush::GetTopRight(ssize_t& x, ssize_t& y) const { GetBottomLeft(x, y); x += m_W-1; diff --git a/source/tools/atlas/GameInterface/Brushes.h b/source/tools/atlas/GameInterface/Brushes.h index 0e47f66b37..78730e8717 100644 --- a/source/tools/atlas/GameInterface/Brushes.h +++ b/source/tools/atlas/GameInterface/Brushes.h @@ -12,21 +12,21 @@ struct Brush Brush(); ~Brush(); - void SetData(int w, int h, const std::vector& data); + void SetData(ssize_t w, ssize_t h, const std::vector& data); void SetRenderEnabled(bool enabled); // initial state is disabled - void GetCentre(int& x, int& y) const; - void GetBottomLeft(int& x, int& y) const; - void GetTopRight(int& x, int& y) const; + void GetCentre(ssize_t& x, ssize_t& y) const; + void GetBottomLeft(ssize_t& x, ssize_t& y) const; + void GetTopRight(ssize_t& x, ssize_t& y) const; - float Get(int x, int y) const + float Get(ssize_t x, ssize_t y) const { debug_assert(x >= 0 && x < m_W && y >= 0 && y < m_H); return m_Data[x + y*m_W]; } - int m_W, m_H; + ssize_t m_W, m_H; CVector3D m_Centre; private: TerrainOverlay* m_TerrainOverlay; // NULL if rendering is not enabled diff --git a/source/tools/atlas/GameInterface/DeltaArray.h b/source/tools/atlas/GameInterface/DeltaArray.h index 3e78cb5301..23a358a9c9 100644 --- a/source/tools/atlas/GameInterface/DeltaArray.h +++ b/source/tools/atlas/GameInterface/DeltaArray.h @@ -6,16 +6,16 @@ template class DeltaArray2D public: virtual ~DeltaArray2D() {} - T get(int x, int y); - void set(int x, int y, const T& val); + T get(ssize_t x, ssize_t y); + void set(ssize_t x, ssize_t y, const T& val); void OverlayWith(const DeltaArray2D& overlayer); void Undo(); void Redo(); protected: - virtual T getOld(int x, int y) = 0; - virtual void setNew(int x, int y, const T& val) = 0; + virtual T getOld(ssize_t x, ssize_t y) = 0; + virtual void setNew(ssize_t x, ssize_t y, const T& val) = 0; private: struct hashfunc { @@ -23,22 +23,22 @@ private: bucket_size = 4, min_buckets = 8 }; - size_t operator()(const std::pair& p) const { + size_t operator()(const std::pair& p) const { return STL_HASH_VALUE(p.first << 16) + STL_HASH_VALUE(p.second); } - bool operator()(const std::pair& a, const std::pair& b) const { + bool operator()(const std::pair& a, const std::pair& b) const { return (a < b); } }; // TODO: more efficient representation - typedef STL_HASH_MAP, std::pair, hashfunc> Data; // map of -> + typedef STL_HASH_MAP, std::pair, hashfunc> Data; // map of -> Data m_Data; }; ////////////////////////////////////////////////////////////////////////// template -T DeltaArray2D::get(int x, int y) +T DeltaArray2D::get(ssize_t x, ssize_t y) { typename Data::iterator it = m_Data.find(std::make_pair(x, y)); if (it == m_Data.end()) @@ -48,7 +48,7 @@ T DeltaArray2D::get(int x, int y) } template -void DeltaArray2D::set(int x, int y, const T& val) +void DeltaArray2D::set(ssize_t x, ssize_t y, const T& val) { typename Data::iterator it = m_Data.find(std::make_pair(x, y)); if (it == m_Data.end()) diff --git a/source/tools/atlas/GameInterface/GameLoop.cpp b/source/tools/atlas/GameInterface/GameLoop.cpp index 10082a03ee..dd17137c09 100644 --- a/source/tools/atlas/GameInterface/GameLoop.cpp +++ b/source/tools/atlas/GameInterface/GameLoop.cpp @@ -68,7 +68,7 @@ static const wchar_t* FindWindowName(const CmdLineArgs& args) return L"ScenarioEditor"; } -static ErrorReaction AtlasDisplayError(const wchar_t* text, uint flags) +static ErrorReaction AtlasDisplayError(const wchar_t* text, int flags) { // TODO: after Atlas has been unloaded, don't do this Atlas_DisplayError(text, flags); diff --git a/source/tools/atlas/GameInterface/Handlers/ElevationHandlers.cpp b/source/tools/atlas/GameInterface/Handlers/ElevationHandlers.cpp index 24fbf67dd9..da42f70231 100644 --- a/source/tools/atlas/GameInterface/Handlers/ElevationHandlers.cpp +++ b/source/tools/atlas/GameInterface/Handlers/ElevationHandlers.cpp @@ -26,18 +26,18 @@ public: m_VertsPerSide = g_Game->GetWorld()->GetTerrain()->GetVerticesPerSide(); } - void RaiseVertex(int x, int y, int amount) + void RaiseVertex(ssize_t x, ssize_t y, int amount) { // Ignore out-of-bounds vertices - if ((unsigned)x >= m_VertsPerSide || (unsigned)y >= m_VertsPerSide) + if (size_t(x) >= size_t(m_VertsPerSide) || size_t(y) >= size_t(m_VertsPerSide)) return; set(x,y, (u16)clamp(get(x,y) + amount, 0, 65535)); } - void MoveVertexTowards(int x, int y, int target, int amount) + void MoveVertexTowards(ssize_t x, ssize_t y, int target, int amount) { - if ((unsigned)x >= m_VertsPerSide || (unsigned)y >= m_VertsPerSide) + if (size_t(x) >= size_t(m_VertsPerSide) || size_t(y) >= size_t(m_VertsPerSide)) return; int h = get(x,y); @@ -51,31 +51,31 @@ public: set(x,y, (u16)clamp(h, 0, 65535)); } - void SetVertex(int x, int y, u16 value) + void SetVertex(ssize_t x, ssize_t y, u16 value) { - if ((unsigned)x >= m_VertsPerSide || (unsigned)y >= m_VertsPerSide) + if (size_t(x) >= size_t(m_VertsPerSide) || size_t(y) >= size_t(m_VertsPerSide)) return; set(x,y, value); } - u16 GetVertex(int x, int y) + u16 GetVertex(ssize_t x, ssize_t y) { - return get(clamp(x, 0, (int)m_VertsPerSide-1), clamp(y, 0, (int)m_VertsPerSide-1)); + return get(clamp(x, ssize_t(0), ssize_t(m_VertsPerSide-1)), clamp(y, ssize_t(0), ssize_t(m_VertsPerSide-1))); } protected: - u16 getOld(int x, int y) + u16 getOld(ssize_t x, ssize_t y) { return m_Heightmap[y*m_VertsPerSide + x]; } - void setNew(int x, int y, const u16& val) + void setNew(ssize_t x, ssize_t y, const u16& val) { m_Heightmap[y*m_VertsPerSide + x] = val; } u16* m_Heightmap; - size_t m_VertsPerSide; + ssize_t m_VertsPerSide; }; @@ -106,11 +106,11 @@ BEGIN_COMMAND(AlterElevation) g_CurrentBrush.m_Centre = msg->pos->GetWorldSpace(previousPosition); previousPosition = g_CurrentBrush.m_Centre; - int x0, y0; + ssize_t x0, y0; g_CurrentBrush.GetBottomLeft(x0, y0); - for (int dy = 0; dy < g_CurrentBrush.m_H; ++dy) - for (int dx = 0; dx < g_CurrentBrush.m_W; ++dx) + for (ssize_t dy = 0; dy < g_CurrentBrush.m_H; ++dy) + for (ssize_t dx = 0; dx < g_CurrentBrush.m_W; ++dx) { // TODO: proper variable raise amount (store floats in terrain delta array?) float b = g_CurrentBrush.Get(dx, dy); @@ -162,15 +162,15 @@ BEGIN_COMMAND(FlattenElevation) g_CurrentBrush.m_Centre = msg->pos->GetWorldSpace(previousPosition); previousPosition = g_CurrentBrush.m_Centre; - int xc, yc; + ssize_t xc, yc; g_CurrentBrush.GetCentre(xc, yc); u16 height = m_TerrainDelta.GetVertex(xc, yc); - int x0, y0; + ssize_t x0, y0; g_CurrentBrush.GetBottomLeft(x0, y0); - for (int dy = 0; dy < g_CurrentBrush.m_H; ++dy) - for (int dx = 0; dx < g_CurrentBrush.m_W; ++dx) + for (ssize_t dy = 0; dy < g_CurrentBrush.m_H; ++dy) + for (ssize_t dx = 0; dx < g_CurrentBrush.m_W; ++dx) { float b = g_CurrentBrush.Get(dx, dy); if (b) diff --git a/source/tools/atlas/GameInterface/Handlers/GraphicsSetupHandlers.cpp b/source/tools/atlas/GameInterface/Handlers/GraphicsSetupHandlers.cpp index 4a4ee44a63..ab0f95dafd 100644 --- a/source/tools/atlas/GameInterface/Handlers/GraphicsSetupHandlers.cpp +++ b/source/tools/atlas/GameInterface/Handlers/GraphicsSetupHandlers.cpp @@ -51,7 +51,7 @@ MESSAGEHANDLER(Init) g_Quickstart = true; - uint flags = INIT_HAVE_VMODE|INIT_NO_GUI; + int flags = INIT_HAVE_VMODE|INIT_NO_GUI; if (! msg->initsimulation) flags |= INIT_NO_SIM; @@ -85,7 +85,7 @@ MESSAGEHANDLER(Shutdown) View::DestroyViews(); g_GameLoop->view = View::GetView_None(); - uint flags = 0; + int flags = 0; if (! g_DidInitSim) flags |= INIT_NO_SIM; Shutdown(flags); diff --git a/source/tools/atlas/GameInterface/Handlers/MapHandlers.cpp b/source/tools/atlas/GameInterface/Handlers/MapHandlers.cpp index d362002a16..7fad274c04 100644 --- a/source/tools/atlas/GameInterface/Handlers/MapHandlers.cpp +++ b/source/tools/atlas/GameInterface/Handlers/MapHandlers.cpp @@ -35,7 +35,7 @@ namespace g_GameAttributes.GetSlot(i)->AssignLocal(); // Make the whole world visible - g_GameAttributes.m_LOSSetting = 2; + g_GameAttributes.m_LOSSetting = LOS_SETTING_ALL_VISIBLE; g_GameAttributes.m_FogOfWar = false; // Don't use screenshot mode, because we want working AI for the diff --git a/source/tools/atlas/GameInterface/Handlers/ObjectHandlers.cpp b/source/tools/atlas/GameInterface/Handlers/ObjectHandlers.cpp index a5bd46379c..166cc0d15c 100644 --- a/source/tools/atlas/GameInterface/Handlers/ObjectHandlers.cpp +++ b/source/tools/atlas/GameInterface/Handlers/ObjectHandlers.cpp @@ -144,7 +144,7 @@ QUERYHANDLER(GetObjectSettings) if (! unit) return; sObjectSettings settings; - settings.player = unit->GetPlayerID(); + settings.player = (int)unit->GetPlayerID(); // Get the unit's possible variants and selected variants std::vector > groups = unit->GetObject()->m_Base->GetVariantGroups(); @@ -188,7 +188,7 @@ QUERYHANDLER(GetObjectSettings) BEGIN_COMMAND(SetObjectSettings) { - int m_PlayerOld, m_PlayerNew; + size_t m_PlayerOld, m_PlayerNew; std::set m_SelectionsOld, m_SelectionsNew; void Do() @@ -199,7 +199,7 @@ BEGIN_COMMAND(SetObjectSettings) sObjectSettings settings = msg->settings; m_PlayerOld = unit->GetPlayerID(); - m_PlayerNew = settings.player; + m_PlayerNew = (size_t)settings.player; m_SelectionsOld = unit->GetActorSelections(); @@ -223,7 +223,7 @@ BEGIN_COMMAND(SetObjectSettings) } private: - void Set(int player, const std::set& selections) + void Set(size_t player, const std::set& selections) { CUnit* unit = View::GetView(msg->view)->GetUnit(msg->id); if (! unit) return; @@ -241,7 +241,7 @@ END_COMMAND(SetObjectSettings); ////////////////////////////////////////////////////////////////////////// -static int g_PreviewUnitID = -1; +static size_t g_PreviewUnitID = CUnit::invalidId; static CStrW g_PreviewUnitName; static bool g_PreviewUnitFloating; @@ -306,7 +306,7 @@ MESSAGEHANDLER(ObjectPreview) previewUnit = NULL; } - g_PreviewUnitID = -1; + g_PreviewUnitID = CUnit::invalidId; bool isEntity; CStrW name; @@ -384,8 +384,8 @@ BEGIN_COMMAND(CreateObject) { CVector3D m_Pos; float m_Angle; - int m_ID; - int m_Player; + size_t m_ID; + size_t m_Player; void Do() { @@ -519,7 +519,7 @@ QUERYHANDLER(PickObject) if (target) msg->id = target->GetID(); else - msg->id = -1; + msg->id = CUnit::invalidId; if (target) { diff --git a/source/tools/atlas/GameInterface/Handlers/TerrainHandlers.cpp b/source/tools/atlas/GameInterface/Handlers/TerrainHandlers.cpp index da702a34cd..3b1cef9718 100644 --- a/source/tools/atlas/GameInterface/Handlers/TerrainHandlers.cpp +++ b/source/tools/atlas/GameInterface/Handlers/TerrainHandlers.cpp @@ -52,7 +52,7 @@ QUERYHANDLER(GetTerrainGroupPreviews) // Read the size of the texture. (Usually loads the texture from // disk, which is slow.) GLint w, h; - int level = 1; // level 0 is the original size + ssize_t level = 1; // level 0 is the original size ogl_tex_bind((*it)->GetHandle()); glGetTexLevelParameteriv(GL_TEXTURE_2D, level, GL_TEXTURE_WIDTH, &w); glGetTexLevelParameteriv(GL_TEXTURE_2D, level, GL_TEXTURE_HEIGHT, &h); @@ -61,7 +61,7 @@ QUERYHANDLER(GetTerrainGroupPreviews) { // Oops, too small to preview - just use a flat colour u32 c = (*it)->GetBaseColor(); - for (int i = 0; i < msg->imagewidth*msg->imageheight; ++i) + for (ssize_t i = 0; i < msg->imagewidth*msg->imageheight; ++i) { buf[i*3+0] = (c>>16) & 0xff; buf[i*3+1] = (c>>8) & 0xff; @@ -78,7 +78,7 @@ QUERYHANDLER(GetTerrainGroupPreviews) // and copy into buf unsigned char* texdata_ptr = texdata + (w*(h - msg->imageheight)/2 + (w - msg->imagewidth)/2) * 3; unsigned char* buf_ptr = &buf[0]; - for (int y = 0; y < msg->imageheight; ++y) + for (ssize_t y = 0; y < msg->imageheight; ++y) { memcpy(buf_ptr, texdata_ptr, msg->imagewidth*3); buf_ptr += msg->imagewidth*3; @@ -104,9 +104,9 @@ BEGIN_COMMAND(PaintTerrain) { struct TerrainTile { - TerrainTile(Handle t, int p) : tex(t), priority(p) {} + TerrainTile(Handle t, ssize_t p) : tex(t), priority(p) {} Handle tex; - int priority; + ssize_t priority; }; class TerrainArray : public DeltaArray2D { @@ -117,18 +117,18 @@ BEGIN_COMMAND(PaintTerrain) m_VertsPerSide = g_Game->GetWorld()->GetTerrain()->GetVerticesPerSide(); } - void PaintTile(int x, int y, Handle tex, int priority) + void PaintTile(ssize_t x, ssize_t y, Handle tex, ssize_t priority) { // Ignore out-of-bounds tiles - if ((unsigned)x >= m_VertsPerSide-1 || (unsigned)y >= m_VertsPerSide-1) + if (size_t(x) >= size_t(m_VertsPerSide-1) || size_t(y) >= size_t(m_VertsPerSide-1)) return; // Priority system: If the new tile should have a high priority, // set it to one plus the maximum priority of all surrounding tiles // (so that it's definitely the highest). // Similar for low priority. - int greatest = 0; - int scale = (priority == ePaintTerrainPriority::HIGH ? +1 : -1); + ssize_t greatest = 0; + ssize_t scale = (priority == ePaintTerrainPriority::HIGH ? +1 : -1); CMiniPatch* tile; #define TILE(dx, dy) tile = m_Terrain->GetTile(x dx, y dy); if (tile && tile->Tex1Priority*scale > greatest) greatest = tile->Tex1Priority*scale; TILE(-1, -1) TILE(+0, -1) TILE(+1, -1) @@ -139,12 +139,12 @@ BEGIN_COMMAND(PaintTerrain) } protected: - TerrainTile getOld(int x, int y) + TerrainTile getOld(ssize_t x, ssize_t y) { CMiniPatch* mp = m_Terrain->GetTile(x, y); return TerrainTile(mp->Tex1, mp->Tex1Priority); } - void setNew(int x, int y, const TerrainTile& val) + void setNew(ssize_t x, ssize_t y, const TerrainTile& val) { CMiniPatch* mp = m_Terrain->GetTile(x, y); mp->Tex1 = val.tex; @@ -152,7 +152,7 @@ BEGIN_COMMAND(PaintTerrain) } CTerrain* m_Terrain; - size_t m_VertsPerSide; + ssize_t m_VertsPerSide; }; TerrainArray m_TerrainDelta; @@ -167,7 +167,7 @@ BEGIN_COMMAND(PaintTerrain) g_CurrentBrush.m_Centre = msg->pos->GetWorldSpace(); - int x0, y0; + ssize_t x0, y0; g_CurrentBrush.GetBottomLeft(x0, y0); CTextureEntry* texentry = g_TexMan.FindTexture(CStrW(*msg->texture)); @@ -178,9 +178,9 @@ BEGIN_COMMAND(PaintTerrain) } Handle texture = texentry->GetHandle(); - for (int dy = 0; dy < g_CurrentBrush.m_H; ++dy) + for (ssize_t dy = 0; dy < g_CurrentBrush.m_H; ++dy) { - for (int dx = 0; dx < g_CurrentBrush.m_W; ++dx) + for (ssize_t dx = 0; dx < g_CurrentBrush.m_W; ++dx) { if (g_CurrentBrush.Get(dx, dy) > 0.5f) // TODO: proper solid brushes m_TerrainDelta.PaintTile(x0+dx, y0+dy, texture, msg->priority); diff --git a/source/tools/atlas/GameInterface/Messages.h b/source/tools/atlas/GameInterface/Messages.h index 6803fca4f8..370295936d 100644 --- a/source/tools/atlas/GameInterface/Messages.h +++ b/source/tools/atlas/GameInterface/Messages.h @@ -178,7 +178,7 @@ QUERY(GetObjectsList, #ifndef MESSAGES_SKIP_STRUCTS struct sObjectSettings { - Shareable player; + Shareable player; Shareable > selections; // Some settings are immutable and therefore are ignored (and should be left diff --git a/source/tools/atlas/GameInterface/Shareable.h b/source/tools/atlas/GameInterface/Shareable.h index f3ca23a718..e11683ef4b 100644 --- a/source/tools/atlas/GameInterface/Shareable.h +++ b/source/tools/atlas/GameInterface/Shareable.h @@ -75,6 +75,7 @@ public: SHAREABLE_PRIMITIVE(unsigned char); SHAREABLE_PRIMITIVE(int); +SHAREABLE_PRIMITIVE(size_t); SHAREABLE_PRIMITIVE(long); SHAREABLE_PRIMITIVE(bool); SHAREABLE_PRIMITIVE(float); @@ -239,8 +240,16 @@ public: { wrapped_type r; r.reserve(size); + // (/Wp64 causes a spurious warning here. see https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=253172) +#if MSC_VERSION +#pragma warning(push) +#pragma warning(disable:4267) +#endif for (size_t i = 0; i < size; ++i) r.push_back(array[i]._Unwrap()); +#if MSC_VERSION +#pragma warning(pop) +#endif return r; } diff --git a/source/tools/atlas/GameInterface/SharedTypes.h b/source/tools/atlas/GameInterface/SharedTypes.h index 58e9f8ab20..bbab34870e 100644 --- a/source/tools/atlas/GameInterface/SharedTypes.h +++ b/source/tools/atlas/GameInterface/SharedTypes.h @@ -66,8 +66,8 @@ struct Colour SHAREABLE_STRUCT(Colour); -typedef int ObjectID; -inline bool ObjectIDIsValid(ObjectID id) { return (id >= 0); } +typedef size_t ObjectID; +inline bool ObjectIDIsValid(ObjectID id) { return (id != ~(size_t)0); } struct sCinemaSplineNode diff --git a/source/tools/atlas/GameInterface/SimState.h b/source/tools/atlas/GameInterface/SimState.h index c31970f77f..eaf6de2af5 100644 --- a/source/tools/atlas/GameInterface/SimState.h +++ b/source/tools/atlas/GameInterface/SimState.h @@ -20,9 +20,9 @@ public: CEntity* Thaw(); private: CStrW templateName; - int unitID; + size_t unitID; std::set selections; - int playerID; + size_t playerID; CVector3D position; float angle; }; @@ -34,7 +34,7 @@ public: CUnit* Thaw(); private: CStrW actorName; - int unitID; + size_t unitID; std::set selections; CVector3D position; float angle;