From 7a5213715d3f551e25174c7b951da99f1b5a71b1 Mon Sep 17 00:00:00 2001 From: Alfredo Tupone Date: Tue, 3 Oct 2023 08:07:00 +0200 Subject: [PATCH 1/2] Enable avx2 --- configure.ac | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/configure.ac b/configure.ac index 254a250abe..e12b1694cc 100644 --- a/configure.ac +++ b/configure.ac @@ -171,6 +171,8 @@ if test x$enable_robots != xno; then AC_DEFINE(ROBOT, 1, [Enabling Robots]) fi +AC_ARG_ENABLE(avx2, [ --enable-avx2 turn on simd]) + # debugging and profiling AC_ARG_ENABLE(debug, [ --enable-debug turn on debugging]) AC_ARG_ENABLE(profiling, [ --enable-profiling turn on profiling]) @@ -432,6 +434,8 @@ AC_CHECK_HEADERS( \ values.h \ ) +AC_DEFINE(GLM_FORCE_AVX2, 1, [ Enable avx2 if available]) + if test "x$enable_UPnP" = "xyes"; then AC_CHECK_HEADERS( [miniupnpc/miniupnpc.h], @@ -687,6 +691,9 @@ case $host_os in pc) FLAGS=-mtune=native CONF_CFLAGS="$CONF_CFLAGS $FLAGS"; + if test x$enable_avx2 = xyes ; then + CONF_CXXFLAGS="$CONF_CXXFLAGS -mavx2"; + fi CONF_CXXFLAGS="$CONF_CXXFLAGS $FLAGS"; CONF_CXXFLAGS="$CONF_CXXFLAGS -fsigned-char";; ppc) From cc91c8fb8390a3a02ed33ef87137f5de2f6253d7 Mon Sep 17 00:00:00 2001 From: Alfredo Tupone Date: Sun, 24 Sep 2023 20:47:02 +0200 Subject: [PATCH 2/2] use glm --- MSVC/build/ogl.vcxproj | 4 +- MSVC/build/ogl.vcxproj.filters | 8 +- Xcode/BZFlag.xcodeproj/project.pbxproj | 4 - configure.ac | 4 + include/AnsiCodes.h | 3 +- include/ArcObstacle.h | 47 +- include/BSPSceneDatabase.h | 3 +- include/BaseBuilding.h | 31 +- include/BillboardSceneNode.h | 10 +- include/BoltSceneNode.h | 49 +- include/BoxBuilding.h | 55 +- include/BzMaterial.h | 24 +- include/CollisionManager.h | 10 +- include/ConeObstacle.h | 45 +- include/DynamicColor.h | 12 +- include/EighthDBaseSceneNode.h | 13 +- include/EighthDBoxSceneNode.h | 15 +- include/EighthDPyrSceneNode.h | 14 +- include/EighthDimSceneNode.h | 10 +- include/EighthDimShellNode.h | 8 +- include/Extents.h | 90 +- include/Flag.h | 11 +- include/FlagSceneNode.h | 14 +- include/FlagWarpSceneNode.h | 19 +- include/FontManager.h | 10 +- include/Frustum.h | 61 +- include/Intersect.h | 34 +- include/LaserSceneNode.h | 22 +- include/Makefile.am | 3 +- include/MeshDrawInfo.h | 46 +- include/MeshFace.h | 92 +- include/MeshFragSceneNode.h | 10 +- include/MeshObstacle.h | 103 +- include/MeshPolySceneNode.h | 95 +- include/MeshSceneNode.h | 18 +- include/MeshSceneNodeGenerator.h | 6 +- include/MeshTransform.h | 25 +- include/Obstacle.h | 54 +- include/OccluderSceneNode.h | 8 +- include/OpenGLAPI.h | 48 + include/OpenGLLight.h | 18 +- include/OpenGLMaterial.h | 30 +- include/OpenGLUtils.h | 4 +- include/Pack.h | 7 +- include/ParseColor.h | 4 + include/PlayerState.h | 7 +- include/PolyWallSceneNode.h | 29 +- include/PyramidBuilding.h | 55 +- include/QuadWallSceneNode.h | 60 +- include/Ray.h | 23 +- include/RenderNode.h | 5 +- include/SceneNode.h | 66 +- include/SceneRenderer.h | 34 +- include/ShotUpdate.h | 5 +- include/SphereObstacle.h | 45 +- include/SphereSceneNode.h | 24 +- include/TankGeometryMgr.h | 2 +- include/TankSceneNode.h | 72 +- include/Team.h | 24 +- include/Teleporter.h | 63 +- include/TetraBuilding.h | 53 +- include/TriWallSceneNode.h | 42 +- include/WallObstacle.h | 43 +- include/WallSceneNode.h | 62 +- include/vectors.h | 1100 ----------------- include/vectors_old.h | 135 -- src/3D/FontManager.cxx | 96 +- src/3D/ImageFont.h | 5 +- src/3D/TextureFont.cxx | 9 +- src/3D/TextureFont.h | 4 +- src/bzflag/AutoPilot.cxx | 100 +- src/bzflag/BackgroundRenderer.cxx | 570 ++++----- src/bzflag/BackgroundRenderer.h | 30 +- src/bzflag/BaseLocalPlayer.cxx | 41 +- src/bzflag/BaseLocalPlayer.h | 6 +- src/bzflag/CommandsImplementation.cxx | 2 +- src/bzflag/ControlPanel.cxx | 15 +- src/bzflag/ControlPanel.h | 5 +- src/bzflag/GuidedMissleStrategy.cxx | 111 +- src/bzflag/GuidedMissleStrategy.h | 5 +- src/bzflag/HUDRenderer.cxx | 310 ++--- src/bzflag/HUDRenderer.h | 53 +- src/bzflag/HUDuiControl.cxx | 8 +- src/bzflag/HUDuiControl.h | 6 +- src/bzflag/HUDuiLabel.cxx | 8 +- src/bzflag/HUDuiLabel.h | 4 +- src/bzflag/HUDuiList.cxx | 3 +- src/bzflag/HUDuiTextureLabel.cxx | 3 +- src/bzflag/HUDuiTypeIn.cxx | 3 +- src/bzflag/LocalPlayer.cxx | 215 ++-- src/bzflag/LocalPlayer.h | 45 +- src/bzflag/Plan.cxx | 53 +- src/bzflag/Player.cxx | 162 ++- src/bzflag/Player.h | 49 +- src/bzflag/RadarRenderer.cxx | 115 +- src/bzflag/RadarRenderer.h | 8 +- src/bzflag/Region.cxx | 80 +- src/bzflag/Region.h | 18 +- src/bzflag/RemotePlayer.cxx | 22 +- src/bzflag/RemotePlayer.h | 6 +- src/bzflag/Roaming.cxx | 2 +- src/bzflag/Roaming.h | 2 +- src/bzflag/RobotPlayer.cxx | 164 +-- src/bzflag/RobotPlayer.h | 16 +- src/bzflag/RoofTops.cxx | 4 +- src/bzflag/SceneBuilder.cxx | 63 +- src/bzflag/SceneBuilder.h | 38 +- src/bzflag/SceneRenderer.cxx | 53 +- src/bzflag/ScoreboardRenderer.cxx | 48 +- src/bzflag/ScoreboardRenderer.h | 4 +- src/bzflag/SegmentedShotStrategy.cxx | 199 ++- src/bzflag/SegmentedShotStrategy.h | 8 +- src/bzflag/ServerLink.cxx | 2 +- src/bzflag/ServerLink.h | 2 +- src/bzflag/ShockWaveStrategy.cxx | 29 +- src/bzflag/ShockWaveStrategy.h | 2 +- src/bzflag/ShotPath.cxx | 26 +- src/bzflag/ShotPath.h | 14 +- src/bzflag/ShotPathSegment.cxx | 16 +- src/bzflag/ShotPathSegment.h | 2 +- src/bzflag/ShotStatistics.cxx | 26 +- src/bzflag/ShotStatistics.h | 2 +- src/bzflag/ShotStrategy.cxx | 24 +- src/bzflag/ShotStrategy.h | 8 +- src/bzflag/TargetingUtils.cxx | 95 +- src/bzflag/TargetingUtils.h | 28 +- src/bzflag/TrackMarks.cxx | 15 +- src/bzflag/TrackMarks.h | 5 +- src/bzflag/WeatherRenderer.cxx | 203 +-- src/bzflag/WeatherRenderer.h | 15 +- src/bzflag/World.cxx | 150 +-- src/bzflag/World.h | 65 +- src/bzflag/WorldBuilder.cxx | 14 +- src/bzflag/WorldBuilder.h | 2 +- src/bzflag/WorldPlayer.cxx | 8 +- src/bzflag/WorldPlayer.h | 8 +- src/bzflag/callbacks.cxx | 4 +- src/bzflag/daylight.cxx | 159 +-- src/bzflag/daylight.h | 22 +- src/bzflag/effectsRenderer.cxx | 389 ++---- src/bzflag/effectsRenderer.h | 40 +- src/bzflag/playing.cxx | 359 +++--- src/bzflag/playing.h | 8 +- src/bzflag/sound.cxx | 12 +- src/bzflag/sound.h | 9 +- src/bzfs/CustomArc.cxx | 6 +- src/bzfs/CustomBase.cxx | 2 +- src/bzfs/CustomBox.cxx | 35 +- src/bzfs/CustomCone.cxx | 10 +- src/bzfs/CustomGroup.cxx | 2 +- src/bzfs/CustomMesh.cxx | 18 +- src/bzfs/CustomMesh.h | 8 +- src/bzfs/CustomMeshTransform.cxx | 9 +- src/bzfs/CustomPyramid.cxx | 62 +- src/bzfs/CustomTetra.cxx | 2 +- src/bzfs/CustomTetra.h | 2 +- src/bzfs/CustomZone.cxx | 9 +- src/bzfs/CustomZone.h | 4 +- src/bzfs/DropGeometry.cxx | 21 +- src/bzfs/DropGeometry.h | 9 +- src/bzfs/EntryZones.cxx | 12 +- src/bzfs/EntryZones.h | 10 +- src/bzfs/FlagInfo.cxx | 8 +- src/bzfs/FlagInfo.h | 4 +- src/bzfs/GameKeeper.cxx | 10 +- src/bzfs/GameKeeper.h | 4 +- src/bzfs/ParseMaterial.cxx | 10 +- src/bzfs/RandomSpawnPolicy.cxx | 2 +- src/bzfs/RandomSpawnPolicy.h | 4 +- src/bzfs/ServerSidePlayer.cxx | 13 +- src/bzfs/ShotManager.cxx | 50 +- src/bzfs/ShotManager.h | 45 +- src/bzfs/SpawnPolicy.cxx | 10 +- src/bzfs/SpawnPolicy.h | 11 +- src/bzfs/SpawnPosition.h | 5 +- src/bzfs/TeamBases.cxx | 40 +- src/bzfs/TeamBases.h | 13 +- src/bzfs/WorldFileLocation.cxx | 9 +- src/bzfs/WorldFileLocation.h | 4 +- src/bzfs/WorldGenerators.cxx | 20 +- src/bzfs/WorldInfo.cxx | 32 +- src/bzfs/WorldInfo.h | 14 +- src/bzfs/WorldWeapons.cxx | 17 +- src/bzfs/WorldWeapons.h | 16 +- src/bzfs/bzfs.cxx | 92 +- src/bzfs/bzfs.h | 4 +- src/bzfs/bzfsAPI.cxx | 41 +- src/bzfs/commands.cxx | 5 +- src/common/Flag.cxx | 11 +- src/common/ParseColor.cxx | 11 + src/common/Team.cxx | 29 +- src/game/BzMaterial.cxx | 112 +- src/game/CollisionManager.cxx | 42 +- src/game/DynamicColor.cxx | 56 +- src/game/Frustum.cxx | 280 ++--- src/game/Intersect.cxx | 228 ++-- src/game/MeshTransform.cxx | 170 +-- src/game/MsgStrings.cxx | 13 +- src/game/Ray.cxx | 34 +- src/geometry/BillboardSceneNode.cxx | 49 +- src/geometry/BoltSceneNode.cxx | 176 +-- src/geometry/EighthDBaseSceneNode.cxx | 49 +- src/geometry/EighthDBoxSceneNode.cxx | 48 +- src/geometry/EighthDPyrSceneNode.cxx | 54 +- src/geometry/EighthDimSceneNode.cxx | 27 +- src/geometry/EighthDimShellNode.cxx | 2 +- src/geometry/FlagSceneNode.cxx | 42 +- src/geometry/FlagWarpSceneNode.cxx | 92 +- src/geometry/LaserSceneNode.cxx | 71 +- src/geometry/MeshFragSceneNode.cxx | 67 +- src/geometry/MeshPolySceneNode.cxx | 302 +++-- src/geometry/MeshRenderNode.cxx | 23 +- src/geometry/MeshRenderNode.h | 20 +- src/geometry/MeshSceneNode.cxx | 87 +- src/geometry/OccluderSceneNode.cxx | 50 +- src/geometry/PolyWallSceneNode.cxx | 94 +- src/geometry/QuadWallSceneNode.cxx | 158 +-- src/geometry/SceneNode.cxx | 56 +- src/geometry/SphereSceneNode.cxx | 87 +- src/geometry/TankGeometryMgr.cxx | 31 +- src/geometry/TankSceneNode.cxx | 282 ++--- src/geometry/TriWallSceneNode.cxx | 115 +- src/geometry/ViewFrustum.cxx | 11 +- src/geometry/WallSceneNode.cxx | 197 ++- src/net/Pack.cxx | 44 + src/obstacle/ArcObstacle.cxx | 66 +- src/obstacle/BaseBuilding.cxx | 65 +- src/obstacle/BaseSceneNodeGenerator.cxx | 31 +- src/obstacle/BoxBuilding.cxx | 96 +- src/obstacle/BoxSceneNodeGenerator.cxx | 15 +- src/obstacle/ConeObstacle.cxx | 102 +- src/obstacle/MeshDrawInfo.cxx | 174 ++- src/obstacle/MeshFace.cxx | 219 ++-- src/obstacle/MeshObstacle.cxx | 227 ++-- src/obstacle/MeshSceneNodeGenerator.cxx | 78 +- src/obstacle/Obstacle.cxx | 89 +- src/obstacle/ObstacleMgr.cxx | 2 +- src/obstacle/ObstacleModifier.cxx | 7 +- src/obstacle/PyramidBuilding.cxx | 114 +- src/obstacle/PyramidSceneNodeGenerator.cxx | 24 +- src/obstacle/SphereObstacle.cxx | 81 +- src/obstacle/Teleporter.cxx | 203 ++- src/obstacle/TeleporterSceneNodeGenerator.cxx | 208 ++-- src/obstacle/TetraBuilding.cxx | 84 +- src/obstacle/Triangulate.cxx | 110 +- src/obstacle/Triangulate.h | 3 +- src/obstacle/WallObstacle.cxx | 42 +- src/obstacle/WallSceneNodeGenerator.cxx | 8 +- src/ogl/Makefile.am | 1 + src/ogl/OpenGLAPI.cxx | 120 ++ src/ogl/OpenGLLight.cxx | 89 +- src/ogl/OpenGLMaterial.cxx | 45 +- src/ogl/OpenGLUtils.cxx | 15 +- src/ogl/RenderNode.cxx | 12 +- src/scene/BSPSceneDatabase.cxx | 39 +- src/scene/Occluder.cxx | 86 +- src/scene/Occluder.h | 4 +- src/scene/Octree.cxx | 63 +- src/scene/Octree.h | 2 +- src/scene/ZSceneDatabase.cxx | 19 +- 260 files changed, 5879 insertions(+), 8272 deletions(-) create mode 100644 include/OpenGLAPI.h delete mode 100644 include/vectors.h delete mode 100644 include/vectors_old.h create mode 100644 src/ogl/OpenGLAPI.cxx diff --git a/MSVC/build/ogl.vcxproj b/MSVC/build/ogl.vcxproj index a51143b5fa..c7469e6d23 100644 --- a/MSVC/build/ogl.vcxproj +++ b/MSVC/build/ogl.vcxproj @@ -193,6 +193,7 @@ + Disabled @@ -279,6 +280,7 @@ + @@ -290,4 +292,4 @@ - \ No newline at end of file + diff --git a/MSVC/build/ogl.vcxproj.filters b/MSVC/build/ogl.vcxproj.filters index 5b0d571de4..a1689ec3d3 100644 --- a/MSVC/build/ogl.vcxproj.filters +++ b/MSVC/build/ogl.vcxproj.filters @@ -19,6 +19,9 @@ Source Files + + Source Files + Source Files @@ -48,6 +51,9 @@ Header Files + + Header Files + Header Files @@ -60,4 +66,4 @@ {8b1c786a-fe0a-4a9f-8809-6572c90a8d13} - \ No newline at end of file + diff --git a/Xcode/BZFlag.xcodeproj/project.pbxproj b/Xcode/BZFlag.xcodeproj/project.pbxproj index 62493fc74d..6362de191f 100644 --- a/Xcode/BZFlag.xcodeproj/project.pbxproj +++ b/Xcode/BZFlag.xcodeproj/project.pbxproj @@ -1111,8 +1111,6 @@ 0305D5F0166C9DAE00557FC4 /* TextUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TextUtils.h; sourceTree = ""; }; 0305D5F2166C9DAE00557FC4 /* TimeKeeper.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TimeKeeper.h; sourceTree = ""; }; 0305D5F4166C9DAE00557FC4 /* TriWallSceneNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TriWallSceneNode.h; sourceTree = ""; }; - 0305D5F5166C9DAE00557FC4 /* vectors.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = vectors.h; sourceTree = ""; }; - 0305D5F6166C9DAE00557FC4 /* vectors_old.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = vectors_old.h; sourceTree = ""; }; 0305D5F7166C9DAE00557FC4 /* version.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = version.h; sourceTree = ""; }; 0305D5F8166C9DAE00557FC4 /* ViewFrustum.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ViewFrustum.h; sourceTree = ""; }; 0305D5FA166C9DAE00557FC4 /* VotingBooth.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = VotingBooth.h; sourceTree = ""; }; @@ -2368,8 +2366,6 @@ 0305D5F0166C9DAE00557FC4 /* TextUtils.h */, 0305D5F2166C9DAE00557FC4 /* TimeKeeper.h */, 0305D5F4166C9DAE00557FC4 /* TriWallSceneNode.h */, - 0305D5F5166C9DAE00557FC4 /* vectors.h */, - 0305D5F6166C9DAE00557FC4 /* vectors_old.h */, 0305D5F7166C9DAE00557FC4 /* version.h */, 0305D5F8166C9DAE00557FC4 /* ViewFrustum.h */, 0305D5FA166C9DAE00557FC4 /* VotingBooth.h */, diff --git a/configure.ac b/configure.ac index e12b1694cc..7bc02dba51 100644 --- a/configure.ac +++ b/configure.ac @@ -414,6 +414,10 @@ AC_CHECK_HEADERS( \ cstdio \ cstring ) +AC_CHECK_HEADERS( + [glm/glm.hpp], + , + [AC_MSG_ERROR([glm (from https://glm.g-truc.net) is needed])]) AC_LANG(C) AC_CHECK_HEADERS( \ SDL2/SDL.h \ diff --git a/include/AnsiCodes.h b/include/AnsiCodes.h index 8dd1d95cc2..0b629ec7cd 100644 --- a/include/AnsiCodes.h +++ b/include/AnsiCodes.h @@ -18,6 +18,7 @@ // System headers #include +#include // Common headers #include "TextUtils.h" @@ -105,7 +106,7 @@ static const std::string ColorStrings[17] = ANSI_STR_NO_UNDERLINE // 16 No Underlining }; -inline std::string rgbToAnsi(const float* color) +inline std::string rgbToAnsi(const glm::vec3 &color) { return TextUtils::format("%s;%u;%u;%um", ANSI_STR_FG_RGB, diff --git a/include/ArcObstacle.h b/include/ArcObstacle.h index dc6cb52d44..4eabbc8ccf 100644 --- a/include/ArcObstacle.h +++ b/include/ArcObstacle.h @@ -46,46 +46,33 @@ class ArcObstacle : public Obstacle ArcObstacle(); ArcObstacle(const MeshTransform& transform, - const float* _pos, const float* _size, + const glm::vec3 &_pos, const glm::vec3 &_size, float _rotation, float _angle, float _ratio, const float _texsize[4], bool _useNormals, int _divisions, const BzMaterial* mats[MaterialCount], int physics, bool bounce, bool drive, bool shoot, bool ricochet); ~ArcObstacle(); - Obstacle* copyWithTransform(const MeshTransform&) const; + Obstacle* copyWithTransform(const MeshTransform&) const override; MeshObstacle* makeMesh(); - const char* getType() const; + const char* getType() const override; static const char* getClassName(); // const - bool isValid() const; - bool isFlatTop() const; - - float intersect(const Ray&) const; - void getNormal(const float* p, float* n) const; - void get3DNormal(const float* p, float* n) const; - - bool inCylinder(const float* p, float radius, float height) const; - bool inBox(const float* p, float angle, - float halfWidth, float halfBreadth, float height) const; - bool inMovingBox(const float* oldP, float oldAngle, - const float *newP, float newAngle, - float halfWidth, float halfBreadth, float height) const; - bool isCrossing(const float* p, float angle, - float halfWidth, float halfBreadth, float height, - float* plane) const; - - bool getHitNormal(const float* pos1, float azimuth1, - const float* pos2, float azimuth2, - float halfWidth, float halfBreadth, - float height, float* normal) const; - - int packSize() const; - void *pack(void*) const; - const void *unpack(const void*); - - void print(std::ostream& out, const std::string& indent) const; + bool isValid() const override; + bool isFlatTop() const override; + + float intersect(const Ray&) const override; + void getNormal(const glm::vec3 &p, glm::vec3 &n) const override; + void get3DNormal(const glm::vec3 &p, glm::vec3 &n) const override; + + bool inCylinder(const glm::vec3 &p, float radius, float height) const override; + + int packSize() const override; + void *pack(void*) const override; + const void *unpack(const void*) override; + + void print(std::ostream& out, const std::string& indent) const override; private: void finalize(); diff --git a/include/BSPSceneDatabase.h b/include/BSPSceneDatabase.h index 6063ac9281..001d0e8b7b 100644 --- a/include/BSPSceneDatabase.h +++ b/include/BSPSceneDatabase.h @@ -22,6 +22,7 @@ // system headers #include +#include // common implementation headers #include "bzfgl.h" @@ -83,7 +84,7 @@ class BSPSceneDatabase : public SceneDatabase Node* root; int depth; // the following members avoid passing parameters around - GLfloat eye[3]; + glm::vec3 eye; SceneRenderer* renderer; const ViewFrustum* frustum; diff --git a/include/BaseBuilding.h b/include/BaseBuilding.h index 8db00fc442..a88b3d794b 100644 --- a/include/BaseBuilding.h +++ b/include/BaseBuilding.h @@ -17,6 +17,7 @@ #ifndef BZF_BASE_BUILDING_H #define BZF_BASE_BUILDING_H +// Inherits from #include "BoxBuilding.h" class BaseBuilding : public BoxBuilding @@ -26,31 +27,31 @@ class BaseBuilding : public BoxBuilding public: BaseBuilding(); - BaseBuilding(const float *pos, float rotation, - const float *size, int _team, bool ricochet); + BaseBuilding(const glm::vec3 &pos, float rotation, + const glm::vec3 &size, int _team, bool ricochet); ~BaseBuilding(); - Obstacle* copyWithTransform(const MeshTransform&) const; + Obstacle* copyWithTransform(const MeshTransform&) const override; - const char* getType() const; + const char* getType() const override; static const char* getClassName(); // const - bool inCylinder(const float* p, float radius, float height) const; - bool inMovingBox(const float* oldP, float oldAngle, - const float *newP, float newAngle, - float halfWidth, float halfBreadth, float height) const; - bool isCrossing(const float* p, float angle, + bool inCylinder(const glm::vec3 &p, float radius, float height) const override; + bool inMovingBox(const glm::vec3 &oldP, float oldAngle, + const glm::vec3 &newP, float newAngle, + float halfWidth, float halfBreadth, float height) const override; + bool isCrossing(const glm::vec3 &p, float angle, float halfWidth, float halfBreadth, float height, - float* plane) const; + glm::vec4 *plane) const override; int getTeam() const; - int packSize() const; - void *pack(void*) const; - const void *unpack(const void*); + int packSize() const override; + void *pack(void*) const override; + const void *unpack(const void*) override; - void print(std::ostream& out, const std::string& indent) const; - void printOBJ(std::ostream& out, const std::string& indent) const; + void print(std::ostream& out, const std::string& indent) const override; + void printOBJ(std::ostream& out, const std::string& indent) const override; std::string userTextures[2]; diff --git a/include/BillboardSceneNode.h b/include/BillboardSceneNode.h index 13b580d79f..06c3bd8470 100644 --- a/include/BillboardSceneNode.h +++ b/include/BillboardSceneNode.h @@ -26,7 +26,7 @@ class BillboardSceneNode : public SceneNode { public: - BillboardSceneNode(const GLfloat pos[3]); + BillboardSceneNode(const glm::vec3 &pos); ~BillboardSceneNode(); virtual BillboardSceneNode* copy() const; @@ -53,7 +53,7 @@ class BillboardSceneNode : public SceneNode void setTexture(const int); void setTextureAnimation(int cu, int cv); - void move(const GLfloat pos[3]); + void move(const glm::vec3 &pos); void setAngle(GLfloat); void addLight(SceneRenderer&); @@ -68,7 +68,7 @@ class BillboardSceneNode : public SceneNode ~BillboardRenderNode(); void setColor(const GLfloat* rgba); void render() override; - const GLfloat* getPosition() const override; + const glm::vec3 &getPosition() const override; void setFrame(float u, float v); void setFrameSize(float du, float dv); private: @@ -90,9 +90,9 @@ class BillboardSceneNode : public SceneNode bool lightSource; bool groundLight; float width, height; - GLfloat color[4]; + glm::vec4 color; GLfloat angle; - GLfloat lightColor[3]; + glm::vec3 lightColor; GLfloat lightScale; float lightCutoffTime; int cu, cv; diff --git a/include/BoltSceneNode.h b/include/BoltSceneNode.h index b7e3f588fc..c22593284d 100644 --- a/include/BoltSceneNode.h +++ b/include/BoltSceneNode.h @@ -20,37 +20,31 @@ // Inherits from #include "SceneNode.h" +// System headers +#include + // Common headers #include "OpenGLLight.h" class BoltSceneNode : public SceneNode { public: - BoltSceneNode(const GLfloat pos[3], const GLfloat vel[3], bool super); + BoltSceneNode(const glm::vec3 &pos, const glm::vec3 &vel, bool super); ~BoltSceneNode(); void setFlares(bool); void setSize(float radius); void setColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a = 1.0f); void setTextureColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a = 1.0f); - void setColor(const GLfloat* rgb); - void setTeamColor(const GLfloat* rgb); + void setColor(const glm::vec3 &rgb); + void setTeamColor(const glm::vec3 &rgb); void setTexture(const int); void setTextureAnimation(int cu, int cv); bool getColorblind() const; void setColorblind(bool); - bool getInvisible() const - { - return invisible; - } - void setInvisible(bool _invisible) - { - invisible = _invisible; - } - - void move(const GLfloat pos[3], const GLfloat forward[3]); + void move(const glm::vec3 &pos, const glm::vec3 &forward); void addLight(SceneRenderer&) override; void notifyStyleChange() override; @@ -64,10 +58,10 @@ class BoltSceneNode : public SceneNode public: BoltRenderNode(const BoltSceneNode*); ~BoltRenderNode(); - void setColor(const GLfloat* rgba); - void setTextureColor(const GLfloat* rgba); + void setColor(const glm::vec4 &rgba); + void setTextureColor(const glm::vec4 &rgba); void render() override; - const GLfloat* getPosition() const override; + const glm::vec3 &getPosition() const override; void setAnimation(int cu, int cv); void renderGeoBolt(); @@ -78,19 +72,18 @@ class BoltSceneNode : public SceneNode const BoltSceneNode* sceneNode; int u, v, cu, cv; GLfloat du, dv; - GLfloat mainColor[4]; - GLfloat innerColor[4]; - GLfloat outerColor[4]; - GLfloat coronaColor[4]; - GLfloat flareColor[4]; - GLfloat textureColor[4]; + glm::vec4 mainColor; + glm::vec4 innerColor; + glm::vec4 outerColor; + glm::vec4 coronaColor; + glm::vec4 flareColor; + glm::vec4 textureColor; int numFlares; float theta[6]; float phi[6]; - static GLfloat core[9][2]; - static GLfloat corona[8][2]; - static const GLfloat ring[8][2]; + static glm::vec2 core[9]; + static const glm::vec2 corona[8]; static const GLfloat CoreFraction; static const GLfloat FlareSize; static const GLfloat FlareSpread; @@ -103,9 +96,9 @@ class BoltSceneNode : public SceneNode bool texturing; bool colorblind; float size; - float velocity[3]; - GLfloat color[4]; - fvec4 teamColor; + glm::vec4 color; + glm::vec4 teamColor; + glm::vec3 velocity; OpenGLLight light; OpenGLGState gstate; OpenGLGState colorblindGState; diff --git a/include/BoxBuilding.h b/include/BoxBuilding.h index 8f52f234be..60c095ef9b 100644 --- a/include/BoxBuilding.h +++ b/include/BoxBuilding.h @@ -17,57 +17,60 @@ #ifndef BZF_BOX_BUILDING_H #define BZF_BOX_BUILDING_H -#include "common.h" -#include +// Inherits from #include "Obstacle.h" +// System headers +#include +#include + class BoxBuilding : public Obstacle { public: BoxBuilding(); - BoxBuilding(const float* pos, float rotation, + BoxBuilding(const glm::vec3 &pos, float rotation, float width, float breadth, float height, bool drive = false, bool shoot = false, bool ricochet = false, bool invisible = false); ~BoxBuilding(); - Obstacle* copyWithTransform(const MeshTransform&) const; + Obstacle* copyWithTransform(const MeshTransform&) const override; - const char* getType() const; + const char* getType() const override; static const char* getClassName(); // const - bool isFlatTop() const; + bool isFlatTop() const override; - float intersect(const Ray&) const; - void getNormal(const float* p, float* n) const; - void get3DNormal(const float* p, float* n) const; + float intersect(const Ray&) const override; + void getNormal(const glm::vec3 &p, glm::vec3 &n) const override; + void get3DNormal(const glm::vec3 &p, glm::vec3 &n) const override; inline bool isInvisible() const; - bool inCylinder(const float* p, float radius, float height) const; - bool inBox(const float* p, float angle, - float halfWidth, float halfBreadth, float height) const; - bool inMovingBox(const float* oldP, float oldAngle, - const float *newP, float newAngle, - float halfWidth, float halfBreadth, float height) const; - bool isCrossing(const float* p, float angle, + bool inCylinder(const glm::vec3 &p, float radius, float height) const override; + bool inBox(const glm::vec3 &p, float angle, + float halfWidth, float halfBreadth, float height) const override; + bool inMovingBox(const glm::vec3 &oldP, float oldAngle, + const glm::vec3 &newP, float newAngle, + float halfWidth, float halfBreadth, float height) const override; + bool isCrossing(const glm::vec3 &p, float angle, float halfWidth, float halfBreadth, float height, - float* plane) const; + glm::vec4 *plane) const override; bool getHitNormal( - const float* pos1, float azimuth1, - const float* pos2, float azimuth2, + const glm::vec3 &pos1, float azimuth1, + const glm::vec3 &pos2, float azimuth2, float halfWidth, float halfBreadth, float height, - float* normal) const; + glm::vec3 &normal) const override; - void getCorner(int index, float* pos) const; + void getCorner(int index, glm::vec3 &pos) const; - int packSize() const; - void *pack(void*) const; - const void *unpack(const void*); + int packSize() const override; + void *pack(void*) const override; + const void *unpack(const void*) override; - void print(std::ostream& out, const std::string& indent) const; - void printOBJ(std::ostream& out, const std::string& indent) const; + void print(std::ostream& out, const std::string& indent) const override; + void printOBJ(std::ostream& out, const std::string& indent) const override; std::string userTextures[2]; diff --git a/include/BzMaterial.h b/include/BzMaterial.h index d521d3cdcb..3fe0d4ed65 100644 --- a/include/BzMaterial.h +++ b/include/BzMaterial.h @@ -17,13 +17,17 @@ #ifndef BZ_MATERIAL_H #define BZ_MATERIAL_H +// 1st #include "common.h" + +// System interfaces #include #include #include #include #include - +#include +#include class BzMaterial; @@ -57,9 +61,9 @@ class BzMaterial void setDynamicColor(int); void setAmbient(const float[4]); - void setDiffuse(const float[4]); - void setSpecular(const float[3]); - void setEmission(const float[3]); + void setDiffuse(const glm::vec4 &); + void setSpecular(const glm::vec3 &); + void setEmission(const glm::vec3 &); void setShininess(const float); void setOccluder(bool); @@ -95,9 +99,9 @@ class BzMaterial int getDynamicColor() const; const float* getAmbient() const; - const float* getDiffuse() const; - const float* getSpecular() const; - const float* getEmission() const; + const glm::vec4 &getDiffuse() const; + const glm::vec3 &getSpecular() const; + const glm::vec3 &getEmission() const; float getShininess() const; bool getOccluder() const; @@ -145,9 +149,9 @@ class BzMaterial int dynamicColor; float ambient[4]; - float diffuse[4]; - float specular[4]; - float emission[4]; + glm::vec4 diffuse; + glm::vec3 specular; + glm::vec3 emission; float shininess; bool occluder; diff --git a/include/CollisionManager.h b/include/CollisionManager.h index daa719a095..d1984e1aea 100644 --- a/include/CollisionManager.h +++ b/include/CollisionManager.h @@ -59,7 +59,7 @@ typedef struct // well you know my name is Simon, and I like to do drawings typedef void (*DrawLinesFunc) -(int pointCount, float (*points)[3], int color); +(int pointCount, const glm::vec3 points[], int color); class CollisionManager @@ -83,14 +83,14 @@ class CollisionManager const ObsList* axisBoxTest (const Extents& extents); // test against a cylinder - const ObsList* cylinderTest (const float *pos, + const ObsList* cylinderTest (const glm::vec3 &pos, float radius, float height) const; // test against a box - const ObsList* boxTest (const float* pos, float angle, + const ObsList* boxTest (const glm::vec3 &pos, float angle, float dx, float dy, float dz) const; // test against a moving box - const ObsList* movingBoxTest (const float* oldPos, float oldAngle, - const float* pos, float angle, + const ObsList* movingBoxTest (const glm::vec3 &oldPos, float oldAngle, + const glm::vec3 &pos, float angle, float dx, float dy, float dz) const; // test against a Ray const ObsList* rayTest (const Ray* ray, float timeLeft) const; diff --git a/include/ConeObstacle.h b/include/ConeObstacle.h index bc3140d11c..cf99bec5b6 100644 --- a/include/ConeObstacle.h +++ b/include/ConeObstacle.h @@ -40,45 +40,32 @@ class ConeObstacle : public Obstacle ConeObstacle(); ConeObstacle(const MeshTransform& transform, - const float* _pos, const float* _size, + const glm::vec3 &_pos, const glm::vec3 &_size, float _rotation, float _angle, const float _texsize[2], bool _useNormals, int _divisions, const BzMaterial* mats[MaterialCount], int physics, bool bounce, bool drive, bool shoot, bool ricochet); ~ConeObstacle(); - Obstacle* copyWithTransform(const MeshTransform&) const; + Obstacle* copyWithTransform(const MeshTransform&) const override; MeshObstacle* makeMesh(); - const char* getType() const; + const char* getType() const override; static const char* getClassName(); // const - bool isValid() const; - - float intersect(const Ray&) const; - void getNormal(const float* p, float* n) const; - void get3DNormal(const float* p, float* n) const; - - bool inCylinder(const float* p, float radius, float height) const; - bool inBox(const float* p, float angle, - float halfWidth, float halfBreadth, float height) const; - bool inMovingBox(const float* oldP, float oldAngle, - const float *newP, float newAngle, - float halfWidth, float halfBreadth, float height) const; - bool isCrossing(const float* p, float angle, - float halfWidth, float halfBreadth, float height, - float* plane) const; - - bool getHitNormal(const float* pos1, float azimuth1, - const float* pos2, float azimuth2, - float halfWidth, float halfBreadth, - float height, float* normal) const; - - int packSize() const; - void *pack(void*) const; - const void *unpack(const void*); - - void print(std::ostream& out, const std::string& indent) const; + bool isValid() const override; + + float intersect(const Ray&) const override; + void getNormal(const glm::vec3 &p, glm::vec3 &n) const override; + void get3DNormal(const glm::vec3 &p, glm::vec3 &n) const override; + + bool inCylinder(const glm::vec3 &p, float radius, float height) const override; + + int packSize() const override; + void *pack(void*) const override; + const void *unpack(const void*) override; + + void print(std::ostream& out, const std::string& indent) const override; private: void finalize(); diff --git a/include/DynamicColor.h b/include/DynamicColor.h index b97b9b8fc6..c8c356752e 100644 --- a/include/DynamicColor.h +++ b/include/DynamicColor.h @@ -13,12 +13,14 @@ #ifndef _DYNAMIC_COLOR_H_ #define _DYNAMIC_COLOR_H_ +// 1st #include "common.h" /* system interface headers */ #include #include #include +#include typedef struct sequenceList @@ -68,7 +70,7 @@ class DynamicColor void update(double time); bool canHaveAlpha() const; - const float* getColor() const; + const glm::vec4 *getColor() const; const std::string& getName() const; int packSize() const; @@ -81,11 +83,10 @@ class DynamicColor static const float minPeriod; std::string name; - float color[4]; + glm::vec4 color; typedef struct { - float minValue, maxValue; float totalWeight; // tally of sinusoid weights sequenceParams sequence; std::vector sinusoids; @@ -93,6 +94,7 @@ class DynamicColor std::vector clampDowns; } ChannelParams; + glm::vec4 minValue, maxValue; ChannelParams channels[4]; bool possibleAlpha; @@ -103,9 +105,9 @@ inline bool DynamicColor::canHaveAlpha() const return possibleAlpha; } -inline const float* DynamicColor::getColor() const +inline const glm::vec4 *DynamicColor::getColor() const { - return color; + return &color; } diff --git a/include/EighthDBaseSceneNode.h b/include/EighthDBaseSceneNode.h index bb9281a895..619937bc32 100644 --- a/include/EighthDBaseSceneNode.h +++ b/include/EighthDBaseSceneNode.h @@ -24,8 +24,9 @@ class EighthDBaseSceneNode : public EighthDimSceneNode { public: - EighthDBaseSceneNode(const float pos[3], - const float size[3], float rotation); + EighthDBaseSceneNode(const glm::vec3 &pos, + const glm::vec3 &size, + float rotation); ~EighthDBaseSceneNode(); void notifyStyleChange() override; void addRenderNodes(SceneRenderer&) override; @@ -34,14 +35,14 @@ class EighthDBaseSceneNode : public EighthDimSceneNode { public: EighthDBaseRenderNode(const EighthDBaseSceneNode *, - const float pos[3], - const float size[3], float rotation); + const glm::vec3 &pos, + const glm::vec3 &size, float rotation); ~EighthDBaseRenderNode(); void render() override; - const GLfloat* getPosition() const override; + const glm::vec3 &getPosition() const override; private: const EighthDBaseSceneNode *sceneNode; - GLfloat corner[8][3]; + glm::vec3 corner[8]; }; private: OpenGLGState gstate; diff --git a/include/EighthDBoxSceneNode.h b/include/EighthDBoxSceneNode.h index 80127ebf2a..90614f62a3 100644 --- a/include/EighthDBoxSceneNode.h +++ b/include/EighthDBoxSceneNode.h @@ -24,8 +24,10 @@ class EighthDBoxSceneNode : public EighthDimSceneNode { public: - EighthDBoxSceneNode(const float pos[3], - const float size[3], float rotation); + EighthDBoxSceneNode( + const glm::vec3 &pos, + const glm::vec3 &size, + float rotation); ~EighthDBoxSceneNode(); void notifyStyleChange() override; @@ -36,14 +38,15 @@ class EighthDBoxSceneNode : public EighthDimSceneNode { public: EighthDBoxRenderNode(const EighthDBoxSceneNode*, - const float pos[3], - const float size[3], float rotation); + const glm::vec3 &pos, + const glm::vec3 &size, + float rotation); ~EighthDBoxRenderNode(); void render() override; - const GLfloat* getPosition() const override; + const glm::vec3 &getPosition() const override; private: const EighthDBoxSceneNode* sceneNode; - GLfloat corner[8][3]; + glm::vec3 corner[8]; }; private: diff --git a/include/EighthDPyrSceneNode.h b/include/EighthDPyrSceneNode.h index 5c641b79df..33ada25a6a 100644 --- a/include/EighthDPyrSceneNode.h +++ b/include/EighthDPyrSceneNode.h @@ -24,8 +24,9 @@ class EighthDPyrSceneNode : public EighthDimSceneNode { public: - EighthDPyrSceneNode(const float pos[3], - const float size[3], float rotation); + EighthDPyrSceneNode(const glm::vec3 &pos, + const glm::vec3 &size, + float rotation); ~EighthDPyrSceneNode(); void notifyStyleChange() override; @@ -36,14 +37,15 @@ class EighthDPyrSceneNode : public EighthDimSceneNode { public: EighthDPyrRenderNode(const EighthDPyrSceneNode*, - const float pos[3], - const float size[3], float rotation); + const glm::vec3 &pos, + const glm::vec3 &size, + float rotation); ~EighthDPyrRenderNode(); void render() override; - const GLfloat* getPosition() const override; + const glm::vec3 &getPosition() const override; private: const EighthDPyrSceneNode* sceneNode; - GLfloat corner[5][3]; + glm::vec3 corner[5]; }; private: diff --git a/include/EighthDimSceneNode.h b/include/EighthDimSceneNode.h index be22bc1bd4..fd479a315d 100644 --- a/include/EighthDimSceneNode.h +++ b/include/EighthDimSceneNode.h @@ -32,7 +32,7 @@ class EighthDimSceneNode : public SceneNode protected: EighthDimSceneNode(int numPolys); - void setPolygon(int index, const GLfloat[3][3]); + void setPolygon(int index, const glm::vec3 vertex[3]); protected: class EighthDimRenderNode : public RenderNode @@ -43,13 +43,13 @@ class EighthDimSceneNode : public SceneNode int numPolygons); ~EighthDimRenderNode(); void render() override; - void setPolygon(int index, const GLfloat[3][3]); - const GLfloat* getPosition() const override; + void setPolygon(int index, const glm::vec3[3]); + const glm::vec3 &getPosition() const override; private: const EighthDimSceneNode* sceneNode; int numPolygons; - GLfloat (*color)[4]; - GLfloat (*poly)[3][3]; + glm::vec4 *color; + glm::vec3 (*poly)[3]; }; private: diff --git a/include/EighthDimShellNode.h b/include/EighthDimShellNode.h index e191f46dfb..431fed7979 100644 --- a/include/EighthDimShellNode.h +++ b/include/EighthDimShellNode.h @@ -29,9 +29,9 @@ class EighthDimShellNode : public SceneNode EighthDimShellNode(SceneNode *sceneNode, bool ownTheNode); ~EighthDimShellNode(); - bool cull(const ViewFrustum&) const; - void addRenderNodes(SceneRenderer&); - void notifyStyleChange(); + bool cull(const ViewFrustum&) const override; + void addRenderNodes(SceneRenderer&) override; + void notifyStyleChange() override; protected: class ShellRenderNode : public RenderNode @@ -42,7 +42,7 @@ class EighthDimShellNode : public SceneNode ~ShellRenderNode(); void render() override; void renderShadow() override; - const GLfloat* getPosition() const override; + const glm::vec3 &getPosition() const override; public: const OpenGLGState* getGState() const; private: diff --git a/include/Extents.h b/include/Extents.h index 42afac1793..b9942af797 100644 --- a/include/Extents.h +++ b/include/Extents.h @@ -18,22 +18,26 @@ #ifndef BZF_EXTENTS_H #define BZF_EXTENTS_H +// 1st #include "common.h" +// System headers +#include +#include class Extents { public: Extents(); - Extents(const float mins[3], const float maxs[3]); + Extents(const glm::vec3 &mins, const glm::vec3 &maxs); void reset(); Extents& operator=(const Extents&); - void set(const float mins[3], const float maxs[3]); + void set(const glm::vec3 &mins, const glm::vec3 &maxs); void expandToBox(const Extents& box); // expand to contain the box - void expandToPoint(const float[3]); // expand to contain the point + void expandToPoint(const glm::vec3&); // expand to contain the point void addMargin(float margin); // widen the extents by "margin" float getWidth(int axis) const; @@ -46,27 +50,23 @@ class Extents Extents(const Extents& orig); public: - float mins[3]; - float maxs[3]; + glm::vec3 mins; + glm::vec3 maxs; }; inline void Extents::reset() { - mins[0] = mins[1] = mins[2] = +MAXFLOAT; - maxs[0] = maxs[1] = maxs[2] = -MAXFLOAT; + mins = glm::vec3(+MAXFLOAT); + maxs = glm::vec3(-MAXFLOAT); return; } -inline void Extents::set(const float _mins[3], const float _maxs[3]) +inline void Extents::set(const glm::vec3 &_mins, const glm::vec3 &_maxs) { - mins[0] = _mins[0]; - mins[1] = _mins[1]; - mins[2] = _mins[2]; - maxs[0] = _maxs[0]; - maxs[1] = _maxs[1]; - maxs[2] = _maxs[2]; + mins = _mins; + maxs = _maxs; return; } @@ -78,7 +78,7 @@ inline Extents::Extents() } -inline Extents::Extents(const float _mins[3], const float _maxs[3]) +inline Extents::Extents(const glm::vec3 &_mins, const glm::vec3 &_maxs) { set(_mins, _maxs); return; @@ -87,12 +87,8 @@ inline Extents::Extents(const float _mins[3], const float _maxs[3]) inline Extents& Extents::operator=(const Extents& orig) { - mins[0] = orig.mins[0]; - mins[1] = orig.mins[1]; - mins[2] = orig.mins[2]; - maxs[0] = orig.maxs[0]; - maxs[1] = orig.maxs[1]; - maxs[2] = orig.maxs[2]; + mins = orig.mins; + maxs = orig.maxs; return *this; } @@ -100,73 +96,43 @@ inline Extents& Extents::operator=(const Extents& orig) inline void Extents::expandToBox(const Extents& test) { // test mins - if (test.mins[0] < mins[0]) - mins[0] = test.mins[0]; - if (test.mins[1] < mins[1]) - mins[1] = test.mins[1]; - if (test.mins[2] < mins[2]) - mins[2] = test.mins[2]; + mins = glm::min(mins, test.mins); // test maxs - if (test.maxs[0] > maxs[0]) - maxs[0] = test.maxs[0]; - if (test.maxs[1] > maxs[1]) - maxs[1] = test.maxs[1]; - if (test.maxs[2] > maxs[2]) - maxs[2] = test.maxs[2]; + maxs = glm::max(maxs, test.maxs); return; } -inline void Extents::expandToPoint(const float point[3]) +inline void Extents::expandToPoint(const glm::vec3 &point) { // test mins - if (point[0] < mins[0]) - mins[0] = point[0]; - if (point[1] < mins[1]) - mins[1] = point[1]; - if (point[2] < mins[2]) - mins[2] = point[2]; + mins = glm::min(mins, point); // test maxs - if (point[0] > maxs[0]) - maxs[0] = point[0]; - if (point[1] > maxs[1]) - maxs[1] = point[1]; - if (point[2] > maxs[2]) - maxs[2] = point[2]; + maxs = glm::max(maxs, point); return; } inline bool Extents::touches(const Extents& test) const { - if ((mins[0] > test.maxs[0]) || (maxs[0] < test.mins[0]) || - (mins[1] > test.maxs[1]) || (maxs[1] < test.mins[1]) || - (mins[2] > test.maxs[2]) || (maxs[2] < test.mins[2])) - return false; - return true; + return glm::all(glm::lessThanEqual(mins, test.maxs)) && + glm::all(glm::greaterThanEqual(maxs, test.mins)); } inline bool Extents::contains(const Extents& test) const { - if ((mins[0] < test.mins[0]) && (maxs[0] > test.maxs[0]) && - (mins[1] < test.mins[1]) && (maxs[1] > test.maxs[1]) && - (mins[2] < test.mins[2]) && (maxs[2] > test.maxs[2])) - return true; - return false; + return glm::all(glm::lessThan(mins, test.mins)) && + glm::all(glm::greaterThan(maxs, test.maxs)); } inline void Extents::addMargin(float margin) { // subtract from the mins - mins[0] -= margin; - mins[1] -= margin; - mins[2] -= margin; + mins -= margin; // add to the maxs - maxs[0] += margin; - maxs[1] += margin; - maxs[2] += margin; + maxs += margin; return; } diff --git a/include/Flag.h b/include/Flag.h index 67ad391ca8..4288d8f3d5 100644 --- a/include/Flag.h +++ b/include/Flag.h @@ -50,6 +50,7 @@ #include #include #include +#include /* common interface headers */ #include "global.h" @@ -154,10 +155,10 @@ class FlagType const std::string information() const; /** returns the color of the flag */ - const float* getColor() const; + const glm::vec3 &getColor() const; /** returns the color of the flag as it should be shown on the radar */ - const float* getRadarColor() const; + const glm::vec3 &getRadarColor() const; /** network serialization */ void* pack(void* buf) const; @@ -227,9 +228,9 @@ class Flag FlagStatus status; FlagEndurance endurance; PlayerId owner; // who has flag - float position[3]; // position on ground - float launchPosition[3]; // position flag launched from - float landingPosition[3]; // position flag will land + glm::vec3 position; // position on ground + glm::vec3 launchPosition; // position flag launched from + glm::vec3 landingPosition; // position flag will land float flightTime; // flight time so far float flightEnd; // total duration of flight float initialVelocity; // initial launch velocity diff --git a/include/FlagSceneNode.h b/include/FlagSceneNode.h index eb3c5f04b9..f68ca76ef4 100644 --- a/include/FlagSceneNode.h +++ b/include/FlagSceneNode.h @@ -22,24 +22,24 @@ class FlagSceneNode : public SceneNode { public: - FlagSceneNode(const GLfloat pos[3]); + FlagSceneNode(const glm::vec3 &pos); ~FlagSceneNode(); static void waveFlag(float dt); static void freeFlag(); - void move(const GLfloat pos[3]); + void move(const glm::vec3 &pos); void setAngle(GLfloat angle); void setWind(const GLfloat wind[3], float dt); void setBillboard(bool billboard); - const GLfloat* getColor() const + const glm::vec4 &getColor() const { return color; } void setColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a = 1.0f); - void setColor(const GLfloat* rgba); + void setColor(const glm::vec4 &rgba); void setTexture(const int); void notifyStyleChange() override; @@ -47,7 +47,7 @@ class FlagSceneNode : public SceneNode void addShadowNodes(SceneRenderer&) override; bool cullShadow(int planeCount, - const float (*planes)[4]) const override; + const glm::vec4 planes[]) const override; protected: class FlagRenderNode : public RenderNode { @@ -55,7 +55,7 @@ class FlagSceneNode : public SceneNode FlagRenderNode(const FlagSceneNode*); ~FlagRenderNode(); void render() override; - const GLfloat* getPosition() const override; + const glm::vec3 &getPosition() const override; private: const FlagSceneNode* sceneNode; int waveReference; @@ -67,7 +67,7 @@ class FlagSceneNode : public SceneNode GLfloat angle; GLfloat tilt; GLfloat hscl; - GLfloat color[4]; + glm::vec4 color; bool transparent; bool texturing; OpenGLGState gstate; diff --git a/include/FlagWarpSceneNode.h b/include/FlagWarpSceneNode.h index 02d5d7e547..d966d77d6a 100644 --- a/include/FlagWarpSceneNode.h +++ b/include/FlagWarpSceneNode.h @@ -21,19 +21,22 @@ // Inherits #include "SceneNode.h" +// System headers +#include + class FlagWarpSceneNode : public SceneNode { public: - FlagWarpSceneNode(const GLfloat pos[3]); + FlagWarpSceneNode(const glm::vec3 &pos); ~FlagWarpSceneNode(); void setSizeFraction(GLfloat); - GLfloat getDistance(const GLfloat*) const; - void move(const GLfloat pos[3]); + GLfloat getDistance(const glm::vec3 &) const override; + void move(const glm::vec3 &pos); - void notifyStyleChange(); - void addRenderNodes(SceneRenderer&); + void notifyStyleChange() override; + void addRenderNodes(SceneRenderer&) override; protected: class FlagWarpRenderNode : public RenderNode @@ -42,10 +45,10 @@ class FlagWarpSceneNode : public SceneNode FlagWarpRenderNode(const FlagWarpSceneNode*); ~FlagWarpRenderNode(); void render() override; - const GLfloat* getPosition() const override; + const glm::vec3 &getPosition() const override; private: const FlagWarpSceneNode* sceneNode; - static float ring[12][2]; + static glm::vec3 ring[12]; }; friend class FlagWarpRenderNode; @@ -53,7 +56,7 @@ class FlagWarpSceneNode : public SceneNode GLfloat size; OpenGLGState gstate; FlagWarpRenderNode renderNode; - static const GLfloat color[7][3]; + static const glm::vec3 color[7]; }; #endif // BZF_FLAG_WARP_SCENE_NODE_H diff --git a/include/FontManager.h b/include/FontManager.h index 341a3fd496..ca56883f34 100644 --- a/include/FontManager.h +++ b/include/FontManager.h @@ -50,10 +50,7 @@ class FontManager : public Singleton void drawString(float x, float y, float z, int faceID, float size, const std::string &text, - const float* resetColor = NULL); - void drawString(float x, float y, float z, const std::string &face, - float size, const std::string &text, - const float* resetColor = NULL); + const glm::vec3 resetColor = glm::vec3(-1.0f)); float getStrLength(int faceID, float size, const std::string &text, bool alreadyStripped = false); @@ -73,7 +70,7 @@ class FontManager : public Singleton friend class Singleton; private: - void getPulseColor(const GLfloat* color, GLfloat* pulseColor) const; + float getPulseFactor() const; ImageFont* getClosestSize(int faceID, float size, bool bigger); ImageFont* getClosestRealSize(int faceID, float desiredSize, float &actualSize); FontFaceMap faceNames; @@ -88,7 +85,7 @@ class FontManager : public Singleton static void callback(const std::string& name, void *); static void freeContext(void *data); static void initContext(void *data); - static GLfloat underlineColor[4]; + static glm::vec3 underlineColor; }; inline void FontManager::setDimFactor(float newDimFactor) @@ -99,7 +96,6 @@ inline void FontManager::setDimFactor(float newDimFactor) inline void FontManager::setOpacity(float newOpacity) { opacity = newOpacity; - underlineColor[3] = opacity; } inline void FontManager::setDarkness(float newDarkness) diff --git a/include/Frustum.h b/include/Frustum.h index df7d07dc97..5dd81b55a2 100644 --- a/include/Frustum.h +++ b/include/Frustum.h @@ -17,8 +17,14 @@ #ifndef BZF_FRUSTUM_H #define BZF_FRUSTUM_H +// 1st #include "common.h" +// System headers +#include +#include +#include + // FIXME -- will need a means for off center projections for // looking through teleporters @@ -28,25 +34,24 @@ class Frustum Frustum(); ~Frustum(); - const float* getEye() const; - const float* getDirection() const; - const float* getUp() const; - const float* getRight() const; - const float* getSide(int index) const; + const glm::vec3 &getEye() const; + const glm::vec4 &getDirection() const; + const glm::vec3 &getUp() const; + const glm::vec3 &getRight() const; + const glm::vec4 &getSide(int index) const; int getPlaneCount() const; - const float* getFarCorner(int index) const; + const glm::vec3 &getFarCorner(int index) const; float getTilt() const; // degrees float getRotation() const; // degrees float getNear() const; float getFar() const; - const float* getViewMatrix() const; + const glm::mat4 &getViewMatrix() const; float getFOVx() const; float getFOVy() const; - const float* getProjectionMatrix() const; - float getEyeDepth(const float*) const; + const glm::mat4 &getProjectionMatrix() const; float getAreaFactor() const; - void setView(const float* eye, const float* target); + void setView(const glm::vec3 &eye, const glm::vec3 &target); void setProjection(float fov, float m_near, float m_far, float m_deep_far, int width, int height, int viewHeight); @@ -60,41 +65,41 @@ class Frustum float width, float breadth); protected: - void makePlane(const float* v1, const float* v2, int); + void makePlane(const glm::vec3 &v1, const glm::vec3 &v2, int); protected: - float eye[3]; - float target[3]; - float right[3], up[3]; - float plane[6][4]; // pointing in + glm::vec3 eye; + glm::vec3 target; + glm::vec3 right, up; + glm::vec4 plane[6]; // pointing in int planeCount; - float farCorner[4][3]; + glm::vec3 farCorner[4]; float tilt; float rotation; - float viewMatrix[16]; - float billboardMatrix[16]; + glm::mat4 viewMatrix; + glm::mat4 billboardMatrix; float m_near, m_far; float fovx, fovy; float areaFactor; - float projectionMatrix[16]; - float deepProjectionMatrix[16]; + glm::mat4 projectionMatrix; + glm::mat4 deepProjectionMatrix; }; // // Frustum // -inline const float* Frustum::getEye() const +inline const glm::vec3 &Frustum::getEye() const { return eye; } -inline const float* Frustum::getDirection() const +inline const glm::vec4 &Frustum::getDirection() const { return plane[0]; } -inline const float* Frustum::getSide(int index) const +inline const glm::vec4 &Frustum::getSide(int index) const { return plane[index]; } @@ -104,7 +109,7 @@ inline int Frustum::getPlaneCount() const return planeCount; } -inline const float* Frustum::getFarCorner(int index) const +inline const glm::vec3 &Frustum::getFarCorner(int index) const { return farCorner[index]; } @@ -119,12 +124,12 @@ inline float Frustum::getRotation() const return rotation; } -inline const float* Frustum::getUp() const +inline const glm::vec3 &Frustum::getUp() const { return up; } -inline const float* Frustum::getRight() const +inline const glm::vec3 &Frustum::getRight() const { return right; } @@ -149,12 +154,12 @@ inline float Frustum::getFOVy() const return fovy; } -inline const float* Frustum::getViewMatrix() const +inline const glm::mat4 &Frustum::getViewMatrix() const { return viewMatrix; } -inline const float* Frustum::getProjectionMatrix() const +inline const glm::mat4 &Frustum::getProjectionMatrix() const { return projectionMatrix; } diff --git a/include/Intersect.h b/include/Intersect.h index dc467d0ef9..d175d418e0 100644 --- a/include/Intersect.h +++ b/include/Intersect.h @@ -17,7 +17,13 @@ #ifndef BZF_INTERSECT_H #define BZF_INTERSECT_H +// 1st #include "common.h" + +// System headers +#include + +// Common headers #include "Ray.h" #include "Frustum.h" @@ -31,14 +37,14 @@ enum IntersectLevel }; // returns normal to 2d rect (size 2dx x 2dy) by point p -void getNormalRect(const float* p, const float* boxPos, +void getNormalRect(const glm::vec2 p, const glm::vec2 boxPos, float boxAngle, float dx, - float dy, float* n); + float dy, glm::vec3 &n); // true iff 2d rect (size 2dx x 2dy) intersects circle (in z = const plane) -bool testRectCircle(const float* boxPos, float boxAngle, +bool testRectCircle(const glm::vec2 boxPos, float boxAngle, float dx, float dy, - const float* circPos, float circRadius); + const glm::vec2 circPos, float circRadius); // ray r1 started at time t1 minus ray r2 started at time t2 Ray rayMinusRay(const Ray& r1, float t1, @@ -49,14 +55,14 @@ float rayAtDistanceFromOrigin(const Ray& r, float radius); // return t at which ray intersects box (size 2dx x 2dy x dz) // (-1 if never, 0 if starts inside). -float timeRayHitsBlock(const Ray& r, const float* boxPos, +float timeRayHitsBlock(const Ray& r, const glm::vec3 &boxPos, float boxAngle, float dx, float dy, float dz); // return t at which ray intersects pyramid (size 2dx x 2dy x dz) // (-1 if never, 0 if starts inside). float timeRayHitsPyramids(const Ray& r, - const float* pyrPos, + const glm::vec3 &pyrPos, float pyrAngle, float dx, float dy, float dz, bool flipZ); @@ -69,15 +75,15 @@ float timeRayHitsTetra(const Ray& r, const float* mins, const float *maxs); // true if rectangles intersect (in z = const plane) -bool testRectRect(const float* p1, float angle1, +bool testRectRect(const glm::vec2 p1, float angle1, float dx1, float dy1, - const float* p2, float angle2, + const glm::vec2 p2, float angle2, float dx2, float dy2); // true if first rectangle contains second intersect (in z = const plane) -bool testRectInRect(const float* bigPos, float angle1, +bool testRectInRect(const glm::vec2 bigPos, float angle1, float dx1, float dy1, - const float* smallPos, float angle2, + const glm::vec2 smallPos, float angle2, float dx2, float dy2); // return t at which ray intersects 2d rect (size 2dx x 2dy) and side @@ -88,12 +94,12 @@ float timeAndSideRayHitsOrigRect( const float* rayDir, float dx, float dy, int& side); float timeAndSideRayHitsRect(const Ray& r, - const float* boxPos, float boxAngle, + const glm::vec3 &boxPos, float boxAngle, float dx, float dy, int& side); // return true if polygon touches the axis aligned box -bool testPolygonInAxisBox(int pointCount, const float (*points)[3], - const float* plane, const Extents& extents); +bool testPolygonInAxisBox(int pointCount, const glm::vec3 *points, + const glm::vec4 &plane, const Extents& extents); // return level of axis box intersection with Frumstum // possible values are Outside, Partial, and Contained. @@ -105,7 +111,7 @@ IntersectLevel testAxisBoxInFrustum(const Extents& extents, // is contained within all of the planes. // the occluder plane normals point inwards IntersectLevel testAxisBoxOcclusion(const Extents& extents, - const float (*planes)[4], + const glm::vec4 *planes, int planeCount); // return true if the ray will intersect with the diff --git a/include/LaserSceneNode.h b/include/LaserSceneNode.h index eeaa5401a5..855ff02578 100644 --- a/include/LaserSceneNode.h +++ b/include/LaserSceneNode.h @@ -20,19 +20,23 @@ // Inherits from #include "SceneNode.h" +// System headers +#include +#include + class LaserSceneNode : public SceneNode { public: - LaserSceneNode(const GLfloat pos[3], - const GLfloat forward[3]); + LaserSceneNode(const glm::vec3 &pos, + const glm::vec3 &forward); ~LaserSceneNode(); void setTexture(const int); - bool cull(const ViewFrustum&) const; + bool cull(const ViewFrustum&) const override; - void notifyStyleChange(); - void addRenderNodes(SceneRenderer&); + void notifyStyleChange() override; + void addRenderNodes(SceneRenderer&) override; void setColor ( float r, float g, float b ); void setCenterColor ( float r, float g, float b ); @@ -48,15 +52,15 @@ class LaserSceneNode : public SceneNode LaserRenderNode(const LaserSceneNode*); ~LaserRenderNode(); void render() override; - const GLfloat* getPosition() const override; + const glm::vec3 &getPosition() const override; private: void renderFlatLaser(); void renderGeoLaser(); const LaserSceneNode* sceneNode; - static GLfloat geom[6][2]; + static glm::vec2 geom[6]; }; - fvec4 color; - fvec4 centerColor; + glm::vec4 color; + glm::vec4 centerColor; bool first; friend class LaserRenderNode; diff --git a/include/Makefile.am b/include/Makefile.am index 0730ef41e7..2c1a606648 100644 --- a/include/Makefile.am +++ b/include/Makefile.am @@ -78,6 +78,7 @@ noinst_HEADERS = \ ObstacleModifier.h \ ObstacleSceneNodeGenerator.h \ OccluderSceneNode.h \ + OpenGLAPI.h \ OpenGLFramebuffer.h \ OpenGLGState.h \ OpenGLLight.h \ @@ -145,8 +146,6 @@ noinst_HEADERS = \ messages.h \ multicast.h \ network.h \ - vectors.h \ - vectors_old.h \ version.h \ win32.h diff --git a/include/MeshDrawInfo.h b/include/MeshDrawInfo.h index 75295aab57..a0334e033f 100644 --- a/include/MeshDrawInfo.h +++ b/include/MeshDrawInfo.h @@ -23,7 +23,6 @@ #include // Common headers -#include "vectors.h" #include "Extents.h" #include "BzMaterial.h" #include "MeshTransform.h" @@ -80,15 +79,17 @@ class MeshDrawInfo void setName(const std::string&); const std::string& getName() const; - const float* getSphere() const; + const glm::vec3 &getPosition() const; + float getRadius2() const; + const Extents& getExtents() const; int getLodCount() const; const DrawLod* getDrawLods() const; - const afvec3* getVertices() const; - const afvec3* getNormals() const; - const afvec2* getTexcoords() const; + const glm::vec3 *getVertices() const; + const glm::vec3 *getNormals() const; + const glm::vec2 *getTexcoords() const; int getRadarCount() const; const DrawLod* getRadarLods() const; @@ -126,7 +127,8 @@ class MeshDrawInfo MeshDrawMgr* drawMgr; Extents extents; - float sphere[4]; + glm::vec3 position; + float radius2; MaterialMap* matMap; MeshTransform::Tool* xformTool; @@ -134,16 +136,16 @@ class MeshDrawInfo // elements int cornerCount; Corner* corners; - afvec3* vertices; - afvec3* normals; - afvec2* texcoords; + glm::vec3 *vertices; + glm::vec3 *normals; + glm::vec2 *texcoords; int rawVertCount; - afvec3* rawVerts; + glm::vec3 *rawVerts; int rawNormCount; - afvec3* rawNorms; + glm::vec3 *rawNorms; int rawTxcdCount; - afvec2* rawTxcds; + glm::vec2 *rawTxcds; int lodCount; DrawLod* lods; @@ -179,10 +181,17 @@ inline const std::string& MeshDrawInfo::getName() const { return name; } -inline const float* MeshDrawInfo::getSphere() const + +inline const glm::vec3 &MeshDrawInfo::getPosition() const +{ + return position; +} + +inline float MeshDrawInfo::getRadius2() const { - return sphere; + return radius2; } + inline const Extents& MeshDrawInfo::getExtents() const { return extents; @@ -195,15 +204,15 @@ inline const DrawLod* MeshDrawInfo::getDrawLods() const { return lods; } -inline const afvec3* MeshDrawInfo::getVertices() const +inline const glm::vec3 *MeshDrawInfo::getVertices() const { return vertices; } -inline const afvec3* MeshDrawInfo::getNormals() const +inline const glm::vec3 *MeshDrawInfo::getNormals() const { return normals; } -inline const afvec2* MeshDrawInfo::getTexcoords() const +inline const glm::vec2 *MeshDrawInfo::getTexcoords() const { return texcoords; } @@ -309,7 +318,8 @@ class DrawSet DrawCmd* cmds; const BzMaterial* material; bool wantList; - float sphere[4]; + glm::vec3 position; + float radius2; int triangleCount; }; diff --git a/include/MeshFace.h b/include/MeshFace.h index 8514bee0f4..168b3a32c3 100644 --- a/include/MeshFace.h +++ b/include/MeshFace.h @@ -17,16 +17,18 @@ #ifndef BZF_MESH_FACE_OBSTACLE_H #define BZF_MESH_FACE_OBSTACLE_H -#include "common.h" +// Inherits from +#include "Obstacle.h" + +// System headers #include #include -#include "vectors.h" +#include + +// Common headers #include "Ray.h" -#include "Obstacle.h" #include "global.h" #include "BzMaterial.h" -//#include "PhysicsDrive.h" - class MeshFace : public Obstacle { @@ -37,43 +39,43 @@ class MeshFace : public Obstacle public: MeshFace(class MeshObstacle* mesh); MeshFace(MeshObstacle* mesh, int vertexCount, - float** vertices, float** normals, float** texcoords, + glm::vec3 *vertices[], glm::vec3 **normals, glm::vec2 **texcoords, const BzMaterial* material, int physics, bool noclusters, bool smoothBounce, bool drive, bool shoot, bool ricochet); ~MeshFace(); - const char* getType() const; + const char* getType() const override; static const char* getClassName(); // const - bool isValid() const; - bool isFlatTop() const; - - float intersect(const Ray&) const; - void getNormal(const float* p, float* n) const; - void get3DNormal(const float* p, float* n) const; - - bool inCylinder(const float* p, float radius, float height) const; - bool inBox(const float* p, float angle, - float halfWidth, float halfBreadth, float height) const; - bool inMovingBox(const float* oldP, float oldAngle, - const float *newP, float newAngle, - float halfWidth, float halfBreadth, float height) const; - bool isCrossing(const float* p, float angle, + bool isValid() const override; + bool isFlatTop() const override; + + float intersect(const Ray&) const override; + void getNormal(const glm::vec3 &p, glm::vec3 &n) const override; + void get3DNormal(const glm::vec3 &p, glm::vec3 &n) const override; + + bool inCylinder(const glm::vec3 &p, float radius, float height) const override; + bool inBox(const glm::vec3 &p, float angle, + float halfWidth, float halfBreadth, float height) const override; + bool inMovingBox(const glm::vec3 &oldP, float oldAngle, + const glm::vec3 &newP, float newAngle, + float halfWidth, float halfBreadth, float height) const override; + bool isCrossing(const glm::vec3 &p, float angle, float halfWidth, float halfBreadth, float height, - float* plane) const; + glm::vec4 *plane) const override; - bool getHitNormal(const float* pos1, float azimuth1, - const float* pos2, float azimuth2, + bool getHitNormal(const glm::vec3 &pos1, float azimuth1, + const glm::vec3 &pos2, float azimuth2, float halfWidth, float halfBreadth, - float height, float* normal) const; + float height, glm::vec3 &normal) const override; MeshObstacle* getMesh() const; int getVertexCount() const; bool useNormals() const; bool useTexcoords() const; - const float* getVertex(int index) const; - const float* getNormal(int index) const; - const float* getTexcoord(int index) const; - const float* getPlane() const; + const glm::vec3 &getVertex(int index) const; + const glm::vec3 &getNormal(int index) const; + const glm::vec2 &getTexcoord(int index) const; + const glm::vec4 &getPlane() const; const BzMaterial* getMaterial() const; int getPhysicsDriver() const; bool noClusters() const; @@ -90,11 +92,11 @@ class MeshFace : public Obstacle void setLink(const MeshFace* link); const MeshFace* getLink() const; - int packSize() const; - void *pack(void*) const; - const void *unpack(const void*); + int packSize() const override; + void *pack(void*) const override; + const void *unpack(const void*) override; - void print(std::ostream& out, const std::string& indent) const; + void print(std::ostream& out, const std::string& indent) const override; public: mutable float scratchPad; @@ -107,16 +109,16 @@ class MeshFace : public Obstacle class MeshObstacle* mesh; int vertexCount; - float** vertices; - float** normals; - float** texcoords; + glm::vec3 **vertices; + glm::vec3 **normals; + glm::vec2 **texcoords; const BzMaterial* bzMaterial; bool smoothBounce; bool noclusters; int phydrv; - afvec4 plane; - afvec4* edgePlanes; + glm::vec4 plane; + glm::vec4 *edgePlanes; MeshFace* edges; // edge 0 is between vertex 0 and 1, etc... // not currently used for anything @@ -181,7 +183,7 @@ inline int MeshFace::getPhysicsDriver() const return phydrv; } -inline const float* MeshFace::getPlane() const +inline const glm::vec4 &MeshFace::getPlane() const { return plane; } @@ -191,19 +193,19 @@ inline int MeshFace::getVertexCount() const return vertexCount; } -inline const float* MeshFace::getVertex(int index) const +inline const glm::vec3 &MeshFace::getVertex(int index) const { - return (const float*)vertices[index]; + return *vertices[index]; } -inline const float* MeshFace::getNormal(int index) const +inline const glm::vec3 &MeshFace::getNormal(int index) const { - return (const float*)normals[index]; + return *normals[index]; } -inline const float* MeshFace::getTexcoord(int index) const +inline const glm::vec2 &MeshFace::getTexcoord(int index) const { - return (const float*)texcoords[index]; + return *texcoords[index]; } inline bool MeshFace::useNormals() const diff --git a/include/MeshFragSceneNode.h b/include/MeshFragSceneNode.h index 9b134bb670..51c5a23a7b 100644 --- a/include/MeshFragSceneNode.h +++ b/include/MeshFragSceneNode.h @@ -43,7 +43,7 @@ class MeshFragSceneNode : public WallSceneNode ~MeshFragSceneNode(); // virtual functions from SceneNode - const GLfloat* getPlane() const override; + const glm::vec4 *getPlane() const override; bool cull(const ViewFrustum&) const override; void addShadowNodes(SceneRenderer&) override; void addRenderNodes(SceneRenderer&) override; @@ -65,7 +65,7 @@ class MeshFragSceneNode : public WallSceneNode void setStyle(int style); void render() override; void renderShadow() override; - const GLfloat* getPosition() const override; + const glm::vec3 &getPosition() const override; private: void drawV() const; // draw with just vertices @@ -93,9 +93,9 @@ class MeshFragSceneNode : public WallSceneNode bool noRadar; bool noShadow; GLint arrayCount; - GLfloat* vertices; - GLfloat* normals; - GLfloat* texcoords; + glm::vec3 *vertices; + glm::vec3 *normals; + glm::vec2 *texcoords; friend class MeshFragSceneNode::Geometry; }; diff --git a/include/MeshObstacle.h b/include/MeshObstacle.h index 3abba4cad6..c42dca2391 100644 --- a/include/MeshObstacle.h +++ b/include/MeshObstacle.h @@ -17,13 +17,17 @@ #ifndef BZF_MESH_OBSTACLE_H #define BZF_MESH_OBSTACLE_H -#include "common.h" +// Inherits from +#include "Obstacle.h" + +// System headers #include #include #include -#include "vectors.h" +#include + +// Common headers #include "Ray.h" -#include "Obstacle.h" #include "MeshFace.h" #include "MeshTransform.h" @@ -35,10 +39,10 @@ class MeshObstacle : public Obstacle MeshObstacle(); MeshObstacle(const MeshTransform& transform, const std::vector& checkTypes, - const std::vector& checkPoints, - const std::vector& vertices, - const std::vector& normals, - const std::vector& texcoords, + const std::vector& checkPoints, + const std::vector& vertices, + const std::vector& normals, + const std::vector& texcoords, int faceCount, bool noclusters, bool bounce, bool drive, bool shoot, bool ricochet); @@ -53,7 +57,7 @@ class MeshObstacle : public Obstacle void finalize(); - Obstacle* copyWithTransform(const MeshTransform&) const; + Obstacle* copyWithTransform(const MeshTransform&) const override; void copyFace(int face, MeshObstacle* mesh) const; void setName(const std::string& name); @@ -67,62 +71,58 @@ class MeshObstacle : public Obstacle OutsidePartiy = 3 }; - const char* getType() const; + const char* getType() const override; static const char* getClassName(); // const - bool isValid() const; - - float intersect(const Ray&) const; - void getNormal(const float* p, float* n) const; - void get3DNormal(const float* p, float* n) const; - - bool inCylinder(const float* p, float radius, float height) const; - bool inBox(const float* p, float angle, - float halfWidth, float halfBreadth, float height) const; - bool inMovingBox(const float* oldP, float oldAngle, - const float *newP, float newAngle, - float halfWidth, float halfBreadth, float height) const; - bool isCrossing(const float* p, float angle, - float halfWidth, float halfBreadth, float height, - float* plane) const; - - bool getHitNormal(const float* pos1, float azimuth1, - const float* pos2, float azimuth2, + bool isValid() const override; + + float intersect(const Ray&) const override; + void getNormal(const glm::vec3 &p, glm::vec3 &n) const override; + void get3DNormal(const glm::vec3 &p, glm::vec3 &n) const override; + + bool inCylinder(const glm::vec3 &p, float radius, float height) const override; + bool inBox(const glm::vec3 &p, float angle, + float halfWidth, float halfBreadth, float height) const override; + bool inMovingBox(const glm::vec3 &oldP, float oldAngle, + const glm::vec3 &newP, float newAngle, + float halfWidth, float halfBreadth, float height) const override; + + bool getHitNormal(const glm::vec3 &pos1, float azimuth1, + const glm::vec3 &pos2, float azimuth2, float halfWidth, float halfBreadth, - float height, float* normal) const; + float height, glm::vec3 &normal) const override; - bool containsPoint(const float point[3]) const; - bool containsPointNoOctree(const float point[3]) const; + bool containsPoint(const glm::vec3 &point) const; + bool containsPointNoOctree(const glm::vec3 &point) const; const char *getCheckTypes() const; - const afvec3 *getCheckPoints() const; - afvec3 *getVertices() const; - afvec3 *getNormals() const; - afvec2 *getTexcoords() const; + const glm::vec3 *getCheckPoints() const; + glm::vec3 *getVertices() const; + glm::vec3 *getNormals() const; + glm::vec2 *getTexcoords() const; int getCheckCount() const; int getVertexCount() const; int getNormalCount() const; int getTexcoordCount() const; int getFaceCount() const; MeshFace* getFace(int face) const; - const float* getPosition() const; bool useSmoothBounce() const; bool noClusters() const; MeshDrawInfo* getDrawInfo() const; void setDrawInfo(MeshDrawInfo*); - int packSize() const; - void *pack(void*) const; - const void *unpack(const void*); + int packSize() const override; + void *pack(void*) const override; + const void *unpack(const void*) override; - void print(std::ostream& out, const std::string& indent) const; - void printOBJ(std::ostream& out, const std::string& indent) const; + void print(std::ostream& out, const std::string& indent) const override; + void printOBJ(std::ostream& out, const std::string& indent) const override; private: void makeFacePointers(const std::vector& _vertices, const std::vector& _normals, const std::vector& _texcoords, - float**& v, float**& n, float**& t); + glm::vec3 *v[], glm::vec3 **n, glm::vec2 **t); private: static const char* typeName; @@ -131,13 +131,13 @@ class MeshObstacle : public Obstacle int checkCount; char* checkTypes; - afvec3* checkPoints; + glm::vec3 *checkPoints; int vertexCount; - afvec3* vertices; + glm::vec3 *vertices; int normalCount; - afvec3* normals; + glm::vec3 *normals; int texcoordCount; - afvec2* texcoords; + glm::vec2 *texcoords; int faceCount, faceSize; MeshFace** faces; bool smoothBounce; @@ -154,22 +154,22 @@ inline const char *MeshObstacle::getCheckTypes() const return checkTypes; } -inline const afvec3 *MeshObstacle::getCheckPoints() const +inline const glm::vec3 *MeshObstacle::getCheckPoints() const { return checkPoints; } -inline afvec3 *MeshObstacle::getVertices() const +inline glm::vec3 *MeshObstacle::getVertices() const { return vertices; } -inline afvec3 *MeshObstacle::getNormals() const +inline glm::vec3 *MeshObstacle::getNormals() const { return normals; } -inline afvec2 *MeshObstacle::getTexcoords() const +inline glm::vec2 *MeshObstacle::getTexcoords() const { return texcoords; } @@ -204,11 +204,6 @@ inline MeshFace* MeshObstacle::getFace(int face) const return faces[face]; } -inline const float* MeshObstacle::getPosition() const -{ - return pos; -} - inline bool MeshObstacle::useSmoothBounce() const { return smoothBounce; diff --git a/include/MeshPolySceneNode.h b/include/MeshPolySceneNode.h index 70b305b42c..a7ba7c84d6 100644 --- a/include/MeshPolySceneNode.h +++ b/include/MeshPolySceneNode.h @@ -21,29 +21,32 @@ // Inherits from #include "WallSceneNode.h" +// System headers +#include + class MeshPolySceneNode : public WallSceneNode { public: - MeshPolySceneNode(const float plane[4], + MeshPolySceneNode(const glm::vec4 &plane, bool noRadar, bool noShadow, - const GLfloat3Array& vertices, - const GLfloat3Array& normals, - const GLfloat2Array& texcoords); + const std::vector &vertices, + const std::vector &normals, + const std::vector &texcoords); ~MeshPolySceneNode(); - bool cull(const ViewFrustum& frustum) const; - bool inAxisBox (const Extents& exts) const; - int getVertexCount () const; - const GLfloat* getVertex (int vertex) const; - const GLfloat (*getVertices() const)[3]; + bool cull(const ViewFrustum& frustum) const override; + bool inAxisBox (const Extents& exts) const override; + int getVertexCount () const override; + const glm::vec3 &getVertex (int vertex) const override; + const glm::vec3 *getVertices() const; - int split(const float* plane, SceneNode*&, SceneNode*&) const; + int split(const glm::vec4 &plane, SceneNode*&, SceneNode*&) const override; - void addRenderNodes(SceneRenderer&); - void addShadowNodes(SceneRenderer&); - void renderRadar(); + void addRenderNodes(SceneRenderer&) override; + void addShadowNodes(SceneRenderer&) override; + void renderRadar() override; - void getRenderNodes(std::vector& rnodes); + void getRenderNodes(std::vector& rnodes) override; protected: @@ -51,10 +54,10 @@ class MeshPolySceneNode : public WallSceneNode { public: Geometry(MeshPolySceneNode*, - const GLfloat3Array& vertices, - const GLfloat3Array& normals, - const GLfloat2Array& texcoords, - const GLfloat* normal); + const std::vector &vertices, + const std::vector &normals, + const std::vector &texcoords, + const glm::vec4 &plane); ~Geometry(); void setStyle(int _style) { @@ -62,10 +65,10 @@ class MeshPolySceneNode : public WallSceneNode } void render() override; void renderShadow() override; - const GLfloat* getVertex(int i) const; - const GLfloat (*getVertices() const)[3]; + const glm::vec3 &getVertex(int i) const; + const glm::vec3 *getVertices() const; int getVertexCount() const; - const GLfloat* getPosition() const override; + const glm::vec3 &getPosition() const override; private: void drawV() const; // draw with just vertices void drawVT() const; // draw with texcoords @@ -74,35 +77,35 @@ class MeshPolySceneNode : public WallSceneNode private: MeshPolySceneNode* sceneNode; int style; - const GLfloat* normal; + const glm::vec4 &plane; public: - GLfloat3Array vertices; - GLfloat3Array normals; - GLfloat2Array texcoords; + const std::vector vertices; + const std::vector normals; + const std::vector texcoords; }; private: - int splitWallVTN(const GLfloat* plane, - const GLfloat3Array& vertices, - const GLfloat3Array& normals, - const GLfloat2Array& texcoords, + int splitWallVTN(const glm::vec4 &plane, + const std::vector &vertices, + const std::vector &normals, + const std::vector &texcoords, SceneNode*& front, SceneNode*& back) const; void splitEdgeVTN(float d1, float d2, - const GLfloat* p1, const GLfloat* p2, - const GLfloat* n1, const GLfloat* n2, - const GLfloat* uv1, const GLfloat* uv2, - GLfloat* p, GLfloat* n, GLfloat* uv) const; - - int splitWallVT(const GLfloat* plane, - const GLfloat3Array& vertices, - const GLfloat2Array& texcoords, + const glm::vec3 &p1, const glm::vec3 &p2, + const glm::vec3 &n1, const glm::vec3 &n2, + const glm::vec2 &uv1, const glm::vec2 &uv2, + glm::vec3 &p, glm::vec3 &n, glm::vec2 &uv) const; + + int splitWallVT(const glm::vec4 &plane, + const std::vector &vertices, + const std::vector &texcoords, SceneNode*& front, SceneNode*& back) const; void splitEdgeVT(float d1, float d2, - const GLfloat* p1, const GLfloat* p2, - const GLfloat* uv1, const GLfloat* uv2, - GLfloat* p, GLfloat* uv) const; + const glm::vec3 &p1, const glm::vec3 &p2, + const glm::vec2 &uv1, const glm::vec2 &uv2, + glm::vec3 &p, glm::vec2 &uv) const; Geometry node; bool noRadar; @@ -111,7 +114,7 @@ class MeshPolySceneNode : public WallSceneNode inline int MeshPolySceneNode::Geometry::getVertexCount() const { - return vertices.getSize(); + return vertices.size(); } inline int MeshPolySceneNode::getVertexCount () const @@ -119,22 +122,22 @@ inline int MeshPolySceneNode::getVertexCount () const return node.getVertexCount(); } -inline const GLfloat* MeshPolySceneNode::Geometry::getVertex(int i) const +inline const glm::vec3 &MeshPolySceneNode::Geometry::getVertex(int i) const { return vertices[i]; } -inline const GLfloat (*MeshPolySceneNode::Geometry::getVertices() const)[3] +inline const glm::vec3 *MeshPolySceneNode::Geometry::getVertices() const { - return vertices.getArray(); + return &vertices[0]; } -inline const GLfloat* MeshPolySceneNode::getVertex(int i) const +inline const glm::vec3 &MeshPolySceneNode::getVertex(int i) const { return node.getVertex(i); } -inline const GLfloat (*MeshPolySceneNode::getVertices() const)[3] +inline const glm::vec3 *MeshPolySceneNode::getVertices() const { return node.getVertices(); } diff --git a/include/MeshSceneNode.h b/include/MeshSceneNode.h index bfb6591ea8..97ee60e3fe 100644 --- a/include/MeshSceneNode.h +++ b/include/MeshSceneNode.h @@ -51,16 +51,16 @@ class MeshSceneNode : public SceneNode // virtual functions from SceneNode - void notifyStyleChange(); + void notifyStyleChange() override; - bool cull(const ViewFrustum&) const; - bool inAxisBox(const Extents& exts) const; + bool cull(const ViewFrustum&) const override; + bool inAxisBox(const Extents& exts) const override; - void addShadowNodes(SceneRenderer&); - void addRenderNodes(SceneRenderer&); - void renderRadar(); + void addShadowNodes(SceneRenderer&) override; + void addRenderNodes(SceneRenderer&) override; + void renderRadar() override; - void getRenderNodes(std::vector& rnodes); + void getRenderNodes(std::vector& rnodes) override; void makeXFormList(); static void initContext(void* data); @@ -85,8 +85,8 @@ class MeshSceneNode : public SceneNode { const BzMaterial* bzmat; OpenGLGState gstate; - GLfloat color[4]; - const GLfloat* colorPtr; + glm::vec4 color; + const glm::vec4 *colorPtr; bool drawRadar; bool drawShadow; bool needsSorting; diff --git a/include/MeshSceneNodeGenerator.h b/include/MeshSceneNodeGenerator.h index 1c6a1d81df..632be8e4b9 100644 --- a/include/MeshSceneNodeGenerator.h +++ b/include/MeshSceneNodeGenerator.h @@ -36,9 +36,9 @@ class MeshSceneNodeGenerator const BzMaterial* mat); static MeshPolySceneNode* getMeshPolySceneNode(const MeshFace* face); - static bool makeTexcoords(const float* plane, - const GLfloat3Array& vertices, - GLfloat2Array& texcoords); + static void makeTexcoords(const glm::vec4 &plane, + const std::vector &vertices, + std::vector &texcoords); protected: MeshSceneNodeGenerator(const MeshObstacle*); diff --git a/include/MeshTransform.h b/include/MeshTransform.h index 152ab3bf28..69994c4c90 100644 --- a/include/MeshTransform.h +++ b/include/MeshTransform.h @@ -20,6 +20,9 @@ #include #include #include +#include +#include +#include enum TransformType { @@ -50,10 +53,10 @@ class MeshTransform void prepend(const MeshTransform& transform); bool setName(const std::string& name); - void addShift(const float shift[3]); - void addScale(const float scale[3]); + void addShift(const glm::vec3 &shift); + void addScale(const glm::vec3 &scale); void addShear(const float shear[3]); - void addSpin(const float degrees, const float normal[3]); + void addSpin(const float degrees, const glm::vec3 &normal); void addReference(int transform); bool isEmpty() const @@ -87,11 +90,11 @@ class MeshTransform bool isInverted() const; bool isSkewed() const; // scaled or sheared - void modifyVertex(float vertex[3]) const; - void modifyNormal(float normal[3]) const; - void modifyOldStyle(float pos[3], float size[3], + void modifyVertex(glm::vec3 &vertex) const; + void modifyNormal(glm::vec3 &normal) const; + void modifyOldStyle(glm::vec3 &pos, glm::vec3 &size, float& angle, bool& flipz) const; - const float* getMatrix() const; + const glm::mat4 &getMatrix() const; private: void processTransforms(const std::vector& tforms); @@ -99,8 +102,8 @@ class MeshTransform bool empty; bool inverted; bool skewed; - float vertexMatrix[4][4]; - float normalMatrix[3][3]; + glm::mat4 vertexMatrix; + glm::mat3 normalMatrix; }; friend class MeshTransform::Tool; @@ -116,9 +119,9 @@ inline bool MeshTransform::Tool::isSkewed() const return skewed; } -inline const float* MeshTransform::Tool::getMatrix() const +inline const glm::mat4 &MeshTransform::Tool::getMatrix() const { - return (const float*)vertexMatrix; + return vertexMatrix; } diff --git a/include/Obstacle.h b/include/Obstacle.h index c89f214450..dcec11441b 100644 --- a/include/Obstacle.h +++ b/include/Obstacle.h @@ -28,6 +28,7 @@ // system headers #include #include +#include // common headers #include "Extents.h" @@ -64,7 +65,7 @@ class Obstacle @param shoot @c true if the obstacle is shootthrough, i.e. bullets can pass through it */ - Obstacle(const float* pos, float rotation, float hwidth, float hbreadth, + Obstacle(const glm::vec3 &pos, float rotation, float hwidth, float hbreadth, float height, bool drive = false, bool shoot = false, bool rico = false); /** This function makes a copy using the given transform */ @@ -108,10 +109,10 @@ class Obstacle const Extents& getExtents() const; /** This function returns the position of this obstacle. */ - const float* getPosition() const; + const glm::vec3 &getPosition() const; /** This function returns the sizes of this obstacle. */ - const float* getSize() const; + const glm::vec3 &getSize() const; /** This function returns the obstacle's rotation around its own Y axis. */ float getRotation() const; @@ -132,27 +133,27 @@ class Obstacle /** This function computes the two-dimensional surface normal of this obstacle at the point @c p. The normal is stored in @c n. */ - virtual void getNormal(const float* p, float* n) const = 0; + virtual void getNormal(const glm::vec3 &p, glm::vec3 &n) const = 0; /** This function computes the three-dimensional surface normal of this obstacle at the point @c p. The normal is stored in @c n. */ - virtual void get3DNormal(const float* p, float* n) const; + virtual void get3DNormal(const glm::vec3 &p, glm::vec3 &n) const; /** This function checks if a tank, approximated as a cylinder with base centre in point @c p and radius @c radius, intersects this obstacle. */ - virtual bool inCylinder(const float* p, float radius, float height) const = 0; + virtual bool inCylinder(const glm::vec3 &p, float radius, float height) const = 0; /** This function checks if a tank, approximated as a box rotated around its Z axis, intersects this obstacle. */ - virtual bool inBox(const float* p, float angle, - float halfWidth, float halfBreadth, float height) const = 0; + virtual bool inBox(const glm::vec3 &p, float angle, + float halfWidth, float halfBreadth, float height) const; /** This function checks if a tank, approximated as a box rotated around its Z axis, intersects this obstacle. It also factors in the difference between the old Z location and the new Z location */ - virtual bool inMovingBox(const float* oldP, float oldAngle, - const float* newP, float newAngle, - float halfWidth, float halfBreadth, float height) const = 0; + virtual bool inMovingBox(const glm::vec3 &oldP, float oldAngle, + const glm::vec3 &newP, float newAngle, + float halfWidth, float halfBreadth, float height) const; /** This function checks if a horizontal rectangle crosses the surface of this obstacle. @@ -163,9 +164,9 @@ class Obstacle @param plane The tangent plane of the obstacle where it's intersected by the rectangle will be stored here */ - virtual bool isCrossing(const float* p, float angle, + virtual bool isCrossing(const glm::vec3 &p, float angle, float halfWidth, float halfBreadth, float height, - float* plane) const; + glm::vec4 *plane) const; /** This function checks if a box moving from @c pos1 to @c pos2 will hit this obstacle, and if it does what the surface normal at the hitpoint is. @@ -181,10 +182,10 @@ class Obstacle @returns @c true if the box hits this obstacle, @c false otherwise */ - virtual bool getHitNormal(const float* pos1, float azimuth1, - const float* pos2, float azimuth2, + virtual bool getHitNormal(const glm::vec3 &pos1, float azimuth1, + const glm::vec3 &pos2, float azimuth2, float halfWidth, float halfBreadth, - float height, float* normal) const = 0; + float height, glm::vec3 &normal) const; /** This function returns @c true if tanks can pass through this object, @c false if they can't. */ @@ -266,12 +267,12 @@ class Obstacle rectangle is at @c pos1 and 1 is the time when it's at @c pos2, and -1 means "no hit" */ - float getHitNormal(const float* pos1, float azimuth1, - const float* pos2, float azimuth2, + float getHitNormal(const glm::vec3 &pos1, float azimuth1, + const glm::vec3 &pos2, float azimuth2, float halfWidth, float halfBreadth, - const float* oPos, float oAzimuth, + const glm::vec3 &oPos, float oAzimuth, float oWidth, float oBreadth, float oHeight, - float* normal) const; + glm::vec3 &normal) const; protected: static int getObjCounter(); @@ -279,8 +280,8 @@ class Obstacle protected: Extents extents; - float pos[3]; - float size[3]; // width, breadth, height + glm::vec3 pos; + glm::vec3 size; // width, breadth, height float angle; bool driveThrough; bool shootThrough; @@ -305,12 +306,12 @@ inline const Extents& Obstacle::getExtents() const return extents; } -inline const float* Obstacle::getPosition() const +inline const glm::vec3 &Obstacle::getPosition() const { return pos; } -inline const float* Obstacle::getSize() const +inline const glm::vec3 &Obstacle::getSize() const { return size; } @@ -335,11 +336,6 @@ inline float Obstacle::getHeight() const return size[2]; } -inline void Obstacle::get3DNormal(const float *p, float *n) const -{ - getNormal(p, n); -} - inline bool Obstacle::isDriveThrough() const { return driveThrough; diff --git a/include/OccluderSceneNode.h b/include/OccluderSceneNode.h index ef0cff448e..ff2a4eb780 100644 --- a/include/OccluderSceneNode.h +++ b/include/OccluderSceneNode.h @@ -40,14 +40,14 @@ class OccluderSceneNode : public SceneNode int getVertexCount () const override; - const GLfloat* getPlane() const override; + const glm::vec4 *getPlane() const override; - const GLfloat* getVertex (int vertex) const override; + const glm::vec3 &getVertex (int vertex) const override; private: int vertexCount; - GLfloat3* vertices; - GLfloat plane[4]; // unit normal, distance to origin + glm::vec3 *vertices; + const glm::vec4 plane; // unit normal, distance to origin }; diff --git a/include/OpenGLAPI.h b/include/OpenGLAPI.h new file mode 100644 index 0000000000..a2992550cb --- /dev/null +++ b/include/OpenGLAPI.h @@ -0,0 +1,48 @@ +/* bzflag + * Copyright (c) 1993-2023 Tim Riker + * + * This package is free software; you can redistribute it and/or + * modify it under the terms of the license found in the file + * named COPYING that should have accompanied this file. + * + * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. + */ + +#ifndef _OPENGLAPI_H +#define _OPENGLAPI_H + +// 1st +#include "common.h" + +// System headers +#include + +extern void glColor(const glm::vec3 &c, float alpha = 1.0f); +extern void glColor(const glm::vec4 &c); +extern void glVertex(const glm::vec2 &p); +extern void glVertex(const glm::vec2 &p, float z); +extern void glVertex(const glm::vec3 &p); +extern void glNormal(const glm::vec2 &n); +extern void glNormal(const glm::vec3 &n); +extern void glTexCoord(const glm::vec2 &t); +extern void glLoadMatrix(const glm::mat4 &m); +extern void glMultMatrix(const glm::mat4 &m); +extern void glTranslate(const glm::vec3 &v); +extern glm::vec4 glGetFogColor(); +extern void glSetFogColor(const glm::vec4 fogColor); +extern glm::ivec4 glGetViewport(); +extern void glVertexPointer(const glm::vec3 vertices[]); +extern void glTexCoordPointer(const glm::vec2 texCoords[]); +extern void glClipPlane(int id, const glm::dvec4 &plane); + +#endif // _OPENGLAPI_H + +// Local Variables: *** +// mode: C++ *** +// tab-width: 4 *** +// c-basic-offset: 4 *** +// indent-tabs-mode: nil *** +// End: *** +// ex: shiftwidth=4 tabstop=4 diff --git a/include/OpenGLLight.h b/include/OpenGLLight.h index f36da7550e..857d175c41 100644 --- a/include/OpenGLLight.h +++ b/include/OpenGLLight.h @@ -22,6 +22,7 @@ // system headers #include +#include // common headers #include "bzfgl.h" @@ -36,15 +37,16 @@ class OpenGLLight ~OpenGLLight(); OpenGLLight& operator=(const OpenGLLight&); - const GLfloat* getPosition() const; - const GLfloat* getColor() const; + const glm::vec4 &getPosition() const; + const glm::vec4 &getColor() const; const GLfloat* getAttenuation() const; GLfloat getMaxDist() const; - void setDirection(const GLfloat* xyz); - void setPosition(const GLfloat* xyz); + void setDirection(const glm::vec3 &xyz); + void setPosition(const glm::vec3 &xyz); void setColor(GLfloat r, GLfloat g, GLfloat b); void setColor(const GLfloat* rgb); + void setColor(const glm::vec3 &rgb); void setAttenuation(const GLfloat* clq); void setAttenuation(int index, GLfloat value); @@ -71,8 +73,8 @@ class OpenGLLight static void initContext(void*); private: - GLfloat pos[4]; - GLfloat color[4]; + glm::vec4 pos; + glm::vec4 color; GLfloat atten[3]; GLfloat maxDist; GLfloat importance; @@ -86,12 +88,12 @@ class OpenGLLight // OpenGLLight // -inline const GLfloat* OpenGLLight::getPosition() const +inline const glm::vec4 &OpenGLLight::getPosition() const { return pos; } -inline const GLfloat* OpenGLLight::getColor() const +inline const glm::vec4 &OpenGLLight::getColor() const { return color; } diff --git a/include/OpenGLMaterial.h b/include/OpenGLMaterial.h index ec68697068..341ecc6e2e 100644 --- a/include/OpenGLMaterial.h +++ b/include/OpenGLMaterial.h @@ -30,15 +30,21 @@ #ifndef BZF_OPENGL_MATERIAL_H #define BZF_OPENGL_MATERIAL_H +// 1st #include "common.h" + +// System headers +#include + +// Common headers #include "bzfgl.h" class OpenGLMaterial { public: OpenGLMaterial(); - OpenGLMaterial(const GLfloat specularRGB[3], - const GLfloat emissiveRGB[3], + OpenGLMaterial(const glm::vec3 &specularRGB, + const glm::vec3 &emissiveRGB, GLfloat shininess = 0.0f); OpenGLMaterial(const OpenGLMaterial&); ~OpenGLMaterial(); @@ -48,8 +54,8 @@ class OpenGLMaterial bool operator!=(const OpenGLMaterial&) const; bool operator<(const OpenGLMaterial&) const; - const GLfloat* getSpecularColor() const; - const GLfloat* getEmissiveColor() const; + const glm::vec3 &getSpecularColor() const; + const glm::vec3 &getEmissiveColor() const; GLfloat getShininess() const; bool isValid() const; @@ -63,12 +69,12 @@ class OpenGLMaterial void ref(); void unref(); void execute(); - static Rep* getRep(const GLfloat* specular, - const GLfloat* emissive, + static Rep* getRep(const glm::vec3 &specular, + const glm::vec3 &emissive, GLfloat shininess); private: - Rep(const GLfloat* specular, - const GLfloat* emissive, + Rep(const glm::vec3 &specular, + const glm::vec3 &emissive, GLfloat shininess); static void freeContext(void*); static void initContext(void*); @@ -77,8 +83,8 @@ class OpenGLMaterial Rep* prev; Rep* next; GLuint list; - GLfloat specular[4]; - GLfloat emissive[4]; + glm::vec3 specular; + glm::vec3 emissive; GLfloat shininess; static Rep* head; }; @@ -89,12 +95,12 @@ class OpenGLMaterial // OpenGLMaterial // -inline const GLfloat* OpenGLMaterial::getSpecularColor() const +inline const glm::vec3 &OpenGLMaterial::getSpecularColor() const { return rep->specular; } -inline const GLfloat* OpenGLMaterial::getEmissiveColor() const +inline const glm::vec3 &OpenGLMaterial::getEmissiveColor() const { return rep->emissive; } diff --git a/include/OpenGLUtils.h b/include/OpenGLUtils.h index 80ad522bb2..70917748a9 100644 --- a/include/OpenGLUtils.h +++ b/include/OpenGLUtils.h @@ -19,10 +19,10 @@ #include #include #include +#include // common headers #include "bzfgl.h" -#include "vectors.h" class BzMaterial; @@ -33,7 +33,7 @@ class OpenGLGState; extern void bzMat2gstate(const BzMaterial* bzmat, OpenGLGState& gstate, - fvec4& color, const fvec4*& colorPtr); + glm::vec4 &color, const glm::vec4 *&colorPtr); extern bool parseBlendFactors(const std::string& s, GLenum& src, GLenum& dst); diff --git a/include/Pack.h b/include/Pack.h index 2f8561c0d5..aa2aede8a7 100644 --- a/include/Pack.h +++ b/include/Pack.h @@ -21,9 +21,12 @@ #ifndef BZF_PACK_H #define BZF_PACK_H - +// 1st #include "common.h" + +// System headers #include +#include extern void* nboPackUByte(void*, uint8_t); @@ -33,6 +36,7 @@ extern void* nboPackUShort(void*, uint16_t); extern void* nboPackUInt(void*, uint32_t); extern void* nboPackFloat(void*, float); extern void* nboPackVector(void*, const float*); +extern void* nboPackVector(void*, const glm::vec3 &); extern void* nboPackString(void*, const void*, int len); extern void* nboPackStdString(void*, const std::string& str); @@ -43,6 +47,7 @@ extern const void* nboUnpackUShort(const void*, uint16_t&); extern const void* nboUnpackUInt(const void*, uint32_t&); extern const void* nboUnpackFloat(const void*, float&); extern const void* nboUnpackVector(const void*, float*); +extern const void* nboUnpackVector(const void*, glm::vec3 &); extern const void* nboUnpackString(const void*, void*, int len); extern const void* nboUnpackStdString(const void*, std::string& str); extern const void* nboUnpackStdStringRaw(const void*, std::string& str); diff --git a/include/ParseColor.h b/include/ParseColor.h index 10f9578fd0..dc2aed10ba 100644 --- a/include/ParseColor.h +++ b/include/ParseColor.h @@ -16,12 +16,16 @@ // 1st #include "common.h" +// System interfaces #include #include +#include extern bool parseColorCString(const char* str, float color[4]); extern bool parseColorString(const std::string& str, float color[4]); +extern bool parseColorString(const std::string& str, glm::vec4 &color); extern bool parseColorStream(std::istream& input, float color[4]); +extern bool parseColorStream(std::istream& input, glm::vec4 &color); #endif // _PARSE_COLOR_H_ diff --git a/include/PlayerState.h b/include/PlayerState.h index a94b76627d..1e9bbd353f 100644 --- a/include/PlayerState.h +++ b/include/PlayerState.h @@ -13,8 +13,11 @@ #ifndef BZF_PLAYERSTATE_H #define BZF_PLAYERSTATE_H +// 1st #include "common.h" +// System headers +#include class PlayerState { @@ -50,8 +53,8 @@ class PlayerState long order; // packet ordering short status; // see PStatus enum - float pos[3]; // position of tank - float velocity[3]; // velocity of tank + glm::vec3 pos; // position of tank + glm::vec3 velocity; // velocity of tank float azimuth; // orientation of tank float angVel; // angular velocity of tank int phydrv; // physics driver diff --git a/include/PolyWallSceneNode.h b/include/PolyWallSceneNode.h index cbc1b19e3b..4b358fa90d 100644 --- a/include/PolyWallSceneNode.h +++ b/include/PolyWallSceneNode.h @@ -24,43 +24,44 @@ class PolyWallSceneNode : public WallSceneNode { public: - PolyWallSceneNode(const GLfloat3Array& vertices, - const GLfloat2Array& uvs); + PolyWallSceneNode(const std::vector &vertices, + const std::vector &uvs); ~PolyWallSceneNode(); - int split(const float*, SceneNode*&, SceneNode*&) const; + int split(const glm::vec4 &, SceneNode*&, SceneNode*&) + const override; - void addRenderNodes(SceneRenderer&); - void addShadowNodes(SceneRenderer&); - void renderRadar(); + void addRenderNodes(SceneRenderer&) override; + void addShadowNodes(SceneRenderer&) override; + void renderRadar() override; - void getRenderNodes(std::vector& rnodes); + void getRenderNodes(std::vector& rnodes) override; protected: class Geometry : public RenderNode { public: Geometry(PolyWallSceneNode*, - const GLfloat3Array& vertices, - const GLfloat2Array& uvs, - const GLfloat* normal); + const std::vector &vertices, + const std::vector &uvs, + const glm::vec4 &plane); ~Geometry(); void setStyle(int _style) { style = _style; } void render() override; - const GLfloat* getPosition() const override; + const glm::vec3 &getPosition() const override; private: void drawV() const; void drawVT() const; private: PolyWallSceneNode* wall; int style; - const GLfloat* normal; + const glm::vec4 &plane; public: - GLfloat3Array vertex; - GLfloat2Array uv; + const std::vector vertex; + const std::vector uv; }; private: diff --git a/include/PyramidBuilding.h b/include/PyramidBuilding.h index 44d79086c9..8b26a3ceac 100644 --- a/include/PyramidBuilding.h +++ b/include/PyramidBuilding.h @@ -17,54 +17,57 @@ #ifndef BZF_PYRAMID_BUILDING_H #define BZF_PYRAMID_BUILDING_H -#include "common.h" -#include +// Inherits from #include "Obstacle.h" +// System headers +#include +#include + class PyramidBuilding : public Obstacle { public: PyramidBuilding(); - PyramidBuilding(const float* pos, float rotation, + PyramidBuilding(const glm::vec3 &pos, float rotation, float width, float breadth, float height, bool drive = false, bool shoot = false, bool ricochet = false); ~PyramidBuilding(); - virtual Obstacle* copyWithTransform(const MeshTransform&) const; + virtual Obstacle* copyWithTransform(const MeshTransform&) const override; - const char* getType() const; + const char* getType() const override; static const char* getClassName(); // const - bool isFlatTop() const; + bool isFlatTop() const override; - float intersect(const Ray&) const; - void getNormal(const float* p, float* n) const; - void get3DNormal(const float* p, float* n) const; + float intersect(const Ray&) const override; + void getNormal(const glm::vec3 &p, glm::vec3 &n) const override; + void get3DNormal(const glm::vec3 &p, glm::vec3 &n) const override; - bool inCylinder(const float* p, float radius, float height) const; - bool inBox(const float* p, float angle, - float halfWidth, float halfBreadth, float height) const; - bool inMovingBox(const float* oldP, float oldAngle, - const float *newP, float newAngle, - float halfWidth, float halfBreadth, float height) const; - bool isCrossing(const float* p, float angle, + bool inCylinder(const glm::vec3 &p, float radius, float height) const override; + bool inBox(const glm::vec3 &p, float angle, + float halfWidth, float halfBreadth, float height) const override; + bool inMovingBox(const glm::vec3 &oldP, float oldAngle, + const glm::vec3 &newP, float newAngle, + float halfWidth, float halfBreadth, float height) const override; + bool isCrossing(const glm::vec3 &p, float angle, float halfWidth, float halfBreadth, float height, - float* plane) const; + glm::vec4 *plane) const override; bool getHitNormal( - const float* pos1, float azimuth1, - const float* pos2, float azimuth2, + const glm::vec3 &pos1, float azimuth1, + const glm::vec3 &pos2, float azimuth2, float halfWidth, float halfBreadth, float height, - float* normal) const; + glm::vec3 &normal) const override; - void getCorner(int index, float* pos) const; + void getCorner(int index, glm::vec3 &pos) const; - int packSize() const; - void *pack(void*) const; - const void *unpack(const void*); + int packSize() const override; + void *pack(void*) const override; + const void *unpack(const void*) override; - void print(std::ostream& out, const std::string& indent) const; - void printOBJ(std::ostream& out, const std::string& indent) const; + void print(std::ostream& out, const std::string& indent) const override; + void printOBJ(std::ostream& out, const std::string& indent) const override; std::string userTextures[1]; diff --git a/include/QuadWallSceneNode.h b/include/QuadWallSceneNode.h index 35cb9ca0f9..376bba91e0 100644 --- a/include/QuadWallSceneNode.h +++ b/include/QuadWallSceneNode.h @@ -23,43 +23,41 @@ class QuadWallSceneNode : public WallSceneNode { public: - QuadWallSceneNode(const GLfloat base[3], - const GLfloat sEdge[3], - const GLfloat tEdge[3], + QuadWallSceneNode(const glm::vec3 &base, + const glm::vec3 &sEdge, + const glm::vec3 &tEdge, float uRepeats = 1.0, float vRepeats = 1.0, bool makeLODs = true, bool fixedUVs = false); - QuadWallSceneNode(const GLfloat base[3], - const GLfloat sEdge[3], - const GLfloat tEdge[3], - float uOffset, - float vOffset, + QuadWallSceneNode(const glm::vec3 &base, + const glm::vec3 &sEdge, + const glm::vec3 &tEdge, + const glm::vec2 &uvOffset, float uRepeats, float vRepeats, bool makeLODs); ~QuadWallSceneNode(); - int split(const float*, SceneNode*&, SceneNode*&) const; + int split(const glm::vec4 &, SceneNode*&, SceneNode*&) const override; - void addRenderNodes(SceneRenderer&); - void addShadowNodes(SceneRenderer&); - void renderRadar(); + void addRenderNodes(SceneRenderer&) override; + void addShadowNodes(SceneRenderer&) override; + void renderRadar() override; - bool inAxisBox (const Extents& exts) const; + bool inAxisBox (const Extents& exts) const override; - int getVertexCount () const; - const GLfloat* getVertex (int vertex) const; + int getVertexCount () const override; + const glm::vec3 &getVertex (int vertex) const override; - virtual void getRenderNodes(std::vector& rnodes); + void getRenderNodes(std::vector& rnodes) override; private: - void init(const GLfloat base[3], - const GLfloat uEdge[3], - const GLfloat vEdge[3], - float uOffset, - float vOffset, + void init(const glm::vec3 &base, + const glm::vec3 &uEdge, + const glm::vec3 &vEdge, + const glm::vec2 &uvOffset, float uRepeats, float vRepeats, bool makeLODs, bool fixedUVs); @@ -70,11 +68,11 @@ class QuadWallSceneNode : public WallSceneNode public: Geometry(QuadWallSceneNode*, int uCount, int vCount, - const GLfloat base[3], - const GLfloat uEdge[3], - const GLfloat vEdge[3], - const GLfloat* normal, - float uOffset, float vOffset, + const glm::vec3 &base, + const glm::vec3 &uEdge, + const glm::vec3 &vEdge, + const glm::vec4 &plane, + const glm::vec2 &uvOffset, float uRepeats, float vRepeats, bool fixedUVs); ~Geometry(); @@ -84,8 +82,8 @@ class QuadWallSceneNode : public WallSceneNode } void render() override; void renderShadow() override; - const GLfloat* getVertex(int i) const; - const GLfloat* getPosition() const override; + const glm::vec3 &getVertex(int i) const; + const glm::vec3 &getPosition() const override; private: void drawV() const; void drawVT() const; @@ -94,10 +92,10 @@ class QuadWallSceneNode : public WallSceneNode int style; int ds, dt; int dsq, dsr; - const GLfloat* normal; + const glm::vec4 &plane; public: - GLfloat3Array vertex; - GLfloat2Array uv; + std::vector vertex; + std::vector uv; int triangles; }; diff --git a/include/Ray.h b/include/Ray.h index 5018bb3da9..c163415902 100644 --- a/include/Ray.h +++ b/include/Ray.h @@ -13,8 +13,12 @@ #ifndef BZF_RAY_H #define BZF_RAY_H +// 1st #include "common.h" + +// System headers #include // for memset() +#include /** Encapsulates a semi-infinite ray. */ @@ -22,18 +26,18 @@ class Ray { public: Ray(); - Ray(const float* o, const float* d); + Ray(const glm::vec3 &o, const glm::vec3 &d); Ray(const Ray&); ~Ray(); Ray& operator=(const Ray&); - const float* getOrigin() const; - const float* getDirection() const; - void getPoint(float t, float p[3]) const; + const glm::vec3 &getOrigin() const; + const glm::vec3 &getDirection() const; + void getPoint(float t, glm::vec3 &p) const; private: - float o[3]; - float d[3]; + glm::vec3 o; + glm::vec3 d; }; // @@ -41,9 +45,8 @@ class Ray // inline Ray::Ray() + : o(0.0f), d(0.0f) { - memset(o,0,sizeof(float)*3); - memset(d,0,sizeof(float)*3); } inline Ray::~Ray() @@ -51,12 +54,12 @@ inline Ray::~Ray() // do nothing } -inline const float* Ray::getOrigin() const +inline const glm::vec3 &Ray::getOrigin() const { return o; } -inline const float* Ray::getDirection() const +inline const glm::vec3 &Ray::getDirection() const { return d; } diff --git a/include/RenderNode.h b/include/RenderNode.h index a8bde7a77d..78ba5a07c1 100644 --- a/include/RenderNode.h +++ b/include/RenderNode.h @@ -25,6 +25,7 @@ // System headers #include +#include // Global headers #include "OpenGLGState.h" @@ -40,7 +41,7 @@ class RenderNode virtual void renderShadow(); virtual void renderRadar(); // Used for sorting objects by distance - virtual const GLfloat* getPosition() const = 0; + virtual const glm::vec3 &getPosition() const = 0; static int getTriangleCount(); static void resetTriangleCount(); @@ -91,7 +92,7 @@ class RenderNodeGStateList void append(RenderNode*, const OpenGLGState*, float depth); void render() const; - void sort(const GLfloat* eye); + void sort(const glm::vec3 &eye); private: struct Item diff --git a/include/SceneNode.h b/include/SceneNode.h index 690c0aec98..b0a4d17783 100644 --- a/include/SceneNode.h +++ b/include/SceneNode.h @@ -27,14 +27,18 @@ #ifndef BZF_SCENE_NODE_H #define BZF_SCENE_NODE_H +// top include #include "common.h" + +// System headers +#include +#include + +// Common headers #include "bzfgl.h" -#include "bzfio.h" #include "OpenGLGState.h" #include "RenderNode.h" #include "Extents.h" -#include "vectors.h" -#include #if !defined(_WIN32) // bonehead win32 cruft. just make it go away on other platforms. @@ -61,23 +65,24 @@ class SceneNode virtual void notifyStyleChange(); - const GLfloat* getSphere() const; + const glm::vec3 &getSphere() const; + const float &getRadius2() const; const Extents& getExtents() const; virtual int getVertexCount () const; - virtual const GLfloat* getVertex (int vertex) const; - virtual const GLfloat* getPlane() const; - virtual GLfloat getDistance(const GLfloat* eye) const; // for BSP + virtual const glm::vec3 &getVertex (int vertex) const; + virtual const glm::vec4 *getPlane() const; + virtual GLfloat getDistance(const glm::vec3 &eye) const; // for BSP virtual bool inAxisBox (const Extents& exts) const; virtual bool cull(const ViewFrustum&) const; - virtual bool cullShadow(int pCount, const float (*planes)[4]) const; + virtual bool cullShadow(int pCount, const glm::vec4 planes[]) const; bool isOccluder() const; void setOccluder(bool value); virtual void addLight(SceneRenderer&); - virtual int split(const float* plane, + virtual int split(const glm::vec4 &plane, SceneNode*& front, SceneNode*& back) const; virtual void addShadowNodes(SceneRenderer&); virtual void addRenderNodes(SceneRenderer&); @@ -102,21 +107,42 @@ class SceneNode if (!colorOverride) ::glColor4f(r, g, b, a); }; - static void glColor3fv(const GLfloat* rgb) + static void glColor3fv(const glm::vec3 &rgb) { - if (!colorOverride) ::glColor3fv(rgb); + if (!colorOverride) ::glColor3f(rgb.r, rgb.g, rgb.b); }; - static void glColor4fv(const GLfloat* rgba) + static void glColor4fv(const glm::vec4 &rgba) { - if (!colorOverride) ::glColor4fv(rgba); + if (!colorOverride) + ::glColor4f(rgba.r, rgba.g, rgba.b, rgba.a); }; + static void glVertex2fv(const glm::vec2 &pos) + { + ::glVertex2f(pos.x, pos.y); + } + + static void glVertex3fv(const glm::vec3 &pos) + { + ::glVertex3f(pos.x, pos.y, pos.z); + } + + static void glTexCoord2fv(const glm::vec2 &coord) + { + ::glTexCoord2f(coord.s, coord.t); + } + static void setStipple(GLfloat alpha) { (*stipple)(alpha); } + static void glNormal3fv(const glm::vec3 &normal) + { + ::glNormal3f(normal.x, normal.y, normal.z); + } + enum CullState { OctreeCulled, @@ -131,9 +157,7 @@ class SceneNode protected: void setRadius(GLfloat radiusSquared); - void setCenter(const GLfloat center[3]); - void setCenter(GLfloat x, GLfloat y, GLfloat z); - void setSphere(const GLfloat sphere[4]); + void setCenter(const glm::vec3 ¢er); private: SceneNode(const SceneNode&); @@ -147,16 +171,22 @@ class SceneNode bool occluder; Extents extents; private: - GLfloat sphere[4]; + glm::vec3 sphere; + float radius2; static bool colorOverride; static void (*stipple)(GLfloat); }; -inline const GLfloat* SceneNode::getSphere() const +inline const glm::vec3 &SceneNode::getSphere() const { return sphere; } +inline const float &SceneNode::getRadius2() const +{ + return radius2; +} + inline const Extents& SceneNode::getExtents() const { return extents; diff --git a/include/SceneRenderer.h b/include/SceneRenderer.h index a8fceb8d31..d28fd6f900 100644 --- a/include/SceneRenderer.h +++ b/include/SceneRenderer.h @@ -24,13 +24,14 @@ #include "Singleton.h" /* system interface headers */ +#include #include +#include /* common interface headers */ #include "OpenGLLight.h" #include "ViewFrustum.h" #include "RenderNode.h" -#include "vectors.h" #define RENDERER (SceneRenderer::instance()) @@ -105,7 +106,7 @@ class SceneRenderer : public Singleton void clearRadar(float opacity); - void getGroundUV(const float p[2], float uv[2]) const; + void getGroundUV(const glm::vec2 &p, glm::vec2 &uv) const; bool getBlank() const; bool getInvert() const; @@ -124,7 +125,7 @@ class SceneRenderer : public Singleton void addFlareLight(const float* pos, const float* color); // temporarily turn off non-applicable lights for big meshes - void disableLights(const float mins[3], const float maxs[3]); + void disableLights(const glm::vec3 &mins, const glm::vec3 &maxs); void reenableLights(); void setupSun(); // setup sun lighting params @@ -132,11 +133,10 @@ class SceneRenderer : public Singleton void setTimeOfDay(double julianDay); - const GLfloat* getSunColor() const; - const GLfloat* getSunScaledColor() const; + const glm::vec3 &getSunColor() const; + const glm::vec3 &getSunScaledColor() const; GLfloat getSunBrightness() const; - const GLfloat* getSunDirection() const; - const GLfloat* getAmbientColor() const; + const glm::vec3 *getSunDirection() const; const GLfloat* getCelestialTransform() const; SceneDatabase* getSceneDatabase() const; @@ -161,11 +161,11 @@ class SceneRenderer : public Singleton fogActive = b; } - const fvec4& getFogColor() const + const glm::vec4 &getFogColor() const { return fogColor; } - void setFogColor( float *color) + void setFogColor(const glm::vec4 &color) { fogColor = color; } @@ -220,11 +220,10 @@ class SceneRenderer : public Singleton OpenGLLight theSun; bool sunOrMoonUp; GLfloat sunDirection[3]; // or moon - GLfloat sunColor[4]; - GLfloat sunScaledColor[4]; + glm::vec3 sunColor; + glm::vec3 sunScaledColor; GLfloat celestialTransform[4][4]; GLfloat sunBrightness; - GLfloat ambientColor[4]; SceneDatabase* scene; BackgroundRenderer* background; int triangleCount; @@ -258,7 +257,7 @@ class SceneRenderer : public Singleton bool needStyleUpdate; bool rebuildTanks; bool fogActive; - fvec4 fogColor; + glm::vec4 fogColor; std::vector flareLightList; RenderNodeList shadowList; @@ -315,12 +314,12 @@ inline const OpenGLLight& SceneRenderer::getLight(int index) const return *(lights[index]); } -inline const GLfloat* SceneRenderer::getSunColor() const +inline const glm::vec3 &SceneRenderer::getSunColor() const { return sunColor; } -inline const GLfloat* SceneRenderer::getSunScaledColor() const +inline const glm::vec3 &SceneRenderer::getSunScaledColor() const { return sunScaledColor; } @@ -330,11 +329,6 @@ inline GLfloat SceneRenderer::getSunBrightness() const return sunBrightness; } -inline const GLfloat* SceneRenderer::getAmbientColor() const -{ - return ambientColor; -} - inline const GLfloat* SceneRenderer::getCelestialTransform() const { return &celestialTransform[0][0]; diff --git a/include/ShotUpdate.h b/include/ShotUpdate.h index 5e6881915d..aa17393aa9 100644 --- a/include/ShotUpdate.h +++ b/include/ShotUpdate.h @@ -28,6 +28,7 @@ // system headers #include +#include // local implementation headers #include "Address.h" @@ -47,8 +48,8 @@ struct ShotUpdate public: PlayerId player; // who's shot uint16_t id; // shot id unique to player - float pos[3]; // shot position - float vel[3]; // shot velocity + glm::vec3 pos; // shot position + glm::vec3 vel; // shot velocity float dt; // time shot has existed TeamColor team; }; diff --git a/include/SphereObstacle.h b/include/SphereObstacle.h index 0e21773e28..ad6bbc154f 100644 --- a/include/SphereObstacle.h +++ b/include/SphereObstacle.h @@ -38,45 +38,32 @@ class SphereObstacle : public Obstacle SphereObstacle(); SphereObstacle(const MeshTransform& transform, - const float* _pos, const float* _size, + const glm::vec3 &_pos, const glm::vec3 &_size, float _rotation, const float _texsize[2], bool _useNormals, bool hemisphere, int _divisions, const BzMaterial* mats[MaterialCount], int physics, bool bounce, bool drive, bool shoot, bool ricochet); ~SphereObstacle(); - Obstacle* copyWithTransform(const MeshTransform&) const; + Obstacle* copyWithTransform(const MeshTransform&) const override; MeshObstacle* makeMesh(); - const char* getType() const; + const char* getType() const override; static const char* getClassName(); // const - bool isValid() const; - - float intersect(const Ray&) const; - void getNormal(const float* p, float* n) const; - void get3DNormal(const float* p, float* n) const; - - bool inCylinder(const float* p, float radius, float height) const; - bool inBox(const float* p, float angle, - float halfWidth, float halfBreadth, float height) const; - bool inMovingBox(const float* oldP, float oldAngle, - const float *newP, float newAngle, - float halfWidth, float halfBreadth, float height) const; - bool isCrossing(const float* p, float angle, - float halfWidth, float halfBreadth, float height, - float* plane) const; - - bool getHitNormal(const float* pos1, float azimuth1, - const float* pos2, float azimuth2, - float halfWidth, float halfBreadth, - float height, float* normal) const; - - int packSize() const; - void *pack(void*) const; - const void *unpack(const void*); - - void print(std::ostream& out, const std::string& indent) const; + bool isValid() const override; + + float intersect(const Ray&) const override; + void getNormal(const glm::vec3 &p, glm::vec3 &n) const override; + void get3DNormal(const glm::vec3 &p, glm::vec3 &n) const override; + + bool inCylinder(const glm::vec3 &p, float radius, float height) const override; + + int packSize() const override; + void *pack(void*) const override; + const void *unpack(const void*) override; + + void print(std::ostream& out, const std::string& indent) const override; private: void finalize(); diff --git a/include/SphereSceneNode.h b/include/SphereSceneNode.h index 2e00770c7b..58cb902d6b 100644 --- a/include/SphereSceneNode.h +++ b/include/SphereSceneNode.h @@ -26,12 +26,12 @@ class SphereSceneNode : public SceneNode { public: - SphereSceneNode(const GLfloat pos[3], GLfloat radius); + SphereSceneNode(const glm::vec3 &pos, GLfloat radius); virtual ~SphereSceneNode(); void setColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a = 1.0f); - void setColor(const GLfloat* rgba); - void move(const GLfloat pos[3], GLfloat radius); + void setColor(const glm::vec4 &rgba); + void move(const glm::vec3 &pos, GLfloat radius); void notifyStyleChange(); virtual void setShockWave(bool) @@ -46,7 +46,7 @@ class SphereSceneNode : public SceneNode protected: GLfloat radius; - GLfloat color[4]; + glm::vec4 color; bool transparent; OpenGLGState gstate; }; @@ -59,7 +59,7 @@ const int sphereLods = 5; class SphereLodSceneNode : public SphereSceneNode { public: - SphereLodSceneNode(const GLfloat pos[3], GLfloat radius); + SphereLodSceneNode(const glm::vec3 &pos, GLfloat radius); ~SphereLodSceneNode(); void setShockWave(bool value); @@ -87,7 +87,7 @@ class SphereLodSceneNode : public SphereSceneNode ~SphereLodRenderNode(); void setLod(int lod); void render() override; - const GLfloat* getPosition() const override; + const glm::vec3 &getPosition() const override; private: const SphereLodSceneNode* sceneNode; @@ -143,9 +143,9 @@ class SphereFragmentSceneNode : public SceneNode FragmentRenderNode(const SphereBspSceneNode*, int theta, int phi); ~FragmentRenderNode(); - const GLfloat* getVertex() const; + const glm::vec3 &getVertex() const; void render() override; - const GLfloat* getPosition() const override; + const glm::vec3 &getPosition() const override; private: const SphereBspSceneNode* sceneNode; int theta, phi; @@ -163,7 +163,7 @@ class SphereBspSceneNode : public SphereSceneNode friend class SphereFragmentSceneNode; friend class SphereFragmentSceneNode::FragmentRenderNode; public: - SphereBspSceneNode(const GLfloat pos[3], GLfloat radius); + SphereBspSceneNode(const glm::vec3 &pos, GLfloat radius); ~SphereBspSceneNode(); void addRenderNodes(SceneRenderer&); @@ -191,13 +191,13 @@ class SphereBspSceneNode : public SphereSceneNode void setHighResolution(bool); void setBaseIndex(int index); void render() override; - const GLfloat* getPosition() const override; + const glm::vec3 &getPosition() const override; private: const SphereBspSceneNode* sceneNode; bool highResolution; int baseIndex; - static GLfloat geom[2 * SphereRes * (SphereRes + 1)][3]; - static GLfloat lgeom[SphereLowRes * (SphereLowRes + 1)][3]; + static glm::vec3 geom[2 * SphereRes * (SphereRes + 1)]; + static glm::vec3 lgeom[SphereLowRes * (SphereLowRes + 1)]; }; friend class SphereBspRenderNode; diff --git a/include/TankGeometryMgr.h b/include/TankGeometryMgr.h index 2eb4089fbd..b6c218c428 100644 --- a/include/TankGeometryMgr.h +++ b/include/TankGeometryMgr.h @@ -95,7 +95,7 @@ int getPartTriangleCount(TankGeometryEnums::TankShadow shadow, TankGeometryEnums::TankSize size, TankGeometryEnums::TankLOD lod); -const float* getScaleFactor(TankGeometryEnums::TankSize size); +const glm::vec3 &getScaleFactor(TankGeometryEnums::TankSize size); } diff --git a/include/TankSceneNode.h b/include/TankSceneNode.h index aca6b7b176..34e4135be5 100644 --- a/include/TankSceneNode.h +++ b/include/TankSceneNode.h @@ -20,6 +20,10 @@ // Inherits from #include "SceneNode.h" +// System headers +#include +#include + // Common headers #include "OpenGLLight.h" #include "TankGeometryMgr.h" @@ -34,26 +38,26 @@ class TankDeathOverride class DeathParams { public: - DeathParams( float param, fvec4 c): part() + DeathParams( float param, const glm::vec4 &c): part() { - scale = fvec3(1,1,1); + scale = glm::vec3(1); explodeParam = param; color = c; draw = true; } TankGeometryEnums::TankPart part; - fvec3 pos; - fvec3 rot; - fvec3 scale; + glm::vec3 pos; + glm::vec3 rot; + glm::vec3 scale; float explodeParam; - fvec4 color; + glm::vec4 color; bool draw; }; virtual bool SetDeathRenderParams ( DeathParams &/*params*/ ) = 0; virtual bool ShowExplosion ( void ) = 0; - virtual bool GetDeathVector ( fvec3 &/*vel*/ ) = 0; + virtual bool GetDeathVector (glm::vec3 &/*vel*/) = 0; }; class TankIDLSceneNode : public SceneNode @@ -62,7 +66,7 @@ class TankIDLSceneNode : public SceneNode TankIDLSceneNode(const TankSceneNode*); ~TankIDLSceneNode(); - void move(const GLfloat plane[4]); + void move(const glm::vec4 &plane); void notifyStyleChange() override; void addRenderNodes(SceneRenderer&) override; @@ -82,17 +86,17 @@ class TankIDLSceneNode : public SceneNode IDLRenderNode(const TankIDLSceneNode*); ~IDLRenderNode(); void render() override; - const GLfloat* getPosition() const override; + const glm::vec3 &getPosition() const override; private: const TankIDLSceneNode* sceneNode; static const int idlFaces[][5]; - static const GLfloat idlVertex[][3]; + static const glm::vec3 idlVertex[]; }; friend class IDLRenderNode; private: const TankSceneNode *tank; - GLfloat plane[4]; + glm::vec4 plane; OpenGLGState gstate; IDLRenderNode renderNode; }; @@ -102,15 +106,15 @@ class TankSceneNode : public SceneNode friend class TankIDLSceneNode; friend class TankIDLSceneNode::IDLRenderNode; public: - TankSceneNode(const GLfloat pos[3], - const GLfloat forward[3]); + TankSceneNode(const glm::vec3 &pos, + const glm::vec3 &forward); ~TankSceneNode(); - void move(const GLfloat pos[3], const GLfloat forward[3]); + void move(const glm::vec3 &pos, const glm::vec3 &forward); void setColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a = 1.0f); - void setColor(const GLfloat* rgba); + void setColor(const glm::vec4 &rgba); void setMaterial(const OpenGLMaterial&); void setTexture(const int); void setJumpJetsTexture(const int); @@ -120,9 +124,9 @@ class TankSceneNode : public SceneNode void setTiny(); void setNarrow(); void setThief(); - void setDimensions(const float size[3]); + void setDimensions(const glm::vec3 &size); - void setClipPlane(const float plane[4]); + void setClipPlane(const glm::vec4 &plane); void resetClipPlane(); void setExplodeFraction(float t); void setJumpJets(float scale); @@ -133,16 +137,16 @@ class TankSceneNode : public SceneNode void rebuildExplosion(); void addTreadOffsets(float left, float right); - void notifyStyleChange(); - void addRenderNodes(SceneRenderer&); - void addShadowNodes(SceneRenderer&); + void notifyStyleChange() override; + void addRenderNodes(SceneRenderer&) override; + void addShadowNodes(SceneRenderer&) override; bool cullShadow(int planeCount, - const float (*planes)[4]) const; + const glm::vec4 *planes) const override; - void addLight(SceneRenderer&); + void addLight(SceneRenderer&) override; - void renderRadar(); + void renderRadar() override; static void setMaxLOD(int maxLevel); @@ -155,7 +159,7 @@ class TankSceneNode : public SceneNode return deathOverride; } - fvec3 explodePos; + glm::vec3 explodePos; protected: TankDeathOverride *deathOverride; @@ -171,7 +175,7 @@ class TankSceneNode : public SceneNode void setTankSize(TankGeometryEnums::TankSize); void sortOrder(bool above, bool towards, bool left); void setNarrowWithDepth(bool narrow); - const GLfloat* getPosition() const override; + const glm::vec3 &getPosition() const override; void render() override; void renderPart(TankGeometryEnums::TankPart part); @@ -189,7 +193,7 @@ class TankSceneNode : public SceneNode const TankSceneNode* sceneNode; TankGeometryEnums::TankLOD drawLOD; TankGeometryEnums::TankSize drawSize; - const GLfloat* color; + const glm::vec4 *color; GLfloat alpha; bool isRadar; bool isTreads; @@ -200,14 +204,14 @@ class TankSceneNode : public SceneNode bool isExploding; bool narrowWithDepth; GLfloat explodeFraction; - static const GLfloat centerOfGravity[TankGeometryEnums::LastTankPart][3]; + static const glm::vec3 centerOfGravity[TankGeometryEnums::LastTankPart]; }; friend class TankRenderNode; private: GLfloat azimuth, elevation; GLfloat baseRadius; - float dimensions[3]; // tank dimensions + glm::vec3 dimensions; // tank dimensions float leftTreadOffset; float rightTreadOffset; float leftWheelOffset; @@ -218,8 +222,8 @@ class TankSceneNode : public SceneNode float explodeFraction; bool clip; bool inTheCockpit; - GLfloat color[4]; - GLdouble clipPlane[4]; + glm::vec4 color; + glm::dvec4 clipPlane; OpenGLGState gstate; OpenGLGState treadState; OpenGLGState lightsGState; @@ -227,19 +231,19 @@ class TankSceneNode : public SceneNode TankRenderNode treadsRenderNode; TankRenderNode shadowRenderNode; TankGeometryEnums::TankSize tankSize; - GLfloat vel[TankGeometryEnums::LastTankPart][3]; - GLfloat spin[TankGeometryEnums::LastTankPart][4]; + glm::vec3 vel[TankGeometryEnums::LastTankPart]; + glm::vec4 spin[TankGeometryEnums::LastTankPart]; bool jumpJetsOn; GLfloat jumpJetsScale; GLfloat jumpJetsLengths[4]; - GLfloat jumpJetsPositions[4][3]; + glm::vec3 jumpJetsPositions[4]; OpenGLLight jumpJetsRealLight; OpenGLLight jumpJetsGroundLights[4]; OpenGLGState jumpJetsGState; static int maxLevel; static const int numLOD; - static GLfloat jumpJetsModel[4][3]; + static glm::vec3 jumpJetsModel[4]; }; diff --git a/include/Team.h b/include/Team.h index 06e6667e31..d0f80245a9 100644 --- a/include/Team.h +++ b/include/Team.h @@ -18,9 +18,15 @@ #ifndef BZF_TEAM_H #define BZF_TEAM_H +// 1st #include "common.h" -#include "global.h" + +// System headers #include +#include + +// Common headers +#include "global.h" const int TeamPLen = 10; @@ -35,15 +41,15 @@ struct Team static const std::string getImagePrefix(TeamColor); // const static const char* getName(TeamColor); // const static TeamColor getTeam(const std::string &name); // const - static const float* getTankColor(TeamColor); // const - static const float* getRadarColor(TeamColor team); // const - static const float* getShotColor(TeamColor team); // const + static const glm::vec3 &getTankColor(TeamColor); // const + static const glm::vec3 &getRadarColor(TeamColor team); // const + static const glm::vec3 &getShotColor(TeamColor team); // const static const std::string getAnsiCode(TeamColor team); // const static bool isColorTeam(TeamColor); // const static void setColors(TeamColor, - const float* tank, - const float* radar); + const glm::vec3 &tank, + const glm::vec3 &radar); static void updateShotColors(); public: @@ -66,9 +72,9 @@ struct Team lost = v; } - static float tankColor[NumTeams][3]; - static float radarColor[NumTeams][3]; - static float shotColor[NumTeams][3]; + static glm::vec3 tankColor[NumTeams]; + static glm::vec3 radarColor[NumTeams]; + static glm::vec3 shotColor[NumTeams]; private: unsigned short won; // wins by team members diff --git a/include/Teleporter.h b/include/Teleporter.h index bc7ffcc0ba..48ecf5297c 100644 --- a/include/Teleporter.h +++ b/include/Teleporter.h @@ -26,62 +26,61 @@ class Teleporter : public Obstacle { public: Teleporter(); - Teleporter(const float* pos, float rotation, + Teleporter(const glm::vec3 &pos, float rotation, float width, float breadth, float height, float borderSize = 1.0f, bool horizontal = false, bool drive = false, bool shoot = false, bool ricochet = false); ~Teleporter(); - Obstacle* copyWithTransform(const MeshTransform&) const; + Obstacle* copyWithTransform(const MeshTransform&) const override; void setName(const std::string& name); const std::string& getName() const; - const char* getType() const; + const char* getType() const override; static const char* getClassName(); // const float getBorder() const; bool isHorizontal() const; - bool isValid() const; - - float intersect(const Ray&) const; - void getNormal(const float* p, float* n) const; - - bool inCylinder(const float* p, float radius, float height) const; - bool inBox(const float* p, float angle, - float halfWidth, float halfBreadth, float height) const; - bool inMovingBox(const float* oldP, float oldAngle, - const float *newP, float newAngle, - float halfWidth, float halfBreadth, float height) const; - bool isCrossing(const float* p, float angle, + bool isValid() const override; + + float intersect(const Ray&) const override; + void getNormal(const glm::vec3 &p, glm::vec3 &n) const override; + + bool inCylinder(const glm::vec3 &p, float radius, float height) const override; + bool inBox(const glm::vec3 &p, float angle, + float halfWidth, float halfBreadth, float height) const override; + bool inMovingBox(const glm::vec3 &oldP, float oldAngle, + const glm::vec3 &newP, float newAngle, + float halfWidth, float halfBreadth, float height) const override; + bool isCrossing(const glm::vec3 &p, float angle, float halfWidth, float halfBreadth, float height, - float* plane) const; + glm::vec4 *plane) const override; bool getHitNormal( - const float* pos1, float azimuth1, - const float* pos2, float azimuth2, + const glm::vec3 &pos1, float azimuth1, + const glm::vec3 &pos2, float azimuth2, float halfWidth, float halfBreadth, float height, - float* normal) const; + glm::vec3 &normal) const override; float isTeleported(const Ray&, int& face) const; - float getProximity(const float* p, float radius) const; - bool hasCrossed(const float* p1, const float* p2, + float getProximity(const glm::vec3 &p, float radius) const; + bool hasCrossed(const glm::vec3 &p1, const glm::vec3 &p2, int& face) const; void getPointWRT(const Teleporter& t2, int face1, int face2, - const float* pIn, const float* dIn, float aIn, - float* pOut, float* dOut, float* aOut) const; + glm::vec3 &p, glm::vec3 *d, float *a) const; void makeLinks(); const MeshFace* getBackLink() const; const MeshFace* getFrontLink() const; - int packSize() const; - void* pack(void*) const; - const void* unpack(const void*); + int packSize() const override; + void* pack(void*) const override; + const void* unpack(const void*) override; - void print(std::ostream& out, const std::string& indent) const; - void printOBJ(std::ostream& out, const std::string& indent) const; + void print(std::ostream& out, const std::string& indent) const override; + void printOBJ(std::ostream& out, const std::string& indent) const override; std::string userTextures[1]; @@ -95,13 +94,13 @@ class Teleporter : public Obstacle float border; bool horizontal; - float origSize[3]; + glm::vec3 origSize; MeshFace* backLink; MeshFace* frontLink; - float fvertices[4][3]; // front vertices - float bvertices[4][3]; // back vertices - float texcoords[4][2]; // shared texture coordinates + glm::vec3 fvertices[4]; // front vertices + glm::vec3 bvertices[4]; // back vertices + glm::vec2 texcoords[4]; // shared texture coordinates }; // diff --git a/include/TetraBuilding.h b/include/TetraBuilding.h index 4c122218b4..cd849079f5 100644 --- a/include/TetraBuilding.h +++ b/include/TetraBuilding.h @@ -17,9 +17,13 @@ #ifndef BZF_TETRA_BUILDING_H #define BZF_TETRA_BUILDING_H -#include "common.h" -#include +// Inherits from #include "Obstacle.h" + +// System headers +#include + +// Common headers #include "MeshObstacle.h" #include "MeshTransform.h" #include "BzMaterial.h" @@ -30,50 +34,35 @@ class TetraBuilding : public Obstacle TetraBuilding(); TetraBuilding(const MeshTransform& transform, - const float vertices[4][3], const float normals[4][3][3], + const glm::vec3 vertices[4], const float normals[4][3][3], const float texCoords[4][3][2], const bool useNormals[4], const bool useTexCoords[4], const BzMaterial* materials[4], bool drive = false, bool shoot = false, bool ricochet = false); ~TetraBuilding(); - Obstacle* copyWithTransform(const MeshTransform&) const; + Obstacle* copyWithTransform(const MeshTransform&) const override; MeshObstacle* makeMesh(); void finalize(); - const char* getType() const; + const char* getType() const override; static const char* getClassName(); // const - bool isValid() const; - - float intersect(const Ray&) const; - void getNormal(const float* p, float* n) const; - void get3DNormal(const float* p, float* n) const; - - bool inCylinder(const float* p, float radius, float height) const; - bool inBox(const float* p, float angle, - float halfWidth, float halfBreadth, float height) const; - bool inMovingBox(const float* oldP, float oldAngle, - const float *newP, float newAngle, - float halfWidth, float halfBreadth, float height) const; - bool isCrossing(const float* p, float angle, - float halfWidth, float halfBreadth, float height, - float* plane) const; - - bool getHitNormal( - const float* pos1, float azimuth1, - const float* pos2, float azimuth2, - float halfWidth, float halfBreadth, - float height, - float* normal) const; + bool isValid() const override; + + float intersect(const Ray&) const override; + void getNormal(const glm::vec3 &p, glm::vec3 &n) const override; + void get3DNormal(const glm::vec3 &p, glm::vec3 &n) const override; + + bool inCylinder(const glm::vec3 &p, float radius, float height) const override; void getCorner(int index, float* pos) const; - int packSize() const; - void *pack(void*) const; - const void *unpack(const void*); + int packSize() const override; + void *pack(void*) const override; + const void *unpack(const void*) override; - void print(std::ostream& out, const std::string& indent) const; + void print(std::ostream& out, const std::string& indent) const override; private: void checkVertexOrder(); @@ -82,7 +71,7 @@ class TetraBuilding : public Obstacle static const char* typeName; MeshTransform transform; - float vertices[4][3]; + glm::vec3 vertices[4]; float normals[4][3][3]; float texcoords[4][3][2]; bool useNormals[4]; diff --git a/include/TriWallSceneNode.h b/include/TriWallSceneNode.h index 6266324348..af19b9a1ee 100644 --- a/include/TriWallSceneNode.h +++ b/include/TriWallSceneNode.h @@ -23,28 +23,28 @@ class TriWallSceneNode : public WallSceneNode { public: - TriWallSceneNode(const GLfloat base[3], - const GLfloat sEdge[3], - const GLfloat tEdge[3], + TriWallSceneNode(const glm::vec3 &base, + const glm::vec3 &sEdge, + const glm::vec3 &tEdge, float uRepeats = 1.0, float vRepeats = 1.0, bool makeLODs = true); ~TriWallSceneNode(); - int split(const float*, SceneNode*&, SceneNode*&) const; + int split(const glm::vec4 &, SceneNode*&, SceneNode*&) const override; - void addRenderNodes(SceneRenderer&); - void addShadowNodes(SceneRenderer&); - void renderRadar(); + void addRenderNodes(SceneRenderer&) override; + void addShadowNodes(SceneRenderer&) override; + void renderRadar() override; - bool inAxisBox (const Extents& exts) const; + bool inAxisBox (const Extents& exts) const override; - int getVertexCount () const; - const GLfloat* getVertex (int vertex) const; + int getVertexCount () const override; + const glm::vec3 &getVertex (int vertex) const override; - bool cull(const ViewFrustum&) const; + bool cull(const ViewFrustum&) const override; - void getRenderNodes(std::vector& rnodes); + void getRenderNodes(std::vector& rnodes) override; protected: class Geometry : public RenderNode @@ -52,10 +52,10 @@ class TriWallSceneNode : public WallSceneNode public: Geometry(TriWallSceneNode*, int eCount, - const GLfloat base[3], - const GLfloat uEdge[3], - const GLfloat vEdge[3], - const GLfloat* normal, + const glm::vec3 &base, + const glm::vec3 &uEdge, + const glm::vec3 &vEdge, + const glm::vec4 &plane, float uRepeats, float vRepeats); ~Geometry(); void setStyle(int _style) @@ -64,8 +64,8 @@ class TriWallSceneNode : public WallSceneNode } void render() override; void renderShadow() override; - const GLfloat* getVertex(int i) const; - const GLfloat* getPosition() const override; + const glm::vec3 &getVertex(int i) const; + const glm::vec3 &getPosition() const override; private: void drawV() const; void drawVT() const; @@ -73,10 +73,10 @@ class TriWallSceneNode : public WallSceneNode WallSceneNode* wall; int style; int de; - const GLfloat* normal; + const glm::vec4 &plane; public: - GLfloat3Array vertex; - GLfloat2Array uv; + std::vector vertex; + std::vector uv; int triangles; }; diff --git a/include/WallObstacle.h b/include/WallObstacle.h index 231dbd8c08..450c1f46d7 100644 --- a/include/WallObstacle.h +++ b/include/WallObstacle.h @@ -17,43 +17,46 @@ #ifndef BZF_WALL_OBSTACLE_H #define BZF_WALL_OBSTACLE_H -#include "common.h" -#include +// Inherits from #include "Obstacle.h" +// System interfaces +#include +#include + class WallObstacle : public Obstacle { public: WallObstacle(); - WallObstacle(const float* pos, float rotation, + WallObstacle(const glm::vec3 &pos, float rotation, float breadth, float height, bool ricochet); ~WallObstacle(); - const char* getType() const; + const char* getType() const override; static const char* getClassName(); // const - float intersect(const Ray&) const; - void getNormal(const float* p, float* n) const; + float intersect(const Ray&) const override; + void getNormal(const glm::vec3 &p, glm::vec3 &n) const override; - bool inCylinder(const float* p, float radius, float height) const; - bool inBox(const float* p, float angle, - float halfWidth, float halfBreadth, float height) const; - bool inMovingBox(const float* oldP, float oldAngle, - const float *newP, float newAngle, - float halfWidth, float halfBreadth, float height) const; + bool inCylinder(const glm::vec3 &p, float radius, float height) const override; + bool inBox(const glm::vec3 &p, float angle, + float halfWidth, float halfBreadth, float height) const override; + bool inMovingBox(const glm::vec3 &oldP, float oldAngle, + const glm::vec3 &newP, float newAngle, + float halfWidth, float halfBreadth, float height) const override; bool getHitNormal( - const float* pos1, float azimuth1, - const float* pos2, float azimuth2, + const glm::vec3 &pos1, float azimuth1, + const glm::vec3 &pos2, float azimuth2, float halfWidth, float halfBreadth, float height, - float* normal) const; + glm::vec3 &normal) const override; - int packSize() const; - void *pack(void*) const; - const void *unpack(const void*); + int packSize() const override; + void *pack(void*) const override; + const void *unpack(const void*) override; - void print(std::ostream& out, const std::string& indent) const; + void print(std::ostream& out, const std::string& indent) const override; std::string userTextures[1]; @@ -61,7 +64,7 @@ class WallObstacle : public Obstacle void finalize(); private: - float plane[4]; + glm::vec4 plane; static const char* typeName; }; diff --git a/include/WallSceneNode.h b/include/WallSceneNode.h index e36234df43..4754f39975 100644 --- a/include/WallSceneNode.h +++ b/include/WallSceneNode.h @@ -24,7 +24,7 @@ #ifndef BZF_WALL_SCENE_NODE_H #define BZF_WALL_SCENE_NODE_H -#include "common.h" +// Inherits from #include "SceneNode.h" class WallSceneNode : public SceneNode @@ -33,31 +33,31 @@ class WallSceneNode : public SceneNode WallSceneNode(); ~WallSceneNode(); - const GLfloat* getPlane() const override; - const GLfloat* getColor() const; - const GLfloat* getDynamicColor() const; - const GLfloat* getModulateColor() const; - const GLfloat* getLightedColor() const; - const GLfloat* getLightedModulateColor() const; - GLfloat getDistance(const GLfloat*) const override; + const glm::vec4 *getPlane() const override; + const glm::vec4 &getColor() const; + const glm::vec4 *getDynamicColor() const; + const glm::vec4 &getModulateColor() const; + const glm::vec4 &getLightedColor() const; + const glm::vec4 &getLightedModulateColor() const; + GLfloat getDistance(const glm::vec3 &) const override; bool inAxisBox (const Extents& exts) const override; void setColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a = 1.0f); - void setColor(const GLfloat* rgba); + void setColor(const glm::vec4 &rgba); void setModulateColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a = 1.0f); - void setModulateColor(const GLfloat* rgba); + void setModulateColor(const glm::vec4 &rgba); void setLightedColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a = 1.0f); - void setLightedColor(const GLfloat* rgba); + void setLightedColor(const glm::vec4 &rgba); void setLightedModulateColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a = 1.0f); - void setLightedModulateColor(const GLfloat* rgba); + void setLightedModulateColor(const glm::vec4 &rgba); void setMaterial(const OpenGLMaterial&); void setTexture(const int); void setTextureMatrix(const GLfloat* texmat); - void setDynamicColor(const float* color); + void setDynamicColor(const glm::vec4 *color); void setBlending(bool); void setSphereMap(bool); void setNoCulling(bool); @@ -78,7 +78,7 @@ class WallSceneNode : public SceneNode protected: int getNumLODs() const; void setNumLODs(int, float* elementAreas); - void setPlane(const GLfloat[4]); + void setPlane(const glm::vec4 &); int pickLevelOfDetail(const SceneRenderer&) const; int getStyle() const; @@ -88,26 +88,26 @@ class WallSceneNode : public SceneNode } const OpenGLGState* getWallGState() const; - static int splitWall(const GLfloat* plane, - const GLfloat3Array& vertices, - const GLfloat2Array& uvs, + static int splitWall(const glm::vec4 &plane, + const std::vector &vertices, + const std::vector &uvs, SceneNode*& front, SceneNode*& back); // const - GLfloat plane[4]; // unit normal, distance to origin + glm::vec4 plane; // unit normal, distance to origin private: static void splitEdge(float d1, float d2, - const GLfloat* p1, const GLfloat* p2, - const GLfloat* uv1, const GLfloat* uv2, - GLfloat* p, GLfloat* uv); //const + const glm::vec3 &p1, const glm::vec3 &p2, + const glm::vec2 &uv1, const glm::vec2 &uv2, + glm::vec3 &p, glm::vec2 &uv); //const private: int numLODs; float* elementAreas; - const GLfloat* dynamicColor; - GLfloat color[4]; - GLfloat modulateColor[4]; - GLfloat lightedColor[4]; - GLfloat lightedModulateColor[4]; + const glm::vec4 *dynamicColor; + glm::vec4 color; + glm::vec4 modulateColor; + glm::vec4 lightedColor; + glm::vec4 lightedModulateColor; float alphaThreshold; int style; bool noCulling; @@ -128,23 +128,23 @@ inline int WallSceneNode::getNumLODs() const return numLODs; } -inline const GLfloat* WallSceneNode::getColor() const +inline const glm::vec4 &WallSceneNode::getColor() const { return color; } -inline const GLfloat* WallSceneNode::getDynamicColor() const +inline const glm::vec4 *WallSceneNode::getDynamicColor() const { return dynamicColor; } -inline const GLfloat* WallSceneNode::getModulateColor() const +inline const glm::vec4 &WallSceneNode::getModulateColor() const { return modulateColor; } -inline const GLfloat* WallSceneNode::getLightedColor() const +inline const glm::vec4 &WallSceneNode::getLightedColor() const { return lightedColor; } -inline const GLfloat* WallSceneNode::getLightedModulateColor() const +inline const glm::vec4 &WallSceneNode::getLightedModulateColor() const { return lightedModulateColor; } diff --git a/include/vectors.h b/include/vectors.h deleted file mode 100644 index ce282015da..0000000000 --- a/include/vectors.h +++ /dev/null @@ -1,1100 +0,0 @@ -/* bzflag - * Copyright (c) 1993-2023 Tim Riker - * - * This package is free software; you can redistribute it and/or - * modify it under the terms of the license found in the file - * named COPYING that should have accompanied this file. - * - * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. - */ - -#ifndef VECTORS_H -#define VECTORS_H - -// 1st -#include "common.h" - -// System headers -#include -#include -#include -#include -#include - - -#include "vectors_old.h" // FIXME -- the crappy old-style vectors - -//============================================================================// - -template T typed_cos(T rads); -template<> inline float typed_cos (float rads) -{ - return cosf(rads); -} -template<> inline double typed_cos(double rads) -{ - return cos(rads); -} - -template T typed_sin(T rads); -template<> inline float typed_sin (float rads) -{ - return sinf(rads); -} -template<> inline double typed_sin(double rads) -{ - return sin(rads); -} - -template T typed_sqrt(T rads); -template<> inline float typed_sqrt (float rads) -{ - return sqrtf(rads); -} -template<> inline double typed_sqrt(double rads) -{ - return sqrt(rads); -} - -template inline std::string tostring(T value, const char* fmt) -{ - char buf[256]; - if (fmt == NULL) - fmt = "%.9g"; - snprintf(buf, sizeof(buf), fmt, (double)value); - return std::string(buf); -} - - -//============================================================================// - -template class vec2; -template class vec3; -template class vec4; - - -//============================================================================// -// -// vec2 -// - -template -class vec2 -{ - - friend class vec3; - friend class vec4; - -public: - union - { - T x; - T r; - T s; - }; - union - { - T y; - T g; - T t; - }; - -private: - vec2(bool) {} // does not touch the data - -public: - vec2() : x((T)0), y((T)0) {} - vec2(const vec2& v) : x(v.x), y(v.y) {} - vec2(T _x, T _y): x(_x), y(_y) {} - - inline vec2& operator=(const vec2& v) - { - x = v.x; - y = v.y; - return *this; - } - - inline T* data() - { - return &x; - } - inline const T* data() const - { - return &x; - } - - inline operator T*() - { - return &x; - } - inline operator const T*() const - { - return &x; - } - - inline T& operator[](int index) - { - return ((T*)&x)[index]; - } - inline const T& operator[](int index) const - { - return ((T*)&x)[index]; - } - - inline vec2 operator-() const - { - return vec2(-x, -y); - } - - vec2& operator+=(const vec2& v) - { - x += v.x; - y += v.y; - return *this; - } - vec2& operator-=(const vec2& v) - { - x -= v.x; - y -= v.y; - return *this; - } - vec2& operator*=(const vec2& v) - { - x *= v.x; - y *= v.y; - return *this; - } - vec2& operator/=(const vec2& v) - { - x /= v.x; - y /= v.y; - return *this; - } - - vec2& operator+=(T d) - { - x += d; - y += d; - return *this; - } - vec2& operator-=(T d) - { - x -= d; - y -= d; - return *this; - } - vec2& operator*=(T d) - { - x *= d; - y *= d; - return *this; - } - vec2& operator/=(T d) - { - x /= d; - y /= d; - return *this; - } - - vec2 operator+(const vec2& v) const - { - return vec2(x + v.x, y + v.y); - } - vec2 operator-(const vec2& v) const - { - return vec2(x - v.x, y - v.y); - } - vec2 operator*(const vec2& v) const - { - return vec2(x * v.x, y * v.y); - } - vec2 operator/(const vec2& v) const - { - return vec2(x / v.x, y / v.y); - } - - vec2 operator+(T d) const - { - return vec2(x + d, y + d); - } - vec2 operator-(T d) const - { - return vec2(x - d, y - d); - } - vec2 operator*(T d) const - { - return vec2(x * d, y * d); - } - vec2 operator/(T d) const - { - return vec2(x / d, y / d); - } - - bool operator<(const vec2& v) const - { - if (x < v.x) - return true; - if (x > v.x) - return false; - if (y < v.y) - return true; - if (y > v.y) - return false; - return false; - } - bool operator==(const vec2& v) const - { - return ((x == v.x) && (y == v.y)); - } - bool operator!=(const vec2& v) const - { - return ((x != v.x) || (y != v.y)); - } - - static T dot(const vec2& a, const vec2& b) - { - return ((a.x * b.x) + (a.y * b.y)); - } - T dot(const vec2& v) const - { - return dot(*this, v); - } - - T lengthSq() const - { - return dot(*this, *this); - } - T length() const - { - return typed_sqrt(lengthSq()); - } - - static bool normalize(vec2& v) - { - const T len = v.length(); - if (len == (T)0) - return false; - const T scale = ((T)1 / len); - v *= scale; - return true; - } - vec2 normalize() const - { - vec2 v(*this); - normalize(v); - return v; - } - - vec2 rotate(T radians) const - { - const T cv = typed_cos(radians); - const T sv = typed_sin(radians); - const T nx = (cv * x) - (sv * y); - const T ny = (cv * y) + (sv * x); - return vec2(nx, ny); - } - static void rotate(vec2& v, T radians) - { - v = v.rotate(radians); - } - - std::string tostring(const char* fmt = NULL, const char* sep = NULL) const - { - if (sep == NULL) - sep = " "; - return ::tostring(x, fmt) + sep + - ::tostring(y, fmt); - } -}; - - -template vec2 operator+(T d, const vec2& in) -{ - vec2 v(in); - v += d; - return v; -} -template vec2 operator-(T d, const vec2& in) -{ - vec2 v(d, d); - v -= in; - return v; -} -template vec2 operator*(T d, const vec2& in) -{ - vec2 v(in); - v *= d; - return v; -} -template vec2 operator/(T d, const vec2& in) -{ - vec2 v(d, d); - v /= in; - return v; -} -template std::ostream& operator<<(std::ostream& out, const vec2& v) -{ - out << " " << v.tostring(); - return out; -} - - -//============================================================================// -// -// vec3 -// - -template -class vec3 -{ - - friend class vec4; - -public: - union - { - T x; - T r; - T s; - }; - union - { - T y; - T g; - T t; - }; - union - { - T z; - T b; - T p; - }; - -private: - vec3(bool) {} // does not touch the data - -public: - vec3() : x((T)0), y((T)0), z((T)0) {} - vec3(const vec3& v) : x(v.x), y(v.y), z(v.z) {} - vec3(T _x, T _y, T _z) : x(_x), y(_y), z(_z) {} - vec3(const vec2& v, T _z) : x(v.x), y(v.y), z(_z) {} - - inline vec3& operator=(const vec3& v) - { - x = v.x; - y = v.y; - z = v.z; - return *this; - } - - inline T* data() - { - return &x; - } - inline const T* data() const - { - return &x; - } - - inline operator T*() - { - return &x; - } - inline operator const T*() const - { - return &x; - } - - inline T& operator[](int index) - { - return ((T*)&x)[index]; - } - inline const T& operator[](int index) const - { - return ((T*)&x)[index]; - } - - inline vec3 operator-() const - { - return vec3(-x, -y, -z); - } - - inline vec2& xy() - { - return *(new((void*)&x) vec2(false)); - } - inline const vec2& xy() const - { - return *(new((void*)&x) vec2(false)); - } - inline vec2& yz() - { - return *(new((void*)&y) vec2(false)); - } - inline const vec2& yz() const - { - return *(new((void*)&y) vec2(false)); - } - - vec3& operator+=(const vec3& v) - { - x += v.x; - y += v.y; - z += v.z; - return *this; - } - vec3& operator-=(const vec3& v) - { - x -= v.x; - y -= v.y; - z -= v.z; - return *this; - } - vec3& operator*=(const vec3& v) - { - x *= v.x; - y *= v.y; - z *= v.z; - return *this; - } - vec3& operator/=(const vec3& v) - { - x /= v.x; - y /= v.y; - z /= v.z; - return *this; - } - vec3& operator+=(T d) - { - x += d; - y += d; - z += d; - return *this; - } - vec3& operator-=(T d) - { - x -= d; - y -= d; - z -= d; - return *this; - } - vec3& operator*=(T d) - { - x *= d; - y *= d; - z *= d; - return *this; - } - vec3& operator/=(T d) - { - x /= d; - y /= d; - z /= d; - return *this; - } - - vec3 operator+(const vec3& v) const - { - return vec3(x + v.x, y + v.y, z + v.z); - } - vec3 operator-(const vec3& v) const - { - return vec3(x - v.x, y - v.y, z - v.z); - } - vec3 operator*(const vec3& v) const - { - return vec3(x * v.x, y * v.y, z * v.z); - } - vec3 operator/(const vec3& v) const - { - return vec3(x / v.x, y / v.y, z / v.z); - } - - vec3 operator+(T d) const - { - return vec3(x + d, y + d, z + d); - } - vec3 operator-(T d) const - { - return vec3(x - d, y - d, z - d); - } - vec3 operator*(T d) const - { - return vec3(x * d, y * d, z * d); - } - vec3 operator/(T d) const - { - return vec3(x / d, y / d, z / d); - } - - bool operator<(const vec3& v) const - { - if (x < v.x) - return true; - if (x > v.x) - return false; - if (y < v.y) - return true; - if (y > v.y) - return false; - if (z < v.z) - return true; - if (z > v.z) - return false; - return false; - } - bool operator==(const vec3& v) const - { - return ((x == v.x) && (y == v.y) && (z == v.z)); - } - bool operator!=(const vec3& v) const - { - return ((x != v.x) || (y != v.y) || (z != v.z)); - } - - static T dot(const vec3& a, const vec3& b) - { - return ((a.x * b.x) + (a.y * b.y) + (a.z * b.z)); - } - T dot(const vec3& v) const - { - return dot(*this, v); - } - - static vec3 cross(const vec3& a, const vec3& b) - { - return vec3( - ((a.y * b.z) - (a.z * b.y)), - ((a.z * b.x) - (a.x * b.z)), - ((a.x * b.y) - (a.y * b.x)) - ); - } - vec3 cross(const vec3& v) const - { - return cross(*this, v); - } - - T lengthSq() const - { - return dot(*this, *this); - } - T length() const - { - return typed_sqrt(lengthSq()); - } - - static bool normalize(vec3& v) - { - const T len = v.length(); - if (len == (T)0) - return false; - const T scale = ((T)1 / len); - v *= scale; - return true; - } - vec3 normalize() const - { - vec3 v(*this); - normalize(v); - return v; - } - - static T toRadians(T value) - { - return value * (T)(M_PI/180.0); - } - - vec3 rotateX(T radians) const - { - const T cv = typed_cos(radians); - const T sv = typed_sin(radians); - const T ny = (cv * y) - (sv * z); - const T nz = (cv * z) + (sv * y); - return vec3(x, ny, nz); - } - static void rotateX(vec3& v, T radians) - { - v = v.rotateX(radians); - } - - vec3 rotateY(T radians) const - { - const T cv = typed_cos(radians); - const T sv = typed_sin(radians); - const T nz = (cv * z) - (sv * x); - const T nx = (cv * x) + (sv * z); - return vec3(nx, y, nz); - } - static void rotateY(vec3& v, T radians) - { - v = v.rotateY(radians); - } - - vec3 rotateZ(T radians) const - { - const T cv = typed_cos(radians); - const T sv = typed_sin(radians); - const T nx = (cv * x) - (sv * y); - const T ny = (cv * y) + (sv * x); - return vec3(nx, ny, z); - } - static void rotateZ(vec3& v, T radians) - { - v = v.rotateZ(radians); - } - - vec3 rotate(T radians, const vec3& n) const - { - const T cv = typed_cos(radians); - const T sv = typed_sin(radians); - const T ic = (T)1 - cv; - const T fxx = ic * (n.x * n.x); - const T fyy = ic * (n.y * n.y); - const T fzz = ic * (n.z * n.z); - const T fxy = ic * (n.x * n.y); - const T fxz = ic * (n.x * n.z); - const T fyz = ic * (n.y * n.z); - const T xs = n.x * sv; - const T ys = n.y * sv; - const T zs = n.z * sv; - return vec3(dot(vec3(fxx + cv, fxy - zs, fxz + ys)), - dot(vec3(fxy + zs, fyy + cv, fyz - xs)), - dot(vec3(fxz - ys, fyz + xs, fzz + cv))); - } - static void rotate(vec3& v, T radians, const vec3& n) - { - v = v.rotate(radians, n); - } - - std::string tostring(const char* fmt = NULL, const char* sep = NULL) const - { - if (sep == NULL) - sep = " "; - return ::tostring(x, fmt) + sep + - ::tostring(y, fmt) + sep + - ::tostring(z, fmt); - } -}; - - -template vec3 operator+(T d, const vec3& in) -{ - vec3 v(in); - v += d; - return v; -} -template vec3 operator-(T d, const vec3& in) -{ - vec3 v(d, d, d); - v -= in; - return v; -} -template vec3 operator*(T d, const vec3& in) -{ - vec3 v(in); - v *= d; - return v; -} -template vec3 operator/(T d, const vec3& in) -{ - vec3 v(d, d, d); - v /= in; - return v; -} -template std::ostream& operator<<(std::ostream& out, const vec3& v) -{ - out << " " << v.tostring(); - return out; -} - - -//============================================================================// -// -// vec4 -// - -template -class vec4 -{ -public: - union - { - T x; - T r; - T s; - }; - union - { - T y; - T g; - T t; - }; - union - { - T z; - T b; - T p; - }; - union - { - T w; - T a; - T q; - }; - -public: - vec4() : x((T)0), y((T)0), z((T)0), w((T)1) {} - vec4(const vec4& v) : x(v.x), y(v.y), z(v.z), w(v.w) {} - vec4(T _x, T _y, T _z, T _w) : x(_x), y(_y), z(_z), w(_w) {} - vec4(const vec3& v, T _w) : x(v.x), y(v.y), z(v.z), w(_w) {} - - vec4(T v[4]) : x(v[0]), y(v[1]), z(v[2]), w(v[3]) {} - - inline vec4& operator=(const vec4& v) - { - x = v.x; - y = v.y; - z = v.z; - w = v.w; - return *this; - } - inline vec4& operator=(const T v[4]) - { - x = v[0]; - y = v[1]; - z = v[2]; - w = v[3]; - return *this; - } - - inline T* data() - { - return &x; - } - inline const T* data() const - { - return &x; - } - - inline operator T*() - { - return &x; - } - inline operator const T*() const - { - return &x; - } - - inline T& operator[](int index) - { - return ((T*)&x)[index]; - } - inline const T& operator[](int index) const - { - return ((T*)&x)[index]; - } - - inline vec4 operator-() const - { - return vec4(-x, -y, -z, -w); - } - - inline vec2& xy() - { - return *(new((void*)&x) vec2(false)); - } - inline const vec2& xy() const - { - return *(new((void*)&x) vec2(false)); - } - inline vec2& yz() - { - return *(new((void*)&y) vec2(false)); - } - inline const vec2& yz() const - { - return *(new((void*)&y) vec2(false)); - } - inline vec2& zw() - { - return *(new((void*)&z) vec2(false)); - } - inline const vec2& zw() const - { - return *(new((void*)&z) vec2(false)); - } - inline vec3& xyz() - { - return *(new((void*)&x) vec3(false)); - } - inline const vec3& xyz() const - { - return *(new((void*)&x) vec3(false)); - } - inline vec3& yzw() - { - return *(new((void*)&y) vec3(false)); - } - inline const vec3& yzw() const - { - return *(new((void*)&y) vec3(false)); - } - - vec4& operator+=(const vec4& v) - { - x += v.x; - y += v.y; - z += v.z; - w += v.w; - return *this; - } - vec4& operator-=(const vec4& v) - { - x -= v.x; - y -= v.y; - z -= v.z; - w -= v.w; - return *this; - } - vec4& operator*=(const vec4& v) - { - x *= v.x; - y *= v.y; - z *= v.z; - w *= v.w; - return *this; - } - vec4& operator/=(const vec4& v) - { - x /= v.x; - y /= v.y; - z /= v.z; - w /= v.w; - return *this; - } - - vec4& operator+=(T d) - { - x += d; - y += d; - z += d; - w += d; - return *this; - } - vec4& operator-=(T d) - { - x -= d; - y -= d; - z -= d; - w -= d; - return *this; - } - vec4& operator*=(T d) - { - x *= d; - y *= d; - z *= d; - w *= d; - return *this; - } - vec4& operator/=(T d) - { - x /= d; - y /= d; - z /= d; - w /= d; - return *this; - } - - vec4 operator+(const vec4& v) const - { - return vec4(x + v.x, y + v.y, z + v.z, w + v.w); - } - vec4 operator-(const vec4& v) const - { - return vec4(x - v.x, y - v.y, z - v.z, w - v.w); - } - vec4 operator*(const vec4& v) const - { - return vec4(x * v.x, y * v.y, z * v.z, w * v.w); - } - vec4 operator/(const vec4& v) const - { - return vec4(x / v.x, y / v.y, z / v.z, w / v.w); - } - - vec4 operator+(T d) const - { - return vec4(x + d, y + d, z + d, w + d); - } - vec4 operator-(T d) const - { - return vec4(x - d, y - d, z - d, w - d); - } - vec4 operator*(T d) const - { - return vec4(x * d, y * d, z * d, w * d); - } - vec4 operator/(T d) const - { - return vec4(x / d, y / d, z / d, w / d); - } - - bool operator<(const vec4& v) const - { - if (x < v.x) - return true; - if (x > v.x) - return false; - if (y < v.y) - return true; - if (y > v.y) - return false; - if (z < v.z) - return true; - if (z > v.z) - return false; - if (w < v.w) - return true; - if (w > v.w) - return false; - return false; - } - bool operator==(const vec4& v) const - { - return ((x == v.x) && (y == v.y) && (z == v.z) && (w == v.w)); - } - bool operator!=(const vec4& v) const - { - return ((x != v.x) || (y != v.y) || (z != v.z) || (w != v.w)); - } - - static T dot(const vec4& a, const vec4& b) - { - return ((a.x * b.x) + (a.y * b.y) + (a.z * b.z) + (a.w * b.w)); - } - T dot(const vec4& v) const - { - return dot(*this, v); - } - - T lengthSq() const - { - return dot(*this, *this); - } - T length() const - { - return typed_sqrt(lengthSq()); - } - - // for the plane equation, - // (x * p.x) + (y * p.y) + (z * p.z) + w = 0 {for a point on the plane} - T planeDist(const vec3& point) const - { - return vec3::dot(point, xyz()) + w; - } - - std::string tostring(const char* fmt = NULL, const char* sep = NULL) const - { - if (sep == NULL) - sep = " "; - return ::tostring(x, fmt) + sep + - ::tostring(y, fmt) + sep + - ::tostring(z, fmt) + sep + - ::tostring(w, fmt); - } -}; - - -template vec4 operator+(T d, const vec4& in) -{ - vec4 v(in); - v += d; - return v; -} -template vec4 operator-(T d, const vec4& in) -{ - vec4 v(d, d, d, d); - v -= in; - return v; -} -template vec4 operator*(T d, const vec4& in) -{ - vec4 v(in); - v *= d; - return v; -} -template vec4 operator/(T d, const vec4& in) -{ - vec4 v(d, d, d, d); - v /= in; - return v; -} -template std::ostream& operator<<(std::ostream& out, const vec4& v) -{ - out << " " << v.tostring(); - return out; -} - - -//============================================================================// -// -// Easier to type -// - -typedef vec2 fvec2; -typedef vec3 fvec3; -typedef vec4 fvec4; - -typedef vec2 dvec2; -typedef vec3 dvec3; -typedef vec4 dvec4; - - -//============================================================================// -// -// Static assertions to check type sizes -// -#define VECTORS_STATIC_ASSERT(x) \ - typedef char vectors_h_static_assert[(x) ? 1 : -1] - -VECTORS_STATIC_ASSERT(sizeof(fvec2) == (2 * sizeof(float))); -VECTORS_STATIC_ASSERT(sizeof(fvec3) == (3 * sizeof(float))); -VECTORS_STATIC_ASSERT(sizeof(fvec4) == (4 * sizeof(float))); -VECTORS_STATIC_ASSERT(sizeof(dvec2) == (2 * sizeof(double))); -VECTORS_STATIC_ASSERT(sizeof(dvec3) == (3 * sizeof(double))); -VECTORS_STATIC_ASSERT(sizeof(dvec4) == (4 * sizeof(double))); - -#undef VECTORS_STATIC_ASSERT - - -// utils - -inline fvec3 Float3ToVec3 ( const float * f) -{ - return fvec3(f[0],f[1],f[2]); -} -inline fvec4 Float3ToVec4 ( const float * f) -{ - return fvec4(f[0],f[1],f[2],1.0f); -} -inline fvec4 Float4ToVec4 ( const float * f) -{ - return fvec4(f[0],f[1],f[2],f[3]); -} - -//============================================================================// - - -#endif // VECTORS_H - - -// Local Variables: *** -// mode: C++ *** -// tab-width: 4 *** -// c-basic-offset: 4 *** -// indent-tabs-mode: nil *** -// End: *** -// ex: shiftwidth=4 tabstop=4 diff --git a/include/vectors_old.h b/include/vectors_old.h deleted file mode 100644 index d60a16543e..0000000000 --- a/include/vectors_old.h +++ /dev/null @@ -1,135 +0,0 @@ -/* bzflag - * Copyright (c) 1993-2023 Tim Riker - * - * This package is free software; you can redistribute it and/or - * modify it under the terms of the license found in the file - * named COPYING that should have accompanied this file. - * - * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. - */ - -#ifndef __VECTOR_MATH_H__ -#define __VECTOR_MATH_H__ - -// 1st -#include "common.h" - -// System headers -#include - -// vectors implemented as arrays -typedef float afvec2[2]; -typedef float afvec3[3]; -typedef float afvec4[4]; - -// vectors implemented as simple classes -class cfvec2 -{ -public: - cfvec2() - { - memset(data,0,sizeof(float)*2); - } - cfvec2(const float values[2]) - { - memcpy (data, values, sizeof(float[2])); - } - cfvec2& operator=(const float values[2]) - { - memcpy (data, values, sizeof(float[2])); - return *this; - } - inline float& operator[](int pos) - { - return data[pos]; - } - float data[2]; -}; - -class cfvec3 -{ -public: - cfvec3() - { - memset(data,0,sizeof(float)*3); - } - cfvec3(const float values[3]) - { - memcpy (data, values, sizeof(float[3])); - } - cfvec3& operator=(const float values[3]) - { - memcpy (data, values, sizeof(float[3])); - return *this; - } - inline float& operator[](int pos) - { - return data[pos]; - } - float data[3]; -}; - -class cfvec4 -{ -public: - cfvec4() - { - memset(data,0,sizeof(float)*4); - } - cfvec4(const float values[4]) - { - memcpy (data, values, sizeof(float[4])); - } - cfvec4& operator=(const float values[4]) - { - memcpy (data, values, sizeof(float[4])); - return *this; - } - inline float& operator[](int pos) - { - return data[pos]; - } - float data[4]; -}; - - -// FIXME - some these should go into a common file -// Some handy geometry functions - -static inline void vec3add (float *result, const float* v1, const float* v2) -{ - result[0] = v1[0] + v2[0]; - result[1] = v1[1] + v2[1]; - result[2] = v1[2] + v2[2]; - return; -} -static inline void vec3sub (float *result, const float* v1, const float* v2) -{ - result[0] = v1[0] - v2[0]; - result[1] = v1[1] - v2[1]; - result[2] = v1[2] - v2[2]; - return; -} -static inline float vec3dot (const float* v1, const float* v2) -{ - return (v1[0] * v2[0]) + (v1[1] * v2[1]) + (v1[2] * v2[2]); -} -static inline void vec3cross (float* result, const float* v1, const float* v2) -{ - result[0] = (v1[1] * v2[2]) - (v1[2] * v2[1]); - result[1] = (v1[2] * v2[0]) - (v1[0] * v2[2]); - result[2] = (v1[0] * v2[1]) - (v1[1] * v2[0]); - return; -} - -#endif // __VECTOR_MATH_H__ - -// Local variables: *** -// mode: C++ *** -// tab-width: 8 *** -// c-basic-offset: 2 *** -// indent-tabs-mode: t *** -// End: *** -// ex: shiftwidth=2 tabstop=8 diff --git a/src/3D/FontManager.cxx b/src/3D/FontManager.cxx index ff47f8777e..0a28f5cbdd 100644 --- a/src/3D/FontManager.cxx +++ b/src/3D/FontManager.cxx @@ -10,9 +10,6 @@ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ -// BZFlag common header -#include "common.h" - // Interface header #include "FontManager.h" @@ -31,13 +28,14 @@ #include "OpenGLGState.h" #include "TimeKeeper.h" #include "TextUtils.h" +#include "OpenGLAPI.h" // Local implementation headers #include "ImageFont.h" #include "TextureFont.h" // ANSI code GLFloat equivalents - these should line up with the enums in AnsiCodes.h -static GLfloat BrightColors[9][3] = +static glm::vec3 BrightColors[9] = { {1.0f,1.0f,0.0f}, // yellow {1.0f,0.0f,0.0f}, // red @@ -50,29 +48,17 @@ static GLfloat BrightColors[9][3] = {0.0f,1.0f,1.0f} // cyan }; -GLfloat FontManager::underlineColor[4]; +glm::vec3 FontManager::underlineColor; void FontManager::callback(const std::string &, void *) { // set underline color const std::string uColor = BZDB.get("underlineColor"); if (strcasecmp(uColor.c_str(), "text") == 0) - { - underlineColor[0] = -1.0f; - underlineColor[1] = -1.0f; - underlineColor[2] = -1.0f; - } + underlineColor = glm::vec3(-1.0f); else if (strcasecmp(uColor.c_str(), "cyan") == 0) - { - underlineColor[0] = BrightColors[CyanColor][0]; - underlineColor[1] = BrightColors[CyanColor][1]; - underlineColor[2] = BrightColors[CyanColor][2]; - } + underlineColor = BrightColors[CyanColor]; else if (strcasecmp(uColor.c_str(), "grey") == 0) - { - underlineColor[0] = BrightColors[GreyColor][0]; - underlineColor[1] = BrightColors[GreyColor][1]; - underlineColor[2] = BrightColors[GreyColor][2]; - } + underlineColor = BrightColors[GreyColor]; } FontManager::FontManager() : Singleton(), @@ -244,7 +230,7 @@ const char* FontManager::getFaceName(int faceID) } void FontManager::drawString(float x, float y, float z, int faceID, float size, - const std::string &text, const float* resetColor) + const std::string &text, glm::vec3 resetColor) { if (text.size() == 0) return; @@ -296,25 +282,16 @@ void FontManager::drawString(float x, float y, float z, int faceID, float size, bool pulsating = false; bool underline = false; // negatives are invalid, we use them to signal "no change" - GLfloat color[4] = {-1.0f, -1.0f, -1.0f, opacity}; - if (resetColor != NULL) - { - color[0] = resetColor[0] * darkness; - color[1] = resetColor[1] * darkness; - color[2] = resetColor[2] * darkness; - } + auto color = glm::vec3(-1.0f); + if (resetColor.x >= 0) + color = resetColor * darkness; else resetColor = BrightColors[WhiteColor]; const float darkDim = dimFactor * darkness; // underline color changes for bright == false - GLfloat dimUnderlineColor[4] = { underlineColor[0] * darkDim, - underlineColor[1] * darkDim, - underlineColor[2] * darkDim, - opacity - }; - underlineColor[3] = opacity; + auto dimUnderlineColor = underlineColor * darkDim; /* * ANSI code interpretation is somewhat limited, we only accept values @@ -338,7 +315,7 @@ void FontManager::drawString(float x, float y, float z, int faceID, float size, { // pulsate the text, if desired if (pulsating) - getPulseColor(color, color); + color *= getPulseFactor(); // render text int len = endSend - startSend; if (len > 0) @@ -351,17 +328,20 @@ void FontManager::drawString(float x, float y, float z, int faceID, float size, GLboolean depthMask; glGetBooleanv(GL_DEPTH_WRITEMASK, &depthMask); glDepthMask(0); - pFont->drawString(scale, color, &tmpText[startSend], len); + pFont->drawString(scale, color, opacity, &tmpText[startSend], len); if (underline) { glDisable(GL_TEXTURE_2D); glEnable(GL_BLEND); - if (bright && underlineColor[0] >= 0) - glColor4fv(underlineColor); - else if (underlineColor[0] >= 0) - glColor4fv(dimUnderlineColor); + if (underlineColor[0] >= 0) + { + if (bright) + glColor(underlineColor, opacity); + else + glColor(dimUnderlineColor, opacity); + } else if (color[0] >= 0) - glColor4fv(color); + glColor(color, opacity); // still have a translated matrix, these coordinates are // with respect to the string just drawn glBegin(GL_LINES); @@ -389,17 +369,9 @@ void FontManager::drawString(float x, float y, float z, int faceID, float size, if (tmpText == ColorStrings[i]) { if (bright) - { - color[0] = BrightColors[i][0] * darkness; - color[1] = BrightColors[i][1] * darkness; - color[2] = BrightColors[i][2] * darkness; - } + color = BrightColors[i] * darkness; else - { - color[0] = BrightColors[i][0] * darkDim; - color[1] = BrightColors[i][1] * darkDim; - color[2] = BrightColors[i][2] * darkDim; - } + color = BrightColors[i] * darkDim; tookCareOfANSICode = true; break; } @@ -413,18 +385,14 @@ void FontManager::drawString(float x, float y, float z, int faceID, float size, bright = true; pulsating = false; underline = false; - color[0] = resetColor[0] * darkness; - color[1] = resetColor[1] * darkness; - color[2] = resetColor[2] * darkness; + color = resetColor * darkness; } else if (tmpText == ANSI_STR_RESET_FINAL) { bright = false; pulsating = false; underline = false; - color[0] = resetColor[0] * darkDim; - color[1] = resetColor[1] * darkDim; - color[2] = resetColor[2] * darkDim; + color = resetColor * darkDim; } else if (tmpText == ANSI_STR_BRIGHT) bright = true; @@ -476,14 +444,6 @@ void FontManager::drawString(float x, float y, float z, int faceID, float size, return; } -void FontManager::drawString(float x, float y, float z, - const std::string &face, float size, - const std::string &text, - const float* resetColor) -{ - drawString(x, y, z, getFaceID(face), size, text, resetColor); -} - float FontManager::getStrLength(int faceID, float size, const std::string &text, bool alreadyStripped) { @@ -600,7 +560,7 @@ ImageFont* FontManager::getClosestRealSize(int faceID, float desiredSize, flo return font; } -void FontManager::getPulseColor(const GLfloat *color, GLfloat *pulseColor) const +float FontManager::getPulseFactor() const { float pulseTime = (float)TimeKeeper::getCurrent().getSeconds(); @@ -613,9 +573,7 @@ void FontManager::getPulseColor(const GLfloat *color, GLfloat *pulseColor pulseFactor = fabsf(pulseFactor) / (pulseRate/2.0f); pulseFactor = pulseDepth * pulseFactor + (1.0f - pulseDepth); - pulseColor[0] = color[0] * pulseFactor; - pulseColor[1] = color[1] * pulseFactor; - pulseColor[2] = color[2] * pulseFactor; + return pulseFactor; } // Local Variables: *** diff --git a/src/3D/ImageFont.h b/src/3D/ImageFont.h index 9bde669a00..bfe2b82f55 100644 --- a/src/3D/ImageFont.h +++ b/src/3D/ImageFont.h @@ -18,6 +18,7 @@ /* system headers */ #include +#include /* interface headers */ #include "bzfgl.h" @@ -40,7 +41,9 @@ class ImageFont virtual bool isBuilt() const = 0; virtual void filter(bool dofilter) = 0; - virtual void drawString(float scale, GLfloat color[4], const char *str, int len) = 0; + virtual void drawString(float scale, + const glm::vec3 &color, float alpha, + const char *str, int len) = 0; float getStrLength(float scale, const char *str, int len) const; float getStrLength(float scale, const std::string &str) const; diff --git a/src/3D/TextureFont.cxx b/src/3D/TextureFont.cxx index 80e433f5de..365ebed453 100644 --- a/src/3D/TextureFont.cxx +++ b/src/3D/TextureFont.cxx @@ -20,11 +20,13 @@ // System headers #include #include +#include // Common implementation headers #include "bzfgl.h" #include "bzfio.h" #include "OpenGLGState.h" +#include "OpenGLAPI.h" // Local implementation headers #include "TextureManager.h" @@ -148,8 +150,9 @@ void TextureFont::filter(bool dofilter) } } -void TextureFont::drawString(float scale, GLfloat color[4], const char *str, - int len) +void TextureFont::drawString(float scale, + const glm::vec3 &color, float alpha, + const char *str, int len) { if (!str) return; @@ -167,7 +170,7 @@ void TextureFont::drawString(float scale, GLfloat color[4], const char *str, return; if (color[0] >= 0) - glColor4fv(color); + glColor(color, alpha); glPushMatrix(); glScalef(scale, scale, 1); diff --git a/src/3D/TextureFont.h b/src/3D/TextureFont.h index fb758234dd..2e486b4895 100644 --- a/src/3D/TextureFont.h +++ b/src/3D/TextureFont.h @@ -30,7 +30,9 @@ class TextureFont : public ImageFont } virtual void filter(bool dofilter); - virtual void drawString(float scale, GLfloat color[4], const char *str, int len); + virtual void drawString(float scale, + const glm::vec3 &color, float alpha, + const char *str, int len); virtual void free(); diff --git a/src/bzflag/AutoPilot.cxx b/src/bzflag/AutoPilot.cxx index 49ace49a1c..ca0f88c36b 100644 --- a/src/bzflag/AutoPilot.cxx +++ b/src/bzflag/AutoPilot.cxx @@ -84,7 +84,7 @@ static bool isFlagUseful(FlagType *type) static ShotPath *findWorstBullet(float &minDistance) { LocalPlayer *myTank = LocalPlayer::getMyTank(); - const float *pos = myTank->getPosition(); + const auto &pos = myTank->getPosition(); ShotPath *minPath = NULL; minDistance = Infinity; @@ -109,7 +109,7 @@ static ShotPath *findWorstBullet(float &minDistance) (myTank->getFlag() == Flags::Cloaking)) continue; //cloaked tanks can't die from lasers - const float* shotPos = shot->getPosition(); + const auto shotPos = shot->getPosition(); if ((fabs(shotPos[2] - pos[2]) > BZDBCache::tankHeight) && (shot->getFlag() != Flags::GuidedMissile)) continue; @@ -117,7 +117,7 @@ static ShotPath *findWorstBullet(float &minDistance) const float dist = TargetingUtils::getTargetDistance(pos, shotPos); if (dist < minDistance) { - const float *shotVel = shot->getVelocity(); + const auto shotVel = shot->getVelocity(); float shotAngle = atan2f(shotVel[1], shotVel[0]); float shotUnitVec[2] = {cosf(shotAngle), sinf(shotAngle)}; @@ -145,14 +145,14 @@ static ShotPath *findWorstBullet(float &minDistance) if (shot->getFlag() == Flags::Laser && myTank->getFlag() == Flags::Cloaking) continue; //cloaked tanks can't die from lasers - const float* shotPos = shot->getPosition(); + const auto shotPos = shot->getPosition(); if ((fabs(shotPos[2] - pos[2]) > BZDBCache::tankHeight) && (shot->getFlag() != Flags::GuidedMissile)) continue; const float dist = TargetingUtils::getTargetDistance( pos, shotPos ); if (dist < minDistance) { - const float *shotVel = shot->getVelocity(); + const auto shotVel = shot->getVelocity(); float shotAngle = atan2f(shotVel[1], shotVel[0]); float shotUnitVec[2] = {cosf(shotAngle), sinf(shotAngle)}; @@ -174,9 +174,8 @@ static ShotPath *findWorstBullet(float &minDistance) static bool avoidDeathFall(float & UNUSED(rotation), float &speed) { LocalPlayer *myTank = LocalPlayer::getMyTank(); - float pos1[3], pos2[3]; - memcpy(pos1, myTank->getPosition(), sizeof(pos1)); - memcpy(pos2, pos1, sizeof(pos1)); + auto pos1 = myTank->getPosition(); + auto pos2 = pos1; pos1[2] += 10.0f * BZDBCache::tankHeight; float azimuth = myTank->getAngle(); if (speed < 0.0f) @@ -188,7 +187,7 @@ static bool avoidDeathFall(float & UNUSED(rotation), float &speed) pos2[1] += 8.0f * BZDBCache::tankHeight * sinf(azimuth); pos2[2] += 0.01f; - float collisionPt[3]; + glm::vec3 collisionPt; if (TargetingUtils::getFirstCollisionPoint( pos1, pos2, collisionPt )) { if (collisionPt[2] < 0.0f) @@ -208,7 +207,7 @@ static bool avoidDeathFall(float & UNUSED(rotation), float &speed) static bool avoidBullet(float &rotation, float &speed) { LocalPlayer *myTank = LocalPlayer::getMyTank(); - const float *pos = myTank->getPosition(); + const auto &pos = myTank->getPosition(); if ((myTank->getFlag() == Flags::Narrow) || (myTank->getFlag() == Flags::Burrow)) return false; // take our chances @@ -219,8 +218,8 @@ static bool avoidBullet(float &rotation, float &speed) if ((shot == NULL) || (minDistance > 100.0f)) return false; - const float *shotPos = shot->getPosition(); - const float *shotVel = shot->getVelocity(); + const auto &shotPos = shot->getPosition(); + const auto shotVel = shot->getVelocity(); float shotAngle = atan2f(shotVel[1],shotVel[0]); float shotUnitVec[2] = {cosf(shotAngle), sinf(shotAngle)}; @@ -290,7 +289,7 @@ static bool stuckOnWall(float &rotation, float &speed) } LocalPlayer *myTank = LocalPlayer::getMyTank(); - const float *pos = myTank->getPosition(); + const auto &pos = myTank->getPosition(); float myAzimuth = myTank->getAngle(); const bool phased = (myTank->getFlag() == Flags::OscillationOverthruster) @@ -326,7 +325,7 @@ static RemotePlayer *findBestTarget() { RemotePlayer *target = NULL; LocalPlayer *myTank = LocalPlayer::getMyTank(); - const float *pos = myTank->getPosition(); + const auto &pos = myTank->getPosition(); float myAzimuth = myTank->getAngle(); float distance = Infinity; @@ -385,7 +384,7 @@ static RemotePlayer *findBestTarget() static bool chasePlayer(float &rotation, float &speed) { LocalPlayer *myTank = LocalPlayer::getMyTank(); - const float *pos = myTank->getPosition(); + const auto &pos = myTank->getPosition(); RemotePlayer *rPlayer = findBestTarget(); if (rPlayer == NULL) @@ -393,21 +392,12 @@ static bool chasePlayer(float &rotation, float &speed) myTank->setTarget(rPlayer); - const float *targetPos = rPlayer->getPosition(); + const auto &targetPos = rPlayer->getPosition(); float distance = TargetingUtils::getTargetDistance(pos, targetPos); if (distance > 250.0f) return false; - const float *tp = rPlayer->getPosition(); - float enemyPos[3]; - //toss in some lag adjustment/future prediction - 300 millis - memcpy(enemyPos,tp,sizeof(enemyPos)); - const float *tv = rPlayer->getVelocity(); - enemyPos[0] += 0.3f * tv[0]; - enemyPos[1] += 0.3f * tv[1]; - enemyPos[2] += 0.3f * tv[2]; - if (enemyPos[2] < 0.0f) //Roger doesn't worry about burrow - enemyPos[2] = 0.0; + const auto &tp = rPlayer->getPosition(); float myAzimuth = myTank->getAngle(); float enemyAzimuth = TargetingUtils::getTargetAzimuth( pos, tp ); @@ -419,7 +409,7 @@ static bool chasePlayer(float &rotation, float &speed) const Obstacle *building = NULL; float d = distance - 5.0f; //Make sure building is REALLY in front of player (-5) - float dir[3] = {cosf(myAzimuth), sinf(myAzimuth), 0.0f}; + const auto dir = glm::vec3(cosf(myAzimuth), sinf(myAzimuth), 0.0f); Ray tankRay(pos, dir); building = ShotStrategy::getFirstBuilding(tankRay, -0.5f, d); @@ -497,9 +487,8 @@ static bool chasePlayer(float &rotation, float &speed) static bool lookForFlag(float &rotation, float &speed) { LocalPlayer *myTank = LocalPlayer::getMyTank(); - float pos[3]; - memcpy( pos, myTank->getPosition(), sizeof( pos )); + auto pos = myTank->getPosition(); if (pos[2] < 0.0f) pos[2] = 0.0f; World *world = World::getWorld(); @@ -519,7 +508,7 @@ static bool lookForFlag(float &rotation, float &speed) if (world->getFlag(i).type->flagTeam != NoTeam) teamFlag = i; - const float* fpos = world->getFlag(i).position; + const auto &fpos = world->getFlag(i).position; if (fpos[2] == pos[2]) { float dist = TargetingUtils::getTargetDistance(pos, fpos); @@ -548,7 +537,7 @@ static bool lookForFlag(float &rotation, float &speed) } } - const float *fpos = world->getFlag(closestFlag).position; + const auto &fpos = world->getFlag(closestFlag).position; float myAzimuth = myTank->getAngle(); float flagAzimuth = TargetingUtils::getTargetAzimuth(pos, fpos); rotation = TargetingUtils::getTargetRotation(myAzimuth, flagAzimuth); @@ -572,9 +561,8 @@ static bool navigate(float &rotation, float &speed) } LocalPlayer *myTank = LocalPlayer::getMyTank(); - float pos[3]; - memcpy(pos, myTank->getPosition(), sizeof(pos)); + auto pos = myTank->getPosition(); if (pos[2] < 0.0f) pos[2] = 0.01f; float myAzimuth = myTank->getAngle(); @@ -599,25 +587,28 @@ static bool navigate(float &rotation, float &speed) if (myTank->getFlag()->flagTeam != NoTeam) { World *world = World::getWorld(); - const float *temp = world->getBase(myTank->getTeam()); - if (temp == NULL) + glm::vec3 basePos; + float rrotation; + float w, b, h; + const bool isThereABase = world->getBase(myTank->getTeam(), 0, basePos, rrotation, w, b, h); + const auto myPos = myTank->getPosition(); + if (!isThereABase) { - serverLink->sendDropFlag(myTank->getPosition()); + serverLink->sendDropFlag(myPos); handleFlagDropped(myTank); } else { - if ((((int) *(world->getBase(myTank->getTeam())) + 2 - >= (int) *(myTank->getPosition())) - || (temp[0] == pos[0] && temp[1] == pos[1])) && + if ((((int) basePos[0] + 2 >= (int) pos[0]) + || (basePos[0] == pos[0] && basePos[1] == pos[1])) && myTank->getFlag()->flagTeam == myTank->getTeam()) { - serverLink->sendDropFlag(myTank->getPosition()); + serverLink->sendDropFlag(myPos); handleFlagDropped(myTank); } else { - float baseAzimuth = TargetingUtils::getTargetAzimuth(pos, temp); + float baseAzimuth = TargetingUtils::getTargetAzimuth(pos, basePos); rotation = TargetingUtils::getTargetRotation(myAzimuth, baseAzimuth); speed = (float)(M_PI/2.0 - fabs(rotation)); } @@ -638,14 +629,13 @@ static bool navigate(float &rotation, float &speed) static bool fireAtTank() { static TimeKeeper lastShot; - float pos[3]; LocalPlayer *myTank = LocalPlayer::getMyTank(); - memcpy(pos, myTank->getPosition(), sizeof(pos)); + auto pos = myTank->getPosition(); if (pos[2] < 0.0f) pos[2] = 0.01f; float myAzimuth = myTank->getAngle(); - float dir[3] = {cosf(myAzimuth), sinf(myAzimuth), 0.0f}; + const auto dir = glm::vec3(cosf(myAzimuth), sinf(myAzimuth), 0.0f); pos[2] += myTank->getMuzzleHeight(); Ray tankRay(pos, dir); pos[2] -= myTank->getMuzzleHeight(); @@ -663,14 +653,11 @@ static bool fireAtTank() !remotePlayers[t]->isNotResponding()) { - const float *tp = remotePlayers[t]->getPosition(); - float enemyPos[3]; + const auto &tp = remotePlayers[t]->getPosition(); //toss in some lag adjustment/future prediction - 300 millis - memcpy(enemyPos,tp,sizeof(enemyPos)); - const float *tv = remotePlayers[t]->getVelocity(); - enemyPos[0] += 0.3f * tv[0]; - enemyPos[1] += 0.3f * tv[1]; - enemyPos[2] += 0.3f * tv[2]; + auto enemyPos = tp; + const auto &tv = remotePlayers[t]->getVelocity(); + enemyPos += 0.3f * tv; if (enemyPos[2] < 0.0f) enemyPos[2] = 0.0f; float dist = TargetingUtils::getTargetDistance( pos, enemyPos ); @@ -716,14 +703,11 @@ static bool fireAtTank() && (myTank->getFlag() != Flags::ShockWave)) continue; - const float *tp = remotePlayers[t]->getPosition(); - float enemyPos[3]; + const auto &tp = remotePlayers[t]->getPosition(); //toss in some lag adjustment/future prediction - 300 millis - memcpy(enemyPos,tp,sizeof(enemyPos)); - const float *tv = remotePlayers[t]->getVelocity(); - enemyPos[0] += 0.3f * tv[0]; - enemyPos[1] += 0.3f * tv[1]; - enemyPos[2] += 0.3f * tv[2]; + auto enemyPos = tp; + const auto &tv = remotePlayers[t]->getVelocity(); + enemyPos += 0.3f * tv; if (enemyPos[2] < 0.0f) enemyPos[2] = 0.0f; diff --git a/src/bzflag/BackgroundRenderer.cxx b/src/bzflag/BackgroundRenderer.cxx index f8ba8fd705..3787a82489 100644 --- a/src/bzflag/BackgroundRenderer.cxx +++ b/src/bzflag/BackgroundRenderer.cxx @@ -15,6 +15,9 @@ // system headers #include +#include +#define GLM_ENABLE_EXPERIMENTAL +#include // common headers #include "OpenGLMaterial.h" @@ -24,6 +27,7 @@ #include "TextureMatrix.h" #include "ParseColor.h" #include "BZDBCache.h" +#include "OpenGLAPI.h" // local headers #include "daylight.h" @@ -32,28 +36,28 @@ #include "SceneNode.h" #include "effectsRenderer.h" -static const GLfloat squareShape[4][2] = +static const glm::vec2 squareShape[4] = { { 1.0f, 1.0f }, { -1.0f, 1.0f }, { -1.0f, -1.0f }, { 1.0f, -1.0f } }; -GLfloat BackgroundRenderer::skyPyramid[5][3]; +glm::vec3 BackgroundRenderer::skyPyramid[5]; const GLfloat BackgroundRenderer::cloudRepeats = 3.0f; static const int NumMountainFaces = 16; -GLfloat BackgroundRenderer::groundColor[4][4]; -GLfloat BackgroundRenderer::groundColorInv[4][4]; +glm::vec4 BackgroundRenderer::groundColor[4]; +glm::vec4 BackgroundRenderer::groundColorInv[4]; -const GLfloat BackgroundRenderer::defaultGroundColor[4][4] = +const glm::vec4 BackgroundRenderer::defaultGroundColor[4] = { { 0.0f, 0.35f, 0.0f, 1.0f }, { 0.0f, 0.20f, 0.0f, 1.0f }, { 1.0f, 1.00f, 1.0f, 1.0f }, { 1.0f, 1.00f, 1.0f, 1.0f } }; -const GLfloat BackgroundRenderer::defaultGroundColorInv[4][4] = +const glm::vec4 BackgroundRenderer::defaultGroundColorInv[4] = { { 0.35f, 0.00f, 0.35f, 1.0f }, { 0.20f, 0.00f, 0.20f, 1.0f }, @@ -75,8 +79,8 @@ BackgroundRenderer::BackgroundRenderer() : { static bool init = false; OpenGLGStateBuilder gstate; - static const GLfloat black[3] = { 0.0f, 0.0f, 0.0f }; - static const GLfloat white[3] = { 1.0f, 1.0f, 1.0f }; + static const auto black = glm::vec3(0.0f); + static const auto white = glm::vec3(1.0f); OpenGLMaterial defaultMaterial(black, black, 0.0f); OpenGLMaterial rainMaterial(white, white, 0.0f); @@ -99,9 +103,9 @@ BackgroundRenderer::BackgroundRenderer() : } // initialize the celestial vectors - static const float up[3] = { 0.0f, 0.0f, 1.0f }; - memcpy(sunDirection, up, sizeof(float[3])); - memcpy(moonDirection, up, sizeof(float[3])); + static const auto up = glm::vec3(0.0f, 0.0f, 1.0f); + sunDirection = up; + moonDirection = up; // make ground materials setupSkybox(); @@ -276,7 +280,8 @@ void BackgroundRenderer::setupGroundMaterials() if (bzmat == NULL) { // default ground material - memcpy (groundColor, defaultGroundColor, sizeof(GLfloat[4][4])); + for (int i = 0; i < 4; i++) + groundColor[i] = defaultGroundColor[i]; groundTextureID = tm.getTextureID(BZDB.get("stdGroundTexture").c_str(), true); } else @@ -284,14 +289,15 @@ void BackgroundRenderer::setupGroundMaterials() // map specified material bzmat->setReference(); for (int i = 0; i < 4; i++) - memcpy (groundColor[i], bzmat->getDiffuse(), sizeof(GLfloat[4])); + groundColor[i] = bzmat->getDiffuse(); if (bzmat->getTextureCount() > 0) { groundTextureID = tm.getTextureID(bzmat->getTextureLocal(0).c_str(), false); if (groundTextureID < 0) { // use the default as a backup (default color too) - memcpy (groundColor, defaultGroundColor, sizeof(GLfloat[4][4])); + for (int i = 0; i < 4; i++) + groundColor[i] = defaultGroundColor[i]; groundTextureID = tm.getTextureID(BZDB.get("stdGroundTexture").c_str(), true); } else @@ -305,7 +311,7 @@ void BackgroundRenderer::setupGroundMaterials() } } - static const GLfloat black[3] = { 0.0f, 0.0f, 0.0f }; + static const auto black = glm::vec3(0.0f); OpenGLMaterial defaultMaterial(black, black, 0.0f); OpenGLGStateBuilder gb; @@ -329,7 +335,8 @@ void BackgroundRenderer::setupGroundMaterials() // default inverted ground material int groundInvTextureID = -1; - memcpy (groundColorInv, defaultGroundColorInv, sizeof(GLfloat[4][4])); + for (int i = 0; i < 4; i++) + groundColorInv[i] = defaultGroundColorInv[i]; if (groundInvTextureID < 0) groundInvTextureID = tm.getTextureID(BZDB.get("zoneGroundTexture").c_str(), false); @@ -395,16 +402,12 @@ void BackgroundRenderer::resize() void BackgroundRenderer::setCelestial(const SceneRenderer& renderer, - const float sunDir[3], - const float moonDir[3]) + const glm::vec3 &sunDir, + const glm::vec3 &moonDir) { // set sun and moon positions - sunDirection[0] = sunDir[0]; - sunDirection[1] = sunDir[1]; - sunDirection[2] = sunDir[2]; - moonDirection[0] = moonDir[0]; - moonDirection[1] = moonDir[1]; - moonDirection[2] = moonDir[2]; + sunDirection = sunDir; + moonDirection = moonDir; if (sunXFormList != INVALID_GL_LIST_ID) { @@ -431,21 +434,13 @@ void BackgroundRenderer::setCelestial(const SceneRenderer& renderer, void BackgroundRenderer::setSkyColors() { // change sky colors according to the sun position - GLfloat colors[4][3]; + glm::vec3 colors[4]; getSkyColor(sunDirection, colors); - skyZenithColor[0] = colors[0][0]; - skyZenithColor[1] = colors[0][1]; - skyZenithColor[2] = colors[0][2]; - skySunDirColor[0] = colors[1][0]; - skySunDirColor[1] = colors[1][1]; - skySunDirColor[2] = colors[1][2]; - skyAntiSunDirColor[0] = colors[2][0]; - skyAntiSunDirColor[1] = colors[2][1]; - skyAntiSunDirColor[2] = colors[2][2]; - skyCrossSunDirColor[0] = colors[3][0]; - skyCrossSunDirColor[1] = colors[3][1]; - skyCrossSunDirColor[2] = colors[3][2]; + skyZenithColor = colors[0]; + skySunDirColor = colors[1]; + skyAntiSunDirColor = colors[2]; + skyCrossSunDirColor = colors[3]; return; } @@ -474,9 +469,7 @@ void BackgroundRenderer::makeCelestialLists(const SceneRenderer& renderer) glEndList(); // compute display list for moon - float coverage = (moonDirection[0] * sunDirection[0]) + - (moonDirection[1] * sunDirection[1]) + - (moonDirection[2] * sunDirection[2]); + float coverage = glm::dot(moonDirection, sunDirection); // hack coverage to lean towards full coverage = (coverage < 0.0f) ? -sqrtf(-coverage) : coverage * coverage; float worldSize = BZDBCache::worldSize; @@ -732,14 +725,8 @@ void BackgroundRenderer::resizeSky() // (adjusted for the deepProjection matrix) const GLfloat skySize = 3.0f * BZDBCache::worldSize; for (int i = 0; i < 4; i++) - { - skyPyramid[i][0] = skySize * squareShape[i][0]; - skyPyramid[i][1] = skySize * squareShape[i][1]; - skyPyramid[i][2] = 0.0f; - } - skyPyramid[4][0] = 0.0f; - skyPyramid[4][1] = 0.0f; - skyPyramid[4][2] = skySize; + skyPyramid[i] = glm::vec3(skySize * squareShape[i], 0.0f); + skyPyramid[4] = glm::vec3(0.0f, 0.0f, skySize); } @@ -804,13 +791,10 @@ void BackgroundRenderer::setupSkybox() }; for (i = 0; i < 8; i++) { - for (int c = 0; c < 4; c++) - { - skyboxColor[i][c] = 0.0f; - for (int f = 0; f < 3; f++) - skyboxColor[i][c] += bzmats[cornerFaces[i][f]]->getDiffuse()[c]; - skyboxColor[i][c] /= 3.0f; - } + skyboxColor[i] = glm::vec3(0.0f); + for (int f = 0; f < 3; f++) + skyboxColor[i] += glm::vec3(bzmats[cornerFaces[i][f]]->getDiffuse()); + skyboxColor[i] /= 3.0f; } haveSkybox = true; @@ -818,18 +802,17 @@ void BackgroundRenderer::setupSkybox() return; } - void BackgroundRenderer::drawSkybox() { // sky box must fit inside far clipping plane // (adjusted for the deepProjection matrix) const float d = 3.0f * BZDBCache::worldSize; - const GLfloat verts[8][3] = + const glm::vec3 verts[8] = { {-d, -d, -d}, {+d, -d, -d}, {+d, +d, -d}, {-d, +d, -d}, {-d, -d, +d}, {+d, -d, +d}, {+d, +d, +d}, {-d, +d, +d} }; - const GLfloat txcds[4][2] = + const glm::vec2 txcds[4] = { {1.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 1.0f}, {1.0f, 1.0f} @@ -839,7 +822,7 @@ void BackgroundRenderer::drawSkybox() OpenGLGState::resetState(); - const GLfloat (*color)[4] = skyboxColor; + const auto &color = skyboxColor; glEnable(GL_TEXTURE_2D); glDisable(GL_CULL_FACE); @@ -852,18 +835,18 @@ void BackgroundRenderer::drawSkybox() glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, skyboxWrapMode); glBegin(GL_TRIANGLE_STRIP); { - glTexCoord2fv(txcds[0]); - glColor3fv(color[2]); - glVertex3fv(verts[2]); - glTexCoord2fv(txcds[1]); - glColor3fv(color[3]); - glVertex3fv(verts[3]); - glTexCoord2fv(txcds[3]); - glColor3fv(color[1]); - glVertex3fv(verts[1]); - glTexCoord2fv(txcds[2]); - glColor3fv(color[0]); - glVertex3fv(verts[0]); + glTexCoord(txcds[0]); + glColor(color[2]); + glVertex(verts[2]); + glTexCoord(txcds[1]); + glColor(color[3]); + glVertex(verts[3]); + glTexCoord(txcds[3]); + glColor(color[1]); + glVertex(verts[1]); + glTexCoord(txcds[2]); + glColor(color[0]); + glVertex(verts[0]); } glEnd(); } @@ -873,18 +856,18 @@ void BackgroundRenderer::drawSkybox() glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, skyboxWrapMode); glBegin(GL_TRIANGLE_STRIP); { - glTexCoord2fv(txcds[0]); - glColor3fv(color[5]); - glVertex3fv(verts[5]); - glTexCoord2fv(txcds[1]); - glColor3fv(color[4]); - glVertex3fv(verts[4]); - glTexCoord2fv(txcds[3]); - glColor3fv(color[6]); - glVertex3fv(verts[6]); - glTexCoord2fv(txcds[2]); - glColor3fv(color[7]); - glVertex3fv(verts[7]); + glTexCoord(txcds[0]); + glColor(color[5]); + glVertex(verts[5]); + glTexCoord(txcds[1]); + glColor(color[4]); + glVertex(verts[4]); + glTexCoord(txcds[3]); + glColor(color[6]); + glVertex(verts[6]); + glTexCoord(txcds[2]); + glColor(color[7]); + glVertex(verts[7]); } glEnd(); @@ -893,18 +876,18 @@ void BackgroundRenderer::drawSkybox() glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, skyboxWrapMode); glBegin(GL_TRIANGLE_STRIP); { - glTexCoord2fv(txcds[0]); - glColor3fv(color[0]); - glVertex3fv(verts[0]); - glTexCoord2fv(txcds[1]); - glColor3fv(color[3]); - glVertex3fv(verts[3]); - glTexCoord2fv(txcds[3]); - glColor3fv(color[4]); - glVertex3fv(verts[4]); - glTexCoord2fv(txcds[2]); - glColor3fv(color[7]); - glVertex3fv(verts[7]); + glTexCoord(txcds[0]); + glColor(color[0]); + glVertex(verts[0]); + glTexCoord(txcds[1]); + glColor(color[3]); + glVertex(verts[3]); + glTexCoord(txcds[3]); + glColor(color[4]); + glVertex(verts[4]); + glTexCoord(txcds[2]); + glColor(color[7]); + glVertex(verts[7]); } glEnd(); @@ -913,18 +896,18 @@ void BackgroundRenderer::drawSkybox() glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, skyboxWrapMode); glBegin(GL_TRIANGLE_STRIP); { - glTexCoord2fv(txcds[0]); - glColor3fv(color[1]); - glVertex3fv(verts[1]); - glTexCoord2fv(txcds[1]); - glColor3fv(color[0]); - glVertex3fv(verts[0]); - glTexCoord2fv(txcds[3]); - glColor3fv(color[5]); - glVertex3fv(verts[5]); - glTexCoord2fv(txcds[2]); - glColor3fv(color[4]); - glVertex3fv(verts[4]); + glTexCoord(txcds[0]); + glColor(color[1]); + glVertex(verts[1]); + glTexCoord(txcds[1]); + glColor(color[0]); + glVertex(verts[0]); + glTexCoord(txcds[3]); + glColor(color[5]); + glVertex(verts[5]); + glTexCoord(txcds[2]); + glColor(color[4]); + glVertex(verts[4]); } glEnd(); @@ -933,18 +916,18 @@ void BackgroundRenderer::drawSkybox() glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, skyboxWrapMode); glBegin(GL_TRIANGLE_STRIP); { - glTexCoord2fv(txcds[0]); - glColor3fv(color[2]); - glVertex3fv(verts[2]); - glTexCoord2fv(txcds[1]); - glColor3fv(color[1]); - glVertex3fv(verts[1]); - glTexCoord2fv(txcds[3]); - glColor3fv(color[6]); - glVertex3fv(verts[6]); - glTexCoord2fv(txcds[2]); - glColor3fv(color[5]); - glVertex3fv(verts[5]); + glTexCoord(txcds[0]); + glColor(color[2]); + glVertex(verts[2]); + glTexCoord(txcds[1]); + glColor(color[1]); + glVertex(verts[1]); + glTexCoord(txcds[3]); + glColor(color[6]); + glVertex(verts[6]); + glTexCoord(txcds[2]); + glColor(color[5]); + glVertex(verts[5]); } glEnd(); @@ -953,18 +936,18 @@ void BackgroundRenderer::drawSkybox() glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, skyboxWrapMode); glBegin(GL_TRIANGLE_STRIP); { - glTexCoord2fv(txcds[0]); - glColor3fv(color[3]); - glVertex3fv(verts[3]); - glTexCoord2fv(txcds[1]); - glColor3fv(color[2]); - glVertex3fv(verts[2]); - glTexCoord2fv(txcds[3]); - glColor3fv(color[7]); - glVertex3fv(verts[7]); - glTexCoord2fv(txcds[2]); - glColor3fv(color[6]); - glVertex3fv(verts[6]); + glTexCoord(txcds[0]); + glColor(color[3]); + glVertex(verts[3]); + glTexCoord(txcds[1]); + glColor(color[2]); + glVertex(verts[2]); + glTexCoord(txcds[3]); + glColor(color[7]); + glVertex(verts[7]); + glTexCoord(txcds[2]); + glColor(color[6]); + glVertex(verts[6]); } glEnd(); @@ -993,18 +976,18 @@ void BackgroundRenderer::drawSky(SceneRenderer& renderer, bool mirror) { // just a pyramid glBegin(GL_TRIANGLE_FAN); - glColor3fv(skyZenithColor); - glVertex3fv(skyPyramid[4]); - glColor3fv(skyCrossSunDirColor); - glVertex3fv(skyPyramid[0]); - glColor3fv(skySunDirColor); - glVertex3fv(skyPyramid[3]); - glColor3fv(skyCrossSunDirColor); - glVertex3fv(skyPyramid[2]); - glColor3fv(skyAntiSunDirColor); - glVertex3fv(skyPyramid[1]); - glColor3fv(skyCrossSunDirColor); - glVertex3fv(skyPyramid[0]); + glColor(skyZenithColor); + glVertex(skyPyramid[4]); + glColor(skyCrossSunDirColor); + glVertex(skyPyramid[0]); + glColor(skySunDirColor); + glVertex(skyPyramid[3]); + glColor(skyCrossSunDirColor); + glVertex(skyPyramid[2]); + glColor(skyAntiSunDirColor); + glVertex(skyPyramid[1]); + glColor(skyCrossSunDirColor); + glVertex(skyPyramid[0]); glEnd(); } else @@ -1013,43 +996,43 @@ void BackgroundRenderer::drawSky(SceneRenderer& renderer, bool mirror) // triangles each. the top triangle is all zenith color, // the bottom goes from zenith to sun-dir color. glBegin(GL_TRIANGLE_FAN); - glColor3fv(skyZenithColor); - glVertex3fv(skyPyramid[4]); - glColor3fv(skyCrossSunDirColor); - glVertex3fv(skyPyramid[2]); - glColor3fv(skyAntiSunDirColor); - glVertex3fv(skyPyramid[1]); - glColor3fv(skyCrossSunDirColor); - glVertex3fv(skyPyramid[0]); + glColor(skyZenithColor); + glVertex(skyPyramid[4]); + glColor(skyCrossSunDirColor); + glVertex(skyPyramid[2]); + glColor(skyAntiSunDirColor); + glVertex(skyPyramid[1]); + glColor(skyCrossSunDirColor); + glVertex(skyPyramid[0]); glEnd(); - GLfloat sunsetTopPoint[3]; + glm::vec3 sunsetTopPoint; sunsetTopPoint[0] = skyPyramid[3][0] * (1.0f - sunsetTop); sunsetTopPoint[1] = skyPyramid[3][1] * (1.0f - sunsetTop); sunsetTopPoint[2] = skyPyramid[4][2] * sunsetTop; glBegin(GL_TRIANGLES); - glColor3fv(skyZenithColor); - glVertex3fv(skyPyramid[4]); - glColor3fv(skyCrossSunDirColor); - glVertex3fv(skyPyramid[0]); - glColor3fv(skyZenithColor); - glVertex3fv(sunsetTopPoint); - glVertex3fv(skyPyramid[4]); - glVertex3fv(sunsetTopPoint); - glColor3fv(skyCrossSunDirColor); - glVertex3fv(skyPyramid[2]); - glColor3fv(skyZenithColor); - glVertex3fv(sunsetTopPoint); - glColor3fv(skyCrossSunDirColor); - glVertex3fv(skyPyramid[0]); - glColor3fv(skySunDirColor); - glVertex3fv(skyPyramid[3]); - glColor3fv(skyCrossSunDirColor); - glVertex3fv(skyPyramid[2]); - glColor3fv(skyZenithColor); - glVertex3fv(sunsetTopPoint); - glColor3fv(skySunDirColor); - glVertex3fv(skyPyramid[3]); + glColor(skyZenithColor); + glVertex(skyPyramid[4]); + glColor(skyCrossSunDirColor); + glVertex(skyPyramid[0]); + glColor(skyZenithColor); + glVertex(sunsetTopPoint); + glVertex(skyPyramid[4]); + glVertex(sunsetTopPoint); + glColor(skyCrossSunDirColor); + glVertex(skyPyramid[2]); + glColor(skyZenithColor); + glVertex(sunsetTopPoint); + glColor(skyCrossSunDirColor); + glVertex(skyPyramid[0]); + glColor(skySunDirColor); + glVertex(skyPyramid[3]); + glColor(skyCrossSunDirColor); + glVertex(skyPyramid[2]); + glColor(skyZenithColor); + glVertex(sunsetTopPoint); + glColor(skySunDirColor); + glVertex(skyPyramid[3]); glEnd(); } } @@ -1070,7 +1053,7 @@ void BackgroundRenderer::drawSky(SceneRenderer& renderer, bool mirror) if (sunDirection[2] > -0.009f) { sunGState.setState(); - glColor3fv(renderer.getSunScaledColor()); + glColor(renderer.getSunScaledColor()); glCallList(sunXFormList); } @@ -1108,7 +1091,7 @@ void BackgroundRenderer::drawGround() glNormal3f(0.0f, 0.0f, 1.0f); if (invert) { - glColor4fv(groundColorInv[styleIndex]); + glColor(groundColorInv[styleIndex]); invGroundGState[styleIndex].setState(); } else @@ -1118,7 +1101,7 @@ void BackgroundRenderer::drawGround() parseColorString(BZDB.get("GroundOverideColor"), color)) glColor4fv(color); else - glColor4fv(groundColor[styleIndex]); + glColor(groundColor[styleIndex]); groundGState[styleIndex].setState(); } @@ -1135,19 +1118,12 @@ void BackgroundRenderer::drawGroundCentered() const float centerSize = 128.0f; const ViewFrustum& frustum = RENDERER.getViewFrustum(); - float center[2] = { frustum.getEye()[0], frustum.getEye()[1] }; + auto center = glm::vec2(frustum.getEye()); const float minDist = -groundSize + centerSize; const float maxDist = +groundSize - centerSize; - if (center[0] < minDist) - center[0] = minDist; - if (center[0] > maxDist) - center[0] = maxDist; - if (center[1] < minDist) - center[1] = minDist; - if (center[1] > maxDist) - center[1] = maxDist; - - const float vertices[8][2] = + center = glm::clamp(center, minDist, maxDist); + + const glm::vec2 vertices[8] = { { -groundSize, -groundSize }, { +groundSize, -groundSize }, @@ -1177,9 +1153,8 @@ void BackgroundRenderer::drawGroundCentered() for (int c = 0; c < 4; c++) { const int index = indices[q][c]; - glTexCoord2f(vertices[index][0] * repeat, - vertices[index][1] * repeat); - glVertex2fv(vertices[index]); + glTexCoord(vertices[index] * repeat); + glVertex(vertices[index]); } glEnd(); } @@ -1192,7 +1167,7 @@ void BackgroundRenderer::drawGroundCentered() void BackgroundRenderer::drawGroundGrid( SceneRenderer& renderer) { - const GLfloat* pos = renderer.getViewFrustum().getEye(); + const auto &pos = renderer.getViewFrustum().getEye(); const GLfloat xhalf = gridSpacing * (gridCount + floorf(pos[2] / 4.0f)); const GLfloat yhalf = gridSpacing * (gridCount + floorf(pos[2] / 4.0f)); const GLfloat x0 = floorf(pos[0] / gridSpacing) * gridSpacing; @@ -1301,11 +1276,11 @@ void BackgroundRenderer::drawGroundShadows( } -static void setupBlackFog(float fogColor[4]) +static void setupBlackFog(glm::vec4 &fogColor) { - static const float black[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; - glGetFloatv(GL_FOG_COLOR, fogColor); - glFogfv(GL_FOG_COLOR, black); + static const auto black = glm::vec4(0.0f); + fogColor = glGetFogColor(); + glSetFogColor(black); } @@ -1314,7 +1289,7 @@ void BackgroundRenderer::drawGroundReceivers(SceneRenderer& renderer) static const int receiverRings = 4; static const int receiverSlices = 8; static const float receiverRingSize = 1.2f; // meters - static float angle[receiverSlices + 1][2]; + static glm::vec2 angle[receiverSlices + 1]; static bool init = false; if (!init) @@ -1338,7 +1313,7 @@ void BackgroundRenderer::drawGroundReceivers(SceneRenderer& renderer) receiverGState.setState(); // setup black fog - float fogColor[4]; + glm::vec4 fogColor; setupBlackFog(fogColor); glPushMatrix(); @@ -1349,8 +1324,8 @@ void BackgroundRenderer::drawGroundReceivers(SceneRenderer& renderer) if (light.getOnlyReal()) continue; - const GLfloat* pos = light.getPosition(); - const GLfloat* lightColor = light.getColor(); + const auto &pos = light.getPosition(); + const auto &lightColor = light.getColor(); const GLfloat* atten = light.getAttenuation(); // point under light @@ -1358,11 +1333,7 @@ void BackgroundRenderer::drawGroundReceivers(SceneRenderer& renderer) float I = B / (atten[0] + d * (atten[1] + d * atten[2])); // maximum value - const float maxVal = (lightColor[0] > lightColor[1]) ? - ((lightColor[0] > lightColor[2]) ? - lightColor[0] : lightColor[2]) : - ((lightColor[1] > lightColor[2]) ? - lightColor[1] : lightColor[2]); + const float maxVal = glm::compMax(glm::vec3(lightColor)); // if I is too attenuated, don't bother drawing anything if ((I * maxVal) < 0.02f) @@ -1372,16 +1343,13 @@ void BackgroundRenderer::drawGroundReceivers(SceneRenderer& renderer) glTranslatef(pos[0], pos[1], 0.0f); // set the main lighting color - float color[4]; - color[0] = lightColor[0]; - color[1] = lightColor[1]; - color[2] = lightColor[2]; + auto color = lightColor; color[3] = I; // draw ground receiver, computing lighting at each vertex ourselves glBegin(GL_TRIANGLE_FAN); { - glColor4fv(color); + glColor(color); glVertex2f(0.0f, 0.0f); // inner ring @@ -1389,12 +1357,9 @@ void BackgroundRenderer::drawGroundReceivers(SceneRenderer& renderer) I = B / (atten[0] + d * (atten[1] + d * atten[2])); I *= pos[2] / d; color[3] = I; - glColor4fv(color); + glColor(color); for (j = 0; j <= receiverSlices; j++) - { - glVertex2f(receiverRingSize * angle[j][0], - receiverRingSize * angle[j][1]); - } + glVertex(receiverRingSize * angle[j]); } glEnd(); triangleCount += receiverSlices; @@ -1425,11 +1390,11 @@ void BackgroundRenderer::drawGroundReceivers(SceneRenderer& renderer) for (j = 0; j <= receiverSlices; j++) { color[3] = innerAlpha; - glColor4fv(color); - glVertex2f(angle[j][0] * innerSize, angle[j][1] * innerSize); + glColor(color); + glVertex(angle[j] * innerSize); color[3] = outerAlpha; - glColor4fv(color); - glVertex2f(angle[j][0] * outerSize, angle[j][1] * outerSize); + glColor(color); + glVertex(angle[j] * outerSize); } } glEnd(); @@ -1440,7 +1405,7 @@ void BackgroundRenderer::drawGroundReceivers(SceneRenderer& renderer) } glPopMatrix(); - glFogfv(GL_FOG_COLOR, fogColor); + glSetFogColor(fogColor); } @@ -1449,7 +1414,7 @@ void BackgroundRenderer::drawAdvancedGroundReceivers(SceneRenderer& renderer) const float minLuminance = 0.02f; static const int receiverSlices = 32; static const float receiverRingSize = 0.5f; // meters - static float angle[receiverSlices + 1][2]; + static glm::vec2 angle[receiverSlices + 1]; static bool init = false; if (!init) @@ -1468,8 +1433,8 @@ void BackgroundRenderer::drawAdvancedGroundReceivers(SceneRenderer& renderer) return; // setup the ground tint - const GLfloat* gndColor = groundColor[styleIndex]; - GLfloat overrideColor[4]; + auto gndColor = groundColor[styleIndex]; + glm::vec4 overrideColor; if (BZDB.isSet("GroundOverideColor") && parseColorString(BZDB.get("GroundOverideColor"), overrideColor)) gndColor = overrideColor; @@ -1488,7 +1453,7 @@ void BackgroundRenderer::drawAdvancedGroundReceivers(SceneRenderer& renderer) advGState.setState(); // setup black fog - float fogColor[4]; + glm::vec4 fogColor; setupBlackFog(fogColor); // lazy way to get texcoords @@ -1514,8 +1479,8 @@ void BackgroundRenderer::drawAdvancedGroundReceivers(SceneRenderer& renderer) continue; // get the light parameters - const GLfloat* pos = light.getPosition(); - const GLfloat* lightColor = light.getColor(); + const auto &pos = light.getPosition(); + const auto &lightColor = light.getColor(); const GLfloat* atten = light.getAttenuation(); // point under light @@ -1523,23 +1488,12 @@ void BackgroundRenderer::drawAdvancedGroundReceivers(SceneRenderer& renderer) float I = 1.0f / (atten[0] + d * (atten[1] + d * atten[2])); // set the main lighting color - float baseColor[3]; - baseColor[0] = gndColor[0] * lightColor[0]; - baseColor[1] = gndColor[1] * lightColor[1]; - baseColor[2] = gndColor[2] * lightColor[2]; + auto baseColor = glm::vec3(gndColor * lightColor); if (invert) // beats me, should just color logic op the static nodes - { - baseColor[0] = 1.0f - baseColor[0]; - baseColor[1] = 1.0f - baseColor[1]; - baseColor[2] = 1.0f - baseColor[2]; - } + baseColor = 1.0f - baseColor; // maximum value - const float maxVal = (baseColor[0] > baseColor[1]) ? - ((baseColor[0] > baseColor[2]) ? - baseColor[0] : baseColor[2]) : - ((baseColor[1] > baseColor[2]) ? - baseColor[1] : baseColor[2]); + const float maxVal = glm::compMax(baseColor); // if I is too attenuated, don't bother drawing anything if ((I * maxVal) < minLuminance) @@ -1549,34 +1503,27 @@ void BackgroundRenderer::drawAdvancedGroundReceivers(SceneRenderer& renderer) glTranslatef(pos[0], pos[1], 0.0f); float innerSize; - float innerColor[3]; + glm::vec3 innerColor; float outerSize; - float outerColor[3]; + glm::vec3 outerColor; // draw ground receiver, computing lighting at each vertex ourselves glBegin(GL_TRIANGLE_FAN); { // center point - innerColor[0] = I * baseColor[0]; - innerColor[1] = I * baseColor[1]; - innerColor[2] = I * baseColor[2]; - glColor3fv(innerColor); + innerColor = I * baseColor; + glColor(innerColor); glVertex2f(0.0f, 0.0f); // inner ring d = hypotf(receiverRingSize, pos[2]); I = 1.0f / (atten[0] + d * (atten[1] + d * atten[2])); I *= pos[2] / d; // diffuse angle factor - outerColor[0] = I * baseColor[0]; - outerColor[1] = I * baseColor[1]; - outerColor[2] = I * baseColor[2]; - glColor3fv(outerColor); + outerColor = I * baseColor; + glColor(outerColor); outerSize = receiverRingSize; for (j = 0; j <= receiverSlices; j++) - { - glVertex2f(outerSize * angle[j][0], - outerSize * angle[j][1]); - } + glVertex(outerSize * angle[j]); } glEnd(); triangleCount += receiverSlices; @@ -1586,7 +1533,7 @@ void BackgroundRenderer::drawAdvancedGroundReceivers(SceneRenderer& renderer) { // inner ring innerSize = outerSize; - memcpy(innerColor, outerColor, sizeof(float[3])); + innerColor = outerColor; // outer ring outerSize = receiverRingSize * GLfloat(i * i); @@ -1598,18 +1545,16 @@ void BackgroundRenderer::drawAdvancedGroundReceivers(SceneRenderer& renderer) I = 0.0f; moreRings = false; // bail after this ring } - outerColor[0] = I * baseColor[0]; - outerColor[1] = I * baseColor[1]; - outerColor[2] = I * baseColor[2]; + outerColor = I * baseColor; glBegin(GL_TRIANGLE_STRIP); { for (j = 0; j <= receiverSlices; j++) { - glColor3fv(innerColor); - glVertex2f(angle[j][0] * innerSize, angle[j][1] * innerSize); - glColor3fv(outerColor); - glVertex2f(angle[j][0] * outerSize, angle[j][1] * outerSize); + glColor(innerColor); + glVertex(angle[j] * innerSize); + glColor(outerColor); + glVertex(angle[j] * outerSize); } } glEnd(); @@ -1626,7 +1571,7 @@ void BackgroundRenderer::drawAdvancedGroundReceivers(SceneRenderer& renderer) glDisable(GL_TEXTURE_GEN_T); } - glFogfv(GL_FOG_COLOR, fogColor); + glSetFogColor(fogColor); } @@ -1740,13 +1685,9 @@ void BackgroundRenderer::doInitDisplayLists() // const GLfloat groundSize = 10.0f * worldSize; - GLfloat groundPlane[4][3]; + glm::vec3 groundPlane[4]; for (i = 0; i < 4; i++) - { - groundPlane[i][0] = groundSize * squareShape[i][0]; - groundPlane[i][1] = groundSize * squareShape[i][1]; - groundPlane[i][2] = 0.0f; - } + groundPlane[i] = glm::vec3(groundSize * squareShape[i], 0.0f); { GLfloat xmin, xmax; @@ -1755,7 +1696,7 @@ void BackgroundRenderer::doInitDisplayLists() GLfloat xtexmin, xtexmax; GLfloat ytexmin, ytexmax; GLfloat xtexdist, ytexdist; - float vec[2]; + glm::vec2 vec; #define GROUND_DIVS (4) //FIXME -- seems to be enough @@ -1814,10 +1755,10 @@ void BackgroundRenderer::doInitDisplayLists() glNewList(simpleGroundList[0], GL_COMPILE); { glBegin(GL_TRIANGLE_STRIP); - glVertex2fv(groundPlane[0]); - glVertex2fv(groundPlane[1]); - glVertex2fv(groundPlane[3]); - glVertex2fv(groundPlane[2]); + glVertex(groundPlane[0]); + glVertex(groundPlane[1]); + glVertex(groundPlane[3]); + glVertex(groundPlane[2]); glEnd(); } glEndList(); @@ -1832,13 +1773,12 @@ void BackgroundRenderer::doInitDisplayLists() if (cloudsAvailable) { // make vertices for cloud polygons - GLfloat cloudsOuter[4][3], cloudsInner[4][3]; + glm::vec3 cloudsOuter[4], cloudsInner[4]; const GLfloat uvScale = 0.25f; for (i = 0; i < 4; i++) { - cloudsOuter[i][0] = groundPlane[i][0]; - cloudsOuter[i][1] = groundPlane[i][1]; - cloudsOuter[i][2] = groundPlane[i][2] + 120.0f * BZDBCache::tankHeight; + cloudsOuter[i] = groundPlane[i]; + cloudsOuter[i].z = 120.0f * BZDBCache::tankHeight; cloudsInner[i][0] = uvScale * cloudsOuter[i][0]; cloudsInner[i][1] = uvScale * cloudsOuter[i][1]; cloudsInner[i][2] = cloudsOuter[i][2]; @@ -1851,66 +1791,52 @@ void BackgroundRenderer::doInitDisplayLists() // inner clouds -- full opacity glBegin(GL_TRIANGLE_STRIP); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); - glTexCoord2f(uvScale * cloudRepeats * squareShape[3][0], - uvScale * cloudRepeats * squareShape[3][1]); - glVertex3fv(cloudsInner[3]); - glTexCoord2f(uvScale * cloudRepeats * squareShape[2][0], - uvScale * cloudRepeats * squareShape[2][1]); - glVertex3fv(cloudsInner[2]); - glTexCoord2f(uvScale * cloudRepeats * squareShape[0][0], - uvScale * cloudRepeats * squareShape[0][1]); - glVertex3fv(cloudsInner[0]); - glTexCoord2f(uvScale * cloudRepeats * squareShape[1][0], - uvScale * cloudRepeats * squareShape[1][1]); - glVertex3fv(cloudsInner[1]); + glTexCoord(uvScale * cloudRepeats * squareShape[3]); + glVertex(cloudsInner[3]); + glTexCoord(uvScale * cloudRepeats * squareShape[2]); + glVertex(cloudsInner[2]); + glTexCoord(uvScale * cloudRepeats * squareShape[0]); + glVertex(cloudsInner[0]); + glTexCoord(uvScale * cloudRepeats * squareShape[1]); + glVertex(cloudsInner[1]); glEnd(); // outer clouds -- fade to zero opacity at outer edge glBegin(GL_TRIANGLE_STRIP); glColor4f(1.0f, 1.0f, 1.0f, 0.0f); - glTexCoord2f(cloudRepeats * squareShape[1][0], - cloudRepeats * squareShape[1][1]); - glVertex3fv(cloudsOuter[1]); + glTexCoord(cloudRepeats * squareShape[1]); + glVertex(cloudsOuter[1]); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); - glTexCoord2f(uvScale * cloudRepeats * squareShape[1][0], - uvScale * cloudRepeats * squareShape[1][1]); - glVertex3fv(cloudsInner[1]); + glTexCoord(uvScale * cloudRepeats * squareShape[1]); + glVertex(cloudsInner[1]); glColor4f(1.0f, 1.0f, 1.0f, 0.0f); - glTexCoord2f(cloudRepeats * squareShape[2][0], - cloudRepeats * squareShape[2][1]); - glVertex3fv(cloudsOuter[2]); + glTexCoord(cloudRepeats * squareShape[2]); + glVertex(cloudsOuter[2]); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); - glTexCoord2f(uvScale * cloudRepeats * squareShape[2][0], - uvScale * cloudRepeats * squareShape[2][1]); - glVertex3fv(cloudsInner[2]); + glTexCoord(uvScale * cloudRepeats * squareShape[2]); + glVertex(cloudsInner[2]); glColor4f(1.0f, 1.0f, 1.0f, 0.0f); - glTexCoord2f(cloudRepeats * squareShape[3][0], - cloudRepeats * squareShape[3][1]); - glVertex3fv(cloudsOuter[3]); + glTexCoord(cloudRepeats * squareShape[3]); + glVertex(cloudsOuter[3]); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); - glTexCoord2f(uvScale * cloudRepeats * squareShape[3][0], - uvScale * cloudRepeats * squareShape[3][1]); - glVertex3fv(cloudsInner[3]); + glTexCoord(uvScale * cloudRepeats * squareShape[3]); + glVertex(cloudsInner[3]); glColor4f(1.0f, 1.0f, 1.0f, 0.0f); - glTexCoord2f(cloudRepeats * squareShape[0][0], - cloudRepeats * squareShape[0][1]); - glVertex3fv(cloudsOuter[0]); + glTexCoord(cloudRepeats * squareShape[0]); + glVertex(cloudsOuter[0]); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); - glTexCoord2f(uvScale * cloudRepeats * squareShape[0][0], - uvScale * cloudRepeats * squareShape[0][1]); - glVertex3fv(cloudsInner[0]); + glTexCoord(uvScale * cloudRepeats * squareShape[0]); + glVertex(cloudsInner[0]); glColor4f(1.0f, 1.0f, 1.0f, 0.0f); - glTexCoord2f(cloudRepeats * squareShape[1][0], - cloudRepeats * squareShape[1][1]); - glVertex3fv(cloudsOuter[1]); + glTexCoord(cloudRepeats * squareShape[1]); + glVertex(cloudsOuter[1]); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); - glTexCoord2f(uvScale * cloudRepeats * squareShape[1][0], - uvScale * cloudRepeats * squareShape[1][1]); - glVertex3fv(cloudsInner[1]); + glTexCoord(uvScale * cloudRepeats * squareShape[1]); + glVertex(cloudsInner[1]); glEnd(); } glEndList(); @@ -2004,10 +1930,10 @@ void BackgroundRenderer::initContext(void* self) } -const GLfloat* BackgroundRenderer::getSunDirection() const +const glm::vec3 *BackgroundRenderer::getSunDirection() const { if (areShadowsCast(sunDirection)) - return sunDirection; + return &sunDirection; else return NULL; } diff --git a/src/bzflag/BackgroundRenderer.h b/src/bzflag/BackgroundRenderer.h index 988e1011df..1e0fe7c25c 100644 --- a/src/bzflag/BackgroundRenderer.h +++ b/src/bzflag/BackgroundRenderer.h @@ -50,12 +50,12 @@ class BackgroundRenderer void resize(); - const GLfloat* getSunDirection() const; + const glm::vec3 *getSunDirection() const; void setBlank(bool blank = true); void setInvert(bool invert = true); void setCelestial(const SceneRenderer&, - const float sunDirection[3], - const float moonDirection[3]); + const glm::vec3 &sunDirection, + const glm::vec3 &moonDirection); void addCloudDrift(GLfloat uDrift, GLfloat vDrift); void notifyStyleChange(); @@ -130,15 +130,15 @@ class BackgroundRenderer bool haveSkybox; GLenum skyboxWrapMode; int skyboxTexID[6]; - GLfloat skyboxColor[8][4]; + glm::vec3 skyboxColor[8]; bool doStars; bool doSunset; - GLfloat skyZenithColor[3]; - GLfloat skySunDirColor[3]; - GLfloat skyAntiSunDirColor[3]; - GLfloat skyCrossSunDirColor[3]; - float sunDirection[3]; - float moonDirection[3]; + glm::vec3 skyZenithColor; + glm::vec3 skySunDirColor; + glm::vec3 skyAntiSunDirColor; + glm::vec3 skyCrossSunDirColor; + glm::vec3 sunDirection; + glm::vec3 moonDirection; float sunsetTop; int starGStateIndex; OpenGLGState skyGState; @@ -151,13 +151,13 @@ class BackgroundRenderer GLuint starList; GLuint starXFormList; - static GLfloat skyPyramid[5][3]; + static glm::vec3 skyPyramid[5]; static const GLfloat cloudRepeats; - static GLfloat groundColor[4][4]; - static GLfloat groundColorInv[4][4]; - static const GLfloat defaultGroundColor[4][4]; - static const GLfloat defaultGroundColorInv[4][4]; + static glm::vec4 groundColor[4]; + static glm::vec4 groundColorInv[4]; + static const glm::vec4 defaultGroundColor[4]; + static const glm::vec4 defaultGroundColorInv[4]; int triangleCount; }; diff --git a/src/bzflag/BaseLocalPlayer.cxx b/src/bzflag/BaseLocalPlayer.cxx index 4ad4e1fbd2..dfbdadb766 100644 --- a/src/bzflag/BaseLocalPlayer.cxx +++ b/src/bzflag/BaseLocalPlayer.cxx @@ -24,12 +24,9 @@ BaseLocalPlayer::BaseLocalPlayer(const PlayerId& _id, lastTime(TimeKeeper::getTick()), salt(0) { - lastPosition[0] = 0.0f; - lastPosition[1] = 0.0f; - lastPosition[2] = 0.0f; - bbox[0][0] = bbox[1][0] = 0.0f; - bbox[0][1] = bbox[1][1] = 0.0f; - bbox[0][2] = bbox[1][2] = 0.0f; + lastPosition = glm::vec3(0.0f); + bbox[0] = glm::vec3(0.0f); + bbox[1] = glm::vec3(0.0f); } BaseLocalPlayer::~BaseLocalPlayer() @@ -46,16 +43,14 @@ int BaseLocalPlayer::getSalt() void BaseLocalPlayer::update(float inputDT) { // save last position - const float* oldPosition = getPosition(); + const auto &oldPosition = getPosition(); // update by time step float dt = float(TimeKeeper::getTick() - lastTime); if (dt < MIN_DT_LIMIT) return; - lastPosition[0] = oldPosition[0]; - lastPosition[1] = oldPosition[1]; - lastPosition[2] = oldPosition[2]; + lastPosition = oldPosition; lastTime = TimeKeeper::getTick(); @@ -80,22 +75,20 @@ void BaseLocalPlayer::update(float inputDT) doUpdateMotion(dt); // compute motion's bounding box around center of tank - const float* newVelocity = getVelocity(); - bbox[0][0] = bbox[1][0] = oldPosition[0]; - bbox[0][1] = bbox[1][1] = oldPosition[1]; - bbox[0][2] = bbox[1][2] = oldPosition[2]; - if (newVelocity[0] > 0.0f) - bbox[1][0] += dt * newVelocity[0]; + const auto movement = dt * getVelocity(); + bbox[0] = bbox[1] = oldPosition; + if (movement[0] > 0.0f) + bbox[1][0] += movement[0]; else - bbox[0][0] += dt * newVelocity[0]; - if (newVelocity[1] > 0.0f) - bbox[1][1] += dt * newVelocity[1]; + bbox[0][0] += movement[0]; + if (movement[1] > 0.0f) + bbox[1][1] += movement[1]; else - bbox[0][1] += dt * newVelocity[1]; - if (newVelocity[2] > 0.0f) - bbox[1][2] += dt * newVelocity[2]; + bbox[0][1] += movement[1]; + if (movement[2] > 0.0f) + bbox[1][2] += movement[2]; else - bbox[0][2] += dt * newVelocity[2]; + bbox[0][2] += movement[2]; // expand bounding box to include entire tank float size = BZDBCache::tankRadius; @@ -125,7 +118,7 @@ Ray BaseLocalPlayer::getLastMotion() const return Ray(lastPosition, getVelocity()); } -const float (*BaseLocalPlayer::getLastMotionBBox() const)[3] +const glm::vec3 *BaseLocalPlayer::getLastMotionBBox() const { return bbox; } diff --git a/src/bzflag/BaseLocalPlayer.h b/src/bzflag/BaseLocalPlayer.h index 7200823469..66f868ea7e 100644 --- a/src/bzflag/BaseLocalPlayer.h +++ b/src/bzflag/BaseLocalPlayer.h @@ -33,7 +33,7 @@ class BaseLocalPlayer : public Player void update(float inputDT = -1.0f); Ray getLastMotion() const; - const float (*getLastMotionBBox() const)[3]; + const glm::vec3 *getLastMotionBBox() const; virtual void explodeTank() = 0; virtual bool checkHit(const Player* source, @@ -45,9 +45,9 @@ class BaseLocalPlayer : public Player protected: TimeKeeper lastTime; - float lastPosition[3]; + glm::vec3 lastPosition; // bbox of last motion - float bbox[2][3]; + glm::vec3 bbox[2]; private: int salt; diff --git a/src/bzflag/CommandsImplementation.cxx b/src/bzflag/CommandsImplementation.cxx index 17b9549223..f45ee14779 100644 --- a/src/bzflag/CommandsImplementation.cxx +++ b/src/bzflag/CommandsImplementation.cxx @@ -686,7 +686,7 @@ bool RoamPosCommand::operator() (const char *commandLine) if ((myTank != NULL) && (myTank->getTeam() == ObserverTeam)) { const Roaming::RoamingCamera* camPtr = ROAM.getCamera(); - float fakeVel[3] = { camPtr->theta, camPtr->phi, camPtr->zoom }; + const auto fakeVel = glm::vec3(camPtr->theta, camPtr->phi, camPtr->zoom); myTank->move(camPtr->pos, camPtr->theta); myTank->setVelocity(fakeVel); serverLink->sendPlayerUpdate(myTank); diff --git a/src/bzflag/ControlPanel.cxx b/src/bzflag/ControlPanel.cxx index e097b4e90b..e755d26965 100644 --- a/src/bzflag/ControlPanel.cxx +++ b/src/bzflag/ControlPanel.cxx @@ -10,9 +10,6 @@ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ -/* BZFlag common header */ -#include "common.h" - /* interface header */ #include "ControlPanel.h" @@ -33,6 +30,7 @@ #ifdef _WIN32 # include #endif +#include "OpenGLAPI.h" /* local implementation headers */ #include "SceneRenderer.h" @@ -237,7 +235,7 @@ ControlPanel::ControlPanel(MainWindow& _mainWindow, SceneRenderer& _renderer) : messages[i].clear(); unRead[i] = false; } - teamColor[0] = teamColor[1] = teamColor[2] = (GLfloat)0.0f; + teamColor = glm::vec3(0.0f); maxLines = 30; @@ -294,12 +292,9 @@ void ControlPanel::bzdbCallback(const std::string& UNUSED(name), void* data) return; } -void ControlPanel::setControlColor(const GLfloat *color) +void ControlPanel::setControlColor(const glm::vec3 &color) { - if (color) - memcpy(teamColor, color, 3 * sizeof(float)); - else - memset(teamColor, 0, 3 * sizeof(float)); + teamColor = color; } void ControlPanel::render(SceneRenderer& _renderer) @@ -584,7 +579,7 @@ void ControlPanel::render(SceneRenderer& _renderer) glEnable(GL_BLEND); // nice border - glColor4f(teamColor[0], teamColor[1], teamColor[2],outlineOpacity ); + glColor(teamColor, outlineOpacity); glBegin(GL_LINE_LOOP); { long xpos; diff --git a/src/bzflag/ControlPanel.h b/src/bzflag/ControlPanel.h index ab809c7669..7ae6ea9549 100644 --- a/src/bzflag/ControlPanel.h +++ b/src/bzflag/ControlPanel.h @@ -20,6 +20,7 @@ #include #include #include +#include //common headers #include "bzfgl.h" @@ -55,7 +56,7 @@ class ControlPanel ControlPanel(MainWindow&, SceneRenderer&); ~ControlPanel(); - void setControlColor(const GLfloat *color = NULL); + void setControlColor(const glm::vec3 &color = glm::vec3(0.0f)); void render(SceneRenderer&); void resize(); void invalidate(); @@ -121,7 +122,7 @@ class ControlPanel int messageAreaPixels[4]; std::deque messages[MessageModeCount]; int messageMode; - GLfloat teamColor[3]; + glm::vec3 teamColor; static int messagesOffset; static const int maxScrollPages; int maxLines; diff --git a/src/bzflag/GuidedMissleStrategy.cxx b/src/bzflag/GuidedMissleStrategy.cxx index 39d7b298ec..01c55f3cdf 100644 --- a/src/bzflag/GuidedMissleStrategy.cxx +++ b/src/bzflag/GuidedMissleStrategy.cxx @@ -13,10 +13,15 @@ /* interface header */ #include "GuidedMissleStrategy.h" +// System headers +#define GLM_ENABLE_EXPERIMENTAL +#include + /* common implementation headers */ #include "BZDBCache.h" #include "TextureManager.h" #include "Intersect.h" +#include "OpenGLAPI.h" /* local implementation headers */ #include "LocalPlayer.h" @@ -52,12 +57,8 @@ GuidedMissileStrategy::GuidedMissileStrategy(ShotPath* _path) : // get initial shot info FiringInfo& f = getFiringInfo(_path); f.lifetime *= BZDB.eval(StateDatabase::BZDB_GMADLIFE); - const float* vel = getPath().getVelocity(); - const float d = 1.0f / hypotf(vel[0], hypotf(vel[1], vel[2])); - float dir[3]; - dir[0] = vel[0] * d; - dir[1] = vel[1] * d; - dir[2] = vel[2] * d; + const auto vel = getPath().getVelocity(); + const auto dir = glm::normalize(vel); azimuth = limitAngle(atan2f(dir[1], dir[0])); elevation = limitAngle(atan2f(dir[2], hypotf(dir[1], dir[0]))); @@ -72,21 +73,14 @@ GuidedMissileStrategy::GuidedMissileStrategy(ShotPath* _path) : // setup shot float shotSpeed = BZDB.eval(StateDatabase::BZDB_SHOTSPEED); - f.shot.vel[0] = shotSpeed * dir[0]; - f.shot.vel[1] = shotSpeed * dir[1]; - f.shot.vel[2] = shotSpeed * dir[2]; + f.shot.vel = shotSpeed * dir; // set next position to starting position - nextPos[0] = f.shot.pos[0]; - nextPos[1] = f.shot.pos[1]; - nextPos[2] = f.shot.pos[2]; + nextPos = f.shot.pos; // check that first segment doesn't start inside a building - float startPos[3]; float muzzleFront = BZDB.eval(StateDatabase::BZDB_MUZZLEFRONT); - startPos[0] = f.shot.pos[0] - muzzleFront * dir[0]; - startPos[1] = f.shot.pos[1] - muzzleFront * dir[1]; - startPos[2] = f.shot.pos[2] - muzzleFront * dir[2]; + auto startPos = f.shot.pos - muzzleFront * dir; Ray firstRay = Ray(startPos, dir); prevTime = currentTime; prevTime += -muzzleFront / BZDB.eval(StateDatabase::BZDB_SHOTSPEED); @@ -179,11 +173,8 @@ void GuidedMissileStrategy::update(float dt) { // turn towards target // find desired direction - const float* targetPos = target->getPosition(); - float desiredDir[3]; - desiredDir[0] = targetPos[0] - nextPos[0]; - desiredDir[1] = targetPos[1] - nextPos[1]; - desiredDir[2] = targetPos[2] - nextPos[2]; + const auto &targetPos = target->getPosition(); + auto desiredDir = targetPos - nextPos; desiredDir[2] += target->getMuzzleHeight(); // right between the eyes // compute desired angles @@ -211,10 +202,10 @@ void GuidedMissileStrategy::update(float dt) else elevation = limitAngle(elevation - dt * gmissileAng); } - float newDirection[3]; - newDirection[0] = cosf(azimuth) * cosf(elevation); - newDirection[1] = sinf(azimuth) * cosf(elevation); - newDirection[2] = sinf(elevation); + auto newDirection = glm::vec3( + cosf(azimuth) * cosf(elevation), + sinf(azimuth) * cosf(elevation), + sinf(elevation)); Ray ray = Ray(nextPos, newDirection); renderTimes++; @@ -267,9 +258,7 @@ void GuidedMissileStrategy::update(float dt) segments.pop_back(); // update shot - newDirection[0] *= shotSpeed; - newDirection[1] *= shotSpeed; - newDirection[2] *= shotSpeed; + newDirection *= shotSpeed; setPosition(nextPos); setVelocity(newDirection); } @@ -294,14 +283,14 @@ float GuidedMissileStrategy::checkBuildings(const Ray& ray) const Teleporter* outTeleporter = World::getWorld()->getTeleporter(target, outFace); teleporter->getPointWRT(*outTeleporter, face, outFace, - nextPos, NULL, azimuth, nextPos, NULL, &azimuth); + nextPos, NULL, &azimuth); return t / shotSpeed; } else if (building) { // expire on next update setExpiring(); - float pos[3]; + glm::vec3 pos; ray.getPoint(t / shotSpeed, pos); addShotExplosion(pos); return t / shotSpeed; @@ -309,7 +298,8 @@ float GuidedMissileStrategy::checkBuildings(const Ray& ray) return -1.0f; } -float GuidedMissileStrategy::checkHit(const BaseLocalPlayer* tank, float position[3]) const +float GuidedMissileStrategy::checkHit( + const BaseLocalPlayer* tank, glm::vec3 &position) const { float minTime = Infinity; if (getPath().isExpired()) return minTime; @@ -329,10 +319,8 @@ float GuidedMissileStrategy::checkHit(const BaseLocalPlayer* tank, float positio // half a tank height. const float tankHeight = tank->getDimensions()[2]; Ray tankLastMotionRaw = tank->getLastMotion(); - float lastTankPositionRaw[3]; - lastTankPositionRaw[0] = tankLastMotionRaw.getOrigin()[0]; - lastTankPositionRaw[1] = tankLastMotionRaw.getOrigin()[1]; - lastTankPositionRaw[2] = tankLastMotionRaw.getOrigin()[2] + 0.5f * tankHeight; + auto lastTankPositionRaw = tankLastMotionRaw.getOrigin(); + lastTankPositionRaw.z += 0.5f * tankHeight; Ray tankLastMotion(lastTankPositionRaw, tankLastMotionRaw.getDirection()); // check each segment @@ -346,12 +334,9 @@ float GuidedMissileStrategy::checkHit(const BaseLocalPlayer* tank, float positio const Ray& ray = segments[i].ray; // construct ray with correct velocity - float speed[3]; - const float* dir = ray.getDirection(); + const auto &dir = ray.getDirection(); float shotSpeed = BZDB.eval(StateDatabase::BZDB_SHOTSPEED); - speed[0] = shotSpeed * dir[0]; - speed[1] = shotSpeed * dir[1]; - speed[2] = shotSpeed * dir[2]; + auto speed = shotSpeed * dir; Ray speedRay(ray.getOrigin(), speed); // construct relative shot ray: origin and velocity relative to @@ -364,7 +349,7 @@ float GuidedMissileStrategy::checkHit(const BaseLocalPlayer* tank, float positio { // find closest approach to narrow box around tank. width of box // is shell radius so you can actually hit narrow tank head on. - static float tankBase[3] = { 0.0f, 0.0f, -0.5f * tankHeight }; + static auto tankBase = glm::vec3(0.0f, 0.0f, -0.5f * tankHeight); t = timeRayHitsBlock(relativeRay, tankBase, tank->getAngle(), 0.5f * BZDBCache::tankLength, shotRadius, tankHeight); } @@ -380,23 +365,19 @@ float GuidedMissileStrategy::checkHit(const BaseLocalPlayer* tank, float positio continue; // check if shot hits tank -- get position at time t, see if in radius - float closestPos[3]; + glm::vec3 closestPos; relativeRay.getPoint(t, closestPos); - if (closestPos[0] * closestPos[0] + - closestPos[1] * closestPos[1] + - closestPos[2] * closestPos[2] < radius2) + if (glm::length2(closestPos) < radius2) { // save best time so far minTime = t; // compute location of tank at time of hit - float tankPos[3]; + glm::vec3 tankPos; tank->getLastMotion().getPoint(t, tankPos); // compute position of intersection - position[0] = tankPos[0] + closestPos[0]; - position[1] = tankPos[1] + closestPos[1]; - position[2] = tankPos[2] + closestPos[2]; + position = tankPos + closestPos; } } @@ -432,18 +413,12 @@ void GuidedMissileStrategy::readUpdate(uint16_t code, const void* msg) nboUnpackUByte(msg, lastTarget); // fix up dependent variables - const float* vel = getPath().getVelocity(); - const float d = 1.0f / hypotf(vel[0], hypotf(vel[1], vel[2])); - float dir[3]; - dir[0] = vel[0] * d; - dir[1] = vel[1] * d; - dir[2] = vel[2] * d; + const auto vel = getPath().getVelocity(); + auto dir = glm::normalize(vel); azimuth = limitAngle(atan2f(dir[1], dir[0])); elevation = limitAngle(atan2f(dir[2], hypotf(dir[1], dir[0]))); - const float* pos = getPath().getPosition(); - nextPos[0] = pos[0]; - nextPos[1] = pos[1]; - nextPos[2] = pos[2]; + const auto pos = getPath().getPosition(); + nextPos = pos; // note that we do not call update(float). let that happen on the // next time step. @@ -467,7 +442,7 @@ void GuidedMissileStrategy::expire() void GuidedMissileStrategy::radarRender() const { - const float *orig = getPath().getPosition(); + const auto &orig = getPath().getPosition(); const int length = (int)BZDBCache::linedRadarShots; const int size = (int)BZDBCache::sizedRadarShots; @@ -475,14 +450,10 @@ void GuidedMissileStrategy::radarRender() const // Display leading lines if (length > 0) { - const float* vel = getPath().getVelocity(); - const float d = 1.0f / hypotf(vel[0], hypotf(vel[1], vel[2])); - float dir[3]; - dir[0] = vel[0] * d * shotTailLength * length; - dir[1] = vel[1] * d * shotTailLength * length; - dir[2] = vel[2] * d * shotTailLength * length; + const auto vel = getPath().getVelocity(); + const auto dir = glm::normalize(vel) * shotTailLength * float(length); glBegin(GL_LINES); - glVertex2fv(orig); + glVertex(orig); if (BZDBCache::leadingShotLine == 1) //leading { glVertex2f(orig[0] + dir[0], orig[1] + dir[1]); @@ -498,7 +469,7 @@ void GuidedMissileStrategy::radarRender() const glVertex2f(orig[0] + dir[0], orig[1] + dir[1]); glEnd(); glBegin(GL_LINES); - glVertex2fv(orig); + glVertex(orig); glVertex2f(orig[0] - dir[0], orig[1] - dir[1]); glEnd(); } @@ -521,7 +492,7 @@ void GuidedMissileStrategy::radarRender() const // draw a sized missle glPointSize((float)size); glBegin(GL_POINTS); - glVertex2fv(orig); + glVertex(orig); glEnd(); glPointSize(1.0f); } @@ -529,7 +500,7 @@ void GuidedMissileStrategy::radarRender() const { // draw the tiny missle glBegin(GL_POINTS); - glVertex2fv(orig); + glVertex(orig); glEnd(); } } diff --git a/src/bzflag/GuidedMissleStrategy.h b/src/bzflag/GuidedMissleStrategy.h index 5a3c3124d0..f82dd403ea 100644 --- a/src/bzflag/GuidedMissleStrategy.h +++ b/src/bzflag/GuidedMissleStrategy.h @@ -18,6 +18,7 @@ /* system interface headers */ #include +#include /* common interface headers */ #include "SceneDatabase.h" @@ -36,7 +37,7 @@ class GuidedMissileStrategy : public ShotStrategy ~GuidedMissileStrategy(); void update(float dt); - float checkHit(const BaseLocalPlayer*, float[3]) const; + float checkHit(const BaseLocalPlayer*, glm::vec3 &) const; void sendUpdate(const FiringInfo&) const; void readUpdate(uint16_t, const void*); void addShot(SceneDatabase*, bool colorblind); @@ -53,7 +54,7 @@ class GuidedMissileStrategy : public ShotStrategy int renderTimes; float azimuth; float elevation; - float nextPos[3]; + glm::vec3 nextPos; BoltSceneNode* ptSceneNode; float puffTime,rootPuff; diff --git a/src/bzflag/HUDRenderer.cxx b/src/bzflag/HUDRenderer.cxx index de2a0bd5e0..39af75f8f0 100644 --- a/src/bzflag/HUDRenderer.cxx +++ b/src/bzflag/HUDRenderer.cxx @@ -15,12 +15,16 @@ // system headers #include +#define GLM_ENABLE_EXPERIMENTAL +#include +#include /* common implementation headers */ #include "BundleMgr.h" #include "Bundle.h" #include "FontManager.h" #include "BZDBCache.h" +#include "OpenGLAPI.h" /* local implementation headers */ #include "LocalPlayer.h" @@ -38,7 +42,6 @@ // headingOffset: the number of degrees from the center of the heading // strip display to either side. altitudeOffset is similar. const float HUDRenderer::altitudeOffset = 20.0f; -const GLfloat HUDRenderer::black[3] = { 0.0f, 0.0f, 0.0f }; std::string HUDRenderer::headingLabel[36]; std::string HUDRenderer::restartLabelFormat("Press %s to start"); std::string HUDRenderer::resumeLabel("Press Pause to resume"); @@ -46,10 +49,10 @@ std::string HUDRenderer::autoPilotLabel("AutoPilot on"); std::string HUDRenderer::cancelDestructLabel("Press Destruct to cancel"); std::string HUDRenderer::gameOverLabel("GAME OVER"); -static const GLfloat whiteColor[3] = { 1.0f, 1.0f, 1.0f }; -static const GLfloat redColor[3] = { 1.0f, 0.0f, 0.0f }; -static const GLfloat yellowColor[3] = { 1.0f, 1.0f, 0.0f }; -static const GLfloat greenColor[3] = { 0.0f, 1.0f, 0.0f }; +static const auto whiteColor = glm::vec3(1.0f, 1.0f, 1.0f); +static const auto redColor = glm::vec3(1.0f, 0.0f, 0.0f); +static const auto yellowColor = glm::vec3(1.0f, 1.0f, 0.0f); +static const auto greenColor = glm::vec3(0.0f, 1.0f, 0.0f); HUDRenderer::HUDRenderer(const BzfDisplay* _display, const SceneRenderer& renderer) : @@ -82,15 +85,9 @@ HUDRenderer::HUDRenderer(const BzfDisplay* _display, dater = true; // initialize colors - hudColor[0] = 1.0f; - hudColor[1] = 0.625f; - hudColor[2] = 0.125f; - messageColor[0] = 1.0f; - messageColor[1] = 1.0f; - messageColor[2] = 1.0f; - warningColor[0] = 1.0f; - warningColor[1] = 0.0f; - warningColor[2] = 0.0f; + hudColor = glm::vec3(1.0f, 0.625f, 0.125f); + messageColor = glm::vec3(1.0f); + warningColor = glm::vec3(1.0f, 0.0f, 0.0f); // make sure we're notified when MainWindow resizes window.getWindow()->addResizeCallback(resizeCallback, this); @@ -306,9 +303,7 @@ void HUDRenderer::setLabelsFontSize(int, int height) void HUDRenderer::setColor(float r, float g, float b) { - hudColor[0] = r; - hudColor[1] = g; - hudColor[2] = b; + hudColor = glm::vec3(r, g, b); } void HUDRenderer::setPlaying(bool _playing) @@ -497,10 +492,8 @@ void HUDRenderer::initCracks() { const float d = 0.90f * float(maxMotionSize) * ((float)bzfrand() + 0.90f); const float a = (float)(2.0 * M_PI * (double(i) + bzfrand()) / double(HUDNumCracks)); - cracks[i][0][0] = 0.0f; - cracks[i][0][1] = 0.0f; - cracks[i][1][0] = d * cosf(a); - cracks[i][1][1] = d * sinf(a); + cracks[i][0] = glm::vec3(0.0f); + cracks[i][1] = d * glm::vec3(cosf(a), sinf(a), 0.0f); makeCrack(cracks, i, 1, a); } } @@ -515,7 +508,7 @@ void HUDRenderer::setCracks(bool _showCracks) showCracks = _showCracks; } -void HUDRenderer::addMarker(float _heading, const float *_color ) +void HUDRenderer::addMarker(float _heading, const glm::vec3 &_color) { markers.resize(markers.size() + 1); HUDMarker &m = markers[markers.size() - 1]; @@ -524,13 +517,14 @@ void HUDRenderer::addMarker(float _heading, const float *_color ) while (_heading < 0.0f) _heading += 360.0f; while (_heading >= 360.0f) _heading -= 360.0f; m.heading = _heading; - memcpy(m.color, _color, sizeof(m.color)); + m.color = _color; } -void HUDRenderer::AddEnhancedNamedMarker(const fvec3& pos, const fvec3& color, - std::string name, bool friendly, - float zShift) +void HUDRenderer::AddEnhancedNamedMarker( + const glm::vec3 &pos, const glm::vec3 &color, + std::string name, bool friendly, + float zShift) { return; @@ -541,8 +535,10 @@ void HUDRenderer::AddEnhancedNamedMarker(const fvec3& pos, const fvec3& color, enhancedMarkers.push_back(newMarker); } -void HUDRenderer::AddEnhancedMarker(const fvec3& pos, const fvec3& color, - bool friendly, float zShift ) +void HUDRenderer::AddEnhancedMarker( + const glm::vec3 &pos, const glm::vec3 &color, + bool friendly, + float zShift) { EnhancedHUDMarker newMarker(pos, color); newMarker.pos.z += zShift; @@ -550,10 +546,10 @@ void HUDRenderer::AddEnhancedMarker(const fvec3& pos, const fvec3& color, enhancedMarkers.push_back(newMarker); } -void HUDRenderer::AddLockOnMarker(const fvec3& pos, std::string name, +void HUDRenderer::AddLockOnMarker(const glm::vec3 &pos, std::string name, bool friendly, float zShift ) { - const fvec3 color(0.75f, 0.125f, 0.125f); + const auto color = glm::vec3(0.75f, 0.125f, 0.125f); EnhancedHUDMarker newMarker(pos, color); newMarker.pos.z += zShift; newMarker.name = name; @@ -641,33 +637,32 @@ std::string HUDRenderer::makeHelpString(const char* help) const return msg; } -void HUDRenderer::makeCrack(float crackpattern[HUDNumCracks][(1 << HUDCrackLevels) + 1][2], int n, int l, - float a) +void HUDRenderer::makeCrack(glm::vec3 crackpattern[HUDNumCracks][(1 << HUDCrackLevels) + 1], int n, int l, + float a) { if (l >= (1 << (HUDCrackLevels - 1))) return; float d = 0.5f * float(maxMotionSize) * ((float)bzfrand() + 0.5f) * powf(0.5f, 0.69f * logf(float(l))); float newAngle = (float)(a + M_PI * bzfrand() / double(HUDNumCracks)); - crackpattern[n][2*l][0] = crackpattern[n][l][0] + d * cosf(newAngle); - crackpattern[n][2*l][1] = crackpattern[n][l][1] + d * sinf(newAngle); + crackpattern[n][2 * l] = crackpattern[n][l] + + d * glm::vec3(cosf(newAngle), sinf(newAngle), 0.0f); makeCrack(crackpattern, n, 2*l, newAngle); d = 0.5f * float(maxMotionSize) * ((float)bzfrand() + 0.5f) * powf(0.5f, 0.69f * logf(float(l))); newAngle = (float)(a - M_PI * bzfrand() / double(HUDNumCracks)); - crackpattern[n][2*l+1][0] = crackpattern[n][l][0] + d * cosf(newAngle); - crackpattern[n][2*l+1][1] = crackpattern[n][l][1] + d * sinf(newAngle); + crackpattern[n][2 * l + 1] = crackpattern[n][l] + + d * glm::vec3(cosf(newAngle), sinf(newAngle), 0.0f); makeCrack(crackpattern, n, 2*l+1, newAngle); } static const float dimFactor = 0.2f; - -void HUDRenderer::hudColor3Afv(const float * c, const float a) +void HUDRenderer::hudColor3Afv(const glm::vec3 &c, const float a) { if ( dim ) - glColor4f( dimFactor *c[0], dimFactor *c[1], dimFactor *c[2], a ); + glColor(dimFactor * c, a); else - glColor4f( c[0],c[1],c[2],a ); + glColor(c, a); } void HUDRenderer::drawGeometry() @@ -873,16 +868,14 @@ void HUDRenderer::renderStatus(void) Player *target = ROAM.getTargetTank(); if (target) { - float vel[3] = {0}; - memcpy(vel,target->getVelocity(),sizeof(float)*3); + const auto &vel = target->getVelocity(); - float apparentVel[3] = {0}; - memcpy(apparentVel,target->getApparentVelocity(),sizeof(float)*3); + auto apparentVel = target->getApparentVelocity(); - float linSpeed = sqrt(vel[0]*vel[0]+vel[1]*vel[1]); + float linSpeed = glm::length(glm::vec2(vel)); float vertSpeed = vel[2]; float rotSpeed = fabs(target->getAngularVelocity()); - float apparentLinSpeed = sqrt(apparentVel[0]*apparentVel[0]+apparentVel[1]*apparentVel[1]); + float apparentLinSpeed = glm::length(glm::vec2(apparentVel)); // calc maximum apparent velocity value for each 0.5s interval static float maxApparentLinSpeed = 0.0f; @@ -964,7 +957,7 @@ void HUDRenderer::renderStatus(void) // print status top-center - const GLfloat* statusColor = warningColor; + auto statusColor = warningColor; std::string msg; // TODO: the upper 4 values of timeLeft (~0u-3 to ~0u) // are reserved for future use as timer flags (e.g. paused) @@ -1041,19 +1034,13 @@ void HUDRenderer::renderTankLabels(SceneRenderer& renderer) int offset = window.getViewHeight() - window.getHeight(); - GLint view[] = {window.getOriginX(), window.getOriginY(), + auto view = glm::ivec4( + window.getOriginX(), window.getOriginY(), window.getWidth(), window.getHeight() - }; - const GLfloat *projf = renderer.getViewFrustum().getProjectionMatrix(); - const GLfloat *modelf = renderer.getViewFrustum().getViewMatrix(); + ); - // convert to doubles - GLdouble proj[16], model[16]; - for (int j = 0; j < 16; j++) - { - proj[j] = projf[j]; - model[j] = modelf[j]; - } + const auto proj = renderer.getViewFrustum().getProjectionMatrix(); + const auto model = renderer.getViewFrustum().getViewMatrix(); for (int i = 0; i < curMaxPlayers; i++) { @@ -1063,8 +1050,10 @@ void HUDRenderer::renderTankLabels(SceneRenderer& renderer) const std::string name = pl->getCallSign(); double x, y, z; hudColor3Afv(Team::getRadarColor(pl->getTeam()), 1.0f); - gluProject(pl->getPosition()[0], pl->getPosition()[1], - pl->getPosition()[2]/*+BZDB.eval(StateDatabase::BZDB_MUZZLEHEIGHT)*3.0f*/, model, proj, view, &x, &y, &z); + auto p = glm::project(pl->getPosition(), model, proj, view); + x = p.x; + y = p.y; + z = p.z; if (z >= 0.0 && z <= 1.0) { FontManager &fm = FontManager::instance(); @@ -1085,9 +1074,8 @@ void HUDRenderer::renderTankLabels(SceneRenderer& renderer) if (roaming && BZDB.isTrue("showVelocities")) { - float vel[3] = {0}; - memcpy(vel,pl->getVelocity(),sizeof(float)*3); - std::string speedStr = TextUtils::format("[%5.2f]",sqrt(vel[0]*vel[0]+vel[1]*vel[1])); + const auto vel = pl->getVelocity(); + std::string speedStr = TextUtils::format("[%5.2f]", glm::length(glm::vec2(vel))); fm.drawString(float(x) - fm.getStrLength(labelsFontFace, labelsFontSize, speedStr.c_str()) / 2.0f, float(y) + offset - (3.0f * fm.getStrHeight(labelsFontFace, labelsFontSize, speedStr.c_str())), @@ -1113,17 +1101,17 @@ void HUDRenderer::renderCracks() glBegin(GL_LINES); for (int i = 0; i < HUDNumCracks; i++) { - glVertex2fv(cracks[i][0]); - glVertex2fv(cracks[i][1]); + glVertex(cracks[i][0]); + glVertex(cracks[i][1]); for (int j = 0; j < maxLevels-1; j++) { const int num = 1 << j; for (int k = 0; k < num; k++) { - glVertex2fv(cracks[i][num + k]); - glVertex2fv(cracks[i][2 * (num + k)]); - glVertex2fv(cracks[i][num + k]); - glVertex2fv(cracks[i][2 * (num + k) + 1]); + glVertex(cracks[i][num + k]); + glVertex(cracks[i][2 * (num + k)]); + glVertex(cracks[i][num + k]); + glVertex(cracks[i][2 * (num + k) + 1]); } } } @@ -1181,72 +1169,29 @@ void HUDRenderer::renderTimes(void) } } -void HUDRenderer::saveMatrixes(const float *mm, const float *pm ) +void HUDRenderer::saveMatrixes(const glm::mat4 &mm, const glm::mat4 &pm) { // ssave off the stuff before we reset it - for (int i = 0; i < 16; i++) - { - modelMatrix[i] = mm[i]; - projMatrix[i] = pm[i]; - } - glGetIntegerv(GL_VIEWPORT,(GLint*)viewport); + modelMatrix = mm; + projMatrix = pm; + viewport = glGetViewport(); } -void HUDRenderer::drawWaypointMarker(float* color, float alpha, float* object, - const float* viewPos, std::string name, - bool friendly) +void HUDRenderer::drawWaypointMarker(const EnhancedHUDMarker &marker, + const glm::vec2 &viewPos) { - double map[3] = {0,0,0}; - double o[3]; - o[0] = object[0]; - o[1] = object[1]; - o[2] = object[2]; + const auto &color = marker.color; + const float alpha = 0.45f; + const auto &pos = marker.pos; + const auto &name = marker.name; + const bool friendly = marker.friendly; + const auto map = getMarkerCoordinate(pos, viewPos); + float halfWidth = window.getWidth() * 0.5f; + float halfHeight = window.getHeight() * 0.5f; hudColor3Afv( color, alpha ); - gluProject(o[0], o[1], o[2], modelMatrix, projMatrix, - (GLint*)viewport, &map[0], &map[1], &map[2]); - - float halfWidth = window.getWidth() * 0.5f; - float halfHeight = window.getHeight() * 0.5f; - - // comp us back to the view - map[0] -= halfWidth; - map[1] -= halfHeight; - - const fvec2 headingVec(sinf(heading * DEG2RADf), - cosf(heading * DEG2RADf)); - - const fvec2 toPosVec((float)object[0] - viewPos[0], - (float)object[1] - viewPos[1]); - - if (fvec2::dot(toPosVec, headingVec) <= 1.0f /*0.866f*/) - { - if (NEAR_ZERO(map[0], ZERO_TOLERANCE)) - { - map[0] = -halfWidth; - map[1] = 0; - } - else - { - map[0] = -halfWidth * (fabs(map[0])/map[0]); - map[1] = 0; - } - } - else - { - if (map[0] < -halfWidth) - map[0] = -halfWidth; - if (map[0] > halfWidth) - map[0] = halfWidth; - - if (map[1] < -halfHeight) - map[1] = -halfHeight; - if (map[1] > halfHeight) - map[1] = halfHeight; - } - glPushMatrix(); glTranslatef((float)map[0],(float)map[1],0); glPushMatrix(); @@ -1311,60 +1256,18 @@ void HUDRenderer::drawWaypointMarker(float* color, float alpha, float* object, // HUDRenderer::drawLockonMarker //------------------------------------------------------------------------- -void HUDRenderer::drawLockonMarker(float* color, float alpha, float* object, - const float *viewPos, std::string name, - bool friendly) +void HUDRenderer::drawLockonMarker(const EnhancedHUDMarker &marker, + const glm::vec2 &viewPos) { - double map[3] = {0,0,0}; - double o[3]; - o[0] = object[0]; - o[1] = object[1]; - o[2] = object[2]; + const auto &color = marker.color; + const float alpha = 0.45f; + const auto &pos = marker.pos; + const auto &name = marker.name; + const bool friendly = marker.friendly; + const auto map = getMarkerCoordinate(pos, viewPos); hudColor3Afv( color, alpha ); - gluProject(o[0], o[1], o[2], modelMatrix,projMatrix, - (GLint*)viewport, &map[0], &map[1], &map[2]); - - float halfWidth = window.getWidth() * 0.5f; - float halfHeight = window.getHeight() * 0.5f; - - // comp us back to the view - map[0] -= halfWidth; - map[1] -= halfHeight; - - const fvec2 headingVec(sinf(heading * DEG2RADf), - cosf(heading * DEG2RADf)); - - const fvec2 toPosVec((float)object[0] - viewPos[0], - (float)object[1] - viewPos[1]); - - if (fvec2::dot(toPosVec, headingVec) <= 1.0f) - { - if (NEAR_ZERO(map[0], ZERO_TOLERANCE)) - { - map[0] = -halfWidth; - map[1] = 0; - } - else - { - map[0] = -halfWidth * (fabs(map[0])/map[0]); - map[1] = 0; - } - } - else - { - if ( map[0] < -halfWidth ) - map[0] = -halfWidth; - if ( map[0] > halfWidth ) - map[0] = halfWidth; - - if ( map[1] < -halfHeight ) - map[1] = -halfHeight; - if ( map[1] > halfHeight ) - map[1] = halfHeight; - } - glPushMatrix(); glTranslatef((float)map[0],(float)map[1],0); glPushMatrix(); @@ -1410,6 +1313,43 @@ void HUDRenderer::drawLockonMarker(float* color, float alpha, float* object, glPopMatrix(); } +glm::vec2 HUDRenderer::getMarkerCoordinate( + const glm::vec3 &pos, + const glm::vec2 &viewPos) +{ + const float headingR = glm::radians(heading); + float halfWidth = window.getWidth() * 0.5f; + float halfHeight = window.getHeight() * 0.5f; + const auto halfLimit = glm::vec2(halfWidth, halfHeight); + const auto headingVec = glm::vec2(sinf(headingR), cosf(headingR)); + const auto toPosVec = glm::vec2(pos) - viewPos; + + glm::vec3 map; + + if (glm::length2(toPosVec) < 1.0E-6) + map = glm::vec3(halfWidth, 0, 0); + else + map = glm::project(pos, modelMatrix, projMatrix, viewport); + + + // comp us back to the view + if (glm::dot(toPosVec, headingVec) <= 1.0f) + { + if (map[0] < halfWidth) + map[0] = halfWidth; + else + map[0] = -halfWidth; + map[1] = 0; + return glm::vec2(map[0], map[1]); + } + + auto result = glm::vec2(map[0], map[1]) - halfLimit; + + result = glm::clamp(result, -halfLimit, +halfLimit); + + return result; +} + void HUDRenderer::renderBox(SceneRenderer&) { // get view metrics @@ -1666,23 +1606,17 @@ void HUDRenderer::drawMarkersInView( int centerx, int centery, const LocalPlayer glTranslatef((float)centerx,(float)centery,0); glLineWidth(2.0f); + auto viewPos = glm::vec2(myTank->getPosition()); + // draw any waypoint markers - for (int i = 0; i < (int)enhancedMarkers.size(); i++) - { - drawWaypointMarker(enhancedMarkers[i].color, 0.45f, - enhancedMarkers[i].pos, myTank->getPosition(), - enhancedMarkers[i].name, enhancedMarkers[i].friendly); - } + for (const auto &marker : enhancedMarkers) + drawWaypointMarker(marker, viewPos); enhancedMarkers.clear(); // draw any lockon markers - for (int i = 0; i < (int)lockOnMarkers.size(); i++) - { - drawLockonMarker(lockOnMarkers[i].color, 0.45f, - lockOnMarkers[i]. pos,myTank->getPosition(), - lockOnMarkers[i].name, lockOnMarkers[i].friendly); - } + for (const auto &marker : lockOnMarkers) + drawLockonMarker(marker, viewPos); lockOnMarkers.clear(); diff --git a/src/bzflag/HUDRenderer.h b/src/bzflag/HUDRenderer.h index 49193dc385..3447a21927 100644 --- a/src/bzflag/HUDRenderer.h +++ b/src/bzflag/HUDRenderer.h @@ -18,6 +18,10 @@ /* system interface headers */ #include #include +#include +#include +#include +#include /* common interface headers */ #include "TimeKeeper.h" @@ -44,7 +48,7 @@ class HUDMarker { public: float heading; - GLfloat color[3]; + glm::vec3 color; }; typedef std::vector MarkerList; @@ -57,13 +61,13 @@ class EnhancedHUDMarker , color(0.0f, 0.0f, 0.0f) , friendly(false) {} - EnhancedHUDMarker(const fvec3& p, const fvec3& c) + EnhancedHUDMarker(const glm::vec3 &p, const glm::vec3 &c) : pos(p) , color(c) , friendly(false) {} - fvec3 pos; - fvec3 color; + glm::vec3 pos; + glm::vec3 color; std::string name; bool friendly; }; @@ -102,18 +106,18 @@ class HUDRenderer void setFlagHelp(FlagType* desc, float duration); void initCracks(); void setCracks(bool showCracks); - void addMarker(float heading, const float *color); + void addMarker(float heading, const glm::vec3 &color); void setRestartKeyLabel(const std::string&); void setTimeLeft(uint32_t timeLeftInSeconds); - void AddEnhancedMarker(const fvec3& pos, const fvec3& color, + void AddEnhancedMarker(const glm::vec3 &pos, const glm::vec3 &color, bool friendly = false, float zShift = 0.0f); - void AddEnhancedNamedMarker(const fvec3& pos, const fvec3& color, std::string name, + void AddEnhancedNamedMarker(const glm::vec3 &pos, const glm::vec3 &color, std::string name, bool friendly = false, float zShift = 0.0f); - void AddLockOnMarker(const fvec3& pos, std::string name, + void AddLockOnMarker(const glm::vec3 &pos, std::string name, bool friendly = false, float zShift = 0.0f); - void saveMatrixes(const float* mm, const float* pm); + void saveMatrixes(const glm::mat4 &mm, const glm::mat4 &pm); void setDim(bool); bool getComposing() const; @@ -128,7 +132,7 @@ class HUDRenderer ScoreboardRenderer *getScoreboard(); protected: - void hudColor3Afv(const float*, const float); + void hudColor3Afv(const glm::vec3 &, const float); void renderAlerts(void); void renderStatus(void); void renderCracks(); @@ -142,13 +146,13 @@ class HUDRenderer void renderTimes(void); void renderShots(const Player*); - void drawLockonMarker(float* color, float alpha, float* object, const float* viewPos, std::string name, - bool friendly); - void drawWaypointMarker(float* color, float alpha, float* object, const float* viewPos, std::string name, - bool friendly); + void drawLockonMarker(const EnhancedHUDMarker &marker, + const glm::vec2 &viewPos); + void drawWaypointMarker(const EnhancedHUDMarker &marker, + const glm::vec2 &viewPos); void drawMarkersInView(int centerX, int centerY, const LocalPlayer* myTank); - void makeCrack(float crackpattern[HUDNumCracks][(1 << HUDCrackLevels) + 1][2], int n, int l, float a); + void makeCrack(glm::vec3 crackpattern[HUDNumCracks][(1 << HUDCrackLevels) + 1], int n, int l, float a); std::string makeHelpString(const char* help) const; private: @@ -161,6 +165,8 @@ class HUDRenderer void setLabelsFontSize(int width, int height); void setOneToOnePrj(); void coverWhenBurrowed(const LocalPlayer &myTank); + glm::vec2 getMarkerCoordinate(const glm::vec3 &pos, + const glm::vec2 &viewPos); void resize(bool firstTime); static void resizeCallback(void*); @@ -172,9 +178,9 @@ class HUDRenderer int noMotionSize; int maxMotionSize; float headingOffset; - GLfloat hudColor[3]; - GLfloat messageColor[3]; - GLfloat warningColor[3]; + glm::vec3 hudColor; + glm::vec3 messageColor; + glm::vec3 warningColor; int bigFontFace; float bigFontSize; @@ -230,7 +236,7 @@ class HUDRenderer FlashClock alertClock[MaxAlerts]; std::string alertLabel[MaxAlerts]; float alertLabelWidth[MaxAlerts]; - const GLfloat* alertColor[MaxAlerts]; + glm::vec3 alertColor[MaxAlerts]; float flagHelpY; FlashClock flagHelpClock; @@ -240,22 +246,21 @@ class HUDRenderer bool showOptions; bool showCompose; - GLfloat cracks[HUDNumCracks][(1 << HUDCrackLevels) + 1][2]; + glm::vec3 cracks[HUDNumCracks][(1 << HUDCrackLevels) + 1]; TimeKeeper crackStartTime; bool showCracks; HUDuiTypeIn* composeTypeIn; - double modelMatrix[16]; - double projMatrix[16]; - int viewport[4]; + glm::mat4 modelMatrix; + glm::mat4 projMatrix; + glm::ivec4 viewport; MarkerList markers; EnhancedMarkerList enhancedMarkers; EnhancedMarkerList lockOnMarkers; static const float altitudeOffset; - static const GLfloat black[3]; static std::string headingLabel[36]; static std::string restartLabelFormat; static std::string resumeLabel; diff --git a/src/bzflag/HUDuiControl.cxx b/src/bzflag/HUDuiControl.cxx index 6c5fc56a1c..555e2e99e2 100644 --- a/src/bzflag/HUDuiControl.cxx +++ b/src/bzflag/HUDuiControl.cxx @@ -21,6 +21,7 @@ #include "Bundle.h" #include "TextureManager.h" #include "FontManager.h" +#include "OpenGLAPI.h" // local implementation headers #include "HUDui.h" @@ -31,9 +32,8 @@ // // init static members -const GLfloat HUDuiControl::dimTextColor[3] = { 0.7f, 0.7f, 0.7f }; -const GLfloat HUDuiControl::moreDimTextColor[3] = { 0.4f, 0.4f, 0.4f }; -const GLfloat HUDuiControl::textColor[3] = { 1.0f, 1.0f, 1.0f }; +const glm::vec3 HUDuiControl::dimTextColor = { 0.7f, 0.7f, 0.7f }; +const glm::vec3 HUDuiControl::textColor = { 1.0f, 1.0f, 1.0f }; OpenGLGState* HUDuiControl::gstate = NULL; int HUDuiControl::arrow = -1; int HUDuiControl::arrowFrame = 0; @@ -293,7 +293,7 @@ void HUDuiControl::renderLabel() void HUDuiControl::render() { if (hasFocus() && showingFocus) renderFocus(); - glColor3fv(hasFocus() ? textColor : dimTextColor); + glColor(hasFocus() ? textColor : dimTextColor); renderLabel(); doRender(); } diff --git a/src/bzflag/HUDuiControl.h b/src/bzflag/HUDuiControl.h index dfc023a3b1..7f2dc9773d 100644 --- a/src/bzflag/HUDuiControl.h +++ b/src/bzflag/HUDuiControl.h @@ -23,6 +23,7 @@ /* system headers */ #include +#include // common interface headers #include "BzfEvent.h" @@ -85,9 +86,8 @@ class HUDuiControl void doCallback(); - static const GLfloat dimTextColor[3]; - static const GLfloat moreDimTextColor[3]; - static const GLfloat textColor[3]; + static const glm::vec3 dimTextColor; + static const glm::vec3 textColor; private: bool showingFocus; diff --git a/src/bzflag/HUDuiLabel.cxx b/src/bzflag/HUDuiLabel.cxx index 290f12f0a4..1d5c16f02f 100644 --- a/src/bzflag/HUDuiLabel.cxx +++ b/src/bzflag/HUDuiLabel.cxx @@ -29,9 +29,7 @@ HUDuiLabel::HUDuiLabel() : HUDuiControl() { darker = false; params = NULL; - color[0] = textColor[0]; - color[1] = textColor[1]; - color[2] = textColor[2]; + color = textColor; } HUDuiLabel::~HUDuiLabel() @@ -113,9 +111,7 @@ void HUDuiLabel::setDarker(bool d) void HUDuiLabel::setColor(GLfloat r, GLfloat g, GLfloat b) { - color[0] = r; - color[1] = g; - color[2] = b; + color = glm::vec3(r, g, b); } void HUDuiLabel::doRender() diff --git a/src/bzflag/HUDuiLabel.h b/src/bzflag/HUDuiLabel.h index f25f98f58e..a384763219 100644 --- a/src/bzflag/HUDuiLabel.h +++ b/src/bzflag/HUDuiLabel.h @@ -21,8 +21,10 @@ // ancestor class #include "HUDuiControl.h" +// System headers #include #include +#include #include "BzfEvent.h" @@ -47,7 +49,7 @@ class HUDuiLabel : public HUDuiControl std::string string; std::vector *params; bool darker; - GLfloat color[3]; + glm::vec3 color; }; #endif // __HUDUILABEL_H__ diff --git a/src/bzflag/HUDuiList.cxx b/src/bzflag/HUDuiList.cxx index 210fe9668e..dddc800525 100644 --- a/src/bzflag/HUDuiList.cxx +++ b/src/bzflag/HUDuiList.cxx @@ -17,6 +17,7 @@ #include "BundleMgr.h" #include "Bundle.h" #include "FontManager.h" +#include "OpenGLAPI.h" // local implementation headers #include "HUDui.h" @@ -156,7 +157,7 @@ void HUDuiList::doRender() Bundle *bdl = BundleMgr::getCurrentBundle(); if (index != -1 && getFontFace() >= 0) { - glColor3fv(hasFocus() ? textColor : dimTextColor); + glColor(hasFocus() ? textColor : dimTextColor); FontManager &fm = FontManager::instance(); fm.drawString(getX(), getY(), 0, getFontFace(), getFontSize(), bdl->getLocalString(list[index])); } diff --git a/src/bzflag/HUDuiTextureLabel.cxx b/src/bzflag/HUDuiTextureLabel.cxx index c1f0a986e3..1be5f7bf2c 100644 --- a/src/bzflag/HUDuiTextureLabel.cxx +++ b/src/bzflag/HUDuiTextureLabel.cxx @@ -19,6 +19,7 @@ // common implementation headers #include "TextureManager.h" #include "OpenGLTexture.h" +#include "OpenGLAPI.h" // // HUDuiTextureLabel @@ -60,7 +61,7 @@ void HUDuiTextureLabel::doRender() const float xx = getX(); const float yy = getY(); gstate.setState(); - glColor3fv(textColor); + glColor(textColor); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0.0f, 0.0f); glVertex2f(xx, yy - descent); diff --git a/src/bzflag/HUDuiTypeIn.cxx b/src/bzflag/HUDuiTypeIn.cxx index 98b3726589..aba599ed9f 100644 --- a/src/bzflag/HUDuiTypeIn.cxx +++ b/src/bzflag/HUDuiTypeIn.cxx @@ -19,6 +19,7 @@ // common implementation headers #include "FontManager.h" #include "PlatformFactory.h" +#include "OpenGLAPI.h" // local implementation headers #include "HUDui.h" @@ -213,7 +214,7 @@ void HUDuiTypeIn::doRender() if (getFontFace() < 0) return; // render string - glColor3fv(hasFocus() ? textColor : dimTextColor); + glColor(hasFocus() ? textColor : dimTextColor); FontManager &fm = FontManager::instance(); std::string renderStr; diff --git a/src/bzflag/LocalPlayer.cxx b/src/bzflag/LocalPlayer.cxx index 577fc04074..9bb52a5790 100644 --- a/src/bzflag/LocalPlayer.cxx +++ b/src/bzflag/LocalPlayer.cxx @@ -13,6 +13,11 @@ /* interface header */ #include "LocalPlayer.h" +/* system implementation headers */ +#include +#define GLM_ENABLE_EXPERIMENTAL +#include + /* common implementation headers */ #include "CommandManager.h" #include "BZDBCache.h" @@ -29,9 +34,6 @@ #include "ForceFeedback.h" #include "effectsRenderer.h" -/* system implementation headers */ -#include - LocalPlayer* LocalPlayer::mainPlayer = NULL; LocalPlayer::LocalPlayer(const PlayerId& _id, @@ -171,28 +173,28 @@ void LocalPlayer::doUpdate(float dt) void LocalPlayer::doSlideMotion(float dt, float slideTime, - float newAngVel, float* newVelocity) + float newAngVel, glm::vec3 &newVelocity) { const float oldAzimuth = getAngle(); - const float* oldVelocity = getVelocity(); + const auto &oldVelocity = getVelocity(); const float angle = oldAzimuth + (0.5f * dt * newAngVel); const float cos_val = cosf(angle); const float sin_val = sinf(angle); const float scale = (dt / slideTime); const float speedAdj = desiredSpeed * scale; - const float* ov = oldVelocity; - float* nv = newVelocity; + const auto ov = glm::vec2(oldVelocity); + auto &nv = newVelocity; nv[0] = ov[0] + (cos_val * speedAdj); nv[1] = ov[1] + (sin_val * speedAdj); - const float newSpeed = sqrtf((nv[0] * nv[0]) + (nv[1] * nv[1])); + const float newSpeed = glm::length(glm::vec2(nv)); float maxSpeed = getMaxSpeed(); if (newSpeed > maxSpeed) { float adjSpeed; - const float oldSpeed = sqrtf((ov[0] * ov[0]) + (ov[1] * ov[1])); + const float oldSpeed = glm::length(ov); if (oldSpeed > maxSpeed) { adjSpeed = oldSpeed - maxSpeed * scale; @@ -248,16 +250,13 @@ void LocalPlayer::doUpdateMotion(float dt) // save old state const Location oldLocation = location; - const float* oldPosition = getPosition(); + const auto &oldPosition = getPosition(); const float oldAzimuth = getAngle(); const float oldAngVel = getAngularVelocity(); - const float* oldVelocity = getVelocity(); + const auto &oldVelocity = getVelocity(); // prepare new state - float newVelocity[3]; - newVelocity[0] = oldVelocity[0]; - newVelocity[1] = oldVelocity[1]; - newVelocity[2] = oldVelocity[2]; + auto newVelocity = oldVelocity; float newAngVel = 0.0f; clearRemoteSounds(); @@ -430,10 +429,7 @@ void LocalPlayer::doUpdateMotion(float dt) lastObstacle = NULL; // get new position so far (which is just the current position) - float newPos[3]; - newPos[0] = oldPosition[0]; - newPos[1] = oldPosition[1]; - newPos[2] = oldPosition[2]; + auto newPos = oldPosition; float newAzimuth = oldAzimuth; // move tank through the time step. if there's a collision then @@ -469,46 +465,37 @@ void LocalPlayer::doUpdateMotion(float dt) // we are using a maximum value on time for frame to avoid lagging problem setDesiredSpeed(0.25f); float delta = dt > 0.1f ? 0.1f : dt; - float normalStuck[3]; + glm::vec3 normalStuck; obstacle->getNormal(newPos, normalStuck); // use all the given speed to exit float movementMax = desiredSpeed * delta; - newVelocity[0] = movementMax * normalStuck[0]; - newVelocity[1] = movementMax * normalStuck[1]; + newVelocity = movementMax * normalStuck; if ((World::getWorld()->allowJumping() || (getFlag() == Flags::Jumping) || (getFlag() == Flags::Wings)) && (getFlag() != Flags::NoJumping)) - newVelocity[2] = movementMax * normalStuck[2]; + ; else newVelocity[2] = 0.0f; // exit will be in the normal direction - newPos[0] += newVelocity[0]; - newPos[1] += newVelocity[1]; - newPos[2] += newVelocity[2]; + newPos += newVelocity; // compute time for all other kind of movements timeStep -= delta; } } - float nominalPlanarSpeed2 - = newVelocity[0] * newVelocity[0] - + newVelocity[1] * newVelocity[1]; + float nominalPlanarSpeed2 = glm::length2(glm::vec2(newVelocity)); for (int numSteps = 0; numSteps < MaxSteps; numSteps++) { // record position at beginning of time step - float tmpPos[3], tmpAzimuth; + float tmpAzimuth; tmpAzimuth = newAzimuth; - tmpPos[0] = newPos[0]; - tmpPos[1] = newPos[1]; - tmpPos[2] = newPos[2]; + auto tmpPos = newPos; // get position at end of time step newAzimuth = tmpAzimuth + timeStep * newAngVel; - newPos[0] = tmpPos[0] + timeStep * newVelocity[0]; - newPos[1] = tmpPos[1] + timeStep * newVelocity[1]; - newPos[2] = tmpPos[2] + timeStep * newVelocity[2]; + newPos = tmpPos + timeStep * newVelocity; if ((newPos[2] < groundLimit) && (newVelocity[2] < 0)) { // Hit lower limit, stop falling @@ -551,11 +538,8 @@ void LocalPlayer::doUpdateMotion(float dt) } // record position when hitting - float hitPos[3], hitAzimuth; - hitAzimuth = newAzimuth; - hitPos[0] = newPos[0]; - hitPos[1] = newPos[1]; - hitPos[2] = newPos[2]; + float hitAzimuth = newAzimuth; + auto hitPos = newPos; // find the latest time before the collision float searchTime = 0.0f, searchStep = 0.5f * timeStep; @@ -565,9 +549,7 @@ void LocalPlayer::doUpdateMotion(float dt) // get intermediate position const float t = searchTime + searchStep; newAzimuth = tmpAzimuth + (t * newAngVel); - newPos[0] = tmpPos[0] + (t * newVelocity[0]); - newPos[1] = tmpPos[1] + (t * newVelocity[1]); - newPos[2] = tmpPos[2] + (t * newVelocity[2]); + newPos = tmpPos + t * newVelocity; if ((newPos[2] < groundLimit) && (newVelocity[2] < 0)) newPos[2] = groundLimit; @@ -589,17 +571,13 @@ void LocalPlayer::doUpdateMotion(float dt) expelled = searchExpelled; hitAzimuth = newAzimuth; - hitPos[0] = newPos[0]; - hitPos[1] = newPos[1]; - hitPos[2] = newPos[2]; + hitPos = newPos; } } // get position just before impact newAzimuth = tmpAzimuth + (searchTime * newAngVel); - newPos[0] = tmpPos[0] + (searchTime * newVelocity[0]); - newPos[1] = tmpPos[1] + (searchTime * newVelocity[1]); - newPos[2] = tmpPos[2] + (searchTime * newVelocity[2]); + newPos = tmpPos + searchTime * newVelocity; if (oldPosition[2] < groundLimit) newVelocity[2] = std::max(newVelocity[2], -oldPosition[2] / 2.0f + 0.5f); @@ -610,7 +588,7 @@ void LocalPlayer::doUpdateMotion(float dt) // get normal at intersection. sometimes fancy test says there's // no intersection but we're expecting one so, in that case, fall // back to simple normal calculation. - float normal[3]; + glm::vec3 normal; if (!getHitNormal(obstacle, newPos, newAzimuth, hitPos, hitAzimuth, normal)) obstacle->getNormal(newPos, normal); @@ -698,14 +676,11 @@ void LocalPlayer::doUpdateMotion(float dt) { const float oodt = 1.0f / dt; newAngVel = (newAzimuth - oldAzimuth) * oodt; - newVelocity[0] = (newPos[0] - oldPosition[0]) * oodt; - newVelocity[1] = (newPos[1] - oldPosition[1]) * oodt; - newVelocity[2] = (newPos[2] - oldPosition[2]) * oodt; + newVelocity = (newPos - oldPosition) * oodt; if (nominalPlanarSpeed2) { - float newPlanarSpeed2 = newVelocity[0] * newVelocity[0] - + newVelocity[1] * newVelocity[1]; + float newPlanarSpeed2 = glm::length2(glm::vec2(newVelocity)); float scaling = newPlanarSpeed2 / nominalPlanarSpeed2; if (scaling > 1.0f) { @@ -743,8 +718,7 @@ void LocalPlayer::doUpdateMotion(float dt) const Teleporter* outPort = World::getWorld()->getTeleporter(targetTele, outFace); teleporter->getPointWRT(*outPort, face, outFace, - newPos, newVelocity, newAzimuth, - newPos, newVelocity, &newAzimuth); + newPos, &newVelocity, &newAzimuth); // check for a hit on the other side const Obstacle* teleObs = @@ -752,7 +726,7 @@ void LocalPlayer::doUpdateMotion(float dt) if (teleObs != NULL) { // revert - memcpy (newPos, oldPosition, sizeof(float[3])); + newPos = oldPosition; newVelocity[0] = newVelocity[1] = 0.0f; newVelocity[2] = oldVelocity[2]; newAzimuth = oldAzimuth; @@ -866,9 +840,7 @@ void LocalPlayer::doUpdateMotion(float dt) // see if I'm over my antidote if (antidoteFlag && location == OnGround) { - float dist = - ((flagAntidotePos[0] - newPos[0]) * (flagAntidotePos[0] - newPos[0])) + - ((flagAntidotePos[1] - newPos[1]) * (flagAntidotePos[1] - newPos[1])); + float dist = glm::distance2(glm::vec2(flagAntidotePos), glm::vec2(newPos)); const float twoRads = getRadius() + BZDBCache::flagRadius; if (dist < (twoRads * twoRads)) server->sendDropFlag(getPosition()); @@ -898,36 +870,15 @@ void LocalPlayer::doUpdateMotion(float dt) ((teleporter != NULL) && (getFlag() != Flags::PhantomZone))); } if (NEAR_ZERO(dt, ZERO_TOLERANCE)) - speedSoundReceiver(newVelocity[0], newVelocity[1], newVelocity[2]); + speedSoundReceiver(newVelocity); else - { - speedSoundReceiver((newPos[0] - oldPosition[0]) / dt, - (newPos[1] - oldPosition[1]) / dt, - (newPos[2] - oldPosition[2]) / dt); - } + speedSoundReceiver((newPos - oldPosition) / dt); } } -const Obstacle* LocalPlayer::getHitBuilding(const float* p, float a, - bool phased, bool& expelled) const -{ - const float* dims = getDimensions(); - const Obstacle* obstacle = - World::getWorld()->hitBuilding(p, a, dims[0], dims[1], dims[2]); - - expelled = (obstacle != NULL); - if (expelled && phased) - expelled = (obstacle->getType() == WallObstacle::getClassName() || - obstacle->getType() == Teleporter::getClassName() || - (getFlag() == Flags::OscillationOverthruster && desiredSpeed < 0.0f && - p[2] == 0.0f)); - return obstacle; -} - - -const Obstacle* LocalPlayer::getHitBuilding(const float* oldP, float oldA, - const float* p, float a, +const Obstacle* LocalPlayer::getHitBuilding(const glm::vec3 &oldP, float oldA, + const glm::vec3 &p, float a, bool phased, bool& expelled) { const bool hasOOflag = getFlag() == Flags::OscillationOverthruster; @@ -958,9 +909,9 @@ const Obstacle* LocalPlayer::getHitBuilding(const float* oldP, float oldA, bool LocalPlayer::getHitNormal(const Obstacle* o, - const float* pos1, float azimuth1, - const float* pos2, float azimuth2, - float* normal) const + const glm::vec3 &pos1, float azimuth1, + const glm::vec3 &pos2, float azimuth2, + glm::vec3 &normal) const { const float* dims = getDimensions(); return o->getHitNormal(pos1, azimuth1, pos2, azimuth2, @@ -982,7 +933,7 @@ static bool notInObstacleList(const Obstacle* obs, void LocalPlayer::collectInsideBuildings() { - const float* pos = getPosition(); + const auto &pos = getPosition(); const float angle = getAngle(); const float* dims = getDimensions(); @@ -1040,9 +991,9 @@ int LocalPlayer::getFlagShakingWins() const return flagShakingWins; } -const GLfloat* LocalPlayer::getAntidoteLocation() const +const glm::vec3 *LocalPlayer::getAntidoteLocation() const { - return (const GLfloat*)(antidoteFlag ? antidoteFlag->getSphere() : NULL); + return antidoteFlag ? &antidoteFlag->getSphere() : NULL; } ShotPath* LocalPlayer::getShot(int index) const @@ -1053,7 +1004,7 @@ ShotPath* LocalPlayer::getShot(int index) const return shots[index]; } -void LocalPlayer::restart(const float* pos, float _azimuth) +void LocalPlayer::restart(const glm::vec3 &pos, float _azimuth) { // put me in limbo setStatus(short(PlayerState::DeadStatus)); @@ -1079,7 +1030,7 @@ void LocalPlayer::restart(const float* pos, float _azimuth) deathPhyDrv = -1; // initialize position/speed state - static const float zero[3] = { 0.0f, 0.0f, 0.0f }; + static const auto zero = glm::vec3(0.0f); location = (pos[2] > 0.0f) ? OnBuilding : OnGround; lastObstacle = NULL; lastSpeed = 0.0f; @@ -1247,13 +1198,9 @@ bool LocalPlayer::fireShot() if (firingInfo.flagType == Flags::ShockWave) { // move shot origin under tank and make it stationary - const float* pos = getPosition(); - firingInfo.shot.pos[0] = pos[0]; - firingInfo.shot.pos[1] = pos[1]; - firingInfo.shot.pos[2] = pos[2]; - firingInfo.shot.vel[0] = 0.0f; - firingInfo.shot.vel[1] = 0.0f; - firingInfo.shot.vel[2] = 0.0f; + const auto &pos = getPosition(); + firingInfo.shot.pos = pos; + firingInfo.shot.vel = glm::vec3(0.0f); } else { @@ -1261,12 +1208,12 @@ bool LocalPlayer::fireShot() if (handicap > 0.0f) { const float speedAd = 1.0f + (handicap * (BZDB.eval(StateDatabase::BZDB_HANDICAPSHOTAD) - 1.0f)); - const float* dir = getForward(); - const float* tankVel = getVelocity(); - const float shotSpeed = speedAd * BZDB.eval(StateDatabase::BZDB_SHOTSPEED); - firingInfo.shot.vel[0] = tankVel[0] + shotSpeed * dir[0]; - firingInfo.shot.vel[1] = tankVel[1] + shotSpeed * dir[1]; - firingInfo.shot.vel[2] = tankVel[2] + shotSpeed * dir[2]; + auto dir = getForward(); + dir *= speedAd * BZDB.eval(StateDatabase::BZDB_SHOTSPEED); + + firingInfo.shot.vel = getVelocity(); + firingInfo.shot.vel[0] += dir[0]; + firingInfo.shot.vel[1] += dir[1]; } // Set _shotsKeepVerticalVelocity on the server if you want shots // to have the same vertical velocity as the tank when fired. @@ -1365,7 +1312,7 @@ float LocalPlayer::getReloadTime() const return minTime; } -bool LocalPlayer::doEndShot(int ident, bool isHit, float* pos) +bool LocalPlayer::doEndShot(int ident, bool isHit, glm::vec3 &pos) { const int index = ident & 255; const int slt = (ident >> 8) & 127; @@ -1398,10 +1345,8 @@ bool LocalPlayer::doEndShot(int ident, bool isHit, float* pos) return false; // end it - const float* shotPos = shots[index]->getPosition(); - pos[0] = shotPos[0]; - pos[1] = shotPos[1]; - pos[2] = shotPos[2]; + const auto &shotPos = shots[index]->getPosition(); + pos = shotPos; shots[index]->setExpired(); return true; } @@ -1445,8 +1390,8 @@ void LocalPlayer::doJump() return; // jump velocity - const float* oldVelocity = getVelocity(); - float newVelocity[3]; + const auto &oldVelocity = getVelocity(); + glm::vec3 newVelocity; newVelocity[0] = oldVelocity[0]; newVelocity[1] = oldVelocity[1]; if (flag == Flags::Wings) @@ -1518,10 +1463,8 @@ void LocalPlayer::explodeTank() // Limiting max height increment to this value (the old default value) const float zMax = 49.0f; setExplode(TimeKeeper::getTick()); - const float* oldVelocity = getVelocity(); - float newVelocity[3]; - newVelocity[0] = oldVelocity[0]; - newVelocity[1] = oldVelocity[1]; + const auto &oldVelocity = getVelocity(); + auto newVelocity = oldVelocity; if (gravity < 0) { // comparing 2 speed: @@ -1533,18 +1476,12 @@ void LocalPlayer::explodeTank() if (newVelocity[2] > maxSpeed) newVelocity[2] = maxSpeed; } - else - newVelocity[2] = oldVelocity[2]; TankDeathOverride* death = getDeathEffect(); if (death) { - fvec3 v(newVelocity[0],newVelocity[1],newVelocity[2]); + auto v = newVelocity; if (death->GetDeathVector(v)) - { - newVelocity[0] = v.x; - newVelocity[1] = v.y; - newVelocity[2] = v.z; - } + newVelocity = v; } setVelocity(newVelocity); location = Exploding; @@ -1578,8 +1515,9 @@ void LocalPlayer::doMomentum(float dt, } } -void LocalPlayer::doFriction(float dt, - const float *oldVelocity, float *newVelocity) +void LocalPlayer::doFriction(float dt, + const glm::vec2 &oldVelocity, + glm::vec3 &newVelocity) { const float friction = (getFlag() == Flags::Momentum) ? BZDB.eval(StateDatabase::BZDB_MOMENTUMFRICTION) : BZDB.eval(StateDatabase::BZDB_FRICTION); @@ -1588,21 +1526,20 @@ void LocalPlayer::doFriction(float dt, { // limit vector acceleration - float delta[2] = {newVelocity[0] - oldVelocity[0], newVelocity[1] - oldVelocity[1]}; - float acc2 = (delta[0] * delta[0] + delta[1] * delta[1]) / (dt*dt); - float accLimit = 20.0f * friction; + auto delta = glm::vec2(newVelocity) - oldVelocity; + float acc2 = glm::length2(delta); + float accLimit = 20.0f * friction * dt; if (acc2 > accLimit*accLimit) { float ratio = accLimit / sqrtf(acc2); - newVelocity[0] = oldVelocity[0] + delta[0]*ratio; - newVelocity[1] = oldVelocity[1] + delta[1]*ratio; + newVelocity = glm::vec3(oldVelocity + delta * ratio, 0.0f); } } } void LocalPlayer::doForces(float UNUSED(dt), - float* UNUSED(velocity), + glm::vec3 &UNUSED(velocity), float& UNUSED(angVel)) { // apply external forces @@ -1652,15 +1589,15 @@ bool LocalPlayer::checkHit(const Player* source, continue; // test myself against shot - float position[3]; + glm::vec3 position; const float t = shot->checkHit(this, position); if (t >= minTime) continue; // test if shot hit a part of my tank that's through a teleporter. // hit is no good if hit point is behind crossing plane. - if (isCrossingWall() && position[0] * crossingPlane[0] + - position[1] * crossingPlane[1] + - position[2] * crossingPlane[2] + crossingPlane[3] < 0.0) + if (isCrossingWall() && + (glm::dot(position, glm::vec3(crossingPlane)) + crossingPlane[3] + < 0.0)) continue; // okay, shot hit diff --git a/src/bzflag/LocalPlayer.h b/src/bzflag/LocalPlayer.h index a5e75b21af..f43ff33fac 100644 --- a/src/bzflag/LocalPlayer.h +++ b/src/bzflag/LocalPlayer.h @@ -19,6 +19,7 @@ /* system interface headers */ #include #include +#include /* common interface headers */ #include "Obstacle.h" @@ -65,8 +66,8 @@ class LocalPlayer : public BaseLocalPlayer FiringStatus getFiringStatus() const; float getFlagShakingTime() const; int getFlagShakingWins() const; - const float* getAntidoteLocation() const; - ShotPath* getShot(int index) const; + const glm::vec3 *getAntidoteLocation() const; + ShotPath* getShot(int index) const override; const Player* getTarget() const; int getDeathPhysicsDriver() const; const std::vector& getInsideBuildings() const; @@ -77,7 +78,7 @@ class LocalPlayer : public BaseLocalPlayer void setPause(bool = true); void activateAutoPilot(bool = true); bool fireShot(); - void explodeTank(); + void explodeTank() override; void doJump(); void setJump(); void setJumpPressed(bool value); @@ -92,11 +93,11 @@ class LocalPlayer : public BaseLocalPlayer void setRecipient(const Player*); const Player* getRecipient() const; - void restart(const float* pos, float azimuth); + void restart(const glm::vec3 &pos, float azimuth); bool checkHit(const Player* source, const ShotPath*& hit, - float& minTime) const; - void setFlag(FlagType*); - void changeScore(short deltaWins, short deltaLosses, short deltaTeamKills); + float& minTime) const override; + void setFlag(FlagType*) override; + void changeScore(short deltaWins, short deltaLosses, short deltaTeamKills) override; void addAntidote(SceneDatabase*); @@ -115,30 +116,30 @@ class LocalPlayer : public BaseLocalPlayer static LocalPlayer* getMyTank(); static void setMyTank(LocalPlayer*); - const Obstacle* getHitBuilding(const float* pos, float angle, - bool phased, bool& expel) const; - const Obstacle* getHitBuilding(const float* oldPos, float oldAngle, - const float* pos, float angle, + const Obstacle* getHitBuilding(const glm::vec3 &oldPos, float oldAngle, + const glm::vec3 &pos, float angle, bool phased, bool& expel); bool getHitNormal(const Obstacle* o, - const float* pos1, float azimuth1, - const float* pos2, float azimuth2, - float* normal) const; + const glm::vec3 &pos1, float azimuth1, + const glm::vec3 &pos2, float azimuth2, + glm::vec3 &normal) const; protected: - bool doEndShot(int index, bool isHit, float* pos); - void doUpdate(float dt); - void doUpdateMotion(float dt); + bool doEndShot(int index, bool isHit, glm::vec3 &pos) override; + void doUpdate(float dt) override; + void doUpdateMotion(float dt) override; void doMomentum(float dt, float& speed, float& angVel); - void doFriction(float dt, const float *oldVelocity, float *newVelocity); - void doForces(float dt, float* velocity, float& angVel); + void doFriction(float dt, + const glm::vec2 &oldVelocity, + glm::vec3 &newVelocity); + void doForces(float dt, glm::vec3 &velocity, float& angVel); LocalShotPath** shots; bool gettingSound; ServerLink* server; private: void doSlideMotion(float dt, float slideTime, - float newAngVel, float* newVelocity); + float newAngVel, glm::vec3 &newVelocity); float getNewAngVel(float old, float desired); void collectInsideBuildings(); @@ -149,12 +150,12 @@ class LocalPlayer : public BaseLocalPlayer TimeKeeper agilityTime; float flagShakingTime; int flagShakingWins; - float flagAntidotePos[3]; + glm::vec3 flagAntidotePos; FlagSceneNode* antidoteFlag; float desiredSpeed; float desiredAngVel; float lastSpeed; - float crossingPlane[4]; + glm::vec4 crossingPlane; bool anyShotActive; const Player* target; const Player* nemesis; diff --git a/src/bzflag/Plan.cxx b/src/bzflag/Plan.cxx index 7e54066941..3cff93d596 100644 --- a/src/bzflag/Plan.cxx +++ b/src/bzflag/Plan.cxx @@ -44,14 +44,13 @@ bool Plan::isValid() void Plan::execute(float &, float &) { - float pos[3]; LocalPlayer *myTank = LocalPlayer::getMyTank(); - memcpy(pos, myTank->getPosition(), sizeof(pos)); + auto pos = myTank->getPosition(); if (pos[2] < 0.0f) pos[2] = 0.01f; float myAzimuth = myTank->getAngle(); - float dir[3] = {cosf(myAzimuth), sinf(myAzimuth), 0.0f}; + auto dir = glm::vec3(cosf(myAzimuth), sinf(myAzimuth), 0.0f); pos[2] += myTank->getMuzzleHeight(); Ray tankRay(pos, dir); pos[2] -= myTank->getMuzzleHeight(); @@ -69,15 +68,12 @@ void Plan::execute(float &, float &) !remotePlayers[t]->isNotResponding()) { - const float *tp = remotePlayers[t]->getPosition(); - float enemyPos[3]; + const auto &tp = remotePlayers[t]->getPosition(); //toss in some lag adjustment/future prediction - 300 millis - memcpy(enemyPos,tp,sizeof(enemyPos)); - const float *tv = remotePlayers[t]->getVelocity(); - enemyPos[0] += 0.3f * tv[0]; - enemyPos[1] += 0.3f * tv[1]; - enemyPos[2] += 0.3f * tv[2]; + auto enemyPos = tp; + const auto &tv = remotePlayers[t]->getVelocity(); + enemyPos += 0.3f * tv; if (enemyPos[2] < 0.0f) enemyPos[2] = 0.0f; @@ -122,14 +118,11 @@ void Plan::execute(float &, float &) && (myTank->getFlag() != Flags::SuperBullet)) continue; - const float *tp = remotePlayers[t]->getPosition(); - float enemyPos[3]; + const auto &tp = remotePlayers[t]->getPosition(); //toss in some lag adjustment/future prediction - 300 millis - memcpy(enemyPos,tp,sizeof(enemyPos)); - const float *tv = remotePlayers[t]->getVelocity(); - enemyPos[0] += 0.3f * tv[0]; - enemyPos[1] += 0.3f * tv[1]; - enemyPos[2] += 0.3f * tv[2]; + auto enemyPos = tp; + const auto &tv = remotePlayers[t]->getVelocity(); + enemyPos += 0.3f * tv; if (enemyPos[2] < 0.0f) enemyPos[2] = 0.0f; @@ -165,7 +158,7 @@ void Plan::execute(float &, float &) bool Plan::avoidBullet(float &rotation, float &speed) { LocalPlayer *myTank = LocalPlayer::getMyTank(); - const float *pos = myTank->getPosition(); + const auto pos = glm::vec2(myTank->getPosition()); if ((myTank->getFlag() == Flags::Narrow) || (myTank->getFlag() == Flags::Burrow)) return false; // take our chances @@ -176,13 +169,13 @@ bool Plan::avoidBullet(float &rotation, float &speed) if ((shot == NULL) || (minDistance > 100.0f)) return false; - const float *shotPos = shot->getPosition(); - const float *shotVel = shot->getVelocity(); - float shotAngle = atan2f(shotVel[1],shotVel[0]); - float shotUnitVec[2] = {cosf(shotAngle), sinf(shotAngle)}; + const auto shotPos = glm::vec2(shot->getPosition()); + const auto shotVel = shot->getVelocity(); + const float shotAngle = atan2f(shotVel[1],shotVel[0]); + const auto shotUnitVec = glm::vec2(cosf(shotAngle), sinf(shotAngle)); - float trueVec[2] = {(pos[0]-shotPos[0])/minDistance,(pos[1]-shotPos[1])/minDistance}; - float dotProd = trueVec[0]*shotUnitVec[0]+trueVec[1]*shotUnitVec[1]; + auto trueVec = (pos - shotPos) / minDistance; + float dotProd = glm::dot(trueVec, shotUnitVec); if (((World::getWorld()->allowJumping() || (myTank->getFlag()) == Flags::Jumping || (myTank->getFlag()) == Flags::Wings)) @@ -231,7 +224,7 @@ bool Plan::avoidBullet(float &rotation, float &speed) ShotPath *Plan::findWorstBullet(float &minDistance) { LocalPlayer *myTank = LocalPlayer::getMyTank(); - const float *pos = myTank->getPosition(); + const auto &pos = myTank->getPosition(); ShotPath *minPath = NULL; minDistance = Infinity; @@ -256,7 +249,7 @@ ShotPath *Plan::findWorstBullet(float &minDistance) (myTank->getFlag() == Flags::Cloaking)) continue; //cloaked tanks can't die from lasers - const float* shotPos = shot->getPosition(); + const auto &shotPos = shot->getPosition(); if ((fabs(shotPos[2] - pos[2]) > BZDBCache::tankHeight) && (shot->getFlag() != Flags::GuidedMissile)) continue; @@ -264,7 +257,7 @@ ShotPath *Plan::findWorstBullet(float &minDistance) const float dist = TargetingUtils::getTargetDistance(pos, shotPos); if (dist < minDistance) { - const float *shotVel = shot->getVelocity(); + const auto shotVel = shot->getVelocity(); float shotAngle = atan2f(shotVel[1], shotVel[0]); float shotUnitVec[2] = {cosf(shotAngle), sinf(shotAngle)}; @@ -293,14 +286,14 @@ ShotPath *Plan::findWorstBullet(float &minDistance) if (shot->getFlag() == Flags::Laser && myTank->getFlag() == Flags::Cloaking) continue; //cloaked tanks can't die from lasers - const float* shotPos = shot->getPosition(); + const auto &shotPos = shot->getPosition(); if ((fabs(shotPos[2] - pos[2]) > BZDBCache::tankHeight) && (shot->getFlag() != Flags::GuidedMissile)) continue; const float dist = TargetingUtils::getTargetDistance( pos, shotPos ); if (dist < minDistance) { - const float *shotVel = shot->getVelocity(); + const auto shotVel = shot->getVelocity(); float shotAngle = atan2f(shotVel[1], shotVel[0]); float shotUnitVec[2] = {cosf(shotAngle), sinf(shotAngle)}; @@ -441,7 +434,7 @@ bool WeavePlan::isValid() return false; LocalPlayer *myTank = LocalPlayer::getMyTank(); - const float *pVel = myTank->getVelocity(); + const auto &pVel = myTank->getVelocity(); if ((pVel[0] == 0.0f) && (pVel[1] == 0.0f) && (pVel[2] == 0.0f)) return false; diff --git a/src/bzflag/Player.cxx b/src/bzflag/Player.cxx index 24489e9be2..b15731d41c 100644 --- a/src/bzflag/Player.cxx +++ b/src/bzflag/Player.cxx @@ -80,7 +80,7 @@ Player::Player(const PlayerId& _id, TeamColor _team, oldStatus(0), oldZSpeed(0.0f) { - static const float zero[3] = { 0.0f, 0.0f, 0.0f }; + static const auto zero = glm::vec3(0.0f); move(zero, 0.0f); setVelocity(zero); setAngularVelocity(0.0f); @@ -90,7 +90,7 @@ Player::Player(const PlayerId& _id, TeamColor _team, setUserSpeed(0.0f); setUserAngVel(0.0f); - apparentVelocity[0] = apparentVelocity[1] = apparentVelocity[2] = 0.0f; + apparentVelocity = glm::vec3(0.0f); inputTimestamp = 0.0f; reportedHits = 0; @@ -121,11 +121,9 @@ Player::Player(const PlayerId& _id, TeamColor _team, dimensions[1] = 0.5f * BZDBCache::tankWidth; dimensions[2] = BZDBCache::tankHeight; for (int i = 0; i < 3; i++) - { dimensionsRate[i] = 0.0f; - dimensionsScale[i] = 1.0f; - dimensionsTarget[i] = 1.0f; - } + dimensionsScale = glm::vec3(1.0f); + dimensionsTarget = glm::vec3(1.0f); useDimensions = false; // setup alpha properties @@ -221,7 +219,7 @@ float Player::getMaxSpeed ( void ) const return maxSpeed; } -void Player::getMuzzle(float* m) const +glm::vec3 Player::getMuzzle() const { // NOTE: like getRadius(), we only use dimensionsScale[0]. // as well, we do not use BZDB_MUZZLEFRONT, but the @@ -232,11 +230,10 @@ void Player::getMuzzle(float* m) const front = front + (dimensionsRate[0] * 0.1f); front = front + 0.1f; - m[0] = state.pos[0] + (front * forward[0]); - m[1] = state.pos[1] + (front * forward[1]); + auto m = state.pos + front * forward; const float height = BZDB.eval(StateDatabase::BZDB_MUZZLEHEIGHT); - m[2] = state.pos[2] + (height * dimensionsScale[2]); - return; + m[2] += height * dimensionsScale[2]; + return m; } @@ -251,12 +248,10 @@ void Player::forceReload(float time) jamTime += time; } -void Player::move(const float* _pos, float _azimuth) +void Player::move(const glm::vec3 &_pos, float _azimuth) { // assumes _forward is normalized - state.pos[0] = _pos[0]; - state.pos[1] = _pos[1]; - state.pos[2] = _pos[2]; + state.pos = _pos; state.azimuth = _azimuth; // limit angle @@ -279,11 +274,9 @@ void Player::move(const float* _pos, float _azimuth) } -void Player::setVelocity(const float* _velocity) +void Player::setVelocity(const glm::vec3 &_velocity) { - state.velocity[0] = _velocity[0]; - state.velocity[1] = _velocity[1]; - state.velocity[2] = _velocity[2]; + state.velocity = _velocity; } @@ -465,8 +458,7 @@ void Player::updateTrackMarks() if (lifeTime > TrackMarks::updateTime) { bool drawMark = true; - float markPos[3]; - markPos[2] = state.pos[2]; + auto markPos = state.pos; // FIXME - again, this should be pulled for TankGeometryMgr const float fullLength = 6.0f; const float treadHeight = 1.2f; @@ -476,14 +468,14 @@ void Player::updateTrackMarks() if (relativeSpeed > +minSpeed) { // draw the mark at the back of the treads - markPos[0] = state.pos[0] - (forward[0] * dist); - markPos[1] = state.pos[1] - (forward[1] * dist); + markPos[0] -= forward[0] * dist; + markPos[1] -= forward[1] * dist; } else if (relativeSpeed < -minSpeed) { // draw the mark at the front of the treads - markPos[0] = state.pos[0] + (forward[0] * dist); - markPos[1] = state.pos[1] + (forward[1] * dist); + markPos[0] += forward[0] * dist; + markPos[1] += forward[1] * dist; } else drawMark = false; @@ -504,10 +496,9 @@ void Player::updateDimensions(float dt, bool local) { // copy the current information float oldRates[3]; - float oldScales[3]; float oldDimensions[3]; memcpy (oldRates, dimensionsRate, sizeof(float[3])); - memcpy (oldScales, dimensionsScale, sizeof(float[3])); + auto oldScales = dimensionsScale; memcpy (oldDimensions, dimensions, sizeof(float[3])); // update the dimensions @@ -556,15 +547,13 @@ void Player::updateDimensions(float dt, bool local) { // copy the old information memcpy (dimensions, oldDimensions, sizeof(float[3])); - memcpy (dimensionsScale, oldScales, sizeof(float[3])); + dimensionsScale = oldScales; memcpy (dimensionsRate, oldRates, sizeof(float[3])); } } // check if the dimensions are at a steady state - if ((dimensionsScale[0] == dimensionsTarget[0]) && - (dimensionsScale[1] == dimensionsTarget[1]) && - (dimensionsScale[2] == dimensionsTarget[2])) + if (dimensionsScale == dimensionsTarget) useDimensions = false; else useDimensions = true; @@ -731,9 +720,7 @@ void Player::updateFlagEffect(FlagType* effectFlag) } // set the dimension targets - dimensionsTarget[0] = 1.0f; - dimensionsTarget[1] = 1.0f; - dimensionsTarget[2] = 1.0f; + dimensionsTarget = glm::vec3(1.0f); if (effectFlag == Flags::Obesity) { const float factor = BZDB.eval(StateDatabase::BZDB_OBESEFACTOR); @@ -781,7 +768,7 @@ void Player::updateFlagEffect(FlagType* effectFlag) void Player::endShot(int index, bool isHit, bool showExplosion) { - float pos[3]; + glm::vec3 pos; if (doEndShot(index, isHit, pos) && showExplosion) addShotExplosion(pos); return; @@ -795,25 +782,22 @@ void Player::setVisualTeam (TeamColor visualTeam) return; lastVisualTeam = visualTeam; - static const GLfloat tankSpecular[3] = { 0.1f, 0.1f, 0.1f }; - static GLfloat tankEmissive[3] = { 0.0f, 0.0f, 0.0f }; + static const auto &tankSpecular = glm::vec3(0.1f); + static const auto &tankEmissive = glm::vec3(0.0f); static float tankShininess = 20.0f; - static GLfloat rabbitEmissive[3] = { 0.0f, 0.0f, 0.0f }; + static const auto &rabbitEmissive = glm::vec3(0.0f); static float rabbitShininess = 100.0f; - GLfloat *emissive; - GLfloat shininess; + const auto &emissive + = (visualTeam == RabbitTeam) + ? rabbitEmissive + : tankEmissive; + GLfloat shininess; if (visualTeam == RabbitTeam) - { - emissive = rabbitEmissive; shininess = rabbitShininess; - } else - { - emissive = tankEmissive; shininess = tankShininess; - } TextureManager &tm = TextureManager::instance(); std::string texName; @@ -830,7 +814,7 @@ void Player::setVisualTeam (TeamColor visualTeam) if (tankTexture < 0) tankTexture = tm.getTextureID(texName.c_str(),false); - const float* _color = Team::getTankColor(visualTeam); + const auto &_color = Team::getTankColor(visualTeam); color[0] = _color[0]; color[1] = _color[1]; color[2] = _color[2]; @@ -871,7 +855,7 @@ void Player::addToScene(SceneDatabase* scene, TeamColor effectiveTeam, bool inCockpit, bool seerView, bool showTreads, bool showIDL) { - const GLfloat groundPlane[4] = {0.0f, 0.0f, 1.0f, 0.0f}; + const auto groundPlane = glm::vec4(0.0f, 0.0f, 1.0f, 0.0f); if (!isAlive() && !isExploding()) { @@ -938,15 +922,16 @@ void Player::addToScene(SceneDatabase* scene, TeamColor effectiveTeam, if (isCrossingWall()) { // get which plane to compute IDL against - GLfloat plane[4]; + glm::vec4 plane; const GLfloat a = atan2f(forward[1], forward[0]); const Obstacle* obstacle = World::getWorld()->hitBuilding(state.pos, a, dimensions[0], dimensions[1], dimensions[2]); - if ((obstacle && obstacle->isCrossing(state.pos, a, - dimensions[0], dimensions[1], - dimensions[2], plane)) || + if ((obstacle && obstacle->isCrossing( + state.pos, a, + dimensions[0], dimensions[1], + dimensions[2], &plane)) || World::getWorld()->crossingTeleporter(state.pos, a, dimensions[0], dimensions[1], dimensions[2], plane)) @@ -987,10 +972,9 @@ void Player::addToScene(SceneDatabase* scene, TeamColor effectiveTeam, const float fadeRatio = 0.8f; if (t > fadeRatio) { - GLfloat newColor[4]; - memcpy(newColor, color, sizeof(float[3])); + auto newColor = color; const float fadeFactor = (1.0f - t) / (1.0f - fadeRatio); - newColor[3] = color[3] * fadeFactor; + newColor[3] *= fadeFactor; tankNode->setColor(newColor); } tankNode->setExplodeFraction(t); @@ -1116,51 +1100,42 @@ bool Player::validTeamTarget(const Player *possibleTarget) const } -void Player::getDeadReckoning(float* predictedPos, float* predictedAzimuth, - float* predictedVel, float dt) const +void Player::getDeadReckoning(glm::vec3 &predictedPos, float* predictedAzimuth, + glm::vec3 &predictedVel, float dt) const { *predictedAzimuth = inputAzimuth; if (inputStatus & PlayerState::Paused) { // don't move when paused - predictedPos[0] = inputPos[0]; - predictedPos[1] = inputPos[1]; - predictedPos[2] = inputPos[2]; - predictedVel[0] = 0.0f; - predictedVel[1] = 0.0f; - predictedVel[2] = 0.0f; + predictedPos = inputPos; + predictedVel = glm::vec3(0.0f); } else if (inputStatus & PlayerState::Falling) { // no control when falling - predictedVel[0] = inputVel[0]; - predictedVel[1] = inputVel[1]; - predictedPos[0] = inputPos[0] + (dt * inputVel[0]); - predictedPos[1] = inputPos[1] + (dt * inputVel[1]); + predictedVel = inputVel; + predictedPos = inputPos + dt * predictedVel; // only turn if alive if (inputStatus & PlayerState::Alive) *predictedAzimuth += (dt * inputAngVel); // following the parabola - predictedVel[2] = inputVel[2] + (BZDBCache::gravity * dt); - predictedPos[2] = inputPos[2] + (inputVel[2] * dt) + - (0.5f * BZDBCache::gravity * dt * dt); + predictedVel[2] += BZDBCache::gravity * dt; + predictedPos[2] += 0.5f * BZDBCache::gravity * dt * dt; } else { - // velocity[2] is zero when not falling, except for Burrow flag - predictedVel[2] = inputVel[2]; - predictedPos[2] = inputPos[2] + (inputVel[2] * dt); - // different algorithms for tanks moving in // a straight line vs. turning in a circle if (!inputTurning) { - // move straight + // velocity[2] is zero when not falling, except for Burrow flag predictedVel[0] = inputRelVel[0]; predictedVel[1] = inputRelVel[1]; - predictedPos[0] = inputPos[0] + (dt * inputRelVel[0]); - predictedPos[1] = inputPos[1] + (dt * inputRelVel[1]); + predictedVel[2] = inputVel[2]; + + // move straight + predictedPos = inputPos + dt * predictedVel; } else { @@ -1169,13 +1144,18 @@ void Player::getDeadReckoning(float* predictedPos, float* predictedAzimuth, *predictedAzimuth += angle; const float cos_val = cosf(angle); const float sin_val = sinf(angle); + + // velocity[2] is zero when not falling, except for Burrow flag + const float* rv = inputRelVel; + predictedVel[0] = (rv[0] * cos_val) - (rv[1] * sin_val); + predictedVel[1] = (rv[1] * cos_val) + (rv[0] * sin_val); + predictedVel[2] = inputVel[2]; + const float* tc = inputTurnCenter; const float* tv = inputTurnVector; predictedPos[0] = tc[0] + ((tv[0] * cos_val) - (tv[1] * sin_val)); predictedPos[1] = tc[1] + ((tv[1] * cos_val) + (tv[0] * sin_val)); - const float* rv = inputRelVel; - predictedVel[0] = (rv[0] * cos_val) - (rv[1] * sin_val); - predictedVel[1] = (rv[1] * cos_val) + (rv[0] * sin_val); + predictedPos[2] = inputPos[2] + (inputVel[2] * dt); } // make the physics driver adjustments @@ -1249,8 +1229,8 @@ bool Player::isDeadReckoningWrong() const return true; // get predicted state - float predictedPos[3]; - float predictedVel[3]; + glm::vec3 predictedPos; + glm::vec3 predictedVel; float predictedAzimuth; getDeadReckoning(predictedPos, &predictedAzimuth, predictedVel, dt); @@ -1313,8 +1293,8 @@ void Player::doDeadReckoning() return; // get predicted state - float predictedPos[3]; - float predictedVel[3]; + glm::vec3 predictedPos; + glm::vec3 predictedVel; float predictedAzimuth; float dt = float(TimeKeeper::getTick() - inputTime); getDeadReckoning(predictedPos, &predictedAzimuth, predictedVel, dt); @@ -1407,11 +1387,7 @@ void Player::setDeadReckoning(float timestamp) const float dt = timestamp - inputTimestamp; inputTimestamp = timestamp; if (dt > 0.0f && dt < MaxUpdateTime * 1.5f) - { - apparentVelocity[0] = (inputPos[0] - state.pos[0]) / dt; - apparentVelocity[1] = (inputPos[1] - state.pos[1]) / dt; - apparentVelocity[2] = (inputPos[2] - state.pos[2]) / dt; - } + apparentVelocity = (inputPos - state.pos) / dt; // set the current state setDeadReckoning(); @@ -1428,8 +1404,8 @@ void Player::setDeadReckoning() inputStatus = state.status; inputAzimuth = state.azimuth; inputAngVel = state.angVel; - memcpy(inputPos, state.pos, sizeof(float[3])); - memcpy(inputVel, state.velocity, sizeof(float[3])); + inputPos = state.pos; + inputVel = state.velocity; inputPhyDrv = state.phydrv; // @@ -1454,10 +1430,10 @@ void Player::setDeadReckoning() return; } -void Player::setExplodePos( const float * p) +void Player::setExplodePos(const glm::vec3 &p) { if (tankNode) - tankNode->explodePos = fvec3(p[0],p[1],p[2]); + tankNode->explodePos = p; } diff --git a/src/bzflag/Player.h b/src/bzflag/Player.h index 6b009718d4..a52bcb7020 100644 --- a/src/bzflag/Player.h +++ b/src/bzflag/Player.h @@ -17,6 +17,9 @@ /* system headers */ #include +#include +#include +#include /* common interface headers */ #include "global.h" @@ -75,16 +78,16 @@ class Player FlagType* getFlag() const; long getOrder() const; short getStatus() const; - const float* getPosition() const; + const glm::vec3 &getPosition() const; float getAngle() const; - const float* getForward() const; - const float* getVelocity() const; + const glm::vec3 &getForward() const; + const glm::vec3 &getVelocity() const; float getAngularVelocity() const; int getPhysicsDriver() const; int getDeathPhysicsDriver() const; float getRadius() const; - void getMuzzle(float*) const; + glm::vec3 getMuzzle() const; float getMuzzleHeight() const; short getWins() const; short getLosses() const; @@ -95,10 +98,10 @@ class Player short getScore() const; const float* getDimensions() const; - const float* getApparentVelocity() const; + const glm::vec3 &getApparentVelocity() const; #ifndef BUILDING_BZADMIN - inline const float* getColor() const + inline const glm::vec4 &getColor() const { return color; } @@ -169,8 +172,8 @@ class Player void doDeadReckoning(); // called to update state according to incoming packets - void move(const float* pos, float azimuth); - void setVelocity(const float* velocity); + void move(const glm::vec3 &pos, float azimuth); + void setVelocity(const glm::vec3 &velocity); void setAngularVelocity(float); void setPhysicsDriver(int); void setRelativeMotion(); @@ -202,7 +205,7 @@ class Player void renderRadar() const; - void setExplodePos( const float * p); + void setExplodePos(const glm::vec3 &p); void setZpos (float z); @@ -237,9 +240,9 @@ class Player // was already terminated. position must be set to the shot's // position if you return true (it's okay to return false if // there's no meaningful shot position). - virtual bool doEndShot(int index, bool isHit, float* position) = 0; - void getDeadReckoning(float* predictedPos, float* predictedAzimuth, - float* predictedVel, float time) const; + virtual bool doEndShot(int index, bool isHit, glm::vec3 &position) = 0; + void getDeadReckoning(glm::vec3 &predictedPos, float* predictedAzimuth, + glm::vec3 &predictedVel, float time) const; void calcRelativeMotion(float vel[2], float& speed, float& angvel); void setVisualTeam (TeamColor team ); void updateFlagEffect(FlagType* flag); @@ -269,7 +272,7 @@ class Player TankIDLSceneNode* tankIDLNode; SphereSceneNode* pausedSphere; #ifndef BUILDING_BZADMIN - GLfloat color[4]; + glm::vec4 color; GLfloat teleAlpha; #endif std::string userTexture; @@ -288,9 +291,9 @@ class Player // relatively stable data FlagType* flagType; // flag type I'm holding float dimensions[3]; // current tank dimensions - float dimensionsScale[3]; // use to scale the dimensions + glm::vec3 dimensionsScale; // use to scale the dimensions float dimensionsRate[3]; // relative to scale - float dimensionsTarget[3]; // relative to scale + glm::vec3 dimensionsTarget; // relative to scale bool useDimensions; // use the varying dimensions for gfx float alpha; // current tank translucency float alphaRate; // current tank translucency @@ -318,20 +321,20 @@ class Player bool autoPilot; // computable highly dynamic data - float forward[3]; // forward unit vector + glm::vec3 forward; // forward unit vector // relative motion information float relativeSpeed; // relative speed float relativeAngVel; // relative angular velocity - float apparentVelocity[3]; // velocity of tank as derived from it's last positional update + glm::vec3 apparentVelocity; // velocity of tank as derived from it's last positional update // dead reckoning stuff TimeKeeper inputTime; // time of input float inputTimestamp; // input timestamp of sender int inputStatus; // tank status - float inputPos[3]; // tank position - float inputVel[3]; // tank velocity + glm::vec3 inputPos; // tank position + glm::vec3 inputVel; // tank velocity float inputAzimuth; // direction tank is pointing float inputAngVel; // tank turn rate bool inputTurning; // tank is turning @@ -408,7 +411,7 @@ inline short Player::getStatus() const return state.status; } -inline const float* Player::getPosition() const +inline const glm::vec3 &Player::getPosition() const { return state.pos; } @@ -423,17 +426,17 @@ inline const float* Player::getDimensions() const return dimensions; } -inline const float* Player::getForward() const +inline const glm::vec3 &Player::getForward() const { return forward; } -inline const float* Player::getVelocity() const +inline const glm::vec3 &Player::getVelocity() const { return state.velocity; } -inline const float* Player::getApparentVelocity() const +inline const glm::vec3 &Player::getApparentVelocity() const { return apparentVelocity; } diff --git a/src/bzflag/RadarRenderer.cxx b/src/bzflag/RadarRenderer.cxx index 8bd314c0f1..0f36fced34 100644 --- a/src/bzflag/RadarRenderer.cxx +++ b/src/bzflag/RadarRenderer.cxx @@ -27,6 +27,7 @@ #include "BoxBuilding.h" #include "PyramidBuilding.h" #include "MeshObstacle.h" +#include "OpenGLAPI.h" // local implementation headers #include "LocalPlayer.h" @@ -66,12 +67,9 @@ void RadarRenderer::setWorld(World* _world) } -void RadarRenderer::setControlColor(const GLfloat *color) +void RadarRenderer::setControlColor(const glm::vec3 &color) { - if (color) - memcpy(teamColor, color, 3 * sizeof(float)); - else - memset(teamColor, 0, 3 * sizeof(float)); + teamColor = color; } @@ -115,22 +113,19 @@ void RadarRenderer::setTankColor(const Player* player) { const float dimfactor = 0.4f; - const float *color; + glm::vec3 color; if (myTank->getFlag() == Flags::Colorblindness) color = Team::getRadarColor(RogueTeam); else color = Team::getRadarColor(player->getTeam()); - float dimmedcolor[3]; - dimmedcolor[0] = color[0] * dimfactor; - dimmedcolor[1] = color[1] * dimfactor; - dimmedcolor[2] = color[2] * dimfactor; - glColor3fv(dimmedcolor); + const auto dimmedcolor = color * dimfactor; + glColor(dimmedcolor); } else { - glColor3fv(Team::getRadarColor(myTank->getFlag() == - Flags::Colorblindness ? RogueTeam : player->getTeam())); + glColor(Team::getRadarColor(myTank->getFlag() == + Flags::Colorblindness ? RogueTeam : player->getTeam())); } // If this tank is hunted flash it on the radar if (player->isHunted() && myTank->getFlag() != Flags::Colorblindness) @@ -154,8 +149,17 @@ void RadarRenderer::setTankColor(const Player* player) } } -void RadarRenderer::drawTank(const float pos[3], const Player* player, bool useSquares) +void RadarRenderer::drawTank(const glm::vec3 &pos, const Player* player, bool useSquares) { + auto flag = player->getFlag(); + + // my flag + if (flag != Flags::Null) + { + glColor(flag->getRadarColor()); + drawFlagOnTank(); + } + // 'ps' is pixel scale, setup in render() const float tankRadius = BZDBCache::tankRadius; float minSize = 1.5f + (ps * BZDBCache::radarTankPixels); @@ -249,7 +253,7 @@ void RadarRenderer::drawFancyTank(const Player* player) } -void RadarRenderer::drawFlag(const float pos[3]) +void RadarRenderer::drawFlag(const glm::vec3 &pos) { GLfloat s = BZDBCache::flagRadius > 3.0f * ps ? BZDBCache::flagRadius : 3.0f * ps; glBegin(GL_LINES); @@ -321,7 +325,7 @@ void RadarRenderer::renderFrame(SceneRenderer& renderer) if (BZDBCache::blend) glEnable(GL_BLEND); - glColor4f(teamColor[0],teamColor[1],teamColor[2],outlineOpacity); + glColor(teamColor, outlineOpacity); glBegin(GL_LINE_LOOP); { @@ -335,7 +339,7 @@ void RadarRenderer::renderFrame(SceneRenderer& renderer) if (BZDBCache::blend) glDisable(GL_BLEND); - glColor4f(teamColor[0],teamColor[1],teamColor[2],1.0f); + glColor(teamColor); const float opacity = renderer.getRadarOpacity(); if ((opacity < 1.0f) && (opacity > 0.0f)) @@ -538,7 +542,7 @@ void RadarRenderer::render(SceneRenderer& renderer, bool blank, bool observer) useTankModels = false; // relative to my tank - const float* myPos = myTank->getPosition(); + const auto &myPos = myTank->getPosition(); const float myAngle = myTank->getAngle(); // draw the view angle below stuff @@ -627,19 +631,13 @@ void RadarRenderer::render(SceneRenderer& renderer, bool blank, bool observer) (myTank->getFlag() != Flags::Seer)) continue; - const float* position = player->getPosition(); + const auto &position = player->getPosition(); glPushMatrix(); // transform to the tanks location glTranslatef(position[0], position[1], 0.0f); - if (player->getFlag() != Flags::Null) - { - glColor3fv(player->getFlag()->getRadarColor()); - drawFlagOnTank(); - } - if (!observer) drawTank(position, player, true); else @@ -664,12 +662,12 @@ void RadarRenderer::render(SceneRenderer& renderer, bool blank, bool observer) const float cs = colorScale(shot->getPosition()[2], muzzleHeight); if (coloredShot) { - const float *shotcolor; + glm::vec3 shotcolor; if (myTank->getFlag() == Flags::Colorblindness) shotcolor = Team::getRadarColor(RogueTeam); else shotcolor = Team::getRadarColor(player->getTeam()); - glColor3f(shotcolor[0] * cs, shotcolor[1] * cs, shotcolor[2] * cs); + glColor(shotcolor * cs); } else glColor3f(cs, cs, cs); @@ -706,17 +704,17 @@ void RadarRenderer::render(SceneRenderer& renderer, bool blank, bool observer) } // Flags change color by height const float cs = colorScale(flag.position[2], muzzleHeight); - const float *flagcolor = flag.type->getRadarColor(); - glColor3f(flagcolor[0] * cs, flagcolor[1] * cs, flagcolor[2] * cs); + const auto &flagcolor = flag.type->getRadarColor(); + glColor(flagcolor * cs); drawFlag(flag.position); } // draw antidote flag - const float* antidotePos = + const auto *antidotePos = LocalPlayer::getMyTank()->getAntidoteLocation(); if (antidotePos) { glColor3f(1.0f, 1.0f, 0.0f); - drawFlag(antidotePos); + drawFlag(*antidotePos); } // draw these markers above all others always centered @@ -748,13 +746,6 @@ void RadarRenderer::render(SceneRenderer& renderer, bool blank, bool observer) glPushMatrix(); - // my flag - if (myTank->getFlag() != Flags::Null) - { - glColor3fv(myTank->getFlag()->getRadarColor()); - drawFlagOnTank(); - } - // my tank drawTank(myPos, myTank, false); @@ -876,7 +867,7 @@ void RadarRenderer::renderWalls() const float wid = wall.getBreadth(); const float c = wid * cosf(wall.getRotation()); const float s = wid * sinf(wall.getRotation()); - const float* pos = wall.getPosition(); + const auto &pos = wall.getPosition(); glVertex2f(pos[0] - s, pos[1] + c); glVertex2f(pos[0] + s, pos[1] - c); } @@ -1019,7 +1010,7 @@ void RadarRenderer::renderBoxPyrMesh() const float s = sinf(box.getRotation()); const float wx = c * box.getWidth(), wy = s * box.getWidth(); const float hx = -s * box.getBreadth(), hy = c * box.getBreadth(); - const float* pos = box.getPosition(); + const auto &pos = box.getPosition(); glBegin(GL_TRIANGLE_STRIP); glVertex2f(pos[0] - wx - hx, pos[1] - wy - hy); glVertex2f(pos[0] + wx - hx, pos[1] + wy - hy); @@ -1042,7 +1033,7 @@ void RadarRenderer::renderBoxPyrMesh() const float s = sinf(pyr.getRotation()); const float wx = c * pyr.getWidth(), wy = s * pyr.getWidth(); const float hx = -s * pyr.getBreadth(), hy = c * pyr.getBreadth(); - const float* pos = pyr.getPosition(); + const auto &pos = pyr.getPosition(); glBegin(GL_TRIANGLE_STRIP); glVertex2f(pos[0] - wx - hx, pos[1] - wy - hy); glVertex2f(pos[0] + wx - hx, pos[1] + wy - hy); @@ -1095,8 +1086,8 @@ void RadarRenderer::renderBoxPyrMesh() glBegin(GL_TRIANGLE_FAN); for (int v = 0; v < vertexCount; v++) { - const float* pos = face->getVertex(v); - glVertex2f(pos[0], pos[1]); + const glm::vec2 pos = face->getVertex(v); + glVertex(pos); } glEnd(); } @@ -1128,7 +1119,7 @@ void RadarRenderer::renderBoxPyrMesh() const float s = sinf(box.getRotation()); const float wx = c * box.getWidth(), wy = s * box.getWidth(); const float hx = -s * box.getBreadth(), hy = c * box.getBreadth(); - const float* pos = box.getPosition(); + const auto &pos = box.getPosition(); glBegin(GL_LINE_LOOP); glVertex2f(pos[0] - wx - hx, pos[1] - wy - hy); glVertex2f(pos[0] + wx - hx, pos[1] + wy - hy); @@ -1149,7 +1140,7 @@ void RadarRenderer::renderBoxPyrMesh() const float s = sinf(pyr.getRotation()); const float wx = c * pyr.getWidth(), wy = s * pyr.getWidth(); const float hx = -s * pyr.getBreadth(), hy = c * pyr.getBreadth(); - const float* pos = pyr.getPosition(); + const auto &pos = pyr.getPosition(); glBegin(GL_LINE_LOOP); glVertex2f(pos[0] - wx - hx, pos[1] - wy - hy); glVertex2f(pos[0] + wx - hx, pos[1] + wy - hy); @@ -1174,21 +1165,25 @@ void RadarRenderer::renderBasesAndTeles() { for (int j = 0;; j++) { - const float *base = world->getBase(i, j); - if (base == NULL) + glm::vec3 basePos; + float rotation; + float ww, bb, hh; + const bool baseExist = world->getBase(i, j, basePos, rotation, + ww, bb, hh); + if (!baseExist) break; - glColor3fv(Team::getRadarColor(TeamColor(i))); + glColor(Team::getRadarColor(TeamColor(i))); glBegin(GL_LINE_LOOP); - const float beta = atan2f(base[5], base[4]); - const float r = hypotf(base[4], base[5]); - glVertex2f(base[0] + r * cosf(base[3] + beta), - base[1] + r * sinf(base[3] + beta)); - glVertex2f(base[0] + r * cosf((float)(base[3] - beta + M_PI)), - base[1] + r * sinf((float)(base[3] - beta + M_PI))); - glVertex2f(base[0] + r * cosf((float)(base[3] + beta + M_PI)), - base[1] + r * sinf((float)(base[3] + beta + M_PI))); - glVertex2f(base[0] + r * cosf(base[3] - beta), - base[1] + r * sinf(base[3] - beta)); + const float beta = atan2f(bb, ww); + const float r = hypotf(ww, bb); + glVertex2f(basePos.x + r * cosf(rotation + beta), + basePos.y + r * sinf(rotation + beta)); + glVertex2f(basePos.x + r * cosf((float)(rotation - beta + M_PI)), + basePos.y + r * sinf((float)(rotation - beta + M_PI))); + glVertex2f(basePos.x + r * cosf((float)(rotation + beta + M_PI)), + basePos.y + r * sinf((float)(rotation + beta + M_PI))); + glVertex2f(basePos.x + r * cosf(rotation - beta), + basePos.y + r * sinf(rotation - beta)); glEnd(); } } @@ -1216,7 +1211,7 @@ void RadarRenderer::renderBasesAndTeles() const float s = sinf (tele.getRotation ()); const float wx = c * tele.getWidth (), wy = s * tele.getWidth (); const float hx = -s * tele.getBreadth (), hy = c * tele.getBreadth (); - const float *pos = tele.getPosition (); + const auto &pos = tele.getPosition (); glVertex2f (pos[0] - wx - hx, pos[1] - wy - hy); glVertex2f (pos[0] + wx - hx, pos[1] + wy - hy); @@ -1241,7 +1236,7 @@ void RadarRenderer::renderBasesAndTeles() const float tw = tele.getBreadth (); const float c = tw * cosf (tele.getRotation ()); const float s = tw * sinf (tele.getRotation ()); - const float *pos = tele.getPosition (); + const auto &pos = tele.getPosition (); glVertex2f (pos[0] - s, pos[1] + c); glVertex2f (pos[0] + s, pos[1] - c); glVertex2f (pos[0] + s, pos[1] - c); diff --git a/src/bzflag/RadarRenderer.h b/src/bzflag/RadarRenderer.h index be7eab9f5e..38361d86b8 100644 --- a/src/bzflag/RadarRenderer.h +++ b/src/bzflag/RadarRenderer.h @@ -33,7 +33,7 @@ class RadarRenderer RadarRenderer(const SceneRenderer&, World* _world); void setWorld(World* _world); - void setControlColor(const GLfloat *color = NULL); + void setControlColor(const glm::vec3 &color = glm::vec3(0.0f)); int getX() const; int getY() const; @@ -63,11 +63,11 @@ class RadarRenderer RadarRenderer& operator=(const RadarRenderer&); void setTankColor(const class Player* player); - void drawTank(const float pos[3], + void drawTank(const glm::vec3 &pos, const class Player* player, bool useSquares); void drawFancyTank(const class Player* player); - void drawFlag(const float pos[3]); + void drawFlag(const glm::vec3 &pos); void drawFlagOnTank(); static float colorScale(const float z, const float h); @@ -81,7 +81,7 @@ class RadarRenderer float ps; float range; double decay; - GLfloat teamColor[3]; + glm::vec3 teamColor; bool smooth; bool jammed; bool useTankModels; diff --git a/src/bzflag/Region.cxx b/src/bzflag/Region.cxx index 6fd1aa583f..8fec8e3cf4 100644 --- a/src/bzflag/Region.cxx +++ b/src/bzflag/Region.cxx @@ -16,6 +16,8 @@ /* system implementation headers */ #include #include +#define GLM_ENABLE_EXPERIMENTAL +#include RegionPoint::RegionPoint(float x, float y) @@ -24,10 +26,9 @@ RegionPoint::RegionPoint(float x, float y) p[1] = y; } -RegionPoint::RegionPoint(const float v[2]) +RegionPoint::RegionPoint(const glm::vec2 &v) { - p[0] = v[0]; - p[1] = v[1]; + p = v; } RegionPoint::~RegionPoint() @@ -35,7 +36,7 @@ RegionPoint::~RegionPoint() // do nothing } -const float* RegionPoint::get() const +const glm::vec2 &RegionPoint::get() const { return p; } @@ -52,7 +53,7 @@ BzfRegion::BzfRegion() : mailbox(0), target(0), distance(0.0), A(0.0, 0.0) { } -BzfRegion::BzfRegion(int sides, const float p[][2]) : +BzfRegion::BzfRegion(int sides, const glm::vec2 p[]) : mailbox(0), target(0), distance(), A(0.0, 0.0) { for (int i = 0; i < sides; i++) @@ -71,14 +72,14 @@ BzfRegion::~BzfRegion() neighbors[i]->setNeighbor(this, 0); } -bool BzfRegion::isInside(const float p[2]) const +bool BzfRegion::isInside(const glm::vec2 &p) const { // see if testPoint is inside my edges const int count = corners.size(); if (count < 3) return false; bool inside = false; - const float* p1 = corners[count - 1].get(); - const float* p2 = NULL; + auto p1 = corners[count - 1].get(); + glm::vec2 p2; for (int i = 0; i < count; p1 = p2, i++) { p2 = corners[i].get(); @@ -98,52 +99,45 @@ bool BzfRegion::isInside(const float p[2]) const return inside; } -float BzfRegion::getDistance(const float p[2], float nearest[2]) const +float BzfRegion::getDistance(const glm::vec2 &p, glm::vec2 &nearest) const { const int count = corners.size(); float currentDistance = maxDistance; float pointDistance; //compute distance from any edge - const float* p1 = corners[count - 1].get(); - const float* p2 = NULL; - float d[2]; - float m[2]; + auto p1 = corners[count - 1].get(); + glm::vec2 d; + glm::vec2 m; float t; float edgeSquareDist; - float x, y; + glm::vec2 temp; for (int c = 0; c < count; c++) { - p2 = corners[c].get(); - d[0] = p2[0] - p1[0]; - d[1] = p2[1] - p1[1]; - m[0] = p[0] - p1[0]; - m[1] = p[1] - p1[1]; - edgeSquareDist = d[0] * d[0] + d[1] * d[1]; - t = (m[0] * d[0] + m[1] * d[1]) / edgeSquareDist; + const auto p2 = corners[c].get(); + d = p2 - p1; + m = p - p1; + edgeSquareDist = glm::length2(d); + t = glm::dot(m, d) / edgeSquareDist; if (t <= 0) { - pointDistance = hypotf(m[0], m[1]); - x = p1[0]; - y = p1[1]; + pointDistance = glm::length(m); + temp = p1; } else if (t >= 1) { - pointDistance = hypotf(m[0] - d[0], m[1] - d[1]); - x = p2[0]; - y = p2[1]; + pointDistance = glm::distance(m, d); + temp = p2; } else { - pointDistance = hypotf(m[0] - t * d[0], m[1] - t * d[1]); - x = p1[0] + t * d[0]; - y = p1[1] + t * d[1]; + pointDistance = glm::distance(m, t * d); + temp = p1 + t * d; } if (pointDistance < currentDistance) { currentDistance = pointDistance; - nearest[0] = x; - nearest[1] = y; + nearest = temp; } p1 = p2; } @@ -160,7 +154,7 @@ int BzfRegion::classify(const float e1[2], const float e2[2]) const const int count = corners.size(); for (int i = 0; i < count; i++) { - const float* p = corners[i].get(); + const auto &p = corners[i].get(); const float e = -dy * p[0] + dx * p[1] + d; if (e < -0.00001) toRight++; else if (e <= 0.00001) onEdge++; @@ -198,7 +192,7 @@ BzfRegion* BzfRegion::orphanSplitRegion(const float e1[2], const float e2[2]) const float dx = e2[0] - e1[0]; const float dy = e2[1] - e1[1]; const float d = dy * e1[0] - dx * e1[1]; - const float* p1 = corners[0].get(); + auto p1 = corners[0].get(); // Vector Product between splitter and corner : to know if right or left float lastPVect = d - dy * p1[0] + dx * p1[1]; @@ -208,7 +202,7 @@ BzfRegion* BzfRegion::orphanSplitRegion(const float e1[2], const float e2[2]) bool fistCornerRight = lastSign; for (i = 0; split < 2 && i < count; i++) { - const float* p2 = corners[(i + 1) % count].get(); + const auto &p2 = corners[(i + 1) % count].get(); const float pVect = d - dy * p2[0] + dx * p2[1]; const bool newSign = (pVect >= 0); @@ -248,13 +242,11 @@ BzfRegion* BzfRegion::orphanSplitRegion(const float e1[2], const float e2[2]) // make new corners and region p1 = corners[edge[1]].get(); - const float* p2 = corners[(edge[1]+1) % count].get(); - RegionPoint n2(p1[0] + tsplit[1] * (p2[0] - p1[0]), - p1[1] + tsplit[1] * (p2[1] - p1[1])); + auto p2 = corners[(edge[1]+1) % count].get(); + RegionPoint n2(p1 + tsplit[1] * (p2 - p1)); p1 = corners[edge[0]].get(); p2 = corners[(edge[0]+1) % count].get(); - RegionPoint n1(p1[0] + tsplit[0] * (p2[0] - p1[0]), - p1[1] + tsplit[0] * (p2[1] - p1[1])); + RegionPoint n1(p1 + tsplit[0] * (p2 - p1)); BzfRegion* newRegion = new BzfRegion; // add sides to new region and remove them from me. the new region @@ -371,8 +363,8 @@ void BzfRegion::tidy() int count = corners.size(); for (int i = 0; i < count; i++) { - const float* p1 = corners[i].get(); - const float* p2 = corners[(i+1)%count].get(); + const auto &p1 = corners[i].get(); + const auto &p2 = corners[(i+1)%count].get(); if (fabs(p1[0] - p2[0]) < ZERO_TOLERANCE && fabs(p1[1] - p2[1]) < ZERO_TOLERANCE) { std::vector::iterator it1 = corners.begin(); @@ -394,7 +386,7 @@ bool BzfRegion::test(int mailboxIndex) const void BzfRegion::setPathStuff(float _distance, BzfRegion* _target, - const float _a[2], int mailboxIndex) + const glm::vec2 &_a, int mailboxIndex) { distance = _distance; target = _target; @@ -412,7 +404,7 @@ BzfRegion* BzfRegion::getTarget() const return target; } -const float* BzfRegion::getA() const +const glm::vec2 &BzfRegion::getA() const { return A.get(); } diff --git a/src/bzflag/Region.h b/src/bzflag/Region.h index 7dd5405e1e..00399b5fa6 100644 --- a/src/bzflag/Region.h +++ b/src/bzflag/Region.h @@ -13,10 +13,12 @@ #ifndef __REGION_H__ #define __REGION_H__ +// 1st #include "common.h" /* system interface headers */ #include +#include const float maxDistance = 1.0e6; @@ -25,25 +27,25 @@ class RegionPoint { public: RegionPoint(float x, float y); - RegionPoint(const float v[2]); + RegionPoint(const glm::vec2 &v); ~RegionPoint(); - const float* get() const; + const glm::vec2 &get() const; private: - float p[2]; + glm::vec2 p; }; class BzfRegion { public: - BzfRegion(int sides, const float p[][2]); + BzfRegion(int sides, const glm::vec2 p[2]); ~BzfRegion(); - bool isInside(const float p[2]) const; + bool isInside(const glm::vec2 &p) const; // get point distance from Region. Point should be outside Region! - float getDistance(const float p[2], float nearest[2]) const; + float getDistance(const glm::vec2 &p, glm::vec2 &nearest) const; int classify(const float p1[2], const float p2[2]) const; BzfRegion* orphanSplitRegion(const float p1[2], const float p2[2]); @@ -53,10 +55,10 @@ class BzfRegion bool test(int mailboxIndex) const; void setPathStuff(float distance, BzfRegion* target, - const float p[2], int mailboxIndex); + const glm::vec2 &p, int mailboxIndex); float getDistance() const; BzfRegion* getTarget() const; - const float* getA() const; + const glm::vec2 &getA() const; protected: BzfRegion(); diff --git a/src/bzflag/RemotePlayer.cxx b/src/bzflag/RemotePlayer.cxx index 9f8d49a300..37d0136502 100644 --- a/src/bzflag/RemotePlayer.cxx +++ b/src/bzflag/RemotePlayer.cxx @@ -37,8 +37,8 @@ RemotePlayer::~RemotePlayer() void RemotePlayer::addShot(const FiringInfo& info) { - float newpos[3]; - const float *f = getForward(); + glm::vec3 newpos; + const auto &f = getForward(); RemoteShotPath* newShot = new RemoteShotPath(info); int shotNum = int(newShot->getShotId() & 255); @@ -48,11 +48,9 @@ void RemotePlayer::addShot(const FiringInfo& info) shots[shotNum] = newShot; // Update tanks position and set dead reckoning for better lag handling // shot origin is center of tank for shockwave + newpos = info.shot.pos; if (info.flagType == Flags::ShockWave) { - newpos[0] = info.shot.pos[0]; - newpos[1] = info.shot.pos[1]; - newpos[2] = info.shot.pos[2]; } // shot origin is muzzle for other shots else @@ -61,9 +59,9 @@ void RemotePlayer::addShot(const FiringInfo& info) if (info.flagType == Flags::Obesity) front *= BZDB.eval(StateDatabase::BZDB_OBESEFACTOR); else if (info.flagType == Flags::Tiny) front *= BZDB.eval(StateDatabase::BZDB_TINYFACTOR); else if (info.flagType == Flags::Thief) front *= BZDB.eval(StateDatabase::BZDB_THIEFTINYFACTOR); - newpos[0] = info.shot.pos[0] - (front * f[0]); - newpos[1] = info.shot.pos[1] - (front * f[1]); - newpos[2] = info.shot.pos[2] - BZDB.eval(StateDatabase::BZDB_MUZZLEHEIGHT); + newpos[0] -= front * f[0]; + newpos[1] -= front * f[1]; + newpos[2] -= BZDB.eval(StateDatabase::BZDB_MUZZLEHEIGHT); } shotStatistics.recordFire(info.flagType,f,info.shot.vel); // FIXME - with dynamic dimensions, this may not be a good idea @@ -85,7 +83,7 @@ ShotPath* RemotePlayer::getShot(int index) const } bool RemotePlayer::doEndShot( - int ident, bool isHit, float* pos) + int ident, bool isHit, glm::vec3 &pos) { const int index = ident & 255; const int salt = (ident >> 8) & 127; @@ -118,10 +116,8 @@ bool RemotePlayer::doEndShot( return false; // end it - const float* shotPos = shots[index]->getPosition(); - pos[0] = shotPos[0]; - pos[1] = shotPos[1]; - pos[2] = shotPos[2]; + const auto &shotPos = shots[index]->getPosition(); + pos = shotPos; shots[index]->setExpired(); return true; } diff --git a/src/bzflag/RemotePlayer.h b/src/bzflag/RemotePlayer.h index 1db4a0cb49..745a5613fb 100644 --- a/src/bzflag/RemotePlayer.h +++ b/src/bzflag/RemotePlayer.h @@ -13,8 +13,6 @@ #ifndef __REMOTEPLAYER_H__ #define __REMOTEPLAYER_H__ -#include "common.h" - /* interface header */ #include "Player.h" @@ -35,11 +33,11 @@ class RemotePlayer : public Player ~RemotePlayer(); void addShot(const FiringInfo&); - ShotPath* getShot(int index) const; + ShotPath* getShot(int index) const override; void updateShots(float dt); private: - bool doEndShot(int index, bool isHit, float* pos); + bool doEndShot(int index, bool isHit, glm::vec3 &pos) override; private: int numShots; diff --git a/src/bzflag/Roaming.cxx b/src/bzflag/Roaming.cxx index 2d6480122c..183e5dbd22 100644 --- a/src/bzflag/Roaming.cxx +++ b/src/bzflag/Roaming.cxx @@ -332,7 +332,7 @@ void Roaming::updatePosition(RoamingCamera* dc, float dt) // are we tracking? bool tracking = false; - const float* trackPos; + glm::vec3 trackPos; if (view == roamViewTrack) { Player *target; diff --git a/src/bzflag/Roaming.h b/src/bzflag/Roaming.h index 0c745fab91..6551d4f593 100644 --- a/src/bzflag/Roaming.h +++ b/src/bzflag/Roaming.h @@ -68,7 +68,7 @@ class Roaming : public Singleton struct RoamingCamera { - float pos[3]; + glm::vec3 pos; float theta; float phi; float zoom; diff --git a/src/bzflag/RobotPlayer.cxx b/src/bzflag/RobotPlayer.cxx index aada998992..c67ac68197 100644 --- a/src/bzflag/RobotPlayer.cxx +++ b/src/bzflag/RobotPlayer.cxx @@ -41,41 +41,32 @@ RobotPlayer::RobotPlayer(const PlayerId& _id, const char* _name, } // estimate a player's position at now+t, similar to dead reckoning -void RobotPlayer::projectPosition(const Player *targ,const float t,float &x,float &y,float &z) const +void RobotPlayer::projectPosition(const Player *targ, const float t, glm::vec3 &tPos) const { - double hisx=targ->getPosition()[0]; - double hisy=targ->getPosition()[1]; - double hisz=targ->getPosition()[2]; - double hisvx=targ->getVelocity()[0]; - double hisvy=targ->getVelocity()[1]; - double hisvz=targ->getVelocity()[2]; + auto his = targ->getPosition(); + auto hisv = targ->getVelocity(); double omega=fabs(targ->getAngularVelocity()); - double sx,sy; - if ((targ->getStatus() & PlayerState::Falling) || fabs(omega) < 2*M_PI / 360 * 0.5) - { - sx=t*hisvx; - sy=t*hisvy; - } + tPos = his; + if ((targ->getStatus() & PlayerState::Falling) || omega < 2*M_PI / 360 * 0.5) + tPos += hisv * t; else { - double hisspeed = hypotf(hisvx, hisvy); + double hisspeed = glm::length(glm::vec2(hisv)); double alfa = omega * t; double r = hisspeed / fabs(omega); double dx = r * sin(alfa); double dy2 = r * (1 - cos(alfa)); double beta = atan2(dy2, dx) * (targ->getAngularVelocity() > 0 ? 1 : -1); - double gamma = atan2(hisvy, hisvx); + double gamma = atan2(hisv.y, hisv.x); double rho = gamma+beta; - sx = hisspeed * t * cos(rho); - sy = hisspeed * t * sin(rho); + tPos.x += hisspeed * t * cos(rho); + tPos.y += hisspeed * t * sin(rho); + tPos.z += hisv.z * t; } - x=(float)hisx+(float)sx; - y=(float)hisy+(float)sy; - z=(float)hisz+(float)hisvz*t; if (targ->getStatus() & PlayerState::Falling) - z += 0.5f * BZDBCache::gravity * t * t; - if (z < 0) z = 0; + tPos.z += 0.5f * BZDBCache::gravity * t * t; + if (tPos.z < 0) tPos.z = 0; } @@ -83,43 +74,34 @@ void RobotPlayer::projectPosition(const Player *targ,const float t,float &x,floa // 1. estimate how long it will take shot to hit target // 2. calc position of target at that point of time // 3. jump to 1., using projected position, loop until result is stable -void RobotPlayer::getProjectedPosition(const Player *targ, float *projpos) const +void RobotPlayer::getProjectedPosition(const Player *targ, glm::vec3 &projpos) const { - double myx = getPosition()[0]; - double myy = getPosition()[1]; - double hisx = targ->getPosition()[0]; - double hisy = targ->getPosition()[1]; - double deltax = hisx - myx; - double deltay = hisy - myy; - double distance = hypotf(deltax,deltay) - BZDB.eval(StateDatabase::BZDB_MUZZLEFRONT) - BZDBCache::tankRadius; + const auto my = glm::vec2(getPosition()); + const auto his = glm::vec2(targ->getPosition()); + double distance = glm::distance(his, my) - BZDB.eval(StateDatabase::BZDB_MUZZLEFRONT) - BZDBCache::tankRadius; if (distance <= 0) distance = 0; + const auto myVel = glm::vec2(getVelocity()); double shotspeed = BZDB.eval(StateDatabase::BZDB_SHOTSPEED)* (getFlag() == Flags::Laser ? BZDB.eval(StateDatabase::BZDB_LASERADVEL) : getFlag() == Flags::RapidFire ? BZDB.eval(StateDatabase::BZDB_RFIREADVEL) : getFlag() == Flags::MachineGun ? BZDB.eval(StateDatabase::BZDB_MGUNADVEL) : 1) + - hypotf(getVelocity()[0], getVelocity()[1]); + glm::length(myVel); double errdistance = 1.0; - float tx, ty, tz; + glm::vec3 tPos; for (int tries=0 ; errdistance > 0.05 && tries < 4 ; tries++) { float t = (float)distance / (float)shotspeed; - projectPosition(targ, t + 0.05f, tx, ty, tz); // add 50ms for lag - double distance2 = hypotf(tx - myx, ty - myy); + projectPosition(targ, t + 0.05f, tPos); // add 50ms for lag + double distance2 = glm::distance(glm::vec2(tPos), my); errdistance = fabs(distance2-distance) / (distance + ZERO_TOLERANCE); distance = distance2; } - projpos[0] = tx; - projpos[1] = ty; - projpos[2] = tz; + projpos = tPos; // projected pos in building -> use current pos - if (World::getWorld()->inBuilding(projpos, 0.0f, BZDBCache::tankHeight)) - { - projpos[0] = targ->getPosition()[0]; - projpos[1] = targ->getPosition()[1]; - projpos[2] = targ->getPosition()[2]; - } + if (World::getWorld()->inBuilding(projpos, 0.0f, BZDBCache::tankHeight, 0.0f)) + projpos = targ->getPosition(); } @@ -144,9 +126,9 @@ void RobotPlayer::doUpdate(float dt) // Allow shooting only if angle is near and timer has elapsed if ((!path.empty()) && timerForShot <= 0.0f) { - float p1[3]; + glm::vec3 p1; getProjectedPosition(target, p1); - const float* p2 = getPosition(); + const auto &p2 = getPosition(); float shootingAngle = atan2f(p1[1] - p2[1], p1[0] - p2[0]); if (shootingAngle < 0.0f) shootingAngle += (float)(2.0 * M_PI); @@ -165,10 +147,10 @@ void RobotPlayer::doUpdate(float dt) if (missby < 0.5f * BZDBCache::tankLength && p1[2] < shotRadius) { - float pos[3] = {getPosition()[0], getPosition()[1], - getPosition()[2] + BZDB.eval(StateDatabase::BZDB_MUZZLEHEIGHT) - }; - float dir[3] = {cosf(azimuth), sinf(azimuth), 0.0f}; + auto pos = glm::vec3(getPosition()[0], getPosition()[1], + getPosition()[2] + BZDB.eval(StateDatabase::BZDB_MUZZLEHEIGHT) + ); + auto dir = glm::vec3(cosf(azimuth), sinf(azimuth), 0.0f); Ray tankRay(pos, dir); float maxdistance = targetdistance; if (!ShotStrategy::getFirstBuilding(tankRay, -0.5f, maxdistance)) @@ -184,10 +166,7 @@ void RobotPlayer::doUpdate(float dt) p = LocalPlayer::getMyTank(); if (!p || p->getId() == getId() || validTeamTarget(p) || !p->isAlive()) continue; - float relpos[3] = {getPosition()[0] - p->getPosition()[0], - getPosition()[1] - p->getPosition()[1], - getPosition()[2] - p->getPosition()[2] - }; + auto relpos = getPosition() - p->getPosition(); Ray ray(relpos, dir); float impact = rayAtDistanceFromOrigin(ray, 5 * BZDBCache::tankRadius); if (impact > 0 && impact < shotRange) @@ -214,11 +193,8 @@ void RobotPlayer::doUpdateMotion(float dt) bool evading = false; // record previous position const float oldAzimuth = getAngle(); - const float* oldPosition = getPosition(); - float position[3]; - position[0] = oldPosition[0]; - position[1] = oldPosition[1]; - position[2] = oldPosition[2]; + const auto &oldPosition = getPosition(); + auto position = oldPosition; float azimuth = oldAzimuth; float tankAngVel = BZDB.eval(StateDatabase::BZDB_TANKANGVEL); float tankSpeed = BZDBCache::tankSpeed; @@ -244,13 +220,13 @@ void RobotPlayer::doUpdateMotion(float dt) if (shot->getFlag() == Flags::InvisibleBullet) continue; - const float* shotPos = shot->getPosition(); + const auto shotPos = shot->getPosition(); if ((fabs(shotPos[2] - position[2]) > BZDBCache::tankHeight) && (shot->getFlag() != Flags::GuidedMissile)) continue; const float dist = TargetingUtils::getTargetDistance(position, shotPos); if (dist < 150.0f) { - const float *shotVel = shot->getVelocity(); + const auto shotVel = shot->getVelocity(); float shotAngle = atan2f(shotVel[1], shotVel[0]); float shotUnitVec[2] = {cosf(shotAngle), sinf(shotAngle)}; @@ -284,12 +260,10 @@ void RobotPlayer::doUpdateMotion(float dt) if (!evading && dt > 0.0 && pathIndex < (int)path.size()) { float distance; - float v[2]; - const float* endPoint = path[pathIndex].get(); + const auto &endPoint = path[pathIndex].get(); // find how long it will take to get to next path segment - v[0] = endPoint[0] - position[0]; - v[1] = endPoint[1] - position[1]; - distance = hypotf(v[0], v[1]); + auto v = endPoint - glm::vec2(position); + distance = glm::length(v); float tankRadius = BZDBCache::tankRadius; // smooth path a little by turning early at corners, might get us stuck, though if (distance <= 2.5f * tankRadius) @@ -342,7 +316,7 @@ void RobotPlayer::explodeTank() path.clear(); } -void RobotPlayer::restart(const float* pos, float _azimuth) +void RobotPlayer::restart(const glm::vec3 &pos, float _azimuth) { LocalPlayer::restart(pos, _azimuth); // no target @@ -362,8 +336,8 @@ float RobotPlayer::getTargetPriority(const // go after closest player // FIXME -- this is a pretty stupid heuristic const float worldSize = BZDBCache::worldSize; - const float* p1 = getPosition(); - const float* p2 = _target->getPosition(); + const auto &p1 = getPosition(); + const auto &p2 = _target->getPosition(); float basePriority = 1.0f; // give bonus to non-paused player @@ -372,7 +346,7 @@ float RobotPlayer::getTargetPriority(const // give bonus to non-deadzone targets if (obstacleList) { - float nearest[2]; + glm::vec2 nearest; const BzfRegion* targetRegion = findRegion (p2, nearest); if (targetRegion && targetRegion->isInside(p2)) basePriority += 1.0f; @@ -401,11 +375,11 @@ void RobotPlayer::setTarget(const Player* _target) if (!target) return; // work backwards (from target to me) - float proj[3]; + glm::vec3 proj; getProjectedPosition(target, proj); - const float *p1 = proj; - const float* p2 = getPosition(); - float q1[2], q2[2]; + auto p1 = glm::vec2(proj); + const auto &p2 = getPosition(); + glm::vec2 q1, q2; BzfRegion* headRegion = findRegion(p1, q1); BzfRegion* tailRegion = findRegion(p2, q2); if (!headRegion || !tailRegion) @@ -438,11 +412,10 @@ void RobotPlayer::setTarget(const Player* _target) pathIndex = 0; } -BzfRegion* RobotPlayer::findRegion(const float p[2], - float nearest[2]) const +BzfRegion* RobotPlayer::findRegion(const glm::vec2 &p, + glm::vec2 &nearest) const { - nearest[0] = p[0]; - nearest[1] = p[1]; + nearest = p; const int count = obstacleList->size(); for (int o = 0; o < count; o++) if ((*obstacleList)[o]->isInside(p)) @@ -453,30 +426,25 @@ BzfRegion* RobotPlayer::findRegion(const float p[2], BzfRegion* nearestRegion = NULL; for (int i = 0; i < count; i++) { - float currNearest[2]; + glm::vec2 currNearest; float currDistance = (*obstacleList)[i]->getDistance(p, currNearest); if (currDistance < distance) { nearestRegion = (*obstacleList)[i]; distance = currDistance; - nearest[0] = currNearest[0]; - nearest[1] = currNearest[1]; + nearest = currNearest; } } return nearestRegion; } float RobotPlayer::getRegionExitPoint( - const float p1[2], const float p2[2], - const float a[2], const float targetPoint[2], - float mid[2], float& priority) + const glm::vec2 &p1, const glm::vec2 &p2, + const glm::vec2 &a, const glm::vec2 &targetPoint, + glm::vec2 &mid, float& priority) { - float b[2]; - b[0] = targetPoint[0] - a[0]; - b[1] = targetPoint[1] - a[1]; - float d[2]; - d[0] = p2[0] - p1[0]; - d[1] = p2[1] - p1[1]; + auto b = targetPoint - a; + auto d = p2 - p1; float vect = d[0] * b[1] - d[1] * b[0]; float t = 0.0f; // safe value @@ -490,12 +458,11 @@ float RobotPlayer::getRegionExitPoint( t = 0.0f; } - mid[0] = p1[0] + t * d[0]; - mid[1] = p1[1] + t * d[1]; + mid = p1 + t * d; - const float distance = hypotf(a[0] - mid[0], a[1] - mid[1]); + const float distance = glm::distance(a, mid); // priority is to minimize distance traveled and distance left to go - priority = distance + hypotf(targetPoint[0] - mid[0], targetPoint[1] - mid[1]); + priority = distance + glm::distance(targetPoint, mid); // return distance traveled return distance; } @@ -503,7 +470,7 @@ float RobotPlayer::getRegionExitPoint( void RobotPlayer::findPath(RegionPriorityQueue& queue, BzfRegion* region, BzfRegion* targetRegion, - const float targetPoint[2], + const glm::vec2 &targetPoint, int mailbox) { const int numEdges = region->getNumSides(); @@ -512,14 +479,15 @@ void RobotPlayer::findPath(RegionPriorityQueue& queue, BzfRegion* neighbor = region->getNeighbor(i); if (!neighbor) continue; - const float* p1 = region->getCorner(i).get(); - const float* p2 = region->getCorner((i+1)%numEdges).get(); - float mid[2], priority; + const auto &p1 = region->getCorner(i).get(); + const auto &p2 = region->getCorner((i+1)%numEdges).get(); + glm::vec2 mid; + float priority; float total = getRegionExitPoint(p1, p2, region->getA(), targetPoint, mid, priority); priority += region->getDistance(); if (neighbor == targetRegion) - total += hypotf(targetPoint[0] - mid[0], targetPoint[1] - mid[1]); + total += glm::distance(targetPoint, mid); total += region->getDistance(); if (neighbor->test(mailbox) || total < neighbor->getDistance()) { diff --git a/src/bzflag/RobotPlayer.h b/src/bzflag/RobotPlayer.h index d19bf06460..67e88922f1 100644 --- a/src/bzflag/RobotPlayer.h +++ b/src/bzflag/RobotPlayer.h @@ -43,23 +43,23 @@ class RobotPlayer : public LocalPlayer void setTarget(const Player*); static void setObstacleList(std::vector*); - void restart(const float* pos, float azimuth); + void restart(const glm::vec3 &pos, float azimuth); void explodeTank(); private: void doUpdate(float dt); void doUpdateMotion(float dt); - BzfRegion* findRegion(const float p[2], float nearest[2]) const; + BzfRegion* findRegion(const glm::vec2 &p, glm::vec2 &nearest) const; float getRegionExitPoint( - const float p1[2], const float p2[2], - const float a[2], const float targetPoint[2], - float mid[2], float& priority); + const glm::vec2 &p1, const glm::vec2 &p2, + const glm::vec2 &a, const glm::vec2 &targetPoint, + glm::vec2 &mid, float& priority); void findPath(RegionPriorityQueue& queue, BzfRegion* region, BzfRegion* targetRegion, - const float targetPoint[2], int mailbox); + const glm::vec2 &targetPoint, int mailbox); - void projectPosition(const Player *targ,const float t,float &x,float &y,float &z) const; - void getProjectedPosition(const Player *targ, float *projpos) const; + void projectPosition(const Player *targ, const float t, glm::vec3 &tPos) const; + void getProjectedPosition(const Player *targ, glm::vec3 &projpos) const; private: const Player* target; diff --git a/src/bzflag/RoofTops.cxx b/src/bzflag/RoofTops.cxx index dbeb05120f..1c92b9ad9e 100644 --- a/src/bzflag/RoofTops.cxx +++ b/src/bzflag/RoofTops.cxx @@ -49,8 +49,8 @@ float RoofTops::getTopHeight(float x, float y, float maxHeight) const float zSpeed = -1.0f; // setup the test ray - const float dir[3] = { 0.0f, 0.0f, zSpeed }; - const float org[3] = { x, y, maxHeight }; + const auto dir = glm::vec3(0.0f, 0.0f, zSpeed); + const auto org = glm::vec3(x, y, maxHeight); Ray ray(org, dir); // get the obstacle list diff --git a/src/bzflag/SceneBuilder.cxx b/src/bzflag/SceneBuilder.cxx index 1e85369dca..04c3c8af04 100644 --- a/src/bzflag/SceneBuilder.cxx +++ b/src/bzflag/SceneBuilder.cxx @@ -50,32 +50,32 @@ // SceneDatabaseBuilder // -static const GLfloat black[3] = { 0.0f, 0.0f, 0.0f }; +static const auto black = glm::vec3(0.0f); -const GLfloat SceneDatabaseBuilder::wallColors[4][4] = +const glm::vec4 SceneDatabaseBuilder::wallColors[4] = { { 0.5f, 0.5f, 0.5f, 1.0f }, { 0.4f, 0.4f, 0.4f, 1.0f }, { 0.5f, 0.5f, 0.5f, 1.0f }, { 0.6f, 0.6f, 0.6f, 1.0f } }; -const GLfloat SceneDatabaseBuilder::wallModulateColors[4][4] = +const glm::vec4 SceneDatabaseBuilder::wallModulateColors[4] = { { 0.5f, 0.5f, 0.5f, 1.0f }, { 0.4f, 0.4f, 0.4f, 1.0f }, { 0.5f, 0.5f, 0.5f, 1.0f }, { 0.6f, 0.6f, 0.6f, 1.0f } }; -const GLfloat SceneDatabaseBuilder::wallLightedColors[1][4] = +const glm::vec4 SceneDatabaseBuilder::wallLightedColors[1] = { { 0.5f, 0.5f, 0.5f, 1.0f } }; -const GLfloat SceneDatabaseBuilder::wallLightedModulateColors[1][4] = +const glm::vec4 SceneDatabaseBuilder::wallLightedModulateColors[1] = { { 0.5f, 0.5f, 0.5f, 1.0f } }; -const GLfloat SceneDatabaseBuilder::boxColors[6][4] = +const glm::vec4 SceneDatabaseBuilder::boxColors[6] = { { 0.75f, 0.25f, 0.25f, 1.0f }, { 0.63f, 0.25f, 0.25f, 1.0f }, @@ -84,7 +84,7 @@ const GLfloat SceneDatabaseBuilder::boxColors[6][4] = { 0.875f, 0.5f, 0.5f, 1.0f }, { 0.275f, 0.2f, 0.2f, 1.0f } }; -const GLfloat SceneDatabaseBuilder::boxModulateColors[6][4] = +const glm::vec4 SceneDatabaseBuilder::boxModulateColors[6] = { { 0.75f, 0.75f, 0.75f, 1.0f }, { 0.63f, 0.63f, 0.63f, 1.0f }, @@ -93,7 +93,7 @@ const GLfloat SceneDatabaseBuilder::boxModulateColors[6][4] = { 0.875f, 0.875f, 0.875f, 1.0f }, { 0.375f, 0.375f, 0.375f, 1.0f } }; -const GLfloat SceneDatabaseBuilder::boxLightedColors[6][4] = +const glm::vec4 SceneDatabaseBuilder::boxLightedColors[6] = { { 0.75f, 0.25f, 0.25f, 1.0f }, { 0.75f, 0.25f, 0.25f, 1.0f }, @@ -102,7 +102,7 @@ const GLfloat SceneDatabaseBuilder::boxLightedColors[6][4] = { 0.875f, 0.5f, 0.5f, 1.0f }, { 0.875f, 0.5f, 0.5f, 1.0f } }; -const GLfloat SceneDatabaseBuilder::boxLightedModulateColors[6][4] = +const glm::vec4 SceneDatabaseBuilder::boxLightedModulateColors[6] = { { 0.75f, 0.75f, 0.75f, 1.0f }, { 0.75f, 0.75f, 0.75f, 1.0f }, @@ -112,7 +112,7 @@ const GLfloat SceneDatabaseBuilder::boxLightedModulateColors[6][4] = { 0.875f, 0.875f, 0.875f, 1.0f } }; -const GLfloat SceneDatabaseBuilder::pyramidColors[5][4] = +const glm::vec4 SceneDatabaseBuilder::pyramidColors[5] = { { 0.25f, 0.25f, 0.63f, 1.0f }, { 0.13f, 0.13f, 0.51f, 1.0f }, @@ -121,7 +121,7 @@ const GLfloat SceneDatabaseBuilder::pyramidColors[5][4] = { 0.175f, 0.175f, 0.35f, 1.0f } }; -const GLfloat SceneDatabaseBuilder::pyramidModulateColors[5][4] = +const glm::vec4 SceneDatabaseBuilder::pyramidModulateColors[5] = { { 0.25f, 0.25f, 0.63f, 1.0f }, { 0.13f, 0.13f, 0.51f, 1.0f }, @@ -129,7 +129,7 @@ const GLfloat SceneDatabaseBuilder::pyramidModulateColors[5][4] = { 0.375f, 0.375f, 0.75f, 1.0f }, { 0.175f, 0.175f, 0.35f, 1.0f } }; -const GLfloat SceneDatabaseBuilder::pyramidLightedColors[5][4] = +const glm::vec4 SceneDatabaseBuilder::pyramidLightedColors[5] = { { 0.25f, 0.25f, 0.63f, 1.0f }, { 0.25f, 0.25f, 0.63f, 1.0f }, @@ -137,7 +137,7 @@ const GLfloat SceneDatabaseBuilder::pyramidLightedColors[5][4] = { 0.25f, 0.25f, 0.63f, 1.0f }, { 0.25f, 0.25f, 0.63f, 1.0f } }; -const GLfloat SceneDatabaseBuilder::pyramidLightedModulateColors[5][4] = +const glm::vec4 SceneDatabaseBuilder::pyramidLightedModulateColors[5] = { { 0.25f, 0.25f, 0.63f, 1.0f }, { 0.25f, 0.25f, 0.63f, 1.0f }, @@ -146,25 +146,25 @@ const GLfloat SceneDatabaseBuilder::pyramidLightedModulateColors[5][4] = { 0.25f, 0.25f, 0.63f, 1.0f } }; -const GLfloat SceneDatabaseBuilder::teleporterColors[3][4] = +const glm::vec4 SceneDatabaseBuilder::teleporterColors[3] = { { 1.0f, 0.875f, 0.0f, 1.0f }, { 0.9f, 0.8f, 0.0f, 1.0f }, { 0.0f, 0.0f, 0.0f, 0.5f } }; -const GLfloat SceneDatabaseBuilder::teleporterModulateColors[3][4] = +const glm::vec4 SceneDatabaseBuilder::teleporterModulateColors[3] = { { 1.0f, 1.0f, 1.0f, 1.0f }, { 0.9f, 0.9f, 0.9f, 1.0f }, { 0.0f, 0.0f, 0.0f, 0.5f } }; -const GLfloat SceneDatabaseBuilder::teleporterLightedColors[3][4] = +const glm::vec4 SceneDatabaseBuilder::teleporterLightedColors[3] = { { 1.0f, 0.875f, 0.0f, 1.0f }, { 1.0f, 0.875f, 0.0f, 1.0f }, { 0.0f, 0.0f, 0.0f, 0.5f } }; -const GLfloat SceneDatabaseBuilder::teleporterLightedModulateColors[3][4] = +const glm::vec4 SceneDatabaseBuilder::teleporterLightedModulateColors[3] = { { 1.0f, 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f, 1.0f }, @@ -272,24 +272,27 @@ SceneDatabase* SceneDatabaseBuilder::make(const World* world) void SceneDatabaseBuilder::addWaterLevel(SceneDatabase* db, const World* world) { - float plane[4] = { 0.0f, 0.0f, 1.0f, 0.0f }; const float level = world->getWaterLevel(); - plane[3] = -level; // don't draw it if it isn't active if (level < 0.0f) return; + auto plane = glm::vec4(0.0f, 0.0f, 1.0f, -level); + // setup the vertex and texture coordinates float size = BZDBCache::worldSize; - GLfloat3Array v(4); - GLfloat3Array n(0); - GLfloat2Array t(4); - v[0][0] = v[0][1] = v[1][1] = v[3][0] = -size/2.0f; - v[1][0] = v[2][0] = v[2][1] = v[3][1] = +size/2.0f; - v[0][2] = v[1][2] = v[2][2] = v[3][2] = level; - t[0][0] = t[0][1] = t[1][1] = t[3][0] = 0.0f; - t[1][0] = t[2][0] = t[2][1] = t[3][1] = 2.0f; + std::vector v(4); + std::vector n(0); + std::vector t(4); + v[0] = glm::vec3(-size/2.0f, -size/2.0f, level); + v[1] = glm::vec3(+size/2.0f, -size/2.0f, level); + v[2] = glm::vec3(+size/2.0f, +size/2.0f, level); + v[3] = glm::vec3(-size/2.0f, +size/2.0f, level); + t[0] = glm::vec2(0.0f, 0.0f); + t[1] = glm::vec2(2.0f, 0.0f); + t[2] = glm::vec2(2.0f, 2.0f); + t[3] = glm::vec2(0.0f, 2.0f); // get the material const BzMaterial* mat = world->getWaterMaterial(); @@ -437,7 +440,7 @@ void SceneDatabaseBuilder::addBox(SceneDatabase* db, BoxBuilding& o) #ifndef SHELL_INSIDE_NODES // add the inside node - GLfloat obstacleSize[3]; + glm::vec3 obstacleSize; obstacleSize[0] = o.getWidth(); obstacleSize[1] = o.getBreadth(); obstacleSize[2] = o.getHeight(); @@ -499,7 +502,7 @@ void SceneDatabaseBuilder::addPyramid(SceneDatabase* db, PyramidBuilding& o) #ifndef SHELL_INSIDE_NODES // add the inside node - GLfloat obstacleSize[3]; + glm::vec3 obstacleSize; obstacleSize[0] = o.getWidth(); obstacleSize[1] = o.getBreadth(); obstacleSize[2] = o.getHeight(); @@ -595,7 +598,7 @@ void SceneDatabaseBuilder::addBase(SceneDatabase *db, BaseBuilding &o) #ifndef SHELL_INSIDE_NODES // add the inside node - GLfloat obstacleSize[3]; + glm::vec3 obstacleSize; obstacleSize[0] = o.getWidth(); obstacleSize[1] = o.getBreadth(); obstacleSize[2] = o.getHeight(); diff --git a/src/bzflag/SceneBuilder.h b/src/bzflag/SceneBuilder.h index e45d41e77c..a1e5804eb1 100644 --- a/src/bzflag/SceneBuilder.h +++ b/src/bzflag/SceneBuilder.h @@ -18,7 +18,13 @@ #ifndef BZF_SCENE_BUILDER_H #define BZF_SCENE_BUILDER_H +// 1st #include "common.h" + +// System interfaces +#include + +// Common headers #include "OpenGLMaterial.h" class SceneRenderer; @@ -72,22 +78,22 @@ class SceneDatabaseBuilder OpenGLMaterial teleporterMaterial; bool teleporterLOD; - static const GLfloat wallColors[4][4]; - static const GLfloat wallModulateColors[4][4]; - static const GLfloat wallLightedColors[1][4]; - static const GLfloat wallLightedModulateColors[1][4]; - static const GLfloat boxColors[6][4]; - static const GLfloat boxModulateColors[6][4]; - static const GLfloat boxLightedColors[6][4]; - static const GLfloat boxLightedModulateColors[6][4]; - static const GLfloat pyramidColors[5][4]; - static const GLfloat pyramidModulateColors[5][4]; - static const GLfloat pyramidLightedColors[5][4]; - static const GLfloat pyramidLightedModulateColors[5][4]; - static const GLfloat teleporterColors[3][4]; - static const GLfloat teleporterModulateColors[3][4]; - static const GLfloat teleporterLightedColors[3][4]; - static const GLfloat teleporterLightedModulateColors[3][4]; + static const glm::vec4 wallColors[4]; + static const glm::vec4 wallModulateColors[4]; + static const glm::vec4 wallLightedColors[1]; + static const glm::vec4 wallLightedModulateColors[1]; + static const glm::vec4 boxColors[6]; + static const glm::vec4 boxModulateColors[6]; + static const glm::vec4 boxLightedColors[6]; + static const glm::vec4 boxLightedModulateColors[6]; + static const glm::vec4 pyramidColors[5]; + static const glm::vec4 pyramidModulateColors[5]; + static const glm::vec4 pyramidLightedColors[5]; + static const glm::vec4 pyramidLightedModulateColors[5]; + static const glm::vec4 teleporterColors[3]; + static const glm::vec4 teleporterModulateColors[3]; + static const glm::vec4 teleporterLightedColors[3]; + static const glm::vec4 teleporterLightedModulateColors[3]; }; #endif // BZF_SCENE_BUILDER_H diff --git a/src/bzflag/SceneRenderer.cxx b/src/bzflag/SceneRenderer.cxx index 2b7fee1bc6..7ca6394644 100644 --- a/src/bzflag/SceneRenderer.cxx +++ b/src/bzflag/SceneRenderer.cxx @@ -19,6 +19,9 @@ // interface header #include "SceneRenderer.h" +// System headers +#include + /* common implementation headers */ #include "SceneDatabase.h" #include "MainWindow.h" @@ -30,6 +33,7 @@ #include "ParseColor.h" #include "BZDBCache.h" #include "MeshSceneNode.h" +#include "OpenGLAPI.h" /* FIXME - local implementation dependancies */ #include "BackgroundRenderer.h" @@ -505,7 +509,7 @@ void SceneRenderer::setBackground(BackgroundRenderer* br) } -void SceneRenderer::getGroundUV(const float p[2], float uv[2]) const +void SceneRenderer::getGroundUV(const glm::vec2 &p, glm::vec2 &uv) const { float repeat = 0.01f; if (BZDB.isSet("groundTexRepeat")) @@ -514,8 +518,7 @@ void SceneRenderer::getGroundUV(const float p[2], float uv[2]) const if (useQualityValue >= 3) repeat = BZDB.eval("groundHighResTexRepeat"); - uv[0] = repeat * p[0]; - uv[1] = repeat * p[1]; + uv = repeat * p; } @@ -586,7 +589,7 @@ void SceneRenderer::setTimeOfDay(double julianDay) { // get position of sun and moon at 0,0 lat/long - float sunDir[3], moonDir[3]; + glm::vec3 sunDir, moonDir; float latitude, longitude; if (!BZDB.isTrue(StateDatabase::BZDB_SYNCLOCATION)) { @@ -626,17 +629,16 @@ void SceneRenderer::setTimeOfDay(double julianDay) } // set sun and ambient colors + glm::vec3 ambientColor; ::getSunColor(sunDir, sunColor, ambientColor, sunBrightness); theSun.setColor(sunColor); GLfloat maxComponent = sunColor[0]; if (sunColor[1] > maxComponent) maxComponent = sunColor[1]; if (sunColor[2] > maxComponent) maxComponent = sunColor[2]; if (maxComponent <= 0.0f) maxComponent = 1.0f; - sunScaledColor[0] = sunColor[0] / maxComponent; - sunScaledColor[1] = sunColor[1] / maxComponent; - sunScaledColor[2] = sunColor[2] / maxComponent; - ambientColor[3] = 1.0f; - glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientColor); + sunScaledColor = sunColor / maxComponent; + const auto color = glm::vec4(ambientColor, 1.0f); + glLightModelfv(GL_LIGHT_MODEL_AMBIENT, glm::value_ptr(color)); if (background) background->setCelestial(*this, sunDir, moonDir); @@ -778,12 +780,9 @@ void SceneRenderer::render(bool _lastFrame, bool _sameFrame, frustum.flipVertical(); glFrontFace(GL_CCW); - float mirrorColor[4]; + glm::vec4 mirrorColor; if (!parseColorString(BZDB.get(StateDatabase::BZDB_MIRROR), mirrorColor)) - { - mirrorColor[0] = mirrorColor[1] = mirrorColor[2] = 0.0f; - mirrorColor[3] = 0.5f; - } + mirrorColor = glm::vec4(0.0f, 0.0f, 0.0f, 0.5f); else if (mirrorColor[3] == 1.0f) { // probably a mistake @@ -818,12 +817,12 @@ void SceneRenderer::render(bool _lastFrame, bool _sameFrame, { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); - glColor4fv(mirrorColor); + glColor(mirrorColor); } else { float stipple = mirrorColor[3]; - glColor3fv(mirrorColor); + glColor(glm::vec3(mirrorColor)); OpenGLGState::setStipple(stipple); glEnable(GL_POLYGON_STIPPLE); } @@ -948,7 +947,7 @@ void SceneRenderer::renderScene(bool UNUSED(_lastFrame), bool UNUSED(_sameFrame) // draw start of background (no depth testing) OpenGLGState::resetState(); - const GLdouble plane[4] = {0.0, 0.0, +1.0, 0.0}; + const auto plane = glm::dvec4(0.0, 0.0, +1.0, 0.0); glClipPlane(GL_CLIP_PLANE0, plane); if (background) @@ -1103,7 +1102,7 @@ static bool setupMapFog() GLfloat fogDensity = 0.001f; GLfloat fogStart = 0.5f * BZDBCache::worldSize; GLfloat fogEnd = BZDBCache::worldSize; - GLfloat fogColor[4] = {0.25f, 0.25f, 0.25f, 0.25f}; + auto fogColor = glm::vec4(0.25f, 0.25f, 0.25f, 0.25f); // parse the values; const std::string modeStr = BZDB.get("_fogMode"); @@ -1119,10 +1118,7 @@ static bool setupMapFog() fogStart = BZDB.eval(StateDatabase::BZDB_FOGSTART); fogEnd = BZDB.eval(StateDatabase::BZDB_FOGEND); if (!parseColorString(BZDB.get(StateDatabase::BZDB_FOGCOLOR), fogColor)) - { - fogColor[0] = fogColor[1] = fogColor[2] = 0.1f; - fogColor[3] = 0.0f; // has no effect - } + fogColor = glm::vec4(0.1f, 0.1f, 0.1f, 0.0f); // has no effect if (BZDB.evalInt("fogEffect") >= 1) glHint(GL_FOG_HINT, GL_NICEST); else @@ -1133,7 +1129,7 @@ static bool setupMapFog() glFogf(GL_FOG_DENSITY, fogDensity); glFogf(GL_FOG_START, fogStart); glFogf(GL_FOG_END, fogEnd); - glFogfv(GL_FOG_COLOR, fogColor); + glSetFogColor(fogColor); glEnable(GL_FOG); RENDERER.setFogColor(fogColor); @@ -1288,16 +1284,15 @@ void SceneRenderer::getLights() } -void SceneRenderer::disableLights(const float mins[3], const float maxs[3]) +void SceneRenderer::disableLights(const glm::vec3 &mins, const glm::vec3 &maxs) { // temporarily turn off non-applicable lights for big meshes for (int i = 0; i < dynamicLights; i++) { - const float* pos = lights[i]->getPosition(); + const auto pos = glm::vec3(lights[i]->getPosition()); const float dist = lights[i]->getMaxDist(); - if ((pos[0] < (mins[0] - dist)) || (pos[0] > (maxs[0] + dist)) || - (pos[1] < (mins[1] - dist)) || (pos[1] > (maxs[1] + dist)) || - (pos[2] < (mins[2] - dist)) || (pos[2] > (maxs[2] + dist))) + if (glm::any(glm::lessThan(pos, mins - dist)) || + glm::any(glm::greaterThan(pos, maxs + dist))) lights[i]->enableLight(i + reservedLights, false); } return; @@ -1326,7 +1321,7 @@ const RenderNodeList& SceneRenderer::getShadowList() const } -const GLfloat* SceneRenderer::getSunDirection() const +const glm::vec3 *SceneRenderer::getSunDirection() const { if (background) return background->getSunDirection(); diff --git a/src/bzflag/ScoreboardRenderer.cxx b/src/bzflag/ScoreboardRenderer.cxx index 869486419c..ada0a999ca 100644 --- a/src/bzflag/ScoreboardRenderer.cxx +++ b/src/bzflag/ScoreboardRenderer.cxx @@ -13,6 +13,9 @@ /* interface header */ #include "ScoreboardRenderer.h" +// System headers +#include + /* common implementation headers */ #include "Bundle.h" #include "Team.h" @@ -21,6 +24,7 @@ #include "OpenGLGState.h" #include "TextUtils.h" #include "TimeKeeper.h" +#include "OpenGLAPI.h" /* local implementation headers */ #include "LocalPlayer.h" @@ -87,9 +91,7 @@ ScoreboardRenderer::ScoreboardRenderer() : numHunted(0) { // initialize message color (white) - messageColor[0] = 1.0f; - messageColor[1] = 1.0f; - messageColor[2] = 1.0f; + messageColor = glm::vec3(1.0f); sortMode = BZDB.getIntClamped("scoreboardSort", 0, SORT_MAXNUM); alwaysShowTeamScore = (BZDB.getIntClamped("alwaysShowTeamScore", 0, 1) != 0); } @@ -201,12 +203,12 @@ void ScoreboardRenderer::setDim(bool _dim) static const float dimFactor = 0.2f; -void ScoreboardRenderer::hudColor3fv(const GLfloat* c) +void ScoreboardRenderer::hudColor3fv(const glm::vec3 &c) { if (dim) - glColor3f(dimFactor * c[0], dimFactor * c[1], dimFactor * c[2]); + glColor(dimFactor * c); else - glColor3fv(c); + glColor(c); } @@ -615,22 +617,10 @@ void ScoreboardRenderer::drawRoamTarget(float _x0, float _y0, const float x1 = floorf(_x1) + 0.5f; const float y1 = y0 + 1.0f; - const float black[4] = - { - 0.0f * (dim ? dimFactor : 1.0f), - 0.0f * (dim ? dimFactor : 1.0f), - 0.0f * (dim ? dimFactor : 1.0f), - 1.0f - }; - const float white[4] = - { - 1.0f * (dim ? dimFactor : 1.0f), - 1.0f * (dim ? dimFactor : 1.0f), - 1.0f * (dim ? dimFactor : 1.0f), - 1.0f - }; - const float* c0 = black; - const float* c1 = white; + const auto black = glm::vec3(0.0f); + const auto white = glm::vec3(dim ? dimFactor : 1.0f); + glm::vec3 c0; + glm::vec3 c1; const double diff = (TimeKeeper::getCurrent() - startTime); if (fmod(diff, 0.5) > 0.25) @@ -638,16 +628,21 @@ void ScoreboardRenderer::drawRoamTarget(float _x0, float _y0, c0 = white; c1 = black; } + else + { + c0 = black; + c1 = white; + } glPushAttrib(GL_ALL_ATTRIB_BITS); glDisable(GL_BLEND); glDisable(GL_LIGHTING); glDisable(GL_TEXTURE_2D); glBegin(GL_LINES); - glColor4fv(c0); + glColor(c0); glVertex2f(x0, y1); glVertex2f(x1, y1); - glColor4fv(c1); + glColor(c1); glVertex2f(x0, y0); glVertex2f(x1, y0); glEnd(); @@ -741,10 +736,9 @@ void ScoreboardRenderer::drawPlayerScore(const Player* player, if (roaming && BZDB.isTrue("showVelocities")) { - float vel[3] = {0}; - memcpy(vel,player->getVelocity(),sizeof(float)*3); + const auto vel = glm::vec2(player->getVelocity()); - float linSpeed = sqrt(vel[0]*vel[0]+vel[1]*vel[1]); + float linSpeed = glm::length(vel); float badFactor = 1.5f; if (linSpeed > player->getMaxSpeed()*badFactor) diff --git a/src/bzflag/ScoreboardRenderer.h b/src/bzflag/ScoreboardRenderer.h index 21bd2a4fe9..954e454b1c 100644 --- a/src/bzflag/ScoreboardRenderer.h +++ b/src/bzflag/ScoreboardRenderer.h @@ -82,7 +82,7 @@ class ScoreboardRenderer static void getPlayerList(std::vector& players); protected: - void hudColor3fv(const GLfloat*); + void hudColor3fv(const glm::vec3 &); void renderTeamScores (float y, float x, float dy); void renderScoreboard(); void renderCtfFlags(); @@ -119,7 +119,7 @@ class ScoreboardRenderer float teamScoreYVal; bool roaming; - GLfloat messageColor[3]; + glm::vec3 messageColor; int minorFontFace; float minorFontSize; int labelsFontFace; diff --git a/src/bzflag/SegmentedShotStrategy.cxx b/src/bzflag/SegmentedShotStrategy.cxx index e1518189ca..9cc27f778e 100644 --- a/src/bzflag/SegmentedShotStrategy.cxx +++ b/src/bzflag/SegmentedShotStrategy.cxx @@ -15,6 +15,8 @@ /* system implementation headers */ #include +#define GLM_ENABLE_EXPERIMENTAL +#include /* common implementation headers */ #include "TextureManager.h" @@ -22,6 +24,7 @@ #include "BZDBCache.h" #include "WallObstacle.h" #include "mathRoutine.h" +#include "OpenGLAPI.h" /* local implementation headers */ #include "sound.h" @@ -57,7 +60,7 @@ SegmentedShotStrategy::SegmentedShotStrategy(ShotPath* _path, bool useSuperTextu // initialize scene nodes boltSceneNode = new BoltSceneNode(_path->getPosition(), _path->getVelocity(), useSuperTexture); - const float* c = Team::getShotColor(team); + const auto &c = Team::getShotColor(team); if (faint) { boltSceneNode->setColor(c[0], c[1], c[2], 0.2f); @@ -105,19 +108,16 @@ void SegmentedShotStrategy::update(float dt) // are important, others are not. const PlayerId myTankId = LocalPlayer::getMyTank()->getId(); const bool important = (getPath().getPlayer() == myTankId); - const float* pos = segments[segment].ray.getOrigin(); + const auto &pos = segments[segment].ray.getOrigin(); playWorldSound(SFX_RICOCHET, pos, important); // this is fugly but it's what we do - float dir[3]; - const float* newDir = segments[segment].ray.getDirection(); - const float* oldDir = segments[segment - 1].ray.getDirection(); - dir[0] = newDir[0] - oldDir[0]; - dir[1] = newDir[1] - oldDir[1]; - dir[2] = newDir[2] - oldDir[2]; + const auto &newDir = segments[segment].ray.getDirection(); + const auto &oldDir = segments[segment - 1].ray.getDirection(); + const auto dir = newDir - oldDir; float rots[2]; - const float horiz = sqrtf((dir[0] * dir[0]) + (dir[1] * dir[1])); + const float horiz = glm::length(glm::vec2(dir)); rots[0] = atan2f(dir[1], dir[0]); rots[1] = atan2f(dir[2], horiz); @@ -129,17 +129,14 @@ void SegmentedShotStrategy::update(float dt) default: { // this is fugly but it's what we do - float dir[3]; - dir[0] = segments[segment].ray.getDirection()[0]; - dir[1] = segments[segment].ray.getDirection()[1]; - dir[2] = segments[segment].ray.getDirection()[2]; + const auto dir = segments[segment].ray.getDirection(); float rots[2]; - const float horiz = sqrtf((dir[0] * dir[0]) + (dir[1] * dir[1])); + const float horiz = glm::length(glm::vec2(dir)); rots[0] = atan2f(dir[1], dir[0]); rots[1] = atan2f(dir[2], horiz); - const float* pos = segments[segment].ray.getOrigin(); + const auto &pos = segments[segment].ray.getOrigin(); EFFECTS.addShotTeleportEffect(pos, rots); } break; @@ -156,10 +153,9 @@ void SegmentedShotStrategy::update(float dt) if (numSegments > 0) { ShotPathSegment &segm = segments[numSegments - 1]; - const float *dir = segm.ray.getDirection(); - const float speed2 - = dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]; - float pos[3]; + const auto &dir = segm.ray.getDirection(); + const float speed2 = glm::length2(dir); + glm::vec3 pos; segm.ray.getPoint( float(segm.end - segm.start - bzInverseSqrt(speed2)), pos); /* NOTE -- comment out to not explode when shot expires */ @@ -170,7 +166,7 @@ void SegmentedShotStrategy::update(float dt) // otherwise update position and velocity else { - float p[3]; + glm::vec3 p; segments[segment].ray.getPoint(float(currentTime - segments[segment].start), p); setPosition(p); setVelocity(segments[segment].ray.getDirection()); @@ -189,8 +185,8 @@ const TimeKeeper& SegmentedShotStrategy::getLastTime() const } bool SegmentedShotStrategy::isOverlapping( - const float(*bbox1)[3], - const float(*bbox2)[3]) const + const glm::vec3 bbox1[2], + const glm::vec3 bbox2[2]) const { if (bbox1[1][0] < bbox2[0][0]) return false; if (bbox1[0][0] > bbox2[1][0]) return false; @@ -207,7 +203,7 @@ void SegmentedShotStrategy::setCurrentSegment(int _segment) } float SegmentedShotStrategy::checkHit(const BaseLocalPlayer* tank, - float position[3]) const + glm::vec3 &position) const { float minTime = Infinity; // expired shot can't hit anything @@ -221,14 +217,12 @@ float SegmentedShotStrategy::checkHit(const BaseLocalPlayer* tank, // half a tank height. const float tankHeight = tank->getDimensions()[2]; Ray tankLastMotionRaw = tank->getLastMotion(); - float lastTankPositionRaw[3]; - lastTankPositionRaw[0] = tankLastMotionRaw.getOrigin()[0]; - lastTankPositionRaw[1] = tankLastMotionRaw.getOrigin()[1]; - lastTankPositionRaw[2] = tankLastMotionRaw.getOrigin()[2] + 0.5f * tankHeight; + auto lastTankPositionRaw = tankLastMotionRaw.getOrigin(); + lastTankPositionRaw.z += 0.5f * tankHeight; Ray tankLastMotion(lastTankPositionRaw, tankLastMotionRaw.getDirection()); // if bounding box of tank and entire shot doesn't overlap then no hit - const float(*tankBBox)[3] = tank->getLastMotionBBox(); + const auto tankBBox = tank->getLastMotionBBox(); if (!isOverlapping(bbox, tankBBox)) return minTime; float shotRadius = BZDB.eval(StateDatabase::BZDB_SHOTRADIUS); @@ -263,7 +257,7 @@ float SegmentedShotStrategy::checkHit(const BaseLocalPlayer* tank, { // find closest approach to narrow box around tank. width of box // is shell radius so you can actually hit narrow tank head on. - static float tankBase[3] = { 0.0f, 0.0f, -0.5f * tankHeight }; + static auto tankBase = glm::vec3(0.0f, 0.0f, -0.5f * tankHeight); t = timeRayHitsBlock(relativeRay, tankBase, tank->getAngle(), 0.5f * BZDBCache::tankLength, shotRadius, tankHeight); } @@ -281,23 +275,19 @@ float SegmentedShotStrategy::checkHit(const BaseLocalPlayer* tank, if (t > s.end - prevTime) continue; // check if shot hits tank -- get position at time t, see if in radius - float closestPos[3]; + glm::vec3 closestPos; relativeRay.getPoint(t, closestPos); - if (closestPos[0] * closestPos[0] + - closestPos[1] * closestPos[1] + - closestPos[2] * closestPos[2] < radius2) + if (glm::length2(closestPos) < radius2) { // save best time so far minTime = t; // compute location of tank at time of hit - float tankPos[3]; + glm::vec3 tankPos; tank->getLastMotion().getPoint(t, tankPos); // compute position of intersection - position[0] = tankPos[0] + closestPos[0]; - position[1] = tankPos[1] + closestPos[1]; - position[2] = tankPos[2] + closestPos[2]; + position = tankPos + closestPos; //printf("%u:%u %u:%u\n", tank->getId().port, tank->getId().number, getPath().getPlayer().port, getPath().getPlayer().number); } } @@ -313,7 +303,7 @@ void SegmentedShotStrategy::addShot(SceneDatabase* scene, bool colorblind) boltSceneNode->setColorblind(colorblind); TeamColor currentTeam = colorblind ? RogueTeam : team; - const float* c = Team::getShotColor(currentTeam); + const auto &c = Team::getShotColor(currentTeam); boltSceneNode->setColor(c[0], c[1], c[2]); TextureManager &tm = TextureManager::instance(); @@ -328,7 +318,7 @@ void SegmentedShotStrategy::addShot(SceneDatabase* scene, bool colorblind) void SegmentedShotStrategy::radarRender() const { - const float *orig = getPath().getPosition(); + const auto &orig = getPath().getPosition(); const int length = (int)BZDBCache::linedRadarShots; const int size = (int)BZDBCache::sizedRadarShots; @@ -337,21 +327,14 @@ void SegmentedShotStrategy::radarRender() const // Display leading lines if (length > 0) { - const float* vel = getPath().getVelocity(); - float dir[3]; - dir[0] = vel[0]; - dir[1] = vel[1]; - dir[2] = vel[2]; - const float d = bzInverseSqrt(vel[0] * vel[0] + - vel[1] * vel[1] + - vel[2] * vel[2]) * + const auto vel = getPath().getVelocity(); + auto dir = vel; + const float d = bzInverseSqrt(glm::length2(vel)) * shotTailLength * length; - dir[0] *= d; - dir[1] *= d; - dir[2] *= d; + dir *= d; glBegin(GL_LINES); - glVertex2fv(orig); + glVertex(orig); if (BZDBCache::leadingShotLine == 0) //lagging { glVertex2f(orig[0] - dir[0], orig[1] - dir[1]); @@ -362,7 +345,7 @@ void SegmentedShotStrategy::radarRender() const glVertex2f(orig[0] + dir[0], orig[1] + dir[1]); glEnd(); glBegin(GL_LINES); - glVertex2fv(orig); + glVertex(orig); glVertex2f(orig[0] - dir[0], orig[1] - dir[1]); glEnd(); } @@ -390,7 +373,7 @@ void SegmentedShotStrategy::radarRender() const // draw a sized bullet glPointSize((float)size); glBegin(GL_POINTS); - glVertex2fv(orig); + glVertex(orig); glEnd(); glPointSize(1.0f); @@ -399,7 +382,7 @@ void SegmentedShotStrategy::radarRender() const { // draw the tiny little bullet glBegin(GL_POINTS); - glVertex2fv(orig); + glVertex(orig); glEnd(); } } @@ -411,24 +394,19 @@ void SegmentedShotStrategy::makeSegments(ObstacleEffect e) // compute segments of shot until total length of segments exceeds the // lifetime of the shot. const ShotPath &shotPath = getPath(); - const float *v = shotPath.getVelocity(); + const auto v = shotPath.getVelocity(); TimeKeeper startTime = shotPath.getStartTime(); float timeLeft = shotPath.getLifetime(); float minTime = BZDB.eval(StateDatabase::BZDB_MUZZLEFRONT) * - bzInverseSqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); + bzInverseSqrt(glm::length2(v)); // if all shots ricochet and obstacle effect is stop, then make it ricochet if (e == Stop && World::getWorld()->allShotsRicochet()) e = Reflect; // prepare first segment - float o[3], d[3]; - d[0] = v[0]; - d[1] = v[1]; - d[2] = v[2]; // use v[2] to have jumping affect shot velocity - o[0] = shotPath.getPosition()[0]; - o[1] = shotPath.getPosition()[1]; - o[2] = shotPath.getPosition()[2]; + auto d = v; // use v[2] to have jumping affect shot velocity + auto o = shotPath.getPosition(); segments.clear(); ShotPathSegment::Reason reason = ShotPathSegment::Initial; @@ -438,10 +416,7 @@ void SegmentedShotStrategy::makeSegments(ObstacleEffect e) for (i = 0; (i < maxSegment) && (timeLeft > Epsilon); i++) { // construct ray and find the first building, teleporter, or outer wall - float o2[3]; - o2[0] = o[0] - minTime * d[0]; - o2[1] = o[1] - minTime * d[1]; - o2[2] = o[2] - minTime * d[2]; + auto o2 = o - minTime * d; // Sometime shot start outside world if (o2[0] <= -worldSize) @@ -493,9 +468,7 @@ void SegmentedShotStrategy::makeSegments(ObstacleEffect e) { // uh...ignore this. usually used if you shoot over the boundary wall. // just move the point of origin and build the next segment - o[0] += t * d[0]; - o[1] += t * d[1]; - o[2] += t * d[2]; + o += t * d; reason = ShotPathSegment::Boundary; } else if (teleporter) @@ -508,11 +481,9 @@ void SegmentedShotStrategy::makeSegments(ObstacleEffect e) int outFace; const Teleporter* outTeleporter = World::getWorld()->getTeleporter(target, outFace); - o[0] += t * d[0]; - o[1] += t * d[1]; - o[2] += t * d[2]; + o += t * d; teleporter->getPointWRT(*outTeleporter, face, outFace, - o, d, 0.0f, o, d, NULL); + o, &d, NULL); reason = ShotPathSegment::Teleport; } else if (building) @@ -530,12 +501,10 @@ void SegmentedShotStrategy::makeSegments(ObstacleEffect e) if ((e == Stop && !handled) || e == Reflect) { // move origin to point of reflection - o[0] += t * d[0]; - o[1] += t * d[1]; - o[2] += t * d[2]; + o += t * d; // reflect direction about normal to building - float normal[3]; + glm::vec3 normal; building->get3DNormal(o, normal); reflect(d, normal); reason = ShotPathSegment::Ricochet; @@ -559,15 +528,10 @@ void SegmentedShotStrategy::makeSegments(ObstacleEffect e) case Reflect: { // move origin to point of reflection - o[0] += t * d[0]; - o[1] += t * d[1]; - o[2] += t * d[2]; + o += t * d; // reflect direction about normal to ground - float normal[3]; - normal[0] = 0.0f; - normal[1] = 0.0f; - normal[2] = 1.0f; + auto normal = glm::vec3(0.0f, 0.0f, 1.0f); reflect(d, normal); reason = ShotPathSegment::Ricochet; break; @@ -582,12 +546,8 @@ void SegmentedShotStrategy::makeSegments(ObstacleEffect e) if (numSegments > 0) { const ShotPathSegment& firstSeg = segments[0]; - bbox[0][0] = firstSeg.bbox[0][0]; - bbox[0][1] = firstSeg.bbox[0][1]; - bbox[0][2] = firstSeg.bbox[0][2]; - bbox[1][0] = firstSeg.bbox[1][0]; - bbox[1][1] = firstSeg.bbox[1][1]; - bbox[1][2] = firstSeg.bbox[1][2]; + bbox[0] = firstSeg.bbox[0]; + bbox[1] = firstSeg.bbox[1]; for (i = 1; i < numSegments; i++) { const ShotPathSegment& segm = segments[i]; @@ -601,9 +561,8 @@ void SegmentedShotStrategy::makeSegments(ObstacleEffect e) } else { - bbox[0][0] = bbox[1][0] = 0.0f; - bbox[0][1] = bbox[1][1] = 0.0f; - bbox[0][2] = bbox[1][2] = 0.0f; + bbox[0] = glm::vec3(0.0f); + bbox[1] = glm::vec3(0.0f); } } @@ -638,10 +597,7 @@ RapidFireStrategy::RapidFireStrategy(ShotPath* _path) : // speed up shell and decrease lifetime FiringInfo& f = getFiringInfo(_path); f.lifetime *= BZDB.eval(StateDatabase::BZDB_RFIREADLIFE); - float fireAdVel = BZDB.eval(StateDatabase::BZDB_RFIREADVEL); - f.shot.vel[0] *= fireAdVel; - f.shot.vel[1] *= fireAdVel; - f.shot.vel[2] *= fireAdVel; + f.shot.vel *= BZDB.eval(StateDatabase::BZDB_RFIREADVEL); setReloadTime(_path->getReloadTime() / BZDB.eval(StateDatabase::BZDB_RFIREADRATE)); @@ -664,10 +620,7 @@ ThiefStrategy::ThiefStrategy(ShotPath *_path) : // speed up shell and decrease lifetime FiringInfo& f = getFiringInfo(_path); f.lifetime *= BZDB.eval(StateDatabase::BZDB_THIEFADLIFE); - float thiefAdVel = BZDB.eval(StateDatabase::BZDB_THIEFADSHOTVEL); - f.shot.vel[0] *= thiefAdVel; - f.shot.vel[1] *= thiefAdVel; - f.shot.vel[2] *= thiefAdVel; + f.shot.vel *= BZDB.eval(StateDatabase::BZDB_THIEFADSHOTVEL); setReloadTime(_path->getReloadTime() / BZDB.eval(StateDatabase::BZDB_THIEFADRATE)); @@ -688,11 +641,8 @@ ThiefStrategy::ThiefStrategy(ShotPath *_path) : const ShotPathSegment& segm = getSegments()[i]; const float t = float(segm.end - segm.start); const Ray& ray = segm.ray; - const float* rawdir = ray.getDirection(); - float dir[3]; - dir[0] = t * rawdir[0]; - dir[1] = t * rawdir[1]; - dir[2] = t * rawdir[2]; + const auto &rawdir = ray.getDirection(); + const auto dir = t * rawdir; thiefNodes[i] = new LaserSceneNode(ray.getOrigin(), dir); if (texture >= 0) thiefNodes[i]->setTexture(texture); @@ -737,11 +687,11 @@ void ThiefStrategy::radarRender() const for (int i = 0; i < numSegments; i++) { const ShotPathSegment& segm = segmts[i]; - const float* origin = segm.ray.getOrigin(); - const float* direction = segm.ray.getDirection(); + const auto origin = glm::vec2(segm.ray.getOrigin()); + const auto direction = glm::vec2(segm.ray.getDirection()); const float dt = float(segm.end - segm.start); - glVertex2fv(origin); - glVertex2f(origin[0] + dt * direction[0], origin[1] + dt * direction[1]); + glVertex(origin); + glVertex(origin + dt * direction); } glEnd(); } @@ -762,10 +712,7 @@ MachineGunStrategy::MachineGunStrategy(ShotPath* _path) : // speed up shell and decrease lifetime FiringInfo& f = getFiringInfo(_path); f.lifetime *= BZDB.eval(StateDatabase::BZDB_MGUNADLIFE); - float mgunAdVel = BZDB.eval(StateDatabase::BZDB_MGUNADVEL); - f.shot.vel[0] *= mgunAdVel; - f.shot.vel[1] *= mgunAdVel; - f.shot.vel[2] *= mgunAdVel; + f.shot.vel *= BZDB.eval(StateDatabase::BZDB_MGUNADVEL); setReloadTime(_path->getReloadTime() / BZDB.eval(StateDatabase::BZDB_MGUNADRATE)); @@ -833,10 +780,7 @@ LaserStrategy::LaserStrategy(ShotPath* _path) : // speed up shell and decrease lifetime FiringInfo& f = getFiringInfo(_path); f.lifetime *= BZDB.eval(StateDatabase::BZDB_LASERADLIFE); - float laserAdVel = BZDB.eval(StateDatabase::BZDB_LASERADVEL); - f.shot.vel[0] *= laserAdVel; - f.shot.vel[1] *= laserAdVel; - f.shot.vel[2] *= laserAdVel; + f.shot.vel *= BZDB.eval(StateDatabase::BZDB_LASERADVEL); setReloadTime(_path->getReloadTime() / BZDB.eval(StateDatabase::BZDB_LASERADRATE)); @@ -861,16 +805,13 @@ LaserStrategy::LaserStrategy(ShotPath* _path) : const ShotPathSegment& segm = getSegments()[i]; const float t = float(segm.end - segm.start); const Ray& ray = segm.ray; - const float* rawdir = ray.getDirection(); - float dir[3]; - dir[0] = t * rawdir[0]; - dir[1] = t * rawdir[1]; - dir[2] = t * rawdir[2]; + const auto &rawdir = ray.getDirection(); + const auto dir = t * rawdir; laserNodes[i] = new LaserSceneNode(ray.getOrigin(), dir); if (texture >= 0) laserNodes[i]->setTexture(texture); - const float* color = Team::getShotColor(tmpTeam); + const auto &color = Team::getShotColor(tmpTeam); laserNodes[i]->setColor(color[0], color[1], color[2]); if (i == 0) @@ -910,11 +851,11 @@ void LaserStrategy::radarRender() const for (int i = 0; i < numSegments; i++) { const ShotPathSegment& segm = segmts[i]; - const float* origin = segm.ray.getOrigin(); - const float* direction = segm.ray.getDirection(); + const auto origin = glm::vec2(segm.ray.getOrigin()); + const auto direction = glm::vec2(segm.ray.getDirection()); const float dt = float(segm.end - segm.start); - glVertex2fv(origin); - glVertex2f(origin[0] + dt * direction[0], origin[1] + dt * direction[1]); + glVertex(origin); + glVertex(origin + dt * direction); } glEnd(); } diff --git a/src/bzflag/SegmentedShotStrategy.h b/src/bzflag/SegmentedShotStrategy.h index 6c4d4ca35c..c851255c90 100644 --- a/src/bzflag/SegmentedShotStrategy.h +++ b/src/bzflag/SegmentedShotStrategy.h @@ -37,7 +37,7 @@ class SegmentedShotStrategy : public ShotStrategy ~SegmentedShotStrategy(); void update(float dt); - float checkHit(const BaseLocalPlayer*, float[3]) const; + float checkHit(const BaseLocalPlayer*, glm::vec3 &) const; void addShot(SceneDatabase*, bool colorblind); void radarRender() const; TeamColor team; @@ -55,8 +55,8 @@ class SegmentedShotStrategy : public ShotStrategy void setCurrentTime(const TimeKeeper&); const TimeKeeper& getLastTime() const; - bool isOverlapping(const float (*bbox1)[3], - const float (*bbox2)[3]) const; + bool isOverlapping(const glm::vec3 bbox1[2], + const glm::vec3 bbox2[2]) const; void setCurrentSegment(int segment); @@ -67,7 +67,7 @@ class SegmentedShotStrategy : public ShotStrategy int segment, lastSegment; std::vector segments; BoltSceneNode* boltSceneNode; - float bbox[2][3]; + glm::vec3 bbox[2]; }; class NormalShotStrategy : public SegmentedShotStrategy diff --git a/src/bzflag/ServerLink.cxx b/src/bzflag/ServerLink.cxx index 1271744936..8d2926019b 100644 --- a/src/bzflag/ServerLink.cxx +++ b/src/bzflag/ServerLink.cxx @@ -746,7 +746,7 @@ void ServerLink::sendGrabFlag(int flagIndex) send(MsgGrabFlag, sizeof(msg), msg); } -void ServerLink::sendDropFlag(const float* position) +void ServerLink::sendDropFlag(const glm::vec3 &position) { char msg[12]; void* buf = msg; diff --git a/src/bzflag/ServerLink.h b/src/bzflag/ServerLink.h index 3589fcc8c3..caeae777a6 100644 --- a/src/bzflag/ServerLink.h +++ b/src/bzflag/ServerLink.h @@ -77,7 +77,7 @@ class ServerLink void sendCaptureFlag(TeamColor); void sendGrabFlag(int flagIndex); - void sendDropFlag(const float* position); + void sendDropFlag(const glm::vec3 &position); void sendKilled(const PlayerId&, int reason, int shotId, const FlagType* flag, int phydrv); // FIXME -- This is very ugly, but required to build bzadmin with gcc 2.9.5. diff --git a/src/bzflag/ShockWaveStrategy.cxx b/src/bzflag/ShockWaveStrategy.cxx index 35b2749388..930c0105bc 100644 --- a/src/bzflag/ShockWaveStrategy.cxx +++ b/src/bzflag/ShockWaveStrategy.cxx @@ -13,6 +13,10 @@ /* interface header */ #include "ShockWaveStrategy.h" +// System headers +#define GLM_ENABLE_EXPERIMENTAL +#include + /* common implementation headers */ #include "SceneRenderer.h" @@ -32,7 +36,7 @@ ShockWaveStrategy::ShockWaveStrategy(ShotPath *_path) : f.lifetime *= BZDB.eval(StateDatabase::BZDB_SHOCKADLIFE); // make scene node - const float* pos = _path->getPosition(); + const auto &pos = _path->getPosition(); if (RENDERER.useQuality() >= 2) { shockNode = new SphereLodSceneNode(pos, radius); @@ -54,7 +58,7 @@ ShockWaveStrategy::ShockWaveStrategy(ShotPath *_path) : team = p ? p->getTeam() : RogueTeam; } - const float* c = Team::getShotColor(team); + const auto &c = Team::getShotColor(team); if (RENDERER.useQuality() >= 2) shockNode->setColor(c[0], c[1], c[2], 0.5f); else @@ -86,7 +90,7 @@ void ShockWaveStrategy::update(float dt) else currentTeam = team; - const float* c = Team::getShotColor(currentTeam); + const auto &c = Team::getShotColor(currentTeam); // fade old-style shockwaves if (RENDERER.useQuality() >= 2) @@ -104,21 +108,18 @@ void ShockWaveStrategy::update(float dt) } -float ShockWaveStrategy::checkHit(const BaseLocalPlayer* tank, float position[3]) const +float ShockWaveStrategy::checkHit( + const BaseLocalPlayer* tank, glm::vec3 &position) const { // return if player is inside radius of destruction -- note that a // shock wave can kill anything inside the radius, be it behind or // in a building or even zoned. - const float* playerPos = tank->getPosition(); - const float* shotPos = getPath().getPosition(); - const float dx = playerPos[0] - shotPos[0]; - const float dy = playerPos[1] - shotPos[1]; - const float dz = playerPos[2] - shotPos[2]; - if (dx * dx + dy * dy + dz * dz <= radius2) + const auto &playerPos = tank->getPosition(); + const auto &shotPos = getPath().getPosition(); + const float distance2 = glm::distance2(playerPos, shotPos); + if (distance2 <= radius2) { - position[0] = playerPos[0]; - position[1] = playerPos[1]; - position[2] = playerPos[2]; + position = playerPos; return 0.5f; } else @@ -139,7 +140,7 @@ void ShockWaveStrategy::radarRender() const { // draw circle of current radius static const int sides = 20; - const float* shotPos = getPath().getPosition(); + const auto &shotPos = getPath().getPosition(); glBegin(GL_LINE_LOOP); for (int i = 0; i < sides; i++) { diff --git a/src/bzflag/ShockWaveStrategy.h b/src/bzflag/ShockWaveStrategy.h index f9c1af66be..d04105168a 100644 --- a/src/bzflag/ShockWaveStrategy.h +++ b/src/bzflag/ShockWaveStrategy.h @@ -32,7 +32,7 @@ class ShockWaveStrategy : public ShotStrategy ~ShockWaveStrategy(); void update(float dt); - float checkHit(const BaseLocalPlayer*, float[3]) const; + float checkHit(const BaseLocalPlayer*, glm::vec3 &) const; bool isStoppedByHit() const; void addShot(SceneDatabase*, bool colorblind); void radarRender() const; diff --git a/src/bzflag/ShotPath.cxx b/src/bzflag/ShotPath.cxx index 07bcc30be8..1fcd7684d5 100644 --- a/src/bzflag/ShotPath.cxx +++ b/src/bzflag/ShotPath.cxx @@ -30,13 +30,13 @@ FiringInfo::FiringInfo(const BaseLocalPlayer& tank, int id) { shot.player = tank.getId(); shot.id = uint16_t(id); - tank.getMuzzle(shot.pos); - const float* dir = tank.getForward(); - const float* tankVel = tank.getVelocity(); + shot.pos = tank.getMuzzle(); + const auto &dir = tank.getForward(); + const auto &tankVel = tank.getVelocity(); float shotSpeed = BZDB.eval(StateDatabase::BZDB_SHOTSPEED); - shot.vel[0] = tankVel[0] + shotSpeed * dir[0]; - shot.vel[1] = tankVel[1] + shotSpeed * dir[1]; - shot.vel[2] = tankVel[2] + shotSpeed * dir[2]; + shot.vel = tankVel; + shot.vel[0] += shotSpeed * dir[0]; + shot.vel[1] += shotSpeed * dir[1]; shot.dt = 0.0f; flagType = tank.getFlag(); @@ -97,7 +97,7 @@ ShotPath::~ShotPath() } float ShotPath::checkHit(const BaseLocalPlayer* player, - float position[3]) const + glm::vec3 &position) const { return strategy->checkHit(player, position); } @@ -136,18 +136,14 @@ void ShotPath::setReloadTime(float _reloadTime) reloadTime = _reloadTime; } -void ShotPath::setPosition(const float* p) +void ShotPath::setPosition(const glm::vec3 &p) { - firingInfo.shot.pos[0] = p[0]; - firingInfo.shot.pos[1] = p[1]; - firingInfo.shot.pos[2] = p[2]; + firingInfo.shot.pos = p; } -void ShotPath::setVelocity(const float* v) +void ShotPath::setVelocity(const glm::vec3 &v) { - firingInfo.shot.vel[0] = v[0]; - firingInfo.shot.vel[1] = v[1]; - firingInfo.shot.vel[2] = v[2]; + firingInfo.shot.vel = v; } void ShotPath::setExpiring() diff --git a/src/bzflag/ShotPath.h b/src/bzflag/ShotPath.h index 4502035777..df5f210bef 100644 --- a/src/bzflag/ShotPath.h +++ b/src/bzflag/ShotPath.h @@ -54,10 +54,10 @@ class ShotPath float getReloadTime() const; const TimeKeeper& getStartTime() const; const TimeKeeper& getCurrentTime() const; - const float* getPosition() const; - const float* getVelocity() const; + const glm::vec3 &getPosition() const; + const glm::vec3 getVelocity() const; - float checkHit(const BaseLocalPlayer*, float position[3]) const; + float checkHit(const BaseLocalPlayer*, glm::vec3 &position) const; void setExpiring(); void setExpired(); bool isStoppedByHit() const; @@ -76,8 +76,8 @@ class ShotPath friend class ShotStrategy; void setReloadTime(float); - void setPosition(const float*); - void setVelocity(const float*); + void setPosition(const glm::vec3 &p); + void setVelocity(const glm::vec3 &v); private: ShotStrategy* strategy; // strategy for moving shell @@ -163,12 +163,12 @@ inline const TimeKeeper &ShotPath::getCurrentTime() const return currentTime; } -inline const float* ShotPath::getPosition() const +inline const glm::vec3 &ShotPath::getPosition() const { return firingInfo.shot.pos; } -inline const float* ShotPath::getVelocity() const +inline const glm::vec3 ShotPath::getVelocity() const { return firingInfo.shot.vel; } diff --git a/src/bzflag/ShotPathSegment.cxx b/src/bzflag/ShotPathSegment.cxx index 303479dcde..ec2908e4bb 100644 --- a/src/bzflag/ShotPathSegment.cxx +++ b/src/bzflag/ShotPathSegment.cxx @@ -57,12 +57,8 @@ ShotPathSegment::ShotPathSegment(const ShotPathSegment& segment) : reason(segment.reason) { // copy bounding box - bbox[0][0] = segment.bbox[0][0]; - bbox[0][1] = segment.bbox[0][1]; - bbox[0][2] = segment.bbox[0][2]; - bbox[1][0] = segment.bbox[1][0]; - bbox[1][1] = segment.bbox[1][1]; - bbox[1][2] = segment.bbox[1][2]; + bbox[0] = segment.bbox[0]; + bbox[1] = segment.bbox[1]; } ShotPathSegment::~ShotPathSegment() @@ -79,12 +75,8 @@ ShotPathSegment& ShotPathSegment::operator=(const end = segment.end; ray = segment.ray; reason = segment.reason; - bbox[0][0] = segment.bbox[0][0]; - bbox[0][1] = segment.bbox[0][1]; - bbox[0][2] = segment.bbox[0][2]; - bbox[1][0] = segment.bbox[1][0]; - bbox[1][1] = segment.bbox[1][1]; - bbox[1][2] = segment.bbox[1][2]; + bbox[0] = segment.bbox[0]; + bbox[1] = segment.bbox[1]; } return *this; } diff --git a/src/bzflag/ShotPathSegment.h b/src/bzflag/ShotPathSegment.h index 147559aff0..b2bdd15821 100644 --- a/src/bzflag/ShotPathSegment.h +++ b/src/bzflag/ShotPathSegment.h @@ -37,7 +37,7 @@ class ShotPathSegment TimeKeeper end; Ray ray; Reason reason; - float bbox[2][3]; + glm::vec3 bbox[2]; }; diff --git a/src/bzflag/ShotStatistics.cxx b/src/bzflag/ShotStatistics.cxx index 677beb0115..a16991d657 100644 --- a/src/bzflag/ShotStatistics.cxx +++ b/src/bzflag/ShotStatistics.cxx @@ -13,6 +13,10 @@ // Interface header #include "ShotStatistics.h" +// System headers +#define GLM_ENABLE_EXPERIMENTAL +#include + // Common headers #include "TimeKeeper.h" #include "playing.h" @@ -37,7 +41,8 @@ int ShotStatistics::getTotalPerc() const return (int)(100 * ((float)getTotalHit() / (float)getTotalFired())); } -void ShotStatistics::recordFire(FlagType* flag, const float *pVec, const float *shotVec ) +void ShotStatistics::recordFire( + FlagType* flag, const glm::vec3 &pVec, const glm::vec3 &shotVec) { fired[flag]++; totalFired++; @@ -47,23 +52,10 @@ void ShotStatistics::recordFire(FlagType* flag, const float *pVec, const float * lastShotTimeDelta = currentTime-lastShotTime; lastShotTime = currentTime; - float playerNorm[3]; - float shotNorm[3]; - float playerMag,shotMag; - - playerMag = sqrt((pVec[0]*pVec[0])+(pVec[1]*pVec[1])+pVec[2]*pVec[2]); - shotMag = bzInverseSqrt(shotVec[0] * shotVec[0] + - shotVec[1] * shotVec[1] + - shotVec[2] * shotVec[2]); - - playerNorm[0] = pVec[0]/playerMag; - playerNorm[1] = pVec[1]/playerMag; - playerNorm[2] = pVec[2]/playerMag; - shotNorm[0] = shotVec[0] * shotMag; - shotNorm[1] = shotVec[1] * shotMag; - shotNorm[2] = shotVec[2] * shotMag; + const auto playerNorm = glm::normalize(pVec); + const auto shotNorm = shotVec * bzInverseSqrt(glm::length2(shotVec)); - float dot = (shotNorm[0] * playerNorm[0]) + (shotNorm[1] * playerNorm[1]) + shotNorm[2] * playerNorm[2]; + float dot = glm::dot(shotNorm, playerNorm); lastShotDeviation = acosf(dot) * RAD2DEGf; diff --git a/src/bzflag/ShotStatistics.h b/src/bzflag/ShotStatistics.h index 0c861128d1..8bb2478e3a 100644 --- a/src/bzflag/ShotStatistics.h +++ b/src/bzflag/ShotStatistics.h @@ -43,7 +43,7 @@ class ShotStatistics FlagType* getBestFlag() const; // tally functions - void recordFire(FlagType* flag, const float *pVec, const float *shotVec); + void recordFire(FlagType* flag, const glm::vec3 &pVec, const glm::vec3 &shotVec); void recordHit(FlagType* flag); double getLastShotTimeDelta ( void ) const diff --git a/src/bzflag/ShotStrategy.cxx b/src/bzflag/ShotStrategy.cxx index 518d9973d4..137c0b8c73 100644 --- a/src/bzflag/ShotStrategy.cxx +++ b/src/bzflag/ShotStrategy.cxx @@ -56,12 +56,12 @@ void ShotStrategy::setReloadTime(float t) const path->setReloadTime(t); } -void ShotStrategy::setPosition(const float* p) const +void ShotStrategy::setPosition(const glm::vec3 &p) const { path->setPosition(p); } -void ShotStrategy::setVelocity(const float* v) const +void ShotStrategy::setVelocity(const glm::vec3 &v) const { path->setVelocity(v); } @@ -137,32 +137,26 @@ const Obstacle* ShotStrategy::getFirstBuilding(const Ray& ray, return closestObstacle; } -void ShotStrategy::reflect(float* v, const float* n) // const +void ShotStrategy::reflect(glm::vec3 &v, const glm::vec3 &n) // const { // normal is assumed to be normalized, v needn't be - float d = -2.0f * ((n[0] * v[0]) + (n[1] * v[1]) + (n[2] * v[2])); + float d = -2.0f * glm::dot(n, v); if (d >= 0.0f) { // normal reflection - v[0] += d * n[0]; - v[1] += d * n[1]; - v[2] += d * n[2]; + v += d * n; } else { // refraction due to inverted normal (still using the 2X factor) - float oldSpeed = sqrtf((v[0] * v[0]) + (v[1] * v[1]) + (v[2] * v[2])); + float oldSpeed = glm::length(v); d = -2.0f * d; // now using 4X refraction factor - v[0] += d * n[0]; - v[1] += d * n[1]; - v[2] += d * n[2]; + v += d * n; // keep the same speed as the incoming vector - float newSpeed = sqrtf((v[0] * v[0]) + (v[1] * v[1]) + (v[2] * v[2])); + float newSpeed = glm::length(v); const float scale = (oldSpeed / newSpeed); - v[0] *= scale; - v[1] *= scale; - v[2] *= scale; + v *= scale; } return; diff --git a/src/bzflag/ShotStrategy.h b/src/bzflag/ShotStrategy.h index ca17c0b2ec..17291cdcad 100644 --- a/src/bzflag/ShotStrategy.h +++ b/src/bzflag/ShotStrategy.h @@ -41,7 +41,7 @@ class ShotStrategy virtual ~ShotStrategy(); virtual void update(float dt) = 0; - virtual float checkHit(const BaseLocalPlayer*, float pos[3]) const = 0; + virtual float checkHit(const BaseLocalPlayer*, glm::vec3 &pos) const = 0; virtual bool isStoppedByHit() const; virtual void addShot(SceneDatabase*, bool colorblind) = 0; virtual void expire(); @@ -56,14 +56,14 @@ class ShotStrategy virtual void readUpdate(uint16_t code, const void* msg); static const Obstacle* getFirstBuilding(const Ray&, float min, float& t); - static void reflect(float* v, const float* n); // const + static void reflect(glm::vec3 &v, const glm::vec3 &n); // const protected: const ShotPath& getPath() const; FiringInfo& getFiringInfo(ShotPath*) const; void setReloadTime(float) const; - void setPosition(const float*) const; - void setVelocity(const float*) const; + void setPosition(const glm::vec3 &) const; + void setVelocity(const glm::vec3 &) const; void setExpiring() const; void setExpired() const; diff --git a/src/bzflag/TargetingUtils.cxx b/src/bzflag/TargetingUtils.cxx index baee1489b6..eabea8232d 100644 --- a/src/bzflag/TargetingUtils.cxx +++ b/src/bzflag/TargetingUtils.cxx @@ -15,6 +15,7 @@ // system headers #include +#include // common headers #include "Ray.h" @@ -31,52 +32,37 @@ float TargetingUtils::normalizeAngle(float ang) return ang; } -void TargetingUtils::getUnitVector( const float *src, const float *target, float unitVector[3] ) +glm::vec2 TargetingUtils::getUnitVector(const glm::vec2 &src, + const glm::vec2 &target) { - unitVector[0] = target[0] - src[0]; - unitVector[1] = target[1] - src[1]; - unitVector[2] = 0.0f; + const auto unitVector = target - src; - float len = (float) sqrt(unitVector[0] * unitVector[0] + - unitVector[1] * unitVector[1]); + if (!(unitVector.x || unitVector.y)) + return glm::vec2(0.0f); - if (len == 0.0f) - return; - - unitVector[0] /= len; - unitVector[1] /= len; + return glm::normalize(unitVector); } -void TargetingUtils::get3DUnitVector( const float *src, const float *target, float unitVector[3] ) +glm::vec3 TargetingUtils::get3DUnitVector( + const glm::vec3 &src, + const glm::vec3 &target) { - unitVector[0] = target[0] - src[0]; - unitVector[1] = target[1] - src[1]; - unitVector[2] = target[2] - src[1]; - - float len = (float) sqrt(unitVector[0] * unitVector[0] + - unitVector[1] * unitVector[1] + - unitVector[2] * unitVector[2]); + const auto unitVector = target - src; - if (len == 0.0f) - return; + if (!(unitVector.x || unitVector.y || unitVector.z)) + return glm::vec3(0.0f); - unitVector[0] /= len; - unitVector[1] /= len; - unitVector[2] /= len; + return glm::normalize(unitVector); } -float TargetingUtils::getTargetDistance( const float *src, const float *target ) +float TargetingUtils::getTargetDistance(const glm::vec2 &src, + const glm::vec2 &target) { - float vec[2]; - - vec[0] = target[0] - src[0]; - vec[1] = target[1] - src[1]; - - return (float) sqrt(vec[0] * vec[0] + - vec[1] * vec[1]); + return glm::distance(src, target); } -float TargetingUtils::getTargetAzimuth( const float *src, const float *target ) +float TargetingUtils::getTargetAzimuth(const glm::vec3 &src, + const glm::vec3 &target) { return atan2f((target[1] - src[1]), (target[0] - src[0])); } @@ -90,57 +76,50 @@ float TargetingUtils::getTargetRotation( const float startAzimuth, float targetA return targetRotation; } -float TargetingUtils::getTargetAngleDifference( const float *src, float srcAzimuth, const float *target ) +float TargetingUtils::getTargetAngleDifference(const glm::vec2 &src, float srcAzimuth, const glm::vec3 &target) { - float targetUnitVector[3]; - float srcUnitVector[3]; - - getUnitVector(src, target, targetUnitVector); + const auto targetUnitVector = getUnitVector(src, target); - srcUnitVector[0] = cosf(srcAzimuth); - srcUnitVector[1] = sinf(srcAzimuth); - srcUnitVector[2] = 0.0f; + const auto srcUnitVector = glm::vec2(cosf(srcAzimuth), sinf(srcAzimuth)); - return acos( targetUnitVector[0]*srcUnitVector[0] + targetUnitVector[1]*srcUnitVector[1] ); + return acos(glm::dot(targetUnitVector, srcUnitVector)); } -bool TargetingUtils::isLocationObscured( const float *src, const float *target ) +bool TargetingUtils::isLocationObscured(const glm::vec3 &src, const glm::vec2 &target) { - float dir[3]; - - getUnitVector(src, target, dir); + const auto src2 = glm::vec2(src); + auto dir = glm::vec3(getUnitVector(src2, target), 0.0f); - Ray tankRay( src, dir ); - float targetDistance = getTargetDistance(src, target); + Ray tankRay(src, dir); + float targetDistance = glm::distance(src2, target); const Obstacle *building = ShotStrategy::getFirstBuilding(tankRay, -0.5f, targetDistance); return building != NULL; } -float TargetingUtils::getOpenDistance( const float *src, const float azimuth ) +float TargetingUtils::getOpenDistance(const glm::vec3 &src, const float azimuth ) { float t = MAXFLOAT; //Some constant? - float dir[3] = { cosf(azimuth), sinf(azimuth), 0.0f }; - const float pos[3] = { src[0], src[1], src[2] + 0.1f }; // Don't hit building because you're sitting on one. + const auto dir = glm::vec3(cosf(azimuth), sinf(azimuth), 0.0f); + auto pos = src; // Don't hit building because you're sitting on one. + pos.z += 0.1f; Ray tankRay( pos, dir ); ShotStrategy::getFirstBuilding(tankRay, -0.5f, t); return t; } -bool TargetingUtils::getFirstCollisionPoint( const float *src, const float *target, float *collisionPt ) +bool TargetingUtils::getFirstCollisionPoint( + const glm::vec3 &src, const glm::vec3 &target, glm::vec3 &collisionPt) { float t = MAXFLOAT; - float dir[3]; - get3DUnitVector(src, target, dir); + const auto dir = get3DUnitVector(src, target); - Ray tankRay( src, dir ); + Ray tankRay(src, dir); const Obstacle *building = ShotStrategy::getFirstBuilding(tankRay, 0.0f, t); if (building == NULL) return false; - collisionPt[0] = src[0] + dir[0] * t; - collisionPt[1] = src[1] + dir[1] * t; - collisionPt[2] = src[2] + dir[2] * t; + collisionPt = src + dir * t; return true; } diff --git a/src/bzflag/TargetingUtils.h b/src/bzflag/TargetingUtils.h index 90017e09f3..f990bf1020 100644 --- a/src/bzflag/TargetingUtils.h +++ b/src/bzflag/TargetingUtils.h @@ -16,19 +16,31 @@ // common - 1st #include "common.h" +// System headers +#include + class TargetingUtils { public: static float normalizeAngle( float ang ); - static void getUnitVector( const float *src, const float *target, float unitVector[3] ); - static void get3DUnitVector( const float *src, const float *target, float unitVector[3] ); - static float getTargetDistance( const float *src, const float *target ); - static float getTargetAzimuth( const float *src, const float *target ); + static float getTargetDistance(const glm::vec2 &src, + const glm::vec2 &target); + static glm::vec2 getUnitVector(const glm::vec2 &src, + const glm::vec2 &target); + static glm::vec3 get3DUnitVector(const glm::vec3 &src, + const glm::vec3 &target); + static float getTargetAzimuth(const glm::vec3 &src, const glm::vec3 &target); static float getTargetRotation( const float startAzimuth, float targetAzimuth ); - static float getTargetAngleDifference( const float *src, float srcAzimuth, const float *target ); - static bool isLocationObscured( const float *src, const float *target ); - static float getOpenDistance( const float *src, const float azimuth ); - static bool getFirstCollisionPoint( const float *src, const float *target, float *collisionPt ); + static float getTargetAngleDifference(const glm::vec2 &src, + float srcAzimuth, + const glm::vec3 &target); + static bool isLocationObscured(const glm::vec3 &src, + const glm::vec2 &target); + static float getOpenDistance(const glm::vec3 &src, const float azimuth); + static bool getFirstCollisionPoint( + const glm::vec3 &src, + const glm::vec3 &target, + glm::vec3 &collisionPt); }; #endif diff --git a/src/bzflag/TrackMarks.cxx b/src/bzflag/TrackMarks.cxx index 7361eeb223..e7b2dbf973 100644 --- a/src/bzflag/TrackMarks.cxx +++ b/src/bzflag/TrackMarks.cxx @@ -60,7 +60,7 @@ class TrackEntry TrackEntry* next; TrackEntry* prev; public: - float pos[3]; + glm::vec3 pos; float angle; float scale; char sides; @@ -155,7 +155,7 @@ class TrackRenderNode : public RenderNode { return; } - const GLfloat* getPosition() const override + const glm::vec3 &getPosition() const override { return te->pos; } @@ -322,7 +322,7 @@ static void addEntryToList(TrackList& list, } -bool TrackMarks::addMark(const float pos[3], float scale, float angle, +bool TrackMarks::addMark(const glm::vec3 &pos, float scale, float angle, int phydrv) { TrackEntry te; @@ -353,12 +353,11 @@ bool TrackMarks::addMark(const float pos[3], float scale, float angle, } // copy some parameters - te.pos[0] = pos[0]; - te.pos[1] = pos[1]; + te.pos = pos; if (pos[2] < 0.0f) te.pos[2] = TextureHeightOffset; else - te.pos[2] = pos[2] + TextureHeightOffset; + te.pos[2] += TextureHeightOffset; te.scale = scale; te.angle = (float)(angle * (180.0 / M_PI)); // in degress, for glRotatef() @@ -428,8 +427,8 @@ bool TrackMarks::addMark(const float pos[3], float scale, float angle, static bool onBuilding(const float pos[3]) { - const float dir[3] = {0.0f, 0.0f, -1.0f}; - const float org[3] = {pos[0], pos[1], pos[2] + 0.1f}; + const auto dir = glm::vec3(0.0f, 0.0f, -1.0f); + const auto org = glm::vec3(pos[0], pos[1], pos[2] + 0.1f); Ray ray(org, dir); const ObsList* olist = COLLISIONMGR.rayTest (&ray, 0.5f); for (int i = 0; i < olist->count; i++) diff --git a/src/bzflag/TrackMarks.h b/src/bzflag/TrackMarks.h index 9ed9a1a8ee..46a98da599 100644 --- a/src/bzflag/TrackMarks.h +++ b/src/bzflag/TrackMarks.h @@ -16,6 +16,9 @@ // BZFlag common header #include "common.h" +// System headers +#include + class SceneDatabase; namespace TrackMarks @@ -30,7 +33,7 @@ void notifyStyleChange(); void renderGroundTracks(); // zbuffer is not used void renderObstacleTracks(); // zbuffer is used -bool addMark(const float pos[3], float scale, float angle, int phydrv); +bool addMark(const glm::vec3 &pos, float scale, float angle, int phydrv); void setUserFade(float); float getUserFade(); diff --git a/src/bzflag/WeatherRenderer.cxx b/src/bzflag/WeatherRenderer.cxx index dc42c07213..133828e32a 100644 --- a/src/bzflag/WeatherRenderer.cxx +++ b/src/bzflag/WeatherRenderer.cxx @@ -13,6 +13,9 @@ // interface header #include "WeatherRenderer.h" +// System headers +#include + // common impl headers #include "TextureManager.h" #include "StateDatabase.h" @@ -22,14 +25,11 @@ #include "ParseColor.h" #include "Intersect.h" #include "Extents.h" +#include "OpenGLAPI.h" // local impl headers #include "RoofTops.h" -// for debug -#define _CULLING_RAIN false - - static void bzdbCallBack(const std::string& UNUSED(name), void *userData) { static_cast(userData)->set(); @@ -38,14 +38,8 @@ static void bzdbCallBack(const std::string& UNUSED(name), void *userData) WeatherRenderer::WeatherRenderer() { - rainColor[0][0] = 0.75f; - rainColor[0][1] = 0.75f; - rainColor[0][2] = 0.75f; - rainColor[0][3] = 0.75f; - rainColor[1][0] = 0.0f; - rainColor[1][1] = 0.0f; - rainColor[1][2] = 0.0f; - rainColor[1][3] = 0.0f; + rainColor[0] = glm::vec4(0.75f); + rainColor[1] = glm::vec4(0.0f); rainSize[0] = rainSize[1] = 1.0f; @@ -69,7 +63,7 @@ WeatherRenderer::WeatherRenderer() maxPuddleTime = 5.0f; puddleSpeed = 1.0f; - puddleColor[0] = puddleColor[1] = puddleColor[2] = puddleColor[3] = 1.0f; + puddleColor = glm::vec4(1.0f); dropList = puddleList = INVALID_GL_LIST_ID; @@ -166,18 +160,12 @@ void WeatherRenderer::set(void) rainSpeed = -100.0f; rainSpeedMod = 50.0f; doPuddles = true; - rainColor[0][0] = 0.75f; - rainColor[0][1] = 0.75f; - rainColor[0][2] = 0.85f; - rainColor[0][3] = 0.75f; - rainColor[1][0] = 0.0f; - rainColor[1][1] = 0.0f; - rainColor[1][2] = 0.0f; - rainColor[1][3] = 0.0f; + rainColor[0] = glm::vec4(0.75f, 0.75f, 0.85f, 0.75f); + rainColor[1] = glm::vec4(0.0f); rainSize[0] = rainSize[1] = 1.0f; maxPuddleTime = 1.5f; puddleSpeed = 1.0f; - puddleColor[0] = puddleColor[1] = puddleColor[2] = puddleColor[3] = 1.0f; + puddleColor = glm::vec4(1.0f); spinRain = true; cullRoofTops = true; roofPuddles = false; @@ -386,20 +374,21 @@ void WeatherRenderer::set(void) float rainHeightDelta = rainEndZ - rainStartZ; - int totalRain = rainCount; - if (!_CULLING_RAIN) - totalRain = raindrops.size(); + int totalRain = raindrops.size(); if (totalRain < rainDensity) { + auto minPos = glm::vec3(-rainSpread, -rainSpread, rainStartZ); + auto maxPos = glm::vec3( + rainSpread, + rainSpread, + rainStartZ + rainHeightDelta); for (int drops = totalRain; drops < rainDensity; drops++) { rain drop; - drop.speed = rainSpeed + - (((float) bzfrand() * 2.0f - 1.0f) * rainSpeedMod); - drop.pos[0] = (((float) bzfrand() * 2.0f - 1.0f) * rainSpread); - drop.pos[1] = (((float) bzfrand() * 2.0f - 1.0f) * rainSpread); - drop.pos[2] = rainStartZ + (((float) bzfrand()) * rainHeightDelta); + drop.speed = rainSpeed + + glm::linearRand(-rainSpeedMod, rainSpeedMod); + drop.pos = glm::linearRand(minPos, maxPos); if (cullRoofTops) { drop.roofTop = @@ -408,29 +397,14 @@ void WeatherRenderer::set(void) else drop.roofTop = 0.0f; - if (_CULLING_RAIN) - addDrop (drop); - else + { raindrops.push_back (drop); + } } lastRainTime = float(TimeKeeper::getCurrent().getSeconds()); } // recompute the drops based on the posible new size buildDropList(); - - if (_CULLING_RAIN) // need to update the bbox depths on all the chunks - { - std::map::iterator itr = chunkMap.begin(); - - while (itr != chunkMap.end()) - { - itr->second.bbox.mins[2] = - rainStartZ > rainEndZ ? rainEndZ : rainStartZ; - itr->second.bbox.maxs[2] = - rainStartZ > rainEndZ ? rainStartZ : rainEndZ; - itr++; - } - } } else { @@ -447,59 +421,20 @@ void WeatherRenderer::update(void) float frameTime = float(TimeKeeper::getCurrent().getSeconds() - lastRainTime); lastRainTime = float(TimeKeeper::getCurrent().getSeconds()); - std::vector dropsToAdd; - // clamp the update time // its not an important sim so just keep it smooth if (frameTime > 0.06f) frameTime = 0.06f; - if (!_CULLING_RAIN) { // update all the drops in the world std::vector::iterator itr = raindrops.begin(); while (itr != raindrops.end()) { - if (updateDrop(itr, frameTime, dropsToAdd)) + if (updateDrop(itr, frameTime)) itr++; } } - else - { - std::map::iterator itr = chunkMap.begin(); - - while (itr != chunkMap.end()) - { - if (!itr->second.drops.size()) // kill any empty chunks - { - // cellCount--; - // itr == chunkMap.erase(itr); - } - else - { - std::vector::iterator dropItr = itr->second.drops.begin(); - while (dropItr != itr->second.drops.end()) - { - if (updateDrop(dropItr, frameTime, dropsToAdd)) - dropItr++; - else - { - dropItr = itr->second.drops.erase(dropItr); - rainCount--; - } - } - itr++; - } - } - - // add in any new drops - std::vector::iterator dropItr = dropsToAdd.begin(); - while (dropItr != dropsToAdd.end()) - { - addDrop(*dropItr); - dropItr++; - } - } // update all the puddles std::vector::iterator puddleItr = puddles.begin(); @@ -514,16 +449,10 @@ void WeatherRenderer::update(void) void WeatherRenderer::draw(const SceneRenderer& sr) { - if (!_CULLING_RAIN) { if (raindrops.empty()) return; } - else - { - if (!rainCount) - return; - } glDisable(GL_CULL_FACE); glMatrixMode(GL_MODELVIEW); @@ -533,56 +462,26 @@ void WeatherRenderer::draw(const SceneRenderer& sr) if (doLineRain) // we are doing line rain { rainGState.setState(); - glPushMatrix(); glBegin(GL_LINES); - } - else - texturedRainState.setState(); - - if (!_CULLING_RAIN) // draw ALL the rain - { std::vector::iterator itr = raindrops.begin(); while (itr != raindrops.end()) { - drawDrop(*itr, sr); + drawLineDrop(*itr); itr++; } + glEnd(); } else { - // do the smart thing and just draw the rain that is VISIBLE - std::map::iterator itr = chunkMap.begin(); - - const Frustum *frustum = &sr.getViewFrustum(); - while (itr != chunkMap.end()) + texturedRainState.setState(); + std::vector::iterator itr = raindrops.begin(); + while (itr != raindrops.end()) { - if (itr->second.drops.size()) // skip any empty chunks - { - // see if the chunk is visible - Extents exts; // FIXME - possible nasty slowdown - // Not using an Extents bbox directly because it is nice to - // block the Extents copy constructor to avoid passing by value. - exts.set(itr->second.bbox.mins, itr->second.bbox.maxs); - if (testAxisBoxInFrustum(exts, frustum) != Outside) - { - std::vector::iterator dropItr = itr->second.drops.begin(); - while (dropItr != itr->second.drops.end()) - { - drawDrop(*dropItr, sr); - dropItr++; - } - } - } + drawDrop(*itr, sr); itr++; } } - if (doLineRain) - { - glEnd(); - glPopMatrix(); - } - if (doPuddles) { std::vector::iterator puddleItr = puddles.begin(); @@ -743,7 +642,7 @@ void WeatherRenderer::buildPuddleList(bool _draw) bool WeatherRenderer::updateDrop(std::vector::iterator& drop, - float frameTime, std::vector &toAdd) + float frameTime) { drop->pos[2] += drop->speed * frameTime; @@ -775,7 +674,6 @@ bool WeatherRenderer::updateDrop(std::vector::iterator& drop, puddles.push_back (thePuddle); } - if (!_CULLING_RAIN) { if ((int)(raindrops.size()) <= rainDensity) { @@ -809,38 +707,6 @@ bool WeatherRenderer::updateDrop(std::vector::iterator& drop, return false; } } - else - { - if (rainCount <= rainDensity) - { - rain newDrop; - newDrop.pos[2] = rainStartZ; - newDrop.speed = - rainSpeed + - ((float) (bzfrand() * 2.0f - 1.0f) * rainSpeedMod); - newDrop.pos[0] = (((float) bzfrand() * 2.0f - 1.0f) * rainSpread); - newDrop.pos[1] = (((float) bzfrand() * 2.0f - 1.0f) * rainSpread); - if (cullRoofTops) - { - newDrop.roofTop = - RoofTops::getTopHeight (newDrop.pos[0], newDrop.pos[1], newDrop.pos[2]); - // clamp the rain to the valid rain range. - if ( rainSpeed > 0) - { - if ( newDrop.roofTop < rainEndZ ) - newDrop.roofTop = rainEndZ; - else if ( newDrop.roofTop > rainEndZ ) - newDrop.roofTop = rainEndZ; - } - } - else - newDrop.roofTop = rainEndZ; - - toAdd.push_back(newDrop); - } - // kill the drop - return false; - } } return true; } @@ -859,9 +725,8 @@ bool WeatherRenderer::updatePuddle(std::vector::iterator& splash, } -void WeatherRenderer::drawDrop(rain& drop, const SceneRenderer& sr) +void WeatherRenderer::drawLineDrop(rain& drop) { - if (doLineRain) { float alphaMod = 0; @@ -873,7 +738,7 @@ void WeatherRenderer::drawDrop(rain& drop, const SceneRenderer& sr) alphaVal = 0; glColor4f(rainColor[0][0], rainColor[0][1], rainColor[0][2], alphaVal); - glVertex3fv(drop.pos); + glVertex(drop.pos); alphaVal = rainColor[1][3] - alphaMod; if (alphaVal < 0) @@ -883,7 +748,11 @@ void WeatherRenderer::drawDrop(rain& drop, const SceneRenderer& sr) glVertex3f(drop.pos[0], drop.pos[1], drop.pos[2] + (rainSize[1] - (drop.speed * 0.15f))); } - else +} + + +void WeatherRenderer::drawDrop(rain& drop, const SceneRenderer& sr) +{ { float alphaMod = 0; diff --git a/src/bzflag/WeatherRenderer.h b/src/bzflag/WeatherRenderer.h index 238b9ed192..2d001374fe 100644 --- a/src/bzflag/WeatherRenderer.h +++ b/src/bzflag/WeatherRenderer.h @@ -61,7 +61,7 @@ class WeatherRenderer OpenGLGState puddleState; std::string rainSkin; std::vector rainTextures; - float rainColor[2][4]; + glm::vec4 rainColor[2]; float rainSize[2]; int rainDensity; float rainSpeed; @@ -77,14 +77,14 @@ class WeatherRenderer float rainEndZ; float maxPuddleTime; float puddleSpeed; - float puddleColor[4]; + glm::vec4 puddleColor; GLuint dropList; GLuint puddleList; public: typedef struct { - float pos[3]; + glm::vec3 pos; float speed; float roofTop; int texture; @@ -95,7 +95,7 @@ class WeatherRenderer typedef struct { - float pos[3]; + glm::vec3 pos; float time; int texture; } puddle; @@ -106,9 +106,10 @@ class WeatherRenderer void buildDropList(bool draw = false); void buildPuddleList(bool draw = false); - bool updateDrop(std::vector::iterator &drop, float frameTime, std::vector &toAdd); + bool updateDrop(std::vector::iterator &drop, float frameTime); bool updatePuddle(std::vector::iterator &splash, float frameTime); + void drawLineDrop(rain &drop); void drawDrop(rain &drop, const SceneRenderer& sr); void drawPuddle(puddle &splash); @@ -123,8 +124,8 @@ class WeatherRenderer public: typedef struct { - float mins[3]; - float maxs[3]; + glm::vec3 mins; + glm::vec3 maxs; } copyExtents; protected: diff --git a/src/bzflag/World.cxx b/src/bzflag/World.cxx index 6c3a9f99ad..afebff91b4 100644 --- a/src/bzflag/World.cxx +++ b/src/bzflag/World.cxx @@ -17,6 +17,8 @@ #include #include #include +#include +#include /* common implementation headers */ #include "BZDBCache.h" @@ -34,6 +36,7 @@ #include "GameTime.h" #include "WallObstacle.h" #include "MeshObstacle.h" +#include "OpenGLAPI.h" // // World @@ -178,36 +181,32 @@ const Teleporter* World::getTeleporter(int source, int& face) const } -TeamColor World::whoseBase(const float* pos) const +TeamColor World::whoseBase(const glm::vec3 &pos) const { if (gameType != ClassicCTF) return NoTeam; for (int i = 1; i < NumTeams; i++) - { - for (TeamBases::const_iterator it = bases[i].begin(); it != bases[i].end(); ++it) + for (const auto base : bases[i]) { - float nx = pos[0] - it->p[0]; - float ny = pos[1] - it->p[1]; - float an = atan2f(ny, nx) - it->p[3]; - float di = hypotf(nx, ny); - float rx = cosf(an) * di; - float ry = sinf(an) * di; - if (fabsf(rx) < it->p[4] && - fabsf(ry) < it->p[5]) - { - float nz = it->p[2] + it->p[6]; - float rz = pos[2] - nz; - if (fabsf(rz) < 0.1) // epsilon kludge - return TeamColor(i); - } + auto n = pos - base.pos; + + float rz = n.z - base.h; + if (fabsf(rz) >= 0.1) // epsilon kludge + continue; + + float an = atan2f(n.y, n.x) - base.rotation; + float di = glm::length(glm::vec2(n)); + auto r = glm::abs(glm::vec2(cosf(an), sinf(an))) * di; + if (r.x >= base.w || r.y >= base.b) + continue; + return TeamColor(i); } - } return NoTeam; } -const Obstacle* World::inBuilding(const float* pos, +const Obstacle* World::inBuilding(const glm::vec3 &pos, float radius, float height) const { // check everything but walls @@ -222,24 +221,23 @@ const Obstacle* World::inBuilding(const float* pos, return NULL; } -const Obstacle* World::inBuilding(const float* pos, float angle, - float dx, float dy, float dz) const +bool World::inBuilding(const glm::vec3 &pos, float angle, float dx, float dy) const { // check everything but the walls - const ObsList* olist = COLLISIONMGR.boxTest (pos, angle, dx, dy, dz); + const ObsList* olist = COLLISIONMGR.boxTest (pos, angle, dx, dy, 0.0f); for (int i = 0; i < olist->count; i++) { const Obstacle* obs = olist->list[i]; - if (obs->inBox(pos, angle, dx, dy, dz)) - return obs; + if (obs->inBox(pos, angle, dx, dy, 0.0f)) + return true; } - return NULL; + return false; } -const Obstacle* World::hitBuilding(const float* pos, float angle, +const Obstacle* World::hitBuilding(const glm::vec3 &pos, float angle, float dx, float dy, float dz) const { // check walls @@ -353,8 +351,8 @@ static int compareHitNormal (const void* a, const void* b) return +1; } -const Obstacle* World::hitBuilding(const float* oldPos, float oldAngle, - const float* pos, float angle, +const Obstacle* World::hitBuilding(const glm::vec3 &oldPos, float oldAngle, + const glm::vec3 &pos, float angle, float dx, float dy, float dz, bool directional) const { @@ -396,10 +394,7 @@ const Obstacle* World::hitBuilding(const float* oldPos, float oldAngle, // do some prep work for mesh faces int hitCount = 0; - float vel[3]; - vel[0] = pos[0] - oldPos[0]; - vel[1] = pos[1] - oldPos[1]; - vel[2] = pos[2] - oldPos[2]; + auto vel = pos - oldPos; bool goingDown = (vel[2] <= 0.0f); // check mesh faces @@ -425,8 +420,8 @@ const Obstacle* World::hitBuilding(const float* oldPos, float oldAngle, olist->list[hitCount] = obs; hitCount++; // compute its dot product and stick it in the scratchPad - const float* p = face->getPlane(); - const float dot = (vel[0] * p[0]) + (vel[1] * p[1]) + (vel[2] * p[2]); + const glm::vec3 p = face->getPlane(); + const float dot = glm::dot(vel, p); face->scratchPad = dot; } } @@ -459,22 +454,22 @@ const Obstacle* World::hitBuilding(const float* oldPos, float oldAngle, } -bool World::crossingTeleporter(const float* pos, - float angle, float dx, float dy, float dz, - float* plane) const +bool World::crossingTeleporter(const glm::vec3 &pos, + float angle, float dx, float dy, float dz, + glm::vec4 &plane) const { const ObstacleList& teleporters = OBSTACLEMGR.getTeles(); for (unsigned int i = 0; i < teleporters.size(); i++) { const Teleporter* teleporter = (const Teleporter*) teleporters[i]; - if (teleporter->isCrossing(pos, angle, dx, dy, dz, plane)) + if (teleporter->isCrossing(pos, angle, dx, dy, dz, &plane)) return true; } return false; } -const Teleporter* World::crossesTeleporter(const float* oldPos, - const float* newPos, +const Teleporter *World::crossesTeleporter(const glm::vec3 &oldPos, + const glm::vec3 &newPos, int& face) const { // check teleporters @@ -505,7 +500,7 @@ const Teleporter* World::crossesTeleporter(const Ray& r, int& face) const return NULL; } -float World::getProximity(const float* p, float r) const +float World::getProximity(const glm::vec3 &p, float r) const { // get maximum over all teleporters float bestProximity = 0.0; @@ -668,7 +663,7 @@ void World::makeLinkMaterial() } BzMaterial mat; - const float color[4] = {0.0f, 0.0f, 0.0f, 0.5f}; + const auto color = glm::vec4(0.0f, 0.0f, 0.0f, 0.5f); mat.setDiffuse(color); mat.setDynamicColor(dyncolId); mat.setTexture("telelink"); @@ -687,18 +682,16 @@ void World::initFlag(int index) if (index >= maxFlags || index < 0) return; // set color of flag (opaque) - const float* color = flags[index].type->getColor(); + const auto &color = flags[index].type->getColor(); flagNodes[index]->setColor(color[0], color[1], color[2]); // if coming or going then position warp Flag& flag = flags[index]; if (flag.status == FlagComing || flag.status == FlagGoing) { - GLfloat pos[3]; - pos[0] = flag.position[0]; - pos[1] = flag.position[1]; - pos[2] = 0.5f * flag.flightEnd * (flag.initialVelocity + - 0.25f * BZDBCache::gravity * flag.flightEnd) + flag.position[2]; + auto pos = flag.position; + pos[2] += 0.5f * flag.flightEnd * (flag.initialVelocity + + 0.25f * BZDBCache::gravity * flag.flightEnd); flagWarpNodes[index]->move(pos); flagWarpNodes[index]->setSizeFraction(0.0f); } @@ -729,7 +722,7 @@ void World::updateWind(float UNUSED(dt)) void World::updateFlag(int index, float dt) { if (!flagNodes) return; - const GLfloat* color = flagNodes[index]->getColor(); + const auto &color = flagNodes[index]->getColor(); GLfloat alpha = color[3]; Flag& flag = flags[index]; @@ -746,22 +739,15 @@ void World::updateFlag(int index, float dt) { // touchdown flag.status = FlagOnGround; - flag.position[0] = flag.landingPosition[0]; - flag.position[1] = flag.landingPosition[1]; - flag.position[2] = flag.landingPosition[2]; + flag.position = flag.landingPosition; } else { // still flying float t = flag.flightTime / flag.flightEnd; - flag.position[0] = (1.0f - t) * flag.launchPosition[0] + - t * flag.landingPosition[0]; - flag.position[1] = (1.0f - t) * flag.launchPosition[1] + - t * flag.landingPosition[1]; - flag.position[2] = (1.0f - t) * flag.launchPosition[2] + - t * flag.landingPosition[2] + - flag.flightTime * (flag.initialVelocity + - 0.5f * BZDBCache::gravity * flag.flightTime); + flag.position = glm::mix(flag.launchPosition, flag.landingPosition, t); + flag.position.z += flag.flightTime + * (flag.initialVelocity + 0.5f * BZDBCache::gravity * flag.flightTime); } break; @@ -889,7 +875,7 @@ void World::updateFlag(int index, float dt) { float myWind[3]; getWind(myWind, flagPlayer->getPosition()); - const float* vel = flagPlayer->getVelocity(); + const auto &vel = flagPlayer->getVelocity(); myWind[0] -= vel[0]; myWind[1] -= vel[1]; if (flagPlayer->isFalling()) @@ -952,7 +938,7 @@ static void writeDefaultOBJMaterials(std::ostream& out) { const char* name; const char* texture; - float color[4]; + glm::vec4 color; } MatProps; const MatProps defaultMats[] = { @@ -1068,7 +1054,7 @@ bool World::writeWorld(const std::string& filename, std::string& fullname) out << indent << " -mp 2,"; for (int t = RedTeam; t <= PurpleTeam; t++) { - if (getBase(t, 0) != NULL) + if (isBase(t, 0)) out << "2,"; else out << "0,"; @@ -1247,9 +1233,9 @@ bool World::writeWorld(const std::string& filename, std::string& fullname) return true; } -static void drawLines (int count, float (*vertices)[3], int color) +static void drawLines (int count, const glm::vec3 vertices[], int color) { - const float colors[][4] = + const glm::vec4 colors[] = { { 0.25f, 0.25f, 0.25f, 0.8f }, // gray (branch node) { 0.25f, 0.25f, 0.0f, 0.8f }, // yellow (regular) @@ -1262,11 +1248,11 @@ static void drawLines (int count, float (*vertices)[3], int color) color = 0; else if (color >= colorCount) color = colorCount - 1; - glColor4fv (colors[color]); + glColor(colors[color]); glBegin (GL_LINE_STRIP); for (int i = 0; i < count; i++) - glVertex3fv (vertices[i]); + glVertex(vertices[i]); glEnd (); return; @@ -1275,8 +1261,8 @@ static void drawLines (int count, float (*vertices)[3], int color) static void drawInsideOutsidePoints() { - std::vector insides; - std::vector outsides; + std::vector insides; + std::vector outsides; const ObstacleList& meshes = OBSTACLEMGR.getMeshes(); for (unsigned int i = 0; i < meshes.size(); i++) @@ -1284,19 +1270,19 @@ static void drawInsideOutsidePoints() const MeshObstacle* mesh = (const MeshObstacle*) meshes[i]; const int checkCount = mesh->getCheckCount(); const char* checkTypes = mesh->getCheckTypes(); - const afvec3* checkPoints = mesh->getCheckPoints(); + const auto checkPoints = mesh->getCheckPoints(); for (int c = 0; c < checkCount; c++) { switch (checkTypes[c]) { case MeshObstacle::CheckInside: { - insides.push_back(checkPoints[c]); + insides.push_back(&checkPoints[c]); break; } case MeshObstacle::CheckOutside: { - outsides.push_back(checkPoints[c]); + outsides.push_back(&checkPoints[c]); break; } default: @@ -1318,27 +1304,27 @@ static void drawInsideOutsidePoints() glBegin(GL_POINTS); { glColor4f(0.0f, 1.0f, 0.0f, 0.8f); - for (size_t i = 0; i < insides.size(); i++) - glVertex3fv(insides[i]); + for (const auto pt : insides) + glVertex(*pt); glColor4f(1.0f, 0.0f, 0.0f, 0.8f); - for (size_t i = 0; i < outsides.size(); i++) - glVertex3fv(outsides[i]); + for (const auto pt : outsides) + glVertex(*pt); } glEnd(); glBegin(GL_LINES); { glColor4f(0.0f, 1.0f, 0.0f, 0.2f); - for (size_t i = 0; i < insides.size(); i++) + for (const auto pt : insides) { - glVertex3f(insides[i][0], insides[i][1], 0.0f); - glVertex3fv(insides[i]); + glVertex3f(pt->x, pt->y, 0.0f); + glVertex(*pt); } glColor4f(1.0f, 0.0f, 0.0f, 0.2f); - for (size_t i = 0; i < outsides.size(); i++) + for (const auto pt : outsides) { - glVertex3f(outsides[i][0], outsides[i][1], 0.0f); - glVertex3fv(outsides[i]); + glVertex3f(pt->x, pt->y, 0.0f); + glVertex(*pt); } } glEnd(); diff --git a/src/bzflag/World.h b/src/bzflag/World.h index 129f16f28e..22177d6518 100644 --- a/src/bzflag/World.h +++ b/src/bzflag/World.h @@ -79,39 +79,40 @@ class World RemotePlayer* getCurrentRabbit() const; WorldPlayer* getWorldWeapons() const; Flag& getFlag(int index) const; - const float* getBase(int, int=0) const; + bool isBase(int, int=0) const; + bool getBase(int _team, int base, glm::vec3 &pos, + float &rotation, float &w, float &b, float &h) const; const Teleporter* getTeleporter(int source, int& face) const; int getTeleporter(const Teleporter*, int face) const; int getTeleportTarget(int source) const; int getTeleportTarget(int source, unsigned int seed) const; - TeamColor whoseBase(const float* pos) const; - const Obstacle* inBuilding(const float* pos, float radius, + TeamColor whoseBase(const glm::vec3 &pos) const; + const Obstacle* inBuilding(const glm::vec3 &pos, float radius, float tankHeight) const; - const Obstacle* inBuilding(const float* pos, float angle, - float tankWidth, float tankBreadth, - float tankHeight) const; - const Obstacle* hitBuilding(const float* pos, float angle, + bool inBuilding(const glm::vec3 &pos, float angle, + float tankWidth, float tankBreadth) const; + const Obstacle* hitBuilding(const glm::vec3 &pos, float angle, float tankWidth, float tankBreadth, float tankHeight) const; - const Obstacle* hitBuilding(const float* oldPos, float oldAngle, - const float* pos, float angle, + const Obstacle* hitBuilding(const glm::vec3 &oldPos, float oldAngle, + const glm::vec3 &pos, float angle, float tankWidth, float tankBreadth, float tankHeight, bool directional) const; - bool crossingTeleporter(const float* oldPos, float angle, + bool crossingTeleporter(const glm::vec3 &oldPos, float angle, float tankWidth, float tankBreadth, - float tankHeight, float* plane) const; - const Teleporter* crossesTeleporter(const float* oldPos, - const float* newPos, int& face) const; + float tankHeight, glm::vec4 &plane) const; + const Teleporter* crossesTeleporter(const glm::vec3 &oldPos, + const glm::vec3 &newPos, int& face) const; const Teleporter* crossesTeleporter(const Ray& r, int& face) const; - float getProximity(const float* pos, float radius) const; + float getProximity(const glm::vec3 &pos, float radius) const; void initFlag(int index); void updateFlag(int index, float dt); void updateAnimations(float dt); void addFlags(SceneDatabase*, bool seerView); void updateWind(float dt); - void getWind(float wind[3], const float pos[3]) const; + void getWind(float wind[3], const glm::vec3 &pos) const; void makeMeshDrawMgrs(); @@ -165,7 +166,11 @@ class World typedef struct { - float p[7]; + glm::vec3 pos; + float rotation; + float w; + float b; + float h; } BaseParms; typedef std::vector TeamBases; TeamBases bases[NumTeams]; @@ -367,13 +372,31 @@ inline Flag& World::getFlag(int index) const return flags[index]; } -inline const float* World::getBase(int _team, int base) const +inline bool World::isBase(int _team, int base) const { + if (base < 0) + return false; + const TeamBases &b = bases[_team]; - if ((base < 0) || (base >= (int)b.size())) - return NULL; + return base < (int)b.size(); +} + +inline bool World::getBase( + int _team, int base, + glm::vec3 &pos, + float &rotation, + float &w, float &b, float &h) const +{ + const TeamBases &base_ = bases[_team]; + if ((base < 0) || (base >= (int)base_.size())) + return false; - return b[base].p; + pos = base_[base].pos; + rotation = base_[base].rotation; + w = base_[base].w; + b = base_[base].b; + h = base_[base].h; + return true; } inline World* World::getWorld() @@ -401,7 +424,7 @@ inline void World::setLocale(const std::string& _locale) locale = _locale; } -inline void World::getWind(float w[3], const float[3]) const +inline void World::getWind(float w[3], const glm::vec3 &) const { // homogeneous, for now w[0] = wind[0]; diff --git a/src/bzflag/WorldBuilder.cxx b/src/bzflag/WorldBuilder.cxx index 11283f567a..9e98912370 100644 --- a/src/bzflag/WorldBuilder.cxx +++ b/src/bzflag/WorldBuilder.cxx @@ -323,19 +323,17 @@ void WorldBuilder::setShakeWins(int wins) const } void WorldBuilder::setBase(TeamColor team, - const float* pos, float rotation, + const glm::vec3 &pos, float rotation, float w, float b, float h) { int teamIndex = int(team); World::BaseParms bp; - bp.p[0] = pos[0]; - bp.p[1] = pos[1]; - bp.p[2] = pos[2]; - bp.p[3] = rotation; - bp.p[4] = w; - bp.p[5] = b; - bp.p[6] = h; + bp.pos = pos; + bp.rotation = rotation; + bp.w = w; + bp.b = b; + bp.h = h; world->bases[teamIndex].push_back( bp ); } diff --git a/src/bzflag/WorldBuilder.h b/src/bzflag/WorldBuilder.h index 61226e6462..7b3599fd89 100644 --- a/src/bzflag/WorldBuilder.h +++ b/src/bzflag/WorldBuilder.h @@ -41,7 +41,7 @@ class WorldBuilder void setShakeTimeout(float timeout) const; void setShakeWins(int wins) const; void setBase(TeamColor team, - const float* pos, float rotation, + const glm::vec3 &pos, float rotation, float w, float b, float h); private: diff --git a/src/bzflag/WorldPlayer.cxx b/src/bzflag/WorldPlayer.cxx index 5397956417..d5f66b44be 100644 --- a/src/bzflag/WorldPlayer.cxx +++ b/src/bzflag/WorldPlayer.cxx @@ -50,7 +50,7 @@ ShotPath* WorldPlayer::getShot(int index) const } bool WorldPlayer::doEndShot( - int ident, bool isHit, float* pos) + int ident, bool isHit, glm::vec3 &pos) { const int index = ident & 255; const int salt = (ident >> 8) & 127; @@ -80,10 +80,8 @@ bool WorldPlayer::doEndShot( return false; // end it - const float* shotPos = shots[index]->getPosition(); - pos[0] = shotPos[0]; - pos[1] = shotPos[1]; - pos[2] = shotPos[2]; + const auto &shotPos = shots[index]->getPosition(); + pos = shotPos; shots[index]->setExpired(); return true; } diff --git a/src/bzflag/WorldPlayer.h b/src/bzflag/WorldPlayer.h index 0c90fdb42f..99f06233e6 100644 --- a/src/bzflag/WorldPlayer.h +++ b/src/bzflag/WorldPlayer.h @@ -25,13 +25,13 @@ class WorldPlayer : public Player ~WorldPlayer(); void addShot(const FiringInfo&); - ShotPath* getShot(int index) const; + ShotPath* getShot(int index) const override; void updateShots(float dt); - int getMaxShots() const; - void addShots(SceneDatabase* scene, bool colorblind) const; + int getMaxShots() const override; + void addShots(SceneDatabase* scene, bool colorblind) const override; private: - bool doEndShot(int index, bool isHit, float* pos); + bool doEndShot(int index, bool isHit, glm::vec3 &pos) override; private: std::vector shots; diff --git a/src/bzflag/callbacks.cxx b/src/bzflag/callbacks.cxx index f341e0dc82..c94b056ccb 100644 --- a/src/bzflag/callbacks.cxx +++ b/src/bzflag/callbacks.cxx @@ -22,7 +22,7 @@ static void setTeamColor(TeamColor team, const std::string& str) { - float color[4]; + glm::vec4 color; parseColorString(str, color); // don't worry about alpha, Team::setColors() doesn't use it Team::setColors(team, color, Team::getRadarColor(team)); @@ -30,7 +30,7 @@ static void setTeamColor(TeamColor team, const std::string& str) static void setRadarColor(TeamColor team, const std::string& str) { - float color[4]; + glm::vec4 color; parseColorString(str, color); // don't worry about alpha, Team::setColors() doesn't use it Team::setColors(team, Team::getTankColor(team), color); diff --git a/src/bzflag/daylight.cxx b/src/bzflag/daylight.cxx index 66135b7237..488df3f1c4 100644 --- a/src/bzflag/daylight.cxx +++ b/src/bzflag/daylight.cxx @@ -13,6 +13,9 @@ // interface header #include "daylight.h" +// System interfaces +#include +#include // common headers #include "StateDatabase.h" #include "ParseColor.h" @@ -45,7 +48,7 @@ static double getGreenwichSideral(double julianDay) static void gettruePosition(double julianDay, float latitude, float longitude, double sx, double sy, double sz, - float pos[3]) + glm::vec3 &pos) { // get local sidereal time const float localSidereal = (float)(getGreenwichSideral(julianDay) - @@ -100,7 +103,7 @@ void getCelestialTransform(double julianDay, } void getSunPosition(double julianDay, float latitude, - float longitude, float pos[3]) + float longitude, glm::vec3 &pos) { double T = (julianDay - epoch) / 36525.0; double geometricMeanLongitude = radPerDeg * @@ -140,7 +143,7 @@ void getSunPosition(double julianDay, float latitude, } void getMoonPosition(double julianDay, float latitude, - float longitude, float pos[3]) + float longitude, glm::vec3 &pos) { double T = (julianDay - epoch) / 36525.0; double e = 1.0 + (-0.002495 - 0.00000752 * T) * T; @@ -204,73 +207,53 @@ void getMoonPosition(double julianDay, float latitude, gettruePosition(julianDay, latitude, longitude, sx, sy, sz, pos); } -static void lerpColor(GLfloat out[3], const GLfloat t0[3], - const GLfloat t1[3], float t) -{ - out[0] = (1.0f - t) * t0[0] + t * t1[0]; - out[1] = (1.0f - t) * t0[1] + t * t1[1]; - out[2] = (1.0f - t) * t0[2] + t * t1[2]; -} - static const float nightElevation = -0.25f; // ~sin(-15) static const float duskElevation = -0.17f; // ~sin(-10) static const float twilightElevation = -0.087f; // ~sin(-5) static const float dawnElevation = 0.0f; // sin(0) static const float dayElevation = 0.087f; // ~sin(5) -void getSunColor(const float sunDir[3], GLfloat color[3], - GLfloat ambient[3], GLfloat& brightness) +void getSunColor(const glm::vec3 &sunDir, glm::vec3 &color, + glm::vec3 &ambient, GLfloat& brightness) { - static const GLfloat highSunColor[3] = { 1.75f, 1.75f, 1.4f }; - static const GLfloat lowSunColor[3] = { 0.75f, 0.27f, 0.0f }; - static const GLfloat moonColor[3] = { 0.4f, 0.4f, 0.4f }; - static const GLfloat nightAmbient[3] = { 0.3f, 0.3f, 0.3f }; - static const GLfloat dayAmbient[3] = { 0.35f, 0.5f, 0.5f }; + static const auto highSunColor = glm::vec3(1.75f, 1.75f, 1.4f); + static const auto lowSunColor = glm::vec3(0.75f, 0.27f, 0.0f); + static const auto moonColor = glm::vec3(0.4f, 0.4f, 0.4f); + static const auto nightAmbient = glm::vec3(0.3f, 0.3f, 0.3f); + static const auto dayAmbient = glm::vec3(0.35f, 0.5f, 0.5f); if (sunDir[2] <= -0.009f) // it's the moon { - color[0] = moonColor[0]; - color[1] = moonColor[1]; - color[2] = moonColor[2]; + color = moonColor; brightness = 0.0f; } else if (sunDir[2] < dayElevation) { const GLfloat t = (sunDir[2] - dawnElevation) / (dayElevation - dawnElevation); - lerpColor(color, lowSunColor, highSunColor, t); + color = glm::mix(lowSunColor, highSunColor, t); brightness = t; } else { - color[0] = highSunColor[0]; - color[1] = highSunColor[1]; - color[2] = highSunColor[2]; + color = highSunColor; brightness = 1.0f; } // now ambient if (sunDir[2] < duskElevation) - { - ambient[0] = nightAmbient[0]; - ambient[1] = nightAmbient[1]; - ambient[2] = nightAmbient[2]; - } + ambient = nightAmbient; else if (sunDir[2] < dayElevation) { const GLfloat t = (sunDir[2] - duskElevation) / (dayElevation - duskElevation); - lerpColor(ambient, nightAmbient, dayAmbient, t); + ambient = glm::mix(nightAmbient, dayAmbient, t); } else - { - ambient[0] = dayAmbient[0]; - ambient[1] = dayAmbient[1]; - ambient[2] = dayAmbient[2]; - } + ambient = dayAmbient; } -bool getSunsetTop(const float sunDir[3], float& topAltitude) +bool getSunsetTop(const glm::vec3 &sunDir, float& topAltitude) { if (sunDir[2] > nightElevation && sunDir[2] < dayElevation) { @@ -280,116 +263,80 @@ bool getSunsetTop(const float sunDir[3], float& topAltitude) return false; } -void getSkyColor(const float sunDir[3], GLfloat sky[4][3]) +void getSkyColor(const glm::vec3 &sunDir, glm::vec3 sky[4]) { - static const GLfloat nightColor[3] = { 0.04f, 0.04f, 0.08f }; - static const GLfloat zenithColor[3] = { 0.25f, 0.55f, 0.86f }; - static const GLfloat horizonColor[3] = { 0.43f, 0.75f, 0.95f }; - static const GLfloat sunrise1Color[3] = { 0.30f, 0.12f, 0.08f }; - static const GLfloat sunrise2Color[3] = { 0.47f, 0.12f, 0.08f }; + static const auto nightColor = glm::vec3(0.04f, 0.04f, 0.08f); + static const auto zenithColor = glm::vec3(0.25f, 0.55f, 0.86f); + static const auto horizonColor = glm::vec3(0.43f, 0.75f, 0.95f); + static const auto sunrise1Color = glm::vec3(0.30f, 0.12f, 0.08f); + static const auto sunrise2Color = glm::vec3(0.47f, 0.12f, 0.08f); // sky colors if (sunDir[2] < nightElevation) { // nighttime - sky[0][0] = nightColor[0]; - sky[0][1] = nightColor[1]; - sky[0][2] = nightColor[2]; - sky[1][0] = nightColor[0]; - sky[1][1] = nightColor[1]; - sky[1][2] = nightColor[2]; - sky[2][0] = nightColor[0]; - sky[2][1] = nightColor[1]; - sky[2][2] = nightColor[2]; - sky[3][0] = nightColor[0]; - sky[3][1] = nightColor[1]; - sky[3][2] = nightColor[2]; + sky[0] = nightColor; + sky[1] = nightColor; + sky[2] = nightColor; + sky[3] = nightColor; } else if (sunDir[2] < twilightElevation) { // twilight const float t = (sunDir[2] - nightElevation) / (twilightElevation - nightElevation); - sky[0][0] = nightColor[0]; - sky[0][1] = nightColor[1]; - sky[0][2] = nightColor[2]; - lerpColor(sky[1], nightColor, sunrise1Color, t); - sky[2][0] = nightColor[0]; - sky[2][1] = nightColor[1]; - sky[2][2] = nightColor[2]; - sky[3][0] = nightColor[0]; - sky[3][1] = nightColor[1]; - sky[3][2] = nightColor[2]; + sky[0] = nightColor; + sky[1] = glm::mix(nightColor, sunrise1Color, t); + sky[2] = nightColor; + sky[3] = nightColor; } else if (sunDir[2] < dawnElevation) { // sunrise or sunset const float t = (sunDir[2] - twilightElevation) / (dawnElevation - twilightElevation); - sky[0][0] = nightColor[0]; - sky[0][1] = nightColor[1]; - sky[0][2] = nightColor[2]; - lerpColor(sky[1], sunrise1Color, sunrise2Color, t); - sky[2][0] = nightColor[0]; - sky[2][1] = nightColor[1]; - sky[2][2] = nightColor[2]; - sky[3][0] = nightColor[0]; - sky[3][1] = nightColor[1]; - sky[3][2] = nightColor[2]; + sky[0] = nightColor; + sky[1] = glm::mix(sunrise1Color, sunrise2Color, t); + sky[2] = nightColor; + sky[3] = nightColor; } else if (sunDir[2] < dayElevation) { // early morning/late evening const float t = (sunDir[2] - dawnElevation) / (dayElevation - dawnElevation); - lerpColor(sky[0], nightColor, zenithColor, t); - lerpColor(sky[1], sunrise2Color, horizonColor, t); - lerpColor(sky[2], nightColor, horizonColor, t); - lerpColor(sky[3], nightColor, horizonColor, t); + sky[0] = glm::mix(nightColor, zenithColor, t); + sky[1] = glm::mix(sunrise2Color, horizonColor, t); + sky[2] = glm::mix(nightColor, horizonColor, t); + sky[3] = glm::mix(nightColor, horizonColor, t); } else { // day time - sky[0][0] = zenithColor[0]; - sky[0][1] = zenithColor[1]; - sky[0][2] = zenithColor[2]; - sky[1][0] = horizonColor[0]; - sky[1][1] = horizonColor[1]; - sky[1][2] = horizonColor[2]; - sky[2][0] = horizonColor[0]; - sky[2][1] = horizonColor[1]; - sky[2][2] = horizonColor[2]; - sky[3][0] = horizonColor[0]; - sky[3][1] = horizonColor[1]; - sky[3][2] = horizonColor[2]; + sky[0] = zenithColor; + sky[1] = horizonColor; + sky[2] = horizonColor; + sky[3] = horizonColor; } // user adjustment for the sky color if (BZDB.get("_skyColor") != "white") { - float skyColor[4]; + glm::vec4 skyColor; parseColorString(BZDB.get("_skyColor"), skyColor); - sky[0][0] *= skyColor[0]; - sky[0][1] *= skyColor[1]; - sky[0][2] *= skyColor[2]; - sky[1][0] *= skyColor[0]; - sky[1][1] *= skyColor[1]; - sky[1][2] *= skyColor[2]; - sky[2][0] *= skyColor[0]; - sky[2][1] *= skyColor[1]; - sky[2][2] *= skyColor[2]; - sky[3][0] *= skyColor[0]; - sky[3][1] *= skyColor[1]; - sky[3][2] *= skyColor[2]; + sky[0] *= glm::vec3(skyColor); + sky[1] *= glm::vec3(skyColor); + sky[2] *= glm::vec3(skyColor); + sky[3] *= glm::vec3(skyColor); } } -bool areShadowsCast(const float sunDir[3]) +bool areShadowsCast(const glm::vec3 &sunDir) { return sunDir[2] > 0.5 * dayElevation; } -bool areStarsVisible(const float sunDir[3]) +bool areStarsVisible(const glm::vec3 &sunDir) { return sunDir[2] < dawnElevation; } diff --git a/src/bzflag/daylight.h b/src/bzflag/daylight.h index 5ff90e4fef..9b6648bae0 100644 --- a/src/bzflag/daylight.h +++ b/src/bzflag/daylight.h @@ -18,7 +18,13 @@ #ifndef BZF_DAYLIGHT_H #define BZF_DAYLIGHT_H +// 1st #include "common.h" + +// System interfaces +#include + +// Common headers #include "bzfgl.h" // julian day of midnight 1/1/1970 @@ -26,11 +32,11 @@ static const double unixEpoch = 2440587.5; // return direction of sun given julian day void getSunPosition(double julianDay, float latitude, - float longitude, float pos[3]); + float longitude, glm::vec3 &pos); // return direction of moon given julian day void getMoonPosition(double julianDay, float latitude, - float longitude, float pos[3]); + float longitude, glm::vec3 &pos); // transform a direction from the celestial coordinate system void getCelestialTransform(double julianDay, @@ -38,25 +44,25 @@ void getCelestialTransform(double julianDay, GLfloat (&xform)[4][4]); // sets color of sun. if it's nighttime, the sun is actually the moon. -void getSunColor(const float sunDir[3], GLfloat color[3], - GLfloat ambient[3], GLfloat& brightness); +void getSunColor(const glm::vec3 &sunDir, glm::vec3 &color, + glm::vec3 &ambient, GLfloat& brightness); // make sky colors given sun direction. sun direction should be normalized. // sky is filled with the colors for the zenith, horizon towards sun, and // horizon away from sun, respectively. -void getSkyColor(const float sunDir[3], GLfloat sky[4][3]); +void getSkyColor(const glm::vec3 &sunDir, glm::vec3 sky[4]); // true if sun is high enough to cast shadows. sun direction should be // normalized. -bool areShadowsCast(const float sunDir[3]); +bool areShadowsCast(const glm::vec3 &sunDir); // true if sun is low enough to let stars be visible. sun direction // should be normalized. -bool areStarsVisible(const float sunDir[3]); +bool areStarsVisible(const glm::vec3 &sunDir); // true if near sunset and sky color interpolation shouldn't be from // zenith, but from somewhere lower to flatten out the colors. -bool getSunsetTop(const float sunDir[3], float& topAltitude); +bool getSunsetTop(const glm::vec3 &sunDir, float& topAltitude); #endif // BZF_DAYLIGHT_H diff --git a/src/bzflag/effectsRenderer.cxx b/src/bzflag/effectsRenderer.cxx index 73a4e47821..7f038bfdf7 100644 --- a/src/bzflag/effectsRenderer.cxx +++ b/src/bzflag/effectsRenderer.cxx @@ -13,14 +13,16 @@ // interface header #include "effectsRenderer.h" +// System headers +#include + // common impl headers #include "TextureManager.h" #include "StateDatabase.h" #include "TimeKeeper.h" #include "Flag.h" #include "playing.h" - - +#include "OpenGLAPI.h" class StdSpawnEffect : public BasicEffect { @@ -112,7 +114,7 @@ class SquishDeathEffect : public DeathEffect virtual bool update ( float time ); virtual void draw ( const SceneRenderer& sr ); virtual bool SetDeathRenderParams ( TankDeathOverride::DeathParams ¶ms); - virtual bool GetDeathVector( fvec3 & v ); + virtual bool GetDeathVector(glm::vec3 &v); virtual bool ShowExplosion ( void ) { return false; @@ -128,7 +130,7 @@ class FadeToHeaven : public DeathEffect virtual bool update ( float time ); virtual void draw ( const SceneRenderer& sr ); virtual bool SetDeathRenderParams ( TankDeathOverride::DeathParams ¶ms); - virtual bool GetDeathVector( fvec3 & v ); + virtual bool GetDeathVector(glm::vec3 &v); virtual bool ShowExplosion ( void ) { return false; @@ -157,11 +159,11 @@ class SpikesDeathEffect : public DeathEffect { public: float size; - fvec2 rots; + glm::vec2 rots; float alphaMod; }; std::vector Spikes; - std::vector Puffs; + std::vector Puffs; float explodeFraction; }; @@ -212,7 +214,7 @@ class SmokeGMPuffEffect : public BasicEffect OpenGLGState ringState; float radius; - fvec3 jitter; + glm::vec3 jitter; float u,v,du,dv; }; @@ -254,7 +256,7 @@ static void drawRingYZ(float rad, float z, float topsideOffset = 0, static void drawRingXY(float rad, float z, float topsideOffset = 0, float bottomUV = 0, float topUV = 1.0f, int segments = 32); -static void RadialToCartesian(float angle, float rad, float *pos); +static glm::vec2 RadialToCartesian(float angle); #define deg2Rad 0.017453292519943295769236907684886f @@ -317,7 +319,7 @@ void EffectsRenderer::rebuildContext(void) effectsList[i]->rebuildContext(); } -void EffectsRenderer::addSpawnEffect ( const float* rgb, const float* pos ) +void EffectsRenderer::addSpawnEffect (const glm::vec3 &rgb, const glm::vec3 &pos) { if (!BZDB.isTrue("useFancyEffects")) return; @@ -363,7 +365,12 @@ std::vector EffectsRenderer::getSpawnEffectTypes ( void ) return ret; } -void EffectsRenderer::addShotEffect ( const float* rgb, const float* pos, float rot, const float *vel, int _type) +void EffectsRenderer::addShotEffect ( + const glm::vec3 &rgb, + const glm::vec3 &pos, + float rot, + const glm::vec3 &vel, + int _type) { if (!BZDB.isTrue("useFancyEffects")) return; @@ -417,14 +424,17 @@ std::vector EffectsRenderer::getShotEffectTypes ( void ) return ret; } -void EffectsRenderer::addGMPuffEffect ( const float* pos, float rot[2], const float* vel) +void EffectsRenderer::addGMPuffEffect(const glm::vec3 &pos, float rot[2]) { if (!BZDB.isTrue("useFancyEffects")) return; int flashType = static_cast(BZDB.eval("gmPuffEffect")); - if (flashType == 0) + if (flashType <= 1) + return; + + if (flashType > 3) return; float rots[3] = {0}; @@ -434,10 +444,6 @@ void EffectsRenderer::addGMPuffEffect ( const float* pos, float rot[2], const fl BasicEffect *effect = NULL; switch (flashType) { - case 1: - // handled outside this manager in the "old" code - break; - case 2: effect = new StdGMPuffEffect; break; @@ -447,12 +453,9 @@ void EffectsRenderer::addGMPuffEffect ( const float* pos, float rot[2], const fl break; } - if (effect) { effect->setPos(pos,rots); effect->setStartTime((float)TimeKeeper::getCurrent().getSeconds()); - if (BZDB.isTrue("useVelOnShotEffects")) - effect->setVel(vel); effectsList.push_back(effect); } } @@ -468,8 +471,9 @@ std::vector EffectsRenderer::getGMPuffEffectTypes ( void ) return ret; } -DeathEffect* EffectsRenderer::addDeathEffect (const float *rgb, const float *pos, float rot, - int, Player* player, FlagType *) +DeathEffect* EffectsRenderer::addDeathEffect ( + const glm::vec3 &rgb, const glm::vec3 &pos, float rot, + int, Player* player, FlagType *) { if (!BZDB.isTrue("useFancyEffects")) return NULL; @@ -514,7 +518,8 @@ std::vector EffectsRenderer::getDeathEffectTypes ( void ) } // landing effects -void EffectsRenderer::addLandEffect ( const float* rgb, const float* pos, float rot ) +void EffectsRenderer::addLandEffect ( + const glm::vec3 &rgb, const glm::vec3 &pos, float rot) { if (!BZDB.isTrue("useFancyEffects")) return; @@ -554,35 +559,25 @@ std::vector EffectsRenderer::getLandEffectTypes ( void ) return ret; } -void EffectsRenderer::addRicoEffect ( const float* pos, float rot[2], const float* vel) +void EffectsRenderer::addRicoEffect(const glm::vec3 &pos, float rot[2]) { if (!BZDB.isTrue("useFancyEffects")) return; int flashType = static_cast(BZDB.eval("ricoEffect")); - if (flashType == 0) + if (flashType != 1) return; float rots[3] = {0}; rots[2] = rot[0]; rots[1] = rot[1]; - BasicEffect *effect = NULL; - switch (flashType) - { - case 1: - effect = new StdRicoEffect; - break; - } + BasicEffect *effect = new StdRicoEffect; - if (effect) { effect->setPos(pos,rots); effect->setStartTime((float)TimeKeeper::getCurrent().getSeconds()); - if (BZDB.isTrue("useVelOnShotEffects")) - effect->setVel(vel); - effectsList.push_back(effect); } } @@ -597,34 +592,25 @@ std::vector EffectsRenderer::getRicoEffectTypes ( void ) return ret; } -void EffectsRenderer::addShotTeleportEffect ( const float* pos, float rot[2], const float* vel) +void EffectsRenderer::addShotTeleportEffect(const glm::vec3 &pos, float rot[2]) { if (!BZDB.isTrue("useFancyEffects")) return; int flashType = static_cast(BZDB.eval("tpEffect")); - if (flashType == 0) + if (flashType != 1) return; float rots[3] = {0}; rots[2] = rot[0]; rots[1] = rot[1]; - BasicEffect *effect = NULL; - switch (flashType) - { - case 1: - effect = new StdShotTeleportEffect; - break; - } + BasicEffect *effect = new StdShotTeleportEffect; - if (effect) { effect->setPos(pos,rots); effect->setStartTime((float)TimeKeeper::getCurrent().getSeconds()); - if (BZDB.isTrue("useVelOnShotEffects")) - effect->setVel(vel); effectsList.push_back(effect); } } @@ -644,10 +630,10 @@ std::vector EffectsRenderer::getShotTeleportEffectTypes ( void ) //****************** effects base class******************************* BasicEffect::BasicEffect(): age() { - position[0] = position[1] = position[2] = 0.0f; + position = glm::vec3(0.0f); rotation[0] = rotation[1] = rotation[2] = 0.0f; - velocity[0] = velocity[1] = velocity[2] = 0.0f; - color[0] = color[1] = color[2] = 0.0f; + velocity = glm::vec3(0.0f); + color = glm::vec3(0.0f); startTime = (float)TimeKeeper::getCurrent().getSeconds(); lifetime = 0; @@ -656,14 +642,9 @@ BasicEffect::BasicEffect(): age() lifeParam = 1.0; } -void BasicEffect::setPos ( const float *pos, const float *rot ) +void BasicEffect::setPos(const glm::vec3 &pos, const float *rot) { - if (pos) - { - position[0] = pos[0]; - position[1] = pos[1]; - position[2] = pos[2]; - } + position = pos; if (rot) { @@ -673,21 +654,14 @@ void BasicEffect::setPos ( const float *pos, const float *rot ) } } -void BasicEffect::setVel ( const float *vel ) +void BasicEffect::setVel(const glm::vec3 &vel) { - if (vel) - { - velocity[0] = vel[0]; - velocity[1] = vel[1]; - velocity[2] = vel[2]; - } + velocity = vel; } -void BasicEffect::setColor ( const float *rgb ) +void BasicEffect::setColor (const glm::vec3 &rgb) { - color[0] = rgb[0]; - color[1] = rgb[1]; - color[2] = rgb[2]; + color = rgb; } void BasicEffect::setStartTime ( float time ) @@ -936,11 +910,7 @@ void StdShotEffect::draw(const SceneRenderer &) { glPushMatrix(); - float pos[3]; - - pos[0] = position[0] + velocity[0] * age; - pos[1] = position[1] + velocity[1] * age; - pos[2] = position[2] + velocity[2] * age; + auto pos = position + velocity * age; glTranslatef(pos[0],pos[1],pos[2]); glRotatef(180+rotation[2]/deg2Rad,0,0,1); @@ -952,7 +922,7 @@ void StdShotEffect::draw(const SceneRenderer &) ringState.setState(); - color[0] = color[1] = color[2] = 1; + color = glm::vec3(1.0f); float alpha = 0.5f-(age/lifetime); if (alpha < 0.001f) @@ -1016,24 +986,15 @@ void FlashShotEffect::draw(const SceneRenderer &) glPushMatrix(); - float pos[3]; - - pos[0] = position[0] + velocity[0] * age; - pos[1] = position[1] + velocity[1] * age; - pos[2] = position[2] + velocity[2] * age; + auto pos = position + velocity * age; glTranslatef(pos[0],pos[1],pos[2]); glRotatef(270+rotation[2]/deg2Rad,0,0,1); glTranslatef(0.0f, 0.52f, -0.04f); //barrel roll to camera - const float *playerpos = LocalPlayer::getMyTank()->getPosition(); - float camerapos[3] = - { - playerpos[0] - pos[0], - playerpos[1] - pos[1], - playerpos[2] - pos[2] - }; + const auto &playerpos = LocalPlayer::getMyTank()->getPosition(); + auto camerapos = playerpos - pos; //camerapos[0] = camerapos[0] * cos(-rotation[2]) // - camerapos[1] * sin(-rotation[2]); camerapos[1] = camerapos[1] * cos(-rotation[2]) @@ -1043,7 +1004,7 @@ void FlashShotEffect::draw(const SceneRenderer &) ringState.setState(); - color[0] = color[1] = color[2] = 1; + color = glm::vec3(1.0f); float alpha = 0.8f-(age/lifetime); if (alpha < 0.001f) @@ -1094,18 +1055,17 @@ void SquishDeathEffect::draw ( const SceneRenderer& UNUSED(sr) ) bool SquishDeathEffect::SetDeathRenderParams (TankDeathOverride::DeathParams ¶ms) { - params.scale = fvec3(1,1,0); - params.pos = fvec3(0,0,0.1f); + params.scale = glm::vec3(1.0f, 1.0f, 0.0f); + params.pos = glm::vec3(0.0f, 0.0f, 0.1f); return true; } -bool SquishDeathEffect::GetDeathVector( fvec3 & vel ) +bool SquishDeathEffect::GetDeathVector(glm::vec3 &vel) { if (!player) return false; - const float *v = player->getVelocity(); - vel = fvec3(v[0],v[1],v[2]); + vel = player->getVelocity(); return true; } @@ -1140,16 +1100,16 @@ bool FadeToHeaven::SetDeathRenderParams (TankDeathOverride::DeathParams ¶ms) done = params.explodeParam < 0.0001f; params.color[3] = params.explodeParam; - params.pos = fvec3(0,0,vertDist*params.explodeParam); + params.pos = glm::vec3(0.0f, 0.0f, vertDist * params.explodeParam); return true; } -bool FadeToHeaven::GetDeathVector( fvec3 & vel ) +bool FadeToHeaven::GetDeathVector(glm::vec3 &vel) { if (!player) return false; - vel = fvec3(0,0,0); + vel = glm::vec3(0.0f); return true; } @@ -1201,15 +1161,9 @@ void RingsDeathEffect::draw(const SceneRenderer &) ringState.setState(); - color[0] = 108.0f/256.0f; - color[1] = 16.0f/256.0f; - color[2] = 16.0f/256.0f; - - float deltas[3]; + color = glm::vec3(108.0f / 256.0f, 16.0f / 256.0f, 16.0f / 256.0f); - deltas[0] = 1.0f - color[0]; - deltas[1] = 1.0f - color[1]; - deltas[2] = 1.0f - color[2]; + const auto deltas = 1.0f - color; float ageParam = age/lifetime; @@ -1217,9 +1171,7 @@ void RingsDeathEffect::draw(const SceneRenderer &) if (alpha < 0.005f) alpha = 0.005f; - color[0] += deltas[0] *ageParam; - color[1] += deltas[1] *ageParam; - color[2] += deltas[2] *ageParam; + color += deltas * ageParam; glColor4f(color[0],color[1],color[2],alpha); glDepthMask(0); @@ -1267,13 +1219,14 @@ SpikesDeathEffect::SpikesDeathEffect() : DeathEffect() Spike s; s.alphaMod = ((float)bzfrand() * 0.5f) + 0.5f; s.size = ((float)bzfrand() * 1.5f) + 0.5f; - s.rots = fvec2((float)bzfrand()* 360.0f,(float)bzfrand() * 180.0f); + s.rots = glm::linearRand(glm::vec2(0.0f), glm::vec2(360.0f, 180.0f)); Spikes.push_back(s); } int puffs = (int)((bzfrand() * 25)) + 10; for ( int i = 0; i < puffs; i++) - Puffs.push_back(fvec3((float)bzfrand()*4-2,(float)bzfrand()*4-2,(float)bzfrand()*2)); + Puffs.push_back(glm::linearRand(glm::vec3(-2.0f, -2.0f, 0.0f), + glm::vec3(2.0f, 2.0f, 2.0f))); } SpikesDeathEffect::~SpikesDeathEffect() @@ -1300,41 +1253,8 @@ void SpikesDeathEffect::draw(const SceneRenderer &) glTranslatef(position[0],position[1],position[2]); glRotatef(180+rotation[2]/deg2Rad,0,0,1); - color[0] = 108.0f/256.0f; - color[1] = 16.0f/256.0f; - color[2] = 16.0f/256.0f; - - /*float deltas[3]; - - deltas[0] = 1.0f - color[0]; - deltas[1] = 1.0f - color[1]; - deltas[2] = 1.0f - color[2]; - - float ageParam = age/lifetime; - - float alpha = 1.0f-(ageParam*0.5f); - if (alpha < 0.005f) - alpha = 0.005f; + color = glm::vec3(108.0f / 256.0f, 16.0f / 256.0f, 16.0f / 256.0f); - color[0] += deltas[0] *ageParam; - color[1] += deltas[1] *ageParam; - color[2] += deltas[2] *ageParam; - - glColor4f(color[0],color[1],color[2],alpha); - glDepthMask(0); - - glPushMatrix(); - glTranslatef(0,0,0.5f); - drawRingXY(radius*0.75f,1.5f + (ageParam/1.0f * 10),0.5f*age,0.5f); - drawRingXY(radius,-0.5f,0.5f+ age,0.5f); - - glTranslatef(-1.5,0,0); - glRotatef(90,0,0,1); - drawRingYZ(radius,3,0,0,position[2]+0.5f); - glPopMatrix(); - - glColor4f(1,1,1,1); - glDepthMask(1);*/ glPopMatrix(); } @@ -1384,9 +1304,7 @@ void StdLandEffect::draw(const SceneRenderer &) ringState.setState(); - color[0] = 1; - color[1] = 1; - color[2] = 1; + color = glm::vec3(1.0f); glColor4f(color[0],color[1],color[2],1.0f-(age/lifetime)); glDepthMask(0); @@ -1444,11 +1362,7 @@ void StdGMPuffEffect::draw(const SceneRenderer &) { glPushMatrix(); - float pos[3]; - - pos[0] = position[0] + velocity[0] * age; - pos[1] = position[1] + velocity[1] * age; - pos[2] = position[2] + velocity[2] * age; + auto pos = position + velocity * age; glTranslatef(pos[0],pos[1],pos[2]); glRotatef(180+rotation[2]/deg2Rad,0,0,1); @@ -1456,7 +1370,7 @@ void StdGMPuffEffect::draw(const SceneRenderer &) ringState.setState(); - color[0] = color[1] = color[2] = 1; + color = glm::vec3(1.0f); float alpha = 0.5f-(age/lifetime); if (alpha < 0.000001f) @@ -1556,13 +1470,9 @@ void SmokeGMPuffEffect::draw(const SceneRenderer &) { glPushMatrix(); - float pos[3]; - float vertDrift = 1.5f * age; - pos[0] = position[0] + velocity[0] * age; - pos[1] = position[1] + velocity[1] * age; - pos[2] = position[2] + velocity[2] * age; + auto pos = position + velocity * age; glTranslatef(pos[0]+jitter.x,pos[1]+jitter.y,pos[2]+jitter.z+vertDrift); @@ -1573,7 +1483,7 @@ void SmokeGMPuffEffect::draw(const SceneRenderer &) ringState.setState(); glColor4f(1,1,1,1); - color[0] = color[1] = color[2] = 1; + color = glm::vec3(1.0f); float alpha = 0.5f-(age/lifetime); if (alpha < 0.000001f) @@ -1633,11 +1543,7 @@ void StdRicoEffect::draw(const SceneRenderer &) { glPushMatrix(); - float pos[3]; - - pos[0] = position[0] + velocity[0] * age; - pos[1] = position[1] + velocity[1] * age; - pos[2] = position[2] + velocity[2] * age; + auto pos = position + velocity * age; glTranslatef(pos[0],pos[1],pos[2]); glRotatef((rotation[2]/deg2Rad)+180,0,0,1); @@ -1645,7 +1551,7 @@ void StdRicoEffect::draw(const SceneRenderer &) ringState.setState(); - color[0] = color[1] = color[2] = 1; + color = glm::vec3(1.0f); float alpha = 0.5f-(age/lifetime); if (alpha < 0.000001f) @@ -1704,11 +1610,7 @@ void StdShotTeleportEffect::draw(const SceneRenderer &) { glPushMatrix(); - float pos[3]; - - pos[0] = position[0] + velocity[0] * age; - pos[1] = position[1] + velocity[1] * age; - pos[2] = position[2] + velocity[2] * age; + auto pos = position + velocity * age; glTranslatef(pos[0],pos[1],pos[2]); glRotatef((rotation[2]/deg2Rad),0,0,1); @@ -1717,7 +1619,7 @@ void StdShotTeleportEffect::draw(const SceneRenderer &) ringState.setState(); - color[0] = color[1] = color[2] = 1; + color = glm::vec3(1.0f); float alpha = 1.0f; @@ -1736,82 +1638,70 @@ void StdShotTeleportEffect::draw(const SceneRenderer &) //******************************** geo utiliys******************************** -static void RadialToCartesian(float angle, float rad, float *pos) +static glm::vec2 RadialToCartesian(float angle) { - pos[0] = sinf(angle*deg2Rad)*rad; - pos[1] = cosf(angle*deg2Rad)*rad; + float radians = angle * deg2Rad; + auto pos = glm::vec2(sin(radians), cos(radians)); + + return pos; } static void drawRingXY(float rad, float z, float topsideOffset, float bottomUV, float topUV, int segments ) { + auto nextNormal = glm::vec2(0.0f, 1.0f); + auto nextPos = nextNormal * rad; + auto nextPos2 = nextNormal * (rad + topsideOffset); + glBegin(GL_TRIANGLE_STRIP); for ( int i = 0; i < segments; i ++) { - float thisAng = 360.0f/segments * i; - float nextAng = 360.0f/segments * (i+1); + float nextAng = 360.0f / segments * (i + 1); if ( i+1 >= segments ) nextAng = 0; - float thispos[2]; - float nextPos[2]; - - float thispos2[2]; - float nextPos2[2]; - - float thisNormal[3] = {0}; - float nextNormal[3] = {0}; + const auto thispos = nextPos; + const auto thisNormal = nextNormal; + nextNormal = RadialToCartesian(nextAng); + nextPos = nextNormal * rad; - RadialToCartesian(thisAng,rad,thispos); - RadialToCartesian(thisAng,1,thisNormal); - RadialToCartesian(nextAng,rad,nextPos); - RadialToCartesian(nextAng,1,nextNormal); - - RadialToCartesian(thisAng,rad+topsideOffset,thispos2); - RadialToCartesian(nextAng,rad+topsideOffset,nextPos2); + const auto thispos2 = nextPos2; + nextPos2 = nextNormal * (rad + topsideOffset); // the "inside" - glBegin(GL_TRIANGLE_STRIP); - - glNormal3f(-thisNormal[0],-thisNormal[1],-thisNormal[2]); + glNormal(-thisNormal); glTexCoord2f(0,bottomUV); - glVertex3f(thispos[0],thispos[1],0); + glVertex(thispos); - glNormal3f(-nextNormal[0],-nextNormal[1],-nextNormal[2]); + glNormal(-nextNormal); glTexCoord2f(1,bottomUV); - glVertex3f(nextPos[0],nextPos[1],0); + glVertex(nextPos); - glNormal3f(-thisNormal[0],-thisNormal[1],-thisNormal[2]); + glNormal(-thisNormal); glTexCoord2f(0,topUV); - glVertex3f(thispos2[0],thispos2[1],z); + glVertex(thispos2, z); - glNormal3f(-nextNormal[0],-nextNormal[1],-nextNormal[2]); + glNormal(-nextNormal); glTexCoord2f(1,topUV); - glVertex3f(nextPos2[0],nextPos2[1],z); - - glEnd(); + glVertex(nextPos2, z); // the "outside" - glBegin(GL_TRIANGLE_STRIP); - - glNormal3f(thisNormal[0],thisNormal[1],thisNormal[2]); + glNormal(thisNormal); glTexCoord2f(0,topUV); - glVertex3f(thispos2[0],thispos2[1],z); + glVertex(thispos2, z); - glNormal3f(nextNormal[0],nextNormal[1],nextNormal[2]); + glNormal(nextNormal); glTexCoord2f(1,topUV); - glVertex3f(nextPos2[0],nextPos2[1],z); + glVertex(nextPos2, z); - glNormal3f(thisNormal[0],thisNormal[1],thisNormal[2]); + glNormal(thisNormal); glTexCoord2f(0,bottomUV); - glVertex3f(thispos[0],thispos[1],0); + glVertex(thispos); - glNormal3f(nextNormal[0],nextNormal[1],nextNormal[2]); + glNormal(nextNormal); glTexCoord2f(1,bottomUV); - glVertex3f(nextPos[0],nextPos[1],0); - - glEnd(); - + glVertex(nextPos); } + glEnd(); } static float clampedZ(float z, float offset) @@ -1824,72 +1714,63 @@ static float clampedZ(float z, float offset) static void drawRingYZ(float rad, float z, float topsideOffset, float bottomUV, float ZOffset, float topUV, int segments) { + float nextAng = 0.0f; + auto nextNormal = glm::vec2(0.0f, 1.0f); + auto nextPos = nextNormal * rad; + auto nextPos2 = nextNormal * (rad + topsideOffset); + glBegin(GL_TRIANGLE_STRIP); for ( int i = 0; i < segments; i ++) { - float thisAng = 360.0f/segments * i; - float nextAng = 360.0f/segments * (i+1); + nextAng = 360.0f/segments * (i+1); if ( i+1 >= segments ) nextAng = 0; - float thispos[2]; - float nextPos[2]; - - float thispos2[2]; - float nextPos2[2]; - - float thisNormal[3] = {0}; - float nextNormal[3] = {0}; - - RadialToCartesian(thisAng,rad,thispos); - RadialToCartesian(thisAng,1,thisNormal); - RadialToCartesian(nextAng,rad,nextPos); - RadialToCartesian(nextAng,1,nextNormal); + const auto thispos = nextPos; + const auto thisNormal = nextNormal; + nextNormal = RadialToCartesian(nextAng); + nextPos = nextNormal * rad; + nextPos.x = clampedZ(nextPos.x, ZOffset); - RadialToCartesian(thisAng,rad+topsideOffset,thispos2); - RadialToCartesian(nextAng,rad+topsideOffset,nextPos2); + const auto thispos2 = nextPos2; + nextPos2 = nextNormal * (rad + topsideOffset); + nextPos2.x = clampedZ(nextPos2.x, ZOffset); // the "inside" - glBegin(GL_TRIANGLE_STRIP); - - glNormal3f(-thisNormal[0],-thisNormal[1],-thisNormal[2]); + glNormal(-thisNormal); glTexCoord2f(0,bottomUV); - glVertex3f(0,thispos[1],clampedZ(thispos[0],ZOffset)); + glVertex3f(0, thispos.y, thispos.x); - glNormal3f(-nextNormal[0],-nextNormal[1],-nextNormal[2]); + glNormal(-nextNormal); glTexCoord2f(1,bottomUV); - glVertex3f(0,nextPos[1],clampedZ(nextPos[0],ZOffset)); + glVertex3f(0, nextPos.y, nextPos.x); - glNormal3f(-thisNormal[0],-thisNormal[1],-thisNormal[2]); + glNormal(-thisNormal); glTexCoord2f(0,topUV); - glVertex3f(z,thispos2[1],clampedZ(thispos2[0],ZOffset)); + glVertex3f(z, thispos2.y, thispos2.x); - glNormal3f(-nextNormal[0],-nextNormal[1],-nextNormal[2]); + glNormal(-nextNormal); glTexCoord2f(1,topUV); - glVertex3f(z,nextPos2[1],clampedZ(nextPos2[0],ZOffset)); - - glEnd(); + glVertex3f(z, nextPos2.y, nextPos2.x); // the "outside" - glBegin(GL_TRIANGLE_STRIP); - - glNormal3f(thisNormal[0],thisNormal[1],thisNormal[2]); + glNormal(thisNormal); glTexCoord2f(0,topUV); - glVertex3f(z,thispos2[1],clampedZ(thispos2[0],ZOffset)); + glVertex3f(z, thispos2.y, thispos2.x); - glNormal3f(nextNormal[0],nextNormal[1],nextNormal[2]); + glNormal(nextNormal); glTexCoord2f(1,topUV); - glVertex3f(z,nextPos2[1],clampedZ(nextPos2[0],ZOffset)); + glVertex3f(z, nextPos2.y, nextPos2.x); - glNormal3f(thisNormal[0],thisNormal[1],thisNormal[2]); + glNormal(thisNormal); glTexCoord2f(0,bottomUV); - glVertex3f(0,thispos[1],clampedZ(thispos[0],ZOffset)); + glVertex3f(0, thispos.y, thispos.x); - glNormal3f(nextNormal[0],nextNormal[1],nextNormal[2]); + glNormal(nextNormal); glTexCoord2f(1,bottomUV); - glVertex3f(0,nextPos[1],clampedZ(nextPos[0],ZOffset)); + glVertex3f(0, nextPos.y, nextPos.x); - glEnd(); } + glEnd(); } diff --git a/src/bzflag/effectsRenderer.h b/src/bzflag/effectsRenderer.h index 520ee86d42..710fe7e1ff 100644 --- a/src/bzflag/effectsRenderer.h +++ b/src/bzflag/effectsRenderer.h @@ -44,9 +44,9 @@ class BasicEffect BasicEffect(); virtual ~BasicEffect() {}; - virtual void setPos ( const float *pos, const float *rot ); - virtual void setVel ( const float *vel ); - virtual void setColor( const float *rgb ); + virtual void setPos(const glm::vec3 &pos, const float *rot); + virtual void setVel (const glm::vec3 &vel); + virtual void setColor(const glm::vec3 &rgb); virtual void setStartTime ( float time ); virtual void freeContext(void) {}; @@ -57,10 +57,10 @@ class BasicEffect protected: - float position[3]; + glm::vec3 position; float rotation[3]; - float velocity[3]; - float color[3]; + glm::vec3 velocity; + glm::vec3 color; float startTime; float lifetime; float lastTime; @@ -86,7 +86,7 @@ class DeathEffect : public BasicEffect, public TankDeathOverride { return true; } - virtual bool GetDeathVector ( fvec3 &UNUSED(vel) ) + virtual bool GetDeathVector (glm::vec3 &UNUSED(vel)) { return false; } @@ -120,32 +120,42 @@ class EffectsRenderer : public Singleton void rebuildContext(void); // spawn flashes - void addSpawnEffect ( const float* rgb, const float* pos ); + void addSpawnEffect(const glm::vec3 &rgb, const glm::vec3 &pos); std::vector getSpawnEffectTypes ( void ); // shot flashes - void addShotEffect ( const float* rgb, const float* pos, float rot, const float* vel = NULL, int _type = -1 ); + void addShotEffect ( + const glm::vec3 &rgb, + const glm::vec3 &pos, + float rot, + const glm::vec3 &vel, + int _type = -1); std::vector getShotEffectTypes ( void ); // gm puffs - void addGMPuffEffect ( const float* pos, float rot[2], const float* vel = NULL ); + void addGMPuffEffect(const glm::vec3 &pos, float rot[2]); std::vector getGMPuffEffectTypes ( void ); // death effects - DeathEffect* addDeathEffect ( const float* rgb, const float* pos, float rot, int reason, Player *player, - FlagType* flag = NULL ); + DeathEffect* addDeathEffect ( + const glm::vec3 &rgb, + const glm::vec3 &pos, + float rot, + int reason, + Player *player, + FlagType* flag = NULL ); std::vector getDeathEffectTypes ( void ); // landing effects - void addLandEffect ( const float* rgb, const float* pos, float rot ); + void addLandEffect (const glm::vec3 &rgb, const glm::vec3 &pos, float rot); std::vector getLandEffectTypes ( void ); // rico effect - void addRicoEffect ( const float* pos, float rot[2], const float* vel = NULL ); + void addRicoEffect(const glm::vec3 &pos, float rot[2]); std::vector getRicoEffectTypes ( void ); // shot teleport effect - void addShotTeleportEffect ( const float* pos, float rot[2], const float* vel = NULL ); + void addShotTeleportEffect(const glm::vec3 &pos, float rot[2]); std::vector getShotTeleportEffectTypes ( void ); diff --git a/src/bzflag/playing.cxx b/src/bzflag/playing.cxx index cb1c8bf5a6..0059a4361e 100644 --- a/src/bzflag/playing.cxx +++ b/src/bzflag/playing.cxx @@ -27,6 +27,8 @@ #include #endif #include +#define GLM_ENABLE_EXPERIMENTAL +#include // common headers #include "AccessList.h" @@ -1443,7 +1445,7 @@ static void updateFlag(FlagType* flag) } else { - const float* color = flag->getColor(); + const auto &color = flag->getColor(); hud->setColor(color[0], color[1], color[2]); hud->setAlert(2, flag->flagName.c_str(), 3.0f, flag->endurance == FlagSticky); } @@ -2348,7 +2350,8 @@ static void handleServerMessage(bool human, uint16_t code, case MsgAlive: { PlayerId id; - float pos[3], forward; + glm::vec3 pos; + float forward; msg = nboUnpackUByte(msg, id); msg = nboUnpackVector(msg, pos); msg = nboUnpackFloat(msg, forward); @@ -2356,7 +2359,7 @@ static void handleServerMessage(bool human, uint16_t code, if ((playerIndex >= 0) || (playerIndex == -2)) { - static const float zero[3] = { 0.0f, 0.0f, 0.0f }; + static const auto zero = glm::vec3(0.0f); Player* tank = getPlayerByIndex(playerIndex); if (tank == myTank) { @@ -2393,7 +2396,7 @@ static void handleServerMessage(bool human, uint16_t code, { if (myTank->getFlag() == Flags::Colorblindness) { - static float cbColor[4] = {1,1,1,1}; + static auto cbColor = glm::vec4(1.0f); EFFECTS.addSpawnEffect(cbColor, pos); } else @@ -2486,16 +2489,14 @@ static void handleServerMessage(bool human, uint16_t code, else if (victimPlayer) { victimPlayer->setExplode(TimeKeeper::getTick()); - const float* pos = victimPlayer->getPosition(); + const auto &pos = victimPlayer->getPosition(); const bool localView = isViewTank(victimPlayer); if (reason == GotRunOver) playSound(SFX_RUNOVER, pos, killerLocal == myTank, localView); else playSound(SFX_EXPLOSION, pos, killerLocal == myTank, localView); - float explodePos[3]; - explodePos[0] = pos[0]; - explodePos[1] = pos[1]; - explodePos[2] = pos[2] + victimPlayer->getMuzzleHeight(); + auto explodePos = pos; + explodePos[2] += victimPlayer->getMuzzleHeight(); // TODO hook this back up for 2.4.4 or later TankDeathOverride* death = NULL; @@ -2721,7 +2722,7 @@ static void handleServerMessage(bool human, uint16_t code, && (Team::isColorTeam(myTank->getTeam()))) { hud->setAlert(1, "Team Grab!!!", 3.0f, false); - const float* pos = tank->getPosition(); + const auto &pos = tank->getPosition(); playWorldSound(SFX_TEAMGRAB, pos, false); } } @@ -2820,12 +2821,10 @@ static void handleServerMessage(bool human, uint16_t code, remotePlayers[i]->isAlive() && remotePlayers[i]->getTeam() == capturedTeam) { - const float* pos = remotePlayers[i]->getPosition(); + const auto &pos = remotePlayers[i]->getPosition(); playWorldSound(SFX_EXPLOSION, pos, false); - float explodePos[3]; - explodePos[0] = pos[0]; - explodePos[1] = pos[1]; - explodePos[2] = pos[2] + remotePlayers[i]->getMuzzleHeight(); + auto explodePos = pos; + explodePos[2] += remotePlayers[i]->getMuzzleHeight(); // todo hook this back up for 2.4.4. or later TankDeathOverride *death = NULL; @@ -2916,8 +2915,7 @@ static void handleServerMessage(bool human, uint16_t code, if (SceneRenderer::instance().useQuality() >= 2) { - float shotPos[3]; - shooter->getMuzzle(shotPos); + const auto shotPos = shooter->getMuzzle(); // if you are driving with a tank in observer mode // and do not want local shot effects, @@ -2941,7 +2939,7 @@ static void handleServerMessage(bool human, uint16_t code, if (human) { - const float* pos = firingInfo.shot.pos; + const auto &pos = firingInfo.shot.pos; const bool importance = false; const bool localSound = isViewTank(shooter); if (firingInfo.flagType == Flags::ShockWave) @@ -3074,7 +3072,7 @@ static void handleServerMessage(bool human, uint16_t code, const Teleporter* teleporter = world->getTeleporter(int(to), face); if (teleporter) { - const float* pos = teleporter->getPosition(); + const auto pos = teleporter->getPosition(); tank->setTeleport(TimeKeeper::getTick(), short(from), short(to)); playWorldSound(SFX_TELEPORT, pos); } @@ -3579,7 +3577,7 @@ static void updateFlags(float dt) Player* tank = lookupPlayer(flag.owner); if (tank) { - const float* pos = tank->getPosition(); + const auto &pos = tank->getPosition(); flag.position[0] = pos[0]; flag.position[1] = pos[1]; flag.position[2] = pos[2] + tank->getDimensions()[2]; @@ -3590,8 +3588,8 @@ static void updateFlags(float dt) FlagSceneNode::waveFlag(dt); } -bool addExplosion(const float* _pos, - float size, float duration, bool grounded) +bool addExplosion(const glm::vec3 &_pos, + float size, float duration, bool grounded) { // ignore if no prototypes available; if (prototypeExplosions.empty()) @@ -3609,10 +3607,7 @@ bool addExplosion(const float* _pos, // make a copy and initialize it BillboardSceneNode* newExplosion = prototypeExplosions[index]->copy(); - GLfloat pos[3]; - pos[0] = _pos[0]; - pos[1] = _pos[1]; - pos[2] = _pos[2]; + const auto pos = _pos; newExplosion->move(pos); newExplosion->setSize(size); newExplosion->setDuration(duration); @@ -3647,7 +3642,7 @@ bool addExplosion(const float* _pos, // make a copy and initialize it BillboardSceneNode* newExpl = prototypeExplosions[idx]->copy(); - GLfloat explPos[3]; + glm::vec3 explPos; explPos[0] = _pos[0]+(float)(bzfrand()*12.0 - 6.0); explPos[1] = _pos[1]+(float)(bzfrand()*12.0 - 6.0); explPos[2] = _pos[2]+(float)(bzfrand()*10.0); @@ -3663,19 +3658,19 @@ bool addExplosion(const float* _pos, return true; } -void addTankExplosion(const float* pos) +void addTankExplosion(const glm::vec3 &pos) { addExplosion(pos, BZDB.eval(StateDatabase::BZDB_TANKEXPLOSIONSIZE), 1.2f, false); } -void addShotExplosion(const float* pos) +void addShotExplosion(const glm::vec3 &pos) { // only play explosion sound if you see an explosion if (addExplosion(pos, 1.2f * BZDBCache::tankLength, 0.8f, false)) playWorldSound(SFX_SHOT_BOOM, pos); } -void addShotPuff(const float* pos, float azimuth, float elevation) +void addShotPuff(const glm::vec3 &pos, float azimuth, float elevation) { bool useClasicPuff = false; @@ -3689,7 +3684,7 @@ void addShotPuff(const float* pos, float azimuth, float elevation) } float rots[2] = {azimuth,elevation}; - EFFECTS.addGMPuffEffect(pos, rots, NULL); + EFFECTS.addGMPuffEffect(pos, rots); } // process pending input events @@ -3838,7 +3833,7 @@ static void handleFlagTransferred( Player *fromTank, Player *toTank, int flagInd if ((fromTank == myTank) || (toTank == myTank)) updateFlag(myTank->getFlag()); - const float *pos = toTank->getPosition(); + const auto &pos = toTank->getPosition(); if (f.type->flagTeam != ::NoTeam) { if ((toTank->getTeam() == myTank->getTeam()) && (f.type->flagTeam != myTank->getTeam())) @@ -3922,7 +3917,7 @@ static bool gotBlowedUp(BaseLocalPlayer* tank, } else { - const float* pos = tank->getPosition(); + const auto &pos = tank->getPosition(); if (reason == GotRunOver) { playWorldSound(SFX_RUNOVER, pos, @@ -3937,11 +3932,9 @@ static bool gotBlowedUp(BaseLocalPlayer* tank, if (tank != myTank &&(!death || death->ShowExplosion())) { - const float* pos = tank->getPosition(); - float explodePos[3]; - explodePos[0] = pos[0]; - explodePos[1] = pos[1]; - explodePos[2] = pos[2] + tank->getMuzzleHeight(); + const auto &pos = tank->getPosition(); + auto explodePos = pos; + explodePos[2] += tank->getMuzzleHeight(); addTankExplosion(explodePos); } @@ -4110,16 +4103,17 @@ static void checkEnvironment() if (TimeKeeper::getTick()-lastGrabSent > 0.2) { // grab any and all flags i'm driving over - const float* tpos = myTank->getPosition(); + const auto &tpos = myTank->getPosition(); const float radius = myTank->getRadius(); const float radius2 = (radius + BZDBCache::flagRadius) * (radius + BZDBCache::flagRadius); for (int i = 0; i < numFlags; i++) { if (world->getFlag(i).type == Flags::Null || world->getFlag(i).status != FlagOnGround) continue; - const float* fpos = world->getFlag(i).position; - if ((fabs(tpos[2] - fpos[2]) < 0.1f) && ((tpos[0] - fpos[0]) * (tpos[0] - fpos[0]) + - (tpos[1] - fpos[1]) * (tpos[1] - fpos[1]) < radius2)) + const auto &fpos = world->getFlag(i).position; + if ((fabs(tpos[2] - fpos[2]) < 0.1f) + && (glm::distance2(glm::vec2(tpos), glm::vec2(fpos)) + < radius2)) { serverLink->sendGrabFlag(i); lastGrabSent=TimeKeeper::getTick(); @@ -4183,7 +4177,7 @@ static void checkEnvironment() // if not dead yet, see if i got run over by the steamroller else { - const float* myPos = myTank->getPosition(); + const auto &myPos = myTank->getPosition(); const float myRadius = myTank->getRadius(); for (i = 0; i < curMaxPlayers; i++) { @@ -4192,7 +4186,7 @@ static void checkEnvironment() ((myPos[2] < 0.0f) && remotePlayers[i]->isAlive() && !remotePlayers[i]->isPhantomZoned()))) { - const float* pos = remotePlayers[i]->getPosition(); + const auto &pos = remotePlayers[i]->getPosition(); if (pos[2] < 0.0f) continue; if (remotePlayers[i]->getTeam() != RogueTeam && !World::getWorld()->allowTeamKills() && remotePlayers[i]->getTeam() == myTank->getTeam()) continue; @@ -4200,9 +4194,9 @@ static void checkEnvironment() { const float radius = myRadius + BZDB.eval(StateDatabase::BZDB_SRRADIUSMULT) * remotePlayers[i]->getRadius(); - const float distSquared = - hypotf(hypotf(myPos[0] - pos[0], - myPos[1] - pos[1]), (myPos[2] - pos[2]) * 2.0f); + auto delta = myPos - pos; + delta.z *= 2.0f; + const float distSquared = glm::length(delta); if (distSquared < radius) gotBlowedUp(myTank, GotRunOver, remotePlayers[i]->getId()); } @@ -4268,8 +4262,7 @@ void setLookAtMarker(void) // get info about my tank const float c = cosf(- myTank->getAngle()); const float s = sinf(- myTank->getAngle()); - const float *p = myTank->getPosition(); - const fvec3 myPos(p[0],p[1],p[2]); + const auto myPos = myTank->getPosition(); // initialize best target Player *bestTarget = NULL; @@ -4282,8 +4275,7 @@ void setLookAtMarker(void) continue; // compute position in my local coordinate system - const fvec3 rPos(remotePlayers[i]->getPosition()[0],remotePlayers[i]->getPosition()[1], - remotePlayers[i]->getPosition()[2]); + const auto rPos = remotePlayers[i]->getPosition(); const float x = (c * (rPos.x - myPos.x)) - (s * (rPos.y - myPos.y)); const float y = (s * (rPos.x - myPos.x)) + (c * (rPos.y - myPos.y)); @@ -4299,7 +4291,7 @@ void setLookAtMarker(void) if (inLookRange(a, d, bestDistance, remotePlayers[i])) { // check and see if we can cast a ray from our point to the object - fvec3 vec = rPos - myPos; + auto vec = rPos - myPos; Ray ray = Ray(myPos, vec); @@ -4355,9 +4347,10 @@ void setLookAtMarker(void) if (myTank->getFlag() == Flags::Colorblindness) markercolor = RogueTeam; - hud->AddEnhancedNamedMarker(Float3ToVec3(bestTarget->getPosition()), - Float3ToVec3(Team::getTankColor(markercolor)), - label, isFriendly(bestTarget), 2.0f); + hud->AddEnhancedNamedMarker( + bestTarget->getPosition(), + Team::getTankColor(markercolor), + label, isFriendly(bestTarget), 2.0f); } static inline bool tankHasShotType(const Player* tank, const FlagType* ft) @@ -4391,7 +4384,7 @@ void setTarget() if (!remotePlayers[i] || !remotePlayers[i]->isAlive()) continue; // compute position in my local coordinate system - const float* pos = remotePlayers[i]->getPosition(); + const auto &pos = remotePlayers[i]->getPosition(); const float x = c * (pos[0] - x0) - s * (pos[1] - y0); const float y = s * (pos[0] - x0) + c * (pos[1] - y0); @@ -4509,7 +4502,7 @@ static void setHuntTarget() if (!remotePlayers[i] || !remotePlayers[i]->isAlive()) continue; // compute position in my local coordinate system - const float* pos = remotePlayers[i]->getPosition(); + const auto &pos = remotePlayers[i]->getPosition(); const float x = c * (pos[0] - x0) - s * (pos[1] - y0); const float y = s * (pos[0] - x0) + c * (pos[1] - y0); @@ -4565,7 +4558,7 @@ static void setHuntTarget() } if (!pulse.isOn()) { - const float* bestTargetPosition = bestTarget->getPosition(); + const auto &bestTargetPosition = bestTarget->getPosition(); playWorldSound(SFX_HUNT, bestTargetPosition); pulse.setClock(1.0f); } @@ -4591,7 +4584,7 @@ static std::vector obstacleList; // for robots static void addObstacle(std::vector& rgnList, const Obstacle& obstacle) { float p[4][2]; - const float* c = obstacle.getPosition(); + const auto &c = obstacle.getPosition(); const float tankRadius = BZDBCache::tankRadius; if (BZDBCache::tankHeight < c[2]) @@ -4658,7 +4651,7 @@ static void makeObstacleList() obstacleList.clear(); // FIXME -- shouldn't hard code game area - float gameArea[4][2]; + glm::vec2 gameArea[4]; float worldSize = BZDBCache::worldSize; gameArea[0][0] = -0.5f * worldSize + tankRadius; gameArea[0][1] = -0.5f * worldSize + tankRadius; @@ -4840,21 +4833,21 @@ static void checkEnvironment(RobotPlayer* tank) else { bool dead = false; - const float* myPos = tank->getPosition(); + const auto &myPos = tank->getPosition(); const float myRadius = tank->getRadius(); if (((myTank->getFlag() == Flags::Steamroller) || ((tank->getFlag() == Flags::Burrow) && myTank->isAlive() && !myTank->isPhantomZoned())) && !myTank->isPaused()) { - const float* pos = myTank->getPosition(); + const auto &pos = myTank->getPosition(); if (pos[2] >= 0.0f) { const float radius = myRadius + (BZDB.eval(StateDatabase::BZDB_SRRADIUSMULT) * myTank->getRadius()); - const float distSquared = - hypotf(hypotf(myPos[0] - pos[0], - myPos[1] - pos[1]), (myPos[2] - pos[2]) * 2.0f); + auto delta = myPos - pos; + delta.z *= 2.0f; + const float distSquared = glm::length(delta); if (distSquared < radius) { gotBlowedUp(tank, GotRunOver, myTank->getId()); @@ -4869,13 +4862,13 @@ static void checkEnvironment(RobotPlayer* tank) ((tank->getFlag() == Flags::Burrow) && remotePlayers[i]->isAlive() && !remotePlayers[i]->isPhantomZoned()))) { - const float* pos = remotePlayers[i]->getPosition(); + const auto &pos = remotePlayers[i]->getPosition(); if (pos[2] < 0.0f) continue; const float radius = myRadius + (BZDB.eval(StateDatabase::BZDB_SRRADIUSMULT) * remotePlayers[i]->getRadius()); - const float distSquared = - hypotf(hypotf(myPos[0] - pos[0], - myPos[1] - pos[1]), (myPos[2] - pos[2]) * 2.0f); + auto delta = myPos - pos; + delta.z *= 2.0f; + const float distSquared = glm::length(delta); if (distSquared < radius) { gotBlowedUp(tank, GotRunOver, remotePlayers[i]->getId()); @@ -5050,10 +5043,10 @@ static void enteringServer(const void *buf) // observer colors are actually cyan, make them black const bool observer = (myTank->getTeam() == ObserverTeam); - const GLfloat* borderColor; + glm::vec3 borderColor; if (observer) { - static const GLfloat black[4] = {0.0f, 0.0f, 0.0f, 1.0f}; + static const auto black = glm::vec3(0.0f); borderColor = black; } else @@ -5413,13 +5406,10 @@ void leaveGame() serverNetworkAddress = Address(); // reset viewpoint - float eyePoint[3], targetPoint[3]; - eyePoint[0] = 0.0f; - eyePoint[1] = 0.0f; - eyePoint[2] = 0.0f + BZDB.eval(StateDatabase::BZDB_MUZZLEHEIGHT); - targetPoint[0] = eyePoint[0] - 1.0f; - targetPoint[1] = eyePoint[1] + 0.0f; - targetPoint[2] = eyePoint[2] + 0.0f; + const auto eyePoint + = glm::vec3(0.0f, 0.0f, BZDB.eval(StateDatabase::BZDB_MUZZLEHEIGHT)); + auto targetPoint = eyePoint; + targetPoint.x -= 1.0f; sceneRenderer->getViewFrustum().setProjection((float)(60.0 * M_PI / 180.0), NearPlaneNormal, FarPlaneDefault, @@ -5775,7 +5765,7 @@ static void drawUI() // static bool trackPlayerShot(Player* target, - float* eyePoint, float* targetPoint) + glm::vec3 &eyePoint, glm::vec3 &targetPoint) { // follow the first shot if (BZDB.isTrue("trackShots")) @@ -5800,30 +5790,23 @@ static bool trackPlayerShot(Player* target, } if (sp != NULL) { - const float* pos = sp->getPosition(); - const float* vel = sp->getVelocity(); - const float speed = sqrtf(vel[0]*vel[0] + vel[1]*vel[1] + vel[2]*vel[2]); - if (speed > 0.0f) + const auto pos = sp->getPosition(); + const auto vel = sp->getVelocity(); + if (vel.x || vel.y || vel.z) { - const float ilen = 1.0f / speed; - const float dir[3] = {ilen * vel[0], ilen * vel[1], ilen * vel[2]}; - float topDir[3] = {1.0f, 0.0f, 0.0f}; - const float hlen = sqrtf(dir[0]*dir[0] + dir[1]*dir[1]); - if (hlen > 0.0f) + const auto dir = glm::normalize(vel); + auto topDir = glm::vec3(1.0f, 0.0f, 0.0f); + if (dir.x || dir.y) { - topDir[2] = hlen; + const auto dirXY = glm::vec2(dir); + const float hlen = glm::length(dirXY); const float hfactor = -fabsf(dir[2] / hlen); - topDir[0] = hfactor * dir[0]; - topDir[1] = hfactor * dir[1]; + topDir = glm::vec3(hfactor * dirXY, hlen); } const float offset = -10.0f; const float tOffset = +2.0f; - eyePoint[0] = pos[0] + (offset * dir[0]) + (tOffset * topDir[0]); - eyePoint[1] = pos[1] + (offset * dir[1]) + (tOffset * topDir[1]); - eyePoint[2] = pos[2] + (offset * dir[2]) + (tOffset * topDir[2]); - targetPoint[0] = eyePoint[0] + dir[0]; - targetPoint[1] = eyePoint[1] + dir[1]; - targetPoint[2] = eyePoint[2] + dir[2]; + eyePoint = pos + offset * dir + tOffset * topDir; + targetPoint = eyePoint + dir; return true; } } @@ -5927,17 +5910,16 @@ void drawFrame(const float dt) // get media object static BzfMedia* media = PlatformFactory::getMedia(); - static const float defaultPos[3] = { 0.0f, 0.0f, 0.0f }; - static const float defaultDir[3] = { 1.0f, 0.0f, 0.0f }; + static const auto defaultPos = glm::vec3(0.0f); + static const auto defaultDir = glm::vec2(1.0f, 0.0f); static int frameCount = 0; static float cumTime = 0.0f; - const float* myTankPos; - const float* myTankDir; + glm::vec3 myTankPos; + glm::vec2 myTankDir; float myTankAngle = 0.0f; GLfloat fov; - GLfloat eyePoint[3]; - GLfloat targetPoint[3]; + glm::vec3 targetPoint; checkDirtyControlPanel(controlPanel); @@ -5982,12 +5964,9 @@ void drawFrame(const float dt) fov *= (float)(M_PI / 180.0); // set projection and view - eyePoint[0] = myTankPos[0]; - eyePoint[1] = myTankPos[1]; - eyePoint[2] = myTankPos[2] + muzzleHeight; - targetPoint[0] = eyePoint[0] + myTankDir[0]; - targetPoint[1] = eyePoint[1] + myTankDir[1]; - targetPoint[2] = eyePoint[2] + myTankDir[2]; + auto eyePoint = myTankPos; + eyePoint.z += muzzleHeight; + targetPoint = eyePoint + glm::vec3(myTankDir, 0.0f); if (devDriving || ROAM.isRoaming()) { @@ -6002,17 +5981,13 @@ void drawFrame(const float dt) target = ROAM.getTargetTank(); else target = myTank; - const float *targetTankDir = target->getForward(); + const auto &targetTankDir = target->getForward(); // fixed camera tracking target if (ROAM.getMode() == Roaming::roamViewTrack) { - eyePoint[0] = roam->pos[0]; - eyePoint[1] = roam->pos[1]; - eyePoint[2] = roam->pos[2]; - targetPoint[0] = target->getPosition()[0]; - targetPoint[1] = target->getPosition()[1]; - targetPoint[2] = target->getPosition()[2] + - target->getMuzzleHeight(); + eyePoint = roam->pos; + targetPoint = target->getPosition(); + targetPoint.z += target->getMuzzleHeight(); } // camera following target else if (ROAM.getMode() == Roaming::roamViewFollow) @@ -6022,23 +5997,18 @@ void drawFrame(const float dt) const bool slowKB = BZDB.isTrue("slowKeyboard"); if (slowKB == (BZDB.eval("roamSmoothTime") < 0.0f)) { - eyePoint[0] = target->getPosition()[0] - targetTankDir[0] * 40; - eyePoint[1] = target->getPosition()[1] - targetTankDir[1] * 40; - eyePoint[2] = target->getPosition()[2] + muzzleHeight * 6; - targetPoint[0] = target->getPosition()[0]; - targetPoint[1] = target->getPosition()[1]; - targetPoint[2] = target->getPosition()[2]; + eyePoint = target->getPosition(); + targetPoint = eyePoint; + eyePoint[0] -= targetTankDir[0] * 40; + eyePoint[1] -= targetTankDir[1] * 40; + eyePoint[2] += muzzleHeight * 6; } else { // the same as for the roamViewTrack mode - eyePoint[0] = roam->pos[0]; - eyePoint[1] = roam->pos[1]; - eyePoint[2] = roam->pos[2]; - targetPoint[0] = target->getPosition()[0]; - targetPoint[1] = target->getPosition()[1]; - targetPoint[2] = target->getPosition()[2] + - target->getMuzzleHeight(); + eyePoint = roam->pos; + targetPoint = target->getPosition(); + targetPoint.z += target->getMuzzleHeight(); if (BZDB.isSet("followOffsetZ")) targetPoint[2] += BZDB.eval("followOffsetZ"); } @@ -6049,12 +6019,9 @@ void drawFrame(const float dt) { if (!trackPlayerShot(target, eyePoint, targetPoint)) { - eyePoint[0] = target->getPosition()[0]; - eyePoint[1] = target->getPosition()[1]; - eyePoint[2] = target->getPosition()[2] + target->getMuzzleHeight(); - targetPoint[0] = eyePoint[0] + targetTankDir[0]; - targetPoint[1] = eyePoint[1] + targetTankDir[1]; - targetPoint[2] = eyePoint[2] + targetTankDir[2]; + eyePoint = target->getPosition(); + eyePoint.z += target->getMuzzleHeight(); + targetPoint = eyePoint + targetTankDir; hud->setAltitude(target->getPosition()[2]); } } @@ -6062,12 +6029,8 @@ void drawFrame(const float dt) else if (ROAM.getMode() == Roaming::roamViewFlag) { Flag* targetFlag = ROAM.getTargetFlag(); - eyePoint[0] = roam->pos[0]; - eyePoint[1] = roam->pos[1]; - eyePoint[2] = roam->pos[2]; - targetPoint[0] = targetFlag->position[0]; - targetPoint[1] = targetFlag->position[1]; - targetPoint[2] = targetFlag->position[2]; + eyePoint = roam->pos; + targetPoint = targetFlag->position; if (targetFlag->status != FlagOnTank) targetPoint[2] += muzzleHeight; else @@ -6082,21 +6045,17 @@ void drawFrame(const float dt) // free Roaming else { - float dir[3]; + glm::vec3 dir; dir[0] = cosf((float)(roam->phi * M_PI / 180.0)) * cosf((float)(roam->theta * M_PI / 180.0)); dir[1] = cosf((float)(roam->phi * M_PI / 180.0)) * sinf((float)(roam->theta * M_PI / 180.0)); dir[2] = sinf((float)(roam->phi * M_PI / 180.0)); - eyePoint[0] = roam->pos[0]; - eyePoint[1] = roam->pos[1]; - eyePoint[2] = roam->pos[2]; - targetPoint[0] = eyePoint[0] + dir[0]; - targetPoint[1] = eyePoint[1] + dir[1]; - targetPoint[2] = eyePoint[2] + dir[2]; + eyePoint = roam->pos; + targetPoint = eyePoint + dir; roamViewAngle = roam->theta; } if (!devDriving) { - float virtPos[] = {eyePoint[0], eyePoint[1], 0}; + const auto virtPos = glm::vec3(eyePoint[0], eyePoint[1], 0); if (myTank) myTank->move(virtPos, (float)(roamViewAngle * M_PI / 180.0)); } @@ -6210,15 +6169,12 @@ void drawFrame(const float dt) if (myTank) { const float hnp = 0.5f * NearPlane; // half near plane distance - const float* eye = viewFrustum.getEye(); - const float* dir = viewFrustum.getDirection(); - float clipPos[3]; - clipPos[0] = eye[0] + (dir[0] * hnp); - clipPos[1] = eye[1] + (dir[1] * hnp); - clipPos[2] = eye[2]; - const Obstacle* obs; - obs = world->inBuilding(clipPos, myTank->getAngle(), hnp, 0.0f, 0.0f); - if (obs != NULL) + const auto &eye = viewFrustum.getEye(); + const auto dir = glm::vec2(viewFrustum.getDirection()); + const auto clipPos = eye + glm::vec3(dir * hnp, 0.0f); + bool obs; + obs = world->inBuilding(clipPos, myTank->getAngle(), hnp, 0.0f); + if (obs) insideDim = true; } sceneRenderer->setDim(HUDDialogStack::get()->isActive() || insideDim || @@ -6286,9 +6242,9 @@ void drawFrame(const float dt) // FIXME -- this assumes up is along +z const float cFOV = cosf(fov); const float sFOV = sinf(fov); - targetPoint[0] = eyePoint[0] + cFOV*myTankDir[0] - sFOV*myTankDir[1]; - targetPoint[1] = eyePoint[1] + cFOV*myTankDir[1] + sFOV*myTankDir[0]; - targetPoint[2] = eyePoint[2] + myTankDir[2]; + targetPoint = eyePoint; + targetPoint[0] += cFOV*myTankDir[0] - sFOV*myTankDir[1]; + targetPoint[1] += cFOV*myTankDir[1] + sFOV*myTankDir[0]; viewFrustum.setView(eyePoint, targetPoint); // draw left channel @@ -6297,9 +6253,9 @@ void drawFrame(const float dt) // set up for drawing right channel mainWindow->setQuadrant(MainWindow::LowerRight); // FIXME -- this assumes up is along +z - targetPoint[0] = eyePoint[0] + cFOV*myTankDir[0] + sFOV*myTankDir[1]; - targetPoint[1] = eyePoint[1] + cFOV*myTankDir[1] - sFOV*myTankDir[0]; - targetPoint[2] = eyePoint[2] + myTankDir[2]; + targetPoint = eyePoint; + targetPoint[0] += cFOV*myTankDir[0] + sFOV*myTankDir[1]; + targetPoint[1] += cFOV*myTankDir[1] - sFOV*myTankDir[0]; viewFrustum.setView(eyePoint, targetPoint); // draw right channel @@ -6309,9 +6265,7 @@ void drawFrame(const float dt) // set up for drawing rear channel mainWindow->setQuadrant(MainWindow::UpperLeft); // FIXME -- this assumes up is along +z - targetPoint[0] = eyePoint[0] - myTankDir[0]; - targetPoint[1] = eyePoint[1] - myTankDir[1]; - targetPoint[2] = eyePoint[2] + myTankDir[2]; + targetPoint = eyePoint - glm::vec3(myTankDir, 0.0f); viewFrustum.setView(eyePoint, targetPoint); // draw rear channel @@ -6590,21 +6544,14 @@ static void roamSmoothFollow(Roaming::RoamingCamera& deltaCamera) const float speedY = BZDB.eval("followSpeedY"); const float speedZ = BZDB.eval("followSpeedZ"); - const float* pos = p->getPosition(); - const float* fwd = p->getForward(); - const float target[3] = - { - pos[0] - (fwd[0] * dist), - pos[1] - (fwd[1] * dist), - pos[2] + height - }; - const float* current = ROAM.getCamera()->pos; - const float delta[3] = - { - target[0] - current[0], - target[1] - current[1], - target[2] - current[2] - }; + const auto &pos = p->getPosition(); + const auto fwd = p->getForward() * dist; + auto target = pos; + target.x -= fwd.x; + target.y -= fwd.y; + target.z += height; + const auto ¤t = ROAM.getCamera()->pos; + const auto delta = target - current; const float theta = ROAM.getCamera()->theta; const float c = cosf(theta * (float)(M_PI / 180.0f)); @@ -6787,12 +6734,10 @@ static void setupRoamingCamera(float dt) if (st < 0.1f) st = 0.1f; const float at = (dt / st); - const float bt = 1.0f - at; - deltaCamera.pos[0] = (at * deltaCamera.pos[0]) + (bt * prevDeltaCamera.pos[0]); - deltaCamera.pos[1] = (at * deltaCamera.pos[1]) + (bt * prevDeltaCamera.pos[1]); - deltaCamera.pos[2] = (at * deltaCamera.pos[2]) + (bt * prevDeltaCamera.pos[2]); - deltaCamera.theta = (at * deltaCamera.theta) + (bt * prevDeltaCamera.theta); - deltaCamera.phi = (at * deltaCamera.phi) + (bt * prevDeltaCamera.phi); + deltaCamera.pos = glm::mix(prevDeltaCamera.pos, deltaCamera.pos, at); + deltaCamera.theta = glm::mix(prevDeltaCamera.theta, + deltaCamera.theta, at); + deltaCamera.phi = glm::mix(prevDeltaCamera.phi, deltaCamera.phi, at); } deltaCamera.zoom = roamDZoom; @@ -6815,12 +6760,12 @@ static void prepareTheHUD() // prep the HUD if (myTank) { - const float* myPos = myTank->getPosition(); + const auto &myPos = myTank->getPosition(); hud->setHeading(myTank->getAngle()); hud->setAltitude(myPos[2]); if (world->allowTeamFlags()) { - const float* myTeamColor = Team::getTankColor(myTank->getTeam()); + const auto &myTeamColor = Team::getTankColor(myTank->getTeam()); // markers for my team flag for (int i = 0; i < numFlags; i++) { @@ -6829,24 +6774,27 @@ static void prepareTheHUD() && ((flag.status != FlagOnTank) || (flag.owner != myTank->getId()))) { - const float* flagPos = flag.position; + const auto &flagPos = flag.position; float heading = atan2f(flagPos[1] - myPos[1],flagPos[0] - myPos[0]); hud->addMarker(heading, myTeamColor); - hud->AddEnhancedMarker(Float3ToVec3(flagPos), Float3ToVec3(myTeamColor), - false, BZDBCache::flagPoleSize * 2.0f); + hud->AddEnhancedMarker( + flagPos, myTeamColor, + false, BZDBCache::flagPoleSize * 2.0f); } } } - if (myTank->getAntidoteLocation()) + const auto *antidotePos = myTank->getAntidoteLocation(); + if (antidotePos) { // marker for my antidote flag - const GLfloat* antidotePos = myTank->getAntidoteLocation(); - float heading = atan2f(antidotePos[1] - myPos[1], - antidotePos[0] - myPos[0]); - const float antidoteColor[] = {1.0f, 1.0f, 0.0f}; + float heading = atan2f(antidotePos->y - myPos[1], + antidotePos->x - myPos[0]); + const auto antidoteColor = glm::vec3(1.0f, 1.0f, 0.0f); hud->addMarker(heading, antidoteColor); - hud->AddEnhancedMarker(Float3ToVec3(antidotePos), Float3ToVec3(antidoteColor), false, - BZDBCache::flagPoleSize * 2.0f); + hud->AddEnhancedMarker( + *antidotePos, + antidoteColor, false, + BZDBCache::flagPoleSize * 2.0f); } } return; @@ -7342,9 +7290,10 @@ static void playingLoop() const Player* targetdPlayer = myTank->getTarget(); if (targetdPlayer && targetdPlayer->isAlive() && targetdPlayer->getFlag() != Flags::Stealth) { - hud->AddLockOnMarker(Float3ToVec3(myTank->getTarget()->getPosition()), - myTank->getTarget()->getCallSign(), - !isKillable(myTank->getTarget())); + hud->AddLockOnMarker( + myTank->getTarget()->getPosition(), + myTank->getTarget()->getCallSign(), + !isKillable(myTank->getTarget())); } else // if we should not have a target, force that target to be cleared myTank->setTarget(NULL); @@ -7717,7 +7666,7 @@ void startPlaying(BzfDisplay* _display, BackgroundRenderer background; sceneRenderer->setBackground(&background); - static const GLfloat zero[3] = { 0.0f, 0.0f, 0.0f }; + static const auto zero = glm::vec3(0.0f); TextureManager &tm = TextureManager::instance(); diff --git a/src/bzflag/playing.h b/src/bzflag/playing.h index aba6c38d64..b3685b0e68 100644 --- a/src/bzflag/playing.h +++ b/src/bzflag/playing.h @@ -64,11 +64,11 @@ bool setVideoFormat(int, bool test = false); void startPlaying(BzfDisplay* display, SceneRenderer&); -bool addExplosion(const float* pos, +bool addExplosion(const glm::vec3 &pos, float size, float duration); -void addTankExplosion(const float* pos); -void addShotExplosion(const float* pos); -void addShotPuff(const float* pos, float azimuth, float elevation); +void addTankExplosion(const glm::vec3 &pos); +void addShotExplosion(const glm::vec3 &pos); +void addShotPuff(const glm::vec3 &pos, float azimuth, float elevation); void warnAboutMainFlags(); void warnAboutRadarFlags(); void warnAboutRadar(); diff --git a/src/bzflag/sound.cxx b/src/bzflag/sound.cxx index a4068ba342..20080e9296 100644 --- a/src/bzflag/sound.cxx +++ b/src/bzflag/sound.cxx @@ -17,6 +17,7 @@ #include #include #include +#include // common headers #include "BzfMedia.h" @@ -543,14 +544,14 @@ void moveSoundReceiver(float x, float y, float z, float t, sendSound(&s); } -void speedSoundReceiver(float vx, float vy, float vz) +void speedSoundReceiver(const glm::vec3 &v) { - SoundCommand s(SoundCommand::SET_VEL, 0, vx, vy, vz); + SoundCommand s(SoundCommand::SET_VEL, 0, v.x, v.y, v.z); sendSound(&s); } -void playSound(int soundCode, const float pos[3], - bool important, bool localSound) +void playSound(int soundCode, const glm::vec3 &pos, + bool important, bool localSound) { if (localSound) playLocalSound(soundCode); @@ -559,8 +560,7 @@ void playSound(int soundCode, const float pos[3], return; } -void playWorldSound(int soundCode, const float pos[3], - bool important) +void playWorldSound(int soundCode, const glm::vec3 &pos, bool important) { if (soundLevel <= 0) return; diff --git a/src/bzflag/sound.h b/src/bzflag/sound.h index fe8a8d84f4..e98853548e 100644 --- a/src/bzflag/sound.h +++ b/src/bzflag/sound.h @@ -17,9 +17,12 @@ #ifndef BZF_SOUND_H #define BZF_SOUND_H +// 1st #include "common.h" +// System headers #include +#include #define SFX_FIRE 0 /* shell fired */ #define SFX_EXPLOSION 1 /* something other than me blew up */ @@ -62,14 +65,14 @@ bool isSoundOpen(); /* reposition sound receiver (no Doppler) or move it (w/Doppler effect) */ void moveSoundReceiver(float x, float y, float z, float t, int discontinuity); -void speedSoundReceiver(float vx, float vy, float vz); +void speedSoundReceiver(const glm::vec3 &v); /* sound effect event at given position in world, or possible locally */ -void playSound(int soundCode, const float pos[3], +void playSound(int soundCode, const glm::vec3 &pos, bool important, bool localSound); /* sound effect event at given position in world */ -void playWorldSound(int soundCode, const float pos[3], +void playWorldSound(int soundCode, const glm::vec3 &pos, bool important = false); /* sound effect positioned at receiver */ diff --git a/src/bzfs/CustomArc.cxx b/src/bzfs/CustomArc.cxx index 14a01dc11f..b2b0f4f85d 100644 --- a/src/bzfs/CustomArc.cxx +++ b/src/bzfs/CustomArc.cxx @@ -152,13 +152,13 @@ void CustomArc::writeToGroupDef(GroupDefinition *groupdef) } else { - const float zAxis[3] = {0.0f, 0.0f, 1.0f}; - const float origin[3] = {0.0f, 0.0f, 0.0f}; + const auto zAxis = glm::vec3(0.0f, 0.0f, 1.0f); + const auto origin = glm::vec3(0.0f); MeshTransform xform; xform.addSpin((float)(rotation * (180.0 / M_PI)), zAxis); xform.addShift(pos); xform.append(transform); - float newSize[3]; + glm::vec3 newSize; newSize[0] = (float)(size[0] * M_SQRT2); newSize[1] = (float)(size[1] * M_SQRT2); newSize[2] = size[2]; diff --git a/src/bzfs/CustomBase.cxx b/src/bzfs/CustomBase.cxx index b2aefcb116..078537c049 100644 --- a/src/bzfs/CustomBase.cxx +++ b/src/bzfs/CustomBase.cxx @@ -58,7 +58,7 @@ bool CustomBase::read(const char *cmd, std::istream& input) void CustomBase::writeToGroupDef(GroupDefinition *groupdef) { - float absSize[3] = { fabsf(size[0]), fabsf(size[1]), fabsf(size[2]) }; + auto absSize = glm::abs(size); BaseBuilding* base = new BaseBuilding(pos, rotation, absSize, color, ricochet); groupdef->addObstacle(base); diff --git a/src/bzfs/CustomBox.cxx b/src/bzfs/CustomBox.cxx index ff3051e246..f3440b047c 100644 --- a/src/bzfs/CustomBox.cxx +++ b/src/bzfs/CustomBox.cxx @@ -19,6 +19,7 @@ #include #include #include +#include /* common implementation headers */ #include "BoxBuilding.h" @@ -280,21 +281,17 @@ bool CustomBox::read(const char *cmd, std::istream& input) static void getEdgeLengths(const MeshTransform& xform, float lengths[3]) { MeshTransform::Tool xformTool(xform); - float vo[3] = {-1.0f, -1.0f, 0.0f}; - float vx[3] = {+1.0f, -1.0f, 0.0f}; - float vy[3] = {-1.0f, +1.0f, 0.0f}; - float vz[3] = {-1.0f, -1.0f, 1.0f}; + auto vo = glm::vec3(-1.0f, -1.0f, 0.0f); + auto vx = glm::vec3(+1.0f, -1.0f, 0.0f); + auto vy = glm::vec3(-1.0f, +1.0f, 0.0f); + auto vz = glm::vec3(-1.0f, -1.0f, 1.0f); xformTool.modifyVertex(vo); xformTool.modifyVertex(vx); xformTool.modifyVertex(vy); xformTool.modifyVertex(vz); - float dx[3], dy[3], dz[3]; - vec3sub(dx, vx, vo); - vec3sub(dy, vy, vo); - vec3sub(dz, vz, vo); - lengths[0] = sqrtf(vec3dot(dx, dx)); - lengths[1] = sqrtf(vec3dot(dy, dy)); - lengths[2] = sqrtf(vec3dot(dz, dz)); + lengths[0] = glm::distance(vx, vo); + lengths[1] = glm::distance(vy, vo); + lengths[2] = glm::distance(vz, vo); return; } @@ -316,7 +313,7 @@ void CustomBox::writeToGroupDef(GroupDefinition *groupdef) // setup the transform MeshTransform xform; - const float zAxis[3] = {0.0f, 0.0f, 1.0f}; + const auto zAxis = glm::vec3(0.0f, 0.0f, 1.0f); xform.addScale(size); xform.addSpin((float)(rotation * (180.0 / M_PI)), zAxis); xform.addShift(pos); @@ -328,18 +325,18 @@ void CustomBox::writeToGroupDef(GroupDefinition *groupdef) std::vector checkTypes; - std::vector checkPoints; - std::vector verts; - std::vector norms; - std::vector txcds; + std::vector checkPoints; + std::vector verts; + std::vector norms; + std::vector txcds; // add the checkpoint checkTypes.push_back(MeshObstacle::CheckInside); - const float middle[3] = { 0.0f, 0.0f, 0.5f }; + const auto middle = glm::vec3(0.0f, 0.0f, 0.5f); checkPoints.push_back(middle); // add the vertex coordinates - const float vertsData[8][3] = + const glm::vec3 vertsData[8] = { {-1.0f, -1.0f, 0.0f}, {+1.0f, -1.0f, 0.0f}, {+1.0f, +1.0f, 0.0f}, {-1.0f, +1.0f, 0.0f}, @@ -367,7 +364,7 @@ void CustomBox::writeToGroupDef(GroupDefinition *groupdef) { for (int corner = 0; corner < 4; corner++) { - float txcd[2]; + glm::vec2 txcd; for (int a = 0; a < 2; a++) { float scale; diff --git a/src/bzfs/CustomCone.cxx b/src/bzfs/CustomCone.cxx index 40d8b27dee..aad54ed1c7 100644 --- a/src/bzfs/CustomCone.cxx +++ b/src/bzfs/CustomCone.cxx @@ -151,20 +151,20 @@ void CustomCone::writeToGroupDef(GroupDefinition *groupdef) } else { - const float zAxis[3] = {0.0f, 0.0f, 1.0f}; - const float origin[3] = {0.0f, 0.0f, 0.0f}; + const auto zAxis = glm::vec3(0.0f, 0.0f, 1.0f); + const auto origin = glm::vec3(0.0f); MeshTransform xform; if (flipz || (size[2] < 0.0f)) { - const float flipScale[3] = {1.0f, 1.0f, -1.0f}; - const float flipShift[3] = {0.0f, 0.0f, +size[2]}; + const auto flipScale = glm::vec3(1.0f, 1.0f, -1.0f); + const auto flipShift = glm::vec3(0.0f, 0.0f, +size[2]); xform.addScale(flipScale); xform.addShift(flipShift); } xform.addSpin((float)(rotation * (180.0 / M_PI)), zAxis); xform.addShift(pos); xform.append(transform); - float newSize[3]; + glm::vec3 newSize; newSize[0] = (float)(size[0] * M_SQRT2); newSize[1] = (float)(size[1] * M_SQRT2); newSize[2] = fabsf(size[2]); diff --git a/src/bzfs/CustomGroup.cxx b/src/bzfs/CustomGroup.cxx index d369df7e8e..cc173053a3 100644 --- a/src/bzfs/CustomGroup.cxx +++ b/src/bzfs/CustomGroup.cxx @@ -131,7 +131,7 @@ void CustomGroup::writeToGroupDef(GroupDefinition *grpdef) xform.addScale(size); if (rotation != 0.0f) { - const float zAxis[3] = {0.0f, 0.0f, 1.0f}; + const auto zAxis = glm::vec3(0.0f, 0.0f, 1.0f); xform.addSpin((float)(rotation * (180.0 / M_PI)), zAxis); } if ((pos[0] != 0.0f) || (pos[1] != 0.0f) || (pos[2] != 0.0f)) diff --git a/src/bzfs/CustomMesh.cxx b/src/bzfs/CustomMesh.cxx index 6293d7d759..ccc092e0e4 100644 --- a/src/bzfs/CustomMesh.cxx +++ b/src/bzfs/CustomMesh.cxx @@ -13,6 +13,10 @@ /* interface header */ #include "CustomMesh.h" +// System headers +#include +#include + /* bzfs implementation headers */ #include "CustomMeshFace.h" #include "ParseMaterial.h" @@ -98,7 +102,7 @@ bool CustomMesh::read(const char *cmd, std::istream& input) } else if (strcasecmp(cmd, "inside") == 0) { - cfvec3 inside; + glm::vec3 inside; if (!(input >> inside[0] >> inside[1] >> inside[2])) return false; checkTypes.push_back(MeshObstacle::CheckInside); @@ -106,7 +110,7 @@ bool CustomMesh::read(const char *cmd, std::istream& input) } else if (strcasecmp(cmd, "outside") == 0) { - cfvec3 outside; + glm::vec3 outside; if (!(input >> outside[0] >> outside[1] >> outside[2])) return false; checkTypes.push_back(MeshObstacle::CheckOutside); @@ -114,21 +118,21 @@ bool CustomMesh::read(const char *cmd, std::istream& input) } else if (strcasecmp(cmd, "vertex") == 0) { - cfvec3 vertex; + glm::vec3 vertex; if (!(input >> vertex[0] >> vertex[1] >> vertex[2])) return false; vertices.push_back(vertex); } else if (strcasecmp(cmd, "normal") == 0) { - cfvec3 normal; + glm::vec3 normal; if (!(input >> normal[0] >> normal[1] >> normal[2])) return false; normals.push_back(normal); } else if (strcasecmp(cmd, "texcoord") == 0) { - cfvec2 texcoord; + glm::vec2 texcoord; if (!(input >> texcoord[0] >> texcoord[1])) return false; texcoords.push_back(texcoord); @@ -194,7 +198,7 @@ void CustomMesh::writeToGroupDef(GroupDefinition *groupdef) xform.addScale(size); if (rotation != 0.0f) { - const float zAxis[3] = {0.0f, 0.0f, 1.0f}; + const auto zAxis = glm::vec3(0.0f, 0.0f, 1.0f); xform.addSpin((float)(rotation * (180.0 / M_PI)), zAxis); } if ((pos[0] != 0.0f) || (pos[1] != 0.0f) || (pos[2] != 0.0f)) @@ -205,7 +209,7 @@ void CustomMesh::writeToGroupDef(GroupDefinition *groupdef) bool forcePassable = false; if (drawInfo) { - cfvec3 vert; + glm::vec3 vert; if (decorative) { vert[0] = vert[1] = vert[2] = (Obstacle::maxExtent * 2.0f); diff --git a/src/bzfs/CustomMesh.h b/src/bzfs/CustomMesh.h index 1fd35a0d07..8d93abdbf3 100644 --- a/src/bzfs/CustomMesh.h +++ b/src/bzfs/CustomMesh.h @@ -42,10 +42,10 @@ class CustomMesh : public WorldFileObstacle BzMaterial material; // holds current defaults std::vector checkTypes; - std::vector checkPoints; - std::vector vertices; - std::vector normals; - std::vector texcoords; + std::vector checkPoints; + std::vector vertices; + std::vector normals; + std::vector texcoords; int phydrv; bool noclusters; diff --git a/src/bzfs/CustomMeshTransform.cxx b/src/bzfs/CustomMeshTransform.cxx index 6a5230bdc8..7e2f678982 100644 --- a/src/bzfs/CustomMeshTransform.cxx +++ b/src/bzfs/CustomMeshTransform.cxx @@ -41,7 +41,7 @@ bool CustomMeshTransform::read(const char *cmd, std::istream& input) { if (strcasecmp ("shift", cmd) == 0) { - float data[3]; + glm::vec3 data; if (!(input >> data[0] >> data[1] >> data[2])) { std::cout << "parameters errors " << std::endl; @@ -51,7 +51,7 @@ bool CustomMeshTransform::read(const char *cmd, std::istream& input) } else if (strcasecmp ("scale", cmd) == 0) { - float data[3]; + glm::vec3 data; if (!(input >> data[0] >> data[1] >> data[2])) { std::cout << "parameters errors " << std::endl; @@ -72,12 +72,13 @@ bool CustomMeshTransform::read(const char *cmd, std::istream& input) else if (strcasecmp ("spin", cmd) == 0) { float data[4]; - if (!(input >> data[0] >> data[1] >> data[2] >> data[3])) + glm::vec3 dat; + if (!(input >> data[0] >> dat[0] >> dat[1] >> dat[2])) { std::cout << "parameters errors " << std::endl; return false; } - transform->addSpin(data[0], &data[1]); + transform->addSpin(data[0], dat); } else if (strcasecmp ("xform", cmd) == 0) { diff --git a/src/bzfs/CustomPyramid.cxx b/src/bzfs/CustomPyramid.cxx index 70e906e4d5..366cfce7bc 100644 --- a/src/bzfs/CustomPyramid.cxx +++ b/src/bzfs/CustomPyramid.cxx @@ -19,6 +19,7 @@ #include #include #include +#include /* common implementation headers */ #include "PyramidBuilding.h" @@ -272,14 +273,14 @@ bool CustomPyramid::read(const char *cmd, std::istream& input) static void getEdgeLengths(const MeshTransform& xform, float lengths[6]) { MeshTransform::Tool xformTool(xform); - float vo[3] = {-1.0f, -1.0f, 0.0f}; - float vx[3] = {+1.0f, -1.0f, 0.0f}; - float vy[3] = {-1.0f, +1.0f, 0.0f}; - float vt[3] = {0.0f, 0.0f, 1.0f}; - float vxp[3] = {+1.0f, 0.0f, 0.0f}; - float vxn[3] = {-1.0f, 0.0f, 0.0f}; - float vyp[3] = {0.0f, +1.0f, 0.0f}; - float vyn[3] = {0.0f, -1.0f, 0.0f}; + auto vo = glm::vec3(-1.0f, -1.0f, 0.0f); + auto vx = glm::vec3(+1.0f, -1.0f, 0.0f); + auto vy = glm::vec3(-1.0f, +1.0f, 0.0f); + auto vt = glm::vec3(0.0f, 0.0f, 1.0f); + auto vxp = glm::vec3(+1.0f, 0.0f, 0.0f); + auto vxn = glm::vec3(-1.0f, 0.0f, 0.0f); + auto vyp = glm::vec3(0.0f, +1.0f, 0.0f); + auto vyn = glm::vec3(0.0f, -1.0f, 0.0f); xformTool.modifyVertex(vo); xformTool.modifyVertex(vx); xformTool.modifyVertex(vy); @@ -288,19 +289,12 @@ static void getEdgeLengths(const MeshTransform& xform, float lengths[6]) xformTool.modifyVertex(vxn); xformTool.modifyVertex(vyp); xformTool.modifyVertex(vyn); - float dx[3], dy[3], dxp[3], dxn[3], dyp[3], dyn[3]; - vec3sub(dx, vx, vo); - vec3sub(dy, vy, vo); - vec3sub(dxp, vxp, vt); - vec3sub(dxn, vxn, vt); - vec3sub(dyp, vyp, vt); - vec3sub(dyn, vyn, vt); - lengths[0] = sqrtf(vec3dot(dx, dx)); - lengths[1] = sqrtf(vec3dot(dy, dy)); - lengths[2] = sqrtf(vec3dot(dxp, dxp)); - lengths[3] = sqrtf(vec3dot(dxn, dxn)); - lengths[4] = sqrtf(vec3dot(dyp, dyp)); - lengths[5] = sqrtf(vec3dot(dyn, dyn)); + lengths[0] = glm::distance(vx, vo); + lengths[1] = glm::distance(vy, vo); + lengths[2] = glm::distance(vxp, vt); + lengths[3] = glm::distance(vxn, vt); + lengths[4] = glm::distance(vyp, vt); + lengths[5] = glm::distance(vyn, vt); return; } @@ -325,13 +319,13 @@ void CustomPyramid::writeToGroupDef(GroupDefinition *groupdef) MeshTransform xform; if (flipz || (size[2] < 0.0f)) { - const float flipScale[3] = {1.0f, 1.0f, -1.0f}; - const float flipShift[3] = {0.0f, 0.0f, +1.0f}; + const auto flipScale = glm::vec3(1.0f, 1.0f, -1.0f); + const auto flipShift = glm::vec3(0.0f, 0.0f, +1.0f); xform.addScale(flipScale); xform.addShift(flipShift); } - const float zAxis[3] = {0.0f, 0.0f, 1.0f}; + const auto zAxis = glm::vec3(0.0f, 0.0f, 1.0f); xform.addScale(size); xform.addSpin((float)(rotation * (180.0 / M_PI)), zAxis); xform.addShift(pos); @@ -344,22 +338,22 @@ void CustomPyramid::writeToGroupDef(GroupDefinition *groupdef) std::vector checkTypes; - std::vector checkPoints; - std::vector verts; - std::vector norms; - std::vector txcds; + std::vector checkPoints; + std::vector verts; + std::vector norms; + std::vector txcds; // add the checkpoint checkTypes.push_back(MeshObstacle::CheckInside); - const float middle[3] = { 0.0f, 0.0f, 0.5f }; + const auto middle = glm::vec3(0.0f, 0.0f, 0.5f); checkPoints.push_back(middle); // add the vertex coordinates - const float vertsData[5][3] = + const glm::vec3 vertsData[5] = { - {-1.0f, -1.0f, 0.0f}, {+1.0f, -1.0f, 0.0f}, - {+1.0f, +1.0f, 0.0f}, {-1.0f, +1.0f, 0.0f}, - {+0.0f, +0.0f, 1.0f} + glm::vec3(-1.0f, -1.0f, 0.0f), glm::vec3(+1.0f, -1.0f, 0.0f), + glm::vec3(+1.0f, +1.0f, 0.0f), glm::vec3(-1.0f, +1.0f, 0.0f), + glm::vec3(+0.0f, +0.0f, 1.0f) }; for (i = 0; i < 5; i++) verts.push_back(vertsData[i]); @@ -394,7 +388,7 @@ void CustomPyramid::writeToGroupDef(GroupDefinition *groupdef) } for (int corner = 0; corner < cornerCount; corner++) { - float txcd[2]; + glm::vec2 txcd; for (int a = 0; a < 2; a++) { float scale; diff --git a/src/bzfs/CustomTetra.cxx b/src/bzfs/CustomTetra.cxx index 0c21771cbe..8ff44b9140 100644 --- a/src/bzfs/CustomTetra.cxx +++ b/src/bzfs/CustomTetra.cxx @@ -74,7 +74,7 @@ bool CustomTetra::read(const char *cmd, std::istream& input) } else { - float* vertex = vertices[vertexCount]; + auto &vertex = vertices[vertexCount]; input >> vertex[0] >> vertex[1] >> vertex[2]; vertexCount++; } diff --git a/src/bzfs/CustomTetra.h b/src/bzfs/CustomTetra.h index 6605043028..afc03eb967 100644 --- a/src/bzfs/CustomTetra.h +++ b/src/bzfs/CustomTetra.h @@ -35,7 +35,7 @@ class CustomTetra : public WorldFileObstacle private: int vertexCount; - float vertices[4][3]; + glm::vec3 vertices[4]; float normals[4][3][3]; float texcoords[4][3][2]; bool useNormals[4]; diff --git a/src/bzfs/CustomZone.cxx b/src/bzfs/CustomZone.cxx index d3ca7c12bd..c49f1d90fa 100644 --- a/src/bzfs/CustomZone.cxx +++ b/src/bzfs/CustomZone.cxx @@ -225,7 +225,7 @@ void CustomZone::writeToWorld(WorldInfo* worldInfo) const worldInfo->addZone( this ); } -void CustomZone::getRandomPoint(float *pt) const +void CustomZone::getRandomPoint(glm::vec3 &pt) const { float x = (float)((bzfrand() * (2.0f * size[0])) - size[0]); float y = (float)((bzfrand() * (2.0f * size[1])) - size[1]); @@ -240,14 +240,11 @@ void CustomZone::getRandomPoint(float *pt) const pt[2] = pos[2]; } -float CustomZone::getDistToPoint (const float *_pos) const +float CustomZone::getDistToPoint (const glm::vec3 &_pos) const { // FIXME - should use proper minimum distance from // the zone edge, and maybe -1.0f if its inside the zone - const float dx = _pos[0] - pos[0]; - const float dy = _pos[1] - pos[1]; - const float dz = _pos[2] - pos[2]; - const float dist = sqrtf (dx*dx + dy*dy + dz*dz); + const float dist = glm::distance(_pos, pos); return dist; } diff --git a/src/bzfs/CustomZone.h b/src/bzfs/CustomZone.h index a908cc7082..d5697dc345 100644 --- a/src/bzfs/CustomZone.h +++ b/src/bzfs/CustomZone.h @@ -49,8 +49,8 @@ class CustomZone : public WorldFileLocation const ZoneFlagMap& getZoneFlagMap() const; float getArea() const; - void getRandomPoint(float *pt) const; - float getDistToPoint (const float *pos) const; + void getRandomPoint(glm::vec3 &pt) const; + float getDistToPoint (const glm::vec3 &pos) const; public: static const std::string& getFlagIdQualifier(int flagId); diff --git a/src/bzfs/DropGeometry.cxx b/src/bzfs/DropGeometry.cxx index d8e6783290..7b29f4d12f 100644 --- a/src/bzfs/DropGeometry.cxx +++ b/src/bzfs/DropGeometry.cxx @@ -56,15 +56,15 @@ static int compareDescending(const void* a, const void* b); static bool isDeathLanding(const Obstacle* landing); static bool isOpposingTeam(const Obstacle* obs, int team); static bool isValidLanding(const Obstacle* obs); -static bool isValidClearance(const float pos[3], float radius, +static bool isValidClearance(const glm::vec3 &pos, float radius, float height, int team); -static bool dropIt(float pos[3], float minZ, float maxZ, +static bool dropIt(glm::vec3 &pos, float minZ, float maxZ, float radius, float height, int team); /******************************************************************************/ -bool DropGeometry::dropPlayer(float pos[3], float minZ, float maxZ) +bool DropGeometry::dropPlayer(glm::vec3 &pos, float minZ, float maxZ) { // fudge-it to avoid spawn stickiness on obstacles const float fudge = 0.001f; @@ -75,14 +75,14 @@ bool DropGeometry::dropPlayer(float pos[3], float minZ, float maxZ) } -bool DropGeometry::dropFlag(float pos[3], float minZ, float maxZ) +bool DropGeometry::dropFlag(glm::vec3 &pos, float minZ, float maxZ) { const float flagHeight = BZDB.eval(StateDatabase::BZDB_FLAGHEIGHT); return dropIt(pos, minZ, maxZ, BZDBCache::tankRadius, flagHeight, -1); } -bool DropGeometry::dropTeamFlag(float pos[3], float minZ, float maxZ, +bool DropGeometry::dropTeamFlag(glm::vec3 &pos, float minZ, float maxZ, int team) { // team flags do not get real clearance checks (radius = 0) @@ -143,7 +143,7 @@ static inline bool isValidLanding(const Obstacle* obs) } -static bool isValidClearance(const float pos[3], float radius, +static bool isValidClearance(const glm::vec3 &pos, float radius, float height, int team) { const ObsList* olist = COLLISIONMGR.cylinderTest(pos, radius, height); @@ -164,7 +164,8 @@ static bool isValidClearance(const float pos[3], float radius, if (isDeathLanding(obs) || isOpposingTeam(obs, team)) { const float fudge = 0.001f; // dig in a little to make sure - const float testPos[3] = {pos[0], pos[1], pos[2] - fudge}; + auto testPos = pos; + testPos.z -= fudge; if (obs->inCylinder(testPos, radius, height + fudge)) return false; } @@ -207,7 +208,7 @@ static int compareDescending(const void* a, const void* b) /******************************************************************************/ -static bool dropIt(float pos[3], float minZ, float maxZ, +static bool dropIt(glm::vec3 &pos, float minZ, float maxZ, float radius, float height, int team) { int i; @@ -228,8 +229,8 @@ static bool dropIt(float pos[3], float minZ, float maxZ, // use a downwards ray to hit the onFlatTop() buildings const float maxHeight = COLLISIONMGR.getWorldExtents().maxs[2]; - const float dir[3] = {0.0f, 0.0f, -1.0f}; - const float org[3] = {pos[0], pos[1], maxHeight + 1.0f}; + const auto dir = glm::vec3(0.0f, 0.0f, -1.0f); + const auto org = glm::vec3(pos[0], pos[1], maxHeight + 1.0f); Ray ray(org, dir); // list of possible landings diff --git a/src/bzfs/DropGeometry.h b/src/bzfs/DropGeometry.h index b0e4e6e2ea..2641f124af 100644 --- a/src/bzfs/DropGeometry.h +++ b/src/bzfs/DropGeometry.h @@ -16,15 +16,18 @@ // 1st #include "common.h" +// System headers +#include + class WorldInfo; namespace DropGeometry { -bool dropFlag (float pos[3], float minZ, float maxZ); -bool dropPlayer (float pos[3], float minZ, float maxZ); -bool dropTeamFlag (float pos[3], float minZ, float maxZ, int team); +bool dropFlag (glm::vec3 &pos, float minZ, float maxZ); +bool dropPlayer (glm::vec3 &pos, float minZ, float maxZ); +bool dropTeamFlag (glm::vec3 &pos, float minZ, float maxZ, int team); } diff --git a/src/bzfs/EntryZones.cxx b/src/bzfs/EntryZones.cxx index 75c51e3d13..6a60386ec9 100644 --- a/src/bzfs/EntryZones.cxx +++ b/src/bzfs/EntryZones.cxx @@ -96,7 +96,7 @@ void EntryZones::calculateQualifierLists() } -bool EntryZones::getRandomPoint(const std::string &qual, float *pt) const +bool EntryZones::getRandomPoint(const std::string &qual, glm::vec3 &pt) const { QualifierMap::const_iterator mit = qmap.find(qual); if (mit == qmap.end()) @@ -125,8 +125,8 @@ bool EntryZones::getRandomPoint(const std::string &qual, float *pt) const } -bool EntryZones::getClosePoint(const std::string &qual, const float pos[3], - float *pt) const +bool EntryZones::getClosePoint(const std::string &qual, const glm::vec3 &pos, + glm::vec3 &pt) const { QualifierMap::const_iterator mit = qmap.find(qual); if (mit == qmap.end()) @@ -157,7 +157,7 @@ bool EntryZones::getClosePoint(const std::string &qual, const float pos[3], } -bool EntryZones::getZonePoint(const std::string &qualifier, float *pt) const +bool EntryZones::getZonePoint(const std::string &qualifier, glm::vec3 &pt) const { QualifierMap::const_iterator mit = qmap.find(qualifier); if (mit == qmap.end()) @@ -186,8 +186,8 @@ bool EntryZones::getZonePoint(const std::string &qualifier, float *pt) const } -bool EntryZones::getSafetyPoint( const std::string &qualifier, - const float *pos, float *pt ) const +bool EntryZones::getSafetyPoint(const std::string &qualifier, + const glm::vec3 &pos, glm::vec3 &pt) const { std::string safetyString = /*EntryZones::getSafetyPrefix() + */ qualifier; diff --git a/src/bzfs/EntryZones.h b/src/bzfs/EntryZones.h index e5cd71f3fc..b4d1a5ba61 100644 --- a/src/bzfs/EntryZones.h +++ b/src/bzfs/EntryZones.h @@ -38,13 +38,13 @@ class EntryZones void calculateQualifierLists(); - bool getZonePoint(const std::string &qualifier, float *pt) const; + bool getZonePoint(const std::string &qualifier, glm::vec3 &pt) const; bool getSafetyPoint(const std::string &qualifier, - const float *pos, float *pt) const; + const glm::vec3 &pos, glm::vec3 &pt) const; - bool getRandomPoint(const std::string &qual, float *pt) const; - bool getClosePoint(const std::string &qual, const float pos[3], - float *pt) const; + bool getRandomPoint(const std::string &qual, glm::vec3 &pt) const; + bool getClosePoint(const std::string &qual, const glm::vec3 &pos, + glm::vec3 &pt) const; const ZoneList& getZoneList() const; diff --git a/src/bzfs/FlagInfo.cxx b/src/bzfs/FlagInfo.cxx index 033282a701..7999731fc3 100644 --- a/src/bzfs/FlagInfo.cxx +++ b/src/bzfs/FlagInfo.cxx @@ -151,7 +151,7 @@ void *FlagInfo::pack(void *buf, bool hide) return buf; } -void FlagInfo::dropFlag(float pos[3], float landingPos[3], bool vanish) +void FlagInfo::dropFlag(const glm::vec3 &pos, glm::vec3 &landingPos, bool vanish) { numFlagsInAir++; flag.status = vanish ? FlagGoing : FlagInAir; @@ -185,7 +185,7 @@ void FlagInfo::dropFlag(float pos[3], float landingPos[3], bool vanish) flag.initialVelocity = -gravity * upTime; } -void FlagInfo::resetFlag(float position[3], bool teamIsEmpty) +void FlagInfo::resetFlag(const glm::vec3 &position, bool teamIsEmpty) { // reset a flag's info player = -1; @@ -193,9 +193,7 @@ void FlagInfo::resetFlag(float position[3], bool teamIsEmpty) if (flagIndex >= numFlags - numExtraFlags) flag.type = Flags::Null; - flag.position[0] = position[0]; - flag.position[1] = position[1]; - flag.position[2] = position[2]; + flag.position = position; // required flags mustn't just disappear if (required) diff --git a/src/bzfs/FlagInfo.h b/src/bzfs/FlagInfo.h index 37ffee1c48..f9fe015d29 100644 --- a/src/bzfs/FlagInfo.h +++ b/src/bzfs/FlagInfo.h @@ -34,8 +34,8 @@ class FlagInfo void setRequiredFlag(FlagType *desc); void addFlag(); void *pack(void *buf, bool hide = false); - void dropFlag(float pos[3], float landingPos[3], bool vanish); - void resetFlag(float position[3], bool teamIsEmpty); + void dropFlag(const glm::vec3 &pos, glm::vec3 &landingPos, bool vanish); + void resetFlag(const glm::vec3 &position, bool teamIsEmpty); void grab(int playerIndex); TeamColor teamIndex() const; int getIndex() const; diff --git a/src/bzfs/GameKeeper.cxx b/src/bzfs/GameKeeper.cxx index 8e7aa27cf2..5c2426498e 100644 --- a/src/bzfs/GameKeeper.cxx +++ b/src/bzfs/GameKeeper.cxx @@ -377,13 +377,13 @@ void GameKeeper::Player::handleTcpPacket(fd_set* set) } } -void GameKeeper::Player::setPlayerState(float pos[3], float azimuth) +void GameKeeper::Player::setPlayerState(const glm::vec3 &pos, float azimuth) { serverTimeStamp = (float)TimeKeeper::getCurrent().getSeconds(); - memcpy(lastState.pos, pos, sizeof(float) * 3); + lastState.pos = pos; lastState.azimuth = azimuth; // Set Speeds to 0 too - memset(lastState.velocity, 0, sizeof(float) * 3); + lastState.velocity = glm::vec3(0.0f); lastState.angVel = 0.0f; stateTimeStamp = 0.0f; @@ -507,9 +507,9 @@ void GameKeeper::Player::setPlayerState(PlayerState state, float timestamp) serverTimeStamp = (float)TimeKeeper::getCurrent().getSeconds(); } -void GameKeeper::Player::getPlayerState(float pos[3], float &azimuth) +void GameKeeper::Player::getPlayerState(glm::vec3 &pos, float &azimuth) { - memcpy(pos, lastState.pos, sizeof(float) * 3); + pos = lastState.pos; azimuth = lastState.azimuth; } diff --git a/src/bzfs/GameKeeper.h b/src/bzfs/GameKeeper.h index 8f2d70450d..b059e7edd5 100644 --- a/src/bzfs/GameKeeper.h +++ b/src/bzfs/GameKeeper.h @@ -104,8 +104,8 @@ class GameKeeper bool needsHostbanChecked(); // To handle player State - void setPlayerState(float pos[3], float azimuth); - void getPlayerState(float pos[3], float &azimuth); + void setPlayerState(const glm::vec3 &pos, float azimuth); + void getPlayerState(glm::vec3 &pos, float &azimuth); void setPlayerState(PlayerState state, float timestamp); void setBzIdentifier(const std::string& id); diff --git a/src/bzfs/ParseMaterial.cxx b/src/bzfs/ParseMaterial.cxx index 47430a3abb..a4a6ec1ea5 100644 --- a/src/bzfs/ParseMaterial.cxx +++ b/src/bzfs/ParseMaterial.cxx @@ -90,7 +90,7 @@ bool parseMaterials(const char* cmd, std::istream& input, else if ((strcasecmp(cmd, "diffuse") == 0) || // currently used by bzflag (strcasecmp(cmd, "color") == 0)) { - float diffuse[4]; + glm::vec4 diffuse; error = !parseColorStream(input, diffuse); if (!error) { @@ -102,24 +102,24 @@ bool parseMaterials(const char* cmd, std::istream& input, } else if (strcasecmp(cmd, "specular") == 0) { - float specular[4]; + glm::vec4 specular; error = !parseColorStream(input, specular); if (!error) { for (i = 0; i < materialCount; i++) - materials[i].setSpecular(specular); + materials[i].setSpecular(glm::vec3(specular)); } else std::cout << "bad " << cmd << " specification" << std::endl; } else if (strcasecmp(cmd, "emission") == 0) { - float emission[4]; + glm::vec4 emission; error = !parseColorStream(input, emission); if (!error) { for (i = 0; i < materialCount; i++) - materials[i].setEmission(emission); + materials[i].setEmission(glm::vec3(emission)); } else std::cout << "bad " << cmd << " specification" << std::endl; diff --git a/src/bzfs/RandomSpawnPolicy.cxx b/src/bzfs/RandomSpawnPolicy.cxx index f8dde15673..e2d1b40e17 100644 --- a/src/bzfs/RandomSpawnPolicy.cxx +++ b/src/bzfs/RandomSpawnPolicy.cxx @@ -33,7 +33,7 @@ RandomSpawnPolicy::~RandomSpawnPolicy() { } -void RandomSpawnPolicy::getPosition(float pos[3], int playerId, bool onGroundOnly, bool UNUSED(notNearEdges)) +void RandomSpawnPolicy::getPosition(glm::vec3 &pos, int playerId, bool onGroundOnly, bool) { /* the player is coming to life, depending on who they are an what * style map/configuration is being played determines how they will diff --git a/src/bzfs/RandomSpawnPolicy.h b/src/bzfs/RandomSpawnPolicy.h index 12e2eff716..d2cb0e9c2d 100644 --- a/src/bzfs/RandomSpawnPolicy.h +++ b/src/bzfs/RandomSpawnPolicy.h @@ -29,8 +29,8 @@ class RandomSpawnPolicy : public SpawnPolicy RandomSpawnPolicy(); virtual ~RandomSpawnPolicy(); - virtual void getPosition(float pos[3], int playerId, bool onGroundOnly, bool notNearEdges); - virtual void getAzimuth(float &azimuth); + void getPosition(glm::vec3 &pos, int playerId, bool onGroundOnly, bool notNearEdges) override; + void getAzimuth(float &azimuth) override; }; #endif /*__RANDOMSPAWNPOLICY_H__ */ diff --git a/src/bzfs/ServerSidePlayer.cxx b/src/bzfs/ServerSidePlayer.cxx index 82b92327e8..49698ef7af 100644 --- a/src/bzfs/ServerSidePlayer.cxx +++ b/src/bzfs/ServerSidePlayer.cxx @@ -13,10 +13,13 @@ // bzflag global header #include "common.h" +// Common headers #include "bzfsAPI.h" -#include "bzfs.h" #include "StateDatabase.h" +// Local headers +#include "bzfs.h" + // server side bot API @@ -333,7 +336,9 @@ void bz_ServerSidePlayerHandler::getPosition ( float *p ) if (!player || !p) return; - memcpy(p, player->lastState.pos, sizeof(float[3])); + p[0] = player->lastState.pos[0]; + p[1] = player->lastState.pos[1]; + p[2] = player->lastState.pos[2]; } void bz_ServerSidePlayerHandler::getVelocity ( float *v ) @@ -342,7 +347,9 @@ void bz_ServerSidePlayerHandler::getVelocity ( float *v ) if (!player ||!v) return; - memcpy(v,player->lastState.velocity,sizeof(float)*3); + v[0] = player->lastState.velocity[0]; + v[1] = player->lastState.velocity[1]; + v[2] = player->lastState.velocity[2]; } float bz_ServerSidePlayerHandler::getFacing ( void ) diff --git a/src/bzfs/ShotManager.cxx b/src/bzfs/ShotManager.cxx index f885020375..2d34dee000 100644 --- a/src/bzfs/ShotManager.cxx +++ b/src/bzfs/ShotManager.cxx @@ -12,8 +12,14 @@ // interface header #include "ShotManager.h" + +// System headers +#include +#define GLM_ENABLE_EXPERIMENTAL +#include + +// Common headers #include "TimeKeeper.h" -#include "vectors.h" namespace Shots @@ -299,12 +305,9 @@ bool FlightLogic::Update ( Shot& shot) return shot.GetLastUpdateTime() - shot.GetStartTime() >= shot.GetLifeTime(); } -fvec3 FlightLogic::ProjectShotLocation( Shot& shot, double deltaT ) +glm::vec3 FlightLogic::ProjectShotLocation(Shot& shot, double deltaT) { - fvec3 vec; - vec.x = shot.LastUpdatePosition.x + (shot.Info.shot.vel[0] * (float)deltaT); - vec.y = shot.LastUpdatePosition.y + (shot.Info.shot.vel[1] * (float)deltaT); - vec.z = shot.LastUpdatePosition.z + (shot.Info.shot.vel[2] * (float)deltaT); + const auto vec = shot.LastUpdatePosition + shot.Info.shot.vel * float(deltaT); return vec; } @@ -339,21 +342,22 @@ bool ShockwaveLogic::Update ( Shot& shot ) return FlightLogic::Update(shot); } -bool ShockwaveLogic::CollideBox ( Shot& shot, fvec3& center, fvec3& size, float rotation ) +bool ShockwaveLogic::CollideBox ( + Shot& shot, glm::vec3& center, glm::vec3& size, float rotation) { // check the top locations - fvec3 xyPlus = size; - fvec3 xyNeg(-size.x,-size.y,size.z); - fvec3 xPlusYNeg(size.x,-size.y,size.z); - fvec3 xNegYPlus(-size.x,size.y,size.z); + glm::vec3 xyPlus = size; + glm::vec3 xyNeg(-size.x,-size.y,size.z); + glm::vec3 xPlusYNeg(size.x,-size.y,size.z); + glm::vec3 xNegYPlus(-size.x,size.y,size.z); - float rotRads = fvec3::toRadians(rotation); + float rotRads = glm::radians(rotation); // rotate them all into orientation - xyPlus.rotateZ(rotRads); - xyNeg.rotateZ(rotRads); - xPlusYNeg.rotateZ(rotRads); - xNegYPlus.rotateZ(rotRads); + xyPlus = glm::rotateZ(xyPlus, rotRads); + xyNeg = glm::rotateZ(xyNeg, rotRads); + xPlusYNeg = glm::rotateZ(xPlusYNeg, rotRads); + xNegYPlus = glm::rotateZ(xNegYPlus, rotRads); // attach them to the center xyPlus += center; @@ -379,13 +383,15 @@ bool ShockwaveLogic::CollideBox ( Shot& shot, fvec3& center, fvec3& size, float return false; } -bool ShockwaveLogic::CollideSphere ( Shot& shot, fvec3& center, float radius ) +bool ShockwaveLogic::CollideSphere ( + Shot& shot, glm::vec3 ¢er, float radius) { - fvec3 vecToPoint = center - shot.StartPosition; + glm::vec3 vecToPoint = center - shot.StartPosition; return vecToPoint.length() <= shot.LastUpdatePosition.x - radius; } -bool ShockwaveLogic::CollideCylinder ( Shot& shot, fvec3¢er, float height, float radius ) +bool ShockwaveLogic::CollideCylinder ( + Shot& shot, glm::vec3 ¢er, float height, float radius) { if (center.z > shot.StartPosition.z + shot.LastUpdatePosition.x) return false; // too high @@ -393,15 +399,15 @@ bool ShockwaveLogic::CollideCylinder ( Shot& shot, fvec3¢er, float height, f if (center.z + height < shot.StartPosition.z - shot.LastUpdatePosition.x) return false; // too low - fvec3 vecToPoint = center - shot.StartPosition; + glm::vec3 vecToPoint = center - shot.StartPosition; vecToPoint.z = 0; return vecToPoint.length() <= shot.LastUpdatePosition.x - radius; } -bool ShockwaveLogic::PointInSphere ( fvec3& point, Shot& shot ) +bool ShockwaveLogic::PointInSphere (glm::vec3 &point, Shot& shot) { - fvec3 vecToPoint = point - shot.StartPosition; + glm::vec3 vecToPoint = point - shot.StartPosition; return vecToPoint.length() <= shot.LastUpdatePosition.x; } } diff --git a/src/bzfs/ShotManager.h b/src/bzfs/ShotManager.h index 32196d45d0..29b4069ccb 100644 --- a/src/bzfs/ShotManager.h +++ b/src/bzfs/ShotManager.h @@ -15,11 +15,7 @@ #include "common.h" -/* common interface headers */ -#include "global.h" /* for TeamColor */ -#include "ShotUpdate.h" -#include "vectors.h" - +// System headers #include #include #include @@ -32,6 +28,11 @@ #include #include #endif +#include + +/* common interface headers */ +#include "global.h" /* for TeamColor */ +#include "ShotUpdate.h" /** a ShotManager is used track shots fired by players and the server */ @@ -50,21 +51,25 @@ class FlightLogic virtual void End ( Shot& UNUSED(shot) ) {} virtual void Retarget ( Shot& UNUSED(shot), PlayerId UNUSED(newTarget) ) {}; - virtual bool CollideBox ( Shot& UNUSED(shot), fvec3& UNUSED(center), fvec3& UNUSED(size), float UNUSED(rotation) ) + virtual bool CollideBox ( + Shot& UNUSED(shot), glm::vec3 &UNUSED(center), + glm::vec3 &UNUSED(size), float UNUSED(rotation)) { return false; } - virtual bool CollideSphere ( Shot& UNUSED(shot), fvec3& UNUSED(center), float UNUSED(radius) ) + virtual bool CollideSphere ( Shot& UNUSED(shot), glm::vec3 &UNUSED(center), float UNUSED(radius) ) { return false; } - virtual bool CollideCylinder ( Shot& UNUSED(shot), fvec3& UNUSED(center), float UNUSED(height), float UNUSED(radius) ) + virtual bool CollideCylinder ( + Shot& UNUSED(shot), glm::vec3 &UNUSED(center), + float UNUSED(height), float UNUSED(radius) ) { return false; } protected: - virtual fvec3 ProjectShotLocation( Shot& shot, double deltaT ); + virtual glm::vec3 ProjectShotLocation( Shot& shot, double deltaT ); }; typedef std::map FlightLogicMap; @@ -88,8 +93,8 @@ class Shot std::map MetaData; public: - fvec3 StartPosition; - fvec3 LastUpdatePosition; + glm::vec3 StartPosition; + glm::vec3 LastUpdatePosition; double LastUpdateTime; double StartTime; @@ -138,15 +143,15 @@ class Shot return (LastUpdateTime-StartTime)/LifeTime; } - bool CollideBox ( fvec3 ¢er, fvec3 size, float rotation ) + bool CollideBox (glm::vec3 ¢er, glm::vec3 size, float rotation) { return Logic.CollideBox(*this,center,size,rotation); } - bool CollideSphere ( fvec3 ¢er, float radius ) + bool CollideSphere (glm::vec3 ¢er, float radius) { return Logic.CollideSphere(*this,center,radius); } - bool CollideCylinder ( fvec3 ¢er, float height, float radius) + bool CollideCylinder (glm::vec3 ¢er, float height, float radius) { return Logic.CollideCylinder(*this,center,height,radius); } @@ -247,12 +252,16 @@ class ShockwaveLogic: public FlightLogic virtual void Setup(Shot& shot ); virtual bool Update ( Shot& shot ); - virtual bool CollideBox ( Shot& shot, fvec3& ecnter, fvec3& size, float rotation ); - virtual bool CollideSphere ( Shot& shot, fvec3& center, float radius ); - virtual bool CollideCylinder ( Shot& shot, fvec3& center, float height, float radius ); + virtual bool CollideBox ( + Shot& shot, glm::vec3 ¢er, + glm::vec3& size, float rotation); + virtual bool CollideSphere ( + Shot& shot, glm::vec3 ¢er, float radius ); + virtual bool CollideCylinder ( + Shot& shot, glm::vec3 ¢er, float height, float radius); protected: - bool PointInSphere ( fvec3& point, Shot& shot ); + bool PointInSphere (glm::vec3 &point, Shot& shot); }; } #endif /* __SHOT_MANAGER_H__ */ diff --git a/src/bzfs/SpawnPolicy.cxx b/src/bzfs/SpawnPolicy.cxx index 737440c04e..a6fc1b06ef 100644 --- a/src/bzfs/SpawnPolicy.cxx +++ b/src/bzfs/SpawnPolicy.cxx @@ -33,7 +33,7 @@ SpawnPolicy::~SpawnPolicy() { } -void SpawnPolicy::getPosition(float pos[3], int playerId, bool onGroundOnly, bool notNearEdges) +void SpawnPolicy::getPosition(glm::vec3 &pos, int playerId, bool onGroundOnly, bool notNearEdges) { /* the player is coming to life, depending on who they are an what * style map/configuration is being played determines how they will @@ -181,7 +181,7 @@ void SpawnPolicy::getAzimuth(float &azimuth) } -bool SpawnPolicy::isFacing(const float *enemyPos, const float enemyAzimuth, +bool SpawnPolicy::isFacing(const glm::vec3 &enemyPos, const float enemyAzimuth, const float deviation) const { // vector points from test to enemy @@ -219,7 +219,7 @@ bool SpawnPolicy::isImminentlyDangerous() const continue; if (playerData->player.isAlive()) { - float *enemyPos = playerData->lastState.pos; + const auto &enemyPos = playerData->lastState.pos; float enemyAngle = playerData->lastState.azimuth; if (playerData->player.getFlag() >= 0) { @@ -278,7 +278,7 @@ float SpawnPolicy::enemyProximityCheck(float &enemyAngle) const if (playerData->player.isAlive() && areFoes(playerData->player.getTeam(), team)) { - float *enemyPos = playerData->lastState.pos; + const auto &enemyPos = playerData->lastState.pos; if (fabs(enemyPos[2] - testPos[2]) < 1.0f) { float x = enemyPos[0] - testPos[0]; @@ -299,7 +299,7 @@ float SpawnPolicy::enemyProximityCheck(float &enemyAngle) const } -float SpawnPolicy::distanceFrom(const float* farPos) const +float SpawnPolicy::distanceFrom(const glm::vec3 &farPos) const { float dx = farPos[0] - testPos[0]; float dy = farPos[1] - testPos[1]; diff --git a/src/bzfs/SpawnPolicy.h b/src/bzfs/SpawnPolicy.h index acb7d4b9e1..be157c09b2 100644 --- a/src/bzfs/SpawnPolicy.h +++ b/src/bzfs/SpawnPolicy.h @@ -15,6 +15,9 @@ #include "common.h" +// System headers +#include + /* common interface headers */ #include "global.h" /* for TeamColor */ @@ -32,7 +35,7 @@ class SpawnPolicy SpawnPolicy(); virtual ~SpawnPolicy(); - virtual void getPosition(float pos[3], int playerId, bool onGroundOnly, bool notNearEdges); + virtual void getPosition(glm::vec3 &pos, int playerId, bool onGroundOnly, bool notNearEdges); virtual void getAzimuth(float &azimuth); protected: @@ -40,12 +43,12 @@ class SpawnPolicy private: float enemyProximityCheck(float &enemyAngle) const; - float distanceFrom(const float *farPos) const; - bool isFacing(const float *enemyPos, const float enemyAzimuth, const float deviation) const; + float distanceFrom(const glm::vec3 &farPos) const; + bool isFacing(const glm::vec3 &enemyPos, const float enemyAzimuth, const float deviation) const; /* temp, internal use */ TeamColor team; - float testPos[3]; + glm::vec3 testPos; float safeSWRadius; float safeSRRadius; diff --git a/src/bzfs/SpawnPosition.h b/src/bzfs/SpawnPosition.h index c40dfbc4ce..efe2eae5c0 100644 --- a/src/bzfs/SpawnPosition.h +++ b/src/bzfs/SpawnPosition.h @@ -17,6 +17,9 @@ #include "common.h" +// System headers +#include + /* local interface headers */ #include "SpawnPolicy.h" @@ -44,7 +47,7 @@ class SpawnPosition private: float azimuth; - float pos[3]; + glm::vec3 pos; /* class data - determines how the pos and azimuth are determined */ static SpawnPolicy *policy; diff --git a/src/bzfs/TeamBases.cxx b/src/bzfs/TeamBases.cxx index 2a2e8a383b..4548826c91 100644 --- a/src/bzfs/TeamBases.cxx +++ b/src/bzfs/TeamBases.cxx @@ -15,6 +15,8 @@ // System headers #include +#include +#include // Common headers #include "Protocol.h" @@ -72,7 +74,7 @@ TeamBases::TeamBases(TeamColor team, bool initDefault) teamBase.size[2] = 0.0f; } -void TeamBases::addBase(const float *position, const float *_size, +void TeamBases::addBase(const glm::vec3 &position, const glm::vec3 &_size, float rotation ) { TeamBase base(position, _size, rotation); @@ -89,7 +91,7 @@ TeamColor TeamBases::getTeam() const return color; } -const float *TeamBases::getBasePosition( int base ) const +const glm::vec3 &TeamBases::getBasePosition(int base) const { if ((base < 0) || (base >= (int)teamBases.size())) base = 0; @@ -99,22 +101,20 @@ const float *TeamBases::getBasePosition( int base ) const float TeamBases::findBaseZ( float x, float y, float z ) const { - for (TeamBaseList::const_iterator it = teamBases.begin(); it != teamBases.end(); ++it) + for (auto &teamBase : teamBases) { - const float *pos = it->position; - const float *_size = it->size; - float rotation = it->rotation; - float nx = x - pos[0]; - float ny = y - pos[1]; - float an = atan2f(ny, nx) - rotation; - float di = hypotf(nx, ny); - float rx = cosf(an) * di; - float ry = sinf(an) * di; - - - if (fabsf(rx) < _size[0] && - fabsf(ry) < _size[1] && - pos[2] <= z) + const auto &pos = teamBase.position; + if (pos[2] > z) + continue; + + const auto &_size = teamBase.size; + float rotation = teamBase.rotation; + const auto n = glm::vec2(x, y) - glm::vec2(pos); + const float an = atan2f(n.y, n.x) - rotation; + const float di = glm::length(n); + const auto r = glm::abs(glm::vec2(cosf(an), sinf(an))) * di; + + if (r.x < _size[0] && r.y < _size[1]) return pos[2]; } @@ -126,10 +126,10 @@ const TeamBase &TeamBases::getRandomBase( int id ) return teamBases[id % teamBases.size()]; } -TeamBase::TeamBase(const float *pos, const float *siz, float rot) +TeamBase::TeamBase(const glm::vec3 &pos, const glm::vec3 &siz, float rot) { - memcpy(&position, pos, sizeof position); - memcpy(&size, siz, sizeof size); + position = pos; + size = siz; rotation = rot; } diff --git a/src/bzfs/TeamBases.h b/src/bzfs/TeamBases.h index 2a7a62d13e..9996cfe864 100644 --- a/src/bzfs/TeamBases.h +++ b/src/bzfs/TeamBases.h @@ -19,6 +19,7 @@ /* system interface headers */ #include #include +#include /* common interface headers */ #include "global.h" @@ -29,10 +30,10 @@ class TeamBase // This class represents one base public: TeamBase(): position(), size(), rotation(0.0) {} - TeamBase(const float *pos, const float *siz, float rot); + TeamBase(const glm::vec3 &pos, const glm::vec3 &siz, float rot); void getRandomPosition( float &x, float &y, float &z ) const; - float position[3]; - float size[3]; + glm::vec3 position; + glm::vec3 size; float rotation; }; @@ -44,10 +45,12 @@ class TeamBases TeamBases(); TeamBases(TeamColor team, bool initDefault = false); - void addBase( const float *position, const float *size, float rotation ); + void addBase(const glm::vec3 &position, + const glm::vec3 &size, + float rotation); int size() const; TeamColor getTeam() const; - const float *getBasePosition( int base ) const; + const glm::vec3 &getBasePosition(int base) const; float findBaseZ( float x, float y, float z ) const; const TeamBase& getRandomBase( int id ); diff --git a/src/bzfs/WorldFileLocation.cxx b/src/bzfs/WorldFileLocation.cxx index 5810040755..4b901930a9 100644 --- a/src/bzfs/WorldFileLocation.cxx +++ b/src/bzfs/WorldFileLocation.cxx @@ -24,7 +24,7 @@ WorldFileLocation::WorldFileLocation() { pos[0] = pos[1] = pos[2] = 0.0f; rotation = 0.0f; - size[0] = size[1] = size[2] = 1.0f; + size = glm::vec3(1.0f); } @@ -58,7 +58,7 @@ bool WorldFileLocation::read(const char *cmd, std::istream& input) // else if (strcasecmp ("shift", cmd) == 0) { - float data[3]; + glm::vec3 data; if (!(input >> data[0] >> data[1] >> data[2])) { std::cout << "parameters errors " << std::endl; @@ -68,7 +68,7 @@ bool WorldFileLocation::read(const char *cmd, std::istream& input) } else if (strcasecmp ("scale", cmd) == 0) { - float data[3]; + glm::vec3 data; if (!(input >> data[0] >> data[1] >> data[2])) { std::cout << "parameters errors " << std::endl; @@ -88,7 +88,8 @@ bool WorldFileLocation::read(const char *cmd, std::istream& input) } else if (strcasecmp ("spin", cmd) == 0) { - float angle, normal[3]; + float angle; + glm::vec3 normal; if (!(input >> angle >> normal[0] >> normal[1] >> normal[2])) { std::cout << "parameters errors " << std::endl; diff --git a/src/bzfs/WorldFileLocation.h b/src/bzfs/WorldFileLocation.h index 44422076ed..74d5e27c4c 100644 --- a/src/bzfs/WorldFileLocation.h +++ b/src/bzfs/WorldFileLocation.h @@ -31,9 +31,9 @@ class WorldFileLocation : public WorldFileObject virtual void writeToWorld(WorldInfo*) const; void *pack(void *buf) const; protected: - float pos[3]; + glm::vec3 pos; float rotation; - float size[3]; + glm::vec3 size; MeshTransform transform; }; diff --git a/src/bzfs/WorldGenerators.cxx b/src/bzfs/WorldGenerators.cxx index 2c4bf6046a..2a41b6f8ec 100644 --- a/src/bzfs/WorldGenerators.cxx +++ b/src/bzfs/WorldGenerators.cxx @@ -172,7 +172,7 @@ WorldInfo *defineTeamWorld() if (haveRed) { // around red base - const float *pos = bases[RedTeam].getBasePosition(0); + const auto &pos = bases[RedTeam].getBasePosition(0); myWorld->addPyramid( pos[0] + 0.5f * baseSize - pyrBase, pos[1] - 0.5f * baseSize - pyrBase, 0.0f, 0.0f, @@ -194,7 +194,7 @@ WorldInfo *defineTeamWorld() if (haveGreen) { // around green base - const float *pos = bases[GreenTeam].getBasePosition(0); + const auto &pos = bases[GreenTeam].getBasePosition(0); myWorld->addPyramid( pos[0] - 0.5f * baseSize + pyrBase, pos[1] - 0.5f * baseSize - pyrBase, 0.0f, 0.0f, @@ -216,7 +216,7 @@ WorldInfo *defineTeamWorld() if (haveBlue) { // around blue base - const float *pos = bases[BlueTeam].getBasePosition(0); + const auto &pos = bases[BlueTeam].getBasePosition(0); myWorld->addPyramid( pos[0] - 0.5f * baseSize - pyrBase, pos[1] + 0.5f * baseSize - pyrBase, 0.0f, 0.0f, @@ -238,7 +238,7 @@ WorldInfo *defineTeamWorld() if (havePurple) { // around purple base - const float *pos = bases[PurpleTeam].getBasePosition(0); + const auto &pos = bases[PurpleTeam].getBasePosition(0); myWorld->addPyramid( pos[0] - 0.5f * baseSize - pyrBase, pos[1] - 0.5f * baseSize + pyrBase, 0.0f, 0.0f, @@ -269,10 +269,10 @@ WorldInfo *defineTeamWorld() std::cerr << "need some teams, use -mp\n"; exit(20); } - const float *redPosition = bases[RedTeam].getBasePosition(0); - const float *greenPosition = bases[GreenTeam].getBasePosition(0); - const float *bluePosition = bases[BlueTeam].getBasePosition(0); - const float *purplePosition = bases[PurpleTeam].getBasePosition(0); + const auto &redPosition = bases[RedTeam].getBasePosition(0); + const auto &greenPosition = bases[GreenTeam].getBasePosition(0); + const auto &bluePosition = bases[BlueTeam].getBasePosition(0); + const auto &purplePosition = bases[PurpleTeam].getBasePosition(0); int numBoxes = int((0.5 + 0.4 * bzfrand()) * actCitySize * actCitySize); float boxHeight = BZDB.eval(StateDatabase::BZDB_BOXHEIGHT); @@ -621,8 +621,8 @@ WorldInfo *defineTeamWorld() else { CustomZone zone; - float p[3] = {0.0f, 0.0f, 0.0f}; - const float size[3] = {baseSize * 0.5f, baseSize * 0.5f, 0.0f}; + auto p = glm::vec3(0.0f); + const glm::vec3 size = glm::vec3(baseSize * 0.5f, baseSize * 0.5f, 0.0f); const float safeOff = 0.5f * (baseSize + pyrBase); switch (t) { diff --git a/src/bzfs/WorldInfo.cxx b/src/bzfs/WorldInfo.cxx index 15b94d2590..2c6a1e31a4 100644 --- a/src/bzfs/WorldInfo.cxx +++ b/src/bzfs/WorldInfo.cxx @@ -79,7 +79,7 @@ WorldInfo::~WorldInfo() void WorldInfo::addWall(float x, float y, float z, float r, float w, float h) { - const float pos[3] = {x, y, z}; + const auto pos = glm::vec3(x, y, z); WallObstacle* wall = new WallObstacle(pos, r, w, h, false); OBSTACLEMGR.addWorldObstacle(wall); } @@ -103,7 +103,7 @@ void WorldInfo::addZone(const CustomZone *zone) entryZones.addZone( zone ); } -void WorldInfo::addWeapon(const FlagType *type, const float *origin, +void WorldInfo::addWeapon(const FlagType *type, const glm::vec3 &origin, float direction, float tilt, TeamColor teamColor, float initdelay, const std::vector &delay, TimeKeeper &sync) @@ -121,7 +121,7 @@ void WorldInfo::addWaterLevel (float level, const BzMaterial* matref) void WorldInfo::addBox(float x, float y, float z, float r, float w, float d, float h, bool drive, bool shoot, bool rico) { - const float pos[3] = {x, y, z}; + const auto pos = glm::vec3(x, y, z); BoxBuilding* box = new BoxBuilding(pos, r, w, d, h, drive, shoot, rico, false); OBSTACLEMGR.addWorldObstacle(box); } @@ -130,7 +130,7 @@ void WorldInfo::addPyramid(float x, float y, float z, float r, float w, float d, float h, bool drive, bool shoot, bool rico, bool flipZ) { - const float pos[3] = {x, y, z}; + const auto pos = glm::vec3(x, y, z); PyramidBuilding* pyr = new PyramidBuilding(pos, r, w, d, h, drive, shoot, rico); if (flipZ) pyr->setZFlip(); @@ -141,13 +141,13 @@ void WorldInfo::addTeleporter(float x, float y, float z, float r, float w, float d, float h, float b, bool horizontal, bool drive, bool shoot, bool rico) { - const float pos[3] = {x, y, z}; + const auto pos = glm::vec3(x, y, z); Teleporter* tele = new Teleporter(pos, r, w, d, h, b, horizontal, drive, shoot, rico); OBSTACLEMGR.addWorldObstacle(tele); } -void WorldInfo::addBase(const float pos[3], float r, - const float _size[3], int color, bool, bool, bool rico) +void WorldInfo::addBase(const glm::vec3 &pos, float r, + const glm::vec3 &_size, int color, bool, bool, bool rico) { BaseBuilding* base = new BaseBuilding(pos, r, _size, color, rico); OBSTACLEMGR.addWorldObstacle(base); @@ -165,7 +165,7 @@ void WorldInfo::makeWaterMaterial() // the material BzMaterial material; - const float diffuse[4] = {0.65f, 1.0f, 0.5f, 0.9f}; + const auto diffuse = glm::vec4(0.65f, 1.0f, 0.5f, 0.9f); material.reset(); material.setName("WaterMaterial"); material.setTexture("water"); @@ -274,7 +274,7 @@ InBuildingType WorldInfo::inCylinderNoOctree(Obstacle **location, if (height < Epsilon) height = Epsilon; - float pos[3] = {x, y, z}; + const auto pos = glm::vec3(x, y, z); for (int type = 0; type < GroupDefinition::ObstacleTypeCount; type++) { @@ -299,7 +299,7 @@ InBuildingType WorldInfo::inCylinderNoOctree(Obstacle **location, InBuildingType WorldInfo::cylinderInBuilding(const Obstacle **location, - const float* pos, float radius, + const glm::vec3 &pos, float radius, float height) const { if (height < Epsilon) @@ -327,13 +327,13 @@ InBuildingType WorldInfo::cylinderInBuilding(const Obstacle **location, float x, float y, float z, float radius, float height) const { - const float pos[3] = {x, y, z}; + const auto pos = glm::vec3(x, y, z); return cylinderInBuilding (location, pos, radius, height); } InBuildingType WorldInfo::boxInBuilding(const Obstacle **location, - const float* pos, float angle, + const glm::vec3 &pos, float angle, float width, float breadth, float height) const { if (height < Epsilon) @@ -390,8 +390,8 @@ InBuildingType WorldInfo::classifyHit (const Obstacle* obstacle) const } -bool WorldInfo::getFlagDropPoint(const FlagInfo* fi, const float* pos, - float* pt) const +bool WorldInfo::getFlagDropPoint(const FlagInfo* fi, const glm::vec3 &pos, + glm::vec3 &pt) const { FlagType* flagType = fi->flag.type; const int team = (int)flagType->flagTeam; @@ -419,7 +419,7 @@ bool WorldInfo::getFlagDropPoint(const FlagInfo* fi, const float* pos, } -bool WorldInfo::getFlagSpawnPoint(const FlagInfo* fi, float* pt) const +bool WorldInfo::getFlagSpawnPoint(const FlagInfo* fi, glm::vec3 &pt) const { FlagType* flagType = fi->flag.type; const int team = (int)flagType->flagTeam; @@ -441,7 +441,7 @@ bool WorldInfo::getFlagSpawnPoint(const FlagInfo* fi, float* pt) const } -bool WorldInfo::getPlayerSpawnPoint(const PlayerInfo* pi, float* pt) const +bool WorldInfo::getPlayerSpawnPoint(const PlayerInfo* pi, glm::vec3 &pt) const { const std::string& teamQual = CustomZone::getPlayerTeamQualifier((int)pi->getTeam()); diff --git a/src/bzfs/WorldInfo.h b/src/bzfs/WorldInfo.h index ec8104a92a..eafe5a4d48 100644 --- a/src/bzfs/WorldInfo.h +++ b/src/bzfs/WorldInfo.h @@ -77,7 +77,7 @@ class WorldInfo void addLink(const std::string& from, const std::string& to); void addZone(const CustomZone *zone); - void addWeapon(const FlagType *type, const float *origin, + void addWeapon(const FlagType *type, const glm::vec3 &origin, float direction, float tilt, TeamColor teamColor, float initdelay, const std::vector &delay, TimeKeeper &sync); void addWaterLevel (float level, const BzMaterial* matref); @@ -91,15 +91,15 @@ class WorldInfo void addTeleporter(float x, float y, float z, float r, float w, float d, float h, float b, bool horizontal, bool drive = false, bool shoot = false, bool rico = false); - void addBase(const float pos[3], float r, const float size[3], + void addBase(const glm::vec3 &pos, float r, const glm::vec3 &size, int color, bool drive = false, bool shoot = false, bool rico = false); float getWaterLevel() const; float getMaxWorldHeight() const; - bool getFlagDropPoint(const FlagInfo* fi, const float* pos, float* pt) const; - bool getFlagSpawnPoint(const FlagInfo* fi, float* pt) const; - bool getPlayerSpawnPoint(const PlayerInfo* pi, float* pt) const; + bool getFlagDropPoint(const FlagInfo* fi, const glm::vec3 &pos, glm::vec3 &pt) const; + bool getFlagSpawnPoint(const FlagInfo* fi, glm::vec3 &pt) const; + bool getPlayerSpawnPoint(const PlayerInfo* pi, glm::vec3 &pt) const; void *getDatabase() const; int getDatabaseSize() const; @@ -152,7 +152,7 @@ class WorldInfo * Checking is quite raw */ InBuildingType cylinderInBuilding(const Obstacle **obstacle, - const float* pos, + const glm::vec3 &pos, float radius, float height = 0.0f) const; /** check collision between world object and a Z-axis aligned box. @@ -160,7 +160,7 @@ class WorldInfo * location will return a pointer to the world colliding object */ InBuildingType boxInBuilding(const Obstacle **obstacle, - const float* pos, float angle, + const glm::vec3 &pos, float angle, float width, float breadth, float height) const; diff --git a/src/bzfs/WorldWeapons.cxx b/src/bzfs/WorldWeapons.cxx index 6de9b959c5..2eda3e0b0c 100644 --- a/src/bzfs/WorldWeapons.cxx +++ b/src/bzfs/WorldWeapons.cxx @@ -29,7 +29,8 @@ #include "bzfs.h" #include "ShotManager.h" -uint32_t WorldWeapons::fireShot(FlagType* type, const float origin[3], const float vector[3], int *shotID, +uint32_t WorldWeapons::fireShot(FlagType* type, const glm::vec3 &origin, + const float vector[3], int *shotID, TeamColor teamColor, PlayerId targetPlayerID) { if (!BZDB.isTrue(StateDatabase::BZDB_WEAPONS)) @@ -42,7 +43,7 @@ uint32_t WorldWeapons::fireShot(FlagType* type, const float origin[3], const flo firingInfo.flagType = type; firingInfo.lifetime = BZDB.eval(StateDatabase::BZDB_RELOADTIME); firingInfo.shot.player = ServerPlayer; - memmove(firingInfo.shot.pos, origin, 3 * sizeof(float)); + firingInfo.shot.pos = origin; const float shotSpeed = BZDB.eval(StateDatabase::BZDB_SHOTSPEED); @@ -190,7 +191,7 @@ void WorldWeapons::fire() } -void WorldWeapons::add(const FlagType *type, const float *origin, +void WorldWeapons::add(const FlagType *type, const glm::vec3 &origin, float direction, float tilt, TeamColor teamColor, float initdelay, const std::vector &delay, TimeKeeper &sync) @@ -198,7 +199,7 @@ void WorldWeapons::add(const FlagType *type, const float *origin, Weapon *w = new Weapon(); w->type = type; w->teamColor = teamColor; - memmove(&w->origin, origin, 3*sizeof(float)); + w->origin = origin; w->direction = direction; w->tilt = tilt; w->nextTime = sync; @@ -279,17 +280,13 @@ bool shotUsedInList(int shotID, Shots::ShotList& list) // where we do the world weapon handling for event based shots since they are not really done by the "world" WorldWeaponGlobalEventHandler::WorldWeaponGlobalEventHandler(FlagType *_type, - const float *_origin, + const glm::vec3 &_origin, float _direction, float _tilt, TeamColor teamColor ) { type = _type; - if (_origin) - memcpy(origin,_origin,sizeof(float)*3); - else - origin[0] = origin[1] = origin[2] = 0.0f; - + origin = _origin; direction = _direction; tilt = _tilt; team = convertTeam(teamColor); diff --git a/src/bzfs/WorldWeapons.h b/src/bzfs/WorldWeapons.h index 6a06122e47..b67bcbc1f9 100644 --- a/src/bzfs/WorldWeapons.h +++ b/src/bzfs/WorldWeapons.h @@ -36,7 +36,7 @@ class WorldWeapons WorldWeapons(); ~WorldWeapons(); void fire(); - void add(const FlagType *type, const float *origin, + void add(const FlagType *type, const glm::vec3 &origin, float direction, float tilt, TeamColor teamColor, float initdelay, const std::vector &delay, TimeKeeper &sync); @@ -46,15 +46,17 @@ class WorldWeapons int packSize() const; void *pack(void *buf) const; - uint32_t fireShot(FlagType* type, const float origin[3], const float vector[3], int *shotID, - TeamColor teamColor = RogueTeam, PlayerId targetPlayerID = -1); + uint32_t fireShot(FlagType* type, const glm::vec3 &origin, + const float vector[3], int *shotID, + TeamColor teamColor = RogueTeam, + PlayerId targetPlayerID = -1); private: struct Weapon { const FlagType *type; TeamColor teamColor; - float origin[3]; + glm::vec3 origin; float direction; float tilt; float initDelay; @@ -75,14 +77,16 @@ class WorldWeapons class WorldWeaponGlobalEventHandler : public bz_EventHandler { public: - WorldWeaponGlobalEventHandler(FlagType *type, const float *origin,float direction, float tilt,TeamColor teamColor ); + WorldWeaponGlobalEventHandler(FlagType *type, const glm::vec3 &origin, + float direction, float tilt, + TeamColor teamColor); virtual ~WorldWeaponGlobalEventHandler(); virtual void process ( bz_EventData *eventData ); protected: FlagType *type; - float origin[3]; + glm::vec3 origin; float direction; float tilt; bz_eTeamType team; diff --git a/src/bzfs/bzfs.cxx b/src/bzfs/bzfs.cxx index b6b3379641..db4bec206f 100644 --- a/src/bzfs/bzfs.cxx +++ b/src/bzfs/bzfs.cxx @@ -24,6 +24,9 @@ #include #include #endif +#include +#define GLM_ENABLE_EXPERIMENTAL +#include // implementation-specific bzflag headers #include "NetHandler.h" @@ -508,7 +511,7 @@ void sendTeamUpdate(int playerIndex, int teamIndex1, int teamIndex2) directMessage(playerIndex, MsgTeamUpdate, (char*)buf - (char*)bufStart, bufStart); } -void sendClosestFlagMessage(int playerIndex,FlagType *type, float pos[3] ) +static void sendClosestFlagMessage(int playerIndex, FlagType *type, glm::vec3 &pos) { if (!type) return; @@ -2596,15 +2599,16 @@ void resetFlag(FlagInfo &flag) data.playerID = player; data.flagID = flag.getIndex(); data.flagType = flag.flag.type->flagAbbv.c_str(); - memcpy(data.pos, flag.flag.position, sizeof(float)*3); - + data.pos[0] = flag.flag.position[0]; + data.pos[1] = flag.flag.position[1]; + data.pos[2] = flag.flag.position[2]; worldEventManager.callEvents(bz_eFlagDroppedEvent,&data); } float baseSize = BZDB.eval(StateDatabase::BZDB_BASESIZE); // reposition flag (middle of the map might be a bad idea) - float flagPos[3] = {0.0f, 0.0f, 0.0f}; + auto flagPos = glm::vec3(0.0f); TeamColor teamIndex = flag.teamIndex(); if ((teamIndex >= ::RedTeam) && (teamIndex <= ::PurpleTeam) @@ -2698,7 +2702,9 @@ void zapFlag(FlagInfo &flag) data.playerID = player; data.flagID = flag.getIndex(); data.flagType = flag.flag.type->flagAbbv.c_str(); - memcpy(data.pos, flag.flag.position, sizeof(float)*3); + data.pos[0] = flag.flag.position[0]; + data.pos[1] = flag.flag.position[1]; + data.pos[2] = flag.flag.position[2]; worldEventManager.callEvents(bz_eFlagDroppedEvent,&data); @@ -3256,7 +3262,7 @@ void playerAlive(int playerIndex) // update last position immediately playerData->player.setRestartOnBase(false); - playerData->setPlayerState(spawnData.pos, spawnData.rot); + playerData->setPlayerState(glm::make_vec3(spawnData.pos), spawnData.rot); // send MsgAlive void *buf, *bufStart = getDirectMessageBuffer(); @@ -3624,7 +3630,7 @@ static void searchFlag(GameKeeper::Player &playerData) const PlayerId playerIndex = playerData.getIndex(); - const float *tpos = playerData.lastState.pos; + const auto &tpos = playerData.lastState.pos; float radius2 = radius * radius; int closestFlag = -1; @@ -3636,10 +3642,8 @@ static void searchFlag(GameKeeper::Player &playerData) if (flag.flag.status != FlagOnGround) continue; - const float *fpos = flag.flag.position; - float dist = (tpos[0] - fpos[0]) * (tpos[0] - fpos[0]) - + (tpos[1] - fpos[1]) * (tpos[1] - fpos[1]) - + (tpos[2] - fpos[2]) * (tpos[2] - fpos[2]); + const auto &fpos = flag.flag.position; + float dist = glm::distance2(tpos, fpos); if (dist < radius2) { @@ -3657,7 +3661,9 @@ static void searchFlag(GameKeeper::Player &playerData) FlagInfo &flag = *FlagInfo::get(closestFlag); if (closestFlag != playerData.getLastIdFlag()) { - sendClosestFlagMessage(playerIndex,flag.flag.type,flag.flag.position); + sendClosestFlagMessage(playerIndex, + flag.flag.type, + flag.flag.position); playerData.setLastIdFlag(closestFlag); } } @@ -3676,17 +3682,15 @@ void grabFlag(int playerIndex, FlagInfo &flag, bool checkPos) (checkPos && flag.flag.status != FlagOnGround)) return; - const float* fpos = flag.flag.position; + const auto &fpos = flag.flag.position; if (checkPos) { //last Pos might be lagged by TankSpeed so include in calculation const float tankRadius = BZDBCache::tankRadius; const float tankSpeed = BZDBCache::tankSpeed; - const float radius2 = (tankSpeed + tankRadius + BZDBCache::flagRadius) * (tankSpeed + tankRadius + - BZDBCache::flagRadius); - const float* tpos = playerData->lastState.pos; - const float delta = (tpos[0] - fpos[0]) * (tpos[0] - fpos[0]) + - (tpos[1] - fpos[1]) * (tpos[1] - fpos[1]); + const float radius2 = powf(tankSpeed + tankRadius + BZDBCache::flagRadius, 2); + const auto &tpos = playerData->lastState.pos; + const float delta = glm::distance2(glm::vec2(tpos), glm::vec2(fpos)); if ((fabs(tpos[2] - fpos[2]) < 0.1f) && (delta > radius2)) { @@ -3727,19 +3731,21 @@ void grabFlag(int playerIndex, FlagInfo &flag, bool checkPos) bz_FlagGrabbedEventData_V1 data; data.flagID = flag.getIndex(); data.flagType = flag.flag.type->flagAbbv.c_str(); - memcpy(data.pos,fpos,sizeof(float)*3); + data.pos[0] = fpos[0]; + data.pos[1] = fpos[1]; + data.pos[2] = fpos[2]; data.playerID = playerIndex; worldEventManager.callEvents(bz_eFlagGrabbedEvent,&data); } -void dropFlag(FlagInfo& drpFlag, const float dropPos[3]) +void dropFlag(FlagInfo& drpFlag, const glm::vec3 &dropPos) { assert(world != NULL); const float size = BZDBCache::worldSize * 0.5f; - float pos[3]; + glm::vec3 pos; pos[0] = ((dropPos[0] < -size) || (dropPos[0] > size)) ? 0.0f : dropPos[0]; pos[1] = ((dropPos[1] < -size) || (dropPos[1] > size)) ? 0.0f : dropPos[1]; pos[2] = (dropPos[2] > maxWorldHeight) ? maxWorldHeight : dropPos[2]; @@ -3763,7 +3769,7 @@ void dropFlag(FlagInfo& drpFlag, const float dropPos[3]) minZ = waterLevel; const float maxZ = MAXFLOAT; - float landing[3] = {pos[0], pos[1], pos[2]}; + auto landing = pos; bool safelyDropped = DropGeometry::dropTeamFlag(landing, minZ, maxZ, flagTeam); @@ -3854,14 +3860,16 @@ void dropFlag(FlagInfo& drpFlag, const float dropPos[3]) data.playerID = player; data.flagID = flagIndex; data.flagType = drpFlag.flag.type->flagAbbv.c_str(); - memcpy(data.pos, pos, sizeof(float)*3); + data.pos[0] = pos[0]; + data.pos[1] = pos[1]; + data.pos[2] = pos[2]; worldEventManager.callEvents(bz_eFlagDroppedEvent,&data); } -void dropPlayerFlag(GameKeeper::Player &playerData, const float dropPos[3]) +void dropPlayerFlag(GameKeeper::Player &playerData, const glm::vec3 &dropPos) { const int flagIndex = playerData.player.getFlag(); if (flagIndex < 0) @@ -3954,7 +3962,11 @@ bool captureFlag(int playerIndex, TeamColor teamCaptured, TeamColor teamCapped, allowCap.teamCapped = convertTeam(teamIndex); allowCap.teamCapping = convertTeam(teamCaptured); allowCap.playerCapping = playerIndex; - playerData->getPlayerState(allowCap.pos, allowCap.rot); + glm::vec3 allowCapPos; + playerData->getPlayerState(allowCapPos, allowCap.rot); + allowCap.pos[0] = allowCapPos[0]; + allowCap.pos[1] = allowCapPos[1]; + allowCap.pos[2] = allowCapPos[2]; allowCap.allow = true; @@ -3979,7 +3991,11 @@ bool captureFlag(int playerIndex, TeamColor teamCaptured, TeamColor teamCapped, eventData.teamCapped = convertTeam(teamIndex); eventData.teamCapping = convertTeam(teamCaptured); eventData.playerCapping = playerIndex; - playerData->getPlayerState(eventData.pos, eventData.rot); + glm::vec3 eventDataPos; + playerData->getPlayerState(eventDataPos, eventData.rot); + eventData.pos[0] = eventDataPos[0]; + eventData.pos[1] = eventDataPos[1]; + eventData.pos[2] = eventDataPos[2]; worldEventManager.callEvents(bz_eCaptureEvent,&eventData); @@ -4279,9 +4295,7 @@ static void shotFired(int playerIndex, void *buf, int len) { // drop flag at last known position of player // also handle case where limit was set to 0 - float lastPos [3]; - for (int i = 0; i < 3; i ++) - lastPos[i] = playerData->lastState.pos[i]; + const auto &lastPos = playerData->lastState.pos; fInfo->grabs = 0; // recycle this flag now dropFlag(*fInfo, lastPos); } @@ -4557,7 +4571,7 @@ static bool isTeleporterMotion ( GameKeeper::Player &playerData, PlayerState &st for (i = 0; i < maxTele; i++) { Obstacle *currentTele = teleporterList[i]; - const float *telePosition = currentTele->getPosition(); + const auto &telePosition = currentTele->getPosition(); float deltaInitial2 = squareAndAdd(state.pos[0] - telePosition[0],state.pos[1] - telePosition[1]); float deltaFinal2 = squareAndAdd(playerData.lastState.pos[0] - telePosition[0], playerData.lastState.pos[1] - telePosition[1]); @@ -4916,7 +4930,7 @@ static void handleCommand(int t, void *rawbuf, bool udp) case MsgDropFlag: { // data: position of drop - float pos[3]; + glm::vec3 pos; buf = nboUnpackVector(buf, pos); dropPlayerFlag(*playerData, pos); break; @@ -7908,8 +7922,12 @@ void playerStateToAPIState(bz_PlayerUpdateState &apiState, const PlayerState &pl apiState.phydrv = (playerState.status & PlayerState::OnDriver) ? playerState.phydrv : -1; apiState.rotation = playerState.azimuth; apiState.angVel = playerState.angVel; - memcpy(apiState.pos,playerState.pos,sizeof(float)*3); - memcpy(apiState.velocity,playerState.velocity,sizeof(float)*3); + apiState.pos[0] = playerState.pos[0]; + apiState.pos[1] = playerState.pos[1]; + apiState.pos[2] = playerState.pos[2]; + apiState.velocity[0] = playerState.velocity[0]; + apiState.velocity[1] = playerState.velocity[1]; + apiState.velocity[2] = playerState.velocity[2]; } @@ -7958,8 +7976,12 @@ void APIStateToplayerState(PlayerState &playerState, const bz_PlayerUpdateState playerState.azimuth = apiState.rotation; playerState.angVel = apiState.angVel; - memcpy(playerState.pos,apiState.pos,sizeof(float)*3); - memcpy(playerState.velocity,apiState.velocity,sizeof(float)*3); + playerState.pos[0] = apiState.pos[0]; + playerState.pos[1] = apiState.pos[1]; + playerState.pos[2] = apiState.pos[2]; + playerState.velocity[0] = apiState.velocity[0]; + playerState.velocity[1] = apiState.velocity[1]; + playerState.velocity[2] = apiState.velocity[2]; } diff --git a/src/bzfs/bzfs.h b/src/bzfs/bzfs.h index 7ca943d2d4..f8f826f243 100644 --- a/src/bzfs/bzfs.h +++ b/src/bzfs/bzfs.h @@ -114,7 +114,7 @@ extern bool areFoes(TeamColor team1, TeamColor team2); extern PingPacket getTeamCounts(); extern void zapFlagByPlayer(int playerIndex); extern void resetFlag(FlagInfo &flag); -extern void dropFlag(FlagInfo& flag, const float dropPos[3]); +extern void dropFlag(FlagInfo& flag, const glm::vec3 &dropPos); extern void publicize(); extern TeamColor whoseBase(float x, float y, float z); bool defineWorld(void); @@ -170,7 +170,7 @@ void resumeCountdown(int resumedBy = ServerPlayer); void startCountdown(int delay, float limit, int playerID = ServerPlayer); void cancelCountdown( int playerID = ServerPlayer); -void dropPlayerFlag(GameKeeper::Player &playerData, const float dropPos[3]); +void dropPlayerFlag(GameKeeper::Player &playerData, const glm::vec3 &dropPos); void playerAlive(int playerIndex); void sendChatMessage(PlayerId srcPlayer, PlayerId dstPlayer, const char *message, MessageType type); diff --git a/src/bzfs/bzfsAPI.cxx b/src/bzfs/bzfsAPI.cxx index 8bca408bc1..cac097c365 100644 --- a/src/bzfs/bzfsAPI.cxx +++ b/src/bzfs/bzfsAPI.cxx @@ -16,6 +16,10 @@ // implementation wrappers for all the bzf_ API functions #include "bzfsAPI.h" +// System headers +#include + +// Common headers #include "bzfs.h" #include "WorldWeapons.h" #include "WorldEventManager.h" @@ -118,9 +122,9 @@ void setBZMatFromAPIMat (BzMaterial &bzmat, bz_MaterialInfo* material ) bzmat.setName(std::string(material->name.c_str())); bzmat.setAmbient(material->ambient); - bzmat.setDiffuse(material->diffuse); - bzmat.setSpecular(material->specular); - bzmat.setEmission(material->emisive); + bzmat.setDiffuse(glm::make_vec4(material->diffuse)); + bzmat.setSpecular(glm::make_vec3(material->specular)); + bzmat.setEmission(glm::make_vec3(material->emisive)); bzmat.setShininess(material->shine); bzmat.setNoCulling(!material->culling); @@ -1800,7 +1804,8 @@ BZF_API uint32_t bz_fireServerShot(const char* shotType, float origin[3], float FlagType *flag = flagMap.find(flagType)->second; - return world->getWorldWeapons().fireShot(flag, origin, vector, nullptr, (TeamColor)convertTeam(color), targetPlayerId); + return world->getWorldWeapons().fireShot(flag, glm::make_vec3(origin), vector, nullptr, (TeamColor)convertTeam(color), + targetPlayerId); } BZF_API uint32_t bz_getShotMetaData (int fromPlayer, int shotID, const char* name) @@ -2891,7 +2896,7 @@ BZF_API bool bz_moveFlag ( int flag, float pos[3] ) if (teamIndex != ::NoTeam) teamIsEmpty = (team[teamIndex].team.size == 0); - pFlag->resetFlag(pos, teamIsEmpty); + pFlag->resetFlag(glm::make_vec3(pos), teamIsEmpty); sendFlagUpdate(*pFlag); return true; @@ -2932,10 +2937,10 @@ BZF_API bool bz_getFlagPosition ( int flag, float* pos ) if (!player) return false; - memcpy(pos,player->lastState.pos,sizeof(float)*3); + memcpy(pos, glm::value_ptr(player->lastState.pos), sizeof(float) * 3); } else - memcpy(pos,pFlag->flag.position,sizeof(float)*3); + memcpy(pos, glm::value_ptr(pFlag->flag.position), sizeof(float) * 3); return true; } @@ -2945,14 +2950,17 @@ BZF_API bool bz_getNearestFlagSafetyZone(int flag, float *pos) FlagInfo *flagInfo = FlagInfo::get(flag); TeamColor myTeam = flagInfo->teamIndex(); - float currPos[3]; - bz_getFlagPosition(flag, currPos); + glm::vec3 currPos; + bz_getFlagPosition(flag, glm::value_ptr(currPos)); if (myTeam == NoTeam) return false; + auto myPos = glm::make_vec3(pos); const std::string &safetyQualifier = CustomZone::getFlagSafetyQualifier(myTeam); - return world->getEntryZones().getClosePoint(safetyQualifier, currPos, pos); + bool result = world->getEntryZones().getClosePoint(safetyQualifier, currPos, myPos); + memcpy(pos, glm::value_ptr(myPos), sizeof(float) * 3); + return result; } //------------------------------------------------------------------------- @@ -3041,7 +3049,7 @@ BZF_API bool bz_addWorldBase( float *pos, float rot, float* scale, int teamIndex if (!world || world->isFinisihed() || !pos || !scale) return false; - world->addBase(pos,rot,scale,teamIndex,options.driveThru,options.shootThru); + world->addBase(glm::make_vec3(pos),rot,glm::make_vec3(scale),teamIndex,options.driveThru,options.shootThru); return true; } @@ -3100,7 +3108,7 @@ BZF_API bool bz_addWorldWeapon( const char* _flagType, float *pos, float rot, fl for (unsigned int i = 0; i < delays.size(); i++) realDelays.push_back(delays.get(i)); - world->addWeapon(flag, pos, rot, tilt, RogueTeam, initDelay, realDelays, synct); + world->addWeapon(flag, glm::make_vec3(pos), rot, tilt, RogueTeam, initDelay, realDelays, synct); return true; } @@ -3318,6 +3326,7 @@ BZF_API bool bz_getSpawnPointWithin ( bz_CustomZoneObject *obj, float randomPos[ TimeKeeper start = TimeKeeper::getCurrent(); int tries = 0; + glm::vec3 posRandom; do { if (tries >= 50) @@ -3328,14 +3337,16 @@ BZF_API bool bz_getSpawnPointWithin ( bz_CustomZoneObject *obj, float randomPos[ return false; } - bz_getRandomPoint(obj, randomPos); + bz_getRandomPoint(obj, glm::value_ptr(posRandom)); ++tries; } while ( - !DropGeometry::dropPlayer(randomPos, obj->zMin, obj->zMax) || - !bz_isWithinWorldBoundaries(randomPos) + !DropGeometry::dropPlayer(posRandom, obj->zMin, obj->zMax) || + !bz_isWithinWorldBoundaries(glm::value_ptr(posRandom)) ); + memcpy(randomPos, glm::value_ptr(posRandom), sizeof(float) * 3); + return true; } diff --git a/src/bzfs/commands.cxx b/src/bzfs/commands.cxx index 4aa55b0d6d..3f68803f39 100644 --- a/src/bzfs/commands.cxx +++ b/src/bzfs/commands.cxx @@ -32,6 +32,7 @@ #endif #include #include +#include // common implementation headers #include "bzglob.h" @@ -1440,7 +1441,9 @@ bool FlagCommand::operator() (const char *message, data.playerID = player; data.flagID = flag.getIndex(); data.flagType = flag.flag.type->flagAbbv.c_str(); - memcpy(data.pos, flag.flag.position, sizeof(float)*3); + data.pos[0] = flag.flag.position[0]; + data.pos[1] = flag.flag.position[1]; + data.pos[2] = flag.flag.position[2]; worldEventManager.callEvents(bz_eFlagDroppedEvent,&data); } diff --git a/src/common/Flag.cxx b/src/common/Flag.cxx index 4b81f3a88e..35959af8ff 100644 --- a/src/common/Flag.cxx +++ b/src/common/Flag.cxx @@ -10,8 +10,6 @@ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ -#include "common.h" - /* interface header */ #include "Flag.h" @@ -20,6 +18,7 @@ #include #include #include +#include /* common implementation headers */ #include "Team.h" @@ -406,9 +405,9 @@ FlagSet& Flag::getBadFlags() return FlagType::flagSets[FlagBad]; } -const float* FlagType::getColor() const +const glm::vec3 &FlagType::getColor() const { - static const float superColor[3] = { 1.0, 1.0, 1.0 }; + static const auto superColor = glm::vec3(1.0f); if (flagTeam == NoTeam) return superColor; @@ -416,9 +415,9 @@ const float* FlagType::getColor() const return Team::getTankColor(flagTeam); } -const float* FlagType::getRadarColor() const +const glm::vec3 &FlagType::getRadarColor() const { - static const float superColor[3] = { 1.0, 1.0, 1.0 }; + static const auto superColor = glm::vec3(1.0f); if (flagTeam == NoTeam) return superColor; diff --git a/src/common/ParseColor.cxx b/src/common/ParseColor.cxx index 224763b251..c6b92d2c30 100644 --- a/src/common/ParseColor.cxx +++ b/src/common/ParseColor.cxx @@ -18,6 +18,7 @@ #include #include #include +#include typedef struct { @@ -794,12 +795,22 @@ bool parseColorStream(std::istream& input, float color[4]) return parseColorString(line, color); } +bool parseColorStream(std::istream& input, glm::vec4 &color) +{ + return parseColorStream(input, glm::value_ptr(color)); +} + bool parseColorString(const std::string& str, float color[4]) { return parseColorCString (str.c_str(), color); } +bool parseColorString(const std::string& str, glm::vec4 &color) +{ + return parseColorCString (str.c_str(), glm::value_ptr(color)); +} + bool parseColorCString(const char* str, float color[4]) { diff --git a/src/common/Team.cxx b/src/common/Team.cxx index dbfb5c6846..7ab11b4790 100644 --- a/src/common/Team.cxx +++ b/src/common/Team.cxx @@ -10,13 +10,18 @@ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ -#include "common.h" +// Own interface #include "Team.h" + +// System headers +#include + +// Common headers #include "AnsiCodes.h" #include "BZDBCache.h" #include "Pack.h" -float Team::tankColor[NumTeams][3] = +glm::vec3 Team::tankColor[NumTeams] = { { 1.0f, 1.0f, 0.0f }, // rogue { 1.0f, 0.0f, 0.0f }, // red @@ -27,7 +32,7 @@ float Team::tankColor[NumTeams][3] = { 0.8f, 0.8f, 0.8f }, // rabbit { 1.0f, 0.5f, 0.0f } // hunter orange }; -float Team::radarColor[NumTeams][3] = +glm::vec3 Team::radarColor[NumTeams] = { { 1.0f, 1.0f, 0.0f }, // rogue { 1.0f, 0.15f, 0.15f }, // red @@ -38,7 +43,7 @@ float Team::radarColor[NumTeams][3] = { 1.0f, 1.0f, 1.0f }, // rabbit { 1.0f, 0.5f, 0.0f } // hunter orange }; -float Team::shotColor[NumTeams][3]; +glm::vec3 Team::shotColor[NumTeams]; Team::Team() @@ -132,21 +137,21 @@ TeamColor Team::getTeam(const std::string &name) // const return NoTeam; } -const float* Team::getTankColor(TeamColor team) // const +const glm::vec3 &Team::getTankColor(TeamColor team) // const { if (int(team) < 0) return tankColor[0]; return tankColor[int(team)]; } -const float* Team::getRadarColor(TeamColor team) // const +const glm::vec3 &Team::getRadarColor(TeamColor team) // const { if (int(team) < 0) return radarColor[0]; return radarColor[int(team)]; } -const float* Team::getShotColor(TeamColor team) // const +const glm::vec3 &Team::getShotColor(TeamColor team) // const { if (int(team) < 0) return shotColor[0]; @@ -164,20 +169,18 @@ bool Team::isColorTeam(TeamColor team) // const } void Team::setColors(TeamColor team, - const float* tank, - const float* radar) + const glm::vec3 &tank, + const glm::vec3 &radar) { const int teamIndex = int(team); // ignore bogus team color if (teamIndex < 0) return; + tankColor[teamIndex] = tank; + radarColor[teamIndex] = radar; for (int i = 0; i <= 2; i++) - { - tankColor[teamIndex][i] = tank[i]; - radarColor[teamIndex][i] = radar[i]; shotColor[teamIndex][i] = addBrightness(tank[i]); - } } void Team::updateShotColors() diff --git a/src/game/BzMaterial.cxx b/src/game/BzMaterial.cxx index 6c45532375..3cc56fc482 100644 --- a/src/game/BzMaterial.cxx +++ b/src/game/BzMaterial.cxx @@ -246,13 +246,13 @@ void BzMaterial::reset() { dynamicColor = -1; const float defAmbient[4] = { 0.2f, 0.2f, 0.2f, 1.0f }; - const float defDiffuse[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; - const float defSpecular[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; - const float defEmission[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; + const auto defDiffuse = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f); + const auto defSpecular = glm::vec3(0.0f, 0.0f, 0.0f); + const auto defEmission = glm::vec3(0.0f, 0.0f, 0.0f); memcpy (ambient, defAmbient, sizeof(ambient)); - memcpy (diffuse, defDiffuse, sizeof(diffuse)); - memcpy (specular, defSpecular, sizeof(specular)); - memcpy (emission, defEmission, sizeof(emission)); + diffuse = defDiffuse; + specular = defSpecular; + emission = defEmission; shininess = 0.0f; alphaThreshold = 0.0f; occluder = false; @@ -314,9 +314,9 @@ BzMaterial& BzMaterial::operator=(const BzMaterial& m) dynamicColor = m.dynamicColor; memcpy (ambient, m.ambient, sizeof(ambient)); - memcpy (diffuse, m.diffuse, sizeof(diffuse)); - memcpy (specular, m.specular, sizeof(specular)); - memcpy (emission, m.emission, sizeof(emission)); + diffuse = m.diffuse; + specular = m.specular; + emission = m.emission; shininess = m.shininess; alphaThreshold = m.alphaThreshold; occluder = m.occluder; @@ -355,9 +355,9 @@ bool BzMaterial::operator==(const BzMaterial& m) const if ((dynamicColor != m.dynamicColor) || (memcmp (ambient, m.ambient, sizeof(float[4])) != 0) || - (memcmp (diffuse, m.diffuse, sizeof(float[4])) != 0) || - (memcmp (specular, m.specular, sizeof(float[3])) != 0) || - (memcmp (emission, m.emission, sizeof(float[3])) != 0) || + (diffuse != m.diffuse) || + (specular != m.specular) || + (emission != m.emission) || (shininess != m.shininess) || (alphaThreshold != m.alphaThreshold) || (occluder != m.occluder) || (groupAlpha != m.groupAlpha) || (noRadar != m.noRadar) || (noShadow != m.noShadow) || @@ -398,6 +398,23 @@ static void* pack4Float(void *buf, const float values[4]) return buf; } +static void* pack4Float(void *buf, const glm::vec4 &values) +{ + int i; + for (i = 0; i < 4; i++) + buf = nboPackFloat(buf, values[i]); + return buf; +} + +static void* pack4Float(void *buf, const glm::vec3 &values) +{ + int i; + float temp = 1.0f; + for (i = 0; i < 3; i++) + buf = nboPackFloat(buf, values[i]); + buf = nboPackFloat(buf, temp); + return buf; +} static const void* unpack4Float(const void *buf, float values[4]) { @@ -407,6 +424,23 @@ static const void* unpack4Float(const void *buf, float values[4]) return buf; } +static const void* unpack4Float(const void *buf, glm::vec4 &values) +{ + int i; + for (i = 0; i < 4; i++) + buf = nboUnpackFloat(buf, values[i]); + return buf; +} + +static const void* unpack4Float(const void *buf, glm::vec3 &values) +{ + int i; + float temp = 1.0f; + for (i = 0; i < 3; i++) + buf = nboUnpackFloat(buf, values[i]); + buf = nboUnpackFloat(buf, temp); + return buf; +} void* BzMaterial::pack(void* buf) const { @@ -558,6 +592,28 @@ static void printColor(std::ostream& out, const char *name, return; } +static void printColor(std::ostream& out, const char *name, + const glm::vec4 &color, const glm::vec4 &reference) +{ + if (color != reference) + { + out << name << color[0] << " " << color[1] << " " + << color[2] << " " << color[3] << std::endl; + } + return; +} + +static void printColor(std::ostream& out, const char *name, + const glm::vec3 &color, const glm::vec3 &reference) +{ + if (color != reference) + { + out << name << color[0] << " " << color[1] << " " + << color[2] << " " << 1.0f << std::endl; + } + return; +} + void BzMaterial::print(std::ostream& out, const std::string& indent) const { @@ -651,12 +707,12 @@ void BzMaterial::printMTL(std::ostream& out, const std::string& UNUSED(indent)) const float* c; c = ambient; // not really used out << "#Ka " << c[0] << " " << c[1] << " " << c[2] << std::endl; - c = diffuse; - out << "Kd " << c[0] << " " << c[1] << " " << c[2] << std::endl; - c = emission; - out << "Ke " << c[0] << " " << c[1] << " " << c[2] << std::endl; - c = specular; - out << "Ks " << c[0] << " " << c[1] << " " << c[2] << std::endl; + auto c1 = diffuse; + out << "Kd " << c1[0] << " " << c1[1] << " " << c1[2] << std::endl; + auto c3 = emission; + out << "Ke " << c3[0] << " " << c3[1] << " " << c3[2] << std::endl; + auto c2 = specular; + out << "Ks " << c2[0] << " " << c2[1] << " " << c2[2] << std::endl; out << "Ns " << (1000.0f * (shininess / 128.0f)) << std::endl; if (textureCount > 0) { @@ -734,23 +790,21 @@ void BzMaterial::setAmbient(const float color[4]) return; } -void BzMaterial::setDiffuse(const float color[4]) +void BzMaterial::setDiffuse(const glm::vec4 &color) { - memcpy (diffuse, color, sizeof(float[4])); + diffuse = color; return; } -void BzMaterial::setSpecular(const float color[3]) +void BzMaterial::setSpecular(const glm::vec3 &color) { - memcpy (specular, color, sizeof(float[3])); - specular[3] = 1.0f; + specular = color; return; } -void BzMaterial::setEmission(const float color[3]) +void BzMaterial::setEmission(const glm::vec3 &color) { - memcpy (emission, color, sizeof(float[3])); - emission[3] = 1.0f; + emission = color; return; } @@ -949,17 +1003,17 @@ const float* BzMaterial::getAmbient() const return ambient; } -const float* BzMaterial::getDiffuse() const +const glm::vec4 &BzMaterial::getDiffuse() const { return diffuse; } -const float* BzMaterial::getSpecular() const +const glm::vec3 &BzMaterial::getSpecular() const { return specular; } -const float* BzMaterial::getEmission() const +const glm::vec3 &BzMaterial::getEmission() const { return emission; } diff --git a/src/game/CollisionManager.cxx b/src/game/CollisionManager.cxx index ff3d1debfa..45d5da3897 100644 --- a/src/game/CollisionManager.cxx +++ b/src/game/CollisionManager.cxx @@ -267,19 +267,19 @@ const ObsList* CollisionManager::axisBoxTest (const Extents& exts) } -const ObsList* CollisionManager::cylinderTest (const float *pos, +const ObsList* CollisionManager::cylinderTest (const glm::vec3 &pos, float radius, float height) const { if (root == NULL) return &EmptyList; - float tmpMins[3], tmpMaxs[3]; - tmpMins[0] = pos[0] - radius; - tmpMins[1] = pos[1] - radius; - tmpMins[2] = pos[2]; - tmpMaxs[0] = pos[0] + radius; - tmpMaxs[1] = pos[1] + radius; - tmpMaxs[2] = pos[2] + height; + auto tmpMins = pos; + auto tmpMaxs = pos; + tmpMins[0] -= radius; + tmpMins[1] -= radius; + tmpMaxs[0] += radius; + tmpMaxs[1] += radius; + tmpMaxs[2] += height; FullPad.count = 0; @@ -296,7 +296,7 @@ const ObsList* CollisionManager::cylinderTest (const float *pos, } -const ObsList* CollisionManager::boxTest (const float* pos, float UNUSED(angle), +const ObsList* CollisionManager::boxTest (const glm::vec3 &pos, float UNUSED(angle), float dx, float dy, float dz) const { float radius = sqrtf (dx*dx + dy*dy); @@ -304,14 +304,12 @@ const ObsList* CollisionManager::boxTest (const float* pos, float UNUSED(angle), } -const ObsList* CollisionManager::movingBoxTest (const float* oldPos, float UNUSED(oldAngle), - const float* pos, float UNUSED(angle), +const ObsList* CollisionManager::movingBoxTest (const glm::vec3 &oldPos, float UNUSED(oldAngle), + const glm::vec3 &pos, float UNUSED(angle), float dx, float dy, float dz) const { - float newpos[3]; - // adjust the Z parameters for the motion - memcpy (newpos, pos, sizeof(float[3])); + auto newpos = pos; if (oldPos[2] < pos[2]) { newpos[2] = oldPos[2]; @@ -612,7 +610,7 @@ ColDetNode::ColDetNode(unsigned char _depth, testExts.addMargin(testFudge); // setup some test parameters - float pos[3]; + glm::vec3 pos; pos[0] = 0.5f * (testExts.maxs[0] + testExts.mins[0]); pos[1] = 0.5f * (testExts.maxs[1] + testExts.mins[1]); pos[2] = testExts.mins[2]; @@ -620,7 +618,7 @@ ColDetNode::ColDetNode(unsigned char _depth, size[0] = 0.5f * (testExts.maxs[0] - testExts.mins[0]); size[1] = 0.5f * (testExts.maxs[1] - testExts.mins[1]); size[2] = (testExts.maxs[2] - testExts.mins[2]); - float point[3]; + glm::vec3 point; point[0] = pos[0]; point[1] = pos[1]; point[2] = 0.5f * (testExts.maxs[2] + testExts.mins[2]); @@ -725,15 +723,13 @@ ColDetNode::~ColDetNode() void ColDetNode::makeChildren () { int side[3]; // the axis sides (0 or 1) - float center[3]; Extents exts; // setup the center point - for (int i = 0; i < 3; i++) - center[i] = 0.5f * (extents.maxs[i] + extents.mins[i]); + auto center = 0.5f * (extents.maxs + extents.mins); childCount = 0; - const float* extentSet[3] = { extents.mins, center, extents.maxs }; + const glm::vec3 extentSet[3] = { extents.mins, center, extents.maxs }; for (side[0] = 0; side[0] < 2; side[0]++) { @@ -942,8 +938,8 @@ void ColDetNode::tallyStats() void ColDetNode::draw(DrawLinesFunc drawLinesFunc) { int x, y, z, c; - float points[5][3]; - const float* exts[2] = { extents.mins, extents.maxs }; + glm::vec3 points[5]; + const glm::vec3 exts[2] = { extents.mins, extents.maxs }; // pick a color int hasMeshObs = 0; @@ -968,7 +964,7 @@ void ColDetNode::draw(DrawLinesFunc drawLinesFunc) points[c][1] = exts[y][1]; points[c][2] = exts[z][2]; } - memcpy (points[4], points[0], sizeof (points[4])); + points[4] = points[0]; drawLinesFunc (5, points, color); } diff --git a/src/game/DynamicColor.cxx b/src/game/DynamicColor.cxx index 0ebc00ec67..36fcd1a476 100644 --- a/src/game/DynamicColor.cxx +++ b/src/game/DynamicColor.cxx @@ -17,6 +17,7 @@ #include #include #include +#include /* common implementation headers */ #include "GameTime.h" @@ -169,14 +170,14 @@ void DynamicColorManager::print(std::ostream& out, const std::string& indent) co DynamicColor::DynamicColor() { + // the parameters are setup so that all channels + // are at 1.0f, and that there are no variations + color = glm::vec4(1.0f); + minValue = glm::vec4(0.0f); + maxValue = glm::vec4(1.0f); // setup the channels for (int c = 0; c < 4; c++) { - // the parameters are setup so that all channels - // are at 1.0f, and that there are no variations - color[c] = 1.0f; - channels[c].minValue = 0.0f; - channels[c].maxValue = 1.0f; channels[c].sequence.count = 0; channels[c].sequence.list = NULL; } @@ -221,7 +222,7 @@ void DynamicColor::finalize() possibleAlpha = true; const ChannelParams& p = channels[3]; // the alpha channel - if ((p.minValue == 1.0f) && (p.maxValue == 1.0f)) + if ((minValue.a == 1.0f) && (maxValue.a == 1.0f)) { // opaque regardless of functions possibleAlpha = false; @@ -232,7 +233,7 @@ void DynamicColor::finalize() // check the a special sequence case const sequenceParams& seq = p.sequence; if ((seq.count > 0) && - (noAlphaSeqMid && (p.minValue == 0.0f) && (p.maxValue == 1.0f))) + (noAlphaSeqMid && (minValue.a == 0.0f) && (maxValue.a == 1.0f))) { // transparency, not translucency possibleAlpha = false; @@ -247,7 +248,7 @@ void DynamicColor::finalize() (p.sequence.count == 0)) { // not using any functions - if (p.maxValue == 1.0f) + if (maxValue.a == 1.0f) possibleAlpha = false; } } @@ -293,8 +294,8 @@ void DynamicColor::setLimits(int channel, float min, float max) else if (max > 1.0f) max = 1.0f; - channels[channel].minValue = min; - channels[channel].maxValue = max; + minValue[channel] = min; + maxValue[channel] = max; return; } @@ -370,6 +371,8 @@ void DynamicColor::addClampDown(int channel, const float clampDown[3]) void DynamicColor::update (double t) { + // the amount of 'max' in the resultant channel's value + auto factor = glm::vec4(1.0f); for (int c = 0; c < 4; c++) { const ChannelParams& channel = channels[c]; @@ -429,16 +432,13 @@ void DynamicColor::update (double t) } } - // the amount of 'max' in the resultant channel's value - float factor = 1.0f; - // check the clamps if (clampUp && clampDown) - factor = 0.5f; + factor[c] = 0.5f; else if (clampUp) - factor = 1.0f; + factor[c] = 1.0f; else if (clampDown) - factor = 0.0f; + factor[c] = 0.0f; // no clamps, try sinusoids else if (channel.sinusoids.size() > 0) { @@ -451,17 +451,13 @@ void DynamicColor::update (double t) value += s.weight * (float)cos(clampedPhase * (M_PI * 2.0)); } // center the factor - factor = 0.5f + (0.5f * value); - if (factor < 0.0f) - factor = 0.0f; - else if (factor > 1.0f) - factor = 1.0f; + factor[c] = 0.5f + (0.5f * value); + factor[c] = glm::clamp(factor[c], 0.0f, 1.0f); } - - color[c] = (channel.minValue * (1.0f - factor)) + - (channel.maxValue * factor); } + color = glm::mix(minValue, maxValue, factor); + return; } @@ -475,8 +471,8 @@ void * DynamicColor::pack(void *buf) const const ChannelParams& p = channels[c]; unsigned int i; - buf = nboPackFloat (buf, p.minValue); - buf = nboPackFloat (buf, p.maxValue); + buf = nboPackFloat (buf, minValue[c]); + buf = nboPackFloat (buf, maxValue[c]); // sinusoids buf = nboPackUInt (buf, (unsigned int)p.sinusoids.size()); @@ -528,8 +524,8 @@ const void * DynamicColor::unpack(const void *buf) unsigned int i; uint32_t size; - buf = nboUnpackFloat (buf, p.minValue); - buf = nboUnpackFloat (buf, p.maxValue); + buf = nboUnpackFloat (buf, minValue[c]); + buf = nboUnpackFloat (buf, maxValue[c]); // sinusoids buf = nboUnpackUInt (buf, size); @@ -621,10 +617,10 @@ void DynamicColor::print(std::ostream& out, const std::string& indent) const { const char *colorStr = colorStrings[c]; const ChannelParams& p = channels[c]; - if ((p.minValue != 0.0f) || (p.maxValue != 1.0f)) + if ((minValue[c] != 0.0f) || (maxValue[c] != 1.0f)) { out << indent << " " << colorStr << " limits " - << p.minValue << " " << p.maxValue << std::endl; + << minValue[c] << " " << maxValue[c] << std::endl; } unsigned int i; if (p.sequence.count > 0) diff --git a/src/game/Frustum.cxx b/src/game/Frustum.cxx index 58555dd7ef..bd1b8ddc21 100644 --- a/src/game/Frustum.cxx +++ b/src/game/Frustum.cxx @@ -10,27 +10,28 @@ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ -#include "common.h" -#include -#include +// Interface #include "Frustum.h" +// System headers +#include +#include +#include +#include +#define GLM_ENABLE_EXPERIMENTAL +#include + Frustum::Frustum() { - static float defaultEye[3] = { 0.0, 0.0, 0.0 }; - static float defaultTarget[3] = { 0.0, 1.0, 0.0 }; - static float identity[16] = { 1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0 - }; + static auto defaultEye = glm::vec3(0.0); + static auto defaultTarget = glm::vec3(0.0, 1.0, 0.0); // initialize view and projection matrices to identity - ::memcpy(viewMatrix, identity, sizeof(viewMatrix)); - ::memcpy(billboardMatrix, identity, sizeof(billboardMatrix)); - ::memcpy(projectionMatrix, identity, sizeof(projectionMatrix)); - ::memcpy(deepProjectionMatrix, identity, sizeof(deepProjectionMatrix)); + viewMatrix = glm::mat4(1.0f); + billboardMatrix = glm::mat4(1.0f); + projectionMatrix = glm::mat4(1.0f); + deepProjectionMatrix = glm::mat4(1.0f); setProjection((float)(M_PI/4.0), 1.0f, 100.0f, 1000.0f, 1, 1, 1); setView(defaultEye, defaultTarget); @@ -43,126 +44,54 @@ Frustum::~Frustum() } -float Frustum::getEyeDepth(const float* p) const -{ - return viewMatrix[2] * p[0] + viewMatrix[6] * p[1] + - viewMatrix[10] * p[2] + viewMatrix[14]; -} - - -void Frustum::setView(const float* _eye, const float* _target) +void Frustum::setView(const glm::vec3 &_eye, const glm::vec3 &_target) { // set eye and target points - eye[0] = _eye[0]; - eye[1] = _eye[1]; - eye[2] = _eye[2]; - target[0] = _target[0]; - target[1] = _target[1]; - target[2] = _target[2]; - - // compute forward vector and normalize - plane[0][0] = target[0] - eye[0]; - plane[0][1] = target[1] - eye[1]; - plane[0][2] = target[2] - eye[2]; - float d = 1.0f / sqrtf(plane[0][0] * plane[0][0] + - plane[0][1] * plane[0][1] + - plane[0][2] * plane[0][2]); - plane[0][0] *= d; - plane[0][1] *= d; - plane[0][2] *= d; - - // compute left vector (by crossing forward with - // world-up [0 0 1]T and normalizing) - right[0] = plane[0][1]; - right[1] = -plane[0][0]; - d = 1.0f / hypotf(right[0], right[1]); - right[0] *= d; - right[1] *= d; - right[2] = 0.0f; - - // compute local up vector (by crossing right and forward, - // normalization unnecessary) - up[0] = right[1] * plane[0][2]; - up[1] = -right[0] * plane[0][2]; - up[2] = right[0] * plane[0][1] - right[1] * plane[0][0]; + eye = _eye; + target = _target; // build view matrix, including a transformation bringing // world up [0 0 1 0]T to eye up [0 1 0 0]T, world north // [0 1 0 0]T to eye forward [0 0 -1 0]T. - viewMatrix[0] = right[0]; - viewMatrix[4] = right[1]; - viewMatrix[8] = 0.0f; - - viewMatrix[1] = up[0]; - viewMatrix[5] = up[1]; - viewMatrix[9] = up[2]; - - viewMatrix[2] = -plane[0][0]; - viewMatrix[6] = -plane[0][1]; - viewMatrix[10] = -plane[0][2]; - - viewMatrix[12] = -(viewMatrix[0] * eye[0] + - viewMatrix[4] * eye[1] + - viewMatrix[8] * eye[2]); - viewMatrix[13] = -(viewMatrix[1] * eye[0] + - viewMatrix[5] * eye[1] + - viewMatrix[9] * eye[2]); - viewMatrix[14] = -(viewMatrix[2] * eye[0] + - viewMatrix[6] * eye[1] + - viewMatrix[10] * eye[2]); + viewMatrix = glm::lookAt(eye, target, glm::vec3(0.0f, 0.0f, 1.0f)); + + // compute left vector + right = glm::vec3(glm::row(viewMatrix, 0)); + + // compute local up vector + up = glm::vec3(glm::row(viewMatrix, 1)); + + // compute forward vector + auto dir = -glm::vec3(glm::row(viewMatrix, 2)); // build billboard matrix. billboard matrix performs rotation // so that polygons drawn in the xy plane face the camera. - billboardMatrix[0] = viewMatrix[0]; - billboardMatrix[1] = viewMatrix[4]; - billboardMatrix[2] = viewMatrix[8]; - billboardMatrix[4] = viewMatrix[1]; - billboardMatrix[5] = viewMatrix[5]; - billboardMatrix[6] = viewMatrix[9]; - billboardMatrix[8] = viewMatrix[2]; - billboardMatrix[9] = viewMatrix[6]; - billboardMatrix[10] = viewMatrix[10]; + billboardMatrix = glm::mat4(glm::transpose(glm::mat3(viewMatrix))); // compute vectors of frustum edges - const float xs = fabsf(1.0f / projectionMatrix[0]); - const float ys = fabsf(1.0f / projectionMatrix[5]); - float edge[4][3]; - edge[0][0] = plane[0][0] - xs * right[0] - ys * up[0]; - edge[0][1] = plane[0][1] - xs * right[1] - ys * up[1]; - edge[0][2] = plane[0][2] - xs * right[2] - ys * up[2]; - edge[1][0] = plane[0][0] + xs * right[0] - ys * up[0]; - edge[1][1] = plane[0][1] + xs * right[1] - ys * up[1]; - edge[1][2] = plane[0][2] + xs * right[2] - ys * up[2]; - edge[2][0] = plane[0][0] + xs * right[0] + ys * up[0]; - edge[2][1] = plane[0][1] + xs * right[1] + ys * up[1]; - edge[2][2] = plane[0][2] + xs * right[2] + ys * up[2]; - edge[3][0] = plane[0][0] - xs * right[0] + ys * up[0]; - edge[3][1] = plane[0][1] - xs * right[1] + ys * up[1]; - edge[3][2] = plane[0][2] - xs * right[2] + ys * up[2]; + const auto xs = right / fabsf(projectionMatrix[0][0]); + const auto ys = up / fabsf(projectionMatrix[1][1]); + glm::vec3 edge[4]; + edge[0] = dir - xs - ys; + edge[1] = dir + xs - ys; + edge[2] = dir + xs + ys; + edge[3] = dir - xs + ys; // make frustum planes - plane[0][3] = -(eye[0] * plane[0][0] + eye[1] * plane[0][1] + - eye[2] * plane[0][2] + m_near); + plane[0] = glm::vec4(dir, -(glm::dot(eye, dir) + m_near)); makePlane(edge[0], edge[3], 1); makePlane(edge[2], edge[1], 2); makePlane(edge[1], edge[0], 3); makePlane(edge[3], edge[2], 4); - plane[5][0] = -plane[0][0]; - plane[5][1] = -plane[0][1]; - plane[5][2] = -plane[0][2]; - plane[5][3] = -plane[0][3] + m_far; + plane[5] = -plane[0]; + plane[5].w += m_far; // make far corners for (int i = 0; i < 4; i++) - { - farCorner[i][0] = eye[0] + m_far * edge[i][0]; - farCorner[i][1] = eye[1] + m_far * edge[i][1]; - farCorner[i][2] = eye[2] + m_far * edge[i][2]; - } + farCorner[i] = eye + m_far * edge[i]; // setup tilt and angle - const float* dir = plane[0]; tilt = (float)((180.0 / M_PI) * atan2((double)dir[2], 1.0)); rotation = (float)((180.0 / M_PI) * atan2((double)dir[1], (double)dir[2])); } @@ -193,28 +122,28 @@ void Frustum::setProjection(float fov, // compute projectionMatrix const float s = 1.0f / tanf(fov / 2.0f); const float fracHeight = 1.0f - float(viewHeight) / float(height); - projectionMatrix[0] = s; - projectionMatrix[5] = (1.0f - fracHeight) * s * float(width) / float(viewHeight); - projectionMatrix[8] = 0.0f; - projectionMatrix[9] = -fracHeight; - projectionMatrix[10] = -(m_far + m_near) / (m_far - m_near); - projectionMatrix[11] = -1.0f; - projectionMatrix[12] = 0.0f; - projectionMatrix[14] = -2.0f * m_far * m_near / (m_far - m_near); - projectionMatrix[15] = 0.0f; - - deepProjectionMatrix[0] = projectionMatrix[0]; - deepProjectionMatrix[5] = projectionMatrix[5]; - deepProjectionMatrix[8] = projectionMatrix[8]; - deepProjectionMatrix[9] = projectionMatrix[9]; - deepProjectionMatrix[11] = projectionMatrix[11]; - deepProjectionMatrix[12] = projectionMatrix[12]; - deepProjectionMatrix[15] = projectionMatrix[15]; - deepProjectionMatrix[10] = -(m_deep_far + m_near) / (m_deep_far - m_near); - deepProjectionMatrix[14] = -2.0f * m_deep_far * m_near / (m_deep_far - m_near); + projectionMatrix[0][0] = s; + projectionMatrix[1][1] = (1.0f - fracHeight) * s * float(width) / float(viewHeight); + projectionMatrix[2][0] = 0.0f; + projectionMatrix[2][1] = -fracHeight; + projectionMatrix[2][2] = -(m_far + m_near) / (m_far - m_near); + projectionMatrix[2][3] = -1.0f; + projectionMatrix[3][0] = 0.0f; + projectionMatrix[3][2] = -2.0f * m_far * m_near / (m_far - m_near); + projectionMatrix[3][3] = 0.0f; + + deepProjectionMatrix[0][0] = projectionMatrix[0][0]; + deepProjectionMatrix[1][1] = projectionMatrix[1][1]; + deepProjectionMatrix[2][0] = projectionMatrix[2][0]; + deepProjectionMatrix[2][1] = projectionMatrix[2][1]; + deepProjectionMatrix[2][3] = projectionMatrix[2][3]; + deepProjectionMatrix[3][0] = projectionMatrix[3][0]; + deepProjectionMatrix[3][3] = projectionMatrix[3][3]; + deepProjectionMatrix[2][2] = -(m_deep_far + m_near) / (m_deep_far - m_near); + deepProjectionMatrix[3][2] = -2.0f * m_deep_far * m_near / (m_deep_far - m_near); // get field of view in y direction - fovy = 2.0f * atanf(1.0f / projectionMatrix[5]); + fovy = 2.0f * atanf(1.0f / projectionMatrix[1][1]); // compute areaFactor areaFactor = 0.25f * s * float(height); @@ -224,26 +153,18 @@ void Frustum::setProjection(float fov, void Frustum::setOffset(float eyeOffset, float focalPlane) { - projectionMatrix[12] = 0.5f * eyeOffset * projectionMatrix[0]; - projectionMatrix[8] = projectionMatrix[12] / focalPlane; - deepProjectionMatrix[8] = projectionMatrix[8]; - deepProjectionMatrix[12] = projectionMatrix[12]; + projectionMatrix[3][0] = 0.5f * eyeOffset * projectionMatrix[0][0]; + projectionMatrix[2][0] = projectionMatrix[3][0] / focalPlane; + deepProjectionMatrix[2][0] = projectionMatrix[2][0]; + deepProjectionMatrix[3][0] = projectionMatrix[3][0]; } -void Frustum::makePlane(const float* v1, const float* v2, int index) +void Frustum::makePlane(const glm::vec3 &v1, const glm::vec3 &v2, int index) { // get normal by crossing v1 and v2 and normalizing - float n[3]; - n[0] = v1[1] * v2[2] - v1[2] * v2[1]; - n[1] = v1[2] * v2[0] - v1[0] * v2[2]; - n[2] = v1[0] * v2[1] - v1[1] * v2[0]; - float d = 1.0f / sqrtf(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]); - plane[index][0] = d * n[0]; - plane[index][1] = d * n[1]; - plane[index][2] = d * n[2]; - plane[index][3] = -(eye[0] * plane[index][0] + eye[1] * plane[index][1] + - eye[2] * plane[index][2]); + auto n = glm::normalize(glm::cross(v1, v2)); + plane[index] = glm::vec4(n, -glm::dot(eye, n)); } @@ -254,8 +175,8 @@ void Frustum::flipVertical() eye[2] = -eye[2]; target[2] = -target[2]; setView(eye, target); - projectionMatrix[5] = -projectionMatrix[5]; - deepProjectionMatrix[5] = -deepProjectionMatrix[5]; + projectionMatrix[1][1] = -projectionMatrix[1][1]; + deepProjectionMatrix[1][1] = -deepProjectionMatrix[1][1]; return; } @@ -266,8 +187,8 @@ void Frustum::flipHorizontal() eye[0] = -eye[0]; target[0] = -target[0]; setView(eye, target); - projectionMatrix[0] = -projectionMatrix[0]; - deepProjectionMatrix[0] = -deepProjectionMatrix[0]; + projectionMatrix[0][0] = -projectionMatrix[0][0]; + deepProjectionMatrix[0][0] = -deepProjectionMatrix[0][0]; return; } @@ -276,54 +197,27 @@ void Frustum::flipHorizontal() void Frustum::setOrthoPlanes(const Frustum& view, float width, float breadth) { // setup the eye, and the clipping planes - memcpy(eye, view.getEye(), sizeof(float[3])); - - float front[2], left[2]; - const float* dir = view.getDirection(); - float len = (dir[0] * dir[0]) + (dir[1] * dir[1]); - if (len != 0) - { - len = 1.0f / sqrtf(len); - front[0] = dir[0] * len; - front[1] = dir[1] * len; - } - else - { - front[0] = 1.0f; - front[1] = 0.0f; - } - - left[0] = -front[1]; - left[1] = +front[0]; + eye = view.getEye(); - plane[1][0] = +left[0]; - plane[1][1] = +left[1]; - plane[1][3] = -((eye[0] * plane[1][0]) + (eye[1] * plane[1][1])) + width; - - plane[2][0] = -left[0]; - plane[2][1] = -left[1]; - plane[2][3] = -((eye[0] * plane[2][0]) + (eye[1] * plane[2][1])) + width; - - plane[3][0] = +front[0]; - plane[3][1] = +front[1]; - plane[3][3] = -((eye[0] * plane[3][0]) + (eye[1] * plane[3][1])) + breadth; + glm::vec3 front; + auto tmp = glm::vec2(view.getDirection()); + if (tmp.x || tmp.y) + front = glm::vec3(glm::normalize(tmp), 0.0f); + else + front = glm::vec3(1.0f, 0.0f, 0.0f); - plane[4][0] = -front[0]; - plane[4][1] = -front[1]; - plane[4][3] = -((eye[0] * plane[4][0]) + (eye[1] * plane[4][1])) + breadth; + auto left = glm::vec3(-front[1], front[0], 0.0f); - plane[1][2] = 0.0f; - plane[2][2] = 0.0f; - plane[3][2] = 0.0f; - plane[4][2] = 0.0f; + float dotl = glm::dot(eye, left); + float dotf = glm::dot(eye, front); + plane[1] = glm::vec4( left, -dotl + width); + plane[2] = glm::vec4(-left, dotl + width); + plane[3] = glm::vec4( front, -dotf + breadth); + plane[4] = glm::vec4(-front, dotf + breadth); // disable the near and far planes - plane[0][0] = plane[0][1] = 0.0f; - plane[0][2] = 1.0f; - plane[0][3] = -1.0e6; - plane[5][0] = plane[0][1] = 0.0f; - plane[5][2] = 1.0f; - plane[5][3] = -1.0e6; + plane[0] = glm::vec4(0.0f, 0.0f, 1.0f, -1.0e6); + plane[5] = glm::vec4(0.0f, 0.0f, 1.0f, -1.0e6); planeCount = 5; diff --git a/src/game/Intersect.cxx b/src/game/Intersect.cxx index 3f75ff6c83..5063d9fc68 100644 --- a/src/game/Intersect.cxx +++ b/src/game/Intersect.cxx @@ -10,9 +10,15 @@ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ -#include "common.h" -#include +// Its interface #include "Intersect.h" + +// System headers +#include +#define GLM_ENABLE_EXPERIMENTAL +#include + +// common headers #include "Extents.h" @@ -72,13 +78,11 @@ static float getNormalOrigRect(const float* p, float dx, float dy) } -void getNormalRect(const float* p1, const float* p2, - float angle, float dx, float dy, float* n) +void getNormalRect(const glm::vec2 p1, const glm::vec2 p2, + float angle, float dx, float dy, glm::vec3 &n) { // translate origin - float pa[2]; - pa[0] = p1[0] - p2[0]; - pa[1] = p1[1] - p2[1]; + auto pa = p1 - p2; // rotate float pb[2]; @@ -90,9 +94,7 @@ void getNormalRect(const float* p1, const float* p2, const float normAngle = getNormalOrigRect(pb, dx, dy) + angle; // make normal - n[0] = cosf(normAngle); - n[1] = sinf(normAngle); - n[2] = 0.0f; + n = glm::vec3(cosf(normAngle), sinf(normAngle), 0.0f); } @@ -127,13 +129,11 @@ bool testOrigRectCircle(float dx, float dy, const float* p, float r) } -bool testRectCircle(const float* p1, float angle, - float dx, float dy, const float* p2, float r) +bool testRectCircle(const glm::vec2 p1, float angle, + float dx, float dy, const glm::vec2 p2, float r) { // translate origin - float pa[2]; - pa[0] = p2[0] - p1[0]; - pa[1] = p2[1] - p1[1]; + auto pa = p2 - p1; // rotate float pb[2]; @@ -150,31 +150,25 @@ bool testRectCircle(const float* p1, float angle, Ray rayMinusRay(const Ray& r1, float t1, const Ray& r2, float t2) { // get points at respective times - float p1[3], p2[3]; + glm::vec3 p1, p2; r1.getPoint(t1, p1); r2.getPoint(t2, p2); // construct new ray - float p[3], d[3]; - p[0] = p1[0] - p2[0]; - p[1] = p1[1] - p2[1]; - p[2] = p1[2] - p2[2]; - d[0] = r1.getDirection()[0] - r2.getDirection()[0]; - d[1] = r1.getDirection()[1] - r2.getDirection()[1]; - d[2] = r1.getDirection()[2] - r2.getDirection()[2]; + const auto p = p1 - p2; + const auto d = r1.getDirection() - r2.getDirection(); return Ray(p, d); } float rayAtDistanceFromOrigin(const Ray& r, float radius) { - const float* d = r.getDirection(); - if (d[0] == 0.0 && d[1] == 0.0 && d[2] == 0.0) return 0.0f; - - const float* p = r.getOrigin(); - const float a = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; - const float b = -(p[0] * d[0] + p[1] * d[1] + p[2] * d[2]); - const float c = p[0] * p[0] + p[1] * p[1] + p[2] * p[2] - radius * radius; + const auto &d = r.getDirection(); + const auto &p = r.getOrigin(); + const float a = glm::length2(d); + if (a == 0.0f) return 0.0f; + const float b = -glm::dot(p, d); + const float c = glm::length2(p) - radius * radius; const float disc = b * b - a * c; if (disc < 0.0f) return -1.0f; // misses sphere const float d1_2 = sqrtf(disc); @@ -267,12 +261,12 @@ static float timeRayHitsOrigBox(const float* p, const float* v, } -float timeRayHitsBlock(const Ray& r, const float* p1, +float timeRayHitsBlock(const Ray& r, const glm::vec3 &p1, float angle, float dx, float dy, float dz) { // get names for ray info - const float* p2 = r.getOrigin(); - const float* d = r.getDirection(); + const auto &p2 = r.getOrigin(); + const auto &d = r.getDirection(); // translate origin float pa[2]; @@ -296,41 +290,30 @@ float timeRayHitsBlock(const Ray& r, const float* p1, /** Computing ray travel time to the plane described by 3 points */ -static float timeRayHitsPlane(const float pb[3], const float db[3], - const float x1[3], const float x2[3], - const float x3[3]) +static float timeRayHitsPlane(const glm::vec3 &pb, const glm::vec3 &db, + const glm::vec3 &x1, const glm::vec3 &x2, + const glm::vec3 &x3) { - float u[3], v[3], d[3]; - int i; + glm::vec3 u, v, d; // Compute the 2 vectors describing the plane - for (i = 0; i < 3; i++) - u[i] = x2[i] - x1[i]; - for (i = 0; i < 3; i++) - v[i] = x3[i] - x1[i]; + u = x2 - x1; + v = x3 - x1; // Thats a distance vector: a vector from the plane to the ray beginning - for (i = 0; i < 3; i++) - d[i] = pb[i] - x1[i]; + d = pb - x1; // plane versor unnormalized - float n[3]; - n[0] = u[1] * v[2] - u[2] * v[1]; - n[1] = u[2] * v[0] - u[0] * v[2]; - n[2] = u[0] * v[1] - u[1] * v[0]; + auto n = glm::cross(u, v); // computing unnormalized distance projecting the distance on versor - float distance = 0.0; - for (i = 0; i < 3; i++) - distance += n[i] * d[i]; + float distance = glm::dot(n, d); // if distance is negative, plane is already passed if (distance <= 0.0f) return 0.0f; // project velocity vector on the plan versor unnormalized - float velocity = 0.0f; - for (i = 0; i < 3; i++) - velocity += n[i] * db[i]; + float velocity = glm::dot(n, db); // if velocity is greater or equal than 0 no way to trespass the plane if (velocity >= 0.0f) @@ -341,27 +324,25 @@ static float timeRayHitsPlane(const float pb[3], const float db[3], } -float timeRayHitsPyramids(const Ray& r, const float* p1, float angle, +float timeRayHitsPyramids(const Ray& r, const glm::vec3 &p1, float angle, float dx, float dy, float dz, bool flipZ) { const float epsilon = 1.0e-3f; // get names for ray info int i; - const float* p2 = r.getOrigin(); - const float* d = r.getDirection(); + const auto &p2 = r.getOrigin(); + const auto &d = r.getDirection(); // translate origin - float pa[2]; - pa[0] = p2[0] - p1[0]; - pa[1] = p2[1] - p1[1]; + auto pa = p2 - p1; // rotate - float pb[3], db[3]; + glm::vec3 pb, db; const float c = cosf(-angle), s = sinf(-angle); pb[0] = c * pa[0] - s * pa[1]; pb[1] = c * pa[1] + s * pa[0]; - pb[2] = p2[2] - p1[2]; + pb[2] = pa[2]; db[0] = c * d[0] - s * d[1]; db[1] = c * d[1] + s * d[0]; db[2] = d[2]; @@ -380,7 +361,7 @@ float timeRayHitsPyramids(const Ray& r, const float* p1, float angle, float residualTime = 0.0f; - float x1[3], x2[3], x3[3]; + glm::vec3 x1, x2, x3; float residualTemp; x1[2] = 0.0f; @@ -509,24 +490,22 @@ float timeAndSideRayHitsOrigRect(const float* p, const float* v, } -float timeAndSideRayHitsRect(const Ray& r, const float* p1, float angle, +float timeAndSideRayHitsRect(const Ray& r, const glm::vec3 &p1, float angle, float dx, float dy, int& side) { // get names for ray info - const float* p2 = r.getOrigin(); - const float* d = r.getDirection(); + const auto &p2 = r.getOrigin(); + const auto &d = r.getDirection(); // translate origin - float pa[2]; - pa[0] = p2[0] - p1[0]; - pa[1] = p2[1] - p1[1]; + auto pa = p2 - p1; // rotate float pb[3], db[3]; const float c = cosf(-angle), s = sinf(-angle); pb[0] = c * pa[0] - s * pa[1]; pb[1] = c * pa[1] + s * pa[0]; - pb[2] = p2[2] - p1[2]; + pb[2] = pa[2]; db[0] = c * d[0] - s * d[1]; db[1] = c * d[1] + s * d[0]; db[2] = d[2]; @@ -620,13 +599,11 @@ static bool testOrigRectRect(const float* p, float angle, } -bool testRectRect(const float* p1, float angle1, float dx1, float dy1, - const float* p2, float angle2, float dx2, float dy2) +bool testRectRect(const glm::vec2 p1, float angle1, float dx1, float dy1, + const glm::vec2 p2, float angle2, float dx2, float dy2) { // translate origin - float pa[2]; - pa[0] = p2[0] - p1[0]; - pa[1] = p2[1] - p1[1]; + auto pa = p2 - p1; // rotate float pb[2]; @@ -639,17 +616,15 @@ bool testRectRect(const float* p1, float angle1, float dx1, float dy1, } -bool testRectInRect(const float* p1, float angle1, float dx1, float dy1, - const float* p2, float angle2, float dx2, float dy2) +bool testRectInRect(const glm::vec2 p1, float angle1, float dx1, float dy1, + const glm::vec2 p2, float angle2, float dx2, float dy2) { static const float box[4][2] = { { 1.0, 1.0 }, { 1.0, -1.0 }, { -1.0, -1.0 }, { -1.0, 1.0 } }; // translate origin - float pa[2]; - pa[0] = p2[0] - p1[0]; - pa[1] = p2[1] - p1[1]; + auto pa = p2 - p1; // rotate float pb[2]; @@ -669,11 +644,11 @@ bool testRectInRect(const float* p1, float angle1, float dx1, float dy1, } -static inline void projectAxisBox(const float* dir, const Extents& extents, +static inline void projectAxisBox(const glm::vec3 &dir, const Extents& extents, float* minDist, float* maxDist) { - static float i[3]; - static float o[3]; + glm::vec3 i; + glm::vec3 o; // find the extreme corners for (int t = 0; t < 3; t++) @@ -690,8 +665,8 @@ static inline void projectAxisBox(const float* dir, const Extents& extents, } } - float idist = (i[0] * dir[0]) + (i[1] * dir[1]) + (i[2] * dir[2]); - float odist = (o[0] * dir[0]) + (o[1] * dir[1]) + (o[2] * dir[2]); + float idist = glm::dot(i, dir); + float odist = glm::dot(o, dir); if (idist < odist) { @@ -708,8 +683,8 @@ static inline void projectAxisBox(const float* dir, const Extents& extents, } -static inline void projectPolygon(const float* dir, - int count, const float (*points)[3], +static inline void projectPolygon(const glm::vec3 &dir, + int count, const glm::vec3 *points, float* minDist, float* maxDist) { float mind = MAXFLOAT; @@ -717,8 +692,8 @@ static inline void projectPolygon(const float* dir, for (int i = 0; i < count; i++) { - const float* p = points[i]; - float dist = (p[0] * dir[0]) + (p[1] * dir[1]) + (p[2] * dir[2]); + const auto p = points[i]; + float dist = glm::dot(p, dir); if (dist < mind) mind = dist; if (dist > maxd) @@ -734,12 +709,12 @@ static inline void projectPolygon(const float* dir, // return true if polygon touches the axis aligned box // *** assumes that an extents test has already been done *** -bool testPolygonInAxisBox(int pointCount, const float (*points)[3], - const float* plane, const Extents& extents) +bool testPolygonInAxisBox(int pointCount, const glm::vec3 *points, + const glm::vec4 &plane, const Extents& extents) { int t; - static float i[3]; // inside point (assuming partial) - static float o[3]; // outside point (assuming partial) + static glm::vec4 i; // inside point (assuming partial) + static glm::vec4 o; // outside point (assuming partial) // test the plane for (t = 0; t < 3; t++) @@ -755,12 +730,10 @@ bool testPolygonInAxisBox(int pointCount, const float (*points)[3], o[t] = extents.maxs[t]; } } - const float icross = (plane[0] * i[0]) + - (plane[1] * i[1]) + - (plane[2] * i[2]) + plane[3]; - const float ocross = (plane[0] * o[0]) + - (plane[1] * o[1]) + - (plane[2] * o[2]) + plane[3]; + i.w = 1.0f; + o.w = 1.0f; + const float icross = glm::dot(plane, i); + const float ocross = glm::dot(plane, o); if ((icross * ocross) > 0.0f) { // same polarity means that the plane doesn't cut the box @@ -768,24 +741,16 @@ bool testPolygonInAxisBox(int pointCount, const float (*points)[3], } // test the edges - const float axisNormals[3][3] = + const glm::vec3 axisNormals[3] = {{1.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}; for (t = 0; t < pointCount; t++) { int next = (t + 1) % pointCount; - float edge[3]; - edge[0] = points[next][0] - points[t][0]; - edge[1] = points[next][1] - points[t][1]; - edge[2] = points[next][2] - points[t][2]; - for (int a = 0; a < 3; a++) + auto edge = points[next] - points[t]; + for (const auto &axis : axisNormals) { - float cross[3]; - const float* axis = axisNormals[a]; - cross[0] = (edge[1] * axis[2]) - (edge[2] * axis[1]); - cross[1] = (edge[2] * axis[0]) - (edge[0] * axis[2]); - cross[2] = (edge[0] * axis[1]) - (edge[1] * axis[0]); - const float length = - (cross[0] * cross[0]) + (cross[1] * cross[1]) + (cross[2] * cross[2]); + const auto cross = glm::cross(edge, axis); + const float length = glm::length2(cross); if (length < 0.001f) continue; // find the projected distances @@ -812,10 +777,9 @@ IntersectLevel testAxisBoxInFrustum(const Extents& extents, // FIXME - use a sphere vs. cone test first? static int s, t; - static float i[3]; // inside point (assuming partial) - static float o[3]; // outside point (assuming partial) + static glm::vec4 i; // inside point (assuming partial) + static glm::vec4 o; // outside point (assuming partial) static float len; - static const float* p; // the plane IntersectLevel result = Contained; // FIXME - 0 is the near clip plane, not that useful really? @@ -823,10 +787,13 @@ IntersectLevel testAxisBoxInFrustum(const Extents& extents, const int planeCount = frustum->getPlaneCount(); + i.w = 1.0f; + o.w = 1.0f; + for (s = 1 /* NOTE: not 0 */; s < planeCount; s++) { - p = frustum->getSide(s); + const auto &p = frustum->getSide(s); // the plane // setup the inside/outside corners // this can be determined easily based @@ -845,14 +812,14 @@ IntersectLevel testAxisBoxInFrustum(const Extents& extents, } } // check the inside length - len = (p[0] * i[0]) + (p[1] * i[1]) + (p[2] * i[2]) + p[3]; + len = glm::dot(p, i); if (len < -1.0f) { return Outside; // box is fully outside the frustum } // check the outside length - len = (p[0] * o[0]) + (p[1] * o[1]) + (p[2] * o[2]) + p[3]; + len = glm::dot(p, o); if (len < -1.0f) { result = Partial; // partial containment at best @@ -867,19 +834,20 @@ IntersectLevel testAxisBoxInFrustum(const Extents& extents, // is contained within all of the planes. // the occluder plane normals point inwards IntersectLevel testAxisBoxOcclusion(const Extents& extents, - const float (*planes)[4], int planeCount) + const glm::vec4 planes[], int planeCount) { static int s, t; - static float i[3]; // inside point (assuming partial) - static float o[3]; // outside point (assuming partial) + static glm::vec4 i; // inside point (assuming partial) + static glm::vec4 o; // outside point (assuming partial) static float len; - static const float* p; // the plane IntersectLevel result = Contained; + i.w = 1.0f; + o.w = 1.0f; for (s = 0; s < planeCount; s++) { - p = planes[s]; + const auto &p = planes[s]; // setup the inside/outside corners // this can be determined easily based @@ -899,7 +867,7 @@ IntersectLevel testAxisBoxOcclusion(const Extents& extents, } // check the inside length - len = (p[0] * i[0]) + (p[1] * i[1]) + (p[2] * i[2]) + p[3]; + len = glm::dot(p, i); if (len < +0.1f) { return Outside; // box is fully outside the occluder @@ -911,7 +879,7 @@ IntersectLevel testAxisBoxOcclusion(const Extents& extents, // the likely number of loops // check the outside length - len = (p[0] * o[0]) + (p[1] * o[1]) + (p[2] * o[2]) + p[3]; + len = glm::dot(p, o); if (len < +0.1f) { result = Partial; // partial containment at best @@ -927,9 +895,8 @@ bool testRayHitsAxisBox(const Ray* ray, const Extents& exts, float* inTime) { int a; - const float* const o = ray->getOrigin(); - const float* const v = ray->getDirection(); - const float* extents[2] = { exts.mins, exts.maxs }; + const auto &o = ray->getOrigin(); + const auto &v = ray->getDirection(); int zone[3]; bool inside = true; @@ -960,6 +927,7 @@ bool testRayHitsAxisBox(const Ray* ray, const Extents& exts, *inTime = 0.0f; else { + const glm::vec3 extents[2] = { exts.mins, exts.maxs }; int hitPlane; // calculate the hitTimes for (a = 0; a < 3; a++) @@ -1006,8 +974,8 @@ bool testRayHitsAxisBox(const Ray* ray, const Extents& extents, return false; int a; - const float* const o = ray->getOrigin(); - const float* const v = ray->getDirection(); + const auto &o = ray->getOrigin(); + const auto &v = ray->getDirection(); // calculate the hitTimes for the outTime float hitTime[3]; diff --git a/src/game/MeshTransform.cxx b/src/game/MeshTransform.cxx index 940f13592d..1f973168e8 100644 --- a/src/game/MeshTransform.cxx +++ b/src/game/MeshTransform.cxx @@ -10,8 +10,6 @@ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ -#include "common.h" - // implementation header #include "MeshTransform.h" @@ -23,6 +21,8 @@ #include #include #include +#include +#include // common headers #include "Pack.h" @@ -151,77 +151,42 @@ void MeshTransformManager::print(std::ostream& out, const std::string& indent) c // Mesh Transform Tool // -static void multiply(float m[4][4], const float n[4][4]) +static void shift(glm::mat4 &m, const float p[3]) { - float t[4][4]; - for (int i = 0; i < 4; i++) - { - for (int j = 0; j < 4; j++) - { - t[i][j] = (m[0][j] * n[i][0]) + (m[1][j] * n[i][1]) + - (m[2][j] * n[i][2]) + (m[3][j] * n[i][3]); - } - } - memcpy (m, t, sizeof(float[4][4])); - return; -} - - -static void shift(float m[4][4], const float p[3]) -{ - const float t[4][4] = {{1.0f, 0.0f, 0.0f, p[0]}, + const glm::mat4 t = {{1.0f, 0.0f, 0.0f, p[0]}, {0.0f, 1.0f, 0.0f, p[1]}, {0.0f, 0.0f, 1.0f, p[2]}, {0.0f, 0.0f, 0.0f, 1.0f} }; - multiply(m, t); - return; -} - - -static void scale(float m[4][4], const float p[3]) -{ - const float t[4][4] = {{p[0], 0.0f, 0.0f, 0.0f}, - {0.0f, p[1], 0.0f, 0.0f}, - {0.0f, 0.0f, p[2], 0.0f}, - {0.0f, 0.0f, 0.0f, 1.0f} - }; - multiply(m, t); + m *= t; return; } -static void shear(float m[4][4], const float p[3]) +static void shear(glm::mat4 &m, const float p[3]) { - const float t[4][4] = {{1.0f, 0.0f, p[0], 0.0f}, + const glm::mat4 t = {{1.0f, 0.0f, p[0], 0.0f}, {0.0f, 1.0f, p[1], 0.0f}, {p[2], 0.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 0.0f, 1.0f} }; - multiply(m, t); + m *= t; return; } -static void spin(float m[4][4], const float radians, const float normal[3]) +static void spin(glm::mat4 &m, const float radians, const glm::vec3 normal) { // normalize - const float len = (normal[0] * normal[0]) + - (normal[1] * normal[1]) + - (normal[2] * normal[2]); - if (len <= 0.0f) + if (!(normal.x || normal.y || normal.z)) return; - const float scale = 1.0f / sqrtf(len); - const float n[3] = {normal[0] * scale, - normal[1] * scale, - normal[2] * scale - }; + const auto n = glm::normalize(normal); // setup const float cos_val = cosf(radians); const float sin_val = sinf(radians); const float icos_val = (1.0f - cos_val); - float t[4][4]; + glm::mat4 t; t[3][3] = 1.0f; t[0][3] = t[1][3] = t[2][3] = 0.0f; t[3][0] = t[3][1] = t[3][2] = 0.0f; @@ -236,7 +201,7 @@ static void spin(float m[4][4], const float radians, const float normal[3]) t[2][2] = (n[2] * n[2] * icos_val) + cos_val; // execute - multiply(m, t); + m *= t; return; } @@ -245,27 +210,8 @@ static void spin(float m[4][4], const float radians, const float normal[3]) MeshTransform::Tool::Tool(const MeshTransform& xform) { // load the identity matrices - int i, j; - for (i = 0; i < 4; i++) - { - for (j = 0; j < 4; j++) - { - if (i == j) - vertexMatrix[i][j] = 1.0f; - else - vertexMatrix[i][j] = 0.0f; - } - } - for (i = 0; i < 3; i++) - { - for (j = 0; j < 3; j++) - { - if (i == j) - normalMatrix[i][j] = 1.0f; - else - normalMatrix[i][j] = 0.0f; - } - } + vertexMatrix = glm::mat4(1.0f); + normalMatrix = glm::mat3(1.0f); skewed = false; if (xform.transforms.size() > 0) @@ -281,7 +227,7 @@ MeshTransform::Tool::Tool(const MeshTransform& xform) processTransforms(xform.transforms); // generate the normal matrix - const float (*vm)[4] = vertexMatrix; + const auto &vm = vertexMatrix; normalMatrix[0][0] = (vm[1][1] * vm[2][2]) - (vm[1][2] * vm[2][1]); normalMatrix[0][1] = (vm[1][2] * vm[2][0]) - (vm[1][0] * vm[2][2]); normalMatrix[0][2] = (vm[1][0] * vm[2][1]) - (vm[1][1] * vm[2][0]); @@ -293,10 +239,7 @@ MeshTransform::Tool::Tool(const MeshTransform& xform) normalMatrix[2][2] = (vm[0][0] * vm[1][1]) - (vm[0][1] * vm[1][0]); // setup the polarity - const float determinant = - (vm[0][0] * ((vm[1][1] * vm[2][2]) - (vm[1][2] * vm[2][1]))) + - (vm[0][1] * ((vm[1][2] * vm[2][0]) - (vm[1][0] * vm[2][2]))) + - (vm[0][2] * ((vm[1][0] * vm[2][1]) - (vm[1][1] * vm[2][0]))); + const float determinant = glm::determinant(glm::mat3(vm)); if (determinant < 0.0f) inverted = true; else @@ -328,7 +271,10 @@ void MeshTransform::Tool::processTransforms( case ScaleTransform: { skewed = true; - scale(vertexMatrix, transform.data); + const auto scaling = glm::vec3(transform.data[0], + transform.data[1], + transform.data[2]); + vertexMatrix = glm::scale(vertexMatrix, scaling); break; } case ShearTransform: @@ -339,7 +285,10 @@ void MeshTransform::Tool::processTransforms( } case SpinTransform: { - spin(vertexMatrix, transform.data[3], transform.data); + const auto normal = glm::vec3(transform.data[0], + transform.data[1], + transform.data[2]); + spin(vertexMatrix, transform.data[3], normal); break; } case IndexTransform: @@ -363,57 +312,36 @@ void MeshTransform::Tool::processTransforms( } -void MeshTransform::Tool::modifyVertex(float v[3]) const +void MeshTransform::Tool::modifyVertex(glm::vec3 &v) const { if (empty) return; - float t[3]; - const float (*vm)[4] = vertexMatrix; - t[0] = (v[0] * vm[0][0]) + (v[1] * vm[0][1]) + (v[2] * vm[0][2]) + vm[0][3]; - t[1] = (v[0] * vm[1][0]) + (v[1] * vm[1][1]) + (v[2] * vm[1][2]) + vm[1][3]; - t[2] = (v[0] * vm[2][0]) + (v[1] * vm[2][1]) + (v[2] * vm[2][2]) + vm[2][3]; - memcpy(v, t, sizeof(float[3])); + v = glm::vec3(glm::vec4(v, 1.0f) * vertexMatrix); } -void MeshTransform::Tool::modifyNormal(float n[3]) const +void MeshTransform::Tool::modifyNormal(glm::vec3 &n) const { if (empty) return; - float t[3]; - const float (*nm)[3] = normalMatrix; - t[0] = (n[0] * nm[0][0]) + (n[1] * nm[0][1]) + (n[2] * nm[0][2]); - t[1] = (n[0] * nm[1][0]) + (n[1] * nm[1][1]) + (n[2] * nm[1][2]); - t[2] = (n[0] * nm[2][0]) + (n[1] * nm[2][1]) + (n[2] * nm[2][2]); + glm::vec3 t; + t = n * normalMatrix; // normalize - const float len = (t[0] * t[0]) + (t[1] * t[1]) + (t[2] * t[2]); - if (len > 0.0f) - { - const float scale = 1.0f / sqrtf(len); - n[0] = t[0] * scale; - n[1] = t[1] * scale; - n[2] = t[2] * scale; - } + if (t.x || t.y || t.z) + n = glm::normalize(t); else - { - n[0] = n[1] = 0.0f; // dunno, going with Z... - n[2] = 1.0f; - } + n = glm::vec3(0.0f, 0.0f, 1.0f); // dunno, going with Z... if (inverted) - { - n[0] = -n[0]; - n[1] = -n[1]; - n[2] = -n[2]; - } + n = -n; return; } -void MeshTransform::Tool::modifyOldStyle(float pos[3], float size[3], +void MeshTransform::Tool::modifyOldStyle(glm::vec3 &pos, glm::vec3 &size, float& angle, bool& flipz) const { if (empty) @@ -428,8 +356,8 @@ void MeshTransform::Tool::modifyOldStyle(float pos[3], float size[3], // transform the object's axis unit vectors const float cos_val = cosf (angle); const float sin_val = sinf (angle); - float x[3], y[3], z[3]; - const float (*vm)[4] = vertexMatrix; + glm::vec3 x, y, z; + const auto &vm = vertexMatrix; // NOTE - the translation (shift) elements are not used x[0] = (+cos_val * vm[0][0]) + (+sin_val * vm[0][1]); x[1] = (+cos_val * vm[1][0]) + (+sin_val * vm[1][1]); @@ -440,9 +368,9 @@ void MeshTransform::Tool::modifyOldStyle(float pos[3], float size[3], z[0] = vm[0][2]; z[1] = vm[1][2]; z[2] = vm[2][2]; - const float xlen = sqrtf ((x[0] * x[0]) + (x[1] * x[1]) + (x[2] * x[2])); - const float ylen = sqrtf ((y[0] * y[0]) + (y[1] * y[1]) + (y[2] * y[2])); - const float zlen = sqrtf ((z[0] * z[0]) + (z[1] * z[1]) + (z[2] * z[2])); + const float xlen = glm::length(x); + const float ylen = glm::length(y); + const float zlen = glm::length(z); size[0] *= xlen; size[1] *= ylen; size[2] *= zlen; @@ -552,10 +480,12 @@ const std::string& MeshTransform::getName() const } -void MeshTransform::addShift(const float shift[3]) +void MeshTransform::addShift(const glm::vec3 &shift) { TransformData transform; - memcpy(transform.data, shift, sizeof(float[3])); + transform.data[0] = shift[0]; + transform.data[1] = shift[1]; + transform.data[2] = shift[2]; transform.data[3] = 0.0f; transform.type = ShiftTransform; transform.index = -1; @@ -564,10 +494,12 @@ void MeshTransform::addShift(const float shift[3]) } -void MeshTransform::addScale(const float scale[3]) +void MeshTransform::addScale(const glm::vec3 &scale) { TransformData transform; - memcpy(transform.data, scale, sizeof(float[3])); + transform.data[0] = scale[0]; + transform.data[1] = scale[1]; + transform.data[2] = scale[2]; transform.data[3] = 0.0f; transform.type = ScaleTransform; transform.index = -1; @@ -588,11 +520,13 @@ void MeshTransform::addShear(const float shear[3]) } -void MeshTransform::addSpin(const float degrees, const float normal[3]) +void MeshTransform::addSpin(const float degrees, const glm::vec3 &normal) { const float radians = (float)(degrees * (M_PI / 180.0)); TransformData transform; - memcpy(transform.data, normal, sizeof(float[3])); + transform.data[0] = normal[0]; + transform.data[1] = normal[1]; + transform.data[2] = normal[2]; transform.data[3] = radians; transform.type = SpinTransform; transform.index = -1; diff --git a/src/game/MsgStrings.cxx b/src/game/MsgStrings.cxx index 3145bb54e4..39711ba9dc 100644 --- a/src/game/MsgStrings.cxx +++ b/src/game/MsgStrings.cxx @@ -21,6 +21,7 @@ #include #include #include +#include // common headers #include "global.h" @@ -423,6 +424,14 @@ static std::string strPlayer (u16 id) } +static std::string strVector (const glm::vec3 &vector) +{ + std::string str = TextUtils::format ("(%8.3f, %8.3f, %8.3f)", + vector[0], vector[1], vector[2]); + return str; +} + + static std::string strVector (const float *vector) { std::string str = TextUtils::format ("(%8.3f, %8.3f, %8.3f)", @@ -661,8 +670,8 @@ static MsgStringList handleMsgGMUpdate (PacketInfo *pi) listPush (list, 1, "target: %s", strPlayer(target).c_str()); listPush (list, 2, "id: %i", shot.id); listPush (list, 2, "team: %s", strTeam(shot.team).c_str()); - listPush (list, 2, "pos: %s", strVector((float*)shot.pos).c_str()); - listPush (list, 2, "vel: %s", strVector((float*)shot.vel).c_str()); + listPush (list, 2, "pos: %s", strVector(shot.pos).c_str()); + listPush (list, 2, "vel: %s", strVector(shot.vel).c_str()); return list; } diff --git a/src/game/Ray.cxx b/src/game/Ray.cxx index 7802503c1b..1c57aecefd 100644 --- a/src/game/Ray.cxx +++ b/src/game/Ray.cxx @@ -10,48 +10,34 @@ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ -#include "common.h" +// Its interface #include "Ray.h" -Ray::Ray(const float* _o, const float* _d) +Ray::Ray(const glm::vec3 &_o, const glm::vec3 &_d) { - o[0] = _o[0]; - o[1] = _o[1]; - o[2] = _o[2]; - d[0] = _d[0]; - d[1] = _d[1]; - d[2] = _d[2]; + o = _o; + d = _d; } Ray::Ray(const Ray& r) { - o[0] = r.o[0]; - o[1] = r.o[1]; - o[2] = r.o[2]; - d[0] = r.d[0]; - d[1] = r.d[1]; - d[2] = r.d[2]; + o = r.o; + d = r.d; } Ray& Ray::operator=(const Ray& r) { if (this != &r) { - o[0] = r.o[0]; - o[1] = r.o[1]; - o[2] = r.o[2]; - d[0] = r.d[0]; - d[1] = r.d[1]; - d[2] = r.d[2]; + o = r.o; + d = r.d; } return *this; } -void Ray::getPoint(float t, float p[3]) const +void Ray::getPoint(float t, glm::vec3 &p) const { - p[0] = o[0] + t * d[0]; - p[1] = o[1] + t * d[1]; - p[2] = o[2] + t * d[2]; + p = o + t * d; } // Local Variables: *** diff --git a/src/geometry/BillboardSceneNode.cxx b/src/geometry/BillboardSceneNode.cxx index 7286fcaf17..4fdf6fd90b 100644 --- a/src/geometry/BillboardSceneNode.cxx +++ b/src/geometry/BillboardSceneNode.cxx @@ -16,11 +16,14 @@ // system headers #include #include +#define GLM_ENABLE_EXPERIMENTAL +#include // common implementation headers #include "BZDBCache.h" #include "TextureManager.h" #include "mathRoutine.h" +#include "OpenGLAPI.h" // local implementation headers #include "ViewFrustum.h" @@ -29,7 +32,7 @@ // FIXME (SceneRenderer.cxx is in src/bzflag) #include "SceneRenderer.h" -BillboardSceneNode::BillboardSceneNode(const GLfloat pos[3]) : +BillboardSceneNode::BillboardSceneNode(const glm::vec3 &pos) : show(false), hasAlpha(false), hasTexture(false), @@ -78,17 +81,12 @@ BillboardSceneNode* BillboardSceneNode::copy() const e->hasTextureAlpha = hasTextureAlpha; e->looping = looping; e->lightSource = lightSource; - e->lightColor[0] = lightColor[0]; - e->lightColor[1] = lightColor[1]; - e->lightColor[2] = lightColor[2]; + e->lightColor = lightColor; e->lightScale = lightScale; e->lightCutoffTime = lightCutoffTime; e->width = width; e->height = height; - e->color[0] = color[0]; - e->color[1] = color[1]; - e->color[2] = color[2]; - e->color[3] = color[3]; + e->color = color; e->angle = angle; e->duration = duration; e->light = light; @@ -177,9 +175,7 @@ void BillboardSceneNode::setLight(bool on) void BillboardSceneNode::setLightColor( GLfloat r, GLfloat g, GLfloat b) { - lightColor[0] = r; - lightColor[1] = g; - lightColor[2] = b; + lightColor = glm::vec3(r, g, b); prepLight(); } @@ -214,9 +210,7 @@ void BillboardSceneNode::prepLight() if (!lightSource) return; const float s = (t <= lightCutoffTime || lightCutoffTime >= duration) ? 1.0f : (1.0f - (t - lightCutoffTime) / (duration - lightCutoffTime)); - light.setColor(lightColor[0] * lightScale * s, - lightColor[1] * lightScale * s, - lightColor[2] * lightScale * s); + light.setColor(lightColor * lightScale * s); } void BillboardSceneNode::setSize(float side) @@ -234,10 +228,7 @@ void BillboardSceneNode::setSize(float _width, float _height) void BillboardSceneNode::setColor( GLfloat r, GLfloat g, GLfloat b, GLfloat a) { - color[0] = r; - color[1] = g; - color[2] = b; - color[3] = a; + color = glm::vec4(r, g, b, a); hasAlpha = (color[3] != 1.0f || hasTextureAlpha); } @@ -269,7 +260,7 @@ setTextureAnimation(int _cu, int _cv) setFrame(); } -void BillboardSceneNode::move(const GLfloat pos[3]) +void BillboardSceneNode::move(const glm::vec3 &pos) { setCenter(pos); light.setPosition(pos); @@ -332,7 +323,7 @@ BillboardSceneNode::BillboardRenderNode::~BillboardRenderNode() // do nothing } -const GLfloat* BillboardSceneNode::BillboardRenderNode::getPosition() const +const glm::vec3 &BillboardSceneNode::BillboardRenderNode::getPosition() const { return sceneNode->getSphere(); } @@ -360,20 +351,16 @@ void BillboardSceneNode::BillboardRenderNode::render() // will move in the direction of the view, which isn't necessarily // the direction to the billboard from the eye. ViewFrustum& frustum = RENDERER.getViewFrustum(); - const GLfloat* eye = frustum.getEye(); - const GLfloat* sphere = sceneNode->getSphere(); - GLfloat dir[3], d; - dir[0] = eye[0] - sphere[0]; - dir[1] = eye[1] - sphere[1]; - dir[2] = eye[2] - sphere[2]; - float dist2 = dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]; - d = sceneNode->width * bzInverseSqrt(dist2); + const auto &eye = frustum.getEye(); + const auto ¢er = getPosition(); + + auto dir = eye - center; + dir *= bzInverseSqrt(glm::length2(dir)); + const auto pos = center + sceneNode->width * dir; glPushMatrix(); { - glTranslatef(sphere[0] + d * dir[0], - sphere[1] + d * dir[1], - sphere[2] + d * dir[2]); + glTranslate(pos); frustum.executeBillboard(); glRotatef(sceneNode->angle, 0.0f, 0.0f, 1.0f); diff --git a/src/geometry/BoltSceneNode.cxx b/src/geometry/BoltSceneNode.cxx index 2b00f4508a..c1489a09df 100644 --- a/src/geometry/BoltSceneNode.cxx +++ b/src/geometry/BoltSceneNode.cxx @@ -21,6 +21,7 @@ #include "StateDatabase.h" #include "BZDBCache.h" #include "TextureManager.h" +#include "OpenGLAPI.h" // local implementation headers #include "ViewFrustum.h" @@ -30,7 +31,8 @@ #include "TimeKeeper.h" -BoltSceneNode::BoltSceneNode(const GLfloat pos[3],const GLfloat vel[3], bool super) : +BoltSceneNode::BoltSceneNode( + const glm::vec3 &pos, const glm::vec3 &vel, bool super) : isSuper(super), invisible(false), drawFlares(false), @@ -58,7 +60,7 @@ BoltSceneNode::BoltSceneNode(const GLfloat pos[3],const GLfloat vel[3], bool sup move(pos, vel); setSize(size); setColor(1.0f, 1.0f, 1.0f); - teamColor = fvec4(1,1,1,1); + teamColor = glm::vec4(1.0f); } BoltSceneNode::~BoltSceneNode() @@ -78,33 +80,24 @@ void BoltSceneNode::setSize(float radius) } void BoltSceneNode::setTextureColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a) { - color[0] = r; - color[1] = g; - color[2] = b; - color[3] = a; - light.setColor(1.5f * r, 1.5f * g, 1.5f * b); + color = glm::vec4(r, g, b, a); + light.setColor(1.5f * glm::vec3(color)); renderNode.setTextureColor(color); } void BoltSceneNode::setColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a) { - color[0] = r; - color[1] = g; - color[2] = b; - color[3] = a; - light.setColor(1.5f * r, 1.5f * g, 1.5f * b); + color = glm::vec4(r, g, b, a); + light.setColor(1.5f * glm::vec3(color)); renderNode.setColor(color); } -void BoltSceneNode::setTeamColor(const GLfloat *c) +void BoltSceneNode::setTeamColor(const glm::vec3 &c) { - teamColor.r = c[0]; - teamColor.g = c[1]; - teamColor.b = c[2]; - teamColor.w = 1.0f; + teamColor = glm::vec4(c, 1.0f); } -void BoltSceneNode::setColor(const GLfloat* rgb) +void BoltSceneNode::setColor(const glm::vec3 &rgb) { setColor(rgb[0], rgb[1], rgb[2]); } @@ -132,20 +125,16 @@ void BoltSceneNode::setTextureAnimation(int cu, int cv) renderNode.setAnimation(cu, cv); } -void BoltSceneNode::move(const GLfloat pos[3], - const GLfloat vel[3]) +void BoltSceneNode::move(const glm::vec3 &pos, const glm::vec3 &vel) { + const auto xy_vel = glm::length(glm::vec2(vel)); setCenter(pos); light.setPosition(pos); - velocity[0] = vel[0]; - velocity[1] = vel[1]; - velocity[2] = vel[2]; - length = sqrtf((vel[0] * vel[0]) + - (vel[1] * vel[1]) + - (vel[2] * vel[2])); + velocity = vel; + length = glm::length(vel); azimuth = (float)(+RAD2DEG * atan2f(vel[1], vel[0])); - elevation = (float)(-RAD2DEG * atan2f(vel[2], sqrtf(vel[0]* vel[0] + vel[1] *vel[1]))); + elevation = (float)(-RAD2DEG * atan2f(vel[2], xy_vel)); } void BoltSceneNode::addLight( @@ -199,9 +188,8 @@ void BoltSceneNode::addRenderNodes( const GLfloat BoltSceneNode::BoltRenderNode::CoreFraction = 0.4f; const GLfloat BoltSceneNode::BoltRenderNode::FlareSize = 1.0f; const GLfloat BoltSceneNode::BoltRenderNode::FlareSpread = 0.08f; -GLfloat BoltSceneNode::BoltRenderNode::core[9][2]; -GLfloat BoltSceneNode::BoltRenderNode::corona[8][2]; -const GLfloat BoltSceneNode::BoltRenderNode::ring[8][2] = +glm::vec2 BoltSceneNode::BoltRenderNode::core[9]; +const glm::vec2 BoltSceneNode::BoltRenderNode::corona[8] = { { 1.0f, 0.0f }, { (float)M_SQRT1_2, (float)M_SQRT1_2 }, @@ -223,21 +211,12 @@ BoltSceneNode::BoltRenderNode::BoltRenderNode( if (!init) { init = true; - core[0][0] = 0.0f; - core[0][1] = 0.0f; + core[0] = glm::vec2(0.0f); for (int i = 0; i < 8; i++) - { - core[i+1][0] = CoreFraction * ring[i][0]; - core[i+1][1] = CoreFraction * ring[i][1]; - corona[i][0] = ring[i][0]; - corona[i][1] = ring[i][1]; - } + core[i+1] = CoreFraction * corona[i]; } - textureColor[0] = 1.0f; - textureColor[1] = 1.0f; - textureColor[2] = 1.0f; - textureColor[3] = 1.0f; + textureColor = glm::vec4(1.0f); setAnimation(1, 1); } @@ -247,7 +226,7 @@ BoltSceneNode::BoltRenderNode::~BoltRenderNode() // do nothing } -const GLfloat* BoltSceneNode::BoltRenderNode::getPosition() const +const glm::vec3 &BoltSceneNode::BoltRenderNode::getPosition() const { return sceneNode->getSphere(); } @@ -266,42 +245,27 @@ void BoltSceneNode::BoltRenderNode::setAnimation( v = index / cu; if (v >= cv) v = 0; } -void BoltSceneNode::BoltRenderNode::setTextureColor(const GLfloat* rgba) +void BoltSceneNode::BoltRenderNode::setTextureColor(const glm::vec4 &rgba) { - textureColor[0] = rgba[0]; - textureColor[1] = rgba[1]; - textureColor[2] = rgba[2]; - textureColor[3] = rgba[3]; + textureColor = rgba; } -void BoltSceneNode::BoltRenderNode::setColor( - const GLfloat* rgba) +void BoltSceneNode::BoltRenderNode::setColor(const glm::vec4 &rgba) { - mainColor[0] = rgba[0]; - mainColor[1] = rgba[1]; - mainColor[2] = rgba[2]; - mainColor[3] = rgba[3]; - - innerColor[0] = mainColor[0] + 0.5f * (1.0f - mainColor[0]); - innerColor[1] = mainColor[1] + 0.5f * (1.0f - mainColor[1]); - innerColor[2] = mainColor[2] + 0.5f * (1.0f - mainColor[2]); - innerColor[3] = rgba[3]; - - outerColor[0] = mainColor[0]; - outerColor[1] = mainColor[1]; - outerColor[2] = mainColor[2]; - outerColor[3] = (rgba[3] == 1.0f )? 0.1f: rgba[3]; - - coronaColor[0] = mainColor[0]; - coronaColor[1] = mainColor[1]; - coronaColor[2] = mainColor[2]; - coronaColor[3] = (rgba[3] == 1.0f )? 0.5f : rgba[3]; + mainColor = rgba; + innerColor = rgba + 0.5f * (1.0f - rgba); + outerColor = rgba; + coronaColor = rgba; + flareColor = rgba; - flareColor[0] = mainColor[0]; - flareColor[1] = mainColor[1]; - flareColor[2] = mainColor[2]; - flareColor[3] = (rgba[3] == 1.0f )? 0.667f : rgba[3]; + innerColor[3] = rgba[3]; + if (rgba.a == 1.0f) + { + outerColor[3] = 0.1f; + coronaColor[3] = 0.5f; + flareColor[3] = 0.667f; + } } void drawFin ( float maxRad, float finRadius, float boosterLen, float finForeDelta, float finCapSize) @@ -358,10 +322,10 @@ void BoltSceneNode::BoltRenderNode::renderGeoGMBolt() glDisable(GL_TEXTURE_2D); //glEnable(GL_LIGHTING); - fvec4 noseColor = sceneNode->teamColor; - fvec4 finColor(noseColor.r*0.5f,noseColor.g*0.5f,noseColor.b*0.5f,1); - fvec4 coneColor(0.125f,0.125f,0.125f,1); - fvec4 bodyColor(1,1,1,1); + auto noseColor = sceneNode->teamColor; + auto finColor = glm::vec4(glm::vec3(noseColor) * 0.5f, 1.0f); + auto coneColor = glm::vec4(0.125f, 0.125f, 0.125f, 1.0f); + auto bodyColor = glm::vec4(1.0f); glPushMatrix(); @@ -378,7 +342,7 @@ void BoltSceneNode::BoltRenderNode::renderGeoGMBolt() addTriangleCount(slices * 2); // body - myColor4fv(bodyColor); + myColor4f(bodyColor.r, bodyColor.g, bodyColor.b, bodyColor.a); glTranslatef(0, 0, -bodyLen); gluCylinder(q,maxRad,maxRad,bodyLen,slices,1); addTriangleCount(slices); @@ -388,13 +352,13 @@ void BoltSceneNode::BoltRenderNode::renderGeoGMBolt() addTriangleCount(slices); // waist - myColor4fv(coneColor); + myColor4f(coneColor.r, coneColor.g, coneColor.b, coneColor.a); glTranslatef(0, 0, -waistLen); gluCylinder(q,waistRad,waistRad,waistLen,slices,1); addTriangleCount(slices); // booster - myColor3fv(bodyColor); + myColor4f(bodyColor.r, bodyColor.g, bodyColor.b, 1.0f); glTranslatef(0, 0, -bevelLen); gluCylinder(q,maxRad,waistRad,bevelLen,slices,1); addTriangleCount(slices); @@ -408,13 +372,13 @@ void BoltSceneNode::BoltRenderNode::renderGeoGMBolt() addTriangleCount(slices); // engine - myColor3fv(coneColor); + myColor4f(coneColor.r, coneColor.g, coneColor.b, 1.0f); glTranslatef(0, 0, -engineLen); gluCylinder(q,engineRad,waistRad,engineLen,slices,1); addTriangleCount(slices); // fins - myColor3fv(finColor); + myColor4f(finColor.r, finColor.g, finColor.b, 1.0f); glTranslatef(0, 0, engineLen + bevelLen); for ( int i = 0; i < 4; i++) @@ -457,46 +421,32 @@ void BoltSceneNode::BoltRenderNode::renderGeoBolt() float coreBleed = 4.5f; float minimumChannelVal = 0.45f; - fvec3 coreColor; - coreColor.r = sceneNode->color[0] * coreBleed; - coreColor.g = sceneNode->color[1] * coreBleed; - coreColor.b = sceneNode->color[2] * coreBleed; - if (coreColor.r < minimumChannelVal) - coreColor.r = minimumChannelVal; - if (coreColor.g < minimumChannelVal) - coreColor.g = minimumChannelVal; - if (coreColor.b < minimumChannelVal) - coreColor.b = minimumChannelVal; - - myColor4fv(fvec4(coreColor, 0.85f * alphaMod)); + const auto c = glm::vec3(sceneNode->color); + + auto coreColor = glm::max(c * coreBleed, minimumChannelVal); + + myColor4f(coreColor.r, coreColor.g, coreColor.b, 0.85f * alphaMod); renderGeoPill(baseRadius,len,16); float radInc = 1.5f * baseRadius - baseRadius; glPushMatrix(); glTranslatef(0, 0, -radInc * 0.5f); - fvec4 c; - c.x = sceneNode->color[0]; - c.y = sceneNode->color[1]; - c.z = sceneNode->color[2]; - c.w = 0.5f; - myColor4fv(c); + myColor4f(c.r, c.g, c.b, 0.5f); renderGeoPill(1.5f * baseRadius, len + radInc, 25); glPopMatrix(); radInc = 2.7f * baseRadius - baseRadius; glPushMatrix(); glTranslatef(0, 0, -radInc*0.5f); - c.w = 0.25f; - myColor4fv(c); + myColor4f(c.r, c.g, c.b, 0.25f); renderGeoPill(2.7f * baseRadius, len + radInc, 32); glPopMatrix(); radInc = 3.8f * baseRadius - baseRadius; glPushMatrix(); glTranslatef(0, 0,-radInc*0.5f); - c.w = 0.125f; - myColor4fv(c); + myColor4f(c.r, c.g, c.b, 0.125f); renderGeoPill(3.8f * baseRadius, len + radInc, 48); glPopMatrix(); @@ -581,11 +531,11 @@ void BoltSceneNode::BoltRenderNode::render() const bool blackFog = RENDERER.isFogActive() && BZDBCache::blend && ((shotLength > 0) || experimental); if (blackFog) - glFogfv(GL_FOG_COLOR, fvec4(0.0f, 0.0f, 0.0f, 0.0f)); + glSetFogColor(glm::vec4(0.0f)); - const float* sphere = sceneNode->getSphere(); + const auto &sphere = getPosition(); glPushMatrix(); - glTranslatef(sphere[0], sphere[1], sphere[2]); + glTranslate(sphere); bool drawBillboardShot = false; if (experimental) @@ -685,8 +635,7 @@ void BoltSceneNode::BoltRenderNode::render() if (texInfo.id >= 0) texInfo.texture->execute(); - fvec3 vel(sceneNode->velocity[0],sceneNode->velocity[1],sceneNode->velocity[2]); - const fvec3 dir = vel * (-1.0f / sceneNode->length); + auto dir = sceneNode->velocity / sceneNode->length; const float invLenPlusOne = 1.0f / (float)(shotLength + 1); const float shiftScale = 90.0f / (150.0f + (float)shotLength); @@ -695,10 +644,7 @@ void BoltSceneNode::BoltRenderNode::render() const float sizeStep = Size * invLenPlusOne; const float alphaStep = alpha * invLenPlusOne; - fvec3 pos; - pos.x = sphere[0]; - pos.y = sphere[1]; - pos.z = sphere[2]; + auto pos = sphere; int uvCell = rand() % 16; @@ -708,7 +654,7 @@ void BoltSceneNode::BoltRenderNode::render() const float s = Size * (0.65f + (1.0f * (float)bzfrand())); const float shift = s * shiftScale; - pos += (shift * dir); + pos -= (shift * dir); if (pos.z < 0.0f) continue; @@ -857,7 +803,7 @@ void BoltSceneNode::BoltRenderNode::render() glPopMatrix(); if (blackFog) - glFogfv(GL_FOG_COLOR, RENDERER.getFogColor()); + glSetFogColor(RENDERER.getFogColor()); if (RENDERER.isLastFrame()) { diff --git a/src/geometry/EighthDBaseSceneNode.cxx b/src/geometry/EighthDBaseSceneNode.cxx index bbb88811e7..85f65e1b18 100644 --- a/src/geometry/EighthDBaseSceneNode.cxx +++ b/src/geometry/EighthDBaseSceneNode.cxx @@ -10,12 +10,15 @@ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ -// inteface header +// interface header #include "EighthDBaseSceneNode.h" // system headers #include #include +#include +#define GLM_ENABLE_EXPERIMENTAL +#include // common implementation header #include "StateDatabase.h" @@ -25,8 +28,10 @@ const int BasePolygons = 60; -EighthDBaseSceneNode::EighthDBaseSceneNode(const float pos[3], - const float size[3], float rotation) : +EighthDBaseSceneNode::EighthDBaseSceneNode( + const glm::vec3 &pos, + const glm::vec3 &size, + float rotation) : EighthDimSceneNode(BasePolygons), renderNode(this, pos, size, rotation) { @@ -35,40 +40,33 @@ EighthDBaseSceneNode::EighthDBaseSceneNode(const float pos[3], const float s = sinf(rotation); // compute polygons - const GLfloat polySize = size[0] / powf(float(BasePolygons), 0.3333f); + const auto polySize = size[0] / powf(float(BasePolygons), 0.3333f) / 2.0f; + const auto hig = size - polySize; + const auto low = glm::vec3(glm::vec2(hig), 0.0f); + const auto ave = glm::vec3(polySize); for (int i = 0; i < BasePolygons; i++) { - GLfloat base[3], vertex[3][3]; - base[0] = (size[0] - 0.5f * polySize) * (2.0f * (float) bzfrand() - 1.0f); - base[1] = (size[1] - 0.5f * polySize) * (2.0f * (float) bzfrand() - 1.0f); - base[2] = (size[2] - 0.5f * polySize) * (float) bzfrand(); + glm::vec3 vertex[3]; + const auto base = glm::linearRand(-low, hig); for (int j = 0; j < 3; j++) { // pick point around origin - GLfloat p[3]; - p[0] = base[0] + polySize * ((float) bzfrand() - 0.5f); - p[1] = base[1] + polySize * ((float) bzfrand() - 0.5f); - p[2] = base[2] + polySize * ((float) bzfrand() - 0.5f); + auto p = base + glm::linearRand(-ave, +ave); // make sure it's inside the base - if (p[0] < -size[0]) p[0] = -size[0]; - else if (p[0] > size[0]) p[0] = size[0]; - if (p[1] < -size[1]) p[1] = -size[1]; - else if (p[1] > size[1]) p[1] = size[1]; - if (p[2] < -size[2]) p[2] = -size[2]; - else if (p[2] > size[2]) p[2] = size[2]; + p = glm::clamp(p, -size, +size); // rotate it - vertex[j][0] = pos[0] + c * p[0] - s * p[1]; - vertex[j][1] = pos[1] + s * p[0] + c * p[1]; - vertex[j][2] = pos[2] + p[2]; + vertex[j] = pos + glm::vec3(c * p[0] - s * p[1], + s * p[0] + c * p[1], + p[2]); } setPolygon(i, vertex); } // set sphere setCenter(pos); - setRadius(0.25f * (size[0] * size[0] + size[1] * size[1] + size[2] * size[2])); + setRadius(0.25f * glm::length2(size)); } EighthDBaseSceneNode::~EighthDBaseSceneNode() @@ -102,8 +100,9 @@ void EighthDBaseSceneNode::addRenderNodes(SceneRenderer& renderer) EighthDBaseSceneNode::EighthDBaseRenderNode::EighthDBaseRenderNode( const EighthDBaseSceneNode * _sceneNode, - const float pos[3], - const float size[3], float rotation) : + const glm::vec3 &pos, + const glm::vec3 &size, + float rotation) : sceneNode(_sceneNode) { // get rotation stuff @@ -128,7 +127,7 @@ EighthDBaseSceneNode::EighthDBaseRenderNode::~EighthDBaseRenderNode() // do nothing } -const GLfloat* EighthDBaseSceneNode::EighthDBaseRenderNode::getPosition() const +const glm::vec3 &EighthDBaseSceneNode::EighthDBaseRenderNode::getPosition() const { return sceneNode->getSphere(); } diff --git a/src/geometry/EighthDBoxSceneNode.cxx b/src/geometry/EighthDBoxSceneNode.cxx index d2669894e9..a31da7aa3e 100644 --- a/src/geometry/EighthDBoxSceneNode.cxx +++ b/src/geometry/EighthDBoxSceneNode.cxx @@ -16,6 +16,9 @@ // system headers #include #include +#include +#define GLM_ENABLE_EXPERIMENTAL +#include // common implementation header #include "StateDatabase.h" @@ -25,8 +28,10 @@ const int BoxPolygons = 60; -EighthDBoxSceneNode::EighthDBoxSceneNode(const float pos[3], - const float size[3], float rotation) : +EighthDBoxSceneNode::EighthDBoxSceneNode( + const glm::vec3 &pos, + const glm::vec3 &size, + float rotation) : EighthDimSceneNode(BoxPolygons), renderNode(this, pos, size, rotation) { @@ -35,33 +40,27 @@ EighthDBoxSceneNode::EighthDBoxSceneNode(const float pos[3], const float s = sinf(rotation); // compute polygons - const GLfloat polySize = size[0] / powf(float(BoxPolygons), 0.3333f); + const auto polySize = size[0] / powf(float(BoxPolygons), 0.3333f) / 2.0f; + const auto hig = size - polySize; + const auto low = glm::vec3(glm::vec2(hig), 0.0f); + const auto ave = glm::vec3(polySize); + const auto lCl = glm::vec3(-size.x, -size.y, 0.0f); for (int i = 0; i < BoxPolygons; i++) { - GLfloat base[3], vertex[3][3]; - base[0] = (size[0] - 0.5f * polySize) * (2.0f * (float)bzfrand() - 1.0f); - base[1] = (size[1] - 0.5f * polySize) * (2.0f * (float)bzfrand() - 1.0f); - base[2] = (size[2] - 0.5f * polySize) * (float)bzfrand(); + glm::vec3 vertex[3]; + const auto base = glm::linearRand(-low, hig); for (int j = 0; j < 3; j++) { // pick point around origin - GLfloat p[3]; - p[0] = base[0] + polySize * ((float)bzfrand() - 0.5f); - p[1] = base[1] + polySize * ((float)bzfrand() - 0.5f); - p[2] = base[2] + polySize * ((float)bzfrand() - 0.5f); + auto p = base + glm::linearRand(-ave, +ave); // make sure it's inside the box - if (p[0] < -size[0]) p[0] = -size[0]; - else if (p[0] > size[0]) p[0] = size[0]; - if (p[1] < -size[1]) p[1] = -size[1]; - else if (p[1] > size[1]) p[1] = size[1]; - if (p[2] < 0.0f) p[2] = 0.0f; - else if (p[2] > size[2]) p[2] = size[2]; + p = glm::clamp(p, lCl, size); // rotate it - vertex[j][0] = pos[0] + c * p[0] - s * p[1]; - vertex[j][1] = pos[1] + s * p[0] + c * p[1]; - vertex[j][2] = pos[2] + p[2]; + vertex[j] = pos + glm::vec3(c * p[0] - s * p[1], + s * p[0] + c * p[1], + p[2]); } setPolygon(i, vertex); @@ -69,7 +68,7 @@ EighthDBoxSceneNode::EighthDBoxSceneNode(const float pos[3], // set sphere setCenter(pos); - setRadius(0.25f * (size[0]*size[0] + size[1]*size[1] + size[2]*size[2])); + setRadius(0.25f * glm::length2(size)); } EighthDBoxSceneNode::~EighthDBoxSceneNode() @@ -108,8 +107,9 @@ void EighthDBoxSceneNode::addRenderNodes( EighthDBoxSceneNode::EighthDBoxRenderNode::EighthDBoxRenderNode( const EighthDBoxSceneNode* _sceneNode, - const float pos[3], - const float size[3], float rotation) : + const glm::vec3 &pos, + const glm::vec3 &size, + float rotation) : sceneNode(_sceneNode) { // get rotation stuff @@ -134,7 +134,7 @@ EighthDBoxSceneNode::EighthDBoxRenderNode::~EighthDBoxRenderNode() // do nothing } -const GLfloat* EighthDBoxSceneNode::EighthDBoxRenderNode::getPosition() const +const glm::vec3 &EighthDBoxSceneNode::EighthDBoxRenderNode::getPosition() const { return sceneNode->getSphere(); } diff --git a/src/geometry/EighthDPyrSceneNode.cxx b/src/geometry/EighthDPyrSceneNode.cxx index f860faeea5..dc5852e665 100644 --- a/src/geometry/EighthDPyrSceneNode.cxx +++ b/src/geometry/EighthDPyrSceneNode.cxx @@ -16,6 +16,9 @@ // system headers #include #include +#define GLM_ENABLE_EXPERIMENTAL +#include +#include // common implementation header #include "StateDatabase.h" @@ -25,8 +28,10 @@ const int PyrPolygons = 20; -EighthDPyrSceneNode::EighthDPyrSceneNode(const float pos[3], - const float size[3], float rotation) : +EighthDPyrSceneNode::EighthDPyrSceneNode( + const glm::vec3 &pos, + const glm::vec3 &size, + float rotation) : EighthDimSceneNode(PyrPolygons), renderNode(this, pos, size, rotation) { @@ -35,35 +40,35 @@ EighthDPyrSceneNode::EighthDPyrSceneNode(const float pos[3], const float s = sinf(rotation); // compute polygons - const GLfloat polySize = size[0] / powf(float(PyrPolygons), 0.3333f); + const auto polySize = size[0] / powf(float(PyrPolygons), 0.3333f) / 2.0f; const GLfloat slope = size[2] / size[0]; + const auto low = glm::vec3(size.x - polySize, + size.y - polySize, + 0.0f); + const auto high = size - glm::vec3(polySize, + polySize, + slope * hypotf(low.x, low.y)); + const auto ave = glm::vec3(polySize); + for (int i = 0; i < PyrPolygons; i++) { - GLfloat base[3], vertex[3][3]; - base[0] = (size[0] - 0.5f * polySize) * (2.0f * (float)bzfrand() - 1.0f); - base[1] = (size[1] - 0.5f * polySize) * (2.0f * (float)bzfrand() - 1.0f); - base[2] = (size[2] - slope * hypotf(base[0], base[1])) * (float)bzfrand(); + glm::vec3 vertex[3]; + const auto base = glm::linearRand(-low, high); for (int j = 0; j < 3; j++) { // pick point around origin - GLfloat p[3]; - p[0] = base[0] + polySize * ((float)bzfrand() - 0.5f); - p[1] = base[1] + polySize * ((float)bzfrand() - 0.5f); - p[2] = base[2] + polySize * ((float)bzfrand() - 0.5f); + auto p = base + glm::linearRand(-ave, +ave); // make sure it's inside the box - if (p[0] < -size[0]) p[0] = -size[0]; - else if (p[0] > size[0]) p[0] = size[0]; - if (p[1] < -size[1]) p[1] = -size[1]; - else if (p[1] > size[1]) p[1] = size[1]; GLfloat height = size[2] - slope * hypotf(p[0], p[1]); - if (p[2] < 0.0f) p[2] = 0.0f; - else if (p[2] > height) p[2] = height; + p = glm::clamp(p, + glm::vec3(-size.x, -size.y, 0.0f), + glm::vec3( size.x, size.y, height)); // rotate it - vertex[j][0] = pos[0] + c * p[0] - s * p[1]; - vertex[j][1] = pos[1] + s * p[0] + c * p[1]; - vertex[j][2] = pos[2] + p[2]; + vertex[j] = pos + glm::vec3(c * p[0] - s * p[1], + s * p[0] + c * p[1], + p[2]); } setPolygon(i, vertex); @@ -71,7 +76,7 @@ EighthDPyrSceneNode::EighthDPyrSceneNode(const float pos[3], // set sphere setCenter(pos); - setRadius(0.25f * (size[0]*size[0] + size[1]*size[1] + size[2]*size[2])); + setRadius(0.25f * glm::length2(size)); } EighthDPyrSceneNode::~EighthDPyrSceneNode() @@ -110,8 +115,9 @@ void EighthDPyrSceneNode::addRenderNodes( EighthDPyrSceneNode::EighthDPyrRenderNode::EighthDPyrRenderNode( const EighthDPyrSceneNode* _sceneNode, - const float pos[3], - const float size[3], float rotation) : + const glm::vec3 &pos, + const glm::vec3 &size, + float rotation) : sceneNode(_sceneNode) { // get rotation stuff @@ -138,7 +144,7 @@ EighthDPyrSceneNode::EighthDPyrRenderNode::~EighthDPyrRenderNode() // do nothing } -const GLfloat* EighthDPyrSceneNode::EighthDPyrRenderNode::getPosition() const +const glm::vec3 &EighthDPyrSceneNode::EighthDPyrRenderNode::getPosition() const { return sceneNode->getSphere(); } diff --git a/src/geometry/EighthDimSceneNode.cxx b/src/geometry/EighthDimSceneNode.cxx index dcf3becc49..f58da3d884 100644 --- a/src/geometry/EighthDimSceneNode.cxx +++ b/src/geometry/EighthDimSceneNode.cxx @@ -17,6 +17,7 @@ #include #include #include +#include // common implementation header #include "StateDatabase.h" @@ -59,7 +60,7 @@ void EighthDimSceneNode::addRenderNodes( } void EighthDimSceneNode::setPolygon(int index, - const GLfloat vertex[3][3]) + const glm::vec3 vertex[3]) { renderNode.setPolygon(index, vertex); } @@ -74,17 +75,14 @@ EighthDimSceneNode::EighthDimRenderNode::EighthDimRenderNode( sceneNode(_sceneNode), numPolygons(numPolys) { - color = (GLfloat(*)[4])new GLfloat[4 * numPolygons]; - poly = (GLfloat(*)[3][3])new GLfloat[9 * numPolygons]; + color = new glm::vec4[numPolygons]; + poly = new glm::vec3[numPolygons][3]; // make random colors + const auto low = glm::vec4(0.2f); + const auto hig = glm::vec4(1.0f, 1.0f, 1.0f, 0.8f); for (int i = 0; i < numPolygons; i++) - { - color[i][0] = 0.2f + 0.8f * (float)bzfrand(); - color[i][1] = 0.2f + 0.8f * (float)bzfrand(); - color[i][2] = 0.2f + 0.8f * (float)bzfrand(); - color[i][3] = 0.2f + 0.6f * (float)bzfrand(); - } + color[i] = glm::linearRand(low, hig); } EighthDimSceneNode::EighthDimRenderNode::~EighthDimRenderNode() @@ -93,7 +91,7 @@ EighthDimSceneNode::EighthDimRenderNode::~EighthDimRenderNode() delete[] poly; } -const GLfloat* EighthDimSceneNode::EighthDimRenderNode::getPosition() const +const glm::vec3 &EighthDimSceneNode::EighthDimRenderNode::getPosition() const { return sceneNode->getSphere(); } @@ -112,10 +110,13 @@ void EighthDimSceneNode::EighthDimRenderNode::render() glEnd(); } -void EighthDimSceneNode::EighthDimRenderNode::setPolygon( - int index, const GLfloat vertex[3][3]) +void EighthDimSceneNode::EighthDimRenderNode::setPolygon( + int index, const glm::vec3 vertex[3]) { - ::memcpy(poly[index], vertex, sizeof(GLfloat[3][3])); + auto &dest = poly[index]; + dest[0] = vertex[0]; + dest[1] = vertex[1]; + dest[2] = vertex[2]; } // Local Variables: *** diff --git a/src/geometry/EighthDimShellNode.cxx b/src/geometry/EighthDimShellNode.cxx index 0f5eb1ebdc..fb148e9b06 100644 --- a/src/geometry/EighthDimShellNode.cxx +++ b/src/geometry/EighthDimShellNode.cxx @@ -123,7 +123,7 @@ EighthDimShellNode::ShellRenderNode::~ShellRenderNode() return; } -const GLfloat* EighthDimShellNode::ShellRenderNode::getPosition() const +const glm::vec3 &EighthDimShellNode::ShellRenderNode::getPosition() const { return renderNode->getPosition(); } diff --git a/src/geometry/FlagSceneNode.cxx b/src/geometry/FlagSceneNode.cxx index ece04a0143..d8b09a93eb 100644 --- a/src/geometry/FlagSceneNode.cxx +++ b/src/geometry/FlagSceneNode.cxx @@ -22,6 +22,7 @@ #include "OpenGLMaterial.h" #include "StateDatabase.h" #include "BZDBCache.h" +#include "OpenGLAPI.h" // local implementation headers #include "ViewFrustum.h" @@ -77,16 +78,16 @@ class WaveGeometry float ripple2; GLuint glList; - GLfloat verts[maxChunks * 2][3]; - GLfloat txcds[maxChunks * 2][2]; + glm::vec3 verts[maxChunks * 2]; + glm::vec2 txcds[maxChunks * 2]; }; inline void WaveGeometry::executeNoList() const { glDisableClientState(GL_NORMAL_ARRAY); - glVertexPointer(3, GL_FLOAT, 0, verts); - glTexCoordPointer(2, GL_FLOAT, 0, txcds); + glVertexPointer(verts); + glTexCoordPointer(txcds); glDrawArrays(GL_TRIANGLE_STRIP, 0, (flagChunks + 1) * 2); glEnableClientState(GL_NORMAL_ARRAY); return; @@ -205,7 +206,7 @@ WaveGeometry allWaves[waveLists]; // FlagSceneNode // -FlagSceneNode::FlagSceneNode(const GLfloat pos[3]) : +FlagSceneNode::FlagSceneNode(const glm::vec3 &pos) : billboard(true), angle(0.0f), tilt(0.0f), @@ -237,7 +238,7 @@ void FlagSceneNode::freeFlag() allWaves[i].freeFlag(); } -void FlagSceneNode::move(const GLfloat pos[3]) +void FlagSceneNode::move(const glm::vec3 &pos) { setCenter(pos); } @@ -296,19 +297,13 @@ void FlagSceneNode::setBillboard(bool _billboard) void FlagSceneNode::setColor( GLfloat r, GLfloat g, GLfloat b, GLfloat a) { - color[0] = r; - color[1] = g; - color[2] = b; - color[3] = a; + color = glm::vec4(r, g, b, a); transparent = (color[3] != 1.0f); } -void FlagSceneNode::setColor(const GLfloat* rgba) +void FlagSceneNode::setColor(const glm::vec4 &rgba) { - color[0] = rgba[0]; - color[1] = rgba[1]; - color[2] = rgba[2]; - color[3] = rgba[3]; + color = rgba; transparent = (color[3] != 1.0f); } @@ -378,14 +373,15 @@ void FlagSceneNode::addShadowNodes(SceneRenderer& renderer) } -bool FlagSceneNode::cullShadow(int planeCount, const float (*planes)[4]) const +bool FlagSceneNode::cullShadow(int planeCount, const glm::vec4 planes[]) const { - const float* s = getSphere(); + const auto s = glm::vec4(getSphere(), 1.0f); + const float r = getRadius2(); for (int i = 0; i < planeCount; i++) { - const float* p = planes[i]; - const float d = (p[0] * s[0]) + (p[1] * s[1]) + (p[2] * s[2]) + p[3]; - if ((d < 0.0f) && ((d * d) > s[3])) + const auto &p = planes[i]; + const float d = glm::dot(p, s); + if ((d < 0.0f) && (d * d > r)) return true; } return false; @@ -422,7 +418,7 @@ void FlagSceneNode::FlagRenderNode::render() const bool is_billboard = sceneNode->billboard; const bool is_transparent = sceneNode->transparent; - const GLfloat* sphere = sceneNode->getSphere(); + const auto &sphere = getPosition(); const float topHeight = base + Height; myColor4fv(sceneNode->color); @@ -432,7 +428,7 @@ void FlagSceneNode::FlagRenderNode::render() glPushMatrix(); { - glTranslatef(sphere[0], sphere[1], sphere[2]); + glTranslate(sphere); if (!is_billboard || realFlag) glRotatef(sceneNode->angle + 180.0f, 0.0f, 0.0f, 1.0f); @@ -542,7 +538,7 @@ void FlagSceneNode::FlagRenderNode::render() myStipple(0.5f); } -const GLfloat* FlagSceneNode::FlagRenderNode::getPosition() const +const glm::vec3 &FlagSceneNode::FlagRenderNode::getPosition() const { return sceneNode->getSphere(); } diff --git a/src/geometry/FlagWarpSceneNode.cxx b/src/geometry/FlagWarpSceneNode.cxx index a36c2cf721..3ee22774da 100644 --- a/src/geometry/FlagWarpSceneNode.cxx +++ b/src/geometry/FlagWarpSceneNode.cxx @@ -16,10 +16,14 @@ // system headers #include #include +#include +#define GLM_ENABLE_EXPERIMENTAL +#include // common implementation headers #include "StateDatabase.h" #include "BZDBCache.h" +#include "OpenGLAPI.h" // local implementation headers #include "ViewFrustum.h" @@ -29,7 +33,7 @@ const float FlagWarpSize = 7.5; // meters const GLfloat FlagWarpAlpha = 0.5f; -const GLfloat FlagWarpSceneNode::color[7][3] = +const glm::vec3 FlagWarpSceneNode::color[7] = { { 0.25, 1.0, 0.25 }, { 0.25, 0.25, 1.0 }, @@ -40,7 +44,7 @@ const GLfloat FlagWarpSceneNode::color[7][3] = { 1.0, 1.0, 1.0 } }; -FlagWarpSceneNode::FlagWarpSceneNode(const GLfloat pos[3]) : +FlagWarpSceneNode::FlagWarpSceneNode(const glm::vec3 &pos) : renderNode(this) { move(pos); @@ -58,20 +62,19 @@ void FlagWarpSceneNode::setSizeFraction(GLfloat _size) size = _size; } -void FlagWarpSceneNode::move(const GLfloat pos[3]) +void FlagWarpSceneNode::move(const glm::vec3 &pos) { setCenter(pos); } -GLfloat FlagWarpSceneNode::getDistance(const GLfloat* eye) const +GLfloat FlagWarpSceneNode::getDistance(const glm::vec3 &eye) const { // shift position of warp down a little because a flag and it's warp // are at the same position but we want the warp to appear below the // flag. - const GLfloat* mySphere = getSphere(); - return (eye[0] - mySphere[0]) * (eye[0] - mySphere[0]) + - (eye[1] - mySphere[1]) * (eye[1] - mySphere[1]) + - (eye[2] - mySphere[2] + 0.2f) * (eye[2] - mySphere[2] + 0.2f); + auto mySphere = getSphere(); + mySphere.z -= 0.2f; + return glm::distance2(eye, mySphere); } void FlagWarpSceneNode::notifyStyleChange() @@ -100,7 +103,7 @@ void FlagWarpSceneNode::addRenderNodes( // FlagWarpSceneNode::FlagWarpRenderNode // -float FlagWarpSceneNode::FlagWarpRenderNode::ring[12][2]; +glm::vec3 FlagWarpSceneNode::FlagWarpRenderNode::ring[12]; FlagWarpSceneNode::FlagWarpRenderNode::FlagWarpRenderNode( const FlagWarpSceneNode* _sceneNode) : @@ -114,6 +117,7 @@ FlagWarpSceneNode::FlagWarpRenderNode::FlagWarpRenderNode( { ring[i][0] = cosf((float)(2.0 * M_PI * double(i) / 12.0)); ring[i][1] = sinf((float)(2.0 * M_PI * double(i) / 12.0)); + ring[i][2] = 0.0f; } } } @@ -123,7 +127,7 @@ FlagWarpSceneNode::FlagWarpRenderNode::~FlagWarpRenderNode() // do nothing } -const GLfloat* FlagWarpSceneNode::FlagWarpRenderNode::getPosition() const +const glm::vec3 &FlagWarpSceneNode::FlagWarpRenderNode::getPosition() const { return sceneNode->getSphere(); } @@ -131,17 +135,13 @@ const GLfloat* FlagWarpSceneNode::FlagWarpRenderNode::getPosition() const void FlagWarpSceneNode::FlagWarpRenderNode::render() { // make a perturbed ring - GLfloat geom[12][2]; + glm::vec3 geom[12]; for (int i = 0; i < 12; i++) - { - const GLfloat r = FlagWarpSize * (0.9f + 0.2f * (float)bzfrand()); - geom[i][0] = r * ring[i][0]; - geom[i][1] = r * ring[i][1]; - } + geom[i] = FlagWarpSize * glm::linearRand(0.9f, 1.1f) * ring[i]; - const GLfloat* sphere = sceneNode->getSphere(); + const auto &sphere = getPosition(); glPushMatrix(); - glTranslatef(sphere[0], sphere[1], sphere[2]); + glTranslate(sphere); if (sphere[2] > RENDERER.getViewFrustum().getEye()[2]) { @@ -151,20 +151,20 @@ void FlagWarpSceneNode::FlagWarpRenderNode::render() if (s < 0.0f) break; myColor4f(color[i][0], color[i][1], color[i][2], FlagWarpAlpha); glBegin(GL_TRIANGLE_FAN); - glVertex2f(0.0f, 0.0f); - glVertex2f(s * geom[0][0], s * geom[0][1]); - glVertex2f(s * geom[11][0], s * geom[11][1]); - glVertex2f(s * geom[10][0], s * geom[10][1]); - glVertex2f(s * geom[9][0], s * geom[9][1]); - glVertex2f(s * geom[8][0], s * geom[8][1]); - glVertex2f(s * geom[7][0], s * geom[7][1]); - glVertex2f(s * geom[6][0], s * geom[6][1]); - glVertex2f(s * geom[5][0], s * geom[5][1]); - glVertex2f(s * geom[4][0], s * geom[4][1]); - glVertex2f(s * geom[3][0], s * geom[3][1]); - glVertex2f(s * geom[2][0], s * geom[2][1]); - glVertex2f(s * geom[1][0], s * geom[1][1]); - glVertex2f(s * geom[0][0], s * geom[0][1]); + glVertex(glm::vec3(0.0f)); + glVertex(s * geom[0]); + glVertex(s * geom[11]); + glVertex(s * geom[10]); + glVertex(s * geom[9]); + glVertex(s * geom[8]); + glVertex(s * geom[7]); + glVertex(s * geom[6]); + glVertex(s * geom[5]); + glVertex(s * geom[4]); + glVertex(s * geom[3]); + glVertex(s * geom[2]); + glVertex(s * geom[1]); + glVertex(s * geom[0]); glEnd(); // 14 verts -> 12 tris addTriangleCount(12); glTranslatef(0.0f, 0.0f, -0.01f); @@ -178,20 +178,20 @@ void FlagWarpSceneNode::FlagWarpRenderNode::render() if (s < 0.0f) break; myColor4f(color[i][0], color[i][1], color[i][2], FlagWarpAlpha); glBegin(GL_TRIANGLE_FAN); - glVertex2f(0.0f, 0.0f); - glVertex2f(s * geom[0][0], s * geom[0][1]); - glVertex2f(s * geom[1][0], s * geom[1][1]); - glVertex2f(s * geom[2][0], s * geom[2][1]); - glVertex2f(s * geom[3][0], s * geom[3][1]); - glVertex2f(s * geom[4][0], s * geom[4][1]); - glVertex2f(s * geom[5][0], s * geom[5][1]); - glVertex2f(s * geom[6][0], s * geom[6][1]); - glVertex2f(s * geom[7][0], s * geom[7][1]); - glVertex2f(s * geom[8][0], s * geom[8][1]); - glVertex2f(s * geom[9][0], s * geom[9][1]); - glVertex2f(s * geom[10][0], s * geom[10][1]); - glVertex2f(s * geom[11][0], s * geom[11][1]); - glVertex2f(s * geom[0][0], s * geom[0][1]); + glVertex(glm::vec3(0.0f)); + glVertex(s * geom[0]); + glVertex(s * geom[1]); + glVertex(s * geom[2]); + glVertex(s * geom[3]); + glVertex(s * geom[4]); + glVertex(s * geom[5]); + glVertex(s * geom[6]); + glVertex(s * geom[7]); + glVertex(s * geom[8]); + glVertex(s * geom[9]); + glVertex(s * geom[10]); + glVertex(s * geom[11]); + glVertex(s * geom[0]); glEnd(); // 14 verts -> 12 tris addTriangleCount(12); glTranslatef(0.0f, 0.0f, 0.01f); diff --git a/src/geometry/LaserSceneNode.cxx b/src/geometry/LaserSceneNode.cxx index 2a325e5745..b132acd6a7 100644 --- a/src/geometry/LaserSceneNode.cxx +++ b/src/geometry/LaserSceneNode.cxx @@ -10,9 +10,6 @@ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ -// bzflag common header -#include "common.h" - // interface header #include "LaserSceneNode.h" @@ -22,22 +19,22 @@ // common implementation headers #include "StateDatabase.h" #include "BZDBCache.h" +#include "OpenGLAPI.h" // FIXME (SceneRenderer.cxx is in src/bzflag) #include "SceneRenderer.h" -#include "vectors.h" - const GLfloat LaserRadius = 0.1f; -LaserSceneNode::LaserSceneNode(const GLfloat pos[3], const GLfloat forward[3]) : +LaserSceneNode::LaserSceneNode(const glm::vec3 &pos, const glm::vec3 &forward) : texturing(false), renderNode(this) { // prepare rendering info + const float xy_dist = hypotf(forward.x, forward.y); azimuth = (float)(180.0 / M_PI*atan2f(forward[1], forward[0])); - elevation = (float)(-180.0 / M_PI*atan2f(forward[2], hypotf(forward[0],forward[1]))); - length = hypotf(forward[0], hypotf(forward[1], forward[2])); + elevation = (float)(-180.0 / M_PI * atan2f(forward.z, xy_dist)); + length = hypotf(xy_dist, forward.z); // setup sphere setCenter(pos); @@ -54,13 +51,13 @@ LaserSceneNode::LaserSceneNode(const GLfloat pos[3], const GLfloat forward[3]) : void LaserSceneNode::setColor(float r, float g, float b) { - color = fvec4(r, g, b, 1.0f); + color = glm::vec4(r, g, b, 1.0f); } void LaserSceneNode::setCenterColor(float r, float g, float b) { - centerColor = fvec4(r, g, b, 1.0f); + centerColor = glm::vec4(r, g, b, 1.0f); } LaserSceneNode::~LaserSceneNode() @@ -111,7 +108,7 @@ void LaserSceneNode::addRenderNodes( // LaserSceneNode::LaserRenderNode // -GLfloat LaserSceneNode::LaserRenderNode::geom[6][2]; +glm::vec2 LaserSceneNode::LaserRenderNode::geom[6]; LaserSceneNode::LaserRenderNode::LaserRenderNode( const LaserSceneNode* _sceneNode) : @@ -124,8 +121,8 @@ LaserSceneNode::LaserRenderNode::LaserRenderNode( init = true; for (int i = 0; i < 6; i++) { - geom[i][0] = -LaserRadius * cosf((float)(2.0 * M_PI * double(i) / 6.0)); - geom[i][1] = LaserRadius * sinf((float)(2.0 * M_PI * double(i) / 6.0)); + const float angle = 2.0 * M_PI * double(i) / 6.0; + geom[i] = LaserRadius * glm::vec2(-cosf(angle), sinf(angle)); } } } @@ -135,7 +132,7 @@ LaserSceneNode::LaserRenderNode::~LaserRenderNode() // do nothing } -const GLfloat* LaserSceneNode::LaserRenderNode::getPosition() const +const glm::vec3 &LaserSceneNode::LaserRenderNode::getPosition() const { return sceneNode->getSphere(); } @@ -144,7 +141,7 @@ void LaserSceneNode::LaserRenderNode::render() { const bool blackFog = BZDBCache::blend && RENDERER.isFogActive(); if (blackFog) - glFogfv(GL_FOG_COLOR, fvec4(0.0f, 0.0f, 0.0f, 0.0f)); + glSetFogColor(glm::vec4(0.0f)); if (RENDERER.useQuality() >= 3) renderGeoLaser(); @@ -152,15 +149,15 @@ void LaserSceneNode::LaserRenderNode::render() renderFlatLaser(); if (blackFog) - glFogfv(GL_FOG_COLOR, RENDERER.getFogColor()); + glSetFogColor(RENDERER.getFogColor()); } void LaserSceneNode::LaserRenderNode::renderGeoLaser() { const float len = sceneNode->length; - const GLfloat* sphere = sceneNode->getSphere(); + const auto &sphere = getPosition(); glPushMatrix(); - glTranslatef(sphere[0], sphere[1], sphere[2]); + glTranslate(sphere); glRotatef(sceneNode->azimuth, 0.0f, 0.0f, 1.0f); glRotatef(sceneNode->elevation, 0.0f, 1.0f, 0.0f); glRotatef(90, 0.0f, 1.0f, 0.0f); @@ -169,28 +166,23 @@ void LaserSceneNode::LaserRenderNode::renderGeoLaser() GLUquadric *q = gluNewQuadric(); - fvec4 coreColor = sceneNode->centerColor; - coreColor.a = 0.85f; - fvec4 mainColor = sceneNode->color; - mainColor.a = 0.125f; + auto coreColor = sceneNode->centerColor; + auto mainColor = sceneNode->color; - myColor4fv(coreColor); + myColor4f(coreColor.r, coreColor.g, coreColor.b, 0.85f); gluCylinder(q, 0.0625f, 0.0625f, len, 10, 1); addTriangleCount(20); - myColor4fv(mainColor); + myColor4f(mainColor.r, mainColor.g, mainColor.b, 0.125f); gluCylinder(q, 0.1f, 0.1f, len, 16, 1); addTriangleCount(32); - myColor4fv(mainColor); gluCylinder(q, 0.2f, 0.2f, len, 24, 1); addTriangleCount(48); - myColor4fv(mainColor); gluCylinder(q, 0.4f, 0.4f, len, 32, 1); addTriangleCount(64); - myColor4fv(mainColor); if (sceneNode->first) { gluSphere(q, 0.5f, 32, 32); @@ -212,9 +204,9 @@ void LaserSceneNode::LaserRenderNode::renderGeoLaser() void LaserSceneNode::LaserRenderNode::renderFlatLaser() { const float len = sceneNode->length; - const GLfloat *sphere = sceneNode->getSphere(); + const auto &sphere = getPosition(); glPushMatrix(); - glTranslatef(sphere[0], sphere[1], sphere[2]); + glTranslate(sphere); glRotatef(sceneNode->azimuth, 0.0f, 0.0f, 1.0f); glRotatef(sceneNode->elevation, 0.0f, 1.0f, 0.0f); @@ -263,20 +255,13 @@ void LaserSceneNode::LaserRenderNode::renderFlatLaser() myColor4f(1.0f, 0.25f, 0.0f, 0.85f); glBegin(GL_TRIANGLE_STRIP); { - glVertex3f( 0.0f, geom[0][0], geom[0][1]); - glVertex3f( len, geom[0][0], geom[0][1]); - glVertex3f( 0.0f, geom[1][0], geom[1][1]); - glVertex3f( len, geom[1][0], geom[1][1]); - glVertex3f( 0.0f, geom[2][0], geom[2][1]); - glVertex3f( len, geom[2][0], geom[2][1]); - glVertex3f( 0.0f, geom[3][0], geom[3][1]); - glVertex3f( len, geom[3][0], geom[3][1]); - glVertex3f( 0.0f, geom[4][0], geom[4][1]); - glVertex3f( len, geom[4][0], geom[4][1]); - glVertex3f( 0.0f, geom[5][0], geom[5][1]); - glVertex3f( len, geom[5][0], geom[5][1]); - glVertex3f( 0.0f, geom[0][0], geom[0][1]); - glVertex3f( len, geom[0][0], geom[0][1]); + for (int i = 0; i < 6; i++) + { + glVertex(glm::vec3(0.0f, geom[i])); + glVertex(glm::vec3(len, geom[i])); + } + glVertex(glm::vec3(0.0f, geom[0])); + glVertex(glm::vec3(len, geom[0])); } glEnd(); // 14 verts -> 12 tris diff --git a/src/geometry/MeshFragSceneNode.cxx b/src/geometry/MeshFragSceneNode.cxx index a18b2549bb..72c1de69de 100644 --- a/src/geometry/MeshFragSceneNode.cxx +++ b/src/geometry/MeshFragSceneNode.cxx @@ -17,6 +17,8 @@ #include #include #include +#define GLM_ENABLE_EXPERIMENTAL +#include // common implementation headers #include "Intersect.h" @@ -26,6 +28,7 @@ #include "StateDatabase.h" #include "BZDBCache.h" #include "SceneRenderer.h" +#include "OpenGLAPI.h" // FIXME - no tesselation is done on for shot lighting @@ -103,7 +106,7 @@ inline void MeshFragSceneNode::Geometry::drawV() const glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glVertexPointer(3, GL_FLOAT, 0, sceneNode.vertices); + glVertexPointer(sceneNode.vertices); glDrawArrays(GL_TRIANGLES, 0, sceneNode.arrayCount * 3); glEnableClientState(GL_TEXTURE_COORD_ARRAY); @@ -117,7 +120,7 @@ inline void MeshFragSceneNode::Geometry::drawVT() const { glDisableClientState(GL_NORMAL_ARRAY); - glVertexPointer(3, GL_FLOAT, 0, sceneNode.vertices); + glVertexPointer(sceneNode.vertices); glTexCoordPointer(2, GL_FLOAT, 0, sceneNode.texcoords); glDrawArrays(GL_TRIANGLES, 0, sceneNode.arrayCount * 3); @@ -131,7 +134,7 @@ inline void MeshFragSceneNode::Geometry::drawVN() const { glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glVertexPointer(3, GL_FLOAT, 0, sceneNode.vertices); + glVertexPointer(sceneNode.vertices); glNormalPointer(GL_FLOAT, 0, sceneNode.normals); glDrawArrays(GL_TRIANGLES, 0, sceneNode.arrayCount * 3); @@ -143,7 +146,7 @@ inline void MeshFragSceneNode::Geometry::drawVN() const inline void MeshFragSceneNode::Geometry::drawVTN() const { - glVertexPointer(3, GL_FLOAT, 0, sceneNode.vertices); + glVertexPointer(sceneNode.vertices); glNormalPointer(GL_FLOAT, 0, sceneNode.normals); glTexCoordPointer(2, GL_FLOAT, 0, sceneNode.texcoords); glDrawArrays(GL_TRIANGLES, 0, sceneNode.arrayCount * 3); @@ -199,7 +202,7 @@ void MeshFragSceneNode::Geometry::renderShadow() glCallList(list); else { - glVertexPointer(3, GL_FLOAT, 0, sceneNode.vertices); + glVertexPointer(sceneNode.vertices); glDrawArrays(GL_TRIANGLES, 0, triangles * 3); } addTriangleCount(triangles); @@ -211,7 +214,7 @@ void MeshFragSceneNode::Geometry::setStyle(int style_) style = style_; } -const GLfloat* MeshFragSceneNode::Geometry::getPosition() const +const glm::vec3 &MeshFragSceneNode::Geometry::getPosition() const { return sceneNode.getSphere(); } @@ -233,7 +236,7 @@ MeshFragSceneNode::MeshFragSceneNode(int faceCount_, const MeshFace** faces_) assert ((faceCount > 0) && (faces != NULL)); // disable the plane - static const float fakePlane[4] = {0.0f, 0.0f, 1.0f, 0.0f}; + static const auto fakePlane = glm::vec4(0.0f, 0.0f, 1.0f, 0.0f); setPlane(fakePlane); const BzMaterial* bzmat = faces[0]->getMaterial(); @@ -253,17 +256,11 @@ MeshFragSceneNode::MeshFragSceneNode(int faceCount_, const MeshFace** faces_) } // setup sphere - float diffs[3]; - diffs[0] = extents.maxs[0] - extents.mins[0]; - diffs[1] = extents.maxs[1] - extents.mins[1]; - diffs[2] = extents.maxs[2] - extents.mins[2]; - float mySphere[4]; - mySphere[0] = 0.5f * (extents.maxs[0] + extents.mins[0]); - mySphere[1] = 0.5f * (extents.maxs[1] + extents.mins[1]); - mySphere[2] = 0.5f * (extents.maxs[2] + extents.mins[2]); - mySphere[3] = 0.25f * - ((diffs[0] * diffs[0]) + (diffs[1] * diffs[1]) + (diffs[2] * diffs[2])); - setSphere(mySphere); + auto mySphere = 0.5f * (extents.maxs + extents.mins); + setCenter(mySphere); + + float radius = 0.25f * glm::distance2(extents.maxs, extents.mins); + setRadius(radius); // count the number of actual vertices for (i = 0; i < faceCount; i++) @@ -274,9 +271,9 @@ MeshFragSceneNode::MeshFragSceneNode(int faceCount_, const MeshFace** faces_) // make the lists const int vertexCount = (arrayCount * 3); - normals = new GLfloat[vertexCount * 3]; - vertices = new GLfloat[vertexCount * 3]; - texcoords = new GLfloat[vertexCount * 2]; + normals = new glm::vec3[vertexCount]; + vertices = new glm::vec3[vertexCount]; + texcoords = new glm::vec2[vertexCount]; // fill in the lists int arrayIndex = 0; @@ -285,12 +282,12 @@ MeshFragSceneNode::MeshFragSceneNode(int faceCount_, const MeshFace** faces_) const MeshFace* face = faces[i]; // pre-generate the texcoords if required - GLfloat2Array t(face->getVertexCount()); + std::vector t(face->getVertexCount()); if (!face->useTexcoords()) { - GLfloat3Array v(face->getVertexCount()); + std::vector v(face->getVertexCount()); for (j = 0; j < face->getVertexCount(); j++) - memcpy(v[j], face->getVertex(j), sizeof(float[3])); + v[j] = face->getVertex(j); MeshSceneNodeGenerator::makeTexcoords(face->getPlane(), v, t); } @@ -309,19 +306,19 @@ MeshFragSceneNode::MeshFragSceneNode(int faceCount_, const MeshFace** faces_) vIndex = (j + k) % face->getVertexCount(); // get the vertices - memcpy(&vertices[aIndex * 3], face->getVertex(vIndex), sizeof(float[3])); + vertices[aIndex] = face->getVertex(vIndex); // get the normals if (face->useNormals()) - memcpy(&normals[aIndex * 3], face->getNormal(vIndex), sizeof(float[3])); + normals[aIndex] = face->getNormal(vIndex); else - memcpy(&normals[aIndex * 3], face->getPlane(), sizeof(float[3])); + normals[aIndex] = face->getPlane(); // get the texcoords if (face->useTexcoords()) - memcpy(&texcoords[aIndex * 2], face->getTexcoord(vIndex), sizeof(float[2])); + texcoords[aIndex] = face->getTexcoord(vIndex); else - memcpy(&texcoords[aIndex * 2], t[vIndex], sizeof(float[2])); + texcoords[aIndex] = t[vIndex]; } } @@ -343,7 +340,7 @@ MeshFragSceneNode::~MeshFragSceneNode() } -const GLfloat* MeshFragSceneNode::getPlane() const +const glm::vec4 *MeshFragSceneNode::getPlane() const { return NULL; } @@ -368,7 +365,7 @@ bool MeshFragSceneNode::inAxisBox (const Extents& exts) const { // NOTE: it should be OK to use the faces while building - float pos[3]; + glm::vec3 pos; pos[0] = 0.5f * (exts.maxs[0] + exts.mins[0]); pos[1] = 0.5f * (exts.maxs[1] + exts.mins[1]); pos[2] = exts.mins[2]; @@ -390,8 +387,8 @@ bool MeshFragSceneNode::inAxisBox (const Extents& exts) const void MeshFragSceneNode::addRenderNodes(SceneRenderer& renderer) { renderNode.setStyle(getStyle()); - const GLfloat* dyncol = getDynamicColor(); - if ((dyncol == NULL) || (dyncol[3] != 0.0f)) + const auto dyncol = getDynamicColor(); + if ((dyncol == NULL) || (dyncol->a != 0.0f)) renderer.addRenderNode(&renderNode, getWallGState()); } @@ -400,8 +397,8 @@ void MeshFragSceneNode::addShadowNodes(SceneRenderer& renderer) { if (!noShadow) { - const GLfloat* dyncol = getDynamicColor(); - if ((dyncol == NULL) || (dyncol[3] != 0.0f)) + const auto dyncol = getDynamicColor(); + if ((dyncol == NULL) || (dyncol->a != 0.0f)) renderer.addShadowNode(&renderNode); } } diff --git a/src/geometry/MeshPolySceneNode.cxx b/src/geometry/MeshPolySceneNode.cxx index 4866a083b3..7f605c0e0c 100644 --- a/src/geometry/MeshPolySceneNode.cxx +++ b/src/geometry/MeshPolySceneNode.cxx @@ -16,6 +16,8 @@ // system headers #include #include +#define GLM_ENABLE_EXPERIMENTAL +#include // common implementation headers #include "Intersect.h" @@ -30,13 +32,15 @@ // MeshPolySceneNode::Geometry // -MeshPolySceneNode::Geometry::Geometry(MeshPolySceneNode* _node, - const GLfloat3Array& _vertices, const GLfloat3Array& _normals, - const GLfloat2Array& _texcoords, const GLfloat* _normal) : - vertices(_vertices), normals(_normals), texcoords(_texcoords) +MeshPolySceneNode::Geometry::Geometry( + MeshPolySceneNode* _node, + const std::vector &_vertices, + const std::vector &_normals, + const std::vector &_texcoords, + const glm::vec4 &_plane) : + plane(_plane), vertices(_vertices), normals(_normals), texcoords(_texcoords) { sceneNode = _node; - normal = _normal; style = 0; return; } @@ -48,17 +52,16 @@ MeshPolySceneNode::Geometry::~Geometry() return; } -const GLfloat* MeshPolySceneNode::Geometry::getPosition() const +const glm::vec3 &MeshPolySceneNode::Geometry::getPosition() const { return sceneNode->getSphere(); } inline void MeshPolySceneNode::Geometry::drawV() const { - const int count = vertices.getSize(); glBegin(GL_TRIANGLE_FAN); - for (int i = 0; i < count; i++) - glVertex3fv(vertices[i]); + for (const auto &v : vertices) + glVertex3fv(v); glEnd(); return; } @@ -66,7 +69,7 @@ inline void MeshPolySceneNode::Geometry::drawV() const inline void MeshPolySceneNode::Geometry::drawVT() const { - const int count = vertices.getSize(); + const int count = vertices.size(); glBegin(GL_TRIANGLE_FAN); for (int i = 0; i < count; i++) { @@ -80,7 +83,7 @@ inline void MeshPolySceneNode::Geometry::drawVT() const inline void MeshPolySceneNode::Geometry::drawVN() const { - const int count = vertices.getSize(); + const int count = vertices.size(); glBegin(GL_TRIANGLE_FAN); for (int i = 0; i < count; i++) { @@ -94,7 +97,7 @@ inline void MeshPolySceneNode::Geometry::drawVN() const inline void MeshPolySceneNode::Geometry::drawVTN() const { - const int count = vertices.getSize(); + const int count = vertices.size(); glBegin(GL_TRIANGLE_FAN); for (int i = 0; i < count; i++) { @@ -111,7 +114,7 @@ void MeshPolySceneNode::Geometry::render() { sceneNode->setColor(); - if (normals.getSize() != 0) + if (!normals.empty()) { if (style >= 2) drawVTN(); @@ -120,14 +123,14 @@ void MeshPolySceneNode::Geometry::render() } else { - glNormal3fv(normal); + glNormal3fv(plane); if (style >= 2) drawVT(); else drawV(); } - addTriangleCount(vertices.getSize() - 2); + addTriangleCount(vertices.size() - 2); return; } @@ -135,7 +138,7 @@ void MeshPolySceneNode::Geometry::render() void MeshPolySceneNode::Geometry::renderShadow() { drawV(); - addTriangleCount(vertices.getSize() - 2); + addTriangleCount(vertices.size() - 2); return; } @@ -144,17 +147,17 @@ void MeshPolySceneNode::Geometry::renderShadow() // MeshPolySceneNode // -MeshPolySceneNode::MeshPolySceneNode(const float _plane[4], +MeshPolySceneNode::MeshPolySceneNode(const glm::vec4 &_plane, bool _noRadar, bool _noShadow, - const GLfloat3Array& vertices, - const GLfloat3Array& normals, - const GLfloat2Array& texcoords) : + const std::vector &vertices, + const std::vector &normals, + const std::vector &texcoords) : node(this, vertices, normals, texcoords, plane) { int i, j; - const int count = vertices.getSize(); - assert(texcoords.getSize() == count); - assert((normals.getSize() == 0) || (normals.getSize() == count)); + const int count = vertices.size(); + assert(texcoords.size() == count); + assert((normals.empty()) || (normals.size() == count)); setPlane(_plane); @@ -180,7 +183,7 @@ MeshPolySceneNode::MeshPolySceneNode(const float _plane[4], } // project vertices onto plane - GLfloat2Array flat(count); + std::vector flat(count); switch (ignoreAxis) { case 0: @@ -217,31 +220,24 @@ MeshPolySceneNode::MeshPolySceneNode(const float _plane[4], setNumLODs(1, area); // compute bounding sphere, put center at average of vertices - GLfloat mySphere[4]; - mySphere[0] = mySphere[1] = mySphere[2] = mySphere[3] = 0.0f; - for (i = 0; i < count; i++) - { - mySphere[0] += vertices[i][0]; - mySphere[1] += vertices[i][1]; - mySphere[2] += vertices[i][2]; - } - mySphere[0] /= (float)count; - mySphere[1] /= (float)count; - mySphere[2] /= (float)count; - for (i = 0; i < count; i++) + auto mySphere = glm::vec3(0.0f); + for (const auto &v : vertices) + mySphere += v; + mySphere /= (float)count; + setCenter(mySphere); + + float myRadius = 0.0f; + for (const auto &v : vertices) { - const float dx = mySphere[0] - vertices[i][0]; - const float dy = mySphere[1] - vertices[i][1]; - const float dz = mySphere[2] - vertices[i][2]; - GLfloat r = ((dx * dx) + (dy * dy) + (dz * dz)); - if (r > mySphere[3]) - mySphere[3] = r; + GLfloat r = glm::distance2(mySphere, v); + if (r > myRadius) + myRadius = r; } - setSphere(mySphere); + setRadius(myRadius); // record extents info - for (i = 0; i < count; i++) - extents.expandToPoint(vertices[i]); + for (const auto &v : vertices) + extents.expandToPoint(v); return; } @@ -256,9 +252,8 @@ MeshPolySceneNode::~MeshPolySceneNode() bool MeshPolySceneNode::cull(const ViewFrustum& frustum) const { // cull if eye is behind (or on) plane - const GLfloat* eye = frustum.getEye(); - if (((eye[0] * plane[0]) + (eye[1] * plane[1]) + (eye[2] * plane[2]) + - plane[3]) <= 0.0f) + const auto eye = glm::vec4(frustum.getEye(), 1.0f); + if (glm::dot(eye, plane) <= 0.0f) return true; // if the Visibility culler tells us that we're @@ -284,10 +279,10 @@ bool MeshPolySceneNode::inAxisBox (const Extents& exts) const } -int MeshPolySceneNode::split(const float* splitPlane, +int MeshPolySceneNode::split(const glm::vec4 &splitPlane, SceneNode*& front, SceneNode*& back) const { - if (node.normals.getSize() > 0) + if (!node.normals.empty()) { return splitWallVTN(splitPlane, node.vertices, node.normals, node.texcoords, front, back); @@ -300,8 +295,8 @@ int MeshPolySceneNode::split(const float* splitPlane, void MeshPolySceneNode::addRenderNodes(SceneRenderer& renderer) { node.setStyle(getStyle()); - const GLfloat* dyncol = getDynamicColor(); - if ((dyncol == NULL) || (dyncol[3] != 0.0f)) + const auto dyncol = getDynamicColor(); + if ((dyncol == NULL) || (dyncol->a != 0.0f)) renderer.addRenderNode(&node, getWallGState()); return; } @@ -311,8 +306,8 @@ void MeshPolySceneNode::addShadowNodes(SceneRenderer& renderer) { if (!noShadow) { - const GLfloat* dyncol = getDynamicColor(); - if ((dyncol == NULL) || (dyncol[3] != 0.0f)) + const auto dyncol = getDynamicColor(); + if ((dyncol == NULL) || (dyncol->a != 0.0f)) renderer.addShadowNode(&node); } return; @@ -327,14 +322,14 @@ void MeshPolySceneNode::renderRadar() } -int MeshPolySceneNode::splitWallVTN(const GLfloat* splitPlane, - const GLfloat3Array& vertices, - const GLfloat3Array& normals, - const GLfloat2Array& texcoords, +int MeshPolySceneNode::splitWallVTN(const glm::vec4 &splitPlane, + const std::vector &vertices, + const std::vector &normals, + const std::vector &texcoords, SceneNode*& front, SceneNode*& back) const { int i; - const int count = vertices.getSize(); + const int count = vertices.size(); const float fudgeFactor = 0.001f; const unsigned char BACK_SIDE = (1 << 0); const unsigned char FRONT_SIDE = (1 << 1); @@ -363,29 +358,29 @@ int MeshPolySceneNode::splitWallVTN(const GLfloat* splitPlane, int bothCount = 0; int backCount = 0; int frontCount = 0; - for (i = 0; i < count; i++) + unsigned char *tmpArray = array; + float *tmpDists = dists; + for (const auto &v : vertices) { - const GLfloat d = (vertices[i][0] * splitPlane[0]) + - (vertices[i][1] * splitPlane[1]) + - (vertices[i][2] * splitPlane[2]) + splitPlane[3]; + const GLfloat d = glm::dot(glm::vec4(v, 1.0f), splitPlane); if (d < -fudgeFactor) { - array[i] = BACK_SIDE; + *tmpArray++ = BACK_SIDE; backCount++; } else if (d > fudgeFactor) { - array[i] = FRONT_SIDE; + *tmpArray++ = FRONT_SIDE; frontCount++; } else { - array[i] = (BACK_SIDE | FRONT_SIDE); + *tmpArray++ = BACK_SIDE | FRONT_SIDE; bothCount++; backCount++; frontCount++; } - dists[i] = d; // save for later + *tmpDists++ = d; // save for later } // see if we need to split @@ -443,58 +438,60 @@ int MeshPolySceneNode::splitWallVTN(const GLfloat* splitPlane, } // make space for new polygons - GLfloat3Array vertexFront(frontCount); - GLfloat3Array normalFront(frontCount); - GLfloat2Array uvFront(frontCount); - GLfloat3Array vertexBack(backCount); - GLfloat3Array normalBack(backCount); - GLfloat2Array uvBack(backCount); + std::vector vertexFront(frontCount); + std::vector normalFront(frontCount); + std::vector uvFront(frontCount); + std::vector vertexBack(backCount); + std::vector normalBack(backCount); + std::vector uvBack(backCount); // fill in the splitting vertices int frontIndex = 0; int backIndex = 0; if (firstFront != lastBack) { - GLfloat splitVertex[3], splitNormal[3], splitUV[2]; + glm::vec3 splitVertex, splitNormal; + glm::vec2 splitUV; splitEdgeVTN(dists[firstFront], dists[lastBack], vertices[firstFront], vertices[lastBack], normals[firstFront], normals[lastBack], texcoords[firstFront], texcoords[lastBack], splitVertex, splitNormal, splitUV); - memcpy(vertexFront[0], splitVertex, sizeof(GLfloat[3])); - memcpy(normalFront[0], splitNormal, sizeof(GLfloat[3])); - memcpy(uvFront[0], splitUV, sizeof(GLfloat[2])); + vertexFront[0] = splitVertex; + normalFront[0] = splitNormal; + uvFront[0] = splitUV; frontIndex++; // bump up the head - const int last = backCount - 1; - memcpy(vertexBack[last], splitVertex, sizeof(GLfloat[3])); - memcpy(normalBack[last], splitNormal, sizeof(GLfloat[3])); - memcpy(uvBack[last], splitUV, sizeof(GLfloat[2])); + const int last = backCount - 1; + vertexBack[last] = splitVertex; + normalBack[last] = splitNormal; + uvBack[last] = splitUV; } if (firstBack != lastFront) { - GLfloat splitVertex[3], splitNormal[3], splitUV[2]; + glm::vec3 splitVertex, splitNormal; + glm::vec2 splitUV; splitEdgeVTN(dists[firstBack], dists[lastFront], vertices[firstBack], vertices[lastFront], normals[firstBack], normals[lastFront], texcoords[firstBack], texcoords[lastFront], splitVertex, splitNormal, splitUV); - memcpy(vertexBack[0], splitVertex, sizeof(GLfloat[3])); - memcpy(normalBack[0], splitNormal, sizeof(GLfloat[3])); - memcpy(uvBack[0], splitUV, sizeof(GLfloat[2])); + vertexBack[0] = splitVertex; + normalBack[0] = splitNormal; + uvBack[0] = splitUV; backIndex++; // bump up the head const int last = frontCount - 1; - memcpy(vertexFront[last], splitVertex, sizeof(GLfloat[3])); - memcpy(normalFront[last], splitNormal, sizeof(GLfloat[3])); - memcpy(uvFront[last], splitUV, sizeof(GLfloat[2])); + vertexFront[last] = splitVertex; + normalFront[last] = splitNormal; + uvFront[last] = splitUV; } // fill in the old front side vertices const int endFront = (lastFront + 1) % count; for (i = firstFront; i != endFront; i = (i + 1) % count) { - memcpy(vertexFront[frontIndex], vertices[i], sizeof(GLfloat[3])); - memcpy(normalFront[frontIndex], normals[i], sizeof(GLfloat[3])); - memcpy(uvFront[frontIndex], texcoords[i], sizeof(GLfloat[2])); + vertexFront[frontIndex] = vertices[i]; + normalFront[frontIndex] = normals[i]; + uvFront[frontIndex] = texcoords[i]; frontIndex++; } @@ -502,16 +499,16 @@ int MeshPolySceneNode::splitWallVTN(const GLfloat* splitPlane, const int endBack = (lastBack + 1) % count; for (i = firstBack; i != endBack; i = (i + 1) % count) { - memcpy(vertexBack[backIndex], vertices[i], sizeof(GLfloat[3])); - memcpy(normalBack[backIndex], normals[i], sizeof(GLfloat[3])); - memcpy(uvBack[backIndex], texcoords[i], sizeof(GLfloat[2])); + vertexBack[backIndex] = vertices[i]; + normalBack[backIndex] = normals[i]; + uvBack[backIndex] = texcoords[i]; backIndex++; } // make new nodes - front = new MeshPolySceneNode(getPlane(), noRadar, noShadow, + front = new MeshPolySceneNode(*getPlane(), noRadar, noShadow, vertexFront, normalFront, uvFront); - back = new MeshPolySceneNode(getPlane(), noRadar, noShadow, + back = new MeshPolySceneNode(*getPlane(), noRadar, noShadow, vertexBack, normalBack, uvBack); // free the arrays, if required @@ -526,10 +523,10 @@ int MeshPolySceneNode::splitWallVTN(const GLfloat* splitPlane, void MeshPolySceneNode::splitEdgeVTN(float d1, float d2, - const GLfloat* p1, const GLfloat* p2, - const GLfloat* n1, const GLfloat* n2, - const GLfloat* uv1, const GLfloat* uv2, - GLfloat* p, GLfloat* n, GLfloat* uv) const + const glm::vec3 &p1, const glm::vec3 &p2, + const glm::vec3 &n1, const glm::vec3 &n2, + const glm::vec2 &uv1, const glm::vec2 &uv2, + glm::vec3 &p, glm::vec3 &n, glm::vec2 &uv) const { // compute fraction along edge where split occurs float t1 = (d2 - d1); @@ -537,40 +534,28 @@ void MeshPolySceneNode::splitEdgeVTN(float d1, float d2, t1 = -(d1 / t1); // compute vertex - p[0] = p1[0] + (t1 * (p2[0] - p1[0])); - p[1] = p1[1] + (t1 * (p2[1] - p1[1])); - p[2] = p1[2] + (t1 * (p2[2] - p1[2])); + p = glm::mix(p1, p2, t1); // compute normal - const float t2 = 1.0f - t1; - n[0] = (n1[0] * t2) + (n2[0] * t1); - n[1] = (n1[1] * t2) + (n2[1] * t1); - n[2] = (n1[2] * t2) + (n2[2] * t1); + n = glm::mix(n1, n2, t1); // normalize - float len = ((n[0] * n[0]) + (n[1] * n[1]) + (n[2] * n[2])); - if (len > 1.0e-20f) // otherwise, let it go... - { - len = 1.0f / sqrtf(len); - n[0] = n[0] * len; - n[1] = n[1] * len; - n[2] = n[2] * len; - } + if (n.x || n.y || n.z) // otherwise, let it go... + n = glm::normalize(n); // compute texture coordinate - uv[0] = uv1[0] + (t1 * (uv2[0] - uv1[0])); - uv[1] = uv1[1] + (t1 * (uv2[1] - uv1[1])); + uv = glm::mix(uv1, uv2, t1); return; } -int MeshPolySceneNode::splitWallVT(const GLfloat* splitPlane, - const GLfloat3Array& vertices, - const GLfloat2Array& texcoords, +int MeshPolySceneNode::splitWallVT(const glm::vec4 &splitPlane, + const std::vector &vertices, + const std::vector &texcoords, SceneNode*& front, SceneNode*& back) const { int i; - const int count = vertices.getSize(); + const int count = vertices.size(); const float fudgeFactor = 0.001f; const unsigned char BACK_SIDE = (1 << 0); const unsigned char FRONT_SIDE = (1 << 1); @@ -599,29 +584,29 @@ int MeshPolySceneNode::splitWallVT(const GLfloat* splitPlane, int bothCount = 0; int backCount = 0; int frontCount = 0; - for (i = 0; i < count; i++) + unsigned char *tmpArray = array; + float *tmpDists = dists; + for (const auto &v : vertices) { - const GLfloat d = (vertices[i][0] * splitPlane[0]) + - (vertices[i][1] * splitPlane[1]) + - (vertices[i][2] * splitPlane[2]) + splitPlane[3]; + const GLfloat d = glm::dot(glm::vec4(v, 1.0f), splitPlane); if (d < -fudgeFactor) { - array[i] = BACK_SIDE; + *tmpArray++ = BACK_SIDE; backCount++; } else if (d > fudgeFactor) { - array[i] = FRONT_SIDE; + *tmpArray++ = FRONT_SIDE; frontCount++; } else { - array[i] = (BACK_SIDE | FRONT_SIDE); + *tmpArray++ = BACK_SIDE | FRONT_SIDE; bothCount++; backCount++; frontCount++; } - dists[i] = d; // save for later + *tmpDists++ = d; // save for later } // see if we need to split @@ -679,51 +664,53 @@ int MeshPolySceneNode::splitWallVT(const GLfloat* splitPlane, } // make space for new polygons - GLfloat3Array vertexFront(frontCount); - GLfloat3Array normalFront(0); - GLfloat2Array uvFront(frontCount); - GLfloat3Array vertexBack(backCount); - GLfloat3Array normalBack(0); - GLfloat2Array uvBack(backCount); + std::vector vertexFront(frontCount); + std::vector normalFront(0); + std::vector uvFront(frontCount); + std::vector vertexBack(backCount); + std::vector normalBack(0); + std::vector uvBack(backCount); // fill in the splitting vertices int frontIndex = 0; int backIndex = 0; if (firstFront != lastBack) { - GLfloat splitVertex[3], splitUV[2]; + glm::vec3 splitVertex; + glm::vec2 splitUV; splitEdgeVT(dists[firstFront], dists[lastBack], vertices[firstFront], vertices[lastBack], texcoords[firstFront], texcoords[lastBack], splitVertex, splitUV); - memcpy(vertexFront[0], splitVertex, sizeof(GLfloat[3])); - memcpy(uvFront[0], splitUV, sizeof(GLfloat[2])); + vertexFront[0] = splitVertex; + uvFront[0] = splitUV; frontIndex++; // bump up the head const int last = backCount - 1; - memcpy(vertexBack[last], splitVertex, sizeof(GLfloat[3])); - memcpy(uvBack[last], splitUV, sizeof(GLfloat[2])); + vertexBack[last] = splitVertex; + uvBack[last] = splitUV; } if (firstBack != lastFront) { - GLfloat splitVertex[3], splitUV[2]; + glm::vec3 splitVertex; + glm::vec2 splitUV; splitEdgeVT(dists[firstBack], dists[lastFront], vertices[firstBack], vertices[lastFront], texcoords[firstBack], texcoords[lastFront], splitVertex, splitUV); - memcpy(vertexBack[0], splitVertex, sizeof(GLfloat[3])); - memcpy(uvBack[0], splitUV, sizeof(GLfloat[2])); + vertexBack[0] = splitVertex; + uvBack[0] = splitUV; backIndex++; // bump up the head const int last = frontCount - 1; - memcpy(vertexFront[last], splitVertex, sizeof(GLfloat[3])); - memcpy(uvFront[last], splitUV, sizeof(GLfloat[2])); + vertexFront[last] = splitVertex; + uvFront[last] = splitUV; } // fill in the old front side vertices const int endFront = (lastFront + 1) % count; for (i = firstFront; i != endFront; i = (i + 1) % count) { - memcpy(vertexFront[frontIndex], vertices[i], sizeof(GLfloat[3])); - memcpy(uvFront[frontIndex], texcoords[i], sizeof(GLfloat[2])); + vertexFront[frontIndex] = vertices[i]; + uvFront[frontIndex] = texcoords[i]; frontIndex++; } @@ -731,15 +718,15 @@ int MeshPolySceneNode::splitWallVT(const GLfloat* splitPlane, const int endBack = (lastBack + 1) % count; for (i = firstBack; i != endBack; i = (i + 1) % count) { - memcpy(vertexBack[backIndex], vertices[i], sizeof(GLfloat[3])); - memcpy(uvBack[backIndex], texcoords[i], sizeof(GLfloat[2])); + vertexBack[backIndex] = vertices[i]; + uvBack[backIndex] = texcoords[i]; backIndex++; } // make new nodes - front = new MeshPolySceneNode(getPlane(), noRadar, noShadow, + front = new MeshPolySceneNode(*getPlane(), noRadar, noShadow, vertexFront, normalFront, uvFront); - back = new MeshPolySceneNode(getPlane(), noRadar, noShadow, + back = new MeshPolySceneNode(*getPlane(), noRadar, noShadow, vertexBack, normalBack, uvBack); // free the arrays, if required @@ -754,9 +741,9 @@ int MeshPolySceneNode::splitWallVT(const GLfloat* splitPlane, void MeshPolySceneNode::splitEdgeVT(float d1, float d2, - const GLfloat* p1, const GLfloat* p2, - const GLfloat* uv1, const GLfloat* uv2, - GLfloat* p, GLfloat* uv) const + const glm::vec3 &p1, const glm::vec3 &p2, + const glm::vec2 &uv1, const glm::vec2 &uv2, + glm::vec3 &p, glm::vec2 &uv) const { // compute fraction along edge where split occurs float t1 = (d2 - d1); @@ -764,13 +751,10 @@ void MeshPolySceneNode::splitEdgeVT(float d1, float d2, t1 = -(d1 / t1); // compute vertex - p[0] = p1[0] + (t1 * (p2[0] - p1[0])); - p[1] = p1[1] + (t1 * (p2[1] - p1[1])); - p[2] = p1[2] + (t1 * (p2[2] - p1[2])); + p = glm::mix(p1, p2, t1); // compute texture coordinate - uv[0] = uv1[0] + (t1 * (uv2[0] - uv1[0])); - uv[1] = uv1[1] + (t1 * (uv2[1] - uv1[1])); + uv = glm::mix(uv1, uv2, t1); return; } diff --git a/src/geometry/MeshRenderNode.cxx b/src/geometry/MeshRenderNode.cxx index f0a8ed9195..9ed2b2d4d9 100644 --- a/src/geometry/MeshRenderNode.cxx +++ b/src/geometry/MeshRenderNode.cxx @@ -13,6 +13,9 @@ // implementation header #include "MeshRenderNode.h" +// System headers +#include + // common implementation headers #include "RenderNode.h" #include "MeshDrawMgr.h" @@ -30,7 +33,7 @@ OpaqueRenderNode::OpaqueRenderNode(MeshDrawMgr* _drawMgr, GLfloat *_xformMatrix, bool _normalize, - const GLfloat* _color, + const glm::vec4 *_color, int _lod, int _set, const Extents* _exts, int tris) { @@ -45,10 +48,10 @@ OpaqueRenderNode::OpaqueRenderNode(MeshDrawMgr* _drawMgr, } -const GLfloat* OpaqueRenderNode::getPosition() const +const auto nullVec3 = glm::vec3(0.0f); +const glm::vec3 &OpaqueRenderNode::getPosition() const { // Better to not crash if called on sort - static GLfloat nullVec3[3]; return nullVec3; } @@ -59,7 +62,7 @@ void OpaqueRenderNode::render() RENDERER.disableLights(exts->mins, exts->maxs); // set the color - myColor4fv(color); + myColor4fv(*color); // do the transformation glPushMatrix(); @@ -102,26 +105,26 @@ void OpaqueRenderNode::renderShadow() AlphaGroupRenderNode::AlphaGroupRenderNode(MeshDrawMgr* _drawMgr, GLfloat *_xformMatrix, bool _normalize, - const GLfloat* _color, + const glm::vec4 *_color, int _lod, int _set, const Extents* _exts, - const GLfloat _pos[3], + const glm::vec3 &_pos, int _triangles) : OpaqueRenderNode(_drawMgr, _xformMatrix, _normalize, _color, _lod, _set, _exts, _triangles) { - memcpy(pos, _pos, sizeof(GLfloat[3])); + pos = _pos; return; } -const GLfloat* AlphaGroupRenderNode::getPosition() const +const glm::vec3 &AlphaGroupRenderNode::getPosition() const { return pos; } -void AlphaGroupRenderNode::setPosition(const GLfloat* _pos) +void AlphaGroupRenderNode::setPosition(const glm::vec3 &_pos) { - memcpy(pos, _pos, sizeof(GLfloat[3])); + pos = _pos; return; } diff --git a/src/geometry/MeshRenderNode.h b/src/geometry/MeshRenderNode.h index 86fe753d32..a40a16a4bd 100644 --- a/src/geometry/MeshRenderNode.h +++ b/src/geometry/MeshRenderNode.h @@ -16,6 +16,10 @@ // Inherits from #include "RenderNode.h" +// System headers +#include +#include + // common implementation headers #include "bzfgl.h" @@ -29,11 +33,11 @@ class OpaqueRenderNode : public RenderNode public: OpaqueRenderNode(MeshDrawMgr* drawMgr, GLfloat *xformMatrix, bool normalize, - const GLfloat* color, int lod, int set, + const glm::vec4 *color, int lod, int set, const Extents* exts, int triangles); void render() override; void renderShadow() override; - const GLfloat* getPosition() const override; + const glm::vec3 &getPosition() const override; private: void drawV() const; void drawVN() const; @@ -44,7 +48,7 @@ class OpaqueRenderNode : public RenderNode GLfloat* xformMatrix; bool normalize; int lod, set; - const GLfloat* color; + const glm::vec4 *color; const Extents* exts; int triangles; }; @@ -55,13 +59,13 @@ class AlphaGroupRenderNode : public OpaqueRenderNode public: AlphaGroupRenderNode(MeshDrawMgr* drawMgr, GLfloat *xformMatrix, bool normalize, - const GLfloat* color, int lod, int set, - const Extents* exts, const float pos[3], + const glm::vec4 *color, int lod, int set, + const Extents* exts, const glm::vec3 &pos, int triangles); - const GLfloat* getPosition() const override; - void setPosition(const GLfloat* pos); + const glm::vec3 &getPosition() const override; + void setPosition(const glm::vec3 &pos); private: - float pos[3]; + glm::vec3 pos; }; diff --git a/src/geometry/MeshSceneNode.cxx b/src/geometry/MeshSceneNode.cxx index 5d55479f0e..51b9bda686 100644 --- a/src/geometry/MeshSceneNode.cxx +++ b/src/geometry/MeshSceneNode.cxx @@ -78,18 +78,21 @@ MeshSceneNode::MeshSceneNode(const MeshObstacle* _mesh) if (xformTool == NULL) { extents = drawInfo->getExtents(); - setSphere(drawInfo->getSphere()); + setCenter(drawInfo->getPosition()); + setRadius(drawInfo->getRadius2()); } else { // sloppy way to recalcuate the transformed extents - afvec3 c[8]; - c[0][0] = c[6][0] = c[5][0] = c[3][0] = diExts.mins[0]; - c[7][0] = c[1][0] = c[2][0] = c[4][0] = diExts.maxs[0]; - c[0][1] = c[1][1] = c[5][1] = c[4][1] = diExts.mins[1]; - c[7][1] = c[6][1] = c[2][1] = c[3][1] = diExts.maxs[1]; - c[0][2] = c[1][2] = c[2][2] = c[3][2] = diExts.mins[2]; - c[7][2] = c[6][2] = c[5][2] = c[4][2] = diExts.maxs[2]; + glm::vec3 c[8]; + c[0] = diExts.mins; + c[6][0] = c[5][0] = c[3][0] = diExts.mins[0]; + c[1][0] = c[2][0] = c[4][0] = diExts.maxs[0]; + c[1][1] = c[5][1] = c[4][1] = diExts.mins[1]; + c[6][1] = c[2][1] = c[3][1] = diExts.maxs[1]; + c[1][2] = c[2][2] = c[3][2] = diExts.mins[2]; + c[6][2] = c[5][2] = c[4][2] = diExts.maxs[2]; + c[7] = diExts.maxs; extents.reset(); for (int v = 0; v < 8; v++) { @@ -98,27 +101,26 @@ MeshSceneNode::MeshSceneNode(const MeshObstacle* _mesh) } // lengthPerPixel adjustment lengthAdj = +MAXFLOAT; + const auto &s = c[0]; // all mins for (int a = 0; a < 3; a++) { const float oldWidth = diExts.maxs[a] - diExts.mins[a]; - const afvec3& s = c[0]; // all mins + if (oldWidth <= 0.0f) + continue; // mins, except: c[1] -> max[0], c[3] -> max[1], c[5] -> max[2] - const afvec3& e = c[(a * 2) + 1]; - const float d[3] = {s[0] - e[0], s[1] - e[1], s[2] - e[2]}; - const float newWidth = sqrtf(d[0]*d[0] + d[1]*d[1] + d[2]*d[2]); - if (oldWidth > 0.0f) - { - const float scale = (newWidth / oldWidth); - if (scale < lengthAdj) - lengthAdj = scale; - } + const auto &e = c[(a * 2) + 1]; + const float newWidth = glm::distance(s, e); + const float scale = (newWidth / oldWidth); + if (scale < lengthAdj) + lengthAdj = scale; } // adjust the sphere - float mySphere[4]; - memcpy(mySphere, drawInfo->getSphere(), sizeof(float[4])); - xformTool->modifyVertex(mySphere); - mySphere[3] *= (lengthAdj * lengthAdj); - setSphere(mySphere); + auto myCenter = drawInfo->getPosition(); + xformTool->modifyVertex(myCenter); + setCenter(myCenter); + + float myRadius = drawInfo->getRadius2() * lengthAdj * lengthAdj; + setRadius(myRadius); } // setup lod/set nodes @@ -188,12 +190,11 @@ MeshSceneNode::~MeshSceneNode() inline int MeshSceneNode::calcNormalLod(const ViewFrustum& vf) { - const float* e = vf.getEye(); - const float* s = getSphere(); - const float* d = vf.getDirection(); - const float dist = (d[0] * (s[0] - e[0])) + - (d[1] * (s[1] - e[1])) + - (d[2] * (s[2] - e[2])); + const auto &e = vf.getEye(); + const auto &s = getSphere(); + const auto r = s - e; + const auto d = glm::vec3(vf.getDirection()); + const float dist = glm::dot(d, r); const float lengthPerPixel = dist * LodScale; for (int i = (lodCount - 1); i > 0; i--) { @@ -233,8 +234,8 @@ void MeshSceneNode::addRenderNodes(SceneRenderer& renderer) SetNode& set = lod.sets[i]; if (set.meshMat.animRepos) { - const float* s = drawLods[level].sets[i].sphere; - afvec3 pos; + const auto &s = drawLods[level].sets[i].position; + glm::vec3 pos; pos[0] = (cos_val * s[0]) - (sin_val * s[1]); pos[1] = (sin_val * s[0]) + (cos_val * s[1]); pos[2] = s[2]; @@ -248,7 +249,7 @@ void MeshSceneNode::addRenderNodes(SceneRenderer& renderer) for (int i = 0; i < lod.count; i++) { SetNode& set = lod.sets[i]; - if (set.meshMat.colorPtr[3] != 0.0f) + if (set.meshMat.colorPtr->a != 0.0f) renderer.addRenderNode(set.node, &set.meshMat.gstate); } @@ -265,7 +266,7 @@ void MeshSceneNode::addShadowNodes(SceneRenderer& renderer) { SetNode& set = lod.sets[i]; const MeshMaterial& mat = set.meshMat; - if (mat.drawShadow && (mat.colorPtr[3] != 0.0f)) + if (mat.drawShadow && (mat.colorPtr->a != 0.0f)) renderer.addShadowNode(set.node); } return; @@ -351,16 +352,15 @@ void MeshSceneNode::notifyStyleChange() } else { - afvec3 setPos; - memcpy(setPos, drawSet.sphere, sizeof(afvec3)); + auto setPos = drawSet.position; if (xformTool != NULL) xformTool->modifyVertex(setPos); setNode.node = new AlphaGroupRenderNode(drawMgr, xformMatrix, normalize, mat.colorPtr, lod, set, extPtr, setPos, drawSet.triangleCount); - if ((fabsf(drawSet.sphere[0]) > 0.001f) && - (fabsf(drawSet.sphere[1]) > 0.001f) && + if ((fabsf(drawSet.position.x) > 0.001f) && + (fabsf(drawSet.position.y) > 0.001f) && (mat.color[3] != 0.0f) && (drawInfo->getAnimationInfo() != NULL)) { @@ -402,7 +402,7 @@ void MeshSceneNode::updateMaterial(MeshSceneNode::MeshMaterial* mat) // get the references const BzMaterial* bzmat = mat->bzmat; OpenGLGState& gstate = mat->gstate; - GLfloat* color = mat->color; + auto color = &mat->color; OpenGLGStateBuilder builder; TextureManager &tm = TextureManager::instance(); @@ -474,15 +474,15 @@ void MeshSceneNode::updateMaterial(MeshSceneNode::MeshMaterial* mat) // color if (useDiffuseColor) { - memcpy(color, bzmat->getDiffuse(), sizeof(float[4])); - colorAlpha = (color[3] != 1.0f); + *color = bzmat->getDiffuse(); + colorAlpha = (color->a != 1.0f); } else { // set it to white, this should only happen when // we've gotten a user texture, and there's a // request to not use the material's diffuse color. - color[0] = color[1] = color[2] = color[3] = 1.0f; + *color = glm::vec4(1.0f); } // dynamic color @@ -510,7 +510,7 @@ void MeshSceneNode::updateMaterial(MeshSceneNode::MeshMaterial* mat) if (dyncol != NULL) builder.setStipple(0.5f); else - builder.setStipple(color[3]); + builder.setStipple(color->a); } } @@ -564,10 +564,11 @@ void MeshSceneNode::makeXFormList() }; // oops, transpose + const auto &matrix = xformTool->getMatrix(); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) - xformMatrix[(i*4)+j] = xformTool->getMatrix()[(j*4)+i]; + xformMatrix[(i*4)+j] = matrix[j][i]; } } return; diff --git a/src/geometry/OccluderSceneNode.cxx b/src/geometry/OccluderSceneNode.cxx index 31eb2d2510..d84462a305 100644 --- a/src/geometry/OccluderSceneNode.cxx +++ b/src/geometry/OccluderSceneNode.cxx @@ -17,6 +17,8 @@ // system headers #include #include +#define GLM_ENABLE_EXPERIMENTAL +#include // common implementation headers #include "MeshFace.h" @@ -24,48 +26,41 @@ #include "ViewFrustum.h" -OccluderSceneNode::OccluderSceneNode(const MeshFace* face) +OccluderSceneNode::OccluderSceneNode(const MeshFace* face) : + plane(face->getPlane()) { int i; setOccluder(true); - // record plane info - memcpy(plane, face->getPlane(), sizeof(float[4])); - // record extents info extents = face->getExtents(); // record vertex info vertexCount = face->getVertexCount(); - vertices = new GLfloat3[vertexCount]; + vertices = new glm::vec3[vertexCount]; for (i = 0; i < vertexCount; i++) - memcpy(vertices[i], face->getVertex(i), sizeof(float[3])); + vertices[i] = face->getVertex(i); // record sphere info - GLfloat mySphere[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; + auto mySphere = glm::vec3(0.0f); for (i = 0; i < vertexCount; i++) { - const float* v = vertices[i]; - mySphere[0] += v[0]; - mySphere[1] += v[1]; - mySphere[2] += v[2]; + const auto v = vertices[i]; + mySphere += v; } - mySphere[0] /= (float)vertexCount; - mySphere[1] /= (float)vertexCount; - mySphere[2] /= (float)vertexCount; + mySphere /= (float)vertexCount; + setCenter(mySphere); + float myRadius = 0.0f; for (i = 0; i < vertexCount; i++) { - const float* v = vertices[i]; - const float dx = mySphere[0] - v[0]; - const float dy = mySphere[1] - v[1]; - const float dz = mySphere[2] - v[2]; - GLfloat r = ((dx * dx) + (dy * dy) + (dz * dz)); - if (r > mySphere[3]) - mySphere[3] = r; + const auto v = vertices[i]; + GLfloat r = glm::distance2(mySphere, v); + if (r > myRadius) + myRadius = r; } - setSphere(mySphere); + setRadius(myRadius); return; } @@ -78,17 +73,16 @@ OccluderSceneNode::~OccluderSceneNode() } -const GLfloat* OccluderSceneNode::getPlane() const +const glm::vec4 *OccluderSceneNode::getPlane() const { - return plane; + return &plane; } bool OccluderSceneNode::cull(const ViewFrustum& frustum) const { // cull if eye is behind (or on) plane - const GLfloat* eye = frustum.getEye(); - if (((eye[0] * plane[0]) + (eye[1] * plane[1]) + (eye[2] * plane[2]) + - plane[3]) <= 0.0f) + const auto eye = glm::vec4(frustum.getEye(), 1.0f); + if (glm::dot(eye, plane) <= 0.0f) return true; // if the Visibility culler tells us that we're @@ -133,7 +127,7 @@ int OccluderSceneNode::getVertexCount () const return vertexCount; } -const GLfloat* OccluderSceneNode::getVertex (int vertex) const +const glm::vec3 &OccluderSceneNode::getVertex (int vertex) const { return vertices[vertex]; } diff --git a/src/geometry/PolyWallSceneNode.cxx b/src/geometry/PolyWallSceneNode.cxx index 1afca21937..b98b1fc4fb 100644 --- a/src/geometry/PolyWallSceneNode.cxx +++ b/src/geometry/PolyWallSceneNode.cxx @@ -16,6 +16,8 @@ // system headers #include #include +#define GLM_ENABLE_EXPERIMENTAL +#include // FIXME (SceneRenderer.cxx is in src/bzflag) #include "SceneRenderer.h" @@ -25,11 +27,11 @@ // PolyWallSceneNode::Geometry::Geometry(PolyWallSceneNode* _wall, - const GLfloat3Array& _vertex, - const GLfloat2Array& _uv, - const GLfloat* _normal) : + const std::vector &_vertex, + const std::vector &_uv, + const glm::vec4 &_plane) : wall(_wall), - normal(_normal), + plane(_plane), vertex(_vertex), uv(_uv) { @@ -41,7 +43,7 @@ PolyWallSceneNode::Geometry::~Geometry() // do nothing } -const GLfloat* PolyWallSceneNode::Geometry::getPosition() const +const glm::vec3 &PolyWallSceneNode::Geometry::getPosition() const { return wall->getSphere(); } @@ -49,27 +51,26 @@ const GLfloat* PolyWallSceneNode::Geometry::getPosition() const void PolyWallSceneNode::Geometry::render() { wall->setColor(); - glNormal3fv(normal); + glNormal3fv(plane); if (style >= 2) drawVT(); else drawV(); - addTriangleCount(vertex.getSize() - 2); + addTriangleCount(vertex.size() - 2); return; } void PolyWallSceneNode::Geometry::drawV() const { - const int count = vertex.getSize(); glBegin(GL_TRIANGLE_FAN); - for (int i = 0; i < count; i++) - glVertex3fv(vertex[i]); + for (auto v : vertex) + glVertex3fv(v); glEnd(); } void PolyWallSceneNode::Geometry::drawVT() const { - const int count = vertex.getSize(); + const int count = vertex.size(); glBegin(GL_TRIANGLE_FAN); for (int i = 0; i < count; i++) { @@ -83,44 +84,33 @@ void PolyWallSceneNode::Geometry::drawVT() const // PolyWallSceneNode // -PolyWallSceneNode::PolyWallSceneNode(const GLfloat3Array& vertex, - const GLfloat2Array& uv) +PolyWallSceneNode::PolyWallSceneNode(const std::vector &vertex, + const std::vector &uv) { - const int count = vertex.getSize(); - assert(uv.getSize() == count); + const int count = vertex.size(); + assert(uv.size() == count); // figure out plane (find non-colinear edges and get cross product) - GLfloat uEdge[3], vEdge[3], myPlane[4]; - GLfloat uLen, vLen, nLen; - uEdge[0] = vertex[0][0] - vertex[count - 1][0]; - uEdge[1] = vertex[0][1] - vertex[count - 1][1]; - uEdge[2] = vertex[0][2] - vertex[count - 1][2]; - uLen = uEdge[0] * uEdge[0] + uEdge[1] * uEdge[1] + uEdge[2] * uEdge[2]; + auto uEdge = vertex[0] - vertex[count - 1]; + GLfloat uLen = glm::length2(uEdge); + glm::vec3 cross; int i; for (i = 1; i < count; i++) { - vEdge[0] = vertex[i][0] - vertex[i - 1][0]; - vEdge[1] = vertex[i][1] - vertex[i - 1][1]; - vEdge[2] = vertex[i][2] - vertex[i - 1][2]; - vLen = vEdge[0] * vEdge[0] + vEdge[1] * vEdge[1] + vEdge[2] * vEdge[2]; - myPlane[0] = uEdge[1] * vEdge[2] - uEdge[2] * vEdge[1]; - myPlane[1] = uEdge[2] * vEdge[0] - uEdge[0] * vEdge[2]; - myPlane[2] = uEdge[0] * vEdge[1] - uEdge[1] * vEdge[0]; - nLen = myPlane[0] * myPlane[0] + myPlane[1] * myPlane[1] - + myPlane[2] * myPlane[2]; + auto vEdge = vertex[i] - vertex[i - 1]; + GLfloat vLen = glm::length2(vEdge); + cross = glm::cross(uEdge, vEdge); + GLfloat nLen = glm::length2(cross); if (nLen > 1.0e-5f * uLen * vLen) break; - uEdge[0] = vEdge[0]; - uEdge[1] = vEdge[1]; - uEdge[2] = vEdge[2]; + uEdge = vEdge; uLen = vLen; } - myPlane[3] = -(myPlane[0] * vertex[0][0] + myPlane[1] * vertex[0][1] + - myPlane[2] * vertex[0][2]); + auto myPlane = glm::vec4(cross, -glm::dot(cross, vertex[0])); setPlane(myPlane); // choose axis to ignore (the one with the largest normal component) int ignoreAxis; - const auto normal = plane; + const auto &normal = plane; if (fabsf(normal[0]) > fabsf(normal[1])) if (fabsf(normal[0]) > fabsf(normal[2])) ignoreAxis = 0; @@ -132,7 +122,7 @@ PolyWallSceneNode::PolyWallSceneNode(const GLfloat3Array& vertex, ignoreAxis = 2; // project vertices onto plane - GLfloat2Array flat(vertex.getSize()); + GLfloat2Array flat(vertex.size()); switch (ignoreAxis) { case 0: @@ -173,25 +163,19 @@ PolyWallSceneNode::PolyWallSceneNode(const GLfloat3Array& vertex, setNumLODs(1, area); // compute bounding sphere, put center at average of vertices - GLfloat mySphere[4]; - mySphere[0] = mySphere[1] = mySphere[2] = mySphere[3] = 0.0f; - for (i = 0; i < count; i++) - { - mySphere[0] += vertex[i][0]; - mySphere[1] += vertex[i][1]; - mySphere[2] += vertex[i][2]; - } - mySphere[0] /= (float)count; - mySphere[1] /= (float)count; - mySphere[2] /= (float)count; - for (i = 0; i < count; i++) + auto mySphere = glm::vec3(0.0f); + for (auto v : vertex) + mySphere += v; + mySphere /= (float)count; + setCenter(mySphere); + + float myRadius = 0.0f; + for (auto v : vertex) { - GLfloat r = (mySphere[0] - vertex[i][0]) * (mySphere[0] - vertex[i][0]) + - (mySphere[1] - vertex[i][1]) * (mySphere[1] - vertex[i][1]) + - (mySphere[2] - vertex[i][2]) * (mySphere[2] - vertex[i][2]); - if (r > mySphere[3]) mySphere[3] = r; + GLfloat r = glm::distance2(mySphere, v); + if (r > myRadius) myRadius = r; } - setSphere(mySphere); + setRadius(myRadius); } PolyWallSceneNode::~PolyWallSceneNode() @@ -200,7 +184,7 @@ PolyWallSceneNode::~PolyWallSceneNode() delete shadowNode; } -int PolyWallSceneNode::split(const float* _plane, +int PolyWallSceneNode::split(const glm::vec4 &_plane, SceneNode*& front, SceneNode*& back) const { return WallSceneNode::splitWall(_plane, node->vertex, node->uv, front, back); diff --git a/src/geometry/QuadWallSceneNode.cxx b/src/geometry/QuadWallSceneNode.cxx index c64a34ed3a..3b5ec5bcac 100644 --- a/src/geometry/QuadWallSceneNode.cxx +++ b/src/geometry/QuadWallSceneNode.cxx @@ -15,6 +15,9 @@ // system headers #include +#include +#define GLM_ENABLE_EXPERIMENTAL +#include // common implementation headers #include "Intersect.h" @@ -32,11 +35,11 @@ QuadWallSceneNode::Geometry::Geometry(QuadWallSceneNode* _wall, int uCount, int vCount, - const GLfloat base[3], - const GLfloat uEdge[3], - const GLfloat vEdge[3], - const GLfloat* _normal, - float uOffset, float vOffset, + const glm::vec3 &base, + const glm::vec3 &uEdge, + const glm::vec3 &vEdge, + const glm::vec4 &_plane, + const glm::vec2 &uvOffset, float uRepeats, float vRepeats, bool fixedUVs) : wall(_wall), style(0), @@ -44,7 +47,7 @@ QuadWallSceneNode::Geometry::Geometry(QuadWallSceneNode* _wall, dt(vCount), dsq(uCount / 4), dsr(uCount % 4), - normal(_normal), + plane(_plane), vertex((uCount+1) * (vCount+1)), uv((uCount+1) * (vCount+1)) { @@ -54,47 +57,35 @@ QuadWallSceneNode::Geometry::Geometry(QuadWallSceneNode* _wall, for (int i = 0; i <= uCount; n++, i++) { const float s = (float)i / (float)uCount; - vertex[n][0] = base[0] + s * uEdge[0] + t * vEdge[0]; - vertex[n][1] = base[1] + s * uEdge[1] + t * vEdge[1]; - vertex[n][2] = base[2] + s * uEdge[2] + t * vEdge[2]; - uv[n][0] = uOffset + s * uRepeats; - uv[n][1] = vOffset + t * vRepeats; + vertex[n] = base + s * uEdge + t * vEdge; + uv[n] = uvOffset + glm::vec2(s * uRepeats, t * vRepeats); } } if (!fixedUVs && BZDB.isTrue("remapTexCoords")) { - const float uLen = sqrtf((uEdge[0] * uEdge[0]) + - (uEdge[1] * uEdge[1]) + - (uEdge[2] * uEdge[2])); - const float vLen = sqrtf((vEdge[0] * vEdge[0]) + - (vEdge[1] * vEdge[1]) + - (vEdge[2] * vEdge[2])); + const float uLen = glm::length(uEdge); + const float vLen = glm::length(vEdge); const float uScale = 10.0f / floorf(10.0f * uLen / uRepeats); const float vScale = 10.0f / floorf(10.0f * vLen / vRepeats); - if (fabsf(normal[2]) > 0.999f) + const auto uvScale = glm::vec2(uScale, vScale); + if (fabsf(plane[2]) > 0.999f) { // horizontal surface - for (int i = 0; i < vertex.getSize(); i++) - { - uv[i][0] = uScale * vertex[i][0]; - uv[i][1] = vScale * vertex[i][1]; - } + for (unsigned int i = 0; i < vertex.size(); i++) + uv[i] = uvScale * glm::vec2(vertex[i]); } else { // vertical surface - const float nh = sqrtf((normal[0] * normal[0]) + (normal[1] * normal[1])); - const float nx = normal[0] / nh; - const float ny = normal[1] / nh; - const float vs = 1.0f / sqrtf(1.0f - (normal[2] * normal[2])); - for (int i = 0; i < vertex.getSize(); i++) + const auto n = glm::normalize(glm::vec2(plane)); + const float vs = glm::inversesqrt(1.0f - (plane[2] * plane[2])); + for (unsigned int i = 0; i < vertex.size(); i++) { - const float* v = vertex[i]; - const float uGeoScale = (nx * v[1]) - (ny * v[0]); + const auto v = vertex[i]; + const float uGeoScale = n.x * v[1] - n.y * v[0]; const float vGeoScale = v[2] * vs; - uv[i][0] = uScale * uGeoScale; - uv[i][1] = vScale * vGeoScale; + uv[i] = uvScale * glm::vec2(uGeoScale, vGeoScale); } } } @@ -147,7 +138,7 @@ QuadWallSceneNode::Geometry::~Geometry() #define EMITV(_i) glVertex3fv(vertex[_i]) #define EMITVT(_i) glTexCoord2fv(uv[_i]); glVertex3fv(vertex[_i]) -const GLfloat* QuadWallSceneNode::Geometry::getPosition() const +const glm::vec3 &QuadWallSceneNode::Geometry::getPosition() const { return wall->getSphere(); } @@ -155,7 +146,7 @@ const GLfloat* QuadWallSceneNode::Geometry::getPosition() const void QuadWallSceneNode::Geometry::render() { wall->setColor(); - glNormal3fv(normal); + glNormal3fv(plane); if (style >= 2) drawVT(); else @@ -186,7 +177,7 @@ void QuadWallSceneNode::Geometry::drawVT() const RENDER(EMITVT) } -const GLfloat* QuadWallSceneNode::Geometry::getVertex(int i) const +const glm::vec3 &QuadWallSceneNode::Geometry::getVertex(int i) const { return vertex[i]; } @@ -195,61 +186,51 @@ const GLfloat* QuadWallSceneNode::Geometry::getVertex(int i) const // QuadWallSceneNode // -QuadWallSceneNode::QuadWallSceneNode(const GLfloat base[3], - const GLfloat uEdge[3], - const GLfloat vEdge[3], - float uOffset, - float vOffset, +QuadWallSceneNode::QuadWallSceneNode(const glm::vec3 &base, + const glm::vec3 &uEdge, + const glm::vec3 &vEdge, + const glm::vec2 &uvOffset, float uRepeats, float vRepeats, bool makeLODs) { - init(base, uEdge, vEdge, uOffset, vOffset, uRepeats, vRepeats, makeLODs, false); + init(base, uEdge, vEdge, uvOffset, uRepeats, vRepeats, makeLODs, false); } -QuadWallSceneNode::QuadWallSceneNode(const GLfloat base[3], - const GLfloat uEdge[3], - const GLfloat vEdge[3], +QuadWallSceneNode::QuadWallSceneNode(const glm::vec3 &base, + const glm::vec3 &uEdge, + const glm::vec3 &vEdge, float uRepeats, float vRepeats, bool makeLODs, bool fixedUVs) { - init(base, uEdge, vEdge, 0.0f, 0.0f, uRepeats, vRepeats, makeLODs, fixedUVs); + init(base, uEdge, vEdge, glm::vec2(0.0f), uRepeats, vRepeats, makeLODs, fixedUVs); } -void QuadWallSceneNode::init(const GLfloat base[3], - const GLfloat uEdge[3], - const GLfloat vEdge[3], - float uOffset, - float vOffset, +void QuadWallSceneNode::init(const glm::vec3 &base, + const glm::vec3 &uEdge, + const glm::vec3 &vEdge, + const glm::vec2 &uvOffset, float uRepeats, float vRepeats, bool makeLODs, bool fixedUVs) { // record plane and bounding sphere info - GLfloat myPlane[4], mySphere[4]; - myPlane[0] = uEdge[1] * vEdge[2] - uEdge[2] * vEdge[1]; - myPlane[1] = uEdge[2] * vEdge[0] - uEdge[0] * vEdge[2]; - myPlane[2] = uEdge[0] * vEdge[1] - uEdge[1] * vEdge[0]; - myPlane[3] = -(myPlane[0] * base[0] + myPlane[1] * base[1] - + myPlane[2] * base[2]); + auto n = glm::cross(uEdge, vEdge); + auto myPlane = glm::vec4(n, -glm::dot(n, base)); setPlane(myPlane); - mySphere[0] = 0.5f * (uEdge[0] + vEdge[0]); - mySphere[1] = 0.5f * (uEdge[1] + vEdge[1]); - mySphere[2] = 0.5f * (uEdge[2] + vEdge[2]); - mySphere[3] = mySphere[0]*mySphere[0] + mySphere[1]*mySphere[1] - + mySphere[2]*mySphere[2]; - mySphere[0] += base[0]; - mySphere[1] += base[1]; - mySphere[2] += base[2]; - setSphere(mySphere); + + auto mySphere = 0.5f * (uEdge + vEdge); + + setRadius(glm::length2(mySphere)); + + mySphere += base; + setCenter(mySphere); // get length of sides - const float uLength = sqrtf(float(uEdge[0] * uEdge[0] + - uEdge[1] * uEdge[1] + uEdge[2] * uEdge[2])); - const float vLength = sqrtf(float(vEdge[0] * vEdge[0] + - vEdge[1] * vEdge[1] + vEdge[2] * vEdge[2])); + const float uLength = glm::length(uEdge); + const float vLength = glm::length(vEdge); float area = uLength * vLength; // If negative then these values aren't a number of times to repeat @@ -269,7 +250,7 @@ void QuadWallSceneNode::init(const GLfloat base[3], int uLevels = 1, vLevels = 1; while (uElements >>= 1) uLevels++; while (vElements >>= 1) vLevels++; - int numLevels = (uLevels < vLevels ? uLevels : vLevels); + int numLevels = std::min(uLevels, vLevels); // if overly rectangular then add levels to square it up bool needsSquaring = false; @@ -302,11 +283,11 @@ void QuadWallSceneNode::init(const GLfloat base[3], areas[level] = area; nodes[level++] = new Geometry(this, uElements, vElements, base, uEdge, vEdge, - plane, uOffset, vOffset, + plane, uvOffset, uRepeats, vRepeats, fixedUVs); shadowNode = new Geometry(this, uElements, vElements, base, uEdge, vEdge, - plane, uOffset, vOffset, + plane, uvOffset, uRepeats, vRepeats, fixedUVs); shadowNode->setStyle(0); @@ -324,7 +305,7 @@ void QuadWallSceneNode::init(const GLfloat base[3], areas[level] = area / (float)uElements; nodes[level++] = new Geometry(this, uElements, vElements, base, uEdge, vEdge, - plane, uOffset, vOffset, + plane, uvOffset, uRepeats, vRepeats, fixedUVs); } @@ -339,7 +320,7 @@ void QuadWallSceneNode::init(const GLfloat base[3], areas[level] = area / (float)vElements; nodes[level++] = new Geometry(this, uElements, vElements, base, uEdge, vEdge, - plane, uOffset, vOffset, + plane, uvOffset, uRepeats, vRepeats, fixedUVs); } @@ -356,14 +337,14 @@ void QuadWallSceneNode::init(const GLfloat base[3], areas[level] = area; nodes[level++] = new Geometry(this, uElements, vElements, base, uEdge, vEdge, - plane, uOffset, vOffset, + plane, uvOffset, uRepeats, vRepeats, fixedUVs); } // record extents info for (int i = 0; i < 4; i++) { - const float* point = getVertex(i); + const auto point = getVertex(i); extents.expandToPoint(point); } @@ -381,21 +362,18 @@ QuadWallSceneNode::~QuadWallSceneNode() delete shadowNode; } -int QuadWallSceneNode::split(const float *_plane, +int QuadWallSceneNode::split(const glm::vec4 &_plane, SceneNode*& front, SceneNode*& back) const { // need to reorder vertices into counterclockwise order - GLfloat3Array vertex(4); - GLfloat2Array uv(4); + std::vector vertex(4); + std::vector uv(4); for (int i = 0; i < 4; i++) { int j = i; if (j == 2 || j == 3) j = 5 - j; - vertex[i][0] = nodes[0]->vertex[j][0]; - vertex[i][1] = nodes[0]->vertex[j][1]; - vertex[i][2] = nodes[0]->vertex[j][2]; - uv[i][0] = nodes[0]->uv[j][0]; - uv[i][1] = nodes[0]->uv[j][1]; + vertex[i] = nodes[0]->vertex[j]; + uv[i] = nodes[0]->uv[j]; } return WallSceneNode::splitWall(_plane, vertex, uv, front, back); } @@ -420,11 +398,11 @@ bool QuadWallSceneNode::inAxisBox(const Extents& exts) const return false; // NOTE: inefficient - float vertices[4][3]; - memcpy (vertices[0], nodes[0]->getVertex(0), sizeof(float[3])); - memcpy (vertices[1], nodes[0]->getVertex(1), sizeof(float[3])); - memcpy (vertices[2], nodes[0]->getVertex(2), sizeof(float[3])); - memcpy (vertices[3], nodes[0]->getVertex(3), sizeof(float[3])); + glm::vec3 vertices[4]; + vertices[0] = nodes[0]->getVertex(0); + vertices[1] = nodes[0]->getVertex(1); + vertices[2] = nodes[0]->getVertex(2); + vertices[3] = nodes[0]->getVertex(3); return testPolygonInAxisBox (4, vertices, plane, exts); } @@ -434,7 +412,7 @@ int QuadWallSceneNode::getVertexCount () const return 4; } -const GLfloat* QuadWallSceneNode::getVertex (int vertex) const +const glm::vec3 &QuadWallSceneNode::getVertex (int vertex) const { // re-map these to a counter-clockwise order const int order[4] = {0, 1, 3, 2}; diff --git a/src/geometry/SceneNode.cxx b/src/geometry/SceneNode.cxx index 4a38348700..ed4dc6164b 100644 --- a/src/geometry/SceneNode.cxx +++ b/src/geometry/SceneNode.cxx @@ -16,6 +16,8 @@ // system implementation headers #include #include +#define GLM_ENABLE_EXPERIMENTAL +#include // common implementation headers #include "Extents.h" @@ -36,9 +38,8 @@ SceneNode::SceneNode() init = true; setColorOverride(false); } - memset(sphere, 0, sizeof(GLfloat) * 4); - setCenter(0.0f, 0.0f, 0.0f); + setCenter(glm::vec3(0.0f)); setRadius(0.0f); occluder = false; @@ -67,29 +68,12 @@ void SceneNode::setColorOverride(bool on) void SceneNode::setRadius(GLfloat radiusSquared) { - sphere[3] = radiusSquared; + radius2 = radiusSquared; } -void SceneNode::setCenter(const GLfloat center[3]) +void SceneNode::setCenter(const glm::vec3 &_center) { - sphere[0] = center[0]; - sphere[1] = center[1]; - sphere[2] = center[2]; -} - -void SceneNode::setCenter(GLfloat x, GLfloat y, GLfloat z) -{ - sphere[0] = x; - sphere[1] = y; - sphere[2] = z; -} - -void SceneNode::setSphere(const GLfloat _sphere[4]) -{ - sphere[0] = _sphere[0]; - sphere[1] = _sphere[1]; - sphere[2] = _sphere[2]; - sphere[3] = _sphere[3]; + sphere = _center; } void SceneNode::notifyStyleChange() @@ -112,15 +96,12 @@ void SceneNode::addLight(SceneRenderer&) // do nothing } -GLfloat SceneNode::getDistance(const GLfloat* eye) const +GLfloat SceneNode::getDistance(const glm::vec3 &eye) const { - return (eye[0] - sphere[0]) * (eye[0] - sphere[0]) + - (eye[1] - sphere[1]) * (eye[1] - sphere[1]) + - (eye[2] - sphere[2]) * (eye[2] - sphere[2]); + return glm::distance2(eye, sphere); } -int SceneNode::split(const float*, - SceneNode*&, SceneNode*&) const +int SceneNode::split(const glm::vec4 &, SceneNode*&, SceneNode*&) const { // can't split me return 1; @@ -131,19 +112,19 @@ bool SceneNode::cull(const ViewFrustum& view) const // if center of object is outside view frustum and distance is // greater than radius of object then cull. const int planeCount = view.getPlaneCount(); + const auto sphere4 = glm::vec4(sphere, 1.0f); for (int i = 0; i < planeCount; i++) { - const GLfloat* norm = view.getSide(i); - const GLfloat d = (sphere[0] * norm[0]) + - (sphere[1] * norm[1]) + - (sphere[2] * norm[2]) + norm[3]; - if ((d < 0.0f) && ((d * d) > sphere[3])) return true; + const auto norm = view.getSide(i); + const GLfloat d = glm::dot(sphere4, norm); + if ((d < 0.0f) && (d * d > radius2)) + return true; } return false; } -bool SceneNode::cullShadow(int, const float (*)[4]) const +bool SceneNode::cullShadow(int, const glm::vec4 []) const { // currently only used for dynamic nodes by ZSceneDatabase // we let the octree deal with the static nodes @@ -163,12 +144,13 @@ int SceneNode::getVertexCount () const return 0; } -const GLfloat* SceneNode::getVertex (int) const +const auto zeroVector = glm::vec3(0.0f); +const glm::vec3 &SceneNode::getVertex (int) const { - return NULL; + return zeroVector; } -const GLfloat* SceneNode::getPlane() const +const glm::vec4 *SceneNode::getPlane() const { return NULL; } diff --git a/src/geometry/SphereSceneNode.cxx b/src/geometry/SphereSceneNode.cxx index d74adf5c87..b910100559 100644 --- a/src/geometry/SphereSceneNode.cxx +++ b/src/geometry/SphereSceneNode.cxx @@ -15,6 +15,8 @@ // system headers #include +#define GLM_ENABLE_EXPERIMENTAL +#include // common implementation headers #include "SceneRenderer.h" @@ -33,7 +35,7 @@ // SphereSceneNode // -SphereSceneNode::SphereSceneNode(const GLfloat pos[3], GLfloat _radius) +SphereSceneNode::SphereSceneNode(const glm::vec3 &pos, GLfloat _radius) { transparent = false; @@ -58,25 +60,19 @@ SphereSceneNode::~SphereSceneNode() void SphereSceneNode::setColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a) { - color[0] = r; - color[1] = g; - color[2] = b; - color[3] = a; + color = glm::vec4(r, g, b, a); transparent = (color[3] != 1.0f); } -void SphereSceneNode::setColor(const GLfloat* rgba) +void SphereSceneNode::setColor(const glm::vec4 &rgba) { - color[0] = rgba[0]; - color[1] = rgba[1]; - color[2] = rgba[2]; - color[3] = rgba[3]; + color = rgba; transparent = (color[3] != 1.0f); } -void SphereSceneNode::move(const GLfloat pos[3], GLfloat _radius) +void SphereSceneNode::move(const glm::vec3 &pos, GLfloat _radius) { radius = _radius; setCenter(pos); @@ -220,7 +216,7 @@ void SphereLodSceneNode::kill() } -SphereLodSceneNode::SphereLodSceneNode(const GLfloat pos[3], GLfloat _radius) : +SphereLodSceneNode::SphereLodSceneNode(const glm::vec3 &pos, GLfloat _radius) : SphereSceneNode(pos, _radius), renderNode(this) { @@ -240,8 +236,8 @@ SphereLodSceneNode::SphereLodSceneNode(const GLfloat pos[3], GLfloat _radius) : OpenGLGStateBuilder builder(gstate); builder.setCulling(GL_BACK); builder.setShading(GL_SMOOTH); - const float spec[3] = {1.0f, 1.0f, 1.0f}; - const float emis[3] = {0.0f, 0.0f, 0.0f}; + const auto spec = glm::vec3(1.0f); + const auto emis = glm::vec3(0.0f); OpenGLMaterial glmat(spec, emis, 64.0f); builder.setMaterial(glmat); gstate = builder.getState(); @@ -273,13 +269,10 @@ void SphereLodSceneNode::setShockWave(bool value) void SphereLodSceneNode::addRenderNodes(SceneRenderer& renderer) { const ViewFrustum& view = renderer.getViewFrustum(); - const float* s = getSphere(); - const float* e = view.getEye(); - const float dx = e[0] - s[0]; - const float dy = e[1] - s[1]; - const float dz = e[2] - s[2]; + const auto &s = getSphere(); + const auto &e = view.getEye(); - float distSqr = (dx*dx) + (dy*dy) + (dz*dz); + float distSqr = glm::distance2(e, s); if (distSqr <= 0.0f) distSqr = 1.0e-6f; @@ -289,7 +282,8 @@ void SphereLodSceneNode::addRenderNodes(SceneRenderer& renderer) ppl = +MAXFLOAT; else ppl = 1.0f / lpp; - const float pixelsSqr = (s[3] * (ppl * ppl)) / distSqr; + const float r = getRadius2(); + const float pixelsSqr = (r * ppl * ppl) / distSqr; int lod; for (lod = 0; lod < (sphereLods - 1); lod++) @@ -299,7 +293,7 @@ void SphereLodSceneNode::addRenderNodes(SceneRenderer& renderer) } renderNode.setLod(lod); - inside = (distSqr < s[3]); + inside = (distSqr < r); renderer.addRenderNode(&renderNode, &gstate); @@ -330,7 +324,7 @@ SphereLodSceneNode::SphereLodRenderNode::~SphereLodRenderNode() return; } -const GLfloat* SphereLodSceneNode::SphereLodRenderNode::getPosition() const +const glm::vec3 &SphereLodSceneNode::SphereLodRenderNode::getPosition() const { return sceneNode->getSphere(); } @@ -362,7 +356,7 @@ static inline void drawFullScreenRect() void SphereLodSceneNode::SphereLodRenderNode::render() { const GLfloat radius = sceneNode->radius; - const GLfloat* sphere = sceneNode->getSphere(); + const auto &sphere = getPosition(); glEnable(GL_CLIP_PLANE0); @@ -473,7 +467,7 @@ void SphereLodSceneNode::SphereLodRenderNode::render() const int NumSlices = 2 * SphereRes; const int NumParts = SphereLowRes * SphereLowRes; -SphereBspSceneNode::SphereBspSceneNode(const GLfloat pos[3], GLfloat _radius) : +SphereBspSceneNode::SphereBspSceneNode(const glm::vec3 &pos, GLfloat _radius) : SphereSceneNode(pos, _radius), renderNode(this), parts(NULL) @@ -504,7 +498,7 @@ SceneNode** SphereBspSceneNode::getParts(int& numParts) // choose number of parts to cut off bottom at around ground level int i; - const GLfloat* mySphere = getSphere(); + const auto &mySphere = getSphere(); for (i = 0; i < SphereLowRes; i++) if (radius * SphereBspRenderNode::lgeom[SphereLowRes*i][2] + mySphere[2] < 0.01f) @@ -517,17 +511,17 @@ SceneNode** SphereBspSceneNode::getParts(int& numParts) void SphereBspSceneNode::addRenderNodes( SceneRenderer& renderer) { - const GLfloat* mySphere = getSphere(); + const float myRadius2 = getRadius2(); const ViewFrustum& view = renderer.getViewFrustum(); - const float size = mySphere[3] * view.getAreaFactor() / - getDistance(view.getEye()); + const auto &eye = view.getEye(); + const float size = myRadius2 * view.getAreaFactor() / getDistance(eye); const int lod = (size < 100.0f) ? 0 : 1; renderNode.setHighResolution(lod != 0); if (BZDBCache::blend) { - const GLfloat* eye = view.getEye(); + const auto &mySphere = getSphere(); const float azimuth = atan2f(mySphere[1] - eye[1], eye[0] - mySphere[0]); const int numSlices = (lod == 1) ? NumSlices : SphereLowRes; renderNode.setBaseIndex(int(float(numSlices) * @@ -551,10 +545,10 @@ void SphereBspSceneNode::addShadowNodes(SceneRenderer& UNUSED(rendere // SphereBspSceneNode::SphereBspRenderNode // -GLfloat SphereBspSceneNode::SphereBspRenderNode:: -geom[NumSlices * (SphereRes + 1)][3]; -GLfloat SphereBspSceneNode::SphereBspRenderNode:: -lgeom[SphereLowRes * (SphereLowRes + 1)][3]; +glm::vec3 SphereBspSceneNode::SphereBspRenderNode +::geom[NumSlices * (SphereRes + 1)]; +glm::vec3 SphereBspSceneNode::SphereBspRenderNode +::lgeom[SphereLowRes * (SphereLowRes + 1)]; SphereBspSceneNode::SphereBspRenderNode::SphereBspRenderNode( const SphereBspSceneNode* _sceneNode) : @@ -602,7 +596,7 @@ SphereBspSceneNode::SphereBspRenderNode::~SphereBspRenderNode() // do nothing } -const GLfloat* SphereBspSceneNode::SphereBspRenderNode::getPosition() const +const glm::vec3 &SphereBspSceneNode::SphereBspRenderNode::getPosition() const { return sceneNode->getSphere(); } @@ -623,7 +617,7 @@ void SphereBspSceneNode::SphereBspRenderNode::render() { int i, j; const GLfloat radius = sceneNode->radius; - const GLfloat* sphere = sceneNode->getSphere(); + const auto &sphere = getPosition(); glEnable(GL_CLIP_PLANE0); @@ -766,13 +760,12 @@ SphereFragmentSceneNode::~SphereFragmentSceneNode() void SphereFragmentSceneNode::move() { - const GLfloat* pSphere = parentSphere->getSphere(); + const auto &pSphere = parentSphere->getSphere(); const GLfloat pRadius = parentSphere->getRadius(); - const GLfloat* vertex = renderNode.getVertex(); - setCenter(pSphere[0] + pRadius * vertex[0], - pSphere[1] + pRadius * vertex[1], - pSphere[2] + pRadius * vertex[2]); - setRadius((GLfloat)(4.0 * M_PI * M_PI * pSphere[3]) / + const auto vertex = renderNode.getVertex(); + setCenter(pSphere + pRadius * vertex); + + setRadius((GLfloat)(4.0 * M_PI * M_PI * pRadius) / GLfloat(SphereLowRes * SphereLowRes)); } @@ -812,13 +805,13 @@ SphereFragmentSceneNode::FragmentRenderNode::~FragmentRenderNode() // do nothing } -const GLfloat* SphereFragmentSceneNode::FragmentRenderNode:: -getVertex() const +const glm::vec3 &SphereFragmentSceneNode::FragmentRenderNode::getVertex() const { - return SphereBspSceneNode::SphereBspRenderNode::lgeom[phi * SphereLowRes + theta]; + return SphereBspSceneNode::SphereBspRenderNode + ::lgeom[phi * SphereLowRes + theta]; } -const GLfloat* SphereFragmentSceneNode::FragmentRenderNode:: +const glm::vec3 &SphereFragmentSceneNode::FragmentRenderNode:: getPosition() const { return sceneNode->getSphere(); @@ -827,7 +820,7 @@ getPosition() const void SphereFragmentSceneNode::FragmentRenderNode::render() { const GLfloat pRadius = sceneNode->getRadius(); - const GLfloat* pSphere = sceneNode->getSphere(); + const auto &pSphere = getPosition(); glPushMatrix(); { diff --git a/src/geometry/TankGeometryMgr.cxx b/src/geometry/TankGeometryMgr.cxx index 77b5d532e7..d27f3d0190 100644 --- a/src/geometry/TankGeometryMgr.cxx +++ b/src/geometry/TankGeometryMgr.cxx @@ -47,7 +47,7 @@ static int partTriangles[LastTankShadow][LastTankLOD] [LastTankSize][LastTankPart]; // the scaling factors -static GLfloat scaleFactors[LastTankSize][3] = +static glm::vec3 scaleFactors[LastTankSize] = { {1.0f, 1.0f, 1.0f}, // Normal {1.0f, 1.0f, 1.0f}, // Obese @@ -56,7 +56,7 @@ static GLfloat scaleFactors[LastTankSize][3] = {1.0f, 1.0f, 1.0f} // Thief }; // the current scaling factors -static const float* currentScaleFactor = scaleFactors[Normal]; +static auto currentScaleFactor = scaleFactors[Normal]; // the current shadow mode (used to remove glNormal3f and glTexcoord2f calls) static TankShadow shadowMode = ShadowOn; @@ -301,7 +301,7 @@ int TankGeometryMgr::getPartTriangleCount(TankGeometryEnums::TankShadow sh, } -const float* TankGeometryMgr::getScaleFactor(TankSize size) +const glm::vec3 &TankGeometryMgr::getScaleFactor(TankSize size) { return scaleFactors[size]; } @@ -383,11 +383,9 @@ static void setupScales() void TankGeometryUtils::doVertex3f(GLfloat x, GLfloat y, GLfloat z) { - const float* scale = currentScaleFactor; - x = x * scale[0]; - y = y * scale[1]; - z = z * scale[2]; - glVertex3f(x, y, z); + const auto &scale = currentScaleFactor; + const auto xyz = glm::vec3(x, y, z) * scale; + glVertex3f(xyz.x, xyz.y, xyz.z); return; } @@ -396,18 +394,11 @@ void TankGeometryUtils::doNormal3f(GLfloat x, GLfloat y, GLfloat z) { if (shadowMode == ShadowOn) return; - const float* scale = currentScaleFactor; - GLfloat sx = x * scale[0]; - GLfloat sy = y * scale[1]; - GLfloat sz = z * scale[2]; - const GLfloat d = sqrtf ((sx * sx) + (sy * sy) + (sz * sz)); - if (d > 1.0e-5f) - { - x *= scale[0] / d; - y *= scale[1] / d; - z *= scale[2] / d; - } - glNormal3f(x, y, z); + const auto &scale = currentScaleFactor; + auto sxyz = glm::vec3(x, y, z) * scale; + if (sxyz.x || sxyz.y || sxyz.z) + sxyz = glm::normalize(sxyz); + glNormal3f(sxyz.x, sxyz.y, sxyz.z); return; } diff --git a/src/geometry/TankSceneNode.cxx b/src/geometry/TankSceneNode.cxx index c071e967e0..3a1c0f2cfc 100644 --- a/src/geometry/TankSceneNode.cxx +++ b/src/geometry/TankSceneNode.cxx @@ -16,11 +16,13 @@ // system headers #include #include +#include // common implementation headers #include "StateDatabase.h" #include "SceneRenderer.h" #include "BZDBCache.h" +#include "OpenGLAPI.h" // local implementation headers #include "ViewFrustum.h" @@ -41,7 +43,7 @@ static const float vertExplosionRatio = 0.5f; const int TankSceneNode::numLOD = 3; int TankSceneNode::maxLevel = numLOD; -TankSceneNode::TankSceneNode(const GLfloat pos[3], const GLfloat forward[3]) : +TankSceneNode::TankSceneNode(const glm::vec3 &pos, const glm::vec3 &forward) : leftTreadOffset(0.0f), rightTreadOffset(0.0f), leftWheelOffset(0.0f), rightWheelOffset(0.0f), useDimensions(false), onlyShadows(false), @@ -96,20 +98,14 @@ TankSceneNode::~TankSceneNode() void TankSceneNode::setColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a) { - color[0] = r; - color[1] = g; - color[2] = b; - color[3] = a; + color = glm::vec4(r, g, b, a); transparent = (color[3] != 1.0f); } -void TankSceneNode::setColor(const GLfloat* rgba) +void TankSceneNode::setColor(const glm::vec4 &rgba) { - color[0] = rgba[0]; - color[1] = rgba[1]; - color[2] = rgba[2]; - color[3] = rgba[3]; + color = rgba; transparent = (color[3] != 1.0f); } @@ -138,7 +134,7 @@ void TankSceneNode::setJumpJetsTexture(const int texture) } -void TankSceneNode::move(const GLfloat pos[3], const GLfloat forward[3]) +void TankSceneNode::move(const glm::vec3 &pos, const glm::vec3 &forward) { const float rad2deg = (float)(180.0 / M_PI); azimuth = rad2deg * atan2f(forward[1], forward[0]); @@ -223,10 +219,10 @@ void TankSceneNode::notifyStyleChange() void TankSceneNode::addRenderNodes(SceneRenderer& renderer) { // pick level of detail - const GLfloat* mySphere = getSphere(); + const float myRadius = getRadius2(); const ViewFrustum& view = renderer.getViewFrustum(); - const float size = mySphere[3] * - (view.getAreaFactor() /getDistance(view.getEye())); + const auto &eye = view.getEye(); + const float size = myRadius * (view.getAreaFactor() /getDistance(eye)); // set the level of detail TankLOD mode = LowTankLOD; @@ -254,20 +250,19 @@ void TankSceneNode::addRenderNodes(SceneRenderer& renderer) // if drawing in sorted order then decide which order if (sort || transparent || narrow) { - const GLfloat* eye = view.getEye(); - GLfloat dx = eye[0] - mySphere[0]; - GLfloat dy = eye[1] - mySphere[1]; + const auto &mySphere = getSphere(); + const auto d = eye - mySphere; const float radians = (float)(azimuth * M_PI / 180.0); const float cos_val = cosf(radians); const float sin_val = sinf(radians); - const float frontDot = (cos_val * dx) + (sin_val * dy); + const float frontDot = (cos_val * d.x) + (sin_val * d.y); const bool towards = (frontDot > 0.0f); - const float leftDot = (-sin_val * dx) + (cos_val * dy); + const float leftDot = (-sin_val * d.x) + (cos_val * d.y); const bool left = (leftDot > 0.0f); - const bool above = eye[2] > mySphere[2]; + const bool above = d.z > 0.0f; tankRenderNode.sortOrder(above, towards, left); } @@ -365,10 +360,10 @@ void TankSceneNode::setThief() } -void TankSceneNode::setDimensions(const float dims[3]) +void TankSceneNode::setDimensions(const glm::vec3 &dims) { tankSize = Normal; - memcpy(dimensions, dims, sizeof(float[3])); + dimensions = dims; useDimensions = true; return; } @@ -379,7 +374,7 @@ void TankSceneNode::setExplodeFraction(float t) explodeFraction = t; if (t != 0.0f) { - const float radius = sqrtf(getSphere()[3]); + const float radius = sqrtf(getRadius2()); const float radinc = t * maxExplosionVel; const float newrad = radius + radinc; setRadius(newrad * newrad); @@ -397,26 +392,27 @@ void TankSceneNode::setJumpJets(float scale) jumpJetsScale = scale; // set the real light's position - const float* pos = getSphere(); + const auto &pos = getSphere(); jumpJetsRealLight.setPosition(pos); // set the jet ground-light and model positions + const float radians = (float)(azimuth * (M_PI / 180.0)); + const float cos_val = cosf(radians); + const float sin_val = sinf(radians); + const auto &scaleFactor = TankGeometryMgr::getScaleFactor(tankSize); for (int i = 0; i < 4; i++) { - const float radians = (float)(azimuth * (M_PI / 180.0)); - const float cos_val = cosf(radians); - const float sin_val = sinf(radians); - const float* scaleFactor = TankGeometryMgr::getScaleFactor(tankSize); - const float* jm = jumpJetsModel[i]; + const auto &jm = jumpJetsModel[i]; const float v[2] = {jm[0] * scaleFactor[0], jm[1] * scaleFactor[1]}; - float* jetPos = jumpJetsPositions[i]; - jetPos[0] = pos[0] + ((cos_val * v[0]) - (sin_val * v[1])); - jetPos[1] = pos[1] + ((cos_val * v[1]) + (sin_val * v[0])); - jetPos[2] = pos[2] + jm[2]; + auto &jetPos = jumpJetsPositions[i]; + jetPos = pos; + jetPos[0] += cos_val * v[0] - sin_val * v[1]; + jetPos[1] += cos_val * v[1] + sin_val * v[0]; + jetPos[2] += jm[2]; jumpJetsGroundLights[i].setPosition(jetPos); // setup the random lengths - const float randomFactor = (1.0f - (0.5f * (0.5f - (float)bzfrand()))); + const float randomFactor = glm::linearRand(0.75f, 1.25f); jumpJetsLengths[i] = jumpJetsScale * randomFactor; } } @@ -424,13 +420,10 @@ void TankSceneNode::setJumpJets(float scale) } -void TankSceneNode::setClipPlane(const float _plane[4]) +void TankSceneNode::setClipPlane(const glm::vec4 &_plane) { clip = true; - clipPlane[0] = GLdouble(_plane[0]); - clipPlane[1] = GLdouble(_plane[1]); - clipPlane[2] = GLdouble(_plane[2]); - clipPlane[3] = GLdouble(_plane[3]); + clipPlane = _plane; } @@ -464,24 +457,22 @@ void TankSceneNode::setInTheCockpit(bool value) void TankSceneNode::rebuildExplosion() { // prepare explosion rotations and translations + const auto maxSpin = glm::vec3(0.5f); for (int i = 0; i < LastTankPart; i++) { // pick an unbiased rotation vector + glm::vec3 spinVect; GLfloat d; do { - spin[i][0] = (float)bzfrand() - 0.5f; - spin[i][1] = (float)bzfrand() - 0.5f; - spin[i][2] = (float)bzfrand() - 0.5f; - d = hypotf(spin[i][0], hypotf(spin[i][1], spin[i][2])); + spinVect = glm::linearRand(-maxSpin, maxSpin); + d = glm::length(spinVect); } while (d < 0.001f || d > 0.5f); - spin[i][0] /= d; - spin[i][1] /= d; - spin[i][2] /= d; + spinVect /= d; // now an angular velocity -- make sure we get at least 2 complete turns - spin[i][3] = 360.0f * (5.0f * (float)bzfrand() + 2.0f); + spin[i] = glm::vec4(spinVect, 360.0f * glm::linearRand(2.0f, 7.0f)); // cheezy spheroid explosion pattern const float vhMax = maxExplosionVel; @@ -502,25 +493,19 @@ void TankSceneNode::rebuildExplosion() void TankSceneNode::renderRadar() { const float angleCopy = azimuth; - const float* mySphere = getSphere(); - float posCopy[3]; - memcpy(posCopy, mySphere, sizeof(float[3])); + const auto &mySphere = getSphere(); + auto posCopy = mySphere; // allow negative values for burrowed clipping - float tankPos[3]; - tankPos[0] = 0.0f; - tankPos[1] = 0.0f; - if (mySphere[2] >= 0.0f) - tankPos[2] = 0.0f; - else + auto tankPos = glm::vec3(0.0f); + if (mySphere[2] < 0.0f) tankPos[2] = mySphere[2]; setCenter(tankPos); azimuth = 0.0f; float oldAlpha = color[3]; - if (color[3] < 0.15f) - color[3] = 0.15f; + color[3] = std::max(color[3], 0.15f); if (BZDBCache::animatedTreads) { @@ -546,14 +531,15 @@ void TankSceneNode::renderRadar() } -bool TankSceneNode::cullShadow(int planeCount, const float (*planes)[4]) const +bool TankSceneNode::cullShadow(int planeCount, const glm::vec4 *planes) const { - const float* s = getSphere(); + const auto s = glm::vec4(getSphere(), 1.0f); + const float r = getRadius2(); for (int i = 0; i < planeCount; i++) { - const float* p = planes[i]; - const float d = (p[0] * s[0]) + (p[1] * s[1]) + (p[2] * s[2]) + p[3]; - if ((d < 0.0f) && ((d * d) > s[3])) + const auto &p = planes[i]; + const float d = glm::dot(p, s); + if ((d < 0.0f) && (d * d > r)) return true; } return false; @@ -568,7 +554,7 @@ TankIDLSceneNode::TankIDLSceneNode(const TankSceneNode* _tank) : tank(_tank), renderNode(this) { - static const GLfloat defaultPlane[4] = { 1.0f, 0.0f, 0.0f, 0.0f }; + static const auto defaultPlane = glm::vec4(1.0f, 0.0f, 0.0f, 0.0f); move(defaultPlane); float radius = BZDBCache::tankLength; radius = radius * 4.0f; @@ -590,18 +576,13 @@ TankIDLSceneNode::~TankIDLSceneNode() } -void TankIDLSceneNode::move(const GLfloat _plane[4]) +void TankIDLSceneNode::move(const glm::vec4 &_plane) { - plane[0] = _plane[0]; - plane[1] = _plane[1]; - plane[2] = _plane[2]; - plane[3] = _plane[3]; + plane = _plane; // compute new sphere - const GLfloat* s = tank->getSphere(); - setCenter(s[0] + 1.5f * BZDBCache::tankLength * plane[0], - s[1] + 1.5f * BZDBCache::tankLength * plane[1], - s[2] + 1.5f * BZDBCache::tankLength * plane[2]); + const auto &s = tank->getSphere(); + setCenter(s + 1.5f * BZDBCache::tankLength * glm::vec3(plane)); return; } @@ -669,7 +650,7 @@ const int TankIDLSceneNode::IDLRenderNode::idlFaces[][5] = { 4, 37, 36, 38, 32 } }; -const GLfloat TankIDLSceneNode::IDLRenderNode::idlVertex[][3] = +const glm::vec3 TankIDLSceneNode::IDLRenderNode::idlVertex[] = { // body { 2.430f, 0.877f, 0.000f }, @@ -734,38 +715,34 @@ TankIDLSceneNode::IDLRenderNode::~IDLRenderNode() return; } -const GLfloat* TankIDLSceneNode::IDLRenderNode::getPosition() const +const glm::vec3 &TankIDLSceneNode::IDLRenderNode::getPosition() const { return sceneNode->getSphere(); } void TankIDLSceneNode::IDLRenderNode::render() { - static const GLfloat innerColor[4] = { 1.0f, 1.0f, 1.0f, 0.75f }; - static const GLfloat outerColor[4] = { 1.0f, 1.0f, 1.0f, 0.0f }; + static const auto innerColor = glm::vec4(1.0f, 1.0f, 1.0f, 0.75f); + static const auto outerColor = glm::vec4(1.0f, 1.0f, 1.0f, 0.0f); // compute plane in tank's space - const GLfloat* sphere = sceneNode->tank->getSphere(); - const GLfloat* _plane = sceneNode->plane; + const auto sphere = glm::vec4(sceneNode->tank->getSphere(), 1.0f); + const auto &_plane = sceneNode->plane; const GLfloat azimuth = sceneNode->tank->azimuth; const GLfloat ca = cosf(-azimuth * (float)M_PI / 180.0f); const GLfloat sa = sinf(-azimuth * (float)M_PI / 180.0f); - GLfloat tankPlane[4]; + glm::vec4 tankPlane; tankPlane[0] = ca * _plane[0] - sa * _plane[1]; tankPlane[1] = sa * _plane[0] + ca * _plane[1]; tankPlane[2] = _plane[2]; - tankPlane[3] = (sphere[0] * _plane[0] + sphere[1] * _plane[1] + - sphere[2] * _plane[2] + _plane[3]); + tankPlane[3] = glm::dot(sphere, _plane); // compute projection point -- one TankLength in from tankPlane const GLfloat pd = -1.0f * BZDBCache::tankLength - tankPlane[3]; - GLfloat origin[3]; - origin[0] = pd * tankPlane[0]; - origin[1] = pd * tankPlane[1]; - origin[2] = pd * tankPlane[2]; + auto origin = pd * glm::vec3(tankPlane); glPushMatrix(); - glTranslatef(sphere[0], sphere[1], sphere[2]); + glTranslate(sphere); glRotatef(azimuth, 0.0f, 0.0f, 1.0f); const int numFaces = bzcountof(idlFaces); @@ -777,25 +754,23 @@ void TankIDLSceneNode::IDLRenderNode::render() GLfloat d[4]; int j; for (j = 0; j < numVertices; j++) - d[j] = idlVertex[face[j]][0] * tankPlane[0] + - idlVertex[face[j]][1] * tankPlane[1] + - idlVertex[face[j]][2] * tankPlane[2] + - tankPlane[3]; + { + const auto v = glm::vec4(idlVertex[face[j]], 1.0f); + d[j] = glm::dot(v, tankPlane); + } // get crossing points - GLfloat cross[2][3]; + glm::vec3 cross[2]; int crossings = 0, k; for (j = 0, k = numVertices-1; j < numVertices; k = j++) { if ((d[k] < 0.0f && d[j] >= 0.0f) || (d[k] >= 0.0f && d[j] < 0.0f)) { const GLfloat t = d[k] / (d[k] - d[j]); - cross[crossings][0] = (1.0f - t) * idlVertex[face[k]][0] + - t * idlVertex[face[j]][0]; - cross[crossings][1] = (1.0f - t) * idlVertex[face[k]][1] + - t * idlVertex[face[j]][1]; - cross[crossings][2] = (1.0f - t) * idlVertex[face[k]][2] + - t * idlVertex[face[j]][2]; + cross[crossings] = glm::mix( + idlVertex[face[k]], + idlVertex[face[j]], + t); if (++crossings == 2) break; } } @@ -804,23 +779,19 @@ void TankIDLSceneNode::IDLRenderNode::render() if (crossings != 2) continue; // project points out - GLfloat project[2][3]; - const GLfloat dist = 2.0f + 0.3f * ((float)bzfrand() - 0.5f); - project[0][0] = origin[0] + dist * (cross[0][0] - origin[0]); - project[0][1] = origin[1] + dist * (cross[0][1] - origin[1]); - project[0][2] = origin[2] + dist * (cross[0][2] - origin[2]); - project[1][0] = origin[0] + dist * (cross[1][0] - origin[0]); - project[1][1] = origin[1] + dist * (cross[1][1] - origin[1]); - project[1][2] = origin[2] + dist * (cross[1][2] - origin[2]); + glm::vec3 project[2]; + const GLfloat dist = glm::linearRand(1.85f, 2.15f); + project[0] = glm::mix(origin, cross[0], dist); + project[1] = glm::mix(origin, cross[1], dist); // draw it glBegin(GL_TRIANGLE_STRIP); myColor4fv(innerColor); - glVertex3fv(cross[0]); - glVertex3fv(cross[1]); + glVertex(cross[0]); + glVertex(cross[1]); myColor4fv(outerColor); - glVertex3fv(project[0]); - glVertex3fv(project[1]); + glVertex(project[0]); + glVertex(project[1]); glEnd(); } @@ -833,8 +804,8 @@ void TankIDLSceneNode::IDLRenderNode::render() // TankSceneNode::TankRenderNode // -const GLfloat // FIXME: setup so these come from TANKGEOMMGR -TankSceneNode::TankRenderNode::centerOfGravity[LastTankPart][3] = +const glm::vec3 // FIXME: setup so these come from TANKGEOMMGR +TankSceneNode::TankRenderNode::centerOfGravity[LastTankPart] = { { 0.000f, 0.0f, 1.5f * 0.68f }, // body { 3.252f, 0.0f, 1.532f }, // barrel @@ -872,7 +843,7 @@ TankSceneNode::TankRenderNode::~TankRenderNode() return; } -const GLfloat* TankSceneNode::TankRenderNode::getPosition() const +const glm::vec3 &TankSceneNode::TankRenderNode::getPosition() const { return sceneNode->getSphere(); } @@ -939,7 +910,7 @@ void TankSceneNode::TankRenderNode::render() explodeFraction = sceneNode->explodeFraction; isExploding = (explodeFraction != 0.0f); - color = sceneNode->color; + color = &sceneNode->color; alpha = sceneNode->color[3]; if (!BZDBCache::blend && sceneNode->transparent) @@ -951,17 +922,17 @@ void TankSceneNode::TankRenderNode::render() glEnable(GL_CLIP_PLANE1); } - const GLfloat* sphere = sceneNode->getSphere(); + const auto &sphere = getPosition(); // save the MODELVIEW matrix glPushMatrix(); - glTranslatef(sphere[0], sphere[1], sphere[2]); + glTranslate(sphere); glRotatef(sceneNode->azimuth, 0.0f, 0.0f, 1.0f); glRotatef(sceneNode->elevation, 0.0f, 1.0f, 0.0f); if (sceneNode->useDimensions) { - const float* dims = sceneNode->dimensions; + const auto &dims = sceneNode->dimensions; glScalef(dims[0], dims[1], dims[2]); glEnable(GL_NORMALIZE); } @@ -1212,21 +1183,19 @@ void TankSceneNode::TankRenderNode::renderPart(TankPart part) } // apply explosion transform - TankDeathOverride::DeathParams params(explodeFraction,fvec4(color[0],color[1],color[2],color[3])); + TankDeathOverride::DeathParams params(explodeFraction, *color); if (isExploding) { glPushMatrix(); - const float* cog = centerOfGravity[part]; + const auto &cog = centerOfGravity[part]; if (sceneNode->deathOverride) sceneNode->deathOverride->SetDeathRenderParams(params); - const float* velocity = sceneNode->vel[part]; - const float* rotation = sceneNode->spin[part]; - glTranslatef(cog[0] + (explodeFraction * velocity[0]), - cog[1] + (explodeFraction * velocity[1]), - cog[2] + (explodeFraction * velocity[2])); + const auto &velocity = sceneNode->vel[part]; + const auto &rotation = sceneNode->spin[part]; + glTranslate(cog + explodeFraction * velocity); glRotatef(rotation[3] * explodeFraction, rotation[0], rotation[1], rotation[2]); - glTranslatef(-cog[0], -cog[1], -cog[2]); + glTranslate(-cog); } // setup the animation texture matrix @@ -1272,18 +1241,18 @@ void TankSceneNode::TankRenderNode::renderPart(TankPart part) void TankSceneNode::TankRenderNode::setupPartColor(TankPart part) { - const GLfloat white[4] = {1.0f, 1.0f, 1.0f, 1.0f}; - const GLfloat* clr = color; + const auto white = glm::vec4(1.0f); + auto clr = color; // do not use color modulation with tank textures if (BZDBCache::texture) - clr = white; + clr = &white; switch (part) { case Body: { - myColor4f(clr[0], clr[1], clr[2], alpha); + myColor4f(clr->r, clr->g, clr->b, alpha); break; } case Barrel: @@ -1293,19 +1262,19 @@ void TankSceneNode::TankRenderNode::setupPartColor(TankPart part) } case Turret: { - myColor4f(0.9f * clr[0], 0.9f * clr[1], 0.9f * clr[2], alpha); + myColor4f(0.9f * clr->r, 0.9f * clr->g, 0.9f * clr->b, alpha); break; } case LeftCasing: case RightCasing: { - myColor4f(0.7f * clr[0], 0.7f * clr[1], 0.7f * clr[2], alpha); + myColor4f(0.7f * clr->r, 0.7f * clr->g, 0.7f * clr->b, alpha); break; } case LeftTread: case RightTread: { - myColor4f(0.3f * clr[0], 0.3f * clr[1], 0.3f * clr[2], alpha); + myColor4f(0.3f * clr->r, 0.3f * clr->g, 0.3f * clr->b, alpha); break; } case LeftWheel0: @@ -1317,7 +1286,7 @@ void TankSceneNode::TankRenderNode::setupPartColor(TankPart part) case RightWheel2: case RightWheel3: { - myColor4f(0.4f * clr[0], 0.4f * clr[1], 0.4f * clr[2], alpha); + myColor4f(0.4f * clr->r, 0.4f * clr->g, 0.4f * clr->b, alpha); break; } default: // avoid warnings about unused enumerated values @@ -1390,31 +1359,32 @@ bool TankSceneNode::TankRenderNode::setupTextureMatrix(TankPart part) void TankSceneNode::TankRenderNode::renderLights() { - static const GLfloat lights[3][6] = + static const glm::vec3 lights[3] = { - { 1.0f, 1.0f, 1.0f, -1.53f, 0.00f, 2.1f }, - { 1.0f, 0.0f, 0.0f, 0.10f, 0.75f, 2.1f }, - { 0.0f, 1.0f, 0.0f, 0.10f, -0.75f, 2.1f } + { 1.0f, 1.0f, 1.0f }, + { 1.0f, 0.0f, 0.0f }, + { 0.0f, 1.0f, 0.0f } + }; + static const glm::vec3 lightsPos[3] = + { + { -1.53f, 0.00f, 2.1f }, + { 0.10f, 0.75f, 2.1f }, + { 0.10f, -0.75f, 2.1f } }; sceneNode->lightsGState.setState(); glPointSize(2.0f); glBegin(GL_POINTS); { - const float* scale = TankGeometryMgr::getScaleFactor(sceneNode->tankSize); - - myColor3fv(lights[0]); - glVertex3f(lights[0][3] * scale[0], - lights[0][4] * scale[1], - lights[0][5] * scale[2]); - myColor3fv(lights[1]); - glVertex3f(lights[1][3] * scale[0], - lights[1][4] * scale[1], - lights[1][5] * scale[2]); - myColor3fv(lights[2]); - glVertex3f(lights[2][3] * scale[0], - lights[2][4] * scale[1], - lights[2][5] * scale[2]); + const auto &scale + = TankGeometryMgr::getScaleFactor(sceneNode->tankSize); + + for (int i = 0; i < 3; i++) + { + const auto pos = lightsPos[i] * scale; + myColor3fv(lights[i]); + glVertex(pos); + } } glEnd(); @@ -1427,7 +1397,7 @@ void TankSceneNode::TankRenderNode::renderLights() } -GLfloat TankSceneNode::jumpJetsModel[4][3] = +glm::vec3 TankSceneNode::jumpJetsModel[4] = { {-1.5f, -0.6f, +0.25f}, {-1.5f, +0.6f, +0.25f}, @@ -1442,8 +1412,8 @@ void TankSceneNode::TankRenderNode::renderJumpJets() typedef struct { - GLfloat vertex[3]; - GLfloat texcoord[2]; + glm::vec3 vertex; + glm::vec2 texcoord; } jetVertex; static const jetVertex jet[3] = { @@ -1463,8 +1433,8 @@ void TankSceneNode::TankRenderNode::renderJumpJets() { glPushMatrix(); { - const float* pos = sceneNode->jumpJetsPositions[j]; - glTranslatef(pos[0], pos[1], pos[2]); + const auto &pos = sceneNode->jumpJetsPositions[j]; + glTranslate(pos); glScalef(1.0f, 1.0f, sceneNode->jumpJetsLengths[j]); RENDERER.getViewFrustum().executeBillboard(); diff --git a/src/geometry/TriWallSceneNode.cxx b/src/geometry/TriWallSceneNode.cxx index cc0f008b08..6243046a08 100644 --- a/src/geometry/TriWallSceneNode.cxx +++ b/src/geometry/TriWallSceneNode.cxx @@ -16,6 +16,9 @@ // system headers #include #include +#include +#define GLM_ENABLE_EXPERIMENTAL +#include // common implementation headers #include "Intersect.h" @@ -28,10 +31,11 @@ // TriWallSceneNode::Geometry // -TriWallSceneNode::Geometry::Geometry(TriWallSceneNode* _wall, int eCount, - const GLfloat base[3], const GLfloat uEdge[3], const GLfloat vEdge[3], - const GLfloat* _normal, float uRepeats, float vRepeats) : - wall(_wall), style(0), de(eCount), normal(_normal), +TriWallSceneNode::Geometry::Geometry( + TriWallSceneNode* _wall, int eCount, + const glm::vec3 &base, const glm::vec3 &uEdge, const glm::vec3 &vEdge, + const glm::vec4 &_plane, float uRepeats, float vRepeats) : + wall(_wall), style(0), de(eCount), plane(_plane), vertex((eCount+1) * (eCount+2) / 2), uv((eCount+1) * (eCount+2) / 2) { @@ -42,47 +46,36 @@ TriWallSceneNode::Geometry::Geometry(TriWallSceneNode* _wall, int eCount, for (int i = 0; i <= k; n++, i++) { const float s = (float)i / (float)eCount; - vertex[n][0] = base[0] + s * uEdge[0] + t * vEdge[0]; - vertex[n][1] = base[1] + s * uEdge[1] + t * vEdge[1]; - vertex[n][2] = base[2] + s * uEdge[2] + t * vEdge[2]; - uv[n][0] = 0.0f + s * uRepeats; - uv[n][1] = 0.0f + t * vRepeats; + const auto v = base + s * uEdge + t * vEdge; + vertex[n] = v; + uv[n] = glm::vec2(s * uRepeats, t * vRepeats); } } if (BZDB.isTrue("remapTexCoords")) { - const float uLen = sqrtf((uEdge[0] * uEdge[0]) + - (uEdge[1] * uEdge[1]) + - (uEdge[2] * uEdge[2])); - const float vLen = sqrtf((vEdge[0] * vEdge[0]) + - (vEdge[1] * vEdge[1]) + - (vEdge[2] * vEdge[2])); + const float uLen = glm::length(uEdge); + const float vLen = glm::length(vEdge); const float uScale = 10.0f / floorf(10.0f * uLen / uRepeats); const float vScale = 10.0f / floorf(10.0f * vLen / vRepeats); - if (fabsf(normal[2]) > 0.999f) + const auto scale = glm::vec2(uScale, vScale); + if (fabsf(plane[2]) > 0.999f) { // horizontal surface - for (int i = 0; i < vertex.getSize(); i++) - { - uv[i][0] = uScale * vertex[i][0]; - uv[i][1] = vScale * vertex[i][1]; - } + for (unsigned int i = 0; i < vertex.size(); i++) + uv[i] = scale * glm::vec2(vertex[i]); } else { // vertical surface - const float nh = sqrtf((normal[0] * normal[0]) + (normal[1] * normal[1])); - const float nx = normal[0] / nh; - const float ny = normal[1] / nh; - const float vs = 1.0f / sqrtf(1.0f - (normal[2] * normal[2])); - for (int i = 0; i < vertex.getSize(); i++) + const auto n = glm::normalize(glm::vec2(plane)); + const float vs = glm::inversesqrt(1.0f - (plane[2] * plane[2])); + for (unsigned int i = 0; i < vertex.size(); i++) { - const float* v = vertex[i]; - const float uGeoScale = (nx * v[1]) - (ny * v[0]); + const auto v = vertex[i]; + const float uGeoScale = n.x * v[1] - n.y * v[0]; const float vGeoScale = v[2] * vs; - uv[i][0] = uScale * uGeoScale; - uv[i][1] = vScale * vGeoScale; + uv[i] = scale * glm::vec2(uGeoScale, vGeoScale); } } } @@ -112,7 +105,7 @@ TriWallSceneNode::Geometry::~Geometry() #define EMITV(_i) glVertex3fv(vertex[_i]) #define EMITVT(_i) glTexCoord2fv(uv[_i]); glVertex3fv(vertex[_i]) -const GLfloat* TriWallSceneNode::Geometry::getPosition() const +const glm::vec3 &TriWallSceneNode::Geometry::getPosition() const { return wall->getSphere(); } @@ -120,7 +113,7 @@ const GLfloat* TriWallSceneNode::Geometry::getPosition() const void TriWallSceneNode::Geometry::render() { wall->setColor(); - glNormal3fv(normal); + glNormal3fv(plane); if (style >= 2) drawVT(); else @@ -152,7 +145,7 @@ void TriWallSceneNode::Geometry::drawVT() const } -const GLfloat* TriWallSceneNode::Geometry::getVertex(int i) const +const glm::vec3 &TriWallSceneNode::Geometry::getVertex(int i) const { return vertex[i]; } @@ -162,41 +155,32 @@ const GLfloat* TriWallSceneNode::Geometry::getVertex(int i) const // TriWallSceneNode // -TriWallSceneNode::TriWallSceneNode(const GLfloat base[3], - const GLfloat uEdge[3], - const GLfloat vEdge[3], +TriWallSceneNode::TriWallSceneNode(const glm::vec3 &base, + const glm::vec3 &uEdge, + const glm::vec3 &vEdge, float uRepeats, float vRepeats, bool makeLODs) { // record plane info - GLfloat myPlane[4], mySphere[4]; - myPlane[0] = uEdge[1] * vEdge[2] - uEdge[2] * vEdge[1]; - myPlane[1] = uEdge[2] * vEdge[0] - uEdge[0] * vEdge[2]; - myPlane[2] = uEdge[0] * vEdge[1] - uEdge[1] * vEdge[0]; - myPlane[3] = -(myPlane[0] * base[0] + myPlane[1] * base[1] - + myPlane[2] * base[2]); + const auto normal = glm::cross(uEdge, vEdge); + auto myPlane = glm::vec4(normal, -glm::dot(normal, base)); setPlane(myPlane); // record bounding sphere info -- ought to calculate center and // and radius of circumscribing sphere but it's late and i'm tired. // i'll just calculate something easy. it hardly matters as it's // hard to tightly bound a triangle with a sphere. - mySphere[0] = 0.5f * (uEdge[0] + vEdge[0]); - mySphere[1] = 0.5f * (uEdge[1] + vEdge[1]); - mySphere[2] = 0.5f * (uEdge[2] + vEdge[2]); - mySphere[3] = mySphere[0]*mySphere[0] + mySphere[1]*mySphere[1] - + mySphere[2]*mySphere[2]; - mySphere[0] += base[0]; - mySphere[1] += base[1]; - mySphere[2] += base[2]; - setSphere(mySphere); + auto mySphere = 0.5f * (uEdge + vEdge); + + setRadius(glm::length2(mySphere)); + + mySphere += base; + setCenter(mySphere); // get length of sides - const float uLength = sqrtf(uEdge[0] * uEdge[0] + - uEdge[1] * uEdge[1] + uEdge[2] * uEdge[2]); - const float vLength = sqrtf(vEdge[0] * vEdge[0] + - vEdge[1] * vEdge[1] + vEdge[2] * vEdge[2]); + const float uLength = glm::length(uEdge); + const float vLength = glm::length(vEdge); float area = 0.5f * uLength * vLength; // If negative then these values aren't a number of times to repeat @@ -216,7 +200,7 @@ TriWallSceneNode::TriWallSceneNode(const GLfloat base[3], int uLevels = 1, vLevels = 1; while (uElements >>= 1) uLevels++; while (vElements >>= 1) vLevels++; - int numLevels = (uLevels > vLevels ? uLevels : vLevels); + int numLevels = std::max(uLevels, vLevels); // if no lod's required then don't make any except most coarse if (!makeLODs) @@ -249,7 +233,7 @@ TriWallSceneNode::TriWallSceneNode(const GLfloat base[3], // record extents info for (int i = 0; i < 3; i++) { - const float* point = getVertex(i); + const auto point = getVertex(i); extents.expandToPoint(point); } @@ -272,9 +256,8 @@ TriWallSceneNode::~TriWallSceneNode() bool TriWallSceneNode::cull(const ViewFrustum& frustum) const { // cull if eye is behind (or on) plane - const GLfloat* eye = frustum.getEye(); - if (((eye[0] * plane[0]) + (eye[1] * plane[1]) + (eye[2] * plane[2]) + - plane[3]) <= 0.0f) + const auto eye = glm::vec4(frustum.getEye(), 1.0f); + if (glm::dot(eye, plane) <= 0.0f) return true; // if the Visibility culler tells us that we're @@ -291,7 +274,7 @@ bool TriWallSceneNode::cull(const ViewFrustum& frustum) const } -int TriWallSceneNode::split(const float* _plane, +int TriWallSceneNode::split(const glm::vec4 &_plane, SceneNode*& front, SceneNode*& back) const { return WallSceneNode::splitWall(_plane, nodes[0]->vertex, nodes[0]->uv, @@ -321,10 +304,10 @@ bool TriWallSceneNode::inAxisBox(const Extents& exts) const return false; // NOTE: inefficient - float vertices[3][3]; - memcpy (vertices[0], nodes[0]->getVertex(0), sizeof(float[3])); - memcpy (vertices[1], nodes[0]->getVertex(1), sizeof(float[3])); - memcpy (vertices[2], nodes[0]->getVertex(2), sizeof(float[3])); + glm::vec3 vertices[3]; + vertices[0] = nodes[0]->getVertex(0); + vertices[1] = nodes[0]->getVertex(1); + vertices[2] = nodes[0]->getVertex(2); return testPolygonInAxisBox (3, vertices, plane, exts); } @@ -336,7 +319,7 @@ int TriWallSceneNode::getVertexCount () const } -const GLfloat* TriWallSceneNode::getVertex (int vertex) const +const glm::vec3 &TriWallSceneNode::getVertex (int vertex) const { return nodes[0]->getVertex(vertex); } diff --git a/src/geometry/ViewFrustum.cxx b/src/geometry/ViewFrustum.cxx index 4b34ea4208..d03130f6fb 100644 --- a/src/geometry/ViewFrustum.cxx +++ b/src/geometry/ViewFrustum.cxx @@ -15,6 +15,7 @@ // common implementation headers #include "bzfgl.h" +#include "OpenGLAPI.h" ViewFrustum::ViewFrustum() { @@ -28,31 +29,31 @@ ViewFrustum::~ViewFrustum() void ViewFrustum::executeProjection() const { glMatrixMode(GL_PROJECTION); - glLoadMatrixf(projectionMatrix); + glLoadMatrix(projectionMatrix); glMatrixMode(GL_MODELVIEW); } void ViewFrustum::executeDeepProjection() const { glMatrixMode(GL_PROJECTION); - glLoadMatrixf(deepProjectionMatrix); + glLoadMatrix(deepProjectionMatrix); glMatrixMode(GL_MODELVIEW); } void ViewFrustum::executeView() const { - glMultMatrixf(viewMatrix); + glMultMatrix(viewMatrix); } void ViewFrustum::executeOrientation() const { - glMultMatrixf(viewMatrix); + glMultMatrix(viewMatrix); glTranslatef(eye[0], eye[1], eye[2]); } void ViewFrustum::executeBillboard() const { - glMultMatrixf(billboardMatrix); + glMultMatrix(billboardMatrix); } // Local Variables: *** diff --git a/src/geometry/WallSceneNode.cxx b/src/geometry/WallSceneNode.cxx index 8892f051f6..f72e3c8749 100644 --- a/src/geometry/WallSceneNode.cxx +++ b/src/geometry/WallSceneNode.cxx @@ -19,6 +19,8 @@ #include #include #include +#define GLM_ENABLE_EXPERIMENTAL +#include // common implementation headers #include "StateDatabase.h" @@ -36,13 +38,6 @@ WallSceneNode::WallSceneNode() : numLODs(0), style(0) { dynamicColor = NULL; - color[3] = 1.0f; - modulateColor[3] = 1.0f; - lightedColor[3] = 1.0f; - lightedModulateColor[3] = 1.0f; - color[3] = 1.0f; - color[3] = 1.0f; - color[3] = 1.0f; setColor(1.0f, 1.0f, 1.0f); setModulateColor(1.0f, 1.0f, 1.0f); setLightedColor(1.0f, 1.0f, 1.0f); @@ -63,9 +58,9 @@ WallSceneNode::~WallSceneNode() delete[] elementAreas; } -const GLfloat* WallSceneNode::getPlane() const +const glm::vec4 *WallSceneNode::getPlane() const { - return plane; + return &plane; } void WallSceneNode::setNumLODs(int num, float* areas) @@ -74,26 +69,19 @@ void WallSceneNode::setNumLODs(int num, float* areas) elementAreas = areas; } -void WallSceneNode::setPlane(const GLfloat _plane[4]) +void WallSceneNode::setPlane(const glm::vec4 &_plane) { - const float n = bzInverseSqrt(_plane[0] * _plane[0] + - _plane[1] * _plane[1] + - _plane[2] * _plane[2]); + const float n = bzInverseSqrt(glm::length2(glm::vec3(_plane))); // store normalized plane equation - plane[0] = n * _plane[0]; - plane[1] = n * _plane[1]; - plane[2] = n * _plane[2]; - plane[3] = n * _plane[3]; + plane = n * _plane; } bool WallSceneNode::cull(const ViewFrustum& frustum) const { // cull if eye is behind (or on) plane - const GLfloat* eye = frustum.getEye(); - const float eyedot = (eye[0] * plane[0]) + - (eye[1] * plane[1]) + - (eye[2] * plane[2]) + plane[3]; + const auto eye = glm::vec4(frustum.getEye(), 1.0f); + const float eyedot = glm::dot(eye, plane); if (eyedot <= 0.0f) return true; @@ -107,18 +95,17 @@ bool WallSceneNode::cull(const ViewFrustum& frustum) const const int planeCount = frustum.getPlaneCount(); int i; float d[6], d2[6]; - const GLfloat* mySphere = getSphere(); + const auto mySphere = glm::vec4(getSphere(), 1.0f); + const float myRadius = getRadius2(); bool inside = true; for (i = 0; i < planeCount; i++) { - const GLfloat* norm = frustum.getSide(i); - d[i] = (mySphere[0] * norm[0]) + - (mySphere[1] * norm[1]) + - (mySphere[2] * norm[2]) + norm[3]; + const auto &norm = frustum.getSide(i); + d[i] = glm::dot(mySphere, norm); if (d[i] < 0.0f) { d2[i] = d[i] * d[i]; - if (d2[i] > mySphere[3]) + if (d2[i] > myRadius) return true; inside = false; } @@ -137,9 +124,9 @@ bool WallSceneNode::cull(const ViewFrustum& frustum) const { if (d[i] >= 0.0f) continue; - const GLfloat* norm = frustum.getSide(i); - const GLfloat c = norm[0]*plane[0] + norm[1]*plane[1] + norm[2]*plane[2]; - if (d2[i] > mySphere[3] * (1.0f - c*c)) + const auto norm = glm::vec3(frustum.getSide(i)); + const GLfloat c = glm::dot(norm, glm::vec3(plane)); + if (d2[i] > myRadius * (1.0f - c*c)) return true; } @@ -155,26 +142,25 @@ int WallSceneNode::pickLevelOfDetail( int bestLOD = 0; - const GLfloat* mySphere = getSphere(); + const auto &mySphere = getSphere(); + const float myRadius = getRadius2(); const int numLights = renderer.getNumLights(); for (int i = 0; i < numLights; i++) { - const GLfloat* pos = renderer.getLight(i).getPosition(); + auto pos = renderer.getLight(i).getPosition(); + pos.w = 1.0f; // get signed distance from plane - GLfloat pd = pos[0] * plane[0] + pos[1] * plane[1] + - pos[2] * plane[2] + plane[3]; + GLfloat pd = glm::dot(pos, plane); // ignore if behind wall if (pd < 0.0f) continue; // get squared distance from center of wall - GLfloat ld = (pos[0] - mySphere[0]) * (pos[0] - mySphere[0]) + - (pos[1] - mySphere[1]) * (pos[1] - mySphere[1]) + - (pos[2] - mySphere[2]) * (pos[2] - mySphere[2]); + GLfloat ld = glm::distance2(glm::vec3(pos), mySphere); // pick representative distance - GLfloat d = (ld > 1.5f * mySphere[3]) ? ld : pd * pd; + GLfloat d = (ld > 1.5f * myRadius) ? ld : pd * pd; // choose lod based on distance and element areas; int j; @@ -198,23 +184,20 @@ int WallSceneNode::pickLevelOfDetail( return bestLOD; } -GLfloat WallSceneNode::getDistance(const GLfloat* eye) const +GLfloat WallSceneNode::getDistance(const glm::vec3 &eye) const { - const GLfloat d = plane[0] * eye[0] + plane[1] * eye[1] + - plane[2] * eye[2] + plane[3]; + const auto myEye = glm::vec4(eye, 1.0f); + const GLfloat d = glm::dot(plane, myEye); return d * d; } void WallSceneNode::setColor( GLfloat r, GLfloat g, GLfloat b, GLfloat a) { - color[0] = r; - color[1] = g; - color[2] = b; - color[3] = a; + color = glm::vec4(r, g, b, a); } -void WallSceneNode::setDynamicColor(const GLfloat* rgba) +void WallSceneNode::setDynamicColor(const glm::vec4 *rgba) { dynamicColor = rgba; return; @@ -232,64 +215,43 @@ void WallSceneNode::setSphereMap(bool sphereMapping) return; } -void WallSceneNode::setColor(const GLfloat* rgba) +void WallSceneNode::setColor(const glm::vec4 &rgba) { - color[0] = rgba[0]; - color[1] = rgba[1]; - color[2] = rgba[2]; - color[3] = rgba[3]; + color = rgba; } void WallSceneNode::setModulateColor( GLfloat r, GLfloat g, GLfloat b, GLfloat a) { - modulateColor[0] = r; - modulateColor[1] = g; - modulateColor[2] = b; - modulateColor[3] = a; + modulateColor = glm::vec4(r, g, b, a); } -void WallSceneNode::setModulateColor(const GLfloat* rgba) +void WallSceneNode::setModulateColor(const glm::vec4 &rgba) { - modulateColor[0] = rgba[0]; - modulateColor[1] = rgba[1]; - modulateColor[2] = rgba[2]; - modulateColor[3] = rgba[3]; + modulateColor = rgba; } void WallSceneNode::setLightedColor( GLfloat r, GLfloat g, GLfloat b, GLfloat a) { - lightedColor[0] = r; - lightedColor[1] = g; - lightedColor[2] = b; - lightedColor[3] = a; + lightedColor = glm::vec4(r, g, b, a); } -void WallSceneNode::setLightedColor(const GLfloat* rgba) +void WallSceneNode::setLightedColor(const glm::vec4 &rgba) { - lightedColor[0] = rgba[0]; - lightedColor[1] = rgba[1]; - lightedColor[2] = rgba[2]; - lightedColor[3] = rgba[3]; + lightedColor = rgba; } void WallSceneNode::setLightedModulateColor( GLfloat r, GLfloat g, GLfloat b, GLfloat a) { - lightedModulateColor[0] = r; - lightedModulateColor[1] = g; - lightedModulateColor[2] = b; - lightedModulateColor[3] = a; + lightedModulateColor = glm::vec4(r, g, b, a); } -void WallSceneNode::setLightedModulateColor( - const GLfloat* rgba) +void WallSceneNode::setLightedModulateColor( + const glm::vec4 &rgba) { - lightedModulateColor[0] = rgba[0]; - lightedModulateColor[1] = rgba[1]; - lightedModulateColor[2] = rgba[2]; - lightedModulateColor[3] = rgba[3]; + lightedModulateColor = rgba; } void WallSceneNode::setAlphaThreshold(float thresh) @@ -400,7 +362,7 @@ void WallSceneNode::setColor() if (BZDBCache::texture && useColorTexture) myColor4f(1,1,1,1); else if (dynamicColor != NULL) - myColor4fv(dynamicColor); + myColor4fv(*dynamicColor); else { switch (style) @@ -421,13 +383,13 @@ void WallSceneNode::setColor() } } -int WallSceneNode::splitWall(const GLfloat* splitPlane, - const GLfloat3Array& vertices, - const GLfloat2Array& texcoords, +int WallSceneNode::splitWall(const glm::vec4 &splitPlane, + const std::vector &vertices, + const std::vector &texcoords, SceneNode*& front, SceneNode*& back) // const { int i; - const int count = vertices.getSize(); + const int count = vertices.size(); const float fudgeFactor = 0.001f; const unsigned char BACK_SIDE = (1 << 0); const unsigned char FRONT_SIDE = (1 << 1); @@ -456,29 +418,29 @@ int WallSceneNode::splitWall(const GLfloat* splitPlane, int bothCount = 0; int backCount = 0; int frontCount = 0; - for (i = 0; i < count; i++) + unsigned char *tmpArray = array; + float *tmpDists = dists; + for (const auto v : vertices) { - const GLfloat d = (vertices[i][0] * splitPlane[0]) + - (vertices[i][1] * splitPlane[1]) + - (vertices[i][2] * splitPlane[2]) + splitPlane[3]; + const GLfloat d = glm::dot(glm::vec4(v, 1.0f), splitPlane); if (d < -fudgeFactor) { - array[i] = BACK_SIDE; + *tmpArray++ = BACK_SIDE; backCount++; } else if (d > fudgeFactor) { - array[i] = FRONT_SIDE; + *tmpArray++ = FRONT_SIDE; frontCount++; } else { - array[i] = (BACK_SIDE | FRONT_SIDE); + *tmpArray++ = BACK_SIDE | FRONT_SIDE; bothCount++; backCount++; frontCount++; } - dists[i] = d; // save for later + *tmpDists++ = d; // save for later } // see if we need to split @@ -539,49 +501,51 @@ int WallSceneNode::splitWall(const GLfloat* splitPlane, } // make space for new polygons - GLfloat3Array vertexFront(frontCount); - GLfloat2Array uvFront(frontCount); - GLfloat3Array vertexBack(backCount); - GLfloat2Array uvBack(backCount); + std::vector vertexFront(frontCount); + std::vector uvFront(frontCount); + std::vector vertexBack(backCount); + std::vector uvBack(backCount); // fill in the splitting vertices int frontIndex = 0; int backIndex = 0; if (firstFront != lastBack) { - GLfloat splitVertex[3], splitUV[2]; + glm::vec3 splitVertex; + glm::vec2 splitUV; splitEdge(dists[firstFront], dists[lastBack], vertices[firstFront], vertices[lastBack], texcoords[firstFront], texcoords[lastBack], splitVertex, splitUV); - memcpy(vertexFront[0], splitVertex, sizeof(GLfloat[3])); - memcpy(uvFront[0], splitUV, sizeof(GLfloat[2])); + vertexFront[0] = splitVertex; + uvFront[0] = splitUV; frontIndex++; // bump up the head const int last = backCount - 1; - memcpy(vertexBack[last], splitVertex, sizeof(GLfloat[3])); - memcpy(uvBack[last], splitUV, sizeof(GLfloat[2])); + vertexBack[last] = splitVertex; + uvBack[last] = splitUV; } if (firstBack != lastFront) { - GLfloat splitVertex[3], splitUV[2]; + glm::vec3 splitVertex; + glm::vec2 splitUV; splitEdge(dists[firstBack], dists[lastFront], vertices[firstBack], vertices[lastFront], texcoords[firstBack], texcoords[lastFront], splitVertex, splitUV); - memcpy(vertexBack[0], splitVertex, sizeof(GLfloat[3])); - memcpy(uvBack[0], splitUV, sizeof(GLfloat[2])); + vertexBack[0] = splitVertex; + uvBack[0] = splitUV; backIndex++; // bump up the head const int last = frontCount - 1; - memcpy(vertexFront[last], splitVertex, sizeof(GLfloat[3])); - memcpy(uvFront[last], splitUV, sizeof(GLfloat[2])); + vertexFront[last] = splitVertex; + uvFront[last] = splitUV; } // fill in the old front side vertices const int endFront = (lastFront + 1) % count; for (i = firstFront; i != endFront; i = (i + 1) % count) { - memcpy(vertexFront[frontIndex], vertices[i], sizeof(GLfloat[3])); - memcpy(uvFront[frontIndex], texcoords[i], sizeof(GLfloat[2])); + vertexFront[frontIndex] = vertices[i]; + uvFront[frontIndex] = texcoords[i]; frontIndex++; } @@ -589,8 +553,8 @@ int WallSceneNode::splitWall(const GLfloat* splitPlane, const int endBack = (lastBack + 1) % count; for (i = firstBack; i != endBack; i = (i + 1) % count) { - memcpy(vertexBack[backIndex], vertices[i], sizeof(GLfloat[3])); - memcpy(uvBack[backIndex], texcoords[i], sizeof(GLfloat[2])); + vertexBack[backIndex] = vertices[i]; + uvBack[backIndex] = texcoords[i]; backIndex++; } @@ -610,9 +574,9 @@ int WallSceneNode::splitWall(const GLfloat* splitPlane, void WallSceneNode::splitEdge(float d1, float d2, - const GLfloat* p1, const GLfloat* p2, - const GLfloat* uv1, const GLfloat* uv2, - GLfloat* p, GLfloat* uv) // const + const glm::vec3 &p1, const glm::vec3 &p2, + const glm::vec2 &uv1, const glm::vec2 &uv2, + glm::vec3 &p, glm::vec2 &uv) // const { // compute fraction along edge where split occurs float t1 = (d2 - d1); @@ -620,13 +584,10 @@ void WallSceneNode::splitEdge(float d1, float d2, t1 = -(d1 / t1); // compute vertex - p[0] = p1[0] + (t1 * (p2[0] - p1[0])); - p[1] = p1[1] + (t1 * (p2[1] - p1[1])); - p[2] = p1[2] + (t1 * (p2[2] - p1[2])); + p = glm::mix(p1, p2, t1); // compute texture coordinate - uv[0] = uv1[0] + (t1 * (uv2[0] - uv1[0])); - uv[1] = uv1[1] + (t1 * (uv2[1] - uv1[1])); + uv = glm::mix(uv1, uv2, t1); } diff --git a/src/net/Pack.cxx b/src/net/Pack.cxx index 5848a76b53..a056535717 100644 --- a/src/net/Pack.cxx +++ b/src/net/Pack.cxx @@ -15,6 +15,7 @@ // System headers #include +#include // Common headers #include "network.h" @@ -132,6 +133,22 @@ void* nboPackVector(void* b, const float *v) return (void*) (((char*)b)+3*sizeof(uint32_t)); } +void *nboPackVector(void* b, const glm::vec3 &v) +{ + // hope that float is a 4 byte IEEE 754 standard encoding + floatintuni u; + uint32_t data[3]; + + for (int i=0; i<3; i++) + { + u.floatval = v[i]; + data[i] = (uint32_t)htonl(u.intval); + } + + ::memcpy( b, data, 3*sizeof(uint32_t)); + return (void*) (((char*)b)+3*sizeof(uint32_t)); +} + void* nboPackString(void* b, const void* m, int len) { if (!m || len == 0) return b; @@ -302,6 +319,33 @@ const void* nboUnpackVector(const void* b, float *v) return (const char*)b + 3*sizeof(float); } +const void *nboUnpackVector(const void* b, glm::vec3 &v) +{ + if (ErrorChecking) + { + if (Length < sizeof(float[3])) + { + Error = true; + v[0] = v[1] = v[2] = 0.0f; + return b; + } + else + Length -= sizeof(float[3]); + } + // hope that float is a 4 byte IEEE 754 standard encoding + uint32_t data[3]; + floatintuni u; + ::memcpy( data, b, 3*sizeof(uint32_t)); + + for (int i=0; i<3; i++) + { + u.intval = (uint32_t)ntohl(data[i]); + v[i] = u.floatval; + } + + return (const char*)b + 3*sizeof(float); +} + const void* nboUnpackString(const void* b, void* m, int len) { if (!m || len == 0) return b; diff --git a/src/obstacle/ArcObstacle.cxx b/src/obstacle/ArcObstacle.cxx index fa350ad452..5dfe478d33 100644 --- a/src/obstacle/ArcObstacle.cxx +++ b/src/obstacle/ArcObstacle.cxx @@ -16,6 +16,8 @@ // System interfaces #include #include +#include +#include //Common interfaces #include "global.h" @@ -36,7 +38,7 @@ ArcObstacle::ArcObstacle() ArcObstacle::ArcObstacle(const MeshTransform& xform, - const float* _pos, const float* _size, + const glm::vec3 &_pos, const glm::vec3 &_size, float _rotation, float _sweepAngle, float _ratio, const float _texsize[4], bool _useNormals, int _divisions, const BzMaterial* mats[MaterialCount], @@ -212,12 +214,12 @@ MeshObstacle* ArcObstacle::makePie(bool isCircle, float a, float r, // setup the coordinates std::vector checkTypes; - std::vector checkPoints; - std::vector vertices; - std::vector normals; - std::vector texcoords; - cfvec3 v, n; - cfvec2 t; + std::vector checkPoints; + std::vector vertices; + std::vector normals; + std::vector texcoords; + glm::vec3 v, n; + glm::vec2 t; // add the checkpoint (one is sufficient) if (isCircle) @@ -394,12 +396,12 @@ MeshObstacle* ArcObstacle::makeRing(bool isCircle, float a, float r, // setup the coordinates std::vector checkTypes; - std::vector checkPoints; - std::vector vertices; - std::vector normals; - std::vector texcoords; - cfvec3 v, n; - cfvec2 t; + std::vector checkPoints; + std::vector vertices; + std::vector normals; + std::vector texcoords; + glm::vec3 v, n; + glm::vec2 t; // add the checkpoints (very wasteful) v[0] = pos[0]; @@ -586,53 +588,21 @@ float ArcObstacle::intersect(const Ray&) const } -void ArcObstacle::get3DNormal(const float*, float*) const +void ArcObstacle::get3DNormal(const glm::vec3 &, glm::vec3 &) const { assert(false); return; } -void ArcObstacle::getNormal(const float*, float*) const +void ArcObstacle::getNormal(const glm::vec3 &, glm::vec3 &) const { assert(false); return; } -bool ArcObstacle::getHitNormal(const float*, float, const float*, float, - float, float, float, float*) const -{ - assert(false); - return false; -} - - -bool ArcObstacle::inCylinder(const float*,float, float) const -{ - assert(false); - return false; -} - - -bool ArcObstacle::inBox(const float*, float, float, float, float) const -{ - assert(false); - return false; -} - - -bool ArcObstacle::inMovingBox(const float*, float, const float*, float, - float, float, float) const -{ - assert(false); - return false; -} - - -bool ArcObstacle::isCrossing(const float* UNUSED(p), float UNUSED(_angle), - float UNUSED(dx), float UNUSED(dy), float UNUSED(height), - float* UNUSED(_plane)) const +bool ArcObstacle::inCylinder(const glm::vec3 &,float, float) const { assert(false); return false; diff --git a/src/obstacle/BaseBuilding.cxx b/src/obstacle/BaseBuilding.cxx index 9cefcb2f21..3e85fe5a4f 100644 --- a/src/obstacle/BaseBuilding.cxx +++ b/src/obstacle/BaseBuilding.cxx @@ -10,11 +10,16 @@ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ -#include "common.h" +// Interface header +#include "BaseBuilding.h" + +// System headers #include +#include + +// Common headers #include "global.h" #include "Pack.h" -#include "BaseBuilding.h" #include "Intersect.h" #include "MeshTransform.h" @@ -25,8 +30,8 @@ BaseBuilding::BaseBuilding() { } -BaseBuilding::BaseBuilding(const float *p, float rotation, - const float *_size, int _team, bool rico) : +BaseBuilding::BaseBuilding(const glm::vec3 &p, float rotation, + const glm::vec3 &_size, int _team, bool rico) : BoxBuilding(p, rotation, _size[0], _size[1], _size[2], false, false, rico), team(_team) { @@ -39,9 +44,9 @@ BaseBuilding::~BaseBuilding() Obstacle* BaseBuilding::copyWithTransform(const MeshTransform& xform) const { - float newPos[3], newSize[3], newAngle; - memcpy(newPos, pos, sizeof(float[3])); - memcpy(newSize, size, sizeof(float[3])); + auto newPos = pos; + float newAngle; + auto newSize = size; newAngle = angle; MeshTransform::Tool tool(xform); @@ -63,16 +68,16 @@ const char* BaseBuilding::getClassName() return typeName; } -bool BaseBuilding::inCylinder(const float *p, float radius, float height) const +bool BaseBuilding::inCylinder(const glm::vec3 &p, float radius, float height) const { return (p[2] < (getPosition()[2] + getHeight())) && ((p[2]+height) > getPosition()[2]) && testRectCircle(getPosition(), getRotation(), getWidth(), getBreadth(), p, radius); } -bool BaseBuilding::inMovingBox(const float* oldP, float, - const float *p, float _angle, - float dx, float dy, float height) const +bool BaseBuilding::inMovingBox(const glm::vec3 &oldP, float, + const glm::vec3 &p, float _angle, + float dx, float dy, float height) const { // if a base is just the ground (z == 0 && height == 0) no collision // ground is already handled @@ -82,9 +87,9 @@ bool BaseBuilding::inMovingBox(const float* oldP, float, return BoxBuilding::inMovingBox(oldP, 0.0f, p, _angle, dx, dy, height); } -bool BaseBuilding::isCrossing(const float *p, float _angle, - float dx, float dy, float height, - float *plane) const +bool BaseBuilding::isCrossing(const glm::vec3 &p, float _angle, + float dx, float dy, float height, + glm::vec4 *plane) const { // if not inside or contained, then not crossing if (!inBox(p, _angle, dx, dy, height) || @@ -96,30 +101,30 @@ bool BaseBuilding::isCrossing(const float *p, float _angle, // it's crossing -- choose which wall is being crossed (this // is a guestimate, should really do a careful test). Just // see which wall the point is closest to - const float *p2 = getPosition(); + const auto &p2 = getPosition(); const float a2 = getRotation(); const float c = cosf(-a2), s = sinf(-a2); const float x = c * (p[0] - p2[0]) - s * (p[1] - p2[1]); const float y = c * (p[1] - p2[1]) - s * (p[0] - p2[0]); - float pw[2]; + auto pw = p2; if (fabsf(fabsf(x) - getWidth()) < fabsf(fabsf(y) - getBreadth())) { - plane[0] = ((x < 0.0) ? -cosf(a2) : cosf(a2)); - plane[1] = ((x < 0.0) ? -sinf(a2) : sinf(a2)); - pw[0] = p2[0] + getWidth() * plane[0]; - pw[1] = p2[1] + getWidth() * plane[1]; + plane->x = ((x < 0.0) ? -cosf(a2) : cosf(a2)); + plane->y = ((x < 0.0) ? -sinf(a2) : sinf(a2)); + pw[0] += getWidth() * plane->x; + pw[1] += getWidth() * plane->y; } else { - plane[0] = ((y < 0.0) ? sinf(a2) : -sinf(a2)); - plane[1] = ((y < 0.0) ? cosf(a2) : -cosf(a2)); - pw[0] = p2[0] + getBreadth() * plane[0]; - pw[1] = p2[1] + getBreadth() * plane[1]; + plane->x = ((y < 0.0) ? sinf(a2) : -sinf(a2)); + plane->y = ((y < 0.0) ? cosf(a2) : -cosf(a2)); + pw[0] += getBreadth() * plane->x; + pw[1] += getBreadth() * plane->y; } // now finish off plane equation - plane[2] = 0.0; - plane[3] = -(plane[0] * pw[0] + plane[1] * pw[1]); + plane->z = 0.0; + plane->w = -(plane->x * pw[0] + plane->y * pw[1]); return true; } @@ -162,7 +167,7 @@ int BaseBuilding::packSize() const void BaseBuilding::print(std::ostream& out, const std::string& indent) const { out << indent << "base" << std::endl; - const float *myPos = getPosition(); + const auto &myPos = getPosition(); out << indent << " position " << myPos[0] << " " << myPos[1] << " " << myPos[2] << std::endl; out << indent << " size " << getWidth() << " " << getBreadth() @@ -197,7 +202,7 @@ static void outputFloat(std::ostream& out, float value) void BaseBuilding::printOBJ(std::ostream& out, const std::string& UNUSED(indent)) const { int i; - float verts[8][3] = + glm::vec3 verts[8] = { {-1.0f, -1.0f, 0.0f}, {+1.0f, -1.0f, 0.0f}, @@ -208,7 +213,7 @@ void BaseBuilding::printOBJ(std::ostream& out, const std::string& UNUSED(indent) {+1.0f, +1.0f, 1.0f}, {-1.0f, +1.0f, 1.0f} }; - float norms[6][3] = + glm::vec3 norms[6] = { {0.0f, -1.0f, 0.0f}, {+1.0f, 0.0f, 0.0f}, {0.0f, +1.0f, 0.0f}, {-1.0f, 0.0f, 0.0f}, @@ -220,7 +225,7 @@ void BaseBuilding::printOBJ(std::ostream& out, const std::string& UNUSED(indent) }; MeshTransform xform; const float degrees = getRotation() * (float)(180.0 / M_PI); - const float zAxis[3] = {0.0f, 0.0f, +1.0f}; + const glm::vec3 zAxis = glm::vec3(0.0f, 0.0f, +1.0f); xform.addScale(getSize()); xform.addSpin(degrees, zAxis); xform.addShift(getPosition()); diff --git a/src/obstacle/BaseSceneNodeGenerator.cxx b/src/obstacle/BaseSceneNodeGenerator.cxx index 3f9c200586..0ba089ea4a 100644 --- a/src/obstacle/BaseSceneNodeGenerator.cxx +++ b/src/obstacle/BaseSceneNodeGenerator.cxx @@ -32,7 +32,7 @@ WallSceneNode* BaseSceneNodeGenerator::getNextNode(float uRepeats, float vRepea const float height = base->getHeight() + base->getPosition()[2]; if (getNodeNumber() >= 1 && height == 0) return NULL; if (getNodeNumber() >= 6) return NULL; - GLfloat bPoint[3], sCorner[3], tCorner[3]; + glm::vec3 bPoint, sCorner, tCorner; if (height == 0) { fixedUVs = true; @@ -86,40 +86,25 @@ WallSceneNode* BaseSceneNodeGenerator::getNextNode(float uRepeats, float vRepea } } - GLfloat color[4]; + glm::vec4 color; switch (base->getTeam()) { case 1: - color[0] = 0.7f; - color[1] = 0.0f; - color[2] = 0.0f; + color = glm::vec4(0.7f, 0.0f, 0.0f, 1.0f); break; case 2: - color[0] = 0.0f; - color[1] = 0.7f; - color[2] = 0.0f; + color = glm::vec4(0.0f, 0.7f, 0.0f, 1.0f); break; case 3: - color[0] = 0.0f; - color[1] = 0.0f; - color[2] = 0.7f; + color = glm::vec4(0.0f, 0.0f, 0.7f, 1.0f); break; case 4: - color[0] = 0.7f; - color[1] = 0.0f; - color[2] = 0.7f; + color = glm::vec4(0.7f, 0.0f, 0.7f, 1.0f); break; } - color[3] = 1.0; - GLfloat sEdge[3]; - GLfloat tEdge[3]; - sEdge[0] = sCorner[0] - bPoint[0]; - sEdge[1] = sCorner[1] - bPoint[1]; - sEdge[2] = sCorner[2] - bPoint[2]; - tEdge[0] = tCorner[0] - bPoint[0]; - tEdge[1] = tCorner[1] - bPoint[1]; - tEdge[2] = tCorner[2] - bPoint[2]; + const auto sEdge = sCorner - bPoint; + const auto tEdge = tCorner - bPoint; WallSceneNode *retval = new QuadWallSceneNode(bPoint, sEdge, tEdge, uRepeats, vRepeats, lod, fixedUVs); retval->setColor(color); diff --git a/src/obstacle/BoxBuilding.cxx b/src/obstacle/BoxBuilding.cxx index ad0be02206..eab264df23 100644 --- a/src/obstacle/BoxBuilding.cxx +++ b/src/obstacle/BoxBuilding.cxx @@ -10,11 +10,16 @@ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ -#include "common.h" +// Interface header +#include "BoxBuilding.h" + +// System headers #include +#include + +// Common headers #include "global.h" #include "Pack.h" -#include "BoxBuilding.h" #include "Intersect.h" #include "MeshTransform.h" @@ -25,7 +30,7 @@ BoxBuilding::BoxBuilding() : Obstacle(), noNodes(false) // do nothing } -BoxBuilding::BoxBuilding(const float* p, float a, float w, float b, float h, +BoxBuilding::BoxBuilding(const glm::vec3 &p, float a, float w, float b, float h, bool drive, bool shoot, bool rico, bool invisible) : Obstacle(p, a, w, b, h,drive,shoot,rico), noNodes(invisible) { @@ -46,9 +51,9 @@ void BoxBuilding::finalize() Obstacle* BoxBuilding::copyWithTransform(const MeshTransform& xform) const { - float newPos[3], newSize[3], newAngle; - memcpy(newPos, pos, sizeof(float[3])); - memcpy(newSize, size, sizeof(float[3])); + auto newPos = pos; + float newAngle; + auto newSize = size; newAngle = angle; MeshTransform::Tool tool(xform); @@ -77,38 +82,31 @@ float BoxBuilding::intersect(const Ray& r) const getWidth(), getBreadth(), getHeight()); } -void BoxBuilding::getNormal(const float* p, float* n) const +void BoxBuilding::getNormal(const glm::vec3 &p, glm::vec3 &n) const { getNormalRect(p, getPosition(), getRotation(), getWidth(), getBreadth(), n); } -void BoxBuilding::get3DNormal(const float* p, float* n) const +void BoxBuilding::get3DNormal(const glm::vec3 &p, glm::vec3 &n) const { // This bit of cruft causes bullets to bounce of buildings in the z direction if (fabs(p[2] - getPosition()[2]) < Epsilon) - { - n[0] = 0.0f; - n[1] = 0.0f; - n[2] = -1.0f; - } + n = glm::vec3(0.0f, 0.0f, -1.0f); else if (fabs(p[2] - (getPosition()[2] + getHeight())) < Epsilon) - { - n[0] = 0.0f; - n[1] = 0.0f; - n[2] = 1.0f; - } // end cruftiness + n = glm::vec3(0.0f, 0.0f, 1.0f); + // end cruftiness else getNormal(p, n); } -bool BoxBuilding::inCylinder(const float* p, float radius, float height) const +bool BoxBuilding::inCylinder(const glm::vec3 &p, float radius, float height) const { return (p[2] < (getPosition()[2] + getHeight())) && ((p[2]+height) >= getPosition()[2]) && testRectCircle(getPosition(), getRotation(), getWidth(), getBreadth(), p, radius); } -bool BoxBuilding::inBox(const float* p, float a, +bool BoxBuilding::inBox(const glm::vec3 &p, float a, float dx, float dy, float height) const { return (p[2] < (getPosition()[2] + getHeight())) @@ -116,9 +114,9 @@ bool BoxBuilding::inBox(const float* p, float a, && testRectRect(getPosition(), getRotation(), getWidth(), getBreadth(), p, a, dx, dy); } -bool BoxBuilding::inMovingBox(const float* oldP, float, - const float* p, float a, - float dx, float dy, float height) const +bool BoxBuilding::inMovingBox(const glm::vec3 &oldP, float, + const glm::vec3 &p, float a, + float dx, float dy, float height) const { float higherZ; float lowerZ; @@ -140,8 +138,9 @@ bool BoxBuilding::inMovingBox(const float* oldP, float, p, a, dx, dy); } -bool BoxBuilding::isCrossing(const float* p, float a, - float dx, float dy, float height, float* plane) const +bool BoxBuilding::isCrossing(const glm::vec3 &p, float a, + float dx, float dy, float height, + glm::vec4 *plane) const { // if not inside or contained then not crossing if (!inBox(p, a, dx, dy, height) || @@ -153,7 +152,7 @@ bool BoxBuilding::isCrossing(const float* p, float a, // it's crossing -- choose which wall is being crossed (this // is a guestimate, should really do a careful test). just // see which wall the point is closest to. - const float* p2 = getPosition(); + const auto &p2 = getPosition(); const float a2 = getRotation(); const float c = cosf(-a2), s = sinf(-a2); const float x = c * (p[0] - p2[0]) - s * (p[1] - p2[1]); @@ -161,39 +160,39 @@ bool BoxBuilding::isCrossing(const float* p, float a, float pw[2]; if (fabsf(fabsf(x) - getWidth()) < fabsf(fabsf(y) - getBreadth())) { - plane[0] = ((x < 0.0) ? -cosf(a2) : cosf(a2)); - plane[1] = ((x < 0.0) ? -sinf(a2) : sinf(a2)); - pw[0] = p2[0] + getWidth() * plane[0]; - pw[1] = p2[1] + getWidth() * plane[1]; + plane->x = ((x < 0.0) ? -cosf(a2) : cosf(a2)); + plane->y = ((x < 0.0) ? -sinf(a2) : sinf(a2)); + pw[0] = p2[0] + getWidth() * plane->x; + pw[1] = p2[1] + getWidth() * plane->y; } else { - plane[0] = ((y < 0.0) ? sinf(a2) : -sinf(a2)); - plane[1] = ((y < 0.0) ? -cosf(a2) : cosf(a2)); - pw[0] = p2[0] + getBreadth() * plane[0]; - pw[1] = p2[1] + getBreadth() * plane[1]; + plane->x = ((y < 0.0) ? sinf(a2) : -sinf(a2)); + plane->y = ((y < 0.0) ? -cosf(a2) : cosf(a2)); + pw[0] = p2[0] + getBreadth() * plane->x; + pw[1] = p2[1] + getBreadth() * plane->y; } // now finish off plane equation - plane[2] = 0.0; - plane[3] = -(plane[0] * pw[0] + plane[1] * pw[1]); + plane->z = 0.0; + plane->w = -(plane->x * pw[0] + plane->y * pw[1]); return true; } bool BoxBuilding::getHitNormal( - const float* pos1, float azimuth1, - const float* pos2, float azimuth2, + const glm::vec3 &pos1, float azimuth1, + const glm::vec3 &pos2, float azimuth2, float width, float breadth, float, - float* normal) const + glm::vec3 &normal) const { return Obstacle::getHitNormal(pos1, azimuth1, pos2, azimuth2, width, breadth, getPosition(), getRotation(), getWidth(), getBreadth(), getHeight(), normal) >= 0.0f; } -void BoxBuilding::getCorner(int index, float* _pos) const +void BoxBuilding::getCorner(int index, glm::vec3 &_pos) const { - const float* base = getPosition(); + const auto &base = getPosition(); const float c = cosf(getRotation()); const float s = sinf(getRotation()); const float w = getWidth(); @@ -276,7 +275,7 @@ int BoxBuilding::packSize() const void BoxBuilding::print(std::ostream& out, const std::string& indent) const { out << indent << "box" << std::endl; - const float *myPos = getPosition(); + const auto &myPos = getPosition(); out << indent << " position " << myPos[0] << " " << myPos[1] << " " << myPos[2] << std::endl; out << indent << " size " << getWidth() << " " << getBreadth() @@ -310,7 +309,7 @@ static void outputFloat(std::ostream& out, float value) void BoxBuilding::printOBJ(std::ostream& out, const std::string& UNUSED(indent)) const { int i; - float verts[8][3] = + glm::vec3 verts[8] = { {-1.0f, -1.0f, 0.0f}, {+1.0f, -1.0f, 0.0f}, @@ -321,22 +320,23 @@ void BoxBuilding::printOBJ(std::ostream& out, const std::string& UNUSED(indent)) {+1.0f, +1.0f, 1.0f}, {-1.0f, +1.0f, 1.0f} }; - float norms[6][3] = + glm::vec3 norms[6] = { {0.0f, -1.0f, 0.0f}, {+1.0f, 0.0f, 0.0f}, {0.0f, +1.0f, 0.0f}, {-1.0f, 0.0f, 0.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, +1.0f} }; - const float* s = getSize(); + const auto &s = getSize(); const float k = 1.0f / 8.0f; + auto ks = k * s; float txcds[8][2] = { - {0.0f, 0.0f}, {k*s[0], 0.0f}, {k*s[0], k*s[2]}, {0.0f, k*s[2]}, - {k*s[1], 0.0f}, {k*s[1], k*s[2]}, {k*s[0], k*s[1]}, {0.0f, k*s[1]} + {0.0f, 0.0f}, {ks[0], 0.0f}, {ks[0], ks[2]}, {0.0f, ks[2]}, + {ks[1], 0.0f}, {ks[1], ks[2]}, {ks[0], ks[1]}, {0.0f, ks[1]} }; MeshTransform xform; const float degrees = getRotation() * (float)(180.0 / M_PI); - const float zAxis[3] = {0.0f, 0.0f, +1.0f}; + const auto zAxis = glm::vec3(0.0f, 0.0f, +1.0f); xform.addScale(s); xform.addSpin(degrees, zAxis); xform.addShift(getPosition()); diff --git a/src/obstacle/BoxSceneNodeGenerator.cxx b/src/obstacle/BoxSceneNodeGenerator.cxx index 7e8d0fdcb9..8c104ed3fa 100644 --- a/src/obstacle/BoxSceneNodeGenerator.cxx +++ b/src/obstacle/BoxSceneNodeGenerator.cxx @@ -10,7 +10,10 @@ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ +// Interface #include "BoxSceneNodeGenerator.h" + +// Common headers #include "WallSceneNode.h" #include "BoxBuilding.h" #include "QuadWallSceneNode.h" @@ -35,7 +38,7 @@ WallSceneNode* BoxSceneNodeGenerator::getNextNode( { if (getNodeNumber() == 6) return NULL; - GLfloat base[3], sCorner[3], tCorner[3]; + glm::vec3 base, sCorner, tCorner; switch (incNodeNumber()) { case 1: @@ -76,14 +79,8 @@ WallSceneNode* BoxSceneNodeGenerator::getNextNode( break; } - GLfloat sEdge[3]; - GLfloat tEdge[3]; - sEdge[0] = sCorner[0] - base[0]; - sEdge[1] = sCorner[1] - base[1]; - sEdge[2] = sCorner[2] - base[2]; - tEdge[0] = tCorner[0] - base[0]; - tEdge[1] = tCorner[1] - base[1]; - tEdge[2] = tCorner[2] - base[2]; + const auto sEdge = sCorner - base; + const auto tEdge = tCorner - base; return new QuadWallSceneNode(base, sEdge, tEdge, uRepeats, vRepeats, lod); } diff --git a/src/obstacle/ConeObstacle.cxx b/src/obstacle/ConeObstacle.cxx index 19aedf8ed4..93048cc5d1 100644 --- a/src/obstacle/ConeObstacle.cxx +++ b/src/obstacle/ConeObstacle.cxx @@ -16,6 +16,10 @@ // System headers #include #include +#include +#include +#define GLM_ENABLE_EXPERIMENTAL +#include // Common headers #include "global.h" @@ -35,7 +39,7 @@ ConeObstacle::ConeObstacle() ConeObstacle::ConeObstacle(const MeshTransform& xform, - const float* _pos, const float* _size, + const glm::vec3 &_pos, const glm::vec3 &_size, float _rotation, float _sweepAngle, const float _texsize[2], bool _useNormals, int _divisions, @@ -111,10 +115,7 @@ MeshObstacle* ConeObstacle::makeMesh() const float minSize = 1.0e-6f; // cheezy / lazy // absolute the sizes - float sz[3]; - sz[0] = fabsf(size[0]); - sz[1] = fabsf(size[1]); - sz[2] = fabsf(size[2]); + auto sz = glm::abs(size); // validity checking if ((sz[0] < minSize) || (sz[1] < minSize) || (sz[2] < minSize) || @@ -161,26 +162,22 @@ MeshObstacle* ConeObstacle::makeMesh() // setup the coordinates std::vector checkTypes; - std::vector checkPoints; - std::vector vertices; - std::vector normals; - std::vector texcoords; - cfvec3 v, n; - cfvec2 t; - + std::vector checkPoints; + std::vector vertices; + std::vector normals; + std::vector texcoords; + glm::vec3 n; + glm::vec2 t; + + auto v = pos; // add the checkpoint (one is sufficient) - if (isCircle) - { - v[0] = pos[0]; - v[1] = pos[1]; - } - else + if (!isCircle) { const float dir = r + (0.5f * a); - v[0] = pos[0] + (cosf(dir) * sz[0] * 0.25f); - v[1] = pos[1] + (sinf(dir) * sz[1] * 0.25f); + v[0] += cosf(dir) * sz[0] * 0.25f; + v[1] += sinf(dir) * sz[1] * 0.25f; } - v[2] = pos[2] + (0.5f * sz[2]); + v[2] += 0.5f * sz[2]; checkPoints.push_back(v); checkTypes.push_back(MeshObstacle::CheckInside); @@ -200,9 +197,9 @@ MeshObstacle* ConeObstacle::makeMesh() // vertices (around the edge) delta[0] = cos_val * sz[0]; delta[1] = sin_val * sz[1]; - v[0] = pos[0] + delta[0]; - v[1] = pos[1] + delta[1]; - v[2] = pos[2]; + v = pos; + v[0] += delta[0]; + v[1] += delta[1]; vertices.push_back(v); // normals (around the edge) if (useNormals) @@ -212,11 +209,9 @@ MeshObstacle* ConeObstacle::makeMesh() n[1] = sin_val / sz[1]; n[2] = 1.0f / sz[2]; // normalize - float len = (n[0] * n[0]) + (n[1] * n[1]) + (n[2] * n[2]); - len = 1.0f / sqrtf(len); - n[0] *= len; - n[1] *= len; - n[2] *= len; + float len = glm::length2(n); + len = glm::inversesqrt(len); + n *= len; normals.push_back(n); } } @@ -238,21 +233,17 @@ MeshObstacle* ConeObstacle::makeMesh() n[1] = sinf(ang) / sz[1]; n[2] = 1.0f / sz[2]; // normalize - float len = (n[0] * n[0]) + (n[1] * n[1]) + (n[2] * n[2]); - len = 1.0f / sqrtf(len); - n[0] *= len; - n[1] *= len; - n[2] *= len; + float len = glm::length2(n); + len = glm::inversesqrt(len); + n *= len; normals.push_back(n); } } // the central coordinates - v[0] = pos[0]; - v[1] = pos[1]; - v[2] = pos[2]; + v = pos; vertices.push_back(v); // bottom - v[2] = pos[2] + sz[2]; + v[2] += sz[2]; vertices.push_back(v); // top t[0] = texsz[0] * 0.5f; t[1] = texsz[1] * 0.5f; @@ -356,53 +347,24 @@ float ConeObstacle::intersect(const Ray&) const return -1.0f; } -void ConeObstacle::get3DNormal(const float*, float*) const +void ConeObstacle::get3DNormal(const glm::vec3 &, glm::vec3 &) const { assert(false); return; } -void ConeObstacle::getNormal(const float*, float*) const +void ConeObstacle::getNormal(const glm::vec3 &, glm::vec3 &) const { assert(false); return; } -bool ConeObstacle::getHitNormal(const float*, float, const float*, float, - float, float, float, float*) const -{ - assert(false); - return false; -} - -bool ConeObstacle::inCylinder(const float*,float, float) const +bool ConeObstacle::inCylinder(const glm::vec3 &, float, float) const { assert(false); return false; } -bool ConeObstacle::inBox(const float*, float, float, float, float) const -{ - assert(false); - return false; -} - -bool ConeObstacle::inMovingBox(const float*, float, const float*, float, - float, float, float) const -{ - assert(false); - return false; -} - -bool ConeObstacle::isCrossing(const float* UNUSED(p), float UNUSED(_angle), - float UNUSED(dx), float UNUSED(dy), float UNUSED(height), - float* UNUSED(_plane)) const -{ - assert(false); - return false; -} - - void *ConeObstacle::pack(void *buf) const { buf = transform.pack(buf); diff --git a/src/obstacle/MeshDrawInfo.cxx b/src/obstacle/MeshDrawInfo.cxx index 59aa385f43..d2f2d89816 100644 --- a/src/obstacle/MeshDrawInfo.cxx +++ b/src/obstacle/MeshDrawInfo.cxx @@ -23,6 +23,9 @@ #include #include #include +#include +#define GLM_ENABLE_EXPERIMENTAL +#include // common implementation headers #include "Pack.h" @@ -95,7 +98,8 @@ MeshDrawInfo::MeshDrawInfo(const MeshDrawInfo* di, // copy extents and sphere (xform applied later) extents = di->extents; - memcpy(sphere, di->sphere, sizeof(float[4])); + position = di->position; + radius2 = di->radius2; // counts cornerCount = di->cornerCount; @@ -175,7 +179,8 @@ void MeshDrawInfo::init() drawMgr = NULL; extents.reset(); - sphere[0] = sphere[1] = sphere[2] = sphere[3] = +MAXFLOAT; + position = glm::vec3(+MAXFLOAT); + radius2 = +MAXFLOAT; cornerCount = 0; corners = NULL; @@ -311,7 +316,7 @@ bool MeshDrawInfo::serverSetup(const MeshObstacle* mesh) return false; int vCount; - const afvec3* verts; + const glm::vec3 *verts; if (rawVertCount > 0) { vCount = rawVertCount; @@ -324,10 +329,10 @@ bool MeshDrawInfo::serverSetup(const MeshObstacle* mesh) } Extents tmpExts; - const bool calcCenter = (sphere[0] == +MAXFLOAT) && - (sphere[1] == +MAXFLOAT) && - (sphere[2] == +MAXFLOAT); - const bool calcRadius = (sphere[3] == +MAXFLOAT); + const bool calcCenter = (position[0] == +MAXFLOAT) && + (position[1] == +MAXFLOAT) && + (position[2] == +MAXFLOAT); + const bool calcRadius = (radius2 == +MAXFLOAT); const bool calcExtents = (extents.mins[0] == tmpExts.mins[0]) && (extents.mins[1] == tmpExts.mins[1]) && (extents.mins[2] == tmpExts.mins[2]) && @@ -352,12 +357,12 @@ bool MeshDrawInfo::serverSetup(const MeshObstacle* mesh) float maxDistSqr = -MAXFLOAT; for (int v = 0; v < vCount; v++) { - const afvec3& p = verts[v]; + const auto &p = verts[v]; if (p[2] < minZ) minZ = p[2]; if (p[2] > maxZ) maxZ = p[2]; - const float distSqr = (p[0] * p[0]) + (p[1] * p[1]); + const float distSqr = glm::length2(glm::vec2(p)); if (distSqr > maxDistSqr) maxDistSqr = distSqr; } @@ -376,18 +381,10 @@ bool MeshDrawInfo::serverSetup(const MeshObstacle* mesh) // calculate the sphere params? if (calcCenter) - { - sphere[0] = 0.5f * (extents.maxs[0] + extents.mins[0]); - sphere[1] = 0.5f * (extents.maxs[1] + extents.mins[1]); - sphere[2] = 0.5f * (extents.maxs[2] + extents.mins[2]); - } + position = 0.5f * (extents.maxs + extents.mins); if (calcRadius) - { - const float dx = extents.maxs[0] - extents.mins[0]; - const float dy = extents.maxs[1] - extents.mins[1]; - const float dz = extents.maxs[2] - extents.mins[2]; - sphere[3] = 0.25f * (dx*dx + dy*dy + dz*dz); // radius squared - } + // radius squared + radius2 = 0.25f * glm::distance2(extents.maxs, extents.mins); // calculate the DrawSet spheres? for (int lod = 0; lod < lodCount; lod++) @@ -396,10 +393,10 @@ bool MeshDrawInfo::serverSetup(const MeshObstacle* mesh) for (int set = 0; set < drawLod.count; set++) { DrawSet& drawSet = drawLod.sets[set]; - const bool calcSetCenter = (drawSet.sphere[0] == +MAXFLOAT) && - (drawSet.sphere[1] == +MAXFLOAT) && - (drawSet.sphere[2] == +MAXFLOAT); - const bool calcSetRadius = (drawSet.sphere[3] == +MAXFLOAT); + const bool calcSetCenter = (drawSet.position[0] == +MAXFLOAT) && + (drawSet.position[1] == +MAXFLOAT) && + (drawSet.position[2] == +MAXFLOAT); + const bool calcSetRadius = (drawSet.radius2 == +MAXFLOAT); if (calcSetCenter || calcSetRadius) { Extents exts; @@ -413,7 +410,7 @@ bool MeshDrawInfo::serverSetup(const MeshObstacle* mesh) { const unsigned short cIndex = array[idx]; const Corner& corner = corners[cIndex]; - const float* v = verts[corner.vertex]; + const auto v = verts[corner.vertex]; exts.expandToPoint(v); } } @@ -424,24 +421,16 @@ bool MeshDrawInfo::serverSetup(const MeshObstacle* mesh) { const unsigned int cIndex = array[idx]; const Corner& corner = corners[cIndex]; - const float* v = verts[corner.vertex]; + const auto v = verts[corner.vertex]; exts.expandToPoint(v); } } } if (calcSetCenter) - { - drawSet.sphere[0] = 0.5f * (exts.maxs[0] + exts.mins[0]); - drawSet.sphere[1] = 0.5f * (exts.maxs[1] + exts.mins[1]); - drawSet.sphere[2] = 0.5f * (exts.maxs[2] + exts.mins[2]); - } + drawSet.position = 0.5f * (exts.maxs + exts.mins); if (calcSetRadius) - { - const float dx = exts.maxs[0] - exts.mins[0]; - const float dy = exts.maxs[1] - exts.mins[1]; - const float dz = exts.maxs[2] - exts.mins[2]; - drawSet.sphere[3] = 0.25f * (dx*dx + dy*dy + dz*dz); // radius squared - } + drawSet.radius2 = 0.25f + * glm::distance2(exts.maxs, exts.mins); // radius squared } } } @@ -461,9 +450,9 @@ bool MeshDrawInfo::clientSetup(const MeshObstacle* mesh) if (!valid) return false; - const afvec3* verts; - const afvec3* norms; - const afvec2* txcds; + const glm::vec3 *verts; + const glm::vec3 *norms; + const glm::vec2 *txcds; if (rawVertCount > 0) { verts = rawVerts; @@ -478,15 +467,15 @@ bool MeshDrawInfo::clientSetup(const MeshObstacle* mesh) } // make the element arrays - vertices = new afvec3[cornerCount]; - normals = new afvec3[cornerCount]; - texcoords = new afvec2[cornerCount]; + vertices = new glm::vec3[cornerCount]; + normals = new glm::vec3[cornerCount]; + texcoords = new glm::vec2[cornerCount]; for (int i = 0; i < cornerCount; i++) { Corner& corner = corners[i]; - memcpy(vertices[i], verts[corner.vertex], sizeof(afvec3)); - memcpy(normals[i], norms[corner.normal], sizeof(afvec3)); - memcpy(texcoords[i], txcds[corner.texcoord], sizeof(afvec2)); + vertices[i] = verts[corner.vertex]; + normals[i] = norms[corner.normal]; + texcoords[i] = txcds[corner.texcoord]; } // tally the triangle counts @@ -768,8 +757,8 @@ static bool parseDrawSet(std::istream& input, DrawSet& set, int& lines) set.wantList = true; else if (strcasecmp(label.c_str(), "center") == 0) { - if (!(parms >> set.sphere[0]) || !(parms >> set.sphere[1]) || - !(parms >> set.sphere[2])) + if (!(parms >> set.position[0]) || !(parms >> set.position[1]) || + !(parms >> set.position[2])) { success = false; logDebugMessage(0,"Bad center\n"); @@ -777,8 +766,8 @@ static bool parseDrawSet(std::istream& input, DrawSet& set, int& lines) } else if (strcasecmp(label.c_str(), "sphere") == 0) { - if (!(parms >> set.sphere[0]) || !(parms >> set.sphere[1]) || - !(parms >> set.sphere[2]) || !(parms >> set.sphere[3])) + if (!(parms >> set.position[0]) || !(parms >> set.position[1]) || + !(parms >> set.position[2]) || !(parms >> set.radius2)) { success = false; logDebugMessage(0,"Bad sphere\n"); @@ -883,9 +872,9 @@ bool MeshDrawInfo::parse(std::istream& input) std::vector pCorners; std::vector pLods; std::vector pRadarLods; - std::vector pVerts; - std::vector pNorms; - std::vector pTxcds; + std::vector pVerts; + std::vector pNorms; + std::vector pTxcds; setupDrawModeMap(); finishLine(input); // flush the rest of the "drawInfo" line @@ -938,8 +927,8 @@ bool MeshDrawInfo::parse(std::istream& input) } else if (strcasecmp(cmd.c_str(), "center") == 0) { - if (!(parms >> sphere[0]) || !(parms >> sphere[1]) || - !(parms >> sphere[2])) + if (!(parms >> position[0]) || !(parms >> position[1]) || + !(parms >> position[2])) { success = false; logDebugMessage(0,"Bad center\n"); @@ -947,8 +936,8 @@ bool MeshDrawInfo::parse(std::istream& input) } else if (strcasecmp(cmd.c_str(), "sphere") == 0) { - if (!(parms >> sphere[0]) || !(parms >> sphere[1]) || - !(parms >> sphere[2]) || !(parms >> sphere[3])) + if (!(parms >> position[0]) || !(parms >> position[1]) || + !(parms >> position[2]) || !(parms >> radius2)) { success = false; logDebugMessage(0,"Bad sphere\n"); @@ -974,7 +963,7 @@ bool MeshDrawInfo::parse(std::istream& input) } else if (strcasecmp(cmd.c_str(), "vertex") == 0) { - cfvec3 v; + glm::vec3 v; if ((parms >> v[0]) && (parms >> v[1]) && (parms >> v[2])) pVerts.push_back(v); else @@ -985,7 +974,7 @@ bool MeshDrawInfo::parse(std::istream& input) } else if (strcasecmp(cmd.c_str(), "normal") == 0) { - cfvec3 n; + glm::vec3 n; if ((parms >> n[0]) && (parms >> n[1]) && (parms >> n[2])) pNorms.push_back(n); else @@ -996,7 +985,7 @@ bool MeshDrawInfo::parse(std::istream& input) } else if (strcasecmp(cmd.c_str(), "texcoord") == 0) { - cfvec2 t; + glm::vec2 t; if ((parms >> t[0]) && (parms >> t[1])) pTxcds.push_back(t); else @@ -1051,25 +1040,25 @@ bool MeshDrawInfo::parse(std::istream& input) if (!pVerts.empty()) { rawVertCount = pVerts.size(); - rawVerts = new afvec3[rawVertCount]; + rawVerts = new glm::vec3[rawVertCount]; for (i = 0; i < rawVertCount; i++) - memcpy(rawVerts[i], pVerts[i].data, sizeof(afvec3)); + rawVerts[i] = pVerts[i]; } // make raw norms if (!pNorms.empty()) { rawNormCount = pNorms.size(); - rawNorms = new afvec3[rawNormCount]; + rawNorms = new glm::vec3[rawNormCount]; for (i = 0; i < rawNormCount; i++) - memcpy(rawNorms[i], pNorms[i].data, sizeof(afvec3)); + rawNorms[i] = pNorms[i]; } // make raw texcoords if (!pTxcds.empty()) { rawTxcdCount = pTxcds.size(); - rawTxcds = new afvec2[rawTxcdCount]; + rawTxcds = new glm::vec2[rawTxcdCount]; for (i = 0; i < rawTxcdCount; i++) - memcpy(rawTxcds[i], pTxcds[i].data, sizeof(afvec2)); + rawTxcds[i] = pTxcds[i]; } // ask for all display lists @@ -1124,10 +1113,10 @@ void MeshDrawInfo::print(std::ostream& out, const std::string& indent) const << extents.maxs[0] << " " << extents.maxs[1] << " " << extents.maxs[2] << std::endl; - out << indent << " sphere " << sphere[0] << " " - << sphere[1] << " " - << sphere[2] << " " - << sphere[3] << std::endl; + out << indent << " sphere " << position[0] << " " + << position[1] << " " + << position[2] << " " + << radius2 << std::endl; if (animInfo != NULL) { @@ -1139,21 +1128,21 @@ void MeshDrawInfo::print(std::ostream& out, const std::string& indent) const // raw vertices for (i = 0; i < rawVertCount; i++) { - const afvec3& v = rawVerts[i]; + const auto &v = rawVerts[i]; out << indent << " vertex " << v[0] << " " << v[1] << " " << v[2] << std::endl; } // raw normals for (i = 0; i < rawNormCount; i++) { - const afvec3& n = rawNorms[i]; + const auto &n = rawNorms[i]; out << indent << " normal " << n[0] << " " << n[1] << " " << n[2] << std::endl; } // raw texcoords for (i = 0; i < rawTxcdCount; i++) { - const afvec2& t = rawTxcds[i]; + const auto &t = rawTxcds[i]; out << indent << " texcoord " << t[0] << " " << t[1] << std::endl; } @@ -1180,10 +1169,10 @@ void MeshDrawInfo::print(std::ostream& out, const std::string& indent) const out << std::endl; if (set.wantList) out << indent << " dlist" << std::endl; - out << indent << " sphere " << set.sphere[0] << " " - << set.sphere[1] << " " - << set.sphere[2] << " " - << set.sphere[3] << std::endl; + out << indent << " sphere " << set.position[0] << " " + << set.position[1] << " " + << set.position[2] << " " + << set.radius2 << std::endl; const int cmdCount = set.count; for (int k = 0; k < cmdCount; k++) { @@ -1295,13 +1284,13 @@ int MeshDrawInfo::packSize() const // raw vertices fullSize += sizeof(int32_t); // count - fullSize += sizeof(afvec3) * rawVertCount; + fullSize += sizeof(float[3]) * rawVertCount; // raw normals fullSize += sizeof(int32_t); // count - fullSize += sizeof(afvec3) * rawNormCount; + fullSize += sizeof(float[3]) * rawNormCount; // raw texcoords fullSize += sizeof(int32_t); // count - fullSize += sizeof(afvec2) * rawTxcdCount; + fullSize += sizeof(float[2]) * rawTxcdCount; // lods fullSize += sizeof(int32_t); // count @@ -1374,8 +1363,8 @@ void* MeshDrawInfo::pack(void* buf) const buf = radarLods[i].pack(buf); // sphere and extents - buf = nboPackVector(buf, sphere); - buf = nboPackFloat(buf, sphere[3]); + buf = nboPackVector(buf, position); + buf = nboPackFloat(buf, radius2); buf = nboPackVector(buf, extents.mins); buf = nboPackVector(buf, extents.maxs); @@ -1424,19 +1413,19 @@ const void* MeshDrawInfo::unpack(const void* buf) // raw vertices buf = nboUnpackInt (buf, s32); rawVertCount = s32; - rawVerts = new afvec3[rawVertCount]; + rawVerts = new glm::vec3[rawVertCount]; for (i = 0; i < rawVertCount; i++) buf = nboUnpackVector(buf, rawVerts[i]); // raw normals buf = nboUnpackInt (buf, s32); rawNormCount = s32; - rawNorms = new afvec3[rawNormCount]; + rawNorms = new glm::vec3[rawNormCount]; for (i = 0; i < rawNormCount; i++) buf = nboUnpackVector(buf, rawNorms[i]); // raw texcoords buf = nboUnpackInt (buf, s32); rawTxcdCount = s32; - rawTxcds = new afvec2[rawTxcdCount]; + rawTxcds = new glm::vec2[rawTxcdCount]; for (i = 0; i < rawTxcdCount; i++) { buf = nboUnpackFloat(buf, rawTxcds[i][0]); @@ -1458,8 +1447,8 @@ const void* MeshDrawInfo::unpack(const void* buf) buf = radarLods[i].unpack(buf); // sphere and extents - buf = nboUnpackVector(buf, sphere); - buf = nboUnpackFloat(buf, sphere[3]); + buf = nboUnpackVector(buf, position); + buf = nboUnpackFloat(buf, radius2); buf = nboUnpackVector(buf, extents.mins); buf = nboUnpackVector(buf, extents.maxs); @@ -1689,7 +1678,8 @@ DrawSet::DrawSet() cmds = NULL; material = NULL; wantList = false; - sphere[0] = sphere[1] = sphere[2] = sphere[3] = +MAXFLOAT; + position = glm::vec3(+MAXFLOAT); + radius2 = +MAXFLOAT; return; } @@ -1728,8 +1718,8 @@ void* DrawSet::pack(void* buf) const buf = nboPackInt(buf, matindex); // sphere - buf = nboPackVector(buf, sphere); - buf = nboPackFloat(buf, sphere[3]); + buf = nboPackVector(buf, position); + buf = nboPackFloat(buf, radius2); // state bits uint8_t state = 0; @@ -1754,8 +1744,8 @@ const void* DrawSet::unpack(const void* buf) material = MATERIALMGR.getMaterial(s32); // sphere - buf = nboUnpackVector(buf, sphere); - buf = nboUnpackFloat(buf, sphere[3]); + buf = nboUnpackVector(buf, position); + buf = nboUnpackFloat(buf, radius2); // state bits uint8_t state; diff --git a/src/obstacle/MeshFace.cxx b/src/obstacle/MeshFace.cxx index 5f4ef18182..a32f8833b9 100644 --- a/src/obstacle/MeshFace.cxx +++ b/src/obstacle/MeshFace.cxx @@ -15,11 +15,16 @@ // System headers #include +#include +#include +#define GLM_ENABLE_EXPERIMENTAL +#include +#include +#include // Common headers #include "global.h" #include "Pack.h" -#include "vectors.h" #include "MeshObstacle.h" #include "PhysicsDriver.h" #include "Intersect.h" @@ -49,10 +54,11 @@ MeshFace::MeshFace(MeshObstacle* _mesh) } -MeshFace::MeshFace(MeshObstacle* _mesh, int _vertexCount, - float** _vertices, float** _normals, float** _texcoords, - const BzMaterial* _bzMaterial, int physics, - bool _noclusters, bool bounce, bool drive, bool shoot, bool rico) +MeshFace::MeshFace( + MeshObstacle* _mesh, int _vertexCount, + glm::vec3 *_vertices[], glm::vec3 **_normals, glm::vec2 **_texcoords, + const BzMaterial* _bzMaterial, int physics, + bool _noclusters, bool bounce, bool drive, bool shoot, bool rico) { mesh = _mesh; vertexCount = _vertexCount; @@ -80,29 +86,30 @@ MeshFace::MeshFace(MeshObstacle* _mesh, int _vertexCount, void MeshFace::finalize() { float maxCrossSqr = 0.0f; - float bestCross[3] = { 0.0f, 0.0f, 0.0f }; + auto bestCross = glm::vec3(0.0f); int bestSet[3] = { -1, -1, -1 }; // find the best vertices for making the plane int i, j, k; for (i = 0; i < (vertexCount - 2); i++) { + auto &verti = *vertices[i]; for (j = i; j < (vertexCount - 1); j++) { + auto &vertj = *vertices[j]; + auto edge2 = verti - vertj; for (k = j; k < (vertexCount - 0); k++) { - float edge1[3], edge2[3], cross[3]; - vec3sub(edge1, vertices[k], vertices[j]); - vec3sub(edge2, vertices[i], vertices[j]); - vec3cross(cross, edge1, edge2); - const float lenSqr = vec3dot(cross, cross); + auto edge1 = *vertices[k] - vertj; + auto cross = glm::cross(edge1, edge2); + const float lenSqr = glm::length2(cross); if (lenSqr > maxCrossSqr) { maxCrossSqr = lenSqr; bestSet[0] = i; bestSet[1] = j; bestSet[2] = k; - memcpy (bestCross, cross, sizeof(float[3])); + bestCross = cross; } } } @@ -116,7 +123,7 @@ void MeshFace::finalize() { logDebugMessage(0,":"); for (i = 0; i < vertexCount; i++) - logDebugMessage(0," %i", (int)((afvec3*)vertices[i] - mesh->getVertices())); + logDebugMessage(0," %i", vertices[i] - mesh->getVertices()); print(std::cerr, ""); } logDebugMessage(1,"\n"); @@ -127,21 +134,18 @@ void MeshFace::finalize() // make the plane float scale = 1.0f / sqrtf (maxCrossSqr); - const float* vert = vertices[bestSet[1]]; - plane[0] = bestCross[0] * scale; - plane[1] = bestCross[1] * scale; - plane[2] = bestCross[2] * scale; - plane[3] = -vec3dot(plane, vert); + const auto &vert = *vertices[bestSet[1]]; + bestCross *= scale; + plane = glm::vec4(bestCross, -glm::dot(bestCross, vert)); // see if the whole face is convex int v; + auto v0 = *vertices[0]; + auto v1 = *vertices[1]; for (v = 0; v < vertexCount; v++) { - float a[3], b[3], c[3]; - vec3sub(a, vertices[(v + 1) % vertexCount], vertices[(v + 0) % vertexCount]); - vec3sub(b, vertices[(v + 2) % vertexCount], vertices[(v + 1) % vertexCount]); - vec3cross(c, a, b); - const float d = vec3dot(c, plane); + auto &v2 = *vertices[(v + 2) % vertexCount]; + const float d = glm::mixedProduct(v1 - v0, v2 - v1, bestCross); if (d <= 0.0f) { @@ -150,7 +154,7 @@ void MeshFace::finalize() { logDebugMessage(0,":"); for (i = 0; i < vertexCount; i++) - logDebugMessage(0," %i", (int)((afvec3*)vertices[i] - mesh->getVertices())); + logDebugMessage(0," %i", vertices[i] - mesh->getVertices()); print(std::cerr, ""); } logDebugMessage(1,"\n"); @@ -158,12 +162,14 @@ void MeshFace::finalize() vertexCount = 0; return; } + v0 = v1; + v1 = v2; } // see if the vertices are coplanar for (v = 0; v < vertexCount; v++) { - const float cross = vec3dot(vertices[v], plane); + const float cross = glm::dot(*vertices[v], bestCross); if (fabsf(cross + plane[3]) > 1.0e-3) { logDebugMessage(1,"non-planar mesh face (%f)", cross + plane[3]); @@ -171,7 +177,7 @@ void MeshFace::finalize() { logDebugMessage(0,":"); for (i = 0; i < vertexCount; i++) - logDebugMessage(0," %i", (int)((afvec3*)vertices[i] - mesh->getVertices())); + logDebugMessage(0," %i", vertices[i] - mesh->getVertices()); print(std::cerr, ""); } logDebugMessage(1,"\n"); @@ -183,7 +189,7 @@ void MeshFace::finalize() // setup extents for (v = 0; v < vertexCount; v++) - extents.expandToPoint(vertices[v]); + extents.expandToPoint(*vertices[v]); // setup fake obstacle parameters pos[0] = (extents.maxs[0] + extents.mins[0]) / 2.0f; @@ -196,18 +202,15 @@ void MeshFace::finalize() ZFlip = false; // make the edge planes - edgePlanes = new afvec4[vertexCount]; + edgePlanes = new glm::vec4[vertexCount]; + v1 = *vertices[0]; for (v = 0; v < vertexCount; v++) { - float edge[3]; const int next = (v + 1) % vertexCount; - vec3sub(edge, vertices[next], vertices[v]); - vec3cross(edgePlanes[v], edge, plane); - scale = 1.0f / sqrtf(vec3dot(edgePlanes[v], edgePlanes[v])); - edgePlanes[v][0] = edgePlanes[v][0] * scale; - edgePlanes[v][1] = edgePlanes[v][1] * scale; - edgePlanes[v][2] = edgePlanes[v][2] * scale; - edgePlanes[v][3] = -vec3dot(vertices[v], edgePlanes[v]); + auto &v2 = *vertices[next]; + auto edgePlane = glm::normalize(glm::cross(v2 - v1, bestCross)); + edgePlanes[v] = glm::vec4(edgePlane, -glm::dot(v1, edgePlane)); + v1 = v2; } // set the plane type @@ -308,39 +311,32 @@ float MeshFace::intersect(const Ray& ray) const // // t = - (d + (N dot Lo)) / (N dot L) { time of impact } // - const float* dir = ray.getDirection(); - const float* origin = ray.getOrigin(); - float hitTime; + const auto &dir = ray.getDirection(); + const auto &origin = ray.getOrigin(); + const auto normal = glm::vec3(plane); // get the time until the shot would hit each plane - const float linedot = (plane[0] * dir[0]) + - (plane[1] * dir[1]) + - (plane[2] * dir[2]); - if (linedot >= -0.001f) + const float linedot = -glm::dot(normal, dir); + if (linedot <= 0.001f) { // shot is either parallel, or going through backwards return -1.0f; } - const float origindot = (plane[0] * origin[0]) + - (plane[1] * origin[1]) + - (plane[2] * origin[2]); + const float origindot = glm::dot(normal, origin); // linedot should be safe to divide with now - hitTime = - (plane[3] + origindot) / linedot; + float hitTime = plane[3] + origindot; if (hitTime < 0.0f) return -1.0f; + hitTime /= linedot; + // get the contact location - float point[3]; - point[0] = (dir[0] * hitTime) + origin[0]; - point[1] = (dir[1] * hitTime) + origin[1]; - point[2] = (dir[2] * hitTime) + origin[2]; + auto point = glm::vec4(dir * hitTime + origin, 1.0f); // now test against the edge planes for (int q = 0; q < vertexCount; q++) { - float d = (edgePlanes[q][0] * point[0]) + - (edgePlanes[q][1] * point[1]) + - (edgePlanes[q][2] * point[2]) + edgePlanes[q][3]; + float d = glm::dot(edgePlanes[q], point); if (d > 0.001f) return -1.0f; } @@ -349,12 +345,12 @@ float MeshFace::intersect(const Ray& ray) const } -void MeshFace::get3DNormal(const float* p, float* n) const +void MeshFace::get3DNormal(const glm::vec3 &p, glm::vec3 &n) const { if (!smoothBounce || !useNormals()) { // just use the plain normal - memcpy (n, plane, sizeof(float[3])); + n = plane; } else { @@ -363,14 +359,14 @@ void MeshFace::get3DNormal(const float* p, float* n) const int i; // calculate the triangle ares float* areas = new float[vertexCount]; + auto v1 = *vertices[0]; + auto vp = p; for (i = 0; i < vertexCount; i++) { int next = (i + 1) % vertexCount; - float ea[3], eb[3], cross[3]; - vec3sub(ea, p, vertices[i]); - vec3sub(eb, vertices[next], vertices[i]); - vec3cross(cross, ea, eb); - areas[i] = sqrtf(vec3dot(cross, cross)); + auto &v2 = *vertices[next]; + areas[i] = glm::length(glm::cross(vp - v1, v2 - v1)); + v1 = v2; } float smallestArea = MAXFLOAT; float* twinAreas = new float[vertexCount]; @@ -380,7 +376,7 @@ void MeshFace::get3DNormal(const float* p, float* n) const twinAreas[i] = areas[i] + areas[next]; if (twinAreas[i] < 1.0e-10f) { - memcpy (n, normals[next], sizeof(float[3])); + n = *normals[next]; delete[] areas; delete[] twinAreas; return; @@ -388,40 +384,29 @@ void MeshFace::get3DNormal(const float* p, float* n) const if (twinAreas[i] < smallestArea) smallestArea = twinAreas[i]; } - float normal[3] = {0.0f, 0.0f, 0.0f}; + delete[] areas; + auto normal = glm::vec3(0.0f); for (i = 0; i < vertexCount; i++) { int next = (i + 1) % vertexCount; float factor = smallestArea / twinAreas[i]; - normal[0] = normal[0] + (normals[next][0] * factor); - normal[1] = normal[1] + (normals[next][1] * factor); - normal[2] = normal[2] + (normals[next][2] * factor); - } - float len = sqrtf(vec3dot(normal, normal)); - if (len < 1.0e-10) - { - memcpy (n, plane, sizeof(float[3])); - delete[] areas; - delete[] twinAreas; - return; + normal += *normals[next] * factor; } - len = 1.0f / len; - n[0] = normal[0] * len; - n[1] = normal[1] * len; - n[2] = normal[2] * len; - - delete[] areas; delete[] twinAreas; + if (normal.x || normal.y || normal.z) + n = glm::normalize(normal); + else + n = plane; + return; } return; } -void MeshFace::getNormal(const float* UNUSED(p), float* n) const +void MeshFace::getNormal(const glm::vec3 &, glm::vec3 &n) const { - if (n) - memcpy (n, plane, sizeof(float[3])); + n = plane; return; } @@ -431,24 +416,23 @@ void MeshFace::getNormal(const float* UNUSED(p), float* n) const /////////////////////////////////////////////////////////////// -bool MeshFace::getHitNormal(const float* UNUSED(oldPos), float UNUSED(oldAngle), - const float* UNUSED(newPos), float UNUSED(newAngle), +bool MeshFace::getHitNormal(const glm::vec3 &UNUSED(oldPos), float UNUSED(oldAngle), + const glm::vec3 &UNUSED(newPos), float UNUSED(newAngle), float UNUSED(dx), float UNUSED(dy), float UNUSED(height), - float* normal) const + glm::vec3 &normal) const { - if (normal) - memcpy (normal, plane, sizeof(float[3])); + normal = plane; return true; } -bool MeshFace::inCylinder(const float* p,float radius, float height) const +bool MeshFace::inCylinder(const glm::vec3 &p,float radius, float height) const { return inBox(p, 0.0f, radius, radius, height); } -bool MeshFace::inBox(const float* p, float _angle, +bool MeshFace::inBox(const glm::vec3 &p, float _angle, float dx, float dy, float height) const { int i; @@ -462,23 +446,23 @@ bool MeshFace::inBox(const float* p, float _angle, // to move the polygon then the box, tris and quads will // probably be the dominant polygon types). - float pln[4]; // translated plane - afvec3* v = new afvec3[vertexCount]; // translated vertices + glm::vec4 pln; // translated plane + glm::vec3 *v = new glm::vec3[vertexCount]; // translated vertices const float cos_val = cosf(-_angle); const float sin_val = sinf(-_angle); for (i = 0; i < vertexCount; i++) { float h[2]; - h[0] = vertices[i][0] - p[0]; - h[1] = vertices[i][1] - p[1]; + h[0] = vertices[i]->x - p[0]; + h[1] = vertices[i]->y - p[1]; v[i][0] = (cos_val * h[0]) - (sin_val * h[1]); v[i][1] = (cos_val * h[1]) + (sin_val * h[0]); - v[i][2] = vertices[i][2] - p[2]; + v[i][2] = vertices[i]->z - p[2]; } pln[0] = (cos_val * plane[0]) - (sin_val * plane[1]); pln[1] = (cos_val * plane[1]) + (sin_val * plane[0]); pln[2] = plane[2]; - pln[3] = plane[3] + vec3dot(plane, p); + pln[3] = plane[3] + glm::dot(glm::vec3(plane), p); // testPolygonInAxisBox() expects us to have already done all of the // separation tests with respect to the box planes. we could not do @@ -537,12 +521,12 @@ bool MeshFace::inBox(const float* p, float _angle, } -bool MeshFace::inMovingBox(const float* oldPos, float UNUSED(oldAngle), - const float* newPos, float newAngle, +bool MeshFace::inMovingBox(const glm::vec3 &oldPos, float UNUSED(oldAngle), + const glm::vec3 &newPos, float newAngle, float dx, float dy, float height) const { // expand the box with respect to Z axis motion - float _pos[3]; + glm::vec3 _pos; _pos[0] = newPos[0]; _pos[1] = newPos[1]; if (oldPos[2] < newPos[2]) @@ -555,12 +539,11 @@ bool MeshFace::inMovingBox(const float* oldPos, float UNUSED(oldAngle), } -bool MeshFace::isCrossing(const float* UNUSED(p), float UNUSED(_angle), - float UNUSED(dx), float UNUSED(dy), float UNUSED(height), - float* _plane) const +bool MeshFace::isCrossing(const glm::vec3 &, float, float, float, float, + glm::vec4 *_plane) const { if (_plane != NULL) - memcpy(_plane, plane, sizeof(float[4])); + *_plane = plane; return true; } @@ -582,7 +565,7 @@ void *MeshFace::pack(void *buf) const buf = nboPackInt(buf, vertexCount); for (int i = 0; i < vertexCount; i++) { - int32_t index = (afvec3*)vertices[i] - mesh->getVertices(); + int32_t index = vertices[i] - mesh->getVertices(); buf = nboPackInt(buf, index); } @@ -591,7 +574,7 @@ void *MeshFace::pack(void *buf) const { for (int i = 0; i < vertexCount; i++) { - int32_t index = (afvec3*)normals[i] - mesh->getNormals(); + int32_t index = normals[i] - mesh->getNormals(); buf = nboPackInt(buf, index); } } @@ -601,7 +584,7 @@ void *MeshFace::pack(void *buf) const { for (int i = 0; i < vertexCount; i++) { - int32_t index = (afvec2*)texcoords[i] - mesh->getTexcoords(); + int32_t index = texcoords[i] - mesh->getTexcoords(); buf = nboPackInt(buf, index); } } @@ -636,35 +619,35 @@ const void *MeshFace::unpack(const void *buf) // vertices buf = nboUnpackInt(buf, inTmp); vertexCount = int(inTmp); - vertices = new float*[vertexCount]; + vertices = new glm::vec3*[vertexCount]; for (int i = 0; i < vertexCount; i++) { int32_t index; buf = nboUnpackInt(buf, index); - vertices[i] = mesh->getVertices()[index]; + vertices[i] = &mesh->getVertices()[index]; } // normals if (tmpNormals) { - normals = new float*[vertexCount]; + normals = new glm::vec3*[vertexCount]; for (int i = 0; i < vertexCount; i++) { int32_t index; buf = nboUnpackInt(buf, index); - normals[i] = mesh->getNormals()[index]; + normals[i] = &mesh->getNormals()[index]; } } // texcoords if (tmpTexcoords) { - texcoords = new float*[vertexCount]; + texcoords = new glm::vec2*[vertexCount]; for (int i = 0; i < vertexCount; i++) { int32_t index; buf = nboUnpackInt(buf, index); - texcoords[i] = mesh->getTexcoords()[index]; + texcoords[i] = &mesh->getTexcoords()[index]; } } @@ -716,14 +699,14 @@ void MeshFace::print(std::ostream& out, const std::string& indent) const out << indent << " vertices"; for (i = 0; i < vertexCount; i++) { - int index = (afvec3*)vertices[i] - mesh->getVertices(); + int index = vertices[i] - mesh->getVertices(); out << " " << index; } if (debugLevel >= 3) { out << indent << " #"; for (i = 0; i < vertexCount; i++) - out << " " << vertices[i][0] << " " << vertices[i][1] << " " << vertices[i][2]; + out << " " << vertices[i]->x << " " << vertices[i]->y << " " << vertices[i]->z; } out << std::endl; @@ -732,14 +715,14 @@ void MeshFace::print(std::ostream& out, const std::string& indent) const out << indent << " normals"; for (i = 0; i < vertexCount; i++) { - int index = (afvec3*)normals[i] - mesh->getNormals(); + int index = normals[i] - mesh->getNormals(); out << " " << index; } if (debugLevel >= 3) { out << " #"; for (i = 0; i < vertexCount; i++) - out << " " << normals[i][0] << " " << normals[i][1] << " " << normals[i][2]; + out << " " << normals[i]->x << " " << normals[i]->y << " " << normals[i]->z; } out << std::endl; } @@ -749,14 +732,14 @@ void MeshFace::print(std::ostream& out, const std::string& indent) const out << indent << " texcoords"; for (i = 0; i < vertexCount; i++) { - int index = (afvec2*)texcoords[i] - mesh->getTexcoords(); + int index = texcoords[i] - mesh->getTexcoords(); out << " " << index; } if (debugLevel >= 3) { out << " #"; for (i = 0; i < vertexCount; i++) - out << " " << texcoords[i][0] << " " << texcoords[i][1]; + out << " " << texcoords[i]->s << " " << texcoords[i]->t; } out << std::endl; } diff --git a/src/obstacle/MeshObstacle.cxx b/src/obstacle/MeshObstacle.cxx index afa685fafe..4ec4408223 100644 --- a/src/obstacle/MeshObstacle.cxx +++ b/src/obstacle/MeshObstacle.cxx @@ -18,6 +18,7 @@ // system headers #include #include +#include // common headers #include "global.h" @@ -44,7 +45,8 @@ MeshObstacle::MeshObstacle() checkTypes = NULL; checkPoints = NULL; vertexCount = normalCount = 0; - vertices = normals = NULL; + vertices = NULL; + normals = NULL; texcoordCount = 0; texcoords = NULL; noclusters = false; @@ -58,18 +60,18 @@ MeshObstacle::MeshObstacle() } -static void cfvec3ListToArray(const std::vector& list, - int& count, afvec3* &array) +static void cfvec3ListToArray(const std::vector& list, + int& count, glm::vec3 *&array) { count = list.size(); - array = new afvec3[count]; + array = new glm::vec3[count]; for (int i = 0; i < count; i++) - memcpy (array[i], list[i].data, sizeof(afvec3)); + array[i] = list[i]; return; } -static void arrayToCafvec3List(const afvec3* array, int count, - std::vector& list) +static void arrayToCafvec3List(const glm::vec3 *array, int count, + std::vector& list) { list.clear(); for (int i = 0; i < count; i++) @@ -80,10 +82,10 @@ static void arrayToCafvec3List(const afvec3* array, int count, MeshObstacle::MeshObstacle(const MeshTransform& transform, const std::vector& checkTypesL, - const std::vector& checkList, - const std::vector& verticeList, - const std::vector& normalList, - const std::vector& texcoordList, + const std::vector& checkList, + const std::vector& verticeList, + const std::vector& normalList, + const std::vector& texcoordList, int _faceCount, bool _noclusters, bool bounce, bool drive, bool shoot, bool rico) { @@ -111,9 +113,9 @@ MeshObstacle::MeshObstacle(const MeshTransform& transform, xformtool.modifyNormal(normals[j]); texcoordCount = texcoordList.size(); - texcoords = new afvec2[texcoordCount]; + texcoords = new glm::vec2[texcoordCount]; for (i = 0; i < (unsigned int)texcoordCount; i++) - memcpy (texcoords[i], texcoordList[i].data, sizeof(afvec2)); + texcoords[i] = texcoordList[i]; faceSize = _faceCount; faceCount = 0; @@ -169,7 +171,14 @@ bool MeshObstacle::addFace(const std::vector& _vertices, } // use the indices to makes lists of pointers - float **v, **n, **t; + auto v = new glm::vec3*[count]; + glm::vec3 **n = nullptr; + if (!_normals.empty()) + n = new glm::vec3*[count]; + glm::vec2 **t = nullptr; + if (!_texcoords.empty()) + t = new glm::vec2*[count]; + makeFacePointers(_vertices, _normals, _texcoords, v, n, t); // override the flags if they are set for the whole mesh @@ -183,21 +192,17 @@ bool MeshObstacle::addFace(const std::vector& _vertices, triangulate = triangulate && (count > 3); // make the face - MeshFace* face; + int tmpDebugLevel; if (triangulate) { // avoid warnings that may not apply - int tmpDebugLevel = debugLevel; + tmpDebugLevel = debugLevel; debugLevel = 0; - face = new MeshFace(this, count, v, n, t, _material, phydrv, - _noclusters, bounce, drive, shoot, rico); - debugLevel = tmpDebugLevel; - } - else - { - face = new MeshFace(this, count, v, n, t, _material, phydrv, - _noclusters, bounce, drive, shoot, rico); } + auto face = new MeshFace(this, count, v, n, t, _material, phydrv, + _noclusters, bounce, drive, shoot, rico); + if (triangulate) + debugLevel = tmpDebugLevel; // check its validity if (face->isValid()) @@ -210,6 +215,7 @@ bool MeshObstacle::addFace(const std::vector& _vertices, // triangulate std::vector triIndices; triangulateFace(count, v, triIndices); + v = nullptr; delete face; // delete the old face const unsigned int triSize = triIndices.size(); if (triSize == 0) @@ -236,9 +242,19 @@ bool MeshObstacle::addFace(const std::vector& _vertices, if (_texcoords.size() > 0) triT.push_back(_texcoords[index]); } + v = new glm::vec3*[3]; + if (triN.empty()) + n = nullptr; + else + n = new glm::vec3*[3]; + if (triT.empty()) + t = nullptr; + else + t = new glm::vec2*[3]; makeFacePointers(triV, triN, triT, v, n, t); face = new MeshFace(this, 3, v, n, t, _material, phydrv, _noclusters, bounce, drive, shoot, rico); + v = nullptr; if (face->isValid()) { faces[faceCount] = face; @@ -263,29 +279,20 @@ bool MeshObstacle::addFace(const std::vector& _vertices, void MeshObstacle::makeFacePointers(const std::vector& _vertices, const std::vector& _normals, const std::vector& _texcoords, - float**& v, float**& n, float**& t) + glm::vec3 *v[], glm::vec3 **n, glm::vec2 **t) { const int count = _vertices.size(); // use the indices to makes lists of pointers - v = new float*[count]; - n = NULL; - t = NULL; - - if (_normals.size() > 0) - n = new float*[count]; - if (_texcoords.size() > 0) - t = new float*[count]; - for (int i = 0; i < count; i++) { // invert the vertices if required int index = (inverted ? ((count - 1) - i) : i); - v[index] = (float*)vertices[_vertices[i]]; + v[index] = &vertices[_vertices[i]]; if (n != NULL) - n[index] = (float*)normals[_normals[i]]; + n[index] = &normals[_normals[i]]; if (t != NULL) - t[index] = (float*)texcoords[_texcoords[i]]; + t[index] = &texcoords[_texcoords[i]]; } return; } @@ -310,10 +317,10 @@ Obstacle* MeshObstacle::copyWithTransform(const MeshTransform& xform) const { MeshObstacle* copy; std::vector ctlist; - std::vector clist; - std::vector vlist; - std::vector nlist; - std::vector tlist; + std::vector clist; + std::vector vlist; + std::vector nlist; + std::vector tlist; // empty arrays for copies of pure visual meshes if ((drawInfo != NULL) && @@ -360,17 +367,17 @@ void MeshObstacle::copyFace(int f, MeshObstacle* mesh) const for (int i = 0; i < vcount; i++) { int index; - index = ((const afvec3*) face->getVertex(i)) - vertices; + index = &face->getVertex(i) - vertices; vlist.push_back(index); if (face->useNormals()) { - index = ((const afvec3*) face->getNormal(i)) - normals; + index = &face->getNormal(i) - normals; nlist.push_back(index); } if (face->useTexcoords()) { - index = ((const afvec2*) face->getTexcoord(i)) - texcoords; + index = &face->getTexcoord(i) - texcoords; tlist.push_back(index); } } @@ -463,7 +470,7 @@ bool MeshObstacle::isValid() const } -bool MeshObstacle::containsPoint(const float point[3]) const +bool MeshObstacle::containsPoint(const glm::vec3 &point) const { // this should use the CollisionManager's rayTest function // const ObsList* olist = COLLISIONMGR.rayTest (&ray, t); @@ -471,21 +478,22 @@ bool MeshObstacle::containsPoint(const float point[3]) const } -bool MeshObstacle::containsPointNoOctree(const float point[3]) const +bool MeshObstacle::containsPointNoOctree(const glm::vec3 &point) const { if (checkCount <= 0) return false; int c, f; - float dir[3]; bool hasOutsides = false; + const auto glmPoint = point; for (c = 0; c < checkCount; c++) { + const auto checkPoint = checkPoints[c]; if (checkTypes[c] == CheckInside) { - vec3sub (dir, checkPoints[c], point); - Ray ray(point, dir); + auto dir = checkPoint - glmPoint; + Ray ray(glmPoint, dir); bool hitFace = false; for (f = 0; f < faceCount; f++) { @@ -503,8 +511,8 @@ bool MeshObstacle::containsPointNoOctree(const float point[3]) const else if (checkTypes[c] == CheckOutside) { hasOutsides = true; - vec3sub (dir, point, checkPoints[c]); - Ray ray(checkPoints[c], dir); + auto dir = glmPoint - checkPoint; + Ray ray(checkPoint, dir); bool hitFace = false; for (f = 0; f < faceCount; f++) { @@ -536,105 +544,88 @@ float MeshObstacle::intersect(const Ray& UNUSED(ray)) const } -void MeshObstacle::get3DNormal(const float* UNUSED(p), float* UNUSED(n)) const +void MeshObstacle::get3DNormal(const glm::vec3 &, glm::vec3 &) const { return; // this should never be called if intersect() is always < 0.0f } -void MeshObstacle::getNormal(const float* p, float* n) const +void MeshObstacle::getNormal(const glm::vec3 &p, glm::vec3 &n) const { - const afvec3 center = { pos[0], pos[1], pos[2] + (0.5f * size[2]) }; - afvec3 out; - vec3sub (out, p, center); + const auto center = glm::vec3(pos[0], pos[1], pos[2] + (0.5f * size[2])); + auto out = p - center; if (out[2] < 0.0f) out[2] = 0.0f; - float len = vec3dot(out, out); - if (len > 0.0f) - { - len = 1 / sqrtf(len); - n[0] = out[0] * len; - n[1] = out[1] * len; - n[2] = out[2] * len; - } + if (out.x || out.y || out.z) + n = glm::normalize(out); else - { - n[0] = 0.0f; - n[1] = 0.0f; - n[2] = 1.0f; - } + n = glm::vec3(0.0f, 0.0f, 1.0f); return; } -bool MeshObstacle::getHitNormal(const float* UNUSED(oldPos), float UNUSED(oldAngle), - const float* p, float UNUSED(_angle), +bool MeshObstacle::getHitNormal(const glm::vec3 &UNUSED(oldPos), float UNUSED(oldAngle), + const glm::vec3 &p, float UNUSED(_angle), float, float, float UNUSED(height), - float* n) const + glm::vec3 &n) const { - if (n != NULL) - getNormal(p, n); + getNormal(p, n); return true; } -bool MeshObstacle::inCylinder(const float* p, +bool MeshObstacle::inCylinder(const glm::vec3 &p, float UNUSED(radius), float height) const { - const float mid[3] = { p[0], p[1], p[2] + (0.5f * height) }; + auto mid = p; + mid.z += 0.5f * height; return containsPoint(mid); } -bool MeshObstacle::inBox(const float* p, float UNUSED(_angle), +bool MeshObstacle::inBox(const glm::vec3 &p, float UNUSED(_angle), float UNUSED(dx), float UNUSED(dy), float height) const { - const float mid[3] = { p[0], p[1], p[2] + (0.5f * height) }; + auto mid = p; + mid.z += 0.5f * height; return containsPoint(mid); } -bool MeshObstacle::inMovingBox(const float*, float, - const float* p, float UNUSED(_angle), +bool MeshObstacle::inMovingBox(const glm::vec3 &, float, + const glm::vec3 &p, float UNUSED(_angle), float UNUSED(dx), float UNUSED(dy), float height) const { - const float mid[3] = { p[0], p[1], p[2] + (0.5f * height) }; + auto mid = p; + mid.z += 0.5f * height; return containsPoint(mid); } -bool MeshObstacle::isCrossing(const float* UNUSED(p), float UNUSED(_angle), - float UNUSED(dx), float UNUSED(dy), float UNUSED(height), - float* UNUSED(plane)) const -{ - return false; // the MeshFaces should handle this case -} - - int MeshObstacle::packSize() const { int fullSize = 5 * sizeof(int32_t); fullSize += sizeof(char) * checkCount; - fullSize += sizeof(afvec3) * checkCount; - fullSize += sizeof(afvec3) * vertexCount; - fullSize += sizeof(afvec3) * normalCount; - fullSize += sizeof(afvec2) * texcoordCount; + fullSize += sizeof(float[3]) * checkCount; + fullSize += sizeof(float[3]) * vertexCount; + fullSize += sizeof(float[3]) * normalCount; + fullSize += sizeof(float[2]) * texcoordCount; if ((drawInfo != NULL) && !drawInfo->isCopy()) { const int drawInfoPackSize = drawInfo->packSize(); // align the packing - const int align = sizeof(afvec2); + const int align = sizeof(float[2]); fullSize += align * ((drawInfoPackSize + (align - 1)) / align); // drawInfo fake txcd count - fullSize += sizeof(afvec2); + fullSize += sizeof(float[2]); if (debugLevel >= 4) { logDebugMessage(0,"DrawInfo packSize = %i, align = %i, full = %i\n", drawInfoPackSize, align * ((drawInfoPackSize + (align - 1)) / align), - align * ((drawInfoPackSize + (align - 1)) / align) + (int)sizeof(afvec2)); + align * ((drawInfoPackSize + (align - 1)) / align) + (int)sizeof(float[2])); } } for (int f = 0; f < faceCount; f++) @@ -678,23 +669,23 @@ void *MeshObstacle::pack(void *buf) const void* drawInfoStart = buf; buf = drawInfo->pack(buf); // align the packing - const int align = sizeof(afvec2); + const int align = sizeof(float[2]); const int length = (char*)buf - (char*)drawInfoStart; const int missing = (align - (length % align)) % align; for (i = 0; i < missing; i++) buf = nboPackUByte(buf, 0); // bump up the texture coordinate count const int fullLength = ((char*)buf - (char*)drawInfoStart); - const int extraTxcds = fullLength / sizeof(afvec2); + const int extraTxcds = fullLength / sizeof(float[2]); const int fakeTxcdCount = texcoordCount + extraTxcds + 1; nboPackInt(txcdStart, fakeTxcdCount); // NOTE: 'buf' is not being set // add the drawInfo length at the end - buf = nboPackInt(buf, fullLength + sizeof(afvec2)); - buf = nboPackInt(buf, 0); // for alignment to afvec2 + buf = nboPackInt(buf, fullLength + sizeof(float[2])); + buf = nboPackInt(buf, 0); // for alignment to 2 floats logDebugMessage(4,"DrawInfo packing: length = %i, missing = %i\n", length, missing); logDebugMessage(4," texcoordCount = %i, fakeTxcdCount = %i, rewindLen = %i\n", - texcoordCount, fakeTxcdCount, fullLength + (int)sizeof(afvec2)); + texcoordCount, fakeTxcdCount, fullLength + (int)sizeof(float[2])); } buf = nboPackInt(buf, faceCount); @@ -723,7 +714,7 @@ const void *MeshObstacle::unpack(const void *buf) buf = nboUnpackInt(buf, inTmp); checkCount = int(inTmp); checkTypes = new char[checkCount]; - checkPoints = new afvec3[checkCount]; + checkPoints = new glm::vec3[checkCount]; for (i = 0; i < checkCount; i++) { unsigned char tmp; @@ -734,19 +725,19 @@ const void *MeshObstacle::unpack(const void *buf) buf = nboUnpackInt(buf, inTmp); vertexCount = int(inTmp); - vertices = new afvec3[vertexCount]; + vertices = new glm::vec3[vertexCount]; for (i = 0; i < vertexCount; i++) buf = nboUnpackVector(buf, vertices[i]); buf = nboUnpackInt(buf, inTmp); normalCount = int(inTmp); - normals = new afvec3[normalCount]; + normals = new glm::vec3[normalCount]; for (i = 0; i < normalCount; i++) buf = nboUnpackVector(buf, normals[i]); buf = nboUnpackInt(buf, inTmp); texcoordCount = int(inTmp); - texcoords = new afvec2[texcoordCount]; + texcoords = new glm::vec2[texcoordCount]; // note where the texture coordinates begin; skip past them const void* texCoordPtr = buf; buf = (const char*)buf + sizeof(float) * 2 * texcoordCount; @@ -788,13 +779,13 @@ const void *MeshObstacle::unpack(const void *buf) { nboUseErrorChecking(false); { - const void* drawInfoSize = texcoordEnd - sizeof(afvec2); + const void* drawInfoSize = texcoordEnd - sizeof(float[2]); int32_t rewindLen; nboUnpackInt(drawInfoSize, rewindLen); const bool useDrawInfo = BZDB.isTrue("useDrawInfo"); - if (rewindLen <= (int)(texcoordCount * sizeof(afvec2))) + if (rewindLen <= (int)(texcoordCount * sizeof(float[2]))) { // unpack the drawInfo if (useDrawInfo) @@ -807,11 +798,11 @@ const void *MeshObstacle::unpack(const void *buf) // free the bogus texcoords // FIXME - don't allocate storage we won't use - const int fakeTxcds = rewindLen / sizeof(afvec2); + const int fakeTxcds = rewindLen / sizeof(float[2]); texcoordCount = texcoordCount - fakeTxcds; - afvec2* tmpTxcds = new afvec2[texcoordCount]; + auto tmpTxcds = new glm::vec2[texcoordCount]; delete[] texcoords; - int ptrDiff = (char*)tmpTxcds - (char*)texcoords; + int ptrDiff = tmpTxcds - texcoords; texcoords = tmpTxcds; // unpack actual texcoords for (i = 0; i < texcoordCount; i++) @@ -836,13 +827,8 @@ const void *MeshObstacle::unpack(const void *buf) { MeshFace* face = faces[i]; if (face->useTexcoords()) - { for (int v = 0; v < face->getVertexCount(); v++) - { - face->texcoords[v] = - (float*)((char*)face->texcoords[v] + ptrDiff); - } - } + face->texcoords[v] += ptrDiff; } logDebugMessage(4,"DrawInfo unpacking: fakeTxcds = %i, realTxcds = %i\n", @@ -976,8 +962,7 @@ void MeshObstacle::printOBJ(std::ostream& out, const std::string& UNUSED(indent) out << "# normals = " << normalCount << std::endl; out << "# texcoords = " << texcoordCount << std::endl; - const float* tmp; - tmp = extents.mins; + auto tmp = extents.mins; out << "# mins = " << tmp[0] << " " << tmp[1] << " " << tmp[2] << std::endl; tmp = extents.maxs; out << "# maxs = " << tmp[0] << " " << tmp[1] << " " << tmp[2] << std::endl; @@ -1024,12 +1009,12 @@ void MeshObstacle::printOBJ(std::ostream& out, const std::string& UNUSED(indent) out << "f"; for (i = 0; i < vCount; i++) { - int vIndex = (const afvec3*)face->getVertex(i) - vertices; + int vIndex = &face->getVertex(i) - vertices; vIndex = vIndex - vertexCount; out << " " << vIndex; if (useTexcoords) { - int tIndex = (const afvec2*)face->getTexcoord(i) - texcoords; + int tIndex = &face->getTexcoord(i) - texcoords; tIndex = tIndex - texcoordCount; out << "/" << tIndex; } @@ -1037,7 +1022,7 @@ void MeshObstacle::printOBJ(std::ostream& out, const std::string& UNUSED(indent) { if (!useTexcoords) out << "/"; - int nIndex = (const afvec3*)face->getNormal(i) - normals; + int nIndex = &face->getNormal(i) - normals; nIndex = nIndex - normalCount; out << "/" << nIndex; } diff --git a/src/obstacle/MeshSceneNodeGenerator.cxx b/src/obstacle/MeshSceneNodeGenerator.cxx index 139ca22a0f..f8de1d04ab 100644 --- a/src/obstacle/MeshSceneNodeGenerator.cxx +++ b/src/obstacle/MeshSceneNodeGenerator.cxx @@ -16,6 +16,11 @@ // System headers #include +#include +#include +#include +#define GLM_ENABLE_EXPERIMENTAL +#include // Common headers #include "MeshObstacle.h" @@ -130,7 +135,7 @@ static bool translucentMaterial(const BzMaterial* mat) static bool groundClippedFace(const MeshFace* face) { - const float* plane = face->getPlane(); + const auto &plane = face->getPlane(); if (plane[2] < -0.9f) { // plane is facing downwards @@ -371,24 +376,24 @@ MeshPolySceneNode* MeshSceneNodeGenerator::getMeshPolySceneNode(const MeshFace* // vertices const int vertexCount = face->getVertexCount(); - GLfloat3Array vertices(vertexCount); + std::vector vertices(vertexCount); for (i = 0; i < vertexCount; i++) - memcpy (vertices[i], face->getVertex(i), sizeof(float[3])); + vertices[i] = face->getVertex(i); // normals int normalCount = 0; if (face->useNormals()) normalCount = vertexCount; - GLfloat3Array normals(normalCount); + std::vector normals(normalCount); for (i = 0; i < normalCount; i++) - memcpy (normals[i], face->getNormal(i), sizeof(float[3])); + normals[i] = face->getNormal(i); // texcoords - GLfloat2Array texcoords(vertexCount); + std::vector texcoords(vertexCount); if (face->useTexcoords()) { for (i = 0; i < vertexCount; i++) - memcpy (texcoords[i], face->getTexcoord(i), sizeof(float[2])); + texcoords[i] = face->getTexcoord(i); } else makeTexcoords (face->getPlane(), vertices, texcoords); @@ -440,7 +445,7 @@ void MeshSceneNodeGenerator::setupNodeMaterial(WallSceneNode* node, // could use the ambient color for non-lighted,and diffuse // for lighted const DynamicColor* dyncol = DYNCOLORMGR.getColor(mat->getDynamicColor()); - const GLfloat* dc = NULL; + const glm::vec4 *dc = NULL; if (dyncol != NULL) dc = dyncol->getColor(); node->setDynamicColor(dc); @@ -483,7 +488,7 @@ void MeshSceneNodeGenerator::setupNodeMaterial(WallSceneNode* node, // we'll just set it to the middle value. if (dyncol) { - const float color[4] = { 1.0f, 1.0f, 1.0f, 0.5f }; // alpha value != 1.0f + const auto color = glm::vec4(1.0f, 1.0f, 1.0f, 0.5f); // alpha value != 1.0f if (dyncol->canHaveAlpha()) { node->setColor(color); // trigger transparency check @@ -499,51 +504,34 @@ void MeshSceneNodeGenerator::setupNodeMaterial(WallSceneNode* node, } -bool MeshSceneNodeGenerator::makeTexcoords(const float* plane, - const GLfloat3Array& vertices, - GLfloat2Array& texcoords) +void MeshSceneNodeGenerator::makeTexcoords(const glm::vec4 &plane, + const std::vector &vertices, + std::vector &texcoords) { - float x[3], y[3]; + const auto vert0 = vertices[0]; + const auto vert1 = vertices[1]; - vec3sub (x, vertices[1], vertices[0]); - vec3cross (y, plane, x); + auto x = vert1 - vert0; + if (glm::isNull(x, 1.0e-6f)) + return; + x = glm::normalize(x); - float len = vec3dot(x, x); - if (len > 0.0f) - { - len = 1.0f / sqrtf(len); - x[0] = x[0] * len; - x[1] = x[1] * len; - x[2] = x[2] * len; - } - else - return false; - - len = vec3dot(y, y); - if (len > 0.0f) - { - len = 1.0f / sqrtf(len); - y[0] = y[0] * len; - y[1] = y[1] * len; - y[2] = y[2] * len; - } - else - return false; + auto y = glm::cross(glm::vec3(plane), x); + if (glm::isNull(y, 1.0e-6f)) + return; + y = glm::normalize(y); const float uvScale = 8.0f; - texcoords[0][0] = 0.0f; - texcoords[0][1] = 0.0f; - const int count = vertices.getSize(); + texcoords[0] = glm::vec2(0.0f); + const int count = vertices.size(); for (int i = 1; i < count; i++) { - float delta[3]; - vec3sub (delta, vertices[i], vertices[0]); - texcoords[i][0] = vec3dot(delta, x) / uvScale; - texcoords[i][1] = vec3dot(delta, y) / uvScale; + auto delta = vertices[i] - vert0; + auto deltax = glm::dot(delta, x); + auto deltay = glm::dot(delta, y); + texcoords[i] = glm::vec2(deltax, deltay) / uvScale; } - - return true; } diff --git a/src/obstacle/Obstacle.cxx b/src/obstacle/Obstacle.cxx index 0c25c23209..3eff85a9b1 100644 --- a/src/obstacle/Obstacle.cxx +++ b/src/obstacle/Obstacle.cxx @@ -28,8 +28,8 @@ int Obstacle::objCounter = 0; Obstacle::Obstacle() { - memset(pos, 0, sizeof(float) * 3); - memset(size, 0, sizeof(float) * 3); + pos = glm::vec3(0.0f); + size = glm::vec3(0.0f); angle = 0; driveThrough = false; shootThrough = false; @@ -41,13 +41,11 @@ Obstacle::Obstacle() insideNodes = NULL; } -Obstacle::Obstacle(const float* _pos, float _angle, +Obstacle::Obstacle(const glm::vec3 &_pos, float _angle, float _width, float _breadth, float _height, bool drive, bool shoot, bool rico) { - pos[0] = _pos[0]; - pos[1] = _pos[1]; - pos[2] = _pos[2]; + pos = _pos; angle = _angle; size[0] = _width; size[1] = _breadth; @@ -83,12 +81,13 @@ void Obstacle::setExtents() { float xspan = (fabsf(cosf(angle)) * size[0]) + (fabsf(sinf(angle)) * size[1]); float yspan = (fabsf(cosf(angle)) * size[1]) + (fabsf(sinf(angle)) * size[0]); - extents.mins[0] = pos[0] - xspan; - extents.maxs[0] = pos[0] + xspan; - extents.mins[1] = pos[1] - yspan; - extents.maxs[1] = pos[1] + yspan; - extents.mins[2] = pos[2]; - extents.maxs[2] = pos[2] + size[2]; + extents.mins = pos; + extents.maxs = pos; + extents.mins[0] -= xspan; + extents.maxs[0] += xspan; + extents.mins[1] -= yspan; + extents.maxs[1] += yspan; + extents.maxs[2] += size[2]; return; } @@ -108,20 +107,45 @@ bool Obstacle::getZFlip ( void ) const } -bool Obstacle::isCrossing(const float*, float, - float, float, float, float*) const +void Obstacle::get3DNormal(const glm::vec3 &p, glm::vec3 &n) const +{ + getNormal(p, n); +} + +bool Obstacle::inBox(const glm::vec3 &, float, float, float, float) const +{ + return false; +} + +bool Obstacle::getHitNormal(const glm::vec3 &, float, + const glm::vec3 &, float, + float, float, + float, glm::vec3 &) const +{ + return false; +} + +bool Obstacle::inMovingBox(const glm::vec3 &, float, const glm::vec3 &, float, + float, float, float) const +{ + assert(false); + return false; +} + +bool Obstacle::isCrossing(const glm::vec3 &, float, + float, float, float, glm::vec4 *) const { // never crossing by default return false; } float Obstacle::getHitNormal( - const float* pos1, float azimuth1, - const float* pos2, float azimuth2, + const glm::vec3 &pos1, float azimuth1, + const glm::vec3 &pos2, float azimuth2, float width, float breadth, - const float* oPos, float oAzimuth, + const glm::vec3 &oPos, float oAzimuth, float oWidth, float oBreadth, float oHeight, - float* normal) const + glm::vec3 &normal) const { static const float square[4][2] = { @@ -141,13 +165,14 @@ float Obstacle::getHitNormal( float minTime = 1.0f; for (i = 0; i < 4; i++) { - float p[3], d[3]; - p[0] = pos1[0] + square[i][0]*c1*width - square[i][1]*s1*breadth; - p[1] = pos1[1] + square[i][0]*s1*width + square[i][1]*c1*breadth; - p[2] = 0; - d[0] = pos2[0] + square[i][0]*c2*width - square[i][1]*s2*breadth - p[0]; - d[1] = pos2[1] + square[i][0]*s2*width + square[i][1]*c2*breadth - p[1]; - d[2] = 0; + auto p = glm::vec3( + pos1[0] + square[i][0]*c1*width - square[i][1]*s1*breadth, + pos1[1] + square[i][0]*s1*width + square[i][1]*c1*breadth, + 0.0f); + auto d = glm::vec3( + pos2[0] + square[i][0]*c2*width - square[i][1]*s2*breadth, + pos2[1] + square[i][0]*s2*width + square[i][1]*c2*breadth, + 0.0f) - p; int side; const float t = timeAndSideRayHitsRect(Ray(p, d), oPos, oAzimuth, oWidth, oBreadth, side); @@ -209,25 +234,17 @@ float Obstacle::getHitNormal( // get normal if (bestSide == -1) return -1.0f; if (bestSide == 4) - { - normal[0] = 0.0f; - normal[1] = 0.0f; - normal[2] = 1.0f; - } + normal = glm::vec3(0.0f, 0.0f, 1.0f); else if (!isObstacle) { const float _angle = (float)(0.5 * M_PI * (float)bestSide + oAzimuth); - normal[0] = cosf(_angle); - normal[1] = sinf(_angle); - normal[2] = 0.0f; + normal = glm::vec3(cosf(_angle), sinf(_angle), 0.0f); } else { const float _angle = (float)(0.5 * M_PI * (float)bestSide + minTime * (azimuth2 - azimuth1) + azimuth1); - normal[0] = -cosf(_angle); - normal[1] = -sinf(_angle); - normal[2] = 0.0f; + normal = glm::vec3(-cosf(_angle), -sinf(_angle), 0.0f); } return minTime; } diff --git a/src/obstacle/ObstacleMgr.cxx b/src/obstacle/ObstacleMgr.cxx index b83a9e186d..05b0f4b4c9 100644 --- a/src/obstacle/ObstacleMgr.cxx +++ b/src/obstacle/ObstacleMgr.cxx @@ -705,7 +705,7 @@ void GroupDefinition::replaceBasesWithBoxes() for (unsigned int i = 0; i < list.size(); i++) { BaseBuilding* base = (BaseBuilding*) list[i]; - const float* baseSize = base->getSize(); + const auto &baseSize = base->getSize(); BoxBuilding* box = new BoxBuilding(base->getPosition(), base->getRotation(), baseSize[0], baseSize[1], baseSize[2], diff --git a/src/obstacle/ObstacleModifier.cxx b/src/obstacle/ObstacleModifier.cxx index 33fb06b5c5..4f79f79a1e 100644 --- a/src/obstacle/ObstacleModifier.cxx +++ b/src/obstacle/ObstacleModifier.cxx @@ -10,8 +10,6 @@ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ -#include "common.h" - // implementation header #include "ObstacleModifier.h" @@ -159,11 +157,10 @@ static const BzMaterial* getTintedMaterial(const float tint[4], const BzMaterial* mat) { BzMaterial tintmat(*mat); - float newColor[4]; - const float* oldColor; + glm::vec4 newColor; // diffuse - oldColor = mat->getDiffuse(); + auto oldColor = mat->getDiffuse(); newColor[0] = oldColor[0] * tint[0]; newColor[1] = oldColor[1] * tint[1]; newColor[2] = oldColor[2] * tint[2]; diff --git a/src/obstacle/PyramidBuilding.cxx b/src/obstacle/PyramidBuilding.cxx index 841b996171..0b277971df 100644 --- a/src/obstacle/PyramidBuilding.cxx +++ b/src/obstacle/PyramidBuilding.cxx @@ -10,11 +10,16 @@ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ -#include "common.h" +// Interface header +#include "PyramidBuilding.h" + +// System headers #include +#include + +// Common headers #include "global.h" #include "Pack.h" -#include "PyramidBuilding.h" #include "Intersect.h" #include "MeshTransform.h" @@ -25,7 +30,7 @@ PyramidBuilding::PyramidBuilding() // do nothing } -PyramidBuilding::PyramidBuilding(const float* p, float a, +PyramidBuilding::PyramidBuilding(const glm::vec3 &p, float a, float w, float b, float h, bool drive, bool shoot, bool rico) : Obstacle(p, a, w, b, h,drive,shoot,rico) { @@ -46,9 +51,9 @@ void PyramidBuilding::finalize() Obstacle* PyramidBuilding::copyWithTransform(const MeshTransform& xform) const { - float newPos[3], newSize[3], newAngle; - memcpy(newPos, pos, sizeof(float[3])); - memcpy(newSize, size, sizeof(float[3])); + auto newPos = pos; + float newAngle; + auto newSize = size; newAngle = angle; MeshTransform::Tool tool(xform); @@ -81,8 +86,7 @@ float PyramidBuilding::intersect(const Ray& r) const getZFlip()); } -void PyramidBuilding::getNormal(const float* p, - float* n) const +void PyramidBuilding::getNormal(const glm::vec3 &p, glm::vec3 &n) const { // get normal in z = const plane const float s = shrinkFactor(p[2]); @@ -100,8 +104,7 @@ void PyramidBuilding::getNormal(const float* p, { if (p[2] >= top) { - n[0] = n[1] = 0; - n[2] = 1; + n = glm::vec3(0.0f, 0.0f, 1.0f); return; } } @@ -109,8 +112,7 @@ void PyramidBuilding::getNormal(const float* p, { if (p[2] <= bottom) { - n[0] = n[1] = 0; - n[2] = -1; + n = glm::vec3(0.0f, 0.0f, -1.0f); return; } } @@ -127,8 +129,8 @@ void PyramidBuilding::getNormal(const float* p, n[2] *= -1; } -void PyramidBuilding::get3DNormal(const float* p, - float* n) const +void PyramidBuilding::get3DNormal(const glm::vec3 &p, + glm::vec3 &n) const { const float epsilon = ZERO_TOLERANCE; @@ -148,8 +150,7 @@ void PyramidBuilding::get3DNormal(const float* p, { if (p[2] >= top) { - n[0] = n[1] = 0; - n[2] = 1; + n = glm::vec3(0.0f, 0.0f, 1.0f); return; } } @@ -157,8 +158,7 @@ void PyramidBuilding::get3DNormal(const float* p, { if (p[2] <= bottom) { - n[0] = n[1] = 0; - n[2] = -1; + n = glm::vec3(0.0f, 0.0f, -1.0f); return; } } @@ -166,11 +166,10 @@ void PyramidBuilding::get3DNormal(const float* p, if (s >= 1.0f - epsilon) { - n[0] = n[1] = 0; if (getZFlip()) - n[2] = 1; + n = glm::vec3(0.0f, 0.0f, 1.0f); else - n[2] = -1; + n = glm::vec3(0.0f, 0.0f, -1.0f); return; } @@ -192,7 +191,7 @@ void PyramidBuilding::get3DNormal(const float* p, n[2] *= -1; } -bool PyramidBuilding::inCylinder(const float* p, +bool PyramidBuilding::inCylinder(const glm::vec3 &p, float radius, float height) const { // really rough -- doesn't decrease size with height @@ -201,7 +200,7 @@ bool PyramidBuilding::inCylinder(const float* p, && testRectCircle(getPosition(), getRotation(), getWidth(), getBreadth(), p, radius); } -bool PyramidBuilding::inBox(const float* p, float a, +bool PyramidBuilding::inBox(const glm::vec3 &p, float a, float dx, float dy, float height) const { // Tank is below pyramid ? @@ -218,15 +217,16 @@ bool PyramidBuilding::inBox(const float* p, float a, s * getWidth(), s * getBreadth(), p, a, dx, dy); } -bool PyramidBuilding::inMovingBox(const float*, float, - const float* p, float _angle, +bool PyramidBuilding::inMovingBox(const glm::vec3 &, float, + const glm::vec3 &p, float _angle, float dx, float dy, float dz) const { return inBox (p, _angle, dx, dy, dz); } -bool PyramidBuilding::isCrossing(const float* p, float a, - float dx, float dy, float height, float* plane) const +bool PyramidBuilding::isCrossing(const glm::vec3 &p, float a, + float dx, float dy, float height, + glm::vec4 *plane) const { // if not inside or contained then not crossing if (!inBox(p, a, dx, dy, height) || @@ -238,7 +238,7 @@ bool PyramidBuilding::isCrossing(const float* p, float a, // it's crossing -- choose which wall is being crossed (this // is a guestimate, should really do a careful test). just // see which wall the point is closest to. - const float* p2 = getPosition(); + const auto &p2 = getPosition(); const float a2 = getRotation(); const float c = cosf(-a2), s = sinf(-a2); const float x = c * (p[0] - p2[0]) - s * (p[1] - p2[1]); @@ -246,33 +246,33 @@ bool PyramidBuilding::isCrossing(const float* p, float a, float pw[2]; if (fabsf(fabsf(x) - getWidth()) < fabsf(fabsf(y) - getBreadth())) { - plane[0] = ((x < 0.0) ? -cosf(a2) : cosf(a2)); - plane[1] = ((x < 0.0) ? -sinf(a2) : sinf(a2)); - pw[0] = p2[0] + getWidth() * plane[0]; - pw[1] = p2[1] + getWidth() * plane[1]; + plane->x = ((x < 0.0) ? -cosf(a2) : cosf(a2)); + plane->y = ((x < 0.0) ? -sinf(a2) : sinf(a2)); + pw[0] = p2[0] + getWidth() * plane->x; + pw[1] = p2[1] + getWidth() * plane->y; } else { - plane[0] = ((y < 0.0) ? sinf(a2) : -sinf(a2)); - plane[1] = ((y < 0.0) ? -cosf(a2) : cosf(a2)); - pw[0] = p2[0] + getBreadth() * plane[0]; - pw[1] = p2[1] + getBreadth() * plane[1]; + plane->x = ((y < 0.0) ? sinf(a2) : -sinf(a2)); + plane->y = ((y < 0.0) ? -cosf(a2) : cosf(a2)); + pw[0] = p2[0] + getBreadth() * plane->x; + pw[1] = p2[1] + getBreadth() * plane->y; } // now finish off plane equation (FIXME -- assumes a square base) const float h = 1.0f / hypotf(getHeight(), getWidth()); - plane[0] *= h * getHeight(); - plane[1] *= h * getHeight(); - plane[2] = h * getWidth(); - plane[3] = -(plane[0] * pw[0] + plane[1] * pw[1]); + plane->x *= h * getHeight(); + plane->y *= h * getHeight(); + plane->z = h * getWidth(); + plane->w = -(plane->x * pw[0] + plane->y * pw[1]); return true; } bool PyramidBuilding::getHitNormal( - const float* pos1, float, - const float* pos2, float, + const glm::vec3 &pos1, float, + const glm::vec3 &pos2, float, float, float, float height, - float* normal) const + glm::vec3 &normal) const { // pyramids height and flipping // normalize height sign and report that in flip @@ -302,13 +302,13 @@ bool PyramidBuilding::getHitNormal( if (flip && objHigh >= oTop) { // base of higher object is over the plateau - normal[2] = 1; + normal = glm::vec3(0.0f, 0.0f, 1.0f); return true; } else if (!flip && objLow + height < oBottom) { // top of lower object is below the base - normal[2] = -1; + normal = glm::vec3(0.0f, 0.0f, -1.0f); return true; } @@ -331,9 +331,9 @@ bool PyramidBuilding::getHitNormal( } void PyramidBuilding::getCorner(int index, - float* _pos) const + glm::vec3 &_pos) const { - const float* base = getPosition(); + const auto &base = getPosition(); const float c = cosf(getRotation()); const float s = sinf(getRotation()); const float w = getWidth(); @@ -399,7 +399,7 @@ float PyramidBuilding::shrinkFactor(float z, } // Remove heights bias - const float *_pos = getPosition(); + const auto &_pos = getPosition(); z -= _pos[2]; if (oHeight <= ZERO_TOLERANCE) shrink = 1.0f; @@ -488,7 +488,7 @@ int PyramidBuilding::packSize() const void PyramidBuilding::print(std::ostream& out, const std::string& indent) const { out << indent << "pyramid" << std::endl; - const float *_pos = getPosition(); + const auto &_pos = getPosition(); out << indent << " position " << _pos[0] << " " << _pos[1] << " " << _pos[2] << std::endl; out << indent << " size " << getWidth() << " " << getBreadth() @@ -525,7 +525,7 @@ static void outputFloat(std::ostream& out, float value) void PyramidBuilding::printOBJ(std::ostream& out, const std::string& UNUSED(indent)) const { int i; - float verts[5][3] = + glm::vec3 verts[5] = { {-1.0f, -1.0f, 0.0f}, {+1.0f, -1.0f, 0.0f}, @@ -534,26 +534,26 @@ void PyramidBuilding::printOBJ(std::ostream& out, const std::string& UNUSED(inde { 0.0f, 0.0f, 1.0f} }; const float sqrt1_2 = (float)M_SQRT1_2; - float norms[5][3] = + glm::vec3 norms[5] = { {0.0f, -sqrt1_2, +sqrt1_2}, {+sqrt1_2, 0.0f, +sqrt1_2}, {0.0f, +sqrt1_2, +sqrt1_2}, {-sqrt1_2, 0.0f, +sqrt1_2}, {0.0f, 0.0f, -1.0f} }; - const float* s = getSize(); const float k = 1.0f / 8.0f; + const auto s = k * getSize(); float txcds[7][2] = { - {0.0f, 0.0f}, {k*s[0], 0.0f}, {k*s[0], k*s[1]}, {0.0f, k*s[1]}, - {0.5f*k*s[0], k*sqrtf(s[0]*s[0]+s[2]*s[2])}, - {k*s[1], 0.0f}, {0.5f*k*s[1], k*sqrtf(s[1]*s[1]+s[2]*s[2])} + {0.0f, 0.0f}, {s[0], 0.0f}, {s[0], s[1]}, {0.0f, s[1]}, + {0.5f*s[0], sqrtf(s[0]*s[0]+s[2]*s[2])}, + {s[1], 0.0f}, {0.5f*s[1], sqrtf(s[1]*s[1]+s[2]*s[2])} }; MeshTransform xform; const float degrees = getRotation() * (float)(180.0 / M_PI); - const float zAxis[3] = {0.0f, 0.0f, +1.0f}; + const auto zAxis = glm::vec3(0.0f, 0.0f, +1.0f); if (getZFlip()) { - const float xAxis[3] = {1.0f, 0.0f, 0.0f}; + const auto xAxis = glm::vec3(1.0f, 0.0f, 0.0f); xform.addSpin(180.0f, xAxis); xform.addShift(zAxis); } diff --git a/src/obstacle/PyramidSceneNodeGenerator.cxx b/src/obstacle/PyramidSceneNodeGenerator.cxx index 82d2c25c10..6f520bef07 100644 --- a/src/obstacle/PyramidSceneNodeGenerator.cxx +++ b/src/obstacle/PyramidSceneNodeGenerator.cxx @@ -10,7 +10,13 @@ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ +// Interface #include "PyramidSceneNodeGenerator.h" + +// System headers +#include + +// Common headers #include "PyramidBuilding.h" #include "bzfgl.h" #include "TriWallSceneNode.h" @@ -40,7 +46,7 @@ WallSceneNode* PyramidSceneNodeGenerator::getNextNode( if (getNodeNumber() == 5) return NULL; - GLfloat base[3], sCorner[3], tCorner[3]; + glm::vec3 base, sCorner, tCorner; if (pyramid->getZFlip()) { switch (incNodeNumber()) @@ -119,19 +125,15 @@ WallSceneNode* PyramidSceneNodeGenerator::getNextNode( } } - GLfloat sEdge[3]; - GLfloat tEdge[3]; - sEdge[0] = sCorner[0] - base[0]; - sEdge[1] = sCorner[1] - base[1]; - sEdge[2] = sCorner[2] - base[2]; - tEdge[0] = tCorner[0] - base[0]; - tEdge[1] = tCorner[1] - base[1]; - tEdge[2] = tCorner[2] - base[2]; + const auto sEdge = sCorner - base; + const auto tEdge = tCorner - base; if (isQuad == false) - return new TriWallSceneNode(base, sEdge, tEdge, uRepeats, vRepeats, lod); + return new TriWallSceneNode( + base, sEdge, tEdge, uRepeats, vRepeats, lod); else - return new QuadWallSceneNode(base, sEdge, tEdge, uRepeats, vRepeats, lod); + return new QuadWallSceneNode( + base, sEdge, tEdge, uRepeats, vRepeats, lod); } diff --git a/src/obstacle/SphereObstacle.cxx b/src/obstacle/SphereObstacle.cxx index ef56558244..0842fec23a 100644 --- a/src/obstacle/SphereObstacle.cxx +++ b/src/obstacle/SphereObstacle.cxx @@ -16,6 +16,8 @@ // System headers #include #include +#include +#include // Common headers #include "global.h" @@ -35,7 +37,7 @@ SphereObstacle::SphereObstacle() SphereObstacle::SphereObstacle(const MeshTransform& xform, - const float* _pos, const float* _size, + const glm::vec3 &_pos, const glm::vec3 &_size, float _rotation, const float _texsize[2], bool _useNormals, bool _hemisphere, int _divisions, @@ -108,7 +110,8 @@ MeshObstacle* SphereObstacle::makeMesh() { MeshObstacle* mesh; int i, j, q; - float sz[3], texsz[2]; + glm::vec3 sz; + float texsz[2]; const float minSize = 1.0e-6f; // cheezy / lazy int factor = 2; @@ -117,9 +120,7 @@ MeshObstacle* SphereObstacle::makeMesh() factor = 1; // absolute the sizes - sz[0] = fabsf(size[0]); - sz[1] = fabsf(size[1]); - sz[2] = fabsf(size[2]); + sz = glm::abs(size); // adjust the texture sizes memcpy (texsz, texsize, sizeof(float[2])); @@ -145,26 +146,23 @@ MeshObstacle* SphereObstacle::makeMesh() // setup the coordinates std::vector checkTypes; - std::vector checkPoints; - std::vector vertices; - std::vector normals; - std::vector texcoords; - cfvec3 v, n; - cfvec2 t; + std::vector checkPoints; + std::vector vertices; + std::vector normals; + std::vector texcoords; + glm::vec3 v, n; + glm::vec2 t; // add the checkpoint (one is sufficient) - v[0] = pos[0]; - v[1] = pos[1]; - v[2] = pos[2]; + v = pos; if (hemisphere) v[2] = v[2] + (0.5f * fabsf(size[2])); checkPoints.push_back(v); checkTypes.push_back(MeshObstacle::CheckInside); // the center vertices - v[0] = pos[0]; - v[1] = pos[1]; - v[2] = pos[2] + sz[2]; + v = pos; + v[2] += sz[2]; vertices.push_back(v); if (!hemisphere) { @@ -201,25 +199,17 @@ MeshObstacle* SphereObstacle::makeMesh() h_angle = h_angle + getRotation(); float v_angle = (float)((M_PI / 2.0) * (divisions - i - 1) / (divisions)); - float unit[3]; + glm::vec3 unit; unit[0] = cosf(h_angle) * cosf(v_angle); unit[1] = sinf(h_angle) * cosf(v_angle); unit[2] = sinf(v_angle); // vertex - v[0] = pos[0] + (sz[0] * unit[0]); - v[1] = pos[1] + (sz[1] * unit[1]); - v[2] = pos[2] + (sz[2] * unit[2]); + v = pos + sz * unit; vertices.push_back(v); // normal if (useNormals) { - n[0] = unit[0] / sz[0]; - n[1] = unit[1] / sz[1]; - n[2] = unit[2] / sz[2]; - const float len = 1.0f / sqrtf(vec3dot(n.data, n.data)); - n[0] = n[0] * len; - n[1] = n[1] * len; - n[2] = n[2] * len; + n = glm::normalize(unit / sz); normals.push_back(n); } // texcoord @@ -460,53 +450,24 @@ float SphereObstacle::intersect(const Ray&) const return -1.0f; } -void SphereObstacle::get3DNormal(const float*, float*) const +void SphereObstacle::get3DNormal(const glm::vec3 &, glm::vec3 &) const { assert(false); return; } -void SphereObstacle::getNormal(const float*, float*) const +void SphereObstacle::getNormal(const glm::vec3 &, glm::vec3 &) const { assert(false); return; } -bool SphereObstacle::getHitNormal(const float*, float, const float*, float, - float, float, float, float*) const +bool SphereObstacle::inCylinder(const glm::vec3 &, float, float) const { assert(false); return false; } -bool SphereObstacle::inCylinder(const float*,float, float) const -{ - assert(false); - return false; -} - -bool SphereObstacle::inBox(const float*, float, float, float, float) const -{ - assert(false); - return false; -} - -bool SphereObstacle::inMovingBox(const float*, float, const float*, float, - float, float, float) const -{ - assert(false); - return false; -} - -bool SphereObstacle::isCrossing(const float* UNUSED(p), float UNUSED(_angle), - float UNUSED(dx), float UNUSED(dy), float UNUSED(height), - float* UNUSED(_plane)) const -{ - assert(false); - return false; -} - - void *SphereObstacle::pack(void *buf) const { buf = transform.pack(buf); diff --git a/src/obstacle/Teleporter.cxx b/src/obstacle/Teleporter.cxx index ad75090696..7ed1e65df9 100644 --- a/src/obstacle/Teleporter.cxx +++ b/src/obstacle/Teleporter.cxx @@ -10,11 +10,20 @@ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ -#include "common.h" +// Interface +#include "Teleporter.h" + +// System headers #include +#include +#include +#include +#define GLM_ENABLE_EXPERIMENTAL +#include + +// Common headers #include "global.h" #include "Pack.h" -#include "Teleporter.h" #include "Intersect.h" #include "MeshTransform.h" @@ -30,7 +39,7 @@ Teleporter::Teleporter() } -Teleporter::Teleporter(const float* p, float a, float w, +Teleporter::Teleporter(const glm::vec3 &p, float a, float w, float b, float h, float _border, bool _horizontal, bool drive, bool shoot, bool rico) : Obstacle(p, a, w, b, h, drive, shoot, rico), @@ -51,10 +60,9 @@ Teleporter::~Teleporter() Obstacle* Teleporter::copyWithTransform(const MeshTransform& xform) const { - float newPos[3], newSize[3], newAngle; - memcpy(newPos, pos, sizeof(float[3])); - memcpy(newSize, origSize, sizeof(float[3])); - newAngle = angle; + auto newPos = pos; + auto newSize = origSize; + float newAngle = angle; MeshTransform::Tool tool(xform); bool flipped; @@ -107,20 +115,20 @@ void Teleporter::makeLinks() // make the new pointers to floats, // the MeshFace will delete[] them - float **fvrts = new float*[4]; - float **bvrts = new float*[4]; - float **ftxcds = new float*[4]; - float **btxcds = new float*[4]; + auto fvrts = new glm::vec3*[4]; + auto bvrts = new glm::vec3*[4]; + auto ftxcds = new glm::vec2*[4]; + auto btxcds = new glm::vec2*[4]; for (i = 0; i < 4; i++) { - fvrts[i] = fvertices[i]; - bvrts[i] = bvertices[i]; - ftxcds[i] = texcoords[i]; - btxcds[i] = texcoords[i]; + fvrts[i] = &fvertices[i]; + bvrts[i] = &bvertices[i]; + ftxcds[i] = &texcoords[i]; + btxcds[i] = &texcoords[i]; } // get the basics - const float* p = getPosition(); + const auto &p = getPosition(); const float a = getRotation(); const float w = getWidth(); const float b = getBreadth(); @@ -155,18 +163,19 @@ void Teleporter::makeLinks() for (i = 0; i < 4 ; i++) { - bvrts[i][0] = p[0] + (wlen[0] + (blen[0] * params[i][0])); - bvrts[i][1] = p[1] + (wlen[1] + (blen[1] * params[i][0])); - bvrts[i][2] = p[2] + ((h - br) * params[i][1]); + bvrts[i]->x = p[0] + (wlen[0] + (blen[0] * params[i][0])); + bvrts[i]->y = p[1] + (wlen[1] + (blen[1] * params[i][0])); + bvrts[i]->z = p[2] + ((h - br) * params[i][1]); } backLink = new MeshFace(NULL, 4, bvrts, NULL, btxcds, NULL, -1, false, false, true, true, false); for (i = 0; i < 4 ; i++) { - fvrts[i][0] = p[0] - (wlen[0] + (blen[0] * params[i][0])); - fvrts[i][1] = p[1] - (wlen[1] + (blen[1] * params[i][0])); - fvrts[i][2] = p[2] + ((h - br) * params[i][1]); + *fvrts[i] = p; + fvrts[i]->x -= wlen[0] + (blen[0] * params[i][0]); + fvrts[i]->y -= wlen[1] + (blen[1] * params[i][0]); + fvrts[i]->z += (h - br) * params[i][1]; } frontLink = new MeshFace(NULL, 4, fvrts, NULL, ftxcds, NULL, -1, false, false, true, true, false); @@ -175,25 +184,26 @@ void Teleporter::makeLinks() { float xlen = w - br; float ylen = b - br; - bvrts[0][0] = p[0] + ((cos_val * xlen) - (sin_val * ylen)); - bvrts[0][1] = p[1] + ((cos_val * ylen) + (sin_val * xlen)); - bvrts[0][2] = p[2] + h - br; - bvrts[1][0] = p[0] + ((cos_val * xlen) - (sin_val * -ylen)); - bvrts[1][1] = p[1] + ((cos_val * -ylen) + (sin_val * xlen)); - bvrts[1][2] = p[2] + h - br; - bvrts[2][0] = p[0] + ((cos_val * -xlen) - (sin_val * -ylen)); - bvrts[2][1] = p[1] + ((cos_val * -ylen) + (sin_val * -xlen)); - bvrts[2][2] = p[2] + h - br; - bvrts[3][0] = p[0] + ((cos_val * -xlen) - (sin_val * ylen)); - bvrts[3][1] = p[1] + ((cos_val * ylen) + (sin_val * -xlen)); - bvrts[3][2] = p[2] + h - br; + for (i = 0; i < 4 ; i++) + { + *bvrts[i] = p; + bvrts[i]->z += h - br; + } + bvrts[0]->x += (cos_val * xlen) - (sin_val * ylen); + bvrts[0]->y += (cos_val * ylen) + (sin_val * xlen); + bvrts[1]->x += (cos_val * xlen) - (sin_val * -ylen); + bvrts[1]->y += (cos_val * -ylen) + (sin_val * xlen); + bvrts[2]->x += (cos_val * -xlen) - (sin_val * -ylen); + bvrts[2]->y += (cos_val * -ylen) + (sin_val * -xlen); + bvrts[3]->x += (cos_val * -xlen) - (sin_val * ylen); + bvrts[3]->y += (cos_val * ylen) + (sin_val * -xlen); backLink = new MeshFace(NULL, 4, bvrts, NULL, btxcds, NULL, -1, false, false, true, true, false); for (i = 0; i < 4; i++) { - memcpy(fvrts[i], bvrts[3 - i], sizeof(float[3])); // reverse order - fvrts[i][2] = p[2] + h; // change the height + *fvrts[i] = *bvrts[3 - i]; // reverse order + fvrts[i]->z = p[2] + h; // change the height } frontLink = new MeshFace(NULL, 4, fvrts, NULL, ftxcds, NULL, -1, false, false, true, true, false); @@ -231,23 +241,23 @@ float Teleporter::intersect(const Ray& r) const } -void Teleporter::getNormal(const float* p1, float* n) const +void Teleporter::getNormal(const glm::vec3 &p1, glm::vec3 &n) const { // get normal to closest border column (assume column is circular) - const float* p2 = getPosition(); + const auto &p2 = getPosition(); const float c = cosf(-getRotation()); const float s = sinf(-getRotation()); const float b = 0.5f * getBorder(); const float d = getBreadth() - b; const float j = (c * (p1[1] - p2[1]) + s * (p1[0] - p2[0]) > 0.0f) ? d : -d; - float cc[2]; + glm::vec2 cc; cc[0] = p2[0] + (s * j); cc[1] = p2[1] + (c * j); getNormalRect(p1, cc, getRotation(), b, b, n); } -bool Teleporter::inCylinder(const float* p, float radius, float height) const +bool Teleporter::inCylinder(const glm::vec3 &p, float radius, float height) const { return (p[2]+height) >= getPosition()[2] && p[2] <= getPosition()[2] + getHeight() && @@ -256,7 +266,7 @@ bool Teleporter::inCylinder(const float* p, float radius, float height) const } -bool Teleporter::inBox(const float* p, float a, +bool Teleporter::inBox(const glm::vec3 &p, float a, float dx, float dy, float dz) const { const float tankTop = p[2] + dz; @@ -270,7 +280,7 @@ bool Teleporter::inBox(const float* p, float a, const float s = sinf(getRotation()); const float d = getBreadth() - (0.5f * getBorder()); const float r = 0.5f * getBorder(); - float o[2]; + glm::vec2 o; o[0] = getPosition()[0] - (s * d); o[1] = getPosition()[1] + (c * d); if (testRectRect(p, a, dx, dy, o, getRotation(), r, r)) @@ -293,27 +303,24 @@ bool Teleporter::inBox(const float* p, float a, } -bool Teleporter::inMovingBox(const float* oldP, float UNUSED(oldAngle), - const float* p, float a, +bool Teleporter::inMovingBox(const glm::vec3 &oldP, float UNUSED(oldAngle), + const glm::vec3 &p, float a, float dx, float dy, float dz) const { - float minPos[3]; - minPos[0] = p[0]; - minPos[1] = p[1]; + auto minPos = p; if (oldP[2] < p[2]) minPos[2] = oldP[2]; - else - minPos[2] = p[2]; dz += fabsf(oldP[2] - p[2]); return inBox(minPos, a, dx, dy, dz); } -bool Teleporter::isCrossing(const float* p, float a, - float dx, float dy, float /* dz */, float* plane) const +bool Teleporter::isCrossing(const glm::vec3 &p, float a, + float dx, float dy, float, + glm::vec4 *plane) const { // if not inside or contained then not crossing - const float* p2 = getPosition(); + const auto &p2 = getPosition(); if (!testRectRect(p, a, dx, dy, p2, getRotation(), getWidth(), getBreadth() - getBorder()) || p[2] < p2[2] || p[2] > p2[2] + getHeight() - getBorder()) @@ -328,14 +335,14 @@ bool Teleporter::isCrossing(const float* p, float a, const float s = sinf(-a2); const float x = c * (p[0] - p2[0]) - s * (p[1] - p2[1]); float pw[2]; - plane[0] = ((x < 0.0f) ? -cosf(a2) : cosf(a2)); - plane[1] = ((x < 0.0f) ? -sinf(a2) : sinf(a2)); - pw[0] = p2[0] + getWidth() * plane[0]; - pw[1] = p2[1] + getWidth() * plane[1]; + plane->x = ((x < 0.0f) ? -cosf(a2) : cosf(a2)); + plane->y = ((x < 0.0f) ? -sinf(a2) : sinf(a2)); + pw[0] = p2[0] + getWidth() * plane->x; + pw[1] = p2[1] + getWidth() * plane->y; // now finish off plane equation - plane[2] = 0.0f; - plane[3] = -(plane[0] * pw[0] + plane[1] * pw[1]); + plane->z = 0.0f; + plane->w = -(plane->x * pw[0] + plane->y * pw[1]); return true; } @@ -355,7 +362,7 @@ float Teleporter::isTeleported(const Ray& r, int& face) const return -1.0f; // get teleport position. if above or below teleporter then no teleportation. - float p[3]; + glm::vec3 p; r.getPoint(t, p); p[2] -= getPosition()[2]; if (p[2] < 0.0f || p[2] > getHeight() - getBorder()) @@ -370,7 +377,7 @@ float Teleporter::isTeleported(const Ray& r, int& face) const } -float Teleporter::getProximity(const float* p, float radius) const +float Teleporter::getProximity(const glm::vec3 &p, float radius) const { // make sure tank is sufficiently close if (!testRectCircle(getPosition(), getRotation(), @@ -419,10 +426,10 @@ float Teleporter::getProximity(const float* p, float radius) const } -bool Teleporter::hasCrossed(const float* p1, const float* p2, int& f) const +bool Teleporter::hasCrossed(const glm::vec3 &p1, const glm::vec3 &p2, int& f) const { // check above/below teleporter - const float* p = getPosition(); + const auto &p = getPosition(); if ((p1[2] < p[2] && p2[2] < p[2]) || (p1[2] > p[2] + getHeight() - getBorder() && p2[2] > p[2] + getHeight() - getBorder())) @@ -442,30 +449,29 @@ bool Teleporter::hasCrossed(const float* p1, const float* p2, int& f) const void Teleporter::getPointWRT(const Teleporter& t2, int face1, int face2, - const float* pIn, const float* dIn, float aIn, - float* pOut, float* dOut, float* aOut) const + glm::vec3 &p, glm::vec3 *d, float *a) const { // transforming pIn to pOut, going from tele1(this) to tele2 const Teleporter& tele1 = *this; const Teleporter& tele2 = t2; - const float* p1 = tele1.getPosition(); - const float* p2 = tele2.getPosition(); - const float* s1 = tele1.getSize(); - const float* s2 = tele2.getSize(); + const auto &p1 = tele1.getPosition(); + const auto &p2 = tele2.getPosition(); + const auto &s1 = tele1.getSize(); + const auto &s2 = tele2.getSize(); - const fvec3 pos1 (p1[0], p1[1], p1[2]); - const fvec3 size1 (s1[0], s1[1], s1[2]); - const fvec3 pos2 (p2[0], p2[1], p2[2]); - const fvec3 size2 (s2[0], s2[1], s2[2]); + const auto pos1 = p1; + const auto size1 = s1; + const auto pos2 = p2; + const auto size2 = s2; const float bord1 = tele1.getBorder(); const float bord2 = tele2.getBorder(); // y & z axis scaling factors (relative active areas) - const fvec2 dims1(size1.y - bord1, size1.z - bord1); - const fvec2 dims2(size2.y - bord2, size2.z - bord2); - const fvec2 dimsScale = (dims2 / dims1); + const auto dims1 = glm::vec2(size1.y - bord1, size1.z - bord1); + const auto dims2 = glm::vec2(size2.y - bord2, size2.z - bord2); + const auto dimsScale = (dims2 / dims1); // adjust the angles for the faces // NOTE: if (face1 == face2), there's an extra 180 degrees spin @@ -473,12 +479,9 @@ void Teleporter::getPointWRT(const Teleporter& t2, int face1, int face2, const float radians1 = tele1.getRotation() + ((face1 == 0) ? 0.0f : pi); const float radians2 = tele2.getRotation() + ((face2 == 1) ? 0.0f : pi); - // intermediate output position - fvec3 p(pIn[0], pIn[1], pIn[2]); - // translate to origin, and revert rotation p -= pos1; - p = p.rotateZ(-radians1); + p = glm::rotateZ(p, -radians1); // fixed x offset, and scale y & z coordinates p.x = -size2.x; @@ -486,35 +489,29 @@ void Teleporter::getPointWRT(const Teleporter& t2, int face1, int face2, p.z *= dimsScale.y; // apply rotation, translate to new position - p = p.rotateZ(+radians2); + p = glm::rotateZ(p, +radians2); p += pos2; - // final output position - pOut[0] = p.x; - pOut[1] = p.y; - pOut[2] = p.z; - // fill in output angle and direction variables, if requested - const float a = radians2 - radians1; - if (aOut) - *aOut = aIn + a; - if (dOut && dIn) + const float a_ = radians2 - radians1; + if (a) + *a += a_; + if (d) { - const float c = cosf(a); - const float s = sinf(a); - const float dx = dIn[0]; - const float dy = dIn[1]; - dOut[0] = (c * dx) - (s * dy); - dOut[1] = (c * dy) + (s * dx); - dOut[2] = dIn[2]; + const float c = cosf(a_); + const float s = sinf(a_); + const float dx = d->x; + const float dy = d->y; + d->x = c * dx - s * dy; + d->y = s * dx + c * dy; } } -bool Teleporter::getHitNormal(const float* pos1, float azimuth1, - const float* pos2, float azimuth2, +bool Teleporter::getHitNormal(const glm::vec3 &pos1, float azimuth1, + const glm::vec3 &pos2, float azimuth2, float width, float breadth, float, - float* normal) const + glm::vec3 &normal) const { return Obstacle::getHitNormal(pos1, azimuth1, pos2, azimuth2, width, breadth, @@ -591,7 +588,7 @@ void Teleporter::print(std::ostream& out, const std::string& indent) const if (name.size() > 0) out << " " << name; out << std::endl; - const float *_pos = getPosition(); + const auto &_pos = getPosition(); out << indent << " position " << _pos[0] << " " << _pos[1] << " " << _pos[2] << std::endl; out << indent << " size " << origSize[0] << " " << origSize[1] << " " @@ -619,7 +616,7 @@ static void outputFloat(std::ostream& out, float value) void Teleporter::printOBJ(std::ostream& out, const std::string& UNUSED(indent)) const { int i; - float verts[8][3] = + glm::vec3 verts[8] = { {-1.0f, -1.0f, 0.0f}, {+1.0f, -1.0f, 0.0f}, @@ -630,7 +627,7 @@ void Teleporter::printOBJ(std::ostream& out, const std::string& UNUSED(indent)) {+1.0f, +1.0f, 1.0f}, {-1.0f, +1.0f, 1.0f} }; - float norms[6][3] = + glm::vec3 norms[6] = { {0.0f, -1.0f, 0.0f}, {+1.0f, 0.0f, 0.0f}, {0.0f, +1.0f, 0.0f}, {-1.0f, 0.0f, 0.0f}, @@ -642,7 +639,7 @@ void Teleporter::printOBJ(std::ostream& out, const std::string& UNUSED(indent)) }; MeshTransform xform; const float degrees = getRotation() * (float)(180.0 / M_PI); - const float zAxis[3] = {0.0f, 0.0f, +1.0f}; + const auto zAxis = glm::vec3(0.0f, 0.0f, +1.0f); xform.addScale(getSize()); xform.addSpin(degrees, zAxis); xform.addShift(getPosition()); diff --git a/src/obstacle/TeleporterSceneNodeGenerator.cxx b/src/obstacle/TeleporterSceneNodeGenerator.cxx index 028bbe6feb..de2560a43e 100644 --- a/src/obstacle/TeleporterSceneNodeGenerator.cxx +++ b/src/obstacle/TeleporterSceneNodeGenerator.cxx @@ -41,7 +41,7 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( float UNUSED(uRepeats), float UNUSED(vRepeats), bool lod) { - static const float texCoords[][4][2] = + static const glm::vec2 texCoords[][4] = { {{ 0.0f, 0.0f }, { 0.5f, 0.0f }, { 0.5f, 9.5f }, { 0.0f, 9.5f }}, {{ 0.5f, 0.0f }, { 1.0f, 0.0f }, { 1.0f, 9.5f }, { 0.5f, 9.5f }}, @@ -65,11 +65,10 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( if (getNodeNumber () >= 16) return NULL; - GLfloat base[3]; - GLfloat sEdge[3]; - GLfloat tEdge[3]; - const float *pos = teleporter->getPosition (); - const float *size = teleporter->getSize (); + glm::vec3 sEdge; + glm::vec3 tEdge; + const auto &pos = teleporter->getPosition (); + const auto &size = teleporter->getSize (); const float c = cosf (teleporter->getRotation ()); const float s = sinf (teleporter->getRotation ()); const float w = teleporter->getWidth (); @@ -82,13 +81,14 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( // 11,12,13,14: top sides // 15,16 top and bottom teleport faces + auto base = pos; const int n = incNodeNumber (); switch (n) { case 1: // -x outside edge - base[0] = pos[0] + ((-w) * c - (-d) * s); - base[1] = pos[1] + ((-w) * s + (-d) * c); - base[2] = pos[2] + size[2] - b; + base[0] += (-w) * c - (-d) * s; + base[1] += (-w) * s + (-d) * c; + base[2] += size[2] - b; sEdge[0] = 0.0f; sEdge[1] = 0.0f; sEdge[2] = b; @@ -97,9 +97,9 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = 0.0f; break; case 2: // -y outside edge - base[0] = pos[0] + ((-w) * c - (-d) * s); - base[1] = pos[1] + ((-w) * s + (-d) * c); - base[2] = pos[2] + size[2] - b; + base[0] += (-w) * c - (-d) * s; + base[1] += (-w) * s + (-d) * c; + base[2] += size[2] - b; sEdge[0] = (2.0f * w) * c; sEdge[1] = (2.0f * w) * s; sEdge[2] = 0.0f; @@ -108,9 +108,9 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = b; break; case 3: // +x outside edge - base[0] = pos[0] + ((w) * c - (d) * s); - base[1] = pos[1] + ((w) * s + (d) * c); - base[2] = pos[2] + size[2] - b; + base[0] += (w) * c - (d) * s; + base[1] += (w) * s + (d) * c; + base[2] += size[2] - b; sEdge[0] = 0.0f; sEdge[1] = 0.0f; sEdge[2] = b; @@ -119,9 +119,9 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = 0.0f; break; case 4: // +y outside edge - base[0] = pos[0] + ((w) * c - (d) * s); - base[1] = pos[1] + ((w) * s + (d) * c); - base[2] = pos[2] + size[2] - b; + base[0] += (w) * c - (d) * s; + base[1] += (w) * s + (d) * c; + base[2] += size[2] - b; sEdge[0] = (-2.0f * w) * c; sEdge[1] = (-2.0f * w) * s; sEdge[2] = 0.0f; @@ -130,9 +130,9 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = b; break; case 5: // -x inner edge - base[0] = pos[0] + ((b - w) * c - (b - d) * s); - base[1] = pos[1] + ((b - w) * s + (b - d) * c); - base[2] = pos[2] + size[2] - b; + base[0] += (b - w) * c - (b - d) * s; + base[1] += (b - w) * s + (b - d) * c; + base[2] += size[2] - b; sEdge[0] = -s * (2.0f * (d - b)); sEdge[1] = c * (2.0f * (d - b)); sEdge[2] = 0.0f; @@ -141,9 +141,9 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = b; break; case 6: // -y inner edge - base[0] = pos[0] + ((b - w) * c - (b - d) * s); - base[1] = pos[1] + ((b - w) * s + (b - d) * c); - base[2] = pos[2] + size[2] - b; + base[0] += (b - w) * c - (b - d) * s; + base[1] += (b - w) * s + (b - d) * c; + base[2] += size[2] - b; sEdge[0] = 0.0f; sEdge[1] = 0.0f; sEdge[2] = b; @@ -152,9 +152,9 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = 0.0f; break; case 7: // +x inner edge - base[0] = pos[0] + ((w - b) * c - (d - b) * s); - base[1] = pos[1] + ((w - b) * s + (d - b) * c); - base[2] = pos[2] + size[2] - b; + base[0] += (w - b) * c - (d - b) * s; + base[1] += (w - b) * s + (d - b) * c; + base[2] += size[2] - b; sEdge[0] = -(-2.0f * (d - b)) * s; sEdge[1] = (-2.0f * (d - b)) * c; sEdge[2] = 0.0f; @@ -163,9 +163,9 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = b; break; case 8: // +y inner edge - base[0] = pos[0] + ((w - b) * c - (d - b) * s); - base[1] = pos[1] + ((w - b) * s + (d - b) * c); - base[2] = pos[2] + size[2] - b; + base[0] += (w - b) * c - (d - b) * s; + base[1] += (w - b) * s + (d - b) * c; + base[2] += size[2] - b; sEdge[0] = 0.0f; sEdge[1] = 0.0f; sEdge[2] = b; @@ -174,9 +174,9 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = 0.0f; break; case 9: // -x bottom edge - base[0] = pos[0] + ((-w) * c - (-d) * s); - base[1] = pos[1] + ((-w) * s + (-d) * c); - base[2] = pos[2] + size[2] - b; + base[0] += (-w) * c - (-d) * s; + base[1] += (-w) * s + (-d) * c; + base[2] += size[2] - b; sEdge[0] = -s * (2.0f * d); sEdge[1] = c * (2.0f * d); sEdge[2] = 0.0f; @@ -185,9 +185,9 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = 0.0f; break; case 10: // -y bottom edge - base[0] = pos[0] + ((-w) * c - (-d) * s); - base[1] = pos[1] + ((-w) * s + (-d) * c); - base[2] = pos[2] + size[2] - b; + base[0] += (-w) * c - (-d) * s; + base[1] += (-w) * s + (-d) * c; + base[2] += size[2] - b; sEdge[0] = -s * (b); sEdge[1] = c * (b); sEdge[2] = 0.0f; @@ -196,9 +196,9 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = 0.0f; break; case 11: // +x bottom edge - base[0] = pos[0] + ((w) * c - (d) * s); - base[1] = pos[1] + ((w) * s + (d) * c); - base[2] = pos[2] + size[2] - b; + base[0] += (w) * c - (d) * s; + base[1] += (w) * s + (d) * c; + base[2] += size[2] - b; sEdge[0] = -(-2.0f * (d)) * s; sEdge[1] = (-2.0f * (d)) * c; sEdge[2] = 0.0f; @@ -207,9 +207,9 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = 0.0f; break; case 12: // +y bottom edge - base[0] = pos[0] + ((w) * c - (d) * s); - base[1] = pos[1] + ((w) * s + (d) * c); - base[2] = pos[2] + size[2] - b; + base[0] += (w) * c - (d) * s; + base[1] += (w) * s + (d) * c; + base[2] += size[2] - b; sEdge[0] = -s * (-b); sEdge[1] = c * (-b); sEdge[2] = 0.0f; @@ -218,9 +218,9 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = 0.0f; break; case 13: // -x top edge - base[0] = pos[0] + ((-w) * c - (-d) * s); - base[1] = pos[1] + ((-w) * s + (-d) * c); - base[2] = pos[2] + size[2]; + base[0] += (-w) * c - (-d) * s; + base[1] += (-w) * s + (-d) * c; + base[2] += size[2]; sEdge[0] = c * (b); sEdge[1] = s * (b); sEdge[2] = 0.0f; @@ -229,9 +229,9 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = 0.0f; break; case 14: // -y top edge - base[0] = pos[0] + ((-w) * c - (-d) * s); - base[1] = pos[1] + ((-w) * s + (-d) * c); - base[2] = pos[2] + size[2]; + base[0] += (-w) * c - (-d) * s; + base[1] += (-w) * s + (-d) * c; + base[2] += size[2]; sEdge[0] = c * (2.0f * (w)); sEdge[1] = s * (2.0f * (w)); sEdge[2] = 0.0f; @@ -240,9 +240,9 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = 0.0f; break; case 15: // +x top edge - base[0] = pos[0] + ((w) * c - (d) * s); - base[1] = pos[1] + ((w) * s + (d) * c); - base[2] = pos[2] + size[2]; + base[0] += (w) * c - (d) * s; + base[1] += (w) * s + (d) * c; + base[2] += size[2]; sEdge[0] = c * (-b); sEdge[1] = s * (-b); sEdge[2] = 0.0f; @@ -251,9 +251,9 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = 0.0f; break; case 16: // +y top edge - base[0] = pos[0] + ((w) * c - (d) * s); - base[1] = pos[1] + ((w) * s + (d) * c); - base[2] = pos[2] + size[2]; + base[0] += (w) * c - (d) * s; + base[1] += (w) * s + (d) * c; + base[2] += size[2]; sEdge[0] = c * (2.0f * (-w)); sEdge[1] = s * (2.0f * (-w)); sEdge[2] = 0.0f; @@ -263,30 +263,29 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( break; } - float u, v, uc, vc; + glm::vec2 uv; + float uc, vc; if (n >= 1 && n <= 16) { - u = texCoords[0][0][0]; - v = texCoords[0][0][1]; - uc = texCoords[0][1][0] - u; - vc = texCoords[0][3][1] - v; + uv = texCoords[0][0]; + uc = texCoords[0][1][0] - uv[0]; + vc = texCoords[0][3][1] - uv[1]; } else { - u = v = 0.0f; + uv = glm::vec2(0.0f); uc = vc = 1.0f; } - return new QuadWallSceneNode (base, sEdge, tEdge, u, v, uc, vc, lod); + return new QuadWallSceneNode (base, sEdge, tEdge, uv, uc, vc, lod); } else { if (getNodeNumber () >= 12) return NULL; - GLfloat base[3]; - GLfloat sEdge[3]; - GLfloat tEdge[3]; - const float *pos = teleporter->getPosition (); + glm::vec3 sEdge; + glm::vec3 tEdge; + const auto &pos = teleporter->getPosition (); const float c = cosf (teleporter->getRotation ()); const float s = sinf (teleporter->getRotation ()); const float h = teleporter->getBreadth () - teleporter->getBorder (); @@ -304,13 +303,13 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( // 9,10: horizontal bar top and bottom // 11,12: front and back horizontal sides // 13,14: front and back teleport faces + auto base = pos; const int n = incNodeNumber (); switch (n) { case 1: - base[0] = pos[0] + d * y[0] + b * x[0] + b * y[0]; - base[1] = pos[1] + d * y[1] + b * x[1] + b * y[1]; - base[2] = pos[2]; + base[0] += + d * y[0] + b * x[0] + b * y[0]; + base[1] += + d * y[1] + b * x[1] + b * y[1]; sEdge[0] = -2.0f * b * x[0]; sEdge[1] = -2.0f * b * x[1]; sEdge[2] = 0.0f; @@ -319,9 +318,8 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = z + 2.0f * b; break; case 2: - base[0] = pos[0] - d * y[0] - b * x[0] - b * y[0]; - base[1] = pos[1] - d * y[1] - b * x[1] - b * y[1]; - base[2] = pos[2]; + base[0] += - d * y[0] - b * x[0] - b * y[0]; + base[1] += - d * y[1] - b * x[1] - b * y[1]; sEdge[0] = 2.0f * b * x[0]; sEdge[1] = 2.0f * b * x[1]; sEdge[2] = 0.0f; @@ -330,9 +328,8 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = z + 2.0f * b; break; case 3: - base[0] = pos[0] + d * y[0] - b * x[0] - b * y[0]; - base[1] = pos[1] + d * y[1] - b * x[1] - b * y[1]; - base[2] = pos[2]; + base[0] += + d * y[0] - b * x[0] - b * y[0]; + base[1] += + d * y[1] - b * x[1] - b * y[1]; sEdge[0] = 2.0f * b * x[0]; sEdge[1] = 2.0f * b * x[1]; sEdge[2] = 0.0f; @@ -341,9 +338,8 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = z; break; case 4: - base[0] = pos[0] - d * y[0] + b * x[0] + b * y[0]; - base[1] = pos[1] - d * y[1] + b * x[1] + b * y[1]; - base[2] = pos[2]; + base[0] += - d * y[0] + b * x[0] + b * y[0]; + base[1] += - d * y[1] + b * x[1] + b * y[1]; sEdge[0] = -2.0f * b * x[0]; sEdge[1] = -2.0f * b * x[1]; sEdge[2] = 0.0f; @@ -352,9 +348,8 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = z; break; case 5: - base[0] = pos[0] + d * y[0] + b * x[0] - b * y[0]; - base[1] = pos[1] + d * y[1] + b * x[1] - b * y[1]; - base[2] = pos[2]; + base[0] += + d * y[0] + b * x[0] - b * y[0]; + base[1] += + d * y[1] + b * x[1] - b * y[1]; sEdge[0] = 2.0f * b * y[0]; sEdge[1] = 2.0f * b * y[1]; sEdge[2] = 0.0f; @@ -363,9 +358,8 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = z; break; case 6: - base[0] = pos[0] - d * y[0] - b * x[0] + b * y[0]; - base[1] = pos[1] - d * y[1] - b * x[1] + b * y[1]; - base[2] = pos[2]; + base[0] += - d * y[0] - b * x[0] + b * y[0]; + base[1] += - d * y[1] - b * x[1] + b * y[1]; sEdge[0] = -2.0f * b * y[0]; sEdge[1] = -2.0f * b * y[1]; sEdge[2] = 0.0f; @@ -374,9 +368,8 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = z; break; case 7: - base[0] = pos[0] + d * y[0] - b * x[0] + b * y[0]; - base[1] = pos[1] + d * y[1] - b * x[1] + b * y[1]; - base[2] = pos[2]; + base[0] += + d * y[0] - b * x[0] + b * y[0]; + base[1] += + d * y[1] - b * x[1] + b * y[1]; sEdge[0] = -2.0f * b * y[0]; sEdge[1] = -2.0f * b * y[1]; sEdge[2] = 0.0f; @@ -385,9 +378,8 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = z; break; case 8: - base[0] = pos[0] - d * y[0] + b * x[0] - b * y[0]; - base[1] = pos[1] - d * y[1] + b * x[1] - b * y[1]; - base[2] = pos[2]; + base[0] += - d * y[0] + b * x[0] - b * y[0]; + base[1] += - d * y[1] + b * x[1] - b * y[1]; sEdge[0] = 2.0f * b * y[0]; sEdge[1] = 2.0f * b * y[1]; sEdge[2] = 0.0f; @@ -396,9 +388,9 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = z; break; case 9: - base[0] = pos[0] - d * y[0] - b * x[0] - b * y[0]; - base[1] = pos[1] - d * y[1] - b * x[1] - b * y[1]; - base[2] = pos[2] + z + 2.0f * b; + base[0] += - d * y[0] - b * x[0] - b * y[0]; + base[1] += - d * y[1] - b * x[1] - b * y[1]; + base[2] += + z + 2.0f * b; sEdge[0] = 2.0f * b * x[0]; sEdge[1] = 2.0f * b * x[1]; sEdge[2] = 0.0f; @@ -407,9 +399,9 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = 0.0f; break; case 10: - base[0] = pos[0] - d * y[0] + b * x[0] + b * y[0]; - base[1] = pos[1] - d * y[1] + b * x[1] + b * y[1]; - base[2] = pos[2] + z; + base[0] += - d * y[0] + b * x[0] + b * y[0]; + base[1] += - d * y[1] + b * x[1] + b * y[1]; + base[2] += + z; sEdge[0] = -2.0f * b * x[0]; sEdge[1] = -2.0f * b * x[1]; sEdge[2] = 0.0f; @@ -418,9 +410,9 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = 0.0f; break; case 11: - base[0] = pos[0] - d * y[0] + b * x[0] - b * y[0]; - base[1] = pos[1] - d * y[1] + b * x[1] - b * y[1]; - base[2] = pos[2] + z; + base[0] += - d * y[0] + b * x[0] - b * y[0]; + base[1] += - d * y[1] + b * x[1] - b * y[1]; + base[2] += + z; sEdge[0] = 2.0f * (d + b) * y[0]; sEdge[1] = 2.0f * (d + b) * y[1]; sEdge[2] = 0.0f; @@ -429,9 +421,9 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = 2.0f * b; break; case 12: - base[0] = pos[0] + d * y[0] - b * x[0] + b * y[0]; - base[1] = pos[1] + d * y[1] - b * x[1] + b * y[1]; - base[2] = pos[2] + z; + base[0] += + d * y[0] - b * x[0] + b * y[0]; + base[1] += + d * y[1] - b * x[1] + b * y[1]; + base[2] += + z; sEdge[0] = -2.0f * (d + b) * y[0]; sEdge[1] = -2.0f * (d + b) * y[1]; sEdge[2] = 0.0f; @@ -440,20 +432,20 @@ WallSceneNode* TeleporterSceneNodeGenerator::getNextNode( tEdge[2] = 2.0f * b; break; } - float u, v, uc, vc; + glm::vec2 uv; + float uc, vc; if (n >= 1 && n <= 12) { - u = texCoords[n - 1][0][0]; - v = texCoords[n - 1][0][1]; - uc = texCoords[n - 1][1][0] - u; - vc = texCoords[n - 1][3][1] - v; + uv = texCoords[n - 1][0]; + uc = texCoords[n - 1][1][0] - uv[0]; + vc = texCoords[n - 1][3][1] - uv[1]; } else { - u = v = 0.0f; + uv = glm::vec2(0.0f); uc = vc = 1.0f; } - return new QuadWallSceneNode (base, sEdge, tEdge, u, v, uc, vc, lod); + return new QuadWallSceneNode (base, sEdge, tEdge, uv, uc, vc, lod); } } diff --git a/src/obstacle/TetraBuilding.cxx b/src/obstacle/TetraBuilding.cxx index b0e11f6a35..13e58abae4 100644 --- a/src/obstacle/TetraBuilding.cxx +++ b/src/obstacle/TetraBuilding.cxx @@ -16,6 +16,9 @@ // System headers #include #include +#include +#define GLM_ENABLE_EXPERIMENTAL +#include // Common headers #include "global.h" @@ -40,7 +43,7 @@ TetraBuilding::TetraBuilding() TetraBuilding::TetraBuilding(const MeshTransform& xform, - const float _vertices[4][3], + const glm::vec3 _vertices[4], const float _normals[4][3][3], const float _texcoords[4][3][2], const bool _useNormals[4], @@ -49,7 +52,8 @@ TetraBuilding::TetraBuilding(const MeshTransform& xform, bool drive, bool shoot, bool rico) { // tetra specific parameters - memcpy (vertices, _vertices, sizeof(vertices)); + for (int i = 0; i < 4; i++) + vertices[i] = _vertices[i]; memcpy (normals, _normals, sizeof(normals)); memcpy (texcoords, _texcoords, sizeof(texcoords)); memcpy (useNormals, _useNormals, sizeof(useNormals)); @@ -101,22 +105,16 @@ MeshObstacle* TetraBuilding::makeMesh() // setup the coordinates int i; std::vector checkTypes; - std::vector checkPoints; - std::vector verts; - std::vector norms; - std::vector texcds; + std::vector checkPoints; + std::vector verts; + std::vector norms; + std::vector texcds; // setup the inside check point - float center[3] = {0.0f, 0.0f, 0.0f}; + auto center = glm::vec3(0.0f); for (i = 0; i < 4; i++) - { - center[0] += vertices[i][0]; - center[1] += vertices[i][1]; - center[2] += vertices[i][2]; - } - center[0] *= 0.25f; - center[1] *= 0.25f; - center[2] *= 0.25f; + center += vertices[i]; + center *= 0.25f; checkPoints.push_back(center); checkTypes.push_back(MeshObstacle::CheckInside); @@ -158,24 +156,20 @@ void TetraBuilding::checkVertexOrder() int v, a; // make sure the the planes are facing outwards - float edge[3][3]; // edges from vertex 0 + glm::vec3 edge[3]; // edges from vertex 0 for (v = 0; v < 3; v++) { for (a = 0; a < 3; a++) edge[v][a] = vertices[v+1][a] - vertices[0][a]; } - float cross[3]; - vec3cross(cross, edge[0], edge[1]); - - const float dot = vec3dot (cross, edge[2]); + const auto dot = glm::mixedProduct(edge[0], edge[1], edge[2]); // swap vertices 1 & 2 if we are out of order if (dot < 0.0f) { - float tmpVertex[3]; - memcpy (tmpVertex, vertices[1], sizeof(tmpVertex)); - memcpy (vertices[1], vertices[2], sizeof(vertices[1])); - memcpy (vertices[2], tmpVertex, sizeof(vertices[2])); + auto tmpVertex = vertices[1]; + vertices[1] = vertices[2]; + vertices[2] = tmpVertex; float tmpNormals[4][3]; memcpy (tmpNormals, normals[1], sizeof(tmpNormals)); @@ -229,61 +223,27 @@ float TetraBuilding::intersect(const Ray&) const } -void TetraBuilding::get3DNormal(const float*, float*) const +void TetraBuilding::get3DNormal(const glm::vec3 &, glm::vec3 &) const { assert(false); return; } -void TetraBuilding::getNormal(const float*, float*) const +void TetraBuilding::getNormal(const glm::vec3 &, glm::vec3 &) const { assert(false); return; } -bool TetraBuilding::getHitNormal(const float*, float, const float*, float, - float, float, float, float*) const -{ - assert(false); - return false; -} - - -bool TetraBuilding::inCylinder(const float*,float, float) const -{ - assert(false); - return false; -} - - -bool TetraBuilding::inBox(const float*, float, float, float, float) const -{ - assert(false); - return false; -} - - -bool TetraBuilding::inMovingBox(const float*, float, const float*, float, - float, float, float) const +bool TetraBuilding::inCylinder(const glm::vec3 &, float, float) const { assert(false); return false; } -bool TetraBuilding::isCrossing(const float* UNUSED(p), float UNUSED(_angle), - float UNUSED(dx), float UNUSED(dy), float UNUSED(height), - float* UNUSED(_plane)) const -{ - assert(false); - return false; -} - - - - //////////////////////////////////////////////////////////////////////////////// // // Packing stuff @@ -472,7 +432,7 @@ void TetraBuilding::print(std::ostream& out, const std::string& indent) const // write the vertex information for (i = 0; i < 4; i++) { - const float* vertex = vertices[i]; + const auto &vertex = vertices[i]; out << indent << "\tvertex " << vertex[0] << " " << vertex[1] << " " << vertex[2] << std::endl; if (useNormals[i]) diff --git a/src/obstacle/Triangulate.cxx b/src/obstacle/Triangulate.cxx index c15125d4d3..8e8377b74f 100644 --- a/src/obstacle/Triangulate.cxx +++ b/src/obstacle/Triangulate.cxx @@ -11,62 +11,46 @@ */ -// top dog -#include "common.h" - // implementation header #include "Triangulate.h" // system headers #include #include - -// common headers -#include "vectors.h" - +#include +#include +#define GLM_ENABLE_EXPERIMENTAL +#include +#include // triangulation parameters -static afvec3 Normal; // FIXME, uNormal, vNormal; -//static afvec2* MVertsSpace = NULL; -static const float* const *Verts = NULL; +static glm::vec3 Normal; // FIXME, uNormal, vNormal; +static const glm::vec3 * const *Verts = NULL; static int Count = 0; static int* WorkSet = NULL; -static bool vec3norm(afvec3 v) -{ - const float len = sqrtf(vec3dot(v, v)); - if (len < 1.0e-6f) - { - v[0] = v[1] = v[2] = 0.0f; - return false; - } - else - { - const float scale = 1.0f / len; - v[0] *= scale; - v[1] *= scale; - v[2] *= scale; - } - return true; -} - - -static inline bool makeNormal() +static inline void makeNormal() { // Newell method Normal[0] = Normal[1] = Normal[2] = 0.0f; for (int i = 0; i < Count; i++) { - const float* v0 = Verts[i]; - const float* v1 = Verts[(i + 1) % Count]; + const auto &v0 = *Verts[i]; + const auto &v1 = *Verts[(i + 1) % Count]; Normal[0] += ((v0[1] - v1[1]) * (v0[2] + v1[2])); Normal[1] += ((v0[2] - v1[2]) * (v0[0] + v1[0])); Normal[2] += ((v0[0] - v1[0]) * (v0[1] + v1[1])); } // normalize - return vec3norm(Normal); + if (glm::isNull(Normal, 1.0e-6f)) + { + Normal = glm::vec3(0.0f); + return; + } + + Normal = glm::normalize(Normal); } @@ -76,14 +60,11 @@ static inline bool isConvex(int w0, int w1, int w2) const int v0 = WorkSet[w0]; const int v1 = WorkSet[w1]; const int v2 = WorkSet[w2]; - afvec3 e0, e1; - vec3sub(e0, Verts[v1], Verts[v0]); - vec3sub(e1, Verts[v2], Verts[v1]); - afvec3 cross; - vec3cross(cross, e0, e1); - if (vec3dot(cross, Normal) <= 0.0f) - return false; - return true; + auto &vert0 = *Verts[v0]; + auto &vert1 = *Verts[v1]; + auto &vert2 = *Verts[v2]; + auto dotcross = glm::mixedProduct(vert1 - vert0, vert2 - vert1, Normal); + return dotcross > 0.0f; } @@ -94,24 +75,28 @@ static inline bool isFaceClear(int w0, int w1, int w2) const int v1 = WorkSet[w1]; const int v2 = WorkSet[w2]; + auto &vert0 = *Verts[v0]; + auto &vert1 = *Verts[v1]; + auto &vert2 = *Verts[v2]; + // setup the edges - afvec3 edges[3]; - vec3sub(edges[0], Verts[v1], Verts[v0]); - vec3sub(edges[1], Verts[v2], Verts[v1]); - vec3sub(edges[2], Verts[v0], Verts[v2]); + glm::vec3 edges[3]; + edges[0] = vert1 - vert0; + edges[1] = vert2 - vert1; + edges[2] = vert0 - vert2; // get the triangle normal - afvec3 normal; - vec3cross(normal, edges[0], edges[1]); + auto normal = glm::cross(edges[0], edges[1]); // setup the planes - float planes[3][4]; - vec3cross(planes[0], edges[0], normal); - vec3cross(planes[1], edges[1], normal); - vec3cross(planes[2], edges[2], normal); - planes[0][3] = -vec3dot(planes[0], Verts[v0]); - planes[1][3] = -vec3dot(planes[1], Verts[v1]); - planes[2][3] = -vec3dot(planes[2], Verts[v2]); + glm::vec3 planes[3]; + float planesW[3]; + planes[0] = glm::cross(edges[0], normal); + planes[1] = glm::cross(edges[1], normal); + planes[2] = glm::cross(edges[2], normal); + planesW[0] = -glm::dot(planes[0], vert0); + planesW[1] = -glm::dot(planes[1], vert1); + planesW[2] = -glm::dot(planes[2], vert2); for (int w = 0; w < Count; w++) { @@ -120,9 +105,10 @@ static inline bool isFaceClear(int w0, int w1, int w2) continue; // FIXME: lazy } const int v = WorkSet[w]; + auto &vertV = *Verts[v]; for (i = 0; i < 3; i++) { - const float dist = vec3dot(planes[i], Verts[v]) + planes[i][3]; + const float dist = glm::dot(planes[i], vertV) + planesW[i]; if (dist > 0.0f) { break; // this point is clear @@ -140,16 +126,16 @@ static inline float getDot(int w0, int w1, int w2) const int v0 = WorkSet[w0]; const int v1 = WorkSet[w1]; const int v2 = WorkSet[w2]; - afvec3 e0, e1; - vec3sub(e0, Verts[v1], Verts[v0]); - vec3sub(e1, Verts[v2], Verts[v1]); - vec3norm(e0); - vec3norm(e1); - return vec3dot(e0, e1); + + auto &vert0 = *Verts[v0]; + auto &vert1 = *Verts[v1]; + auto &vert2 = *Verts[v2]; + + return glm::dot(glm::normalize(vert1 - vert0), glm::normalize(vert2 - vert1)); } -void triangulateFace(int count, const float* const* verts, +void triangulateFace(int count, const glm::vec3 * const verts[], std::vector& tris) { tris.clear(); diff --git a/src/obstacle/Triangulate.h b/src/obstacle/Triangulate.h index da5f66d471..2b9eb373ab 100644 --- a/src/obstacle/Triangulate.h +++ b/src/obstacle/Triangulate.h @@ -18,6 +18,7 @@ /* system interface headers */ #include +#include typedef struct @@ -25,7 +26,7 @@ typedef struct int indices[3]; } TriIndices; -extern void triangulateFace(int count, const float* const* verts, +extern void triangulateFace(int count, const glm::vec3 *const verts[], std::vector& tris); diff --git a/src/obstacle/WallObstacle.cxx b/src/obstacle/WallObstacle.cxx index f28d81b757..3ad79068a0 100644 --- a/src/obstacle/WallObstacle.cxx +++ b/src/obstacle/WallObstacle.cxx @@ -15,6 +15,8 @@ // System headers #include +#include +#include // Common headers #include "global.h" @@ -28,7 +30,7 @@ WallObstacle::WallObstacle() // do nothing } -WallObstacle::WallObstacle(const float* p, float a, float b, float h, bool rico) : +WallObstacle::WallObstacle(const glm::vec3 &p, float a, float b, float h, bool rico) : Obstacle(p, a, 0.0, b, h, false, false, rico) { finalize(); @@ -37,7 +39,7 @@ WallObstacle::WallObstacle(const float* p, float a, float b, float h, bool rico) void WallObstacle::finalize() { // compute normal - const float* p = getPosition(); + const auto &p = getPosition(); const float a = getRotation(); plane[0] = cosf(a); plane[1] = sinf(a); @@ -64,28 +66,25 @@ const char* WallObstacle::getClassName() // const float WallObstacle::intersect(const Ray& r) const { - const float* o = r.getOrigin(); - const float* d = r.getDirection(); - const float dot = -(d[0] * plane[0] + d[1] * plane[1] + d[2] * plane[2]); + const auto o = glm::vec4(r.getOrigin(), 1.0f); + const auto &d = r.getDirection(); + const float dot = -glm::dot(d, glm::vec3(plane)); if (dot == 0.0f) return -1.0f; - float t = (o[0] * plane[0] + o[1] * plane[1] + o[2] * plane[2] + - plane[3]) / dot; + float t = glm::dot(o, plane) / dot; return t; } -void WallObstacle::getNormal(const float*, float* n) const +void WallObstacle::getNormal(const glm::vec3 &, glm::vec3 &n) const { - n[0] = plane[0]; - n[1] = plane[1]; - n[2] = plane[2]; + n = plane; } -bool WallObstacle::inCylinder(const float* p, float r, float UNUSED( height )) const +bool WallObstacle::inCylinder(const glm::vec3 &p, float r, float UNUSED( height )) const { return p[0] * plane[0] + p[1] * plane[1] + p[2] * plane[2] + plane[3] < r; } -bool WallObstacle::inBox(const float* p, float _angle, +bool WallObstacle::inBox(const glm::vec3 &p, float _angle, float halfWidth, float halfBreadth, float UNUSED( height )) const { @@ -93,7 +92,7 @@ bool WallObstacle::inBox(const float* p, float _angle, const float yWidth = sinf(_angle); const float xBreadth = -yWidth; const float yBreadth = xWidth; - float corner[3]; + glm::vec3 corner; corner[2] = p[2]; // check to see if any corner is inside negative half-space @@ -113,21 +112,22 @@ bool WallObstacle::inBox(const float* p, float _angle, return false; } -bool WallObstacle::inMovingBox(const float* UNUSED( oldP ), float UNUSED( oldAngle ), - const float* p, float _angle, - float halfWidth, float halfBreadth, float height) const +bool WallObstacle::inMovingBox(const glm::vec3 &UNUSED( oldP ), float UNUSED( oldAngle ), + const glm::vec3 &p, float _angle, + float halfWidth, float halfBreadth, float height) const { return inBox (p, _angle, halfWidth, halfBreadth, height); } bool WallObstacle::getHitNormal( - const float*, float, - const float*, float, + const glm::vec3 &, float, + const glm::vec3 &, float, float, float, float, - float* normal) const + glm::vec3 &normal) const { - getNormal(NULL, normal); + static const auto zero = glm::vec3(0.0f); + getNormal(zero, normal); return true; } diff --git a/src/obstacle/WallSceneNodeGenerator.cxx b/src/obstacle/WallSceneNodeGenerator.cxx index 81529ecfb3..dfd9b30651 100644 --- a/src/obstacle/WallSceneNodeGenerator.cxx +++ b/src/obstacle/WallSceneNodeGenerator.cxx @@ -42,10 +42,10 @@ WallSceneNode* WallSceneNodeGenerator::getNextNode( { if (getNodeNumber() == 1) return NULL; - GLfloat base[3]; - GLfloat sEdge[3]; - GLfloat tEdge[3]; - const float* pos = wall->getPosition(); + glm::vec3 base; + glm::vec3 sEdge; + glm::vec3 tEdge; + const auto &pos = wall->getPosition(); const float c = cosf(wall->getRotation()); const float s = sinf(wall->getRotation()); const float h = wall->getBreadth(); diff --git a/src/ogl/Makefile.am b/src/ogl/Makefile.am index 3c0b6d7772..94d102d5ba 100644 --- a/src/ogl/Makefile.am +++ b/src/ogl/Makefile.am @@ -14,6 +14,7 @@ MAINTAINERCLEANFILES = \ libGLKit_la_LDFLAGS = -static libGLKit_la_SOURCES = \ + OpenGLAPI.cxx \ OpenGLFramebuffer.cxx \ OpenGLGState.cxx \ OpenGLLight.cxx \ diff --git a/src/ogl/OpenGLAPI.cxx b/src/ogl/OpenGLAPI.cxx new file mode 100644 index 0000000000..fa7f62cc58 --- /dev/null +++ b/src/ogl/OpenGLAPI.cxx @@ -0,0 +1,120 @@ +/* bzflag + * Copyright (c) 1993-2023 Tim Riker + * + * This package is free software; you can redistribute it and/or + * modify it under the terms of the license found in the file + * named COPYING that should have accompanied this file. + * + * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. + */ + +// Interface header +#include "OpenGLAPI.h" + +// System headers +#include +#include +#include +#include + +// common headers +#include "bzfgl.h" + +void glColor(const glm::vec3 &c, float alpha) +{ + glColor4f(c.r, c.g, c.b, alpha); +} + +void glColor(const glm::vec4 &c) +{ + glColor4f(c.r, c.g, c.b, c.a); +} + +void glVertex(const glm::vec2 &p) +{ + glVertex2f(p.x, p.y); +} + +void glVertex(const glm::vec2 &p, float z) +{ + glVertex3f(p.x, p.y, z); +} + +void glVertex(const glm::vec3 &p) +{ + glVertex3f(p.x, p.y, p.z); +} + +void glNormal(const glm::vec2 &n) +{ + glNormal3f(n.x, n.y, 0.0f); +} + +void glNormal(const glm::vec3 &n) +{ + glNormal3f(n.x, n.y, n.z); +} + +void glTexCoord(const glm::vec2 &t) +{ + glTexCoord2f(t.s, t.t); +} + +void glLoadMatrix(const glm::mat4 &m) +{ + glLoadMatrixf(glm::value_ptr(m)); +} + +void glMultMatrix(const glm::mat4 &m) +{ + glMultMatrixf(glm::value_ptr(m)); +} + +void glTranslate(const glm::vec3 &v) +{ + glTranslatef(v.x, v.y, v.z); +} + +void glVertexPointer(const glm::vec3 vertices[]) +{ + glVertexPointer(3, GL_FLOAT, 0, glm::value_ptr(vertices[0])); +} + +void glTexCoordPointer(const glm::vec2 texCoords[]) +{ + glTexCoordPointer(2, GL_FLOAT, 0, glm::value_ptr(texCoords[0])); +} + +glm::vec4 glGetFogColor() +{ + glm::vec4 fogColor; + glGetFloatv(GL_FOG_COLOR, glm::value_ptr(fogColor)); + return fogColor; +} + +void glSetFogColor(const glm::vec4 fogColor) +{ + glFogfv(GL_FOG_COLOR, glm::value_ptr(fogColor)); +} + +glm::ivec4 glGetViewport() +{ + glm::ivec4 viewport; + glGetIntegerv(GL_VIEWPORT, glm::value_ptr(viewport)); + return viewport; +} + +void glClipPlane(int id, const glm::dvec4 &plane) +{ + glClipPlane(id, glm::value_ptr(plane)); +} + +// Local Variables: *** +// mode: C++ *** +// tab-width: 4 *** +// c-basic-offset: 4 *** +// indent-tabs-mode: nil *** +// End: *** +// ex: shiftwidth=4 tabstop=4 diff --git a/src/ogl/OpenGLLight.cxx b/src/ogl/OpenGLLight.cxx index 5c920901ae..e5537ea94a 100644 --- a/src/ogl/OpenGLLight.cxx +++ b/src/ogl/OpenGLLight.cxx @@ -15,6 +15,7 @@ // System headers #include +#include // Common headers #include "OpenGLGState.h" @@ -26,14 +27,8 @@ GLint OpenGLLight::maxLights = 0; OpenGLLight::OpenGLLight() { - pos[0] = 0.0f; - pos[1] = 0.0f; - pos[2] = 1.0f; - pos[3] = 0.0f; - color[0] = 0.8f; - color[1] = 0.8f; - color[2] = 0.8f; - color[3] = 1.0f; + pos = glm::vec4(0.0f, 0.0f, 1.0f, 0.0f); + color = glm::vec4(0.8f, 0.8f, 0.8f, 1.0f); atten[0] = 1.0f; atten[1] = 0.0f; atten[2] = 0.0f; @@ -59,14 +54,8 @@ OpenGLLight::OpenGLLight() OpenGLLight::OpenGLLight(const OpenGLLight& l) { - pos[0] = l.pos[0]; - pos[1] = l.pos[1]; - pos[2] = l.pos[2]; - pos[3] = l.pos[3]; - color[0] = l.color[0]; - color[1] = l.color[1]; - color[2] = l.color[2]; - color[3] = l.color[3]; + pos = l.pos; + color = l.color; atten[0] = l.atten[0]; atten[1] = l.atten[1]; atten[2] = l.atten[2]; @@ -83,14 +72,8 @@ OpenGLLight& OpenGLLight::operator=(const OpenGLLight& l) if (this != &l) { freeLists(); - pos[0] = l.pos[0]; - pos[1] = l.pos[1]; - pos[2] = l.pos[2]; - pos[3] = l.pos[3]; - color[0] = l.color[0]; - color[1] = l.color[1]; - color[2] = l.color[2]; - color[3] = l.color[3]; + pos = l.pos; + color = l.color; atten[0] = l.atten[0]; atten[1] = l.atten[1]; atten[2] = l.atten[2]; @@ -127,41 +110,38 @@ OpenGLLight::~OpenGLLight() } -void OpenGLLight::setDirection(const GLfloat* _pos) +void OpenGLLight::setDirection(const glm::vec3 &_pos) { freeLists(); - pos[0] = _pos[0]; - pos[1] = _pos[1]; - pos[2] = _pos[2]; - pos[3] = 0.0f; + pos = glm::vec4(_pos, 0.0f); } -void OpenGLLight::setPosition(const GLfloat* _pos) +void OpenGLLight::setPosition(const glm::vec3 &_pos) { freeLists(); - pos[0] = _pos[0]; - pos[1] = _pos[1]; - pos[2] = _pos[2]; - pos[3] = 1.0f; + pos = glm::vec4(_pos, 1.0f); } void OpenGLLight::setColor(GLfloat r, GLfloat g, GLfloat b) { freeLists(); - color[0] = r; - color[1] = g; - color[2] = b; + color = glm::vec4(r, g, b, 1.0f); } void OpenGLLight::setColor(const GLfloat* rgb) { freeLists(); - color[0] = rgb[0]; - color[1] = rgb[1]; - color[2] = rgb[2]; + color = glm::vec4(rgb[0], rgb[1], rgb[2], 1.0f); +} + + +void OpenGLLight::setColor(const glm::vec3 &rgb) +{ + freeLists(); + color = glm::vec4(rgb, 1.0f); } @@ -213,10 +193,8 @@ void OpenGLLight::calculateImportance(const ViewFrustum& frustum) // check if the light is in front of the front viewing plane bool sphereCull = true; - const GLfloat* p = frustum.getDirection(); - const float fd = (p[0] * pos[0]) + - (p[1] * pos[1]) + - (p[2] * pos[2]) + p[3]; + const auto &p = frustum.getDirection(); + const float fd = glm::dot(p, pos); // cull against the frustum planes if (fd > 0.0f) @@ -225,10 +203,8 @@ void OpenGLLight::calculateImportance(const ViewFrustum& frustum) const int planeCount = frustum.getPlaneCount(); for (int i = 1; i < planeCount; i++) { - const float* plane = frustum.getSide(i); - const float len = (plane[0] * pos[0]) + - (plane[1] * pos[1]) + - (plane[2] * pos[2]) + plane[3]; + const auto &plane = frustum.getSide(i); + const float len = glm::dot(plane, pos); if (len < -maxDist) { importance = -1.0f; @@ -238,15 +214,8 @@ void OpenGLLight::calculateImportance(const ViewFrustum& frustum) } // calculate the distance - const GLfloat* eye = frustum.getEye(); - const float v[3] = - { - (eye[0] - pos[0]), - (eye[1] - pos[1]), - (eye[2] - pos[2]), - }; - float dist = (v[0] * v[0]) + (v[1] * v[1]) + (v[2] * v[2]); - dist = sqrtf(dist); + const auto &eye = frustum.getEye(); + float dist = glm::distance(eye, glm::vec3(pos)); // do a sphere cull if requested if (sphereCull && (dist > maxDist)) @@ -300,9 +269,9 @@ void OpenGLLight::execute(int index, bool useList) const void OpenGLLight::genLight(GLenum light) const { - glLightfv(light, GL_POSITION, pos); - glLightfv(light, GL_DIFFUSE, color); - glLightfv(light, GL_SPECULAR, color); + glLightfv(light, GL_POSITION, glm::value_ptr(pos)); + glLightfv(light, GL_DIFFUSE, glm::value_ptr(color)); + glLightfv(light, GL_SPECULAR, glm::value_ptr(color)); glLighti(light, GL_SPOT_EXPONENT, 0); glLightf(light, GL_CONSTANT_ATTENUATION, atten[0]); glLightf(light, GL_LINEAR_ATTENUATION, atten[1]); diff --git a/src/ogl/OpenGLMaterial.cxx b/src/ogl/OpenGLMaterial.cxx index b55c01dfde..08d3b5d735 100644 --- a/src/ogl/OpenGLMaterial.cxx +++ b/src/ogl/OpenGLMaterial.cxx @@ -22,8 +22,8 @@ OpenGLMaterial::Rep* OpenGLMaterial::Rep::head = NULL; OpenGLMaterial::Rep* OpenGLMaterial::Rep::getRep( - const GLfloat* specular, - const GLfloat* emissive, + const glm::vec3 &specular, + const glm::vec3 &emissive, GLfloat shininess) { // see if we've already got an identical material @@ -32,14 +32,10 @@ OpenGLMaterial::Rep* OpenGLMaterial::Rep::getRep( if (shininess != scan->shininess) continue; - const GLfloat* c1 = specular; - const GLfloat* c2 = scan->specular; - if (c1[0] != c2[0] || c1[1] != c2[1] || c1[2] != c2[2]) + if (specular != scan->specular) continue; - c1 = emissive; - c2 = scan->emissive; - if (c1[0] != c2[0] || c1[1] != c2[1] || c1[2] != c2[2]) + if (emissive != scan->emissive) continue; scan->ref(); @@ -50,8 +46,8 @@ OpenGLMaterial::Rep* OpenGLMaterial::Rep::getRep( return new Rep(specular, emissive, shininess); } -OpenGLMaterial::Rep::Rep(const GLfloat* _specular, - const GLfloat* _emissive, +OpenGLMaterial::Rep::Rep(const glm::vec3 &_specular, + const glm::vec3 &_emissive, GLfloat _shininess) : refCount(1), shininess(_shininess) { @@ -62,14 +58,8 @@ OpenGLMaterial::Rep::Rep(const GLfloat* _specular, head = this; if (next) next->prev = this; - specular[0] = _specular[0]; - specular[1] = _specular[1]; - specular[2] = _specular[2]; - specular[3] = 1.0f; - emissive[0] = _emissive[0]; - emissive[1] = _emissive[1]; - emissive[2] = _emissive[2]; - emissive[3] = 1.0f; + specular = _specular; + emissive = _emissive; OpenGLGState::registerContextInitializer(freeContext, initContext, (void*)this); @@ -112,8 +102,19 @@ void OpenGLMaterial::Rep::execute() list = glGenLists(1); glNewList(list, GL_COMPILE_AND_EXECUTE); { - glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular); - glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, emissive); + GLfloat _specular[4]; + GLfloat _emissive[4]; + + _specular[0] = specular[0]; + _specular[1] = specular[1]; + _specular[2] = specular[2]; + _specular[3] = 1.0f; + _emissive[0] = emissive[0]; + _emissive[1] = emissive[1]; + _emissive[2] = emissive[2]; + _emissive[3] = 1.0f; + glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, _specular); + glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, _emissive); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shininess); if (RENDERER.useQuality() > 0) { @@ -165,8 +166,8 @@ OpenGLMaterial::OpenGLMaterial() rep = NULL; } -OpenGLMaterial::OpenGLMaterial(const GLfloat* specular, - const GLfloat* emissive, +OpenGLMaterial::OpenGLMaterial(const glm::vec3 &specular, + const glm::vec3 &emissive, GLfloat shininess) { rep = Rep::getRep(specular, emissive, shininess); diff --git a/src/ogl/OpenGLUtils.cxx b/src/ogl/OpenGLUtils.cxx index d597143483..1cfe56b49b 100644 --- a/src/ogl/OpenGLUtils.cxx +++ b/src/ogl/OpenGLUtils.cxx @@ -15,11 +15,10 @@ // system headers #include +#include // common headers -#include "bzfgl.h" #include "bzfio.h" -#include "vectors.h" #include "BZDBCache.h" #include "BzMaterial.h" #include "DynamicColor.h" @@ -30,14 +29,11 @@ #include "TextureMatrix.h" -#define INVALID_GL_ID 0xffffffff - - //============================================================================// //============================================================================// void bzMat2gstate(const BzMaterial* bzmat, OpenGLGState& gstate, - fvec4& color, const fvec4*& colorPtr) + glm::vec4 &color, const glm::vec4 *&colorPtr) { bzmat->setReference(); @@ -115,15 +111,16 @@ void bzMat2gstate(const BzMaterial* bzmat, OpenGLGState& gstate, // set it to white, this should only happen when // we've gotten a user texture, and there's a // request to not use the material's diffuse color. - color = fvec4(1.0f, 1.0f, 1.0f, 1.0f); + color = glm::vec4(1.0f); } // dynamic color const DynamicColor* dyncol = DYNCOLORMGR.getColor(bzmat->getDynamicColor()); if (dyncol != NULL) { - const float* c = dyncol->getColor(); - colorPtr = new fvec4(c[0],c[1],c[2],c[3]); + const auto c = dyncol->getColor(); + // Do we free it ? + colorPtr = new glm::vec4(*c); colorAlpha = dyncol->canHaveAlpha(); // override } else diff --git a/src/ogl/RenderNode.cxx b/src/ogl/RenderNode.cxx index f732e64bea..961be5d856 100644 --- a/src/ogl/RenderNode.cxx +++ b/src/ogl/RenderNode.cxx @@ -17,6 +17,9 @@ #include #include #include +#include +#define GLM_ENABLE_EXPERIMENTAL +#include // // RenderNode @@ -97,16 +100,13 @@ void RenderNodeGStateList::render() const } -void RenderNodeGStateList::sort(const GLfloat* e) +void RenderNodeGStateList::sort(const glm::vec3 &e) { // calculate distances from the eye (squared) for (auto &item : list) { - const GLfloat* p = item.node->getPosition(); - const float dx = (p[0] - e[0]); - const float dy = (p[1] - e[1]); - const float dz = (p[2] - e[2]); - item.depth = ((dx * dx) + (dy * dy) + (dz * dz)); + const auto &p = item.node->getPosition(); + item.depth = glm::distance2(p, e); } // sort from farthest to closest diff --git a/src/scene/BSPSceneDatabase.cxx b/src/scene/BSPSceneDatabase.cxx index c9a318fbed..2dfaff7d96 100644 --- a/src/scene/BSPSceneDatabase.cxx +++ b/src/scene/BSPSceneDatabase.cxx @@ -14,11 +14,15 @@ * */ -#include "common.h" -#include "SceneNode.h" +// Interface header +#include "BSPSceneDatabase.h" + +// System headers #include #include -#include "BSPSceneDatabase.h" + +// Common headers +#include "SceneNode.h" #include "ViewFrustum.h" #include "SphereSceneNode.h" #include "WallSceneNode.h" @@ -52,10 +56,10 @@ BSPSceneDatabase::Node::Node(bool _dynamic, SceneNode* _node): BSPSceneDatabase::BSPSceneDatabase() : root(NULL), - depth(0) + depth(0), + eye(0.0f) { needNoPlaneNodes = true; - memset(eye, 0, sizeof(GLfloat) * 3); } @@ -184,7 +188,7 @@ bool BSPSceneDatabase::insertStatic(int level, Node* _root, // split against root's plane SceneNode* front = NULL, *back = NULL; - switch (node->split(_root->node->getPlane(), front, back)) + switch (node->split(*_root->node->getPlane(), front, back)) { case 0: // copy style to new nodes @@ -244,9 +248,9 @@ void BSPSceneDatabase::insertDynamic(int level, Node* _root, GLfloat d; if (!_root->dynamic && _root->node->getPlane()) { - const GLfloat* plane = _root->node->getPlane(); - const GLfloat* pos = node->getSphere(); - d = pos[0] * plane[0] + pos[1] * plane[1] + pos[2] * plane[2] + plane[3]; + const auto plane = _root->node->getPlane(); + const auto pos = glm::vec4(node->getSphere(), 1.0f); + d = glm::dot(pos, *plane); } else d = _root->node->getDistance(eye) - node->getDistance(eye); @@ -283,14 +287,14 @@ void BSPSceneDatabase::insertNoPlane(int level, Node* _root, GLfloat d; if (_root->node->getPlane()) { - const GLfloat* plane = _root->node->getPlane(); - const GLfloat* pos = node->getSphere(); - d = pos[0] * plane[0] + pos[1] * plane[1] + pos[2] * plane[2] + plane[3]; + const auto plane = _root->node->getPlane(); + const auto pos = glm::vec4(node->getSphere(), 1.0f); + d = glm::dot(pos, *plane); } else { // it's a crap shoot (draw smaller items first) - d = node->getSphere()[3] - _root->node->getSphere()[3]; + d = node->getRadius2() - _root->node->getRadius2(); } if (d >= 0.0f) @@ -412,8 +416,7 @@ void BSPSceneDatabase::addRenderNodes(SceneRenderer& _renderer) { renderer = &_renderer; frustum = &renderer->getViewFrustum(); - const GLfloat* _eye = frustum->getEye(); - memcpy (eye, _eye, sizeof(GLfloat[3])); + eye = frustum->getEye(); nodeAddRenderNodes(root); } return; @@ -473,11 +476,11 @@ void BSPSceneDatabase::nodeAddRenderNodes(Node* node) Node* front = node->front; SceneNode* snode = node->node; - const GLfloat* plane = snode->getPlane(); + const auto plane = snode->getPlane(); if (plane) { - if (((plane[0] * eye[0]) + (plane[1] * eye[1]) + - (plane[2] * eye[2]) + plane[3]) >= 0.0f) + const auto eye4 = glm::vec4(eye, 1.0f); + if (glm::dot(*plane, eye4) >= 0.0f) { // eye is in front so render: back, node, front if (back) diff --git a/src/scene/Occluder.cxx b/src/scene/Occluder.cxx index 21c25263ba..0a3cb98c57 100644 --- a/src/scene/Occluder.cxx +++ b/src/scene/Occluder.cxx @@ -16,12 +16,16 @@ // System headers #include #include +#include +#define GLM_ENABLE_EXPERIMENTAL +#include // Common headers #include "SceneNode.h" #include "Frustum.h" #include "Intersect.h" #include "StateDatabase.h" +#include "OpenGLAPI.h" ////////////////////////////////////////////////////////////////////////////// @@ -293,18 +297,16 @@ Occluder::Occluder(const SceneNode* node) vertexCount = 0; // used to flag a bad occluder return; } - vertices = new float[vertexCount][3]; + vertices = new glm::vec3[vertexCount]; planeCount = vertexCount + 1; // the occluder's plane normal - planes = new float[planeCount][4]; + planes = new glm::vec4[planeCount]; // counter-clockwise order as viewed from the front face for (int i = 0; i < vertexCount; i++) { - const float* vertex = node->getVertex(i); - vertices[i][0] = vertex[0]; - vertices[i][1] = vertex[1]; - vertices[i][2] = vertex[2]; + const auto vertex = node->getVertex(i); + vertices[i] = vertex; } return; @@ -325,31 +327,26 @@ IntersectLevel Occluder::doCullAxisBox(const Extents& exts) } -static bool makePlane (const float* p1, const float* p2, const float* pc, - float* r) +static bool makePlane (const glm::vec3 &p1, const glm::vec3 &p2, const glm::vec3 &pc, + glm::vec4 &r) { // make vectors from points - float x[3] = {p1[0] - pc[0], p1[1] - pc[1], p1[2] - pc[2]}; - float y[3] = {p2[0] - pc[0], p2[1] - pc[1], p2[2] - pc[2]}; - float n[3]; + auto x = p1 - pc; + auto y = p2 - pc; // cross product to get the normal - n[0] = (x[1] * y[2]) - (x[2] * y[1]); - n[1] = (x[2] * y[0]) - (x[0] * y[2]); - n[2] = (x[0] * y[1]) - (x[1] * y[0]); + auto n = glm::cross(x, y); // normalize - float len = (n[0] * n[0]) + (n[1] * n[1]) + (n[2] * n[2]); + float len = glm::length2(n); if (len < +0.001f) return false; else - len = 1.0f / sqrtf (len); - r[0] = n[0] * len; - r[1] = n[1] * len; - r[2] = n[2] * len; + len = glm::inversesqrt(len); + n *= len; // finish the plane equation: {rx*px + ry*py + rz+pz + rd = 0} - r[3] = -((pc[0] * r[0]) + (pc[1] * r[1]) + (pc[2] * r[2])); + r = glm::vec4(n, -glm::dot(pc, n)); return true; } @@ -357,19 +354,16 @@ static bool makePlane (const float* p1, const float* p2, const float* pc, bool Occluder::makePlanes(const Frustum* frustum) { // occluders can't have their back towards the camera - const float* eye = frustum->getEye(); - const float* p = sceneNode->getPlane(); - float tmp = (p[0] * eye[0]) + (p[1] * eye[1]) + (p[2] * eye[2]) + p[3]; + const auto eye = glm::vec4(frustum->getEye(), 1.0f); + const auto &p = *sceneNode->getPlane(); + float tmp = glm::dot(p, eye); if (tmp < +0.1f) return false; // FIXME - store/flag this so we don't have to do it again? // make the occluder's normal plane - const float* plane = sceneNode->getPlane(); - planes[0][0] = -plane[0]; - planes[0][1] = -plane[1]; - planes[0][2] = -plane[2]; - planes[0][3] = -plane[3]; + const auto &plane = *sceneNode->getPlane(); + planes[0] = -plane; // make the edges planes for (int i = 0; i < vertexCount; i++) @@ -386,7 +380,7 @@ bool Occluder::makePlanes(const Frustum* frustum) void Occluder::draw() const { int v; - GLfloat colors[5][4] = + glm::vec4 colors[5] = { {1.0f, 0.0f, 1.0f, 1.0f}, // purple (occluder's normal) {1.0f, 0.0f, 0.0f, 1.0f}, // red @@ -403,7 +397,7 @@ void Occluder::draw() const if (DrawNormals) { // the tri-wall 'getSphere()' center sucks... - float center[3]; + glm::vec3 center; for (int a = 0; a < 3; a++) { center[a] = 0.0f; @@ -412,16 +406,13 @@ void Occluder::draw() const center[a] = center[a] / (float) vertexCount; } - float outwards[3]; - outwards[0] = center[0] - (length * planes[0][0]); - outwards[1] = center[1] - (length * planes[0][1]); - outwards[2] = center[2] - (length * planes[0][2]); + auto outwards = center - length * glm::vec3(planes[0]); // draw the plane normal glBegin (GL_LINES); - glColor4fv (colors[0]); - glVertex3fv (center); - glVertex3fv (outwards); + glColor(colors[0]); + glVertex(center); + glVertex(outwards); glEnd (); } @@ -430,25 +421,22 @@ void Occluder::draw() const { for (v = 0; v < vertexCount; v++) { - float midpoint[3]; - float outwards[3]; + glm::vec3 midpoint; int vn = (v + 1) % vertexCount; for (int a = 0; a < 3; a++) - { midpoint[a] = 0.5f * (vertices[v][a] + vertices[vn][a]); - outwards[a] = midpoint[a] - (length * planes[vn + 1][a]); - } + auto outwards = midpoint - length * glm::vec3(planes[vn + 1]); glBegin (GL_LINES); - glColor4fv (colors[(v % 4) + 1]); + glColor(colors[(v % 4) + 1]); if (DrawEdges) { - glVertex3fv (vertices[v]); - glVertex3fv (vertices[vn]); + glVertex(vertices[v]); + glVertex(vertices[vn]); } if (DrawNormals) { - glVertex3fv (midpoint); - glVertex3fv (outwards); + glVertex(midpoint); + glVertex(outwards); } glEnd(); } @@ -460,8 +448,8 @@ void Occluder::draw() const for (v = 0; v < vertexCount; v++) { glBegin (GL_POINTS); - glColor4fv (colors[(v % 4) + 1]); - glVertex3fv (vertices[v]); + glColor(colors[(v % 4) + 1]); + glVertex(vertices[v]); glEnd(); } } diff --git a/src/scene/Occluder.h b/src/scene/Occluder.h index 9f3a29a7b2..a626d9c2d1 100644 --- a/src/scene/Occluder.h +++ b/src/scene/Occluder.h @@ -35,8 +35,8 @@ class Occluder unsigned int cullScore; int planeCount; // one more then the vertex count int vertexCount; // vertex count of the occluding plane - float (*planes)[4]; - float (*vertices)[3]; + glm::vec4 *planes; + glm::vec3 *vertices; static const bool DrawEdges; static const bool DrawNormals; static const bool DrawVertices; diff --git a/src/scene/Octree.cxx b/src/scene/Octree.cxx index bb00c8cb01..b7f1ff2425 100644 --- a/src/scene/Octree.cxx +++ b/src/scene/Octree.cxx @@ -10,22 +10,21 @@ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ -#include "common.h" - -// system headers -#include - // implementation header #include "Octree.h" -// local headers -#include "Occluder.h" +// system headers +#include // common headers #include "Extents.h" #include "Intersect.h" - #include "StateDatabase.h" +#include "OpenGLAPI.h" + +// local headers +#include "Occluder.h" + static bool F2BSORT = true;//FIXME @@ -48,7 +47,7 @@ static int CullListCount = 0; static SceneNode** CullList = NULL; static const Frustum* CullFrustum = NULL; static int ShadowCount = 0; -static const float(*ShadowPlanes)[4]; +static const glm::vec4 *ShadowPlanes; static OccluderManager OcclMgrs[2]; static OccluderManager* OcclMgr = &OcclMgrs[0]; @@ -233,7 +232,7 @@ int Octree::getRadarList(SceneNode** list, int listSize, int Octree::getShadowList(SceneNode** list, int listSize, - int planeCount, const float(*planes)[4]) const + int planeCount, const glm::vec4 *planes) const { if (!root) return 0; @@ -414,14 +413,12 @@ void OctreeNode::makeChildren() { int side[3]; // the axis sides (0 or 1) Extents exts; - float center[3]; // setup the center point - for (int i = 0; i < 3; i++) - center[i] = 0.5f * (extents.maxs[i] + extents.mins[i]); + auto center = 0.5f * (extents.maxs + extents.mins); childCount = 0; - const float* extentSet[3] = { extents.mins, center, extents.maxs }; + const glm::vec3 extentSet[3] = { extents.mins, center, extents.maxs }; for (side[0] = 0; side[0] < 2; side[0]++) { @@ -531,7 +528,7 @@ void OctreeNode::getFrustumList() const { if (F2BSORT) { - const float* dir = CullFrustum->getDirection(); + const auto &dir = CullFrustum->getDirection(); unsigned char dirbits = 0; if (dir[0] < 0.0f) dirbits |= (1 << 0); if (dir[1] < 0.0f) dirbits |= (1 << 1); @@ -825,14 +822,14 @@ void OctreeNode::tallyStats() void OctreeNode::draw() { - GLfloat red[4] = { 1.0f, 0.0f, 0.0f, 0.75f }; // red - GLfloat blue[4] = { 0.0f, 0.0f, 1.0f, 0.75f }; // blue - GLfloat green[4] = { 0.0f, 1.0f, 0.0f, 0.75f }; // green - GLfloat yellow[4] = { 1.0f, 1.0f, 0.0f, 0.75f }; // yellow - GLfloat purple[4] = { 1.0f, 0.0f, 1.0f, 0.75f }; // purple - GLfloat *color = purple; + glm::vec4 red = { 1.0f, 0.0f, 0.0f, 0.75f }; // red + glm::vec4 blue = { 0.0f, 0.0f, 1.0f, 0.75f }; // blue + glm::vec4 green = { 0.0f, 1.0f, 0.0f, 0.75f }; // green + glm::vec4 yellow = { 1.0f, 1.0f, 0.0f, 0.75f }; // yellow + glm::vec4 purple = { 1.0f, 0.0f, 1.0f, 0.75f }; // purple + glm::vec4 *color = &purple; int x, y, z, c; - float points[5][3]; + glm::vec3 points[5]; IntersectLevel frustumCull = Contained; bool occludeCull = false; @@ -846,24 +843,24 @@ void OctreeNode::draw() switch (frustumCull) { case Outside: - color = purple; + color = &purple; break; case Partial: if (!occludeCull) - color = blue; + color = &blue; else - color = green; + color = &green; break; case Contained: if (!occludeCull) - color = red; + color = &red; else - color = yellow; + color = &yellow; break; } - glColor4fv(color); + glColor(*color); - const float* exts[2] = { extents.mins, extents.maxs }; + const glm::vec3 exts[2] = { extents.mins, extents.maxs }; // draw Z-normal squares for (z = 0; z < 2; z++) @@ -876,11 +873,11 @@ void OctreeNode::draw() points[c][1] = exts[y][1]; points[c][2] = exts[z][2]; } - memcpy(points[4], points[0], sizeof(points[4])); + points[4] = points[0]; glBegin(GL_LINE_STRIP); for (int i = 0; i < 5; i++) - glVertex3fv(points[i]); + glVertex(points[i]); glEnd(); } @@ -897,8 +894,8 @@ void OctreeNode::draw() points[z][2] = exts[z][2]; } glBegin(GL_LINE_STRIP); - glVertex3fv(points[0]); - glVertex3fv(points[1]); + glVertex(points[0]); + glVertex(points[1]); glEnd(); } diff --git a/src/scene/Octree.h b/src/scene/Octree.h index 946cd7515c..1a87a0d6ed 100644 --- a/src/scene/Octree.h +++ b/src/scene/Octree.h @@ -36,7 +36,7 @@ class Octree int getFrustumList (SceneNode** list, int listSize, const Frustum* frustum) const; int getShadowList (SceneNode** list, int listSize, - int planeCount, const float (*planes)[4]) const; + int planeCount, const glm::vec4 *planes) const; int getRadarList (SceneNode** list, int listSize, const Frustum* frustum) const; diff --git a/src/scene/ZSceneDatabase.cxx b/src/scene/ZSceneDatabase.cxx index fd47dddc36..8d2677e77a 100644 --- a/src/scene/ZSceneDatabase.cxx +++ b/src/scene/ZSceneDatabase.cxx @@ -233,13 +233,13 @@ void ZSceneDatabase::addLights(SceneRenderer& renderer) } -static void setupShadowPlanes(const Frustum* frustum, const float* sunDir, - int& planeCount, float planes[4][4]) +static void setupShadowPlanes(const Frustum* frustum, const glm::vec3 &sunDir, + int& planeCount, glm::vec4 planes[4]) { // FIXME: As a first cut, we'll assume that // the frustum top points towards Z. - const float* eye = frustum->getEye(); + const auto &eye = frustum->getEye(); if (frustum->getUp()[2] < 0.999f) { planeCount = 0; @@ -299,7 +299,7 @@ static void setupShadowPlanes(const Frustum* frustum, const float* sunDir, void ZSceneDatabase::addShadowNodes(SceneRenderer& renderer) { int i; - const float* sunDir = renderer.getSunDirection(); + const auto *sunDir = renderer.getSunDirection(); const ViewFrustum& vf = renderer.getViewFrustum(); const Frustum* frustum = (const Frustum*) &vf; @@ -314,8 +314,8 @@ void ZSceneDatabase::addShadowNodes(SceneRenderer& renderer) // setup the shadow clipping planes int planeCount = 0; - float planes[4][4]; - setupShadowPlanes(frustum, sunDir, planeCount, planes); + glm::vec4 planes[4]; + setupShadowPlanes(frustum, *sunDir, planeCount, planes); // cull if we're supposed to if (octree) @@ -378,7 +378,7 @@ void ZSceneDatabase::addRenderNodes(SceneRenderer& renderer) { int i; const ViewFrustum& frustum = renderer.getViewFrustum(); - const float* eye = frustum.getEye(); + const auto eye = glm::vec4(frustum.getEye(), 1.0f); // see if we need an octree, or if it needs to be rebuilt setupCullList(); @@ -397,13 +397,12 @@ void ZSceneDatabase::addRenderNodes(SceneRenderer& renderer) { SceneNode* node = culledList[i]; - const float* plane = node->getPlane(); + const auto plane = node->getPlane(); if (plane != NULL) { // see if our eye is behind the plane - if (((eye[0] * plane[0]) + (eye[1] * plane[1]) + (eye[2] * plane[2]) + - plane[3]) <= 0.0f) + if (glm::dot(eye, *plane) <= 0.0f) { node->octreeState = SceneNode::OctreeCulled; continue;