Compare commits

...

316 Commits

Author SHA1 Message Date
antc13 24486c314d Reworked the Exporter. 2016-01-13 14:03:58 +01:00
antc13 7b62dc19bf Spitting out Meshes & Animation Data to file. 2016-01-12 15:39:29 +01:00
antc13 0e90382fd1 Merge branch 'master' of https://github.com/teamfisk/TacticalZ into MayaExporter 2016-01-11 13:09:09 +01:00
Jace dc7ed2e0ba Merge pull request #25 from teamfisk/Forward+
Forward+
2016-01-11 12:43:43 +01:00
Tleety f71bfca142 Fixed cullLights into CullLights 2016-01-11 10:23:22 +01:00
Tleety dbb44fb4e4 Changing cullLights to Culllights, need to do this in 2 commits since Git extensions is fucked. 2016-01-11 10:22:56 +01:00
antc13 1667358e0c We now export animations. 2016-01-08 16:47:04 +01:00
Tleety 6e6460a000 Commented out the bugged models 2016-01-08 16:15:18 +01:00
Tleety 9f871bbe7c Lights now use the absolute position instead of it's local position. 2016-01-08 14:31:44 +01:00
Tleety 2bd60be741 Merge remote-tracking branch 'origin/master' into Forward+
# Conflicts:
#	resources/Schema/Types/Entity.xsd
2016-01-08 14:14:43 +01:00
Tleety dab4ba2164 Pointlights are now using the pointlight component and the Light renderqueue to draw. 2016-01-08 14:12:09 +01:00
Tleety 25a99a04c5 Added Visable bool and a better description to Pointlight component. 2016-01-08 14:11:35 +01:00
William Moberg 13ade6d7f2 Merge pull request #24 from teamfisk/HealthSystem
Fixed so the PlayerDeath event doesn't get spammed while the player i…
2016-01-08 11:54:11 +01:00
verysecrethero 592776e783 Fixed so the PlayerDeath event doesn't get spammed while the player is dead. Also made sure that any remaining healthDeltas are cleared when dead. 2016-01-08 11:37:51 +01:00
verysecrethero ff44dccb33 Merge pull request #23 from teamfisk/OrderedSystemPipeline
Ordered system pipeline approved
2016-01-08 10:32:58 +01:00
William Moberg ef9ce7932a New small fix. 2016-01-07 17:40:47 +01:00
William Moberg beb0967c3b Merge branch 'master' into OrderedSystemPipeline
# Conflicts:
#	src/Game/Game.cpp
2016-01-07 16:49:20 +01:00
verysecrethero 0e0a361a38 HotFix: Updated the CMakeList.txt in src/Game so it has the HealthSystem.cpp. This is needed otherwise the solution cant find that file 2016-01-07 16:36:18 +01:00
William Moberg 6ebc4fc784 Merge pull request #22 from teamfisk/HealthSystem
Health system
2016-01-07 16:17:17 +01:00
William Moberg 7fb71f17b2 Destruct all systems properly in the pipeline. 2016-01-07 16:13:52 +01:00
verysecrethero e52c0c9633 Now using the easier/cleaner way of getting/setting the HealthProperties 2016-01-07 15:27:39 +01:00
verysecrethero 578ca13f79 Merge remote-tracking branch 'origin/master' into HealthSystem 2016-01-07 15:19:32 +01:00
William Moberg 4048ce6bd4 Small fix. 2016-01-07 15:18:35 +01:00
William Moberg c4642cc530 Merge branch 'master' into OrderedSystemPipeline
# Conflicts:
#	include/Engine/Core/SystemPipeline.h
2016-01-07 15:07:16 +01:00
William Moberg 32ebc061b4 Merge pull request #21 from teamfisk/AndersTest
Pull request approved.
2016-01-07 14:57:12 +01:00
verysecrethero a1ed79dfbf HealthSystemTest has been created. This runs a single test simple test with HealthEvents and HealthSystem. Also some minor changes 2016-01-07 14:53:31 +01:00
verysecrethero 638c236ceb HealthSystem tested and working. Also the 3 new PlayerEvents seems to work. TODO: a proper test in the testclass 2016-01-07 14:53:31 +01:00
verysecrethero f67f22c82d Added Healthrelated events and start of HealthSystem, also reverted the crash "fix" 2016-01-07 14:53:31 +01:00
verysecrethero f3ff433bf7 Merge remote-tracking branch 'origin/master' into AndersTest 2016-01-07 14:51:08 +01:00
verysecrethero 85ff86a2fe Revert "Exit Crash has been dealt with. There is no need to unsubscribe game since m_ContextRelays has already been destroyed at that point"
This reverts commit 0ae6c42df8.
2016-01-07 14:50:13 +01:00
William Moberg fa8775a72e Renamed vars and added some comments. 2016-01-07 10:28:18 +01:00
Jace 49884d7e60 Fix for crash when unsubscription during event processing (untested) 2016-01-06 13:47:02 +01:00
Tleety e7bb8954bf Merge remote-tracking branch 'origin/master' into Forward+
# Conflicts:
#	include/Engine/Rendering/Renderer.h
#	resources/Schema/Components.xsd
#	resources/Schema/Entities/Test.xml
#	src/Engine/Rendering/Renderer.cpp
2016-01-06 11:35:55 +01:00
Tleety e510f2b88c Forward plus render pass now removed from Renderer.cpp to it's own class. 2016-01-06 11:32:42 +01:00
Jace 34cbbb3eb1 Fixed exit crash(es) 2016-01-06 11:20:16 +01:00
verysecrethero 0ae6c42df8 Exit Crash has been dealt with. There is no need to unsubscribe game since m_ContextRelays has already been destroyed at that point 2016-01-05 15:22:16 +01:00
verysecrethero 3678cceb1c Merge remote-tracking branch 'origin/master' into AndersTest 2016-01-05 14:48:16 +01:00
FakeShemp eb5fca898f Fix small bug with push_back order
Commited directly from GitHub. Blame it if something explodes.
2015-12-21 12:55:25 +01:00
antc13 c9db46564f Spitting out files WIP 2015-12-18 16:21:07 +01:00
William Moberg de8461e257 SystemPipeline should update systems in order depending on input update priority in AddSystem. 2015-12-18 15:33:25 +01:00
Tleety eb69e03e82 Merge branch 'Forward+' of github.com:teamfisk/TacticalZ into Forward+ 2015-12-18 15:28:25 +01:00
Tleety d38f58165f Merge remote-tracking branch 'origin/master' into Forward+
# Conflicts:
#	include/Engine/Rendering/Renderer.h
#	src/Engine/Rendering/RenderState.cpp
#	src/Engine/Rendering/Renderer.cpp
2015-12-18 15:27:47 +01:00
Viktor Ljung c133223bac Merge pull request #19 from teamfisk/Networking
Networking
2015-12-18 14:54:11 +01:00
verysecrethero 2f6d4fcd0b Adjusted some of the corefiles back to the original in preparation for the Pull Request 2015-12-18 14:49:35 +01:00
Tleety 069a6756b9 LightcullingPass for forward+ is now separate from Renderer.cpp. 2015-12-18 14:31:16 +01:00
stiffly a550b6077e Re-enabled InputCommand debugging info in console 2015-12-18 14:25:55 +01:00
verysecrethero e0cc25dbac Fixed the OctTreeTestGameClass.cpp so it draws the OctTree nicely again 2015-12-18 14:22:57 +01:00
stiffly 00bc55370d Added error check in Collision.cpp 2015-12-18 14:19:28 +01:00
stiffly 330f08b926 Merge remote-tracking branch 'origin/master' into Networking
# Conflicts:
#	include/Game/PlayerSystem.h
#	src/Game/Game.cpp
#	src/Game/PlayerSystem.cpp
2015-12-18 14:18:53 +01:00
stiffly a0255f1b31 Now uses config file to determine if client or server should be started. 2015-12-18 13:34:21 +01:00
viktorljung ef4cbfece8 Added PointLight Component in XML files 2015-12-18 13:20:55 +01:00
Tleety ab6af30a28 Base classes for decoupled forward+ renderer and a fix where if you had to many lights in a tile(200-300+) the list would fill up before the end of frustums. 2015-12-18 12:02:02 +01:00
stiffly a858dab8b6 Network not longer threaded 2015-12-18 12:00:14 +01:00
verysecrethero b1ae96f737 Merge remote-tracking branch 'origin/master' into AndersTest
# Conflicts:
#	include/Game/Game.h
#	src/Engine/Core/OctTree.cpp
#	src/Game/Game.cpp
#	src/Tests/CMakeLists.txt
#	src/Tests/OctTreeTest.cpp
#	src/Tests/WorldTest.cpp
2015-12-18 11:57:21 +01:00
Jace 7dcd75fccc Merge pull request #18 from teamfisk/OctTree
CollisionSystem, TriggerSystem and Octree
2015-12-18 11:42:44 +01:00
verysecrethero 1e5e24a036 The tests seems to work under boost 1.59 but test explorer window is broken in 1.60. also changed ResourceManagerTest.cpp 2015-12-18 11:37:02 +01:00
viktorljung 3636ad45af Changed to correct branch 2015-12-18 11:29:11 +01:00
stiffly 6d649e4d35 Merge remote-tracking branch 'origin/Networking' into Networking
# Conflicts:
#	src/Engine/Network/Client.cpp
2015-12-18 11:26:48 +01:00
stiffly 5c1a93021b Client now reads address and port from config file. Default address is set to local host. 2015-12-18 11:22:13 +01:00
viktorljung 6cf7c12d34 Forward+ working 2015-12-18 11:09:54 +01:00
Jocke ad43cc44c3 Merge remote-tracking branch 'origin/Networking' into Networking 2015-12-18 11:03:21 +01:00
Jocke 002e1d8c5a Removed magic number from Packet constructor in Packet.cpp. 2015-12-18 10:52:46 +01:00
Jocke 30db0b10fd Removed NetworkDefinitions.h and moved #define MAXCONNECTIONS 8
#define INPUTSIZE 128 to Network.h.
2015-12-18 10:36:14 +01:00
Jocke 97f8be1915 Made Network.h's Start() and Update pure virtual and removed cpp.
Removed unnecessary code from NetworkDefinitions.h.
Renamed sizeOfPackage to sizeOfPacket in Packet.cpp.
2015-12-18 10:21:56 +01:00
Jocke 0eb51a0fea Merge remote-tracking branch 'origin/Networking' into Networking
# Conflicts:
#	include/Engine/Network/Packet.h
#	src/Engine/Network/Packet.cpp
2015-12-18 10:16:31 +01:00
Teejoon 509a989d3b Merge branch 'MayaExporter' of github.com:teamfisk/TacticalZ into MayaExporter
Conflicts:
	tools/MayaExporter/MayaExporter/Menu.cpp
2015-12-18 10:07:44 +01:00
Teejoon bc4cc5db54 Changed how we get skeletons. Made so that we could get the bind pose for each skeleton in the scene 2015-12-18 10:03:00 +01:00
verysecrethero 13f7fb2561 Stashed test fixes for boost 1.6 2015-12-18 10:01:05 +01:00
stiffly 0b714e593f Removed WinLeakCheck. Minor variable name changes. removed IsWASDKeyDown struct 2015-12-17 17:56:15 +01:00
viktorljung 4a817613e3 Forward+ semi working 2015-12-17 17:55:44 +01:00
verysecrethero 8beddca89a Merge remote-tracking branch 'origin/master' into AndersTest 2015-12-17 17:48:28 +01:00
William Moberg 5e0fe975f3 Small error handling check. 2015-12-17 17:48:00 +01:00
Jocke db5b6ad519 Added more error code to Packet class 2015-12-17 17:32:49 +01:00
William Moberg a26c8f2a24 Merge branch 'master' into OctTree 2015-12-17 17:30:44 +01:00
stiffly 076030a252 Fixes, mostly name changes 2015-12-17 17:28:43 +01:00
William Moberg 0f59b863ee Renamed IF_DEBUG_IS to DEBUG_IF, slightly different behavior and added some safety checking for auto creating AABBs from models. 2015-12-17 17:08:47 +01:00
Adam Byléhn d0927373a3 Merge pull request #20 from teamfisk/Editor
More usable editor
2015-12-17 16:51:59 +01:00
William Moberg 46ae2d39af Merge branch 'master' into OctTree
# Conflicts:
#	src/Game/Game.cpp
2015-12-17 16:44:01 +01:00
Jace e9128efd13 Translation widget planes 2015-12-17 15:30:43 +01:00
Jace 00f6056f7c Uniform scaling when dragging scaling widget origin 2015-12-17 15:30:43 +01:00
Jace a655f0bae5 Drag-and-drop asset picking and base work for showing component field tooltips in the editor 2015-12-17 15:30:43 +01:00
Jace cf6dde6c09 Boost dependency updated to version 1.60! 2015-12-17 15:30:43 +01:00
Jace c1b9404e52 Created a FileDropped event for when a file is dropped onto the client by the OS 2015-12-17 15:30:43 +01:00
Jace 8000654005 Model loading now fetches material opacity value properly 2015-12-17 15:28:05 +01:00
antc13 73708ec706 You can now add/remove animation clips. 2015-12-17 14:58:46 +01:00
stiffly 000adb198f Reset RenderQueueFactory.cpp to original state 2015-12-17 14:36:36 +01:00
stiffly 51a2da9cc0 Removed old Event that is not used 2015-12-17 14:28:17 +01:00
stiffly 0f0a1ceca7 No more fake packet loss 2015-12-17 14:22:31 +01:00
stiffly 50822d09fc Merge remote-tracking branch 'origin/master' into Networking
# Conflicts:
#	src/Game/Game.cpp
2015-12-17 14:10:02 +01:00
William Moberg 3e2ffdb85b Fixed comment on Trigger events. 2015-12-17 13:48:35 +01:00
William Moberg 5160a45b44 Made Ray into a class with checks so the direction will always be normalized. 2015-12-17 13:41:34 +01:00
William Moberg 03d5f0dd67 Added an macro IF_DEBUG_IS(x) that executes if run in debug mode, AABB has a check so max and min corners are set properly in debug mode. 2015-12-17 13:31:54 +01:00
stiffly 4bb4e29515 More cleaning code 2015-12-17 13:23:15 +01:00
stiffly a6a08f48bb Merge remote-tracking branch 'origin/Networking' into Networking
# Conflicts:
#	include/Engine/Network/Client.h
#	src/Engine/Network/Client.cpp
2015-12-17 11:24:34 +01:00
stiffly ba831f8a3c WIP Cleaning 2015-12-17 10:59:55 +01:00
Tobias Dahl 1a9b765d47 Merge pull request #17 from teamfisk/Editor
Kinda usable editor
2015-12-17 10:59:08 +01:00
Jace c8460e0a6c It's no use 2015-12-17 10:55:54 +01:00
stiffly 4c29e071af Cleaned code 2015-12-17 10:47:08 +01:00
Jace b87f559291 Updated default configs with editor stuff 2015-12-17 10:46:49 +01:00
Jace d4f5856304 Component attributes no longer get set on the wrong entity when switching selection while editing a field 2015-12-17 10:44:34 +01:00
viktorljung 6a3c14540d fixes 2015-12-17 10:38:13 +01:00
Jocke 2cb5441b1c Merge remote-tracking branch 'origin/Networking' into Networking
# Conflicts:
#	src/Engine/Network/Client.cpp
2015-12-17 09:47:15 +01:00
stiffly 97a0d97b0b Can now send transform components. 2015-12-16 17:56:44 +01:00
Jace a914a7f924 Switched to deps/master branch 2015-12-16 17:22:35 +01:00
Jace dbbbb7b4e7 Working rotations and translations relative to global and local space for children 2015-12-16 17:20:56 +01:00
William Moberg a23d69af9a Removed old relics from OctTree testing in OctTree. 2015-12-16 17:08:55 +01:00
Jocke 425f3ca3dd Fixed "trying to read more than package size" warnings. 2015-12-16 16:49:18 +01:00
William Moberg 6d1cbd928e Improved collision logic, still not perfect since it updates before PlayerSystem. 2015-12-16 16:34:27 +01:00
Jocke 6da5fd1263 Restructured code and added bool to stop client from spamming Snapshots to a server when
it wasn't connected to one.
2015-12-16 15:47:51 +01:00
Jocke 6eebce05af Merge remote-tracking branch 'origin/Networking' into Networking 2015-12-16 14:58:36 +01:00
Jocke 58a9d38e26 Added a class that client and server inherits from.
Class and server now share the same pointer i game.
You are now able to start a client and a server on the same computer.
2015-12-16 14:56:53 +01:00
stiffly 50ccf96268 Movement code not buggy anymore. Also changed package to not allocate more data than needed. 2015-12-16 13:52:16 +01:00
viktorljung 5602b32507 Forward+ Fixes 2015-12-16 13:36:38 +01:00
William Moberg cf0ff9bfe5 Simple quickly made CollisionSystem. 2015-12-16 12:23:08 +01:00
William Moberg d10df6ae09 TriggerSystem implemented and working. 2015-12-16 12:22:15 +01:00
William Moberg 99b76d7ae1 Fixed returning address to temporary in functions. AABB also constructible from glm::vec4s. 2015-12-16 12:19:43 +01:00
Jace 661532e355 Slightly more usable entity tree 2015-12-16 12:05:55 +01:00
Jace bd6adcc157 Added SetParent to World 2015-12-16 12:05:37 +01:00
antc13 67017fcaf4 Stepping through the timeline. 2015-12-16 11:33:42 +01:00
stiffly a2d55feed1 Merge remote-tracking branch 'origin/Networking' into Networking
# Conflicts:
#	src/Engine/Network/Client.cpp
#	src/Engine/Network/Server.cpp
2015-12-16 11:12:15 +01:00
Jocke e74b2b6874 Made it easier for non network members to create packages and extract information from them by addin PopFrontString() and PopFrontPrimitive<type>(). 2015-12-16 10:40:40 +01:00
Jace 322aedaf72 Basic transformation widgets 2015-12-16 09:47:38 +01:00
stiffly 3f602c9d63 Test code 2015-12-15 17:55:08 +01:00
stiffly 082b3fd3df Removed old input events from client 2015-12-15 17:22:46 +01:00
William Moberg 04a01104b5 Merge branch 'master' into OctTree
# Conflicts:
#	src/Engine/CMakeLists.txt
#	src/Game/Game.cpp
2015-12-15 17:11:11 +01:00
stiffly 9b348a7d97 Updated movement code once again. 2015-12-15 16:50:59 +01:00
stiffly 889e0bb3d3 Cleaned up PlayerSystem. Sets velocity to 0 every frame. 2015-12-15 16:35:09 +01:00
stiffly 1669649186 Fixed bug with entityID. Also trying to fix movement WIP. 2015-12-15 16:24:09 +01:00
antc13 498afb3a5e Merge branch 'MayaExporter' of https://github.com/teamfisk/TacticalZ into MayaExporter
# Conflicts:
#	tools/MayaExporter/MayaExporter/Menu.h
2015-12-15 15:41:18 +01:00
Tleety 1431bd1a11 DebugChanges 2015-12-15 15:39:23 +01:00
William Moberg ed82a0939a Merge branch 'OctTree' of github.com:teamfisk/TacticalZ into OctTree 2015-12-15 15:37:14 +01:00
William Moberg e2417be8c7 Very simple CollisionSystem made, 'Z','Y' to toggle on/off. 2015-12-15 15:36:28 +01:00
stiffly 472a8db81a Various bug fixes. 2015-12-15 15:32:31 +01:00
Tleety 1e370bac13 ForwardPlus base debug commit. 2015-12-15 15:28:37 +01:00
antc13 4e535c1102 File Writer WIP. Rework soon™ 2015-12-15 15:24:46 +01:00
Jocke e940c1d604 WIP 2015-12-15 14:55:56 +01:00
stiffly 478c692315 Refactoring. Client and server has Update Loop that runs before any game logic each frame. 2015-12-15 14:53:56 +01:00
William Moberg 170610bcb1 Added a TriggerSystem, seems to work as intended. 2015-12-15 14:49:52 +01:00
verysecrethero 454ed0032b Refactored some RayVsModel tests 2015-12-15 14:01:49 +01:00
verysecrethero 1910ab705b AndersTest misc small mergefixes 2015-12-15 13:48:14 +01:00
stiffly 0a8a9e5099 Merge remote-tracking branch 'origin/master' into Networking
# Conflicts:
#	src/Engine/Rendering/RenderState.cpp
#	src/Game/Game.cpp
2015-12-15 11:50:01 +01:00
FakeShemp 1689370356 Export the skeletons
Not really tested though
2015-12-15 11:49:59 +01:00
verysecrethero f9508657f5 Merge remote-tracking branch 'origin/master' into AndersTest
# Conflicts:
#	include/Engine/Core/InputController.h
#	include/Game/Game.h
2015-12-15 11:32:47 +01:00
stiffly b698a0d36f WIP
Adding models now crashes. Threading
Added a create player event that currently is not used.
2015-12-15 11:21:46 +01:00
verysecrethero 1229a99af4 Merge branch 'OctTree' of github.com:teamfisk/TacticalZ into OctTree 2015-12-15 11:07:51 +01:00
verysecrethero 8e431c8edd RayVsModel && RayVsAABB tests added and working. Also adjusted RayVsModel,RayVsAABB with deltas when values are very close to each other (floatingprecision problems) 2015-12-15 11:07:09 +01:00
Jace 51dd627ae3 Added Fonts to deploy.bat 2015-12-15 09:49:43 +01:00
Jace c296c4eb3b Fixed picking pass... again... 2015-12-15 09:49:38 +01:00
Jace 422e6f5264 Created a RenderState for ImGuiRenderPass 2015-12-14 20:26:04 +01:00
Viktor Ljung 9cee8b5478 Merge pull request #16 from teamfisk/Editor
Added BlendEquation and BlendFunc to RenderState ...
2015-12-14 20:25:10 +01:00
Jace 522679b14c Added BlendEquation and BlendFunc to RenderState, and cleaned it up A LOT 2015-12-14 20:23:29 +01:00
Viktor Ljung 25683e8a8a Merge pull request #15 from teamfisk/Editor
Editor
2015-12-14 19:05:27 +01:00
verysecrethero 948f6d5de7 RayVsModel & RayVsAABB comparison continued 2015-12-14 17:53:11 +01:00
William Moberg ae7d4b9097 Put Collision folder in CMakeLists.txt and altered paths. 2015-12-14 17:35:39 +01:00
Tleety 7c714d1f98 Changed some error handling in the RenderState class. 2015-12-14 17:35:01 +01:00
William Moberg e6fa9df3a5 Merge branch 'OctTree' of github.com:teamfisk/TacticalZ into OctTree 2015-12-14 17:08:51 +01:00
William Moberg 59095c2ce5 Started on CollisionSystem and TriggerSystem. Moved collision code to Collision folder. 2015-12-14 17:08:00 +01:00
stiffly 3f77da4a07 Merge remote-tracking branch 'origin/master' into Networking
# Conflicts:
#	include/Game/Game.h
#	resources/DefaultConfig.ini
#	src/Game/Game.cpp
2015-12-14 17:07:12 +01:00
verysecrethero 7f8e78c8cd RayVsModel tests in progress 2015-12-14 17:04:35 +01:00
stiffly bac0a1de26 Removed annoying cube 2015-12-14 16:55:23 +01:00
stiffly bf82bbb5d5 Merge remote-tracking branch 'origin/Networking' into Networking 2015-12-14 16:50:51 +01:00
Jocke e52052b431 IdentifyPacketLoss() crashed when multiple users connected which
also crashed the server. The function is not needed for now as the server logic is not
implemented.
2015-12-14 16:50:16 +01:00
stiffly 8d9ff2b6dc Merge remote-tracking branch 'origin/Networking' into Networking
# Conflicts:
#	src/Engine/Network/Client.cpp
2015-12-14 16:41:59 +01:00
Jocke 63db236dfa Fixed bug which made the player not able to move diagonally.
Fixed a bug were m_PlayerID was not set for the client when connecting.
2015-12-14 16:35:43 +01:00
Jace cddd9026fb Toggle editor with "ToggleEditor" command. Enable editor with "Debug.EnableEditor" config variable. 2015-12-14 16:12:52 +01:00
Jace ea239b19bd Fixed component type resolution order to prioritize custom types before native ones, since namespace information doesn't exist at that stage. 2015-12-14 16:12:20 +01:00
Jace f8d927cd91 Don't render invisible model components 2015-12-14 16:11:37 +01:00
Jace 798c73132e Fixed ScreenCoords::ToPixelData stack corruption 2015-12-14 16:11:08 +01:00
Jace fb2cd0c6ae Fixed float angle wrapping 2015-12-14 15:20:55 +01:00
Jace bc6a211276 Removed RenderState log spam 2015-12-14 14:54:19 +01:00
Jace 7719274a37 Correct asset reference for fonts 2015-12-14 14:54:03 +01:00
Jace 797036c204 Fixed picking event 2015-12-14 14:24:11 +01:00
Jace 3a9577c9fb fixup! Enabled rendering "transparency" 2015-12-14 14:08:37 +01:00
Jace 545869e342 Added scene graph UI to Editor 2015-12-14 13:58:28 +01:00
Jace 07c4744436 Added World DeleteEntity, HasComponent and GetEntityChildren 2015-12-14 13:58:27 +01:00
Jace b8620eac26 Made debug camera detect UI focus properly 2015-12-14 13:58:27 +01:00
Jace 7bc492134d Enabled rendering "transparency" 2015-12-14 13:58:24 +01:00
Jace 7c1182c28f Fixed absolute positions once and for all (maybe?) 2015-12-14 13:57:56 +01:00
Jace 2f3843e595 Editor version 1 2015-12-14 13:57:55 +01:00
Jace 5f3c234819 Added DeleteComponent function to world 2015-12-14 13:57:54 +01:00
Jace 9a119f38bb Added events processing to SystemPipeline 2015-12-14 13:57:54 +01:00
Jace 524af211e0 Made resource loading fail gracefully when a resource can't be loaded. Resources should now throw exceptions in their constuctor if the resource can't be loaded. This will result in ResourceManager::Load returning null. 2015-12-14 13:57:53 +01:00
Jace 91ace0d2a0 Fixed bug in ComponentPool::Delete. Wasn't taking EntityID into account when freeing memory. 2015-12-14 13:57:53 +01:00
Jace 2018ba27ae Added KnowsEntity function to ComponentPool to query whether an entity has a component attached 2015-12-14 13:57:52 +01:00
Jace b66cf47ff0 Revert "Clearing raw input events from event broker to encourage use of input commands instead"
This reverts commit 2e7e8d3546.
2015-12-14 13:57:52 +01:00
Jace e5084e13ec Added EditorSystem 2015-12-14 13:57:51 +01:00
Jace 8a6030bf57 Added support for "Impure" systems, which only update once per frame and contain their own logic for manipulating the world, instead of relying on a single list of components. 2015-12-14 13:57:51 +01:00
Jace 2e321e15a5 Cleaned up ImGuiRenderPass 2015-12-14 13:57:50 +01:00
Jace c81a054601 Subscribed ImGui to MouseScroll event 2015-12-14 13:57:50 +01:00
Jace af14d60493 Added MouseScroll event to input manager 2015-12-14 13:57:49 +01:00
Jace 0465fdb16d Added ImGui for compilation 2015-12-14 13:57:49 +01:00
Jace 0c6ac1e060 Added ImGui to README 2015-12-14 13:57:48 +01:00
Jace 7db1feac17 Added basic ImGui implementation 2015-12-14 13:57:45 +01:00
Jace 653b4689b5 Added KeyboardChar event for keyboard text input 2015-12-14 13:56:24 +01:00
Adam Byléhn 6723e71fee Merge pull request #14 from teamfisk/Input
Input
2015-12-14 13:55:11 +01:00
Jace d16cbe84f0 Merge remote-tracking branch 'origin/master' into Input
# Conflicts:
#	src/Engine/Rendering/Renderer.cpp
2015-12-14 13:40:22 +01:00
Jace 95ce024bb6 Merge pull request #13 from teamfisk/RendererDecoupling
Renderer decoupling
2015-12-14 13:39:20 +01:00
Jace a7ed455766 Merge branch 'master' into Input 2015-12-14 13:19:38 +01:00
Tleety d182e6c453 Merge remote-tracking branch 'origin/master' into RendererDecoupling
# Conflicts:
#	src/Game/Game.cpp
2015-12-14 13:16:56 +01:00
antc13 60b3ce89b2 Skeleton/Joints WIP 2015-12-14 12:59:54 +01:00
verysecrethero 5fce7490a9 MergeFix OctTree williambranch and andersbranch 2015-12-14 11:57:18 +01:00
Jace e76a6b74a3 Merge branch 'master' of github.com:teamfisk/TacticalZ
# Conflicts:
#	src/Game/Game.cpp
2015-12-14 11:41:59 +01:00
Jace e82911cb8b Renderer FOV setting in Config.ini 2015-12-14 11:39:13 +01:00
verysecrethero 8abef7024d Merge branch 'OctTree' of github.com:teamfisk/TacticalZ into OctTree
# Conflicts:
#	src/Tests/OctTreeTest.cpp
2015-12-14 11:14:09 +01:00
verysecrethero bf08ffe392 Added InputManagerTest 2015-12-14 11:02:23 +01:00
verysecrethero 5f5cab1171 Added Tests for ResourceManager 2015-12-14 10:55:49 +01:00
William Moberg 8d87841691 Merge branch 'master' into OctTree 2015-12-14 10:51:23 +01:00
William Moberg 11e37ca898 Added functions to test ray vs triangle- and model-intersections. 2015-12-14 10:42:45 +01:00
Tleety d406059c79 Small bugfix. 2015-12-11 17:00:06 +01:00
Tleety 59b261534a Cleaned some comments and random annoyances in Renderer 2015-12-11 16:57:02 +01:00
Tleety 45b87ed6b1 ShaderProgram is now a Resource.
All shaderprograms are now pointers and loaded with Resourcemanager.
2015-12-11 16:53:46 +01:00
William Moberg 55aad493ff Fixed warnings in OctTree. Cleaned unit tests. 2015-12-11 16:45:38 +01:00
William Moberg 9a7d77f29d Removed notes in OldOctTree. 2015-12-11 16:44:49 +01:00
stiffly 36ae451ea6 Indentation 2015-12-11 16:22:14 +01:00
verysecrethero b3bb0e543f Added EventBroker Test from the other project 2015-12-11 16:17:23 +01:00
Tleety 53d5736420 Fixed a bugg with RenderState.
Renderstate now also handles the Frambuffer binding.
2015-12-11 16:07:12 +01:00
William Moberg 81034420a9 Put back old version of OctTree for testing, made unit tests.
Tests shows the old version checks for collisions etc. faster, new version adds objects into tree faster, and doesn't give duplicated results.
2015-12-11 16:04:30 +01:00
stiffly 15442c8c75 Merge branch 'PlayerSystem' into Networking
# Conflicts:
#	src/Game/Game.cpp
2015-12-11 15:45:27 +01:00
Tleety 433331e752 DrawPass now moved to it's own class to make renderer cleaner. 2015-12-11 14:22:54 +01:00
Tleety 2366cd3520 Merge remote-tracking branch 'origin/master' into RendererDecoupling 2015-12-11 13:52:41 +01:00
Tleety 725a8896ce PickingPass now publishes an event that others can listen to to get pickingdata. 2015-12-11 13:51:08 +01:00
verysecrethero 350038057d Misc OctTreeTest changes 2015-12-11 13:51:07 +01:00
Jocke 23c3f0709b Merge branch 'Networking' of github.com:teamfisk/TacticalZ into Networking 2015-12-11 11:59:22 +01:00
Jocke 01d7388f91 Reactored the package loss logic.
Server cannot handle multiple clients yet.
Fixed WorldTest code by adding astrix.
2015-12-11 11:55:23 +01:00
Tleety 8c563a2d76 Merge remote-tracking branch 'origin/Picking' into RendererDecoupling
# Conflicts:
#	include/Engine/Rendering/Renderer.h
#	src/Engine/Rendering/Renderer.cpp
2015-12-11 11:21:58 +01:00
Tleety 91edab34bc PickingPass now sets state and clear it when done.
PickingState now it's own class so renderer is a bit cleaner.
2015-12-11 11:18:30 +01:00
verysecrethero 1ceea91f4a Merge branch 'OctTree' of github.com:teamfisk/TacticalZ into OctTree
# Conflicts:
#	include/Engine/Core/OctTree.h
#	src/Engine/Core/OctTree.cpp
2015-12-10 18:02:03 +01:00
William Moberg 4195baa5dc ContainedObject in OctTree made private. 2015-12-10 17:57:09 +01:00
William Moberg 37f9ab2322 Quick fix for unit test compilation. 2015-12-10 17:53:33 +01:00
verysecrethero d8b1f4e514 ConfigFileTest attempt to explore the memleaks further 2015-12-10 17:46:17 +01:00
stiffly 6a3335315a Merge branch 'master' into Networking 2015-12-10 17:26:01 +01:00
verysecrethero c651face4c ConfigFile now has tests covering the whole class 2015-12-10 17:20:47 +01:00
stiffly 641a43b2ec Merge remote-tracking branch 'origin/Networking' into Networking
# Conflicts:
#	src/Engine/Network/Client.cpp
2015-12-10 17:16:22 +01:00
stiffly 58952725e9 Added class Package to help refactor the code. The code got easier to read. 2015-12-10 17:07:18 +01:00
verysecrethero de044dabd3 Added ConfigFileTests! 2015-12-10 16:55:28 +01:00
William Moberg ce7b26ccac Merge branch 'master' into OctTree
# Conflicts:
#	include/Game/Game.h
#	include/Game/HardcodedTestWorld.h
#	src/Game/Game.cpp
2015-12-10 16:37:55 +01:00
Tleety cefc4e5257 PickingPassState done. 2015-12-10 16:06:25 +01:00
William Moberg 0d8f7acb7e OctTree doesn't check the same object multiple times if it exists in multiple places in the tree. 2015-12-10 16:04:55 +01:00
Tleety 37cf42527b RenderState class structure made. 2015-12-10 16:03:48 +01:00
Jocke 99543a300d Merge remote-tracking branch 'origin/Networking' into Networking
# Conflicts:
#	include/Engine/Network/NetworkDefinitions.h
#	include/Game/Game.h
#	src/Engine/Network/Client.cpp
#	src/Game/Game.cpp
2015-12-10 14:40:06 +01:00
Jocke f377d9ba70 Fixed client movement. 2015-12-10 14:14:36 +01:00
stiffly d22e59f28f Merge remote-tracking branch 'origin/master' into Networking
NOTE (in config file):
[Debug]
LoadMap=Schema/Entities/Test.xml

# Conflicts:
#	include/Game/Game.h
#	src/Game/Game.cpp
2015-12-10 13:53:18 +01:00
verysecrethero 7804d42fea OctTree debug temporarily disabled because of the new master layout 2015-12-10 13:42:39 +01:00
stiffly 9a8f5293af Can now Identify Packet Loss. Enumerated messages that loops around 0-1000. 2015-12-10 12:55:28 +01:00
verysecrethero e535f629bc Merge branch 'master' into PlayerTakeCapturePoint
# Conflicts:
#	include/Game/Game.h
#	include/Game/HardcodedTestWorld.h
#	src/Game/Game.cpp
2015-12-10 11:50:29 +01:00
antc13 a22d086e60 Tested some of the Material Code. Seems to work. The project should now be following the code standard properly (hopefully). 2015-12-10 11:18:34 +01:00
verysecrethero c60e968836 Removed a boxclear in the end of the test2 method 2015-12-10 11:03:40 +01:00
Tleety 9d3313e3ed Calculate frustrum removed from code untill Nvidia isn't shit. 2015-12-10 10:46:27 +01:00
verysecrethero bc8a922b77 Merging octTreeTests a bit 2015-12-09 17:57:32 +01:00
Jocke 663aca2641 Moved client and server from header.
Fixed so user are able to start a server and client on the same computer.
Starting 2 servers on the same computer will probably still crash the newest server (Don't do it).
2015-12-09 17:50:30 +01:00
stiffly 4de613814b WIP Packet loss identification. Put packetID in message 2015-12-09 17:43:36 +01:00
Tleety de6e74c0b1 Forward+ Debugging commit, dont try it. 2015-12-09 17:36:03 +01:00
William Moberg e580540143 Made some optimizations in OctTree and added a unit test for BoxesInSameRegion. 2015-12-09 17:16:11 +01:00
Tleety 393a774140 Framework for Forward+ renderer, Buggy. 2015-12-09 14:50:39 +01:00
Jocke 0807a7d0ae Fixed the bug where starting a server made the program crash on closing.
Fixed some memory leaks in Client.cpp.
2015-12-09 14:43:43 +01:00
Jocke ba150a264c Fixed bug that cause the program to crash when closing if a server had been started.
Removed memory leaks in Client.cpp.
2015-12-09 14:41:26 +01:00
verysecrethero b650eb95df Merge branch 'OctTree' of github.com:teamfisk/TacticalZ into OctTree 2015-12-09 13:57:22 +01:00
verysecrethero 8949db5456 Little more work with OctTreeTest 2015-12-09 13:56:59 +01:00
William Moberg 14bcb7ea0d Added Update call in Game to test OctTree by using collision. 2015-12-09 13:52:17 +01:00
verysecrethero 519178dfba Merge branch 'OctTree' of github.com:teamfisk/TacticalZ into OctTree
# Conflicts:
#	src/Engine/Core/OctTree.cpp
2015-12-09 13:37:27 +01:00
Jocke 0e6353dd79 Fixed bug where closing glwindow as client crashed.
Server bug is still present.
2015-12-09 13:37:02 +01:00
verysecrethero ed5cd392ab Further work in testing OctTree 2015-12-09 13:29:15 +01:00
William Moberg bad42fae1c OctTree differentiates between static/dynamic objects now. Added a general BoxesInSameRegion method. 2015-12-09 13:27:00 +01:00
stiffly 247ff09743 Smoother movement over network. Some refactoring on client side. Now uses EKeyUp to determine if a key is pressed. 2015-12-09 13:02:39 +01:00
FakeShemp 74c1beed20 gitignore 2015-12-09 12:03:01 +01:00
FakeShemp c8cb0ee939 Grab all materials 2015-12-09 11:58:49 +01:00
stiffly 2a35c3055e Renamed NetworkDefines.h --> NetworkDefinitions.h 2015-12-09 11:08:57 +01:00
stiffly ce41421dbb Added a "StartNetwork" bool to DefaultConfig. 2015-12-09 10:37:40 +01:00
verysecrethero 1d0810db10 OctTree is now drawn perfectly 2015-12-09 10:24:06 +01:00
verysecrethero c85bb2eef7 Merge branch 'OctTree' of github.com:teamfisk/TacticalZ into OctTree 2015-12-09 10:08:26 +01:00
verysecrethero 75402b0f93 Working on OctTree tests 2015-12-09 10:08:08 +01:00
stiffly f83e217638 Bugfix. if-statement was incorrect 2015-12-08 18:35:30 +01:00
stiffly 58db7b755a Random bugfixes and cleanup. 2015-12-08 18:24:08 +01:00
stiffly a8c0a1f294 Merge branch 'Networking' of github.com:teamfisk/TacticalZ into Networking
# Conflicts:
#	include/Engine/Network/Client.h
#	src/Engine/Network/Client.cpp
2015-12-08 18:07:18 +01:00
stiffly 9f54a08536 Implemented new version of snapshot for 3D world. Also some cleanup. 2015-12-08 17:57:01 +01:00
Jocke 24dada149f Cleaned up code in Client.h and Client.cpp.
Moved ping code into Ping() function.
2015-12-08 17:18:03 +01:00
William Moberg a7fb77d998 OctTree can check if a box collides with a box in the OctTree. 2015-12-08 17:12:58 +01:00
William Moberg 32d2aa6a93 AABB can also be created with center position and its size. 2015-12-08 17:01:50 +01:00
Jocke d1880754f5 Merge branch 'Networking' of github.com:teamfisk/TacticalZ into Networking 2015-12-08 16:42:32 +01:00
stiffly 27b44d2511 Input events for Client done. Instead of windows getAsyncKeyState(); 2015-12-08 16:41:48 +01:00
Jocke 94adaf8ae3 Added support for multiplayer.
Reactored code, clumped together variables in PlayerDefinition.h.
Integrated server with entity system.
2015-12-08 16:41:22 +01:00
stiffly 6dc5112c26 Merge branch 'Networking' of github.com:teamfisk/TacticalZ into Networking
# Conflicts:
#	include/Engine/Network/Client.h
#	src/Game/Game.cpp
2015-12-08 16:15:50 +01:00
stiffly e92119c99e WIP trying to get Eventsystem to work in client. 2015-12-08 16:13:53 +01:00
Jocke c48c9e1f86 Added leak check when using windows (WinLeakCheck.h).
Added server to project.
A server can now be started in the project.
2015-12-08 13:54:18 +01:00
verysecrethero 7ac2aaef15 Merge branch 'OctTree' of github.com:teamfisk/TacticalZ into OctTree
# Conflicts:
#	src/Engine/Core/OctTree.cpp
2015-12-08 11:16:34 +01:00
verysecrethero 06f56d13d1 added some octTreeTest tests and a few comments in OctTree 2015-12-08 11:14:01 +01:00
Jocke 8f55e90d2d Merge branch 'Networking' of github.com:teamfisk/TacticalZ into Networking
# Conflicts:
#	include/Game/Game.h
2015-12-08 11:11:12 +01:00
Jocke b5a010a517 Network now runs on it's own thread.
Network now sends Disconnect message when game is terminated.
2015-12-08 11:02:40 +01:00
William Moberg b87e543420 Merge branch 'master' into OctTree 2015-12-08 10:47:27 +01:00
William Moberg fa3816e55d Fixed flawed unit test. 2015-12-08 10:44:12 +01:00
stiffly ee41721a75 Merge remote-tracking branch 'origin/master' into Networking 2015-12-08 10:41:04 +01:00
William Moberg 648ba502bb Added small test for OctTree. 2015-12-07 17:27:57 +01:00
stiffly 2c993e82d6 Added the old prototype logic to Client.h. Can now communicate with a external server(on prototype). 2015-12-07 16:55:12 +01:00
stiffly cbbb7deaea Copy pasta error. Corrected #ifndef 2015-12-07 16:53:33 +01:00
stiffly de5bdef58c Rectangle definition conflicted with a definition included by <boost/asio.hpp>. 2015-12-07 16:52:42 +01:00
William Moberg 000ad6358f Merge branch 'OctTree' of github.com:teamfisk/TacticalZ into OctTree 2015-12-07 16:26:49 +01:00
William Moberg 04a8eeebe8 Added test get methods and some comments. 2015-12-07 16:25:01 +01:00
stiffly d8d63f804a Added utility headers for network interface. 2015-12-07 16:11:27 +01:00
William Moberg 955c9ce534 Removed superfluous function declaration. 2015-12-07 16:00:34 +01:00
William Moberg e8d23f3b3f Added AABBVsAABB function. 2015-12-07 15:59:41 +01:00
verysecrethero 89aa8c44b0 Merge branch 'OctTree' of github.com:teamfisk/TacticalZ into OctTree 2015-12-07 10:03:55 +01:00
verysecrethero f0e407bec2 Started on OctTreeTest (Merging with OctTree) 2015-12-07 10:03:36 +01:00
William Moberg 8e21b1fe35 Added ray collision detection in leaf nodes. Fixed possible bug in OctTree::AddBox 2015-12-03 19:25:40 +01:00
verysecrethero 17133b316a Merge branch 'OctTree' of github.com:teamfisk/TacticalZ into OctTree 2015-12-03 17:31:07 +01:00
verysecrethero 28a290600b BOOST MEM LEAK VS VISUAL STUDIO MEM LEAKS COMMENTED TESTS 2015-12-03 17:30:12 +01:00
William Moberg af5b3a9302 Fixed wrong paths and added an outDistance to RayVsAABB. 2015-12-03 17:24:53 +01:00
William Moberg abb61d2cd6 Merge branch 'OctTree' of github.com:teamfisk/TacticalZ into OctTree
# Conflicts:
#	include/Engine/Core/Collision.h
#	src/Engine/Core/Collision.cpp
2015-12-03 17:11:35 +01:00
William Moberg 2f13f5da7a Relocated AABB and Ray in Collision.h to their own files. Started implementation on OctTree. 2015-12-03 17:03:27 +01:00
verysecrethero 464650c370 more tests added 2015-12-02 16:31:39 +01:00
verysecrethero af294f78b7 czdxvxdfvxvxvc 2015-12-02 16:26:30 +01:00
verysecrethero c840183467 Merge remote-tracking branch 'origin/master' into OctTree 2015-12-02 15:43:51 +01:00
verysecrethero 1f99d46a8d Merge branch 'master' into OctTree 2015-12-02 15:15:05 +01:00
verysecrethero fd99562c7a yrryr567yry567 2015-12-02 15:03:55 +01:00
William Moberg c698149bdd Added Ray, AABB structs, and basic rayVsAABB test function. 2015-12-02 14:24:21 +01:00
William Moberg fa0ace8c68 Added empty OctTree files. 2015-12-02 11:32:56 +01:00
William Moberg 1d19c6901e Added collision files. 2015-12-02 11:18:52 +01:00
154 changed files with 9212 additions and 748 deletions
+8
View File
@@ -4,3 +4,11 @@ bin/
lib/
# Because apparently nobody has any self control
*.orig
*.suo
*.sdf
tools/MayaExporter/MayaExporter/x64/Debug/
tools/MayaExporter/x64/Debug/
tools/MayaExporter/MayaExporter/Debug/
tools/MayaExporter/MayaExporter/GeneratedFiles/
+2 -1
View File
@@ -10,10 +10,11 @@ Libraries bundled along with binaries for Windows (MSVC14), available as a submo
| **[zlib](http://www.zlib.net)** | 1.28 | [zlib License](http://www.zlib.net/zlib_license.html) |
| **[libpng](http://www.libpng.org/pub/png/libpng.html)** | 1.6.19 | [libpng License](http://www.libpng.org/pub/png/src/libpng-LICENSE.txt) |
| **[Xerces-C++](https://xerces.apache.org/xerces-c)** | 3.1.2 | [Apache License Version 2.0](https://www.apache.org/licenses/LICENSE-2.0) |
| **[ImGui](https://github.com/ocornut/imgui)** | 2015-12-12 | [MIT License](https://github.com/ocornut/imgui/blob/de3a154f3801de22c8e0bd2aeabf663a70c05972/LICENSE) |
#### External libraries
Libraries that are too big to be bundled with the project.
| Project | Version | License | Root folder environment variable (Windows) |
| ---------------------------------------------------------- | ----------- | --------------------------------------------------------------------------- | ------------------------------------------ |
| **[Boost](http://www.boost.org)** | 1.59.0+ | [Boost Software License, Version 1.0](http://www.boost.org/LICENSE_1_0.txt) | BOOST_ROOT |
| **[Boost](http://www.boost.org)** | 1.60.0+ | [Boost Software License, Version 1.0](http://www.boost.org/LICENSE_1_0.txt) | BOOST_ROOT |
+1 -1
Submodule assets updated: b37468222e...c8e631f449
+1 -1
Submodule deps updated: 1b478d3159...1ae6ba5b12
+59
View File
@@ -0,0 +1,59 @@
#ifndef Collision_h__
#define Collision_h__
//NOTE: Collision.h needs to be #included before <GLFW/glfw3.h>,
//because Collision #includes "RawModel.h", which has "Texture.h", which has "OpenGL.h" which must be #included first
//or you will get "fatal error C1189: #error: gl.h included before glew.h"
#include <vector>
#include "Core/Ray.h"
#include "Core/AABB.h"
#include "Engine/Rendering/RawModel.h"
#include "Core/Entity.h"
class World;
struct ComponentWrapper;
namespace Collision
{
//Return true if the ray hits the box.
bool RayAABBIntr(const Ray& ray, const AABB& box);
bool RayVsAABB(const Ray& ray, const AABB& box);
//Return true if the ray hits the box, also outputs distance from ray origin to intersection point in [outDistance].
bool RayVsAABB(const Ray& ray, const AABB& box, float& outDistance);
//Return true if the ray hits any of the triangles in the model. Stops checking when a hit is detected.
bool RayVsModel(const Ray& ray,
const std::vector<RawModel::Vertex>& modelVertices,
const std::vector<unsigned int>& modelIndices);
//Return true if the ray hits any of the triangles in the model.
//Also returns the position of the intersection point. Will loop through all the whole model indices.
bool RayVsModel(const Ray& ray,
const std::vector<RawModel::Vertex>& modelVertices,
const std::vector<unsigned int>& modelIndices,
glm::vec3& outHitPosition);
//Return true if the ray hits any of the triangles in the model.
//Also returns the distance from the ray origin to the closest
//intersection point, and the barycentric u,v-coordinates. Will loop through all the whole model indices.
bool RayVsModel(const Ray& ray,
const std::vector<RawModel::Vertex>& modelVertices,
const std::vector<unsigned int>& modelIndices,
float& outDistance,
float& outUCoord,
float& outVCoord);
//Return true if the boxes are intersecting.
bool AABBVsAABB(const AABB& a, const AABB& b);
//Return true if the boxes are intersecting.
//Also outputs the minimum translation that box [a] would need in order to resolve collision.
bool AABBVsAABB(const AABB& a, const AABB& b, glm::vec3& minimumTranslation);
bool IsSameBoxProbably(const AABB& first, const AABB& second, const float epsilon = 0.0001f);
//Returns true if the entity has a boundingbox. Outputs the aabb in [outBox].
bool GetEntityBox(World* world, EntityID entity, AABB& outBox, bool forceBoxFromModel = false);
bool GetEntityBox(World* world, ComponentWrapper& AABBComponent, AABB& outBox);
}
#endif
@@ -0,0 +1,31 @@
#ifndef CollisionSystem_h__
#define CollisionSystem_h__
#include <GLFW/glfw3.h>
#include <glm/common.hpp>
#include "Common.h"
#include "Core/System.h"
#include "Core/EventBroker.h"
#include "Core/EKeyUp.h"
class CollisionSystem : public PureSystem
{
public:
CollisionSystem(EventBroker* eventBroker)
: PureSystem(eventBroker, "AABB")
, zPress(false)
{
//TODO: Debug stuff, remove later.
EVENT_SUBSCRIBE_MEMBER(m_EKeyUp, &CollisionSystem::OnKeyUp);
}
virtual void UpdateComponent(World* world, ComponentWrapper& cAABB, double dt) override;
private:
bool zPress;
EventRelay<CollisionSystem, Events::KeyUp> m_EKeyUp;
bool OnKeyUp(const Events::KeyUp &event);
};
#endif
+39
View File
@@ -0,0 +1,39 @@
#ifndef Events_TriggerEnter_h__
#define Events_TriggerEnter_h__
#include "../Core/EventBroker.h"
#include "../Core/Entity.h"
namespace Events
{
/** Thrown once, when an entity is only touching a trigger. */
struct TriggerTouch : Event
{
/** The id of the entity that touches the trigger. */
EntityID Entity;
/** The id of the trigger entity. */
EntityID Trigger;
};
/** Thrown once, when an entity has completely left a trigger. */
struct TriggerLeave : Event
{
/** The id of the entity that left the trigger. */
EntityID Entity;
/** The id of the trigger entity. */
EntityID Trigger;
};
/** Thrown once, when an entity is completely contained inside a trigger. */
struct TriggerEnter : Event
{
/** The id of the entity that entered the trigger. */
EntityID Entity;
/** The id of the trigger entity. */
EntityID Trigger;
};
}
#endif
+38
View File
@@ -0,0 +1,38 @@
#ifndef TriggerSystem_h__
#define TriggerSystem_h__
#include <glm/common.hpp>
#include <unordered_set>
#include "Core/System.h"
#include "Core/EventBroker.h"
#include "ETrigger.h"
class AABB;
class TriggerSystem : public PureSystem
{
public:
TriggerSystem(EventBroker* eventBroker)
: PureSystem(eventBroker, "Trigger")
{}
virtual void UpdateComponent(World* world, ComponentWrapper& collision, double dt) override;
private:
std::unordered_map<EntityID, std::unordered_set<EntityID>> m_EntitiesTouchingTrigger;
std::unordered_map<EntityID, std::unordered_set<EntityID>> m_EntitiesCompletelyInTrigger;
//True if leave event was thrown.
bool throwLeaveIfWasInTrigger(std::unordered_set<EntityID>& triggerSet, EntityID pId, EntityID tId);
template<typename Event>
void publish(EntityID pId, EntityID tId)
{
Event e;
e.Trigger = tId;
e.Entity = pId;
m_EventBroker->Publish(e);
}
};
#endif
+2 -1
View File
@@ -4,4 +4,5 @@
#include <map>
#include <unordered_map>
#include "Core/Util/Logging.h"
#include "Core/Util/Logging.h"
#include "Core/Util/IfDebug.h"
+29
View File
@@ -0,0 +1,29 @@
#ifndef AABB_h__
#define AABB_h__
#include "../GLM.h"
class AABB
{
public:
AABB() = default;
//No checks are made. Values in minPos must be less than values in maxPos, i.e. min.x < max.x, etc.
AABB(const glm::vec3& minPos, const glm::vec3& maxPos);
AABB(const glm::vec4& minPos, const glm::vec4& maxPos);
//No checks are made. Size must consist of non-negative numbers.
virtual void CreateFromCenter(const glm::vec3& center, const glm::vec3& size);
virtual ~AABB();
const glm::vec3& MinCorner() const { return m_MinCorner; }
const glm::vec3& MaxCorner() const { return m_MaxCorner; }
const glm::vec3& Center() const { return m_Center; }
const glm::vec3 Size() const { return 2.0f * m_HalfSize; }
const glm::vec3& HalfSize() const { return m_HalfSize; }
private:
glm::vec3 m_MinCorner;
glm::vec3 m_MaxCorner;
glm::vec3 m_Center;
glm::vec3 m_HalfSize;
};
#endif
+3 -1
View File
@@ -20,7 +20,7 @@ public:
~ComponentPoolForwardIterator() = default;
ComponentPoolForwardIterator& operator=(const ComponentPoolForwardIterator& other) = default;
ComponentPoolForwardIterator& operator++();
ComponentPoolForwardIterator& operator++(int);
ComponentPoolForwardIterator operator++(int);
bool operator!=(const ComponentPoolForwardIterator& other) const;
bool operator==(const ComponentPoolForwardIterator& other) const;
ComponentWrapper operator*() const;
@@ -54,6 +54,8 @@ public:
ComponentWrapper Allocate(EntityID entity);
// Get the component belonging to a specific entity
ComponentWrapper GetByEntity(EntityID ent);
// Returns true if the pool contains a component for the specified entity
bool KnowsEntity(EntityID ent);
// Delete a component and free its memory
void Delete(ComponentWrapper& wrapper);
+16
View File
@@ -0,0 +1,16 @@
#ifndef EFileDropped_h__
#define EFileDropped_h__
#include "EventBroker.h"
namespace Events
{
struct FileDropped : Event
{
std::string Path;
};
}
#endif
+17
View File
@@ -0,0 +1,17 @@
#ifndef Events_KeyboardChar_h__
#define Events_KeyboardChar_h__
#include "EventBroker.h"
namespace Events
{
struct KeyboardChar : Event
{
double Timestamp = 0.f;
unsigned int Char = 0;
};
}
#endif
+17
View File
@@ -0,0 +1,17 @@
#ifndef Events_MouseScroll_h__
#define Events_MouseScroll_h__
#include "EventBroker.h"
namespace Events
{
struct MouseScroll : Event
{
double DeltaX;
double DeltaY;
};
}
#endif
+20
View File
@@ -0,0 +1,20 @@
#ifndef EPlayerDamage_h__
#define EPlayerDamage_h__
#include "EventBroker.h"
#include "../Core/Entity.h"
namespace Events
{
struct PlayerDamage : Event
{
double DamageAmount;
EntityID PlayerDamagedID;
//optional TypeOfDamage
std::string TypeOfDamage;
};
}
#endif
+20
View File
@@ -0,0 +1,20 @@
#ifndef EPlayerDeath_h__
#define EPlayerDeath_h__
#include "EventBroker.h"
#include "../Core/Entity.h"
namespace Events
{
struct PlayerDeath : Event
{
//KilledBy,KilledByWhat is optional for now. It might be used later in the playerlog-system
EntityID KilledBy;
EntityID PlayerID;
std::string KilledByWhat;
};
}
#endif
+18
View File
@@ -0,0 +1,18 @@
#ifndef EPlayerHealthPickup_h__
#define EPlayerHealthPickup_h__
#include "EventBroker.h"
#include "../Core/Entity.h"
namespace Events
{
struct PlayerHealthPickup : Event
{
double HealthAmount;
EntityID PlayerHealedID;
};
}
#endif
+6 -2
View File
@@ -13,6 +13,8 @@
relay = decltype(relay)(std::bind(handler, this, std::placeholders::_1)); \
m_EventBroker->Subscribe(relay);
typedef unsigned int EventID;
class EventBroker;
class BaseEventRelay
@@ -31,6 +33,7 @@ public:
virtual bool Receive(const std::shared_ptr<Event> event) = 0;
protected:
EventID m_EventID;
std::string m_ContextTypeName;
std::string m_EventTypeName;
EventBroker* m_Broker;
@@ -95,6 +98,7 @@ public:
private:
bool m_IsProcessing = false;
EventID m_NextEventID = 0;
typedef std::string ContextTypeName_t; // typeid(ContextType).name()
typedef std::string EventTypeName_t; // typeid(EventType).name()
@@ -103,14 +107,14 @@ private:
typedef std::unordered_map<ContextTypeName_t, EventRelays_t> ContextRelays_t;
ContextRelays_t m_ContextRelays;
std::vector<BaseEventRelay*> m_RelaysToSubscribe;
std::vector<BaseEventRelay*> m_RelaysToUnsubscribe;
std::vector<std::tuple<EventID, ContextTypeName_t, EventTypeName_t>> m_RelaysToUnsubscribe;
typedef std::list<std::pair<EventTypeName_t, std::shared_ptr<Event>>> EventQueue_t;
std::shared_ptr<EventQueue_t> m_EventQueueRead;
std::shared_ptr<EventQueue_t> m_EventQueueWrite;
void subscribeImmediate(BaseEventRelay& relay);
void unsubscribeImmediate(BaseEventRelay& relay);
void unsubscribeImmediate(std::tuple<EventID, ContextTypeName_t, EventTypeName_t> identifier);
};
template <typename EventType>
+10
View File
@@ -8,12 +8,15 @@
#include "EventBroker.h"
#include "EKeyDown.h"
#include "EKeyUp.h"
#include "EKeyboardChar.h"
#include "EMousePress.h"
#include "EMouseRelease.h"
#include "EMouseMove.h"
#include "EMouseScroll.h"
#include "ELockMouse.h"
#include "EGamepadAxis.h"
#include "EGamepadButton.h"
#include "EFileDropped.h"
class InputManager
{
@@ -64,6 +67,13 @@ private:
void PublishGamepadAxisIfChanged(int gamepadID, Gamepad::Axis axis);
void PublishGamepadButtonIfChanged(int gamepadID, Gamepad::Button button);
static std::vector<unsigned int> GLFWCharCallbackQueue;
static void GLFWCharCallback(GLFWwindow* window, unsigned int c);
static std::vector<std::pair<double, double>> GLFWScrollCallbackQueue;
static void GLFWScrollCallback(GLFWwindow* window, double xoffset, double yoffset);
static std::vector<std::string> GLFWDropCallbackQueue;
static void GLFWDropCallback(GLFWwindow* window, int count, const char* paths[]);
};
#endif
+1 -1
View File
@@ -253,7 +253,7 @@ public:
}
//Postfix increment i.e. iter++. Prefer pre-increment (++iter) for efficiency.
MemoryPoolForwardIterator& operator++(int)
MemoryPoolForwardIterator operator++(int)
{
MemoryPoolForwardIterator<T> copyIter(*this);
operator++();
+104
View File
@@ -0,0 +1,104 @@
#ifndef OctTree_h__
#define OctTree_h__
#include "Core/AABB.h"
class Ray;
class OctTree
{
public:
struct Output
{
float CollideDistance;
};
OctTree();
~OctTree();
//For the root OctTree, [octTreeBounds] should be a box containing the entire level.
OctTree(const AABB& octTreeBounds, int subDivisions);
//We cannot copy the OctTree as of now, because of the recursive dynamic allocation.
//Define these if the OctTree suddenly needs to be copied, think of the children OctChild* ptrs.
OctTree(const OctTree& other) = delete;
OctTree(const OctTree&& other) = delete;
OctTree& operator= (const OctTree& other) = delete;
//Add a dynamic object (one that moves around) into the tree.
void AddDynamicObject(const AABB& box);
//Add a static object (that does not move) into the tree.
void AddStaticObject(const AABB& box);
//Get the boxes that are in the same area as the input [box], the boxes are put in [outBoxes].
void BoxesInSameRegion(const AABB& box, std::vector<AABB>& outBoxes);
//Empty the tree of all objects, static and dynamic.
void ClearObjects();
//Empty the tree of all dynamic objects. Static objects remain in the tree.
void ClearDynamicObjects();
//Returns true if the ray collides with something in the tree. Result is written to [data].
bool RayCollides(const Ray& ray, Output& data);
//Returns true if the box collides with something in the tree.
//On collision with a box, that box is written to [outBoxIntersected].
//Note: More efficient than calling BoxesInSameRegion from outside and testing there.
bool BoxCollides(const AABB& boxToTest, AABB& outBoxIntersected);
private:
struct OctChild; //Fwd declaration;
struct ContainedObject
{
ContainedObject()
: Box(AABB())
, Checked(false)
{}
ContainedObject(AABB box)
: Box(box)
, Checked(false)
{}
AABB Box;
bool Checked;
};
OctChild* m_Root;
std::vector<ContainedObject> m_StaticObjects;
std::vector<ContainedObject> m_DynamicObjects;
bool m_UpdatedOnce;
unsigned int m_BoxID;
glm::vec3 m_PrevPos;
glm::quat m_PrevOri;
void falsifyObjectChecks();
struct OctChild
{
~OctChild();
OctChild(const AABB& octTreeBounds,
int subDivisions,
std::vector<OctTree::ContainedObject>& staticObjects,
std::vector<OctTree::ContainedObject>& dynamicObjects);
OctChild(const OctChild& other) = delete;
OctChild(const OctChild&& other) = delete;
OctChild& operator= (const OctChild& other) = delete;
void AddDynamicObject(const AABB& box);
void AddStaticObject(const AABB& box);
void BoxesInSameRegion(const AABB& box, std::vector<AABB>& outBoxes) const;
void ClearObjects();
void ClearDynamicObjects();
bool RayCollides(const Ray& ray, Output& data) const;
bool BoxCollides(const AABB& boxToTest, AABB& outBoxIntersected) const;
OctChild* m_Children[8];
//Indices into the lists in OctTree.
std::vector<int> m_StaticObjIndices;
std::vector<int> m_DynamicObjIndices;
AABB m_Box;
//Reference to the lists in OctTree.
std::vector<OctTree::ContainedObject>& m_StaticObjectsRef;
std::vector<OctTree::ContainedObject>& m_DynamicObjectsRef;
inline bool hasChildren() const;
int childIndexContainingPoint(const glm::vec3& point) const;
std::vector<int> childIndicesContainingBox(const AABB& box) const;
};
};
#endif
+31
View File
@@ -0,0 +1,31 @@
#ifndef Ray_h__
#define Ray_h__
#include "../GLM.h"
#include "Common.h"
class Ray
{
public:
Ray(const glm::vec3& origin, const glm::vec3& dir)
: m_Origin(origin)
, m_Direction(glm::normalize(dir))
{
DEBUG_IF(true) {
if (glm::any(glm::isnan(m_Direction))) {
LOG_WARNING("Ray Direction was set to the zero-vector, expect unknown side effects and/or crashes.");
}
}
}
const glm::vec3& Origin() const { return m_Origin; }
const glm::vec3& Direction() const { return m_Direction; }
//Sets the ray origin at parameter.
void SetOrigin(const glm::vec3& origin) { m_Origin = origin; }
//Normalizes the parameter and sets direction to it.
void SetDirection(const glm::vec3& direction) { m_Direction = glm::normalize(direction); }
private:
glm::vec3 m_Origin;
glm::vec3 m_Direction;
};
#endif // Ray_h__
+34 -9
View File
@@ -9,17 +9,42 @@ class System
{
friend class SystemPipeline;
public:
System(EventBroker* eventBroker, std::string componentType)
: m_EventBroker(eventBroker)
, m_ComponentType(componentType)
{ }
virtual void Update(World* world, ComponentWrapper& component, double dt) = 0;
protected:
std::string m_ComponentType;
System(EventBroker* eventBroker)
: m_EventBroker(eventBroker)
{ }
virtual ~System() = default;
EventBroker* m_EventBroker;
};
class PureSystem : public System
{
friend class SystemPipeline;
protected:
PureSystem(EventBroker* eventBroker, std::string componentType)
: System(eventBroker)
, m_ComponentType(componentType)
{ }
virtual ~PureSystem() = default;
const std::string m_ComponentType;
virtual void UpdateComponent(World* world, ComponentWrapper& component, double dt) = 0;
};
class ImpureSystem : public System
{
friend class SystemPipeline;
protected:
ImpureSystem(EventBroker* eventBroker)
: System(eventBroker)
{ }
virtual ~ImpureSystem() = default;
virtual void Update(World* world, double dt) = 0;
};
#endif
+50 -19
View File
@@ -14,45 +14,76 @@ public:
{ }
~SystemPipeline()
{
for (auto& pair : m_Systems) {
for (auto& system : pair.second) {
delete system;
for (UnorderedSystems& group : m_OrderedSystemGroups) {
for (auto& pair : group.Systems) {
delete pair.second;
}
}
}
template <typename T, typename... Arguments>
void AddSystem(Arguments... args)
//All systems with orderlevel 0 will be updated first, then 1, 2, etc.
void AddSystem(int updateOrderLevel, Arguments... args)
{
if (updateOrderLevel + 1 > m_OrderedSystemGroups.size()) {
m_OrderedSystemGroups.resize(updateOrderLevel + 1);
}
UnorderedSystems& group = m_OrderedSystemGroups[updateOrderLevel];
System* system = new T(m_EventBroker, args...);
if (!system->m_ComponentType.empty()) {
m_Systems[system->m_ComponentType].push_back(system);
} else {
LOG_ERROR("Failed to add system \"%s\": Missing component type!", typeid(T).name());
delete system;
group.Systems[typeid(T).name()] = system;
if (std::is_base_of<PureSystem, T>::value) {
PureSystem* pureSystem = static_cast<PureSystem*>(system);
if (!pureSystem->m_ComponentType.empty()) {
group.PureSystems[pureSystem->m_ComponentType].push_back(pureSystem);
} else {
LOG_ERROR("Failed to add pure system \"%s\": Missing component type!", typeid(T).name());
}
}
if (std::is_base_of<ImpureSystem, T>::value) {
ImpureSystem* impureSystem = static_cast<ImpureSystem*>(system);
group.ImpureSystems.push_back(impureSystem);
}
}
void Update(World* world, double dt)
{
for (auto& pair : m_Systems) {
const std::string& componentName = pair.first;
auto& systems = pair.second;
const ComponentPool* pool = world->GetComponents(componentName);
if (pool == nullptr) {
continue;
for (UnorderedSystems& group : m_OrderedSystemGroups) {
// Process events
for (auto& pair : group.Systems) {
m_EventBroker->Process(pair.first);
}
for (auto& component : *pool) {
for (auto& system : systems) {
system->Update(world, component, dt);
// Update
for (auto& pair : group.PureSystems) {
const std::string& componentName = pair.first;
auto& systems = pair.second;
const ComponentPool* pool = world->GetComponents(componentName);
if (pool == nullptr) {
continue;
}
for (auto& component : *pool) {
for (auto& system : systems) {
system->UpdateComponent(world, component, dt);
}
}
}
for (auto& system : group.ImpureSystems) {
system->Update(world, dt);
}
}
}
private:
EventBroker* m_EventBroker;
std::unordered_map<std::string, std::vector<System*>> m_Systems;
struct UnorderedSystems
{
std::map<std::string, System*> Systems;
std::map<std::string, std::vector<PureSystem*>> PureSystems;
std::vector<ImpureSystem*> ImpureSystems;
};
std::vector<UnorderedSystems> m_OrderedSystemGroups;
};
#endif
+12
View File
@@ -0,0 +1,12 @@
// Example:
// DEBUG_IF(condition) {
// // This code is executed only in debug mode and if condition is true.
// }
// NOTE: condition statement is not executed at all in release mode.
#ifndef DEBUG_IF
#ifndef DEBUG
#define DEBUG_IF(c) if(c)
#else
#define DEBUG_IF(c) if(false)
#endif
#endif
+13
View File
@@ -14,22 +14,35 @@ public:
// Create empty entity
EntityID CreateEntity(EntityID parent = 0);
// Delete entity and all components within
void DeleteEntity(EntityID entity);
// Register a component type and allocate space for it
void RegisterComponent(ComponentInfo& ci);
// Attach a component to an entity and fill it with default values
ComponentWrapper AttachComponent(EntityID entity, std::string componentType);
// Check if an entity has a component
bool HasComponent(EntityID entity, std::string componentType);
// Get a component of an entity
ComponentWrapper GetComponent(EntityID entity, std::string componentType);
// Delete a component off an entity
void DeleteComponent(EntityID entity, std::string componentType);
// Get all components of the specified type
const ComponentPool* GetComponents(std::string componentType);
// Get entity parent
EntityID GetParent(EntityID entity);
// Change the parent of an entity
void SetParent(EntityID entity, EntityID parent);
// Get all component pools
const std::unordered_map<std::string, ComponentPool*>& GetComponentPools() const { return m_ComponentPools; }
// Get the entity children map
const std::unordered_multimap<EntityID, EntityID>& GetEntityChildren() const { return m_EntityChildren; }
private:
EntityID m_CurrentEntityID = 1;
std::unordered_map<EntityID, EntityID> m_EntityParents;
// TODO: This should be a more effective structure
std::unordered_multimap<EntityID, EntityID> m_EntityChildren;
std::unordered_map<std::string, ComponentPool*> m_ComponentPools;
+79
View File
@@ -0,0 +1,79 @@
#include <imgui/imgui.h>
#include <glm/gtx/common.hpp>
#include <boost/filesystem/path.hpp>
#include "../Core/System.h"
#include "../Core/EMousePress.h"
#include "../Core/EMouseRelease.h"
#include "../Core/EMouseMove.h"
#include "../Core/ConfigFile.h"
#include "../Input/EInputCommand.h"
#include "../Rendering/IRenderer.h"
#include "../Rendering/EPicking.h"
#include "../Core/EFileDropped.h"
#include "../Rendering/RenderQueueFactory.h"
class EditorSystem : public ImpureSystem
{
public:
EditorSystem(EventBroker* eventBroker, IRenderer* renderer);
virtual void Update(World* world, double dt) override;
private:
IRenderer* m_Renderer;
World* m_World = nullptr;
bool m_Enabled;
bool m_Visible;
std::vector<glm::vec2> m_PickingQueue;
enum class WidgetMode
{
None,
Translate,
Rotate,
Scale
} m_WidgetMode = WidgetMode::None;
enum class WidgetSpace
{
Local,
Global
} m_WidgetSpace = WidgetSpace::Global;
EntityID m_Widget = 0;
EntityID m_WidgetX = 0;
EntityID m_WidgetPlaneX = 0;
EntityID m_WidgetY = 0;
EntityID m_WidgetPlaneY = 0;
EntityID m_WidgetZ = 0;
EntityID m_WidgetPlaneZ = 0;
EntityID m_WidgetOrigin = 0;
glm::vec3 m_WidgetCurrentAxis;
float m_WidgetPickingDepth = 0.f;
EntityID m_Selection = 0;
EntityID m_LastSelection = 0;
glm::vec3 m_Position;
std::string m_LastDroppedFile;
EventRelay<EditorSystem, Events::InputCommand> m_EInputCommand;
bool OnInputCommand(const Events::InputCommand& e);
EventRelay<EditorSystem, Events::MouseRelease> m_EMouseRelease;
bool OnMouseRelease(const Events::MouseRelease& e);
EventRelay<EditorSystem, Events::MousePress> m_EMousePress;
bool OnMousePress(const Events::MousePress& e);
EventRelay<EditorSystem, Events::MouseMove> m_EMouseMove;
bool OnMouseMove(const Events::MouseMove& e);
EventRelay<EditorSystem, Events::Picking> m_EPicking;
bool OnPicking(const Events::Picking& e);
EventRelay<EditorSystem, Events::FileDropped> m_EFileDropped;
bool OnFileDropped(const Events::FileDropped& e);
void updateWidget();
void setWidgetMode(WidgetMode newMode);
void setWidgetSpace(WidgetSpace space);
void drawUI(World* world, double dt);
bool createDeleteButton(std::string componentType);
void changeParent(EntityID entity, EntityID newParent);
};
+74 -4
View File
@@ -1,14 +1,84 @@
#ifndef Client_h__
#define Client_h__
#include <boost\asio.hpp>
#include <string>
#include <ctime>
class Client
#include <glm/common.hpp>
#include <boost/asio.hpp>
#include "Network/Network.h"
#include "Network/MessageType.h"
#include "Network/PlayerDefinition.h"
#include "Network/SnapshotDefinitions.h"
#include "Core/World.h"
#include "Core/EventBroker.h"
#include "Core/ConfigFile.h"
#include "Input/EInputCommand.h"
class Client : public Network
{
Client();
~Client();
public:
Client(ConfigFile* config);
~Client();
void Start(World* world, EventBroker* eventBroker) override;
void Update() override;
void Close();
private:
// Assio UDP logic
boost::asio::ip::udp::endpoint m_ReceiverEndpoint;
boost::asio::io_service m_IOService;
boost::asio::ip::udp::socket m_Socket;
// Sending message to server logic
int bytesRead = -1;
char readBuf[1024] = { 0 };
int snapshotInterval = 33;
std::clock_t previousSnapshotMessage = std::clock();
// Packet loss logic
unsigned int m_PacketID = 0;
unsigned int m_PreviousPacketID = 0;
unsigned int m_SendPacketID = 0;
// Game logic
World* m_World;
std::string m_PlayerName;
int m_PlayerID = -1;
// Network logic
PlayerDefinition m_PlayerDefinitions[MAXCONNECTIONS];
SnapshotDefinitions m_NextSnapshot;
bool m_ThreadIsRunning = true;
double m_DurationOfPingTime;
std::clock_t m_StartPingTime;
// Use to check if we should send disconnect message
// if game is turned of by closing window.
bool m_WasStarted = false;
// Private member functions
void readFromServer();
void sendSnapshotToServer();
int receive(char* data, size_t length);
void send(Packet& packet);
void connect();
void disconnect();
void ping();
void moveMessageHead(char*& data, size_t& length, size_t stepSize);
void parseMessageType(Packet& packet);
void parseEventMessage(Packet& packet);
void parseConnect(Packet& packet);
void parsePing();
void parseServerPing();
void parseSnapshot(Packet& packet);
void identifyPacketLoss();
bool isConnected();
EntityID createPlayer();
// Events
EventBroker* m_EventBroker;
EventRelay<Client, Events::InputCommand> m_EInputCommand;
bool OnInputCommand(const Events::InputCommand &e);
};
#endif
+17
View File
@@ -0,0 +1,17 @@
#ifndef MessageType_h__
#define MessageType_h__
// Message types used by both server and client.
// Used to determine what type of message was sent.
enum class MessageType
{
Connect,
Disconnect,
ClientPing,
ServerPing,
Message,
Snapshot,
Event,
};
#endif
+19
View File
@@ -0,0 +1,19 @@
#ifndef Network_h__
#define Network_h__
#include "Core/World.h"
#include "Core/EventBroker.h"
#include "Network/Packet.h"
#define MAXCONNECTIONS 8
#define INPUTSIZE 128
class Network
{
public:
virtual ~Network() { };
virtual void Start(World* m_world, EventBroker *eventBroker) = 0;
virtual void Update() = 0;
};
#endif
+61
View File
@@ -0,0 +1,61 @@
#ifndef Packet_h__
#define Packet_h__
#include <string>
#include "Network/MessageType.h"
#include "Core/Util/Logging.h"
// Defines the
class Packet
{
public:
// arg1: Type of message (Connect, Disconnect...)
// arg2: PacketID for identifying packet loss.
Packet(MessageType type, unsigned int& packetID);
// Used to create packet from already existing data buffer.
Packet(char* data, const int sizeOfPacket);
~Packet();
// Add primitive types like int, float, char...
template<typename T>
void WritePrimitive(T val)
{
// Check if we are trying to add more than the package can fit.
if (m_MaxPacketSize < m_Offset + sizeof(T)) {
LOG_WARNING("Packet AddPrimitive(): You are trying to add more than we have allocated for!");
}
memcpy(m_Data + m_Offset, &val, sizeof(T));
m_Offset += sizeof(T);
}
// Pops the first element as if it was a primitive.
template<typename T>
T ReadPrimitive()
{
if (m_Offset < m_ReturnDataOffset + sizeof(T)) {
LOG_WARNING("Packet PopFrontPrimitive(): You are trying to remove more than what exists in this packet!");
return -1;
}
T returnValue;
memcpy(&returnValue, m_Data + m_ReturnDataOffset, sizeof(T));
m_ReturnDataOffset += sizeof(T);
return returnValue;
}
// Add a string to the message
void WriteString(std::string str);
// Add data to the message
void WriteData(char* data, int sizeOfData);
// Pops the first element as if it was a string.
std::string ReadString();
char* ReadData(int SizeOfData);
int Size() { return m_Offset; };
char* Data() { return m_Data; };
private:
char* m_Data;
unsigned int m_ReturnDataOffset = 0;
int m_Offset = 0;
unsigned int m_MaxPacketSize = 128;
};
#endif
+11
View File
@@ -0,0 +1,11 @@
#ifndef PlayerDefinition_h__
#define PlayerDefinition_h__
#include <string>
struct PlayerDefinition {
int EntityID = -1;
std::string Name = "";
boost::asio::ip::udp::endpoint Endpoint;
};
#endif
+77 -4
View File
@@ -1,12 +1,85 @@
#ifndef Server_h__
#define Server_h__
#include <boost\asio.hpp>
#include <string>
#include <ctime>
class Server
#include <glm/common.hpp>
#include <boost/asio/ip/udp.hpp>
#include "Network/MessageType.h"
#include "Network/PlayerDefinition.h"
#include "Core/World.h"
#include "Core/EventBroker.h"
#include "Network/Network.h"
class Server : public Network
{
Server();
~Server();
public:
Server();
~Server();
void Start(World* m_world, EventBroker *eventBroker) override;
void Update() override;
void Close();
private:
// UDP logic
boost::asio::ip::udp::endpoint m_ReceiverEndpoint;
boost::asio::io_service m_IOService;
boost::asio::ip::udp::socket m_Socket;
PlayerDefinition m_PlayerDefinitions[MAXCONNECTIONS];
// Sending messages to client logic
char readBuffer[1024] = { 0 };
int bytesRead = 0;
// time for previouse message
std::clock_t previousePingMessage = std::clock();
std::clock_t previousSnapshotMessage = std::clock();
std::clock_t timOutTimer = std::clock();
// How often we send messages (milliseconds)
int intervalMs = 1000;
int snapshotInterval = 50;
int checkTimeOutInterval = 100;
//Timers
std::clock_t m_StartPingTime;
std::clock_t m_StopTimes[8];
// Game logic
World* m_World;
EventBroker* m_EventBroker;
// vec.size() = ammount of players to create, stores playerID's
std::vector<unsigned int> m_PlayersToCreate;
// Packet loss logic
unsigned int m_PacketID;
unsigned int m_PreviousPacketID;
unsigned int m_SendPacketID;
// Close logic
bool m_ThreadIsRunning = true;
// Private member functions
int receive(char* data, size_t length);
void readFromClients();
void send(Packet& packet, int playerID);
void send(Packet& packet);
void moveMessageHead(char*& data, size_t& length, size_t stepSize);
void broadcast(std::string message);
void broadcast(Packet& packet);
void sendSnapshot();
void sendPing();
void checkForTimeOuts();
void disconnect(int i);
void parseMessageType(Packet& packet);
void parseEvent(Packet& packet);
void parseConnect(Packet& packet);
void parseDisconnect();
void parseClientPing();
void parseServerPing();
void parseSnapshot(Packet& packet);
void identifyPacketLoss();
EntityID createPlayer();
};
#endif
@@ -0,0 +1,12 @@
#ifndef SnapshotDefinitions_h__
#define SnapshotDefinitions_h__
struct SnapshotDefinitions
{
// "+Forward" is 8 characters * sizeof(char) = 8
std::string InputForward;
// "+Right" is 6 characters * sizeof(char) = 6
std::string InputRight;
};
#endif
@@ -1,3 +1,4 @@
#include <imgui/imgui.h>
#include "../Input/FirstPersonInputController.h"
template <typename EventContext>
@@ -13,22 +14,35 @@ public:
virtual bool OnCommand(const Events::InputCommand& e) override
{
ImGuiIO& io = ImGui::GetIO();
if (e.Command == "PrimaryFire") {
if (e.Value > 0) {
LockMouse();
if (!io.WantCaptureMouse) {
LockMouse();
}
} else {
UnlockMouse();
}
return false;
}
if (e.Command == "Right") {
float value = std::max(-1.f, std::min(e.Value, 1.f));
m_Velocity.x = value;
}
if (e.Command == "Forward") {
float value = std::max(-1.f, std::min(e.Value, 1.f));
m_Velocity.z = -value;
if (!io.WantCaptureKeyboard) {
if (e.Command == "Right") {
float value = std::max(-1.f, std::min(e.Value, 1.f));
m_Velocity.x = value;
}
if (e.Command == "Forward") {
float value = std::max(-1.f, std::min(e.Value, 1.f));
m_Velocity.z = -value;
}
if (e.Command == "Sprint") {
if (e.Value > 0.f) {
m_Speed = m_BaseSpeed * 2.f * (e.Value);
} else {
m_Speed = m_BaseSpeed;
}
}
}
return FirstPersonInputController::OnCommand(e);
@@ -37,12 +51,13 @@ public:
void Update(double dt)
{
if (glm::length2(m_Velocity) > 0) {
m_Position += m_Orientation * (glm::normalize(m_Velocity) * m_BaseSpeed);
m_Position += m_Orientation * (glm::normalize(m_Velocity) * m_Speed * (float)dt);
}
}
protected:
glm::vec3 m_Position = glm::vec3(0, 0, 0);
glm::vec3 m_Velocity = glm::vec3(0, 0, 0);
float m_BaseSpeed = 0.1f;
float m_BaseSpeed = 2.0f;
float m_Speed = m_BaseSpeed;
};
+38
View File
@@ -0,0 +1,38 @@
#ifndef DrawFinalPass_h__
#define DrawFinalPass_h__
#include "IRenderer.h"
#include "DrawFinalPassState.h"
#include "LightCullingPass.h"
#include "FrameBuffer.h"
#include "ShaderProgram.h"
#include "Util/UnorderedMapVec2.h"
#include "Texture.h"
class DrawFinalPass
{
public:
DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass);
~DrawFinalPass() { }
void InitializeTextures();
void InitializeFrameBuffers();
void InitializeShaderPrograms();
void Draw(RenderQueueCollection& rq);
//Getters
private:
void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const;
Texture* m_WhiteTexture;
const IRenderer* m_Renderer;
const LightCullingPass* m_LightCullingPass;
ShaderProgram* m_ForwardPlusProgram;
};
#endif
@@ -0,0 +1,15 @@
#ifndef DrawFinalPassState_h__
#define DrawFinalPassState_h__
#include "Rendering/RenderState.h"
class DrawFinalPassState : public RenderState
{
public:
DrawFinalPassState();
~DrawFinalPassState();
private:
};
#endif
+36
View File
@@ -0,0 +1,36 @@
#ifndef DrawScenePass_h__
#define DrawScenePass_h__
#include "IRenderer.h"
#include "DrawScenePassState.h"
#include "FrameBuffer.h"
#include "ShaderProgram.h"
#include "Util/UnorderedMapVec2.h"
#include "Texture.h"
class DrawScenePass
{
public:
DrawScenePass(IRenderer* renderer);
~DrawScenePass() { }
void InitializeTextures();
void InitializeFrameBuffers();
void InitializeShaderPrograms();
void Draw(RenderQueueCollection& rq);
//Getters
private:
void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const;
Texture* m_WhiteTexture;
const IRenderer* m_Renderer;
ShaderProgram* m_BasicForwardProgram;
};
#endif
@@ -0,0 +1,15 @@
#ifndef DrawScenePassState_h__
#define DrawScenePassState_h__
#include "Rendering/RenderState.h"
class DrawScenePassState : public RenderState
{
public:
DrawScenePassState();
~DrawScenePassState();
private:
};
#endif
+7 -2
View File
@@ -34,21 +34,26 @@ public:
EntityID Entity;
//World position of the "pick"
glm::vec3 Position;
// Depth
float Depth;
};
PickData Pick(glm::vec2 screenCoord) const
{
PickData pickData;
// Invert screen y coordinate
screenCoord.y = Resolution.Height - screenCoord.y;
ScreenCoords::PixelData data = ScreenCoords::ToPixelData(screenCoord, PickingBuffer, *DepthBuffer);
pickData.Depth = data.Depth;
auto it = PickingColorsToEntity->find(glm::vec2(data.Color[0], data.Color[1]));
if (it != PickingColorsToEntity->end()) {
pickData.Entity = it->second;
} else {
pickData.Entity = -1;
pickData.Entity = 0;
}
pickData.Position = ScreenCoords::ToWorldPos(screenCoord.x, Resolution.Width - screenCoord.y, data.Depth, Resolution, ProjectionMatrix, ViewMatrix);
pickData.Position = ScreenCoords::ToWorldPos(screenCoord.x, screenCoord.y, data.Depth, Resolution, ProjectionMatrix, ViewMatrix);
return pickData;
}
+1 -1
View File
@@ -35,7 +35,7 @@ public:
virtual void Draw(RenderQueueCollection& rq) = 0;
protected:
Rectangle m_Resolution = Rectangle(1280, 720);
Rectangle m_Resolution = Rectangle::Rectangle(1280, 720);
bool m_Fullscreen = false;
bool m_VSYNC = false;
int m_GLVersion[2];
@@ -0,0 +1,77 @@
#include <imgui/imgui.h>
#include "../OpenGL.h"
#include "IRenderer.h"
#include "RenderState.h"
#include "../Core/EventBroker.h"
#include "../Core/EMousePress.h"
#include "../Core/EMouseRelease.h"
#include "../Core/EMouseMove.h"
#include "../Core/EMouseScroll.h"
#include "../Core/EKeyDown.h"
#include "../Core/EKeyUp.h"
#include "../Core/EKeyboardChar.h"
class ImGuiRenderState : public RenderState
{
public:
ImGuiRenderState()
: RenderState()
{
BindFramebuffer(0);
Enable(GL_BLEND);
BlendEquation(GL_FUNC_ADD);
BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Disable(GL_CULL_FACE);
Disable(GL_DEPTH_TEST);
Enable(GL_SCISSOR_TEST);
}
};
class ImGuiRenderPass
{
public:
ImGuiRenderPass(IRenderer* renderer, EventBroker* eventBroker);
void Update(double dt);
void Draw();
private:
IRenderer* m_Renderer;
EventBroker* m_EventBroker;
GLFWwindow* g_Window;
double g_DeltaTime = 0.0;
float g_MouseWheel = 0.f;
GLuint g_FontTexture;
int g_ShaderHandle;
int g_VertHandle;
int g_FragHandle;
int g_AttribLocationTex;
int g_AttribLocationProjMtx;
int g_AttribLocationPosition;
int g_AttribLocationUV;
int g_AttribLocationColor;
GLuint g_VboHandle;
GLuint g_VaoHandle;
GLuint g_ElementsHandle;
EventRelay<ImGuiRenderPass, Events::MousePress> m_EMousePress;
bool OnMousePress(const Events::MousePress& e);
EventRelay<ImGuiRenderPass, Events::MouseRelease> m_EMouseRelease;
bool OnMouseRelease(const Events::MouseRelease& e);
EventRelay<ImGuiRenderPass, Events::MouseMove> m_EMouseMove;
bool OnMouseMove(const Events::MouseMove& e);
EventRelay<ImGuiRenderPass, Events::MouseScroll> m_EMouseScroll;
bool OnMouseScroll(const Events::MouseScroll& e);
EventRelay<ImGuiRenderPass, Events::KeyDown> m_EKeyDown;
bool OnKeyDown(const Events::KeyDown& e);
EventRelay<ImGuiRenderPass, Events::KeyUp> m_EKeyUp;
bool OnKeyUp(const Events::KeyUp& e);
EventRelay<ImGuiRenderPass, Events::KeyboardChar> m_EKeyboardChar;
bool OnKeyboardChar(const Events::KeyboardChar& e);
bool createDeviceObjects();
bool createFontsTexture();
void newFrame();
};
@@ -0,0 +1,78 @@
#ifndef LightCullingPass_h__
#define LightCullingPass_h__
#define TILE_SIZE 16
#define NUM_LIGHTS 1000
#include "IRenderer.h"
#include "LightCullingPassState.h"
#include "ShaderProgram.h"
class LightCullingPass
{
public:
LightCullingPass(IRenderer* renderer);
~LightCullingPass();
void GenerateNewFrustum();
void CullLights();
void FillLightList(RenderQueueCollection& rq);
GLuint FrustumSSBO() const { return m_FrustumSSBO; }
GLuint LightSSBO() const { return m_LightSSBO; }
GLuint LightGridSSBO() const { return m_LightGridSSBO; }
GLuint LightOffsetSSBO() const { return m_LightOffsetSSBO; }
GLuint LightIndexSSBO() const { return m_LightIndexSSBO; }
private:
void InitializeSSBOs();
void InitializeShaderPrograms();
const IRenderer* m_Renderer;
GLuint m_FrustumSSBO = 0;
GLuint m_LightSSBO = 0;
GLuint m_LightGridSSBO = 0;
GLuint m_LightOffsetSSBO = 0;
GLuint m_LightIndexSSBO = 0;
ShaderProgram* m_CalculateFrustumProgram;
ShaderProgram* m_LightCullProgram;
struct Plane {
glm::vec3 Normal;
float d;
};
struct Frustum {
Plane Planes[4];
};
Frustum m_Frustums[80*45]; //TODO: Renderer: Make this change with resolution
//This should be a component
struct PointLight {
glm::vec4 Position = glm::vec4(0.f);
glm::vec4 Color = glm::vec4(1.f);
float Radius = 5.f;
float Intensity = 0.8f;
float Falloff = 0.3f;
float Padding = 1337;
};
std::vector<PointLight> m_PointLights;
struct LightGrid {
float Start;
float Amount;
glm::vec2 Padding;
};
LightGrid m_LightGrid[80*45]; //TODO: Renderer: Make this change with resolution
int m_LightOffset = 0;
float m_LightIndex[80*45*200]; //TODO: Renderer: Make this change with resolution
};
#endif
+51
View File
@@ -0,0 +1,51 @@
#ifndef PickingPass_h__
#define PickingPass_h__
#include "IRenderer.h"
#include "PickingPassState.h"
#include "FrameBuffer.h"
#include "ShaderProgram.h"
#include "Util/UnorderedMapVec2.h"
#include "../Core/EventBroker.h"
#include "EPicking.h"
class PickingPass
{
public:
PickingPass(IRenderer* renderer, EventBroker* eb);
~PickingPass();
void InitializeTextures();
void InitializeFrameBuffers();
void InitializeShaderPrograms();
void Draw(RenderQueueCollection& rq);
//Getters
const ShaderProgram& PickingProgram() const { return *m_PickingProgram; }
const std::unordered_map<glm::vec2, EntityID>& PickingColorsToEntity() const { return m_PickingColorsToEntity; }
GLuint PickingTexture() const { return m_PickingTexture; }
GLuint DepthBuffer() const { return m_DepthBuffer; }
const FrameBuffer& PickingBuffer() const { return m_PickingBuffer; }
private:
void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const;
EventBroker* m_EventBroker;
const IRenderer* m_Renderer;
ShaderProgram* m_PickingProgram;
std::unordered_map<glm::vec2, EntityID> m_PickingColorsToEntity;
GLuint m_PickingTexture;
GLuint m_DepthBuffer;
FrameBuffer m_PickingBuffer;
};
#endif
@@ -0,0 +1,15 @@
#ifndef PickingPassState_h__
#define PickingPassState_h__
#include "Rendering/RenderState.h"
class PickingPassState : public RenderState
{
public:
PickingPassState(GLuint frameBuffer);
~PickingPassState();
private:
};
#endif
+6 -5
View File
@@ -82,11 +82,12 @@ struct SpriteJob : RenderJob
struct PointLightJob : RenderJob
{
glm::vec3 Position;
glm::vec3 SpecularColor = glm::vec3(1, 1, 1);
glm::vec3 DiffuseColor = glm::vec3(1, 1, 1);
float Radius = 1.f;
float Intensity = 0.8f;
glm::vec4 Position;
glm::vec4 Color;
float Radius;
float Intensity;
float Falloff;
float padding = 123;
void CalculateHash() override
{
@@ -13,8 +13,12 @@ public:
RenderQueueFactory();
void Update(World* world);
RenderQueueCollection RenderQueues() const { return m_RenderQueues; }
static glm::vec3 AbsolutePosition(World* world, EntityID entity);
static glm::quat AbsoluteOrientation(World* world, EntityID entity);
static glm::vec3 AbsoluteScale(World* world, EntityID entity);
private:
RenderQueueCollection m_RenderQueues;
@@ -22,10 +26,6 @@ private:
void FillLights(World* world, RenderQueue* renderQueue);
glm::mat4 ModelMatrix(World* world, EntityID entity);
glm::vec3 AbsolutePosition(World* world, EntityID entity);
glm::quat AbsoluteOrientation(World* world, EntityID entity);
glm::vec3 AbsoluteScale(World* world, EntityID entity);
};
#endif
+27
View File
@@ -0,0 +1,27 @@
#ifndef RenderState_h__
#define RenderState_h__
#include <functional>
#include "../Common.h"
#include "../OpenGL.h"
#include "../GLM.h"
class RenderState
{
public:
RenderState() = default;
~RenderState();
bool Enable(GLenum cap);
bool Disable(GLenum cap);
bool CullFace(GLenum mode);
bool ClearColor(glm::vec4 color);
bool Clear(GLbitfield mask);
bool BindFramebuffer(GLint framebuffer);
bool BlendEquation(GLenum mode);
bool BlendFunc(GLenum sfactor, GLenum dfactor);
private:
std::vector<std::function<void(void)>> m_ResetFunctions;
};
#endif
+28 -22
View File
@@ -10,9 +10,15 @@
#include "Util/UnorderedMapVec2.h"
#include "FrameBuffer.h"
#include "../Core/World.h"
#include "PickingPass.h"
#include "DrawScenePass.h"
#include "DebugCameraInputController.h"
#include "LightCullingPass.h"
#include "DrawFinalPass.h"
#include "../Core/EventBroker.h"
#include "EPicking.h"
#include "ImGuiRenderPass.h"
class Renderer : public IRenderer
{
@@ -21,44 +27,44 @@ public:
: m_EventBroker(eventBroker)
{ }
virtual void Initialize() override;
virtual void Update(double dt) override;
virtual void Draw(RenderQueueCollection& rq) override;
virtual void Initialize() override;
virtual void Update(double dt) override;
virtual void Draw(RenderQueueCollection& rq) override;
private:
//----------------------Variables----------------------//
//----------------------Variables----------------------//
EventBroker* m_EventBroker;
Texture* m_ErrorTexture;
Texture* m_WhiteTexture;
float m_CameraMoveSpeed;
FrameBuffer m_PickingBuffer;
GLuint m_PickingTexture;
GLuint m_DepthBuffer;
std::shared_ptr<DebugCameraInputController<Renderer>> m_DebugCameraInputController;
Texture* m_ErrorTexture;
Texture* m_WhiteTexture;
float m_CameraMoveSpeed;
Model* m_ScreenQuad;
Model* m_UnitQuad;
Model* m_UnitSphere;
std::unordered_map<glm::vec2, EntityID> m_PickingColorsToEntity;
DrawScenePass* m_DrawScenePass;
PickingPass* m_PickingPass;
LightCullingPass* m_LightCullingPass;
ImGuiRenderPass* m_ImGuiRenderPass;
DrawFinalPass* m_DrawFinalPass;
//----------------------Functions----------------------//
void InitializeWindow();
void InitializeShaders();
//----------------------Functions----------------------//
void InitializeWindow();
void InitializeShaders();
void InitializeTextures();
void InitializeFrameBuffers();
void InitializeRenderPasses();
//TODO: Renderer: Get InputUpdate out of renderer
void InputUpdate(double dt);
void PickingPass(RenderQueueCollection& rq);
void InputUpdate(double dt);
//void PickingPass(RenderQueueCollection& rq);
void DrawScreenQuad(GLuint textureToDraw);
void DrawScene(RenderQueueCollection& rq);
void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type);
//--------------------ShaderPrograms-------------------//
ShaderProgram m_BasicForwardProgram;
ShaderProgram m_PickingProgram;
ShaderProgram m_DrawScreenQuadProgram;
ShaderProgram* m_BasicForwardProgram;
ShaderProgram* m_DrawScreenQuadProgram;
};
#endif
+10 -3
View File
@@ -1,6 +1,9 @@
#ifndef ShaderProgram_h__
#define ShaderProgram_h__
#include "../Common.h"
#include "../OpenGL.h"
#include "../Core/ResourceManager.h"
#include <fstream>
class Shader
@@ -60,11 +63,13 @@ public:
: ShaderType(fileName) { }
};
class ShaderProgram
class ShaderProgram : public Resource
{
public:
ShaderProgram()
friend class ResourceManager;
private:
ShaderProgram(std::string)
: m_ShaderProgramHandle(0) { }
public:
~ShaderProgram();
void AddShader(std::shared_ptr<Shader> shader);
@@ -79,3 +84,5 @@ private:
GLuint m_ShaderProgramHandle;
std::vector<std::shared_ptr<Shader>> m_Shaders;
};
#endif
+1 -1
View File
@@ -9,7 +9,7 @@ inline bool _GLERROR(const char* info, const char* file, const char* func, unsig
GLenum error = glGetError();
if (error != GL_NO_ERROR)
{
_LOG(LOG_LEVEL_ERROR, file, func, line, "GL Error: %s %i %s", info, error, gluErrorString(error));
_LOG(LOG_LEVEL_ERROR, file, func, line, "GL Error: %s, %i, %s", info, error, gluErrorString(error));
return true;
}
+17
View File
@@ -17,6 +17,14 @@
#include "Core/SystemPipeline.h"
#include "RaptorCopterSystem.h"
#include "PlayerSystem.h"
#include "Editor/EditorSystem.h"
// Network
#include <boost/thread.hpp>
#include "Network/Network.h"
#include "Network/Server.h"
#include "Network/Client.h"
class Game
{
@@ -38,12 +46,21 @@ private:
World* m_World;
SystemPipeline* m_SystemPipeline;
RenderQueueFactory* m_RenderQueueFactory;
// Network variables
boost::thread m_NetworkThread;
// Network methods
void networkFunction();
Network* m_ClientOrServer;
bool m_IsClientOrServer = false;
EventRelay<Game, Events::InputCommand> m_EInputCommand;
bool debugOnInputCommand(const Events::InputCommand& e);
void debugInitialize();
void debugTick(double dt);
EventRelay<Client, Events::KeyDown> m_EKeyDown;
};
#endif
+36
View File
@@ -0,0 +1,36 @@
#ifndef HealthSystem_h__
#define HealthSystem_h__
#include <GLFW/glfw3.h>
#include <glm/common.hpp>
#include "Common.h"
#include "Core/System.h"
#include "Core\EPlayerDamage.h";
#include "Core\EPlayerHealthPickup.h";
#include "Core\EPlayerDeath.h";
#include <tuple>
#include <vector>
class HealthSystem : public PureSystem
{
public:
HealthSystem(EventBroker* eventBroker);
//updatecomponent
virtual void UpdateComponent(World* world, ComponentWrapper& health, double dt) override;
private:
//methods which will take care of specific events
EventRelay<HealthSystem, Events::PlayerDamage> m_EPlayerDamage;
bool HealthSystem::OnPlayerDamaged(const Events::PlayerDamage& e);
EventRelay<HealthSystem, Events::PlayerHealthPickup> m_EPlayerHealthPickup;
bool HealthSystem::OnPlayerHealthPickup(const Events::PlayerHealthPickup& e);
//vector which will keep track of health changes
std::vector<std::tuple<EntityID, double>> m_DeltaHealthVector;
};
#endif
+13 -24
View File
@@ -6,39 +6,28 @@
#include "Common.h"
#include "Core/System.h"
#include "Core/EventBroker.h"
#include "Core/EKeyDown.h"
#include "Core/EKeyUp.h"
#include "Collision/ETrigger.h"
struct KeyInput
{
bool Forward = false;
bool Left = false;
bool Back = false;
bool Right = false;
};
class PlayerSystem : public System
class PlayerSystem : public PureSystem
{
public:
PlayerSystem(EventBroker* eventBroker)
: System(eventBroker, "Player")
: PureSystem(eventBroker, "Player")
{
EVENT_SUBSCRIBE_MEMBER(m_EKeyDown, &PlayerSystem::OnKeyDown);
EVENT_SUBSCRIBE_MEMBER(m_EKeyUp, &PlayerSystem::OnKeyUp);
EVENT_SUBSCRIBE_MEMBER(m_ETouch, &PlayerSystem::OnTouch);
EVENT_SUBSCRIBE_MEMBER(m_EEnter, &PlayerSystem::OnEnter);
EVENT_SUBSCRIBE_MEMBER(m_ELeave, &PlayerSystem::OnLeave);
}
virtual void Update(World* world, ComponentWrapper& player, double dt) override;
virtual void UpdateComponent(World* world, ComponentWrapper& player, double dt) override;
private:
float m_Speed = 5;
glm::vec3 m_Direction;
KeyInput input;
EventRelay<PlayerSystem, Events::KeyDown> m_EKeyDown;
bool OnKeyDown(const Events::KeyDown &event);
EventRelay<PlayerSystem, Events::KeyUp> m_EKeyUp;
bool OnKeyUp(const Events::KeyUp &event);
EventRelay<PlayerSystem, Events::TriggerEnter> m_EEnter;
bool OnEnter(const Events::TriggerEnter &event);
EventRelay<PlayerSystem, Events::TriggerTouch> m_ETouch;
bool PlayerSystem::OnTouch(const Events::TriggerTouch &event);
EventRelay<PlayerSystem, Events::TriggerLeave> m_ELeave;
bool PlayerSystem::OnLeave(const Events::TriggerLeave &event);
};
#endif
+3 -5
View File
@@ -1,16 +1,14 @@
#include "Common.h"
#include "Core/System.h"
class RaptorCopterSystem : public System
class RaptorCopterSystem : public PureSystem
{
public:
RaptorCopterSystem(EventBroker* eventBroker)
: System(eventBroker, "RaptorCopter")
: PureSystem(eventBroker, "RaptorCopter")
{ }
virtual void Initialize() { }
virtual void Update(World* world, ComponentWrapper& raptorCopter, double dt) override
virtual void UpdateComponent(World* world, ComponentWrapper& raptorCopter, double dt) override
{
ComponentWrapper& transform = world->GetComponent(raptorCopter.EntityID, "Transform");
(glm::vec3&)transform["Orientation"] += (float)(double)raptorCopter["Speed"] * (float)dt * (glm::vec3)raptorCopter["Axis"];
+11 -1
View File
@@ -1,9 +1,19 @@
[Debug]
LogLevel=1
LoadMap=
EditorEnabled=false
[Video]
Fullscreen=false
VSYNC=false
Width=1280
Height=720
Height=720
FOV=45
[Networking]
StartNetwork=false
IsServer=false
Name=Bob
Address=127.0.0.1
Port=13
+8
View File
@@ -14,3 +14,11 @@ R=Reload
Space=Jump
LeftControl=Crouch
LeftShift=Sprint
F1=ToggleEditor
1=EditorToolMove
2=EditorToolRotate
3=EditorToolScale
X=EditorToggleTransformSpace
C=ConnectToServer
N=SwitchToServer
M=SwitchToClient
+4
View File
@@ -6,4 +6,8 @@
<xs:include schemaLocation="Components/Test.xsd"/>
<xs:include schemaLocation="Components/RaptorCopter.xsd"/>
<xs:include schemaLocation="Components/Player.xsd"/>
<xs:include schemaLocation="Components/AABB.xsd"/>
<xs:include schemaLocation="Components/PointLight.xsd"/>
<xs:include schemaLocation="Components/Trigger.xsd"/>
<xs:include schemaLocation="Components/Health.xsd"/>
</xs:schema>
+4
View File
@@ -0,0 +1,4 @@
<c:AABB>
<BoxCenter X="0" Y="0" Z="0"/>
<BoxSize X="1" Y="1" Z="1"/>
</c:AABB>
+14
View File
@@ -0,0 +1,14 @@
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:t="types">
<xs:import schemaLocation="../Types.xsd" namespace="types"/>
<xs:element name="AABB">
<xs:complexType>
<xs:all>
<xs:element name="BoxCenter" type="t:Vector" minOccurs="0"/>
<xs:element name="BoxSize" type="t:Vector" minOccurs="0"/>
</xs:all>
</xs:complexType>
</xs:element>
</xs:schema>
+4
View File
@@ -0,0 +1,4 @@
<c:Health>
<Health>100</Health>
<MaxHealth>100</MaxHealth>
</c:Health>
+14
View File
@@ -0,0 +1,14 @@
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:t="types">
<xs:import schemaLocation="../Types.xsd" namespace="types"/>
<xs:element name="Health">
<xs:complexType>
<xs:all>
<xs:element name="Health" type="t:double" minOccurs="0"/>
<xs:element name="MaxHealth" type="t:double" minOccurs="0"/>
</xs:all>
</xs:complexType>
</xs:element>
</xs:schema>
+4
View File
@@ -1,3 +1,7 @@
<c:Player>
<Velocity X="0" Y="0" Z="0"/>
<Forward>false</Forward>
<Left>false</Left>
<Back>false</Back>
<Right>false</Right>
</c:Player>
+4
View File
@@ -7,6 +7,10 @@
<xs:complexType>
<xs:all>
<xs:element name="Velocity" type="t:Vector" minOccurs="0"/>
<xs:element name="Forward" type="t:bool" minOccurs="0"/>
<xs:element name="Left" type="t:bool" minOccurs="0"/>
<xs:element name="Back" type="t:bool" minOccurs="0"/>
<xs:element name="Right" type="t:bool" minOccurs="0"/>
</xs:all>
</xs:complexType>
</xs:element>
@@ -0,0 +1,7 @@
<c:PointLight>
<Color R="1" G="1" B="1" A="1"/>
<Radius>1.0</Radius>
<Intensity>0.8</Intensity>
<Falloff>0.3</Falloff>
<Visible>true</Visible>
</c:PointLight>
@@ -0,0 +1,20 @@
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:t="types">
<xs:import schemaLocation="../Types.xsd" namespace="types"/>
<xs:element name="PointLight">
<xs:annotation>
<xs:documentation>A pointlight that lights up geometry in a radius.</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:all>
<xs:element name="Color" type="t:Color" minOccurs="0"/>
<xs:element name="Radius" type="t:double" minOccurs="0"/>
<xs:element name="Intensity" type="t:double" minOccurs="0"/>
<xs:element name="Falloff" type="t:double" minOccurs="0"/>
<xs:element name="Visible" type="t:bool" minOccurs="0"/>
</xs:all>
</xs:complexType>
</xs:element>
</xs:schema>
-6
View File
@@ -1,6 +0,0 @@
<c:Test>
<Integer>1</Integer>
<Float>1.333</Float>
<Vector X="1.33333" Y="2.33333" Z="3.33333"/>
<Quaternion X="1.33333" Y="2.33333" Z="3.33333" W="4.44444"/>
</c:Test>
-20
View File
@@ -1,20 +0,0 @@
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:t="types">
<xs:import schemaLocation="../Types.xsd" namespace="types"/>
<xs:element name="Test">
<xs:annotation>
<xs:documentation>ECS Test Component</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:all>
<xs:element name="Integer" type="t:int" minOccurs="0"/>
<xs:element name="Double" type="t:double" minOccurs="0"/>
<xs:element name="String" type="t:string" minOccurs="0"/>
<xs:element name="Vector" type="t:Vector" minOccurs="0"/>
<xs:element name="Quaternion" type="t:Quaternion" minOccurs="0"/>
</xs:all>
</xs:complexType>
</xs:element>
</xs:schema>
+1 -1
View File
@@ -1,5 +1,5 @@
<c:Transform>
<Position X="0" Y="0" Z="0"/>
<Orientation X="0" Y="0" Z="0" W="0"/>
<Orientation X="0" Y="0" Z="0"/>
<Scale X="1" Y="1" Z="1"/>
</c:Transform>
+2
View File
@@ -0,0 +1,2 @@
<c:Trigger>
</c:Trigger>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:t="types">
<xs:import schemaLocation="../Types.xsd" namespace="types"/>
<xs:element name="Trigger">
</xs:element>
</xs:schema>
@@ -0,0 +1,122 @@
<?xml version="1.0" encoding="UTF-8"?>
<Entity xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xi="http://www.w3.org/2001/XInclude" xsi:noNamespaceSchemaLocation="../Types/Entity.xsd" xmlns:c="components">
<Components>
<c:Transform>
<Orientation X="0" Y="0" Z="0"/>
</c:Transform>
<c:Model>
<Resource>Models/DummyScene.obj</Resource>
</c:Model>
</Components>
<Children>
<Entity>
<Components>
<c:Transform>
<Position X="-1.5"/>
<Scale X="1" Y="1" Z="1"/>
</c:Transform>
<c:Model>
<Resource>Models/ScaleWidget.obj</Resource>
</c:Model>
</Components>
</Entity>
<Entity>
<Components>
<c:Transform>
<Position X="1.5"/>
<Scale X="2" Y="2" Z="2"/>
</c:Transform>
<c:Model>
<Resource>Models/RotationWidgetX.obj</Resource>
</c:Model>
<c:Trigger>
</c:Trigger>
</Components>
</Entity>
<Entity>
<Components>
<c:Player>
<Velocity X="0" Y="0" Z="0"/>
</c:Player>
<c:Transform>
<Position X="2.5"/>
</c:Transform>
<c:Model>
<Resource>Models/Core/UnitCube.obj</Resource>
</c:Model>
<c:AABB>
</c:AABB>
</Components>
</Entity>
<Entity>
<Components>
<c:Transform>
<Position X="0" Y="-0"/>
<Scale X="1" Y="1" Z="1"/>
</c:Transform>
<!--<c:Move>
<Speed>1</Speed>
<Direction X="-1"/>
<Rotation Y="3.14"/>
</c:Move>-->
</Components>
<Children>
<Entity>
<Components>
<c:Transform>
<Position X="0" Y="0"/>
<Orientation X="0.0" Y="0" Z="1.0"/>
</c:Transform>
<c:Model>
<Resource>Models/Core/UnitRaptor.obj</Resource>
<Color R="1" G="0.4" B="0.8"/>
</c:Model>
</Components>
<Children>
<Entity>
<Components>
<c:Transform>
<Position X="-0.01" Y="0.55"/>
<Orientation X="0" Y="0" Z="-1"/>
</c:Transform>
<c:RaptorCopter>
<Speed>20</Speed>
<Axis Y="1"/>
</c:RaptorCopter>
</Components>
<Children>
<Entity>
<Components>
<c:Transform>
<Position X="0" Y="0"/>
<Scale X="1.7" Y="0.03" Z="0.1"/>
<Orientation X="0" Y="0" Z="0"/>
</c:Transform>
<c:Model>
<Resource>Models/Core/UnitCube.obj</Resource>
<Color R="1" G="0.4" B="0.8"/>
</c:Model>
</Components>
</Entity>
<Entity>
<Components>
<c:Transform>
<Position X="0" Y="0"/>
<Scale X="1.7" Y="0.03" Z="0.1"/>
<Orientation X="0" Y="1.57" Z="0"/>
</c:Transform>
<c:Model>
<Resource>Models/Core/UnitCube.obj</Resource>
<Color R="1" G="0.4" B="0.8"/>
</c:Model>
</Components>
</Entity>
</Children>
</Entity>
</Children>
</Entity>
</Children>
</Entity>
</Children>
</Entity>
+49
View File
@@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<Entity xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xi="http://www.w3.org/2001/XInclude" xsi:noNamespaceSchemaLocation="../Types/Entity.xsd" xmlns:c="components">
<Components>
<c:Transform>
<Position X="0" Y="0" Z="0"/>
<Orientation X="0" Y="0" Z="0"/>
</c:Transform>
</Components>
<Children>
<Entity>
<Components>
<c:Transform>
<Position X="0" Y="0" Z="0"/>
<Scale X="100" Y="1" Z="100"/>
</c:Transform>
<c:Model>
<Resource>Models/Core/UnitPlane.obj</Resource>
</c:Model>
</Components>
</Entity>
<Entity>
<Components>
<c:Transform>
<Position X="1" Y="1" Z="0"/>
<Orientation X="0" Y="0.78539" Z="0"/>
</c:Transform>
<c:Model>
<Resource>An error</Resource>
</c:Model>
</Components>
<Children>
<Entity>
<Components>
<c:Transform>
<Position X="2" Y="0" Z="0"/>
<Orientation X="0" Y="0.78539" Z="0"/>
</c:Transform>
<c:Model>
<Resource>An error</Resource>
</c:Model>
</Components>
<Children>
</Children>
</Entity>
</Children>
</Entity>
</Children>
</Entity>
+11 -6
View File
@@ -10,7 +10,7 @@
</c:Model>
</Components>
<Children>
<Entity>
<!--<Entity>
<Components>
<c:Transform>
<Position X="-1.5"/>
@@ -20,18 +20,21 @@
<Resource>Models/ScaleWidget.obj</Resource>
</c:Model>
</Components>
</Entity>
<Entity>
</Entity>-->
<!--<Entity>
<Components>
<c:Transform>
<Position X="1.5"/>
<Scale X="2" Y="2" Z="2"/>
</c:Transform>
<c:Model>
<Resource>Models/RotationWidget.obj</Resource>
</c:Model>
<c:Trigger>
</c:Trigger>
</Components>
</Entity>
<Entity>
</Entity>-->
<!--<Entity>
<Components>
<c:Player>
<Velocity X="0" Y="0" Z="0"/>
@@ -42,8 +45,10 @@
<c:Model>
<Resource>Models/Core/UnitCube.obj</Resource>
</c:Model>
<c:AABB>
</c:AABB>
</Components>
</Entity>
</Entity>-->
<Entity>
<Components>
<c:Transform>
+2
View File
@@ -15,6 +15,8 @@
<xs:element ref="c:Test" minOccurs="0"/>
<xs:element ref="c:RaptorCopter" minOccurs="0"/>
<xs:element ref="c:Player" minOccurs="0"/>
<xs:element ref="c:Health" minOccurs="0"/>
<xs:element ref="c:PointLight" minOccurs="0"/>
</xs:all>
</xs:complexType>
</xs:element>
+154
View File
@@ -0,0 +1,154 @@
#version 430
//in uvec3 gl_NumWorkGroups; //contains the number of workgroups that have been dispatched to a compute shader
//in uvec3 gl_WorkGroupID; //contains the index of the workgroup currently being operated on by a compute shader
//in uvec3 gl_LocalInvocationID; //contains the index of work item currently being operated on by a compute shader
//in uvec3 gl_GlobalInvocationID; //contains the global index of work item currently being operated on by a compute shader
//in uint gl_LocalInvocationIndex; //contains the local linear index of work item currently being operated on by a compute shader
#define MAX_LIGHTS_PER_TILE 200
#define NUM_TILES 3600
#define TILE_SIZE 16
uniform mat4 V;
struct Plane {
vec3 Normal;
float d;
};
struct Frustum {
Plane Planes[4];
};
layout (std430, binding = 0) buffer FrustumBuffer
{
Frustum Data[];
} Frustums;
struct PointLight {
vec4 Position;
vec4 Color;
float Radius;
float Intensity;
float Falloff;
float Padding;
};
layout (std430, binding = 1) buffer LightBuffer
{
PointLight List[];
} PointLights;
struct LightGrid {
float Start;
float Amount;
vec2 Padding;
};
layout (std430, binding = 2) buffer LightGridBuffer
{
LightGrid Data[];
} LightGrids;
layout (std430, binding = 3) buffer LightOffsetBuffer
{
int LightOffset[];
};
layout (std430, binding = 4) buffer LightIndexBuffer
{
float LightIndex[];
};
shared int GroupLightCount;
shared int GroupLightIndexStartOffset;
shared int GroupLightIndex[MAX_LIGHTS_PER_TILE];
shared Frustum GroupFrustum;
int GroupIndex;
bool SphereInsidePlane(vec3 center, float radius, Plane plane)
{
return dot(plane.Normal, center) - plane.d > -radius;
}
bool SphereInsideFrustrum(vec3 center, float radius, Frustum frustum/*, float zNear, float zFar*/)
{
//Check depth here
//if ( sphere.c.z - sphere.r > zNear || sphere.c.z + sphere.r < zFar )
//{
// result = false;
//}
for (int i =0; i < 4; i++)
{
if(! SphereInsidePlane(center, radius, frustum.Planes[i]))
{
return false;
}
}
return true;
}
void AppendLight(int li)
{
int index;
index = atomicAdd(GroupLightCount, 1);
if( index < MAX_LIGHTS_PER_TILE )
{
GroupLightIndex[index] = int(li);
}
}
layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
void main ()
{
GroupIndex = int(gl_WorkGroupID.x + (gl_WorkGroupID.y * 80));
if(gl_LocalInvocationIndex == 0)
{
GroupLightCount = 0;
GroupFrustum = Frustums.Data[GroupIndex];
}
barrier();
memoryBarrierShared();
for(int i = int(gl_LocalInvocationIndex); i < PointLights.List.length(); i += TILE_SIZE*TILE_SIZE)
{
PointLight light = PointLights.List[i];
//if pointlight
//Pos i view antagligen
if(SphereInsideFrustrum( vec3(V * light.Position), light.Radius, GroupFrustum))
{
//TODO: Fix transparent and opaque list, and depth test.
AppendLight( i );
}
//if conelight
//if directional
}
barrier();
memoryBarrierShared();
if(gl_LocalInvocationIndex == 0)
{
GroupLightIndexStartOffset = atomicAdd(LightOffset[0], GroupLightCount);
LightGrids.Data[GroupIndex].Start = GroupLightIndexStartOffset;
LightGrids.Data[GroupIndex].Amount = GroupLightCount;
}
barrier();
for (uint i = gl_LocalInvocationIndex; i < GroupLightCount; i += TILE_SIZE * TILE_SIZE )
{
LightIndex[GroupLightIndexStartOffset + i] = GroupLightIndex[i];
}
}
+132
View File
@@ -0,0 +1,132 @@
#version 430
uniform mat4 M;
uniform mat4 V;
uniform mat4 P;
uniform vec4 Color;
uniform sampler2D texture0;
#define TILE_SIZE 16
struct PointLight {
vec4 Position;
vec4 Color;
float Radius;
float Intensity;
float Falloff;
float Padding;
};
layout (std430, binding = 1) buffer LightBuffer
{
PointLight List[];
} PointLights;
struct LightGrid {
float Start;
float Amount;
vec2 Padding;
};
layout (std430, binding = 2) buffer LightGridBuffer
{
LightGrid Data[];
} LightGrids;
layout (std430, binding = 4) buffer LightIndexBuffer
{
float LightIndex[];
};
in VertexData{
vec3 Position;
vec3 Normal;
vec2 TextureCoordinate;
vec4 DiffuseColor;
}Input;
out vec4 fragmentColor;
vec4 scene_ambient = vec4(0.3,0.3,0.3,1);
struct LightResult {
vec4 Diffuse;
vec4 Specular;
};
float CalcAttenuation(float radius, float dist) {
return 1.0 - smoothstep(radius * 0.3, radius, dist);
}
vec4 CalcSpecular(vec4 lightColor, vec4 viewVec, vec4 lightVec, vec4 normal) {
vec4 R = normalize( reflect(-lightVec, normal));
float RdotV = max( dot(R, viewVec), 0.0);
return lightColor * pow(RdotV, 90.0);
}
vec4 CalcDiffuse(vec4 lightColor, vec4 lightVec, vec4 normal) {
float power = max( dot(normal, lightVec), 0.0);
return lightColor * power;
}
LightResult CalcPointLight(vec4 lightPos, float lightRadius, vec4 lightColor, float intensity, vec4 viewVec, vec4 position, vec4 normal)
{
vec4 L = lightPos - position;
float dist = length(L);
L = normalize(L);
float attenuation = CalcAttenuation(lightRadius, dist);
LightResult result;
result.Diffuse = CalcDiffuse(lightColor, L, normal) * attenuation * intensity;
result.Specular = CalcSpecular(lightColor, viewVec, L, normal) * attenuation * intensity;
return result;
}
void main()
{
vec4 texel = texture2D(texture0, Input.TextureCoordinate);
vec4 position = V * M * vec4(Input.Position, 1.0);
vec4 normal = V * vec4(Input.Normal, 0.0);
vec4 viewVec = normalize(-position);
vec2 tilePos;
tilePos.x = int(gl_FragCoord.x/16);
tilePos.y = int(gl_FragCoord.y/16);
LightResult totalLighting;
totalLighting.Diffuse = scene_ambient;
int currentTile = int(floor(gl_FragCoord.x/TILE_SIZE) + (floor(gl_FragCoord.y/TILE_SIZE) * 80));
int start = int(LightGrids.Data[currentTile].Start);
int amount = int(LightGrids.Data[currentTile].Amount);
//for(int i = 0; i < 3; i++)
for(int i = start; i < start + amount; i++)
{
int l = int(LightIndex[i]);
LightResult result = CalcPointLight(V * PointLights.List[l].Position, PointLights.List[l].Radius, PointLights.List[l].Color, PointLights.List[l].Intensity, viewVec, position, normal);
totalLighting.Diffuse += result.Diffuse;
totalLighting.Specular += result.Specular;
}
fragmentColor += Input.DiffuseColor * (totalLighting.Diffuse + totalLighting.Specular) * texel * Color;
//fragmentColor += Input.DiffuseColor * (totalLighting.Diffuse) * texel * Color;
//fragmentColor += vec4(0.0, LightGrids.Data[currentTile].Amount/3.0, 0, 1);
//fragmentColor = texel * Input.DiffuseColor * Color;
if(int(gl_FragCoord.x)%16 == 0 || int(gl_FragCoord.y)%16 == 0 )
{
//fragmentColor += vec4(0.5, 0, 0, 0);
} else {
//fragmentColor += vec4(LightGrids.Data[int(tilePos.x + tilePos.y*80)].Amount/3.0, 0, 0, 1);
}
}
+34
View File
@@ -0,0 +1,34 @@
#version 430
uniform mat4 M;
uniform mat4 V;
uniform mat4 P;
layout(location = 0) in vec3 Position;
layout(location = 1) in vec3 Normal;
layout(location = 2) in vec3 Tangent;
layout(location = 3) in vec3 BiTangent;
layout(location = 4) in vec2 TextureCoords;
layout(location = 5) in vec4 DiffuseVertexColor;
layout(location = 6) in vec4 SpecularVertexColor;
layout(location = 7) in vec4 BoneIndices1;
layout(location = 8) in vec4 BoneIndices2;
layout(location = 9) in vec4 BoneWeights1;
layout(location = 10) in vec4 BoneWeights2;
out VertexData{
vec3 Position;
vec3 Normal;
vec2 TextureCoordinate;
vec4 DiffuseColor;
}Output;
void main()
{
gl_Position = P*V*M * vec4(Position, 1.0);
Output.Position = Position;
Output.TextureCoordinate = TextureCoords;
Output.Normal = Normal;
Output.DiffuseColor = DiffuseVertexColor;
}
+76
View File
@@ -0,0 +1,76 @@
#version 430
#define TILE_SIZE 16
#define NUM_TILES 3600
uniform mat4 P;
uniform vec2 ScreenDimensions;
struct Plane {
vec3 Normal;
float d;
};
struct Frustum {
Plane Planes[4];
};
layout (std430, binding = 0) buffer FrustumBuffer
{
Frustum Data[];
} Frustums;
vec4 ConvertToView(vec4 ScreenCoords)
{
vec2 normalizedScreenCoords = ScreenCoords.xy / ScreenDimensions;
vec4 clipSpace = vec4( vec2(normalizedScreenCoords.x, normalizedScreenCoords.y) * 2.0 - 1.0, ScreenCoords.z, ScreenCoords.w);
vec4 view = inverse(P) * clipSpace;
view = view / view.w;
return view;
}
Plane ComputePlane( vec3 p0, vec3 p1, vec3 p2 )
{
Plane plane;
vec3 v0 = p1 - p0;
vec3 v2 = p2 - p0;
plane.Normal = normalize( cross( v0, v2 ) );
plane.d = dot( vec3(plane.Normal), p0 ); // Always 0 probably
return plane;
}
layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
void main ()
{
//Top-Left = 0 | Top-Right = 1
//Bottom-Left = 2 | Bottom-Right = 3
vec4 ScreenCoords[4];
ScreenCoords[0] = vec4(gl_GlobalInvocationID.x * TILE_SIZE, (gl_GlobalInvocationID.y + 1) * TILE_SIZE, -1.0, 1.0);
ScreenCoords[1] = vec4((gl_GlobalInvocationID.x + 1) * TILE_SIZE, (gl_GlobalInvocationID.y + 1) * TILE_SIZE, -1.0, 1.0);
ScreenCoords[2] = vec4(gl_GlobalInvocationID.x * TILE_SIZE, (gl_GlobalInvocationID.y) * TILE_SIZE, -1.0, 1.0);
ScreenCoords[3] = vec4((gl_GlobalInvocationID.x + 1) * TILE_SIZE, (gl_GlobalInvocationID.y) * TILE_SIZE, -1.0, 1.0);
vec3 ViewVectors[4];
for(int i = 0; i < 4; i++) {
ViewVectors[i] = vec3(ConvertToView(ScreenCoords[i]));
}
vec3 EyePos = vec3(0.0, 0.0 ,0.0);
Frustum f;
f.Planes[0] = ComputePlane(EyePos, ViewVectors[2], ViewVectors[0]); // left plane
f.Planes[1] = ComputePlane(EyePos, ViewVectors[1], ViewVectors[3]); // right plane
f.Planes[2] = ComputePlane(EyePos, ViewVectors[0], ViewVectors[1]); // top plane
f.Planes[3] = ComputePlane(EyePos, ViewVectors[3], ViewVectors[2]); // bottom plane
if ( gl_GlobalInvocationID.x < ScreenDimensions.x / TILE_SIZE && gl_GlobalInvocationID.y < ScreenDimensions.y / TILE_SIZE ) { // inside the screen
Frustums.Data[gl_GlobalInvocationID.x + gl_GlobalInvocationID.y*80] = f;
}
}
+18 -2
View File
@@ -60,7 +60,6 @@ file(GLOB SOURCE_FILES_Rendering_Util
"${INCLUDE_PATH}/Rendering/Util/*.h"
"Rendering/Util/*.cpp"
)
source_group(Rendering FILES ${SOURCE_FILES_Rendering})
source_group(Rendering\\Util FILES ${SOURCE_FILES_Rendering_Util})
@@ -70,6 +69,18 @@ file(GLOB SOURCE_FILES_GUI
)
source_group(GUI FILES ${SOURCE_FILES_GUI})
file(GLOB SOURCE_FILES_Collision
"${INCLUDE_PATH}/Collision/*.h"
"Collision/*.cpp"
)
source_group(Collision FILES ${SOURCE_FILES_Collision})
file(GLOB SOURCE_FILES_Editor
"${INCLUDE_PATH}/Editor/*.h"
"Editor/*.cpp"
)
source_group(Editor FILES ${SOURCE_FILES_Editor})
set(SOURCE_FILES
${SOURCE_FILES_Core}
${SOURCE_FILES_Core_Util}
@@ -78,6 +89,11 @@ set(SOURCE_FILES
${SOURCE_FILES_GUI}
${SOURCE_FILES_Rendering}
${SOURCE_FILES_Rendering_Util}
${SOURCE_FILES_Collision}
${CMAKE_SOURCE_DIR}/deps/include/imgui/imgui.cpp
${CMAKE_SOURCE_DIR}/deps/include/imgui/imgui_draw.cpp
${CMAKE_SOURCE_DIR}/deps/include/imgui/imgui_demo.cpp
${SOURCE_FILES_Editor}
)
set(LIBRARIES
@@ -103,4 +119,4 @@ target_link_libraries(Engine
${LIBRARIES}
)
#set_target_properties(Engine PROPERTIES COTIRE_CXX_PREFIX_HEADER_INIT "${INCLUDE_PATH}/PrecompiledHeader.h")
#cotire(Engine)
#cotire(Engine)
+282
View File
@@ -0,0 +1,282 @@
#include <algorithm>
#include "Collision/Collision.h"
#include "Engine/GLM.h"
#include "Core/World.h"
#include "Rendering/Model.h"
namespace Collision
{
//note: this one hasnt been delta adjusted like RayVsAABB has
bool RayAABBIntr(const Ray& ray, const AABB& box)
{
glm::vec3 w = 75.0f * ray.Direction();
glm::vec3 v = glm::abs(w);
glm::vec3 c = ray.Origin() - box.Center() + w;
glm::vec3 half = box.HalfSize();
if (abs(c.x) > v.x + half.x) {
return false;
}
if (abs(c.y) > v.y + half.y) {
return false;
}
if (abs(c.z) > v.z + half.z) {
return false;
}
if (abs(c.y*w.z - c.z*w.y) > half.y*v.z + half.z*v.y) {
return false;
}
if (abs(c.x*w.z - c.z*w.x) > half.x*v.z + half.z*v.x) {
return false;
}
return !(abs(c.x*w.y - c.y*w.x) > half.x*v.y + half.y*v.x);
}
bool RayVsAABB(const Ray& ray, const AABB& box)
{
float dummy;
return RayVsAABB(ray, box, dummy);
}
bool RayVsAABB(const Ray& ray, const AABB& box, float& outDistance)
{
glm::vec3 invdir = 1.0f / ray.Direction();
glm::vec3 origin = ray.Origin();
float t1 = (box.MinCorner().x - origin.x)*invdir.x;
float t2 = (box.MaxCorner().x - origin.x)*invdir.x;
float t3 = (box.MinCorner().y - origin.y)*invdir.y;
float t4 = (box.MaxCorner().y - origin.y)*invdir.y;
float t5 = (box.MinCorner().z - origin.z)*invdir.z;
float t6 = (box.MaxCorner().z - origin.z)*invdir.z;
float tmin = std::max(std::max(std::min(t1, t2), std::min(t3, t4)), std::min(t5, t6));
float tmax = std::min(std::min(std::max(t1, t2), std::max(t3, t4)), std::max(t5, t6));
//if (tmax < 0 || tmin > tmax)
//if tmin,tmax are almost the same (i.e. hitting exactly in the corner) then tmin might be slightly
//greater than tmax becuase of floating-precision problems. fixed by adding a small delta to tmax
if (tmax < 0 || tmin>(tmax + 0.0001f))
return false;
outDistance = (tmin > 0) ? tmin : tmax;
return true;
}
bool AABBVsAABB(const AABB& a, const AABB& b)
{
const glm::vec3& aCenter = a.Center();
const glm::vec3& bCenter = b.Center();
const glm::vec3& aHSize = a.HalfSize();
const glm::vec3& bHSize = b.HalfSize();
//Test will probably exit because of the X and Z axes more often, so test them first.
if (abs(aCenter[0] - bCenter[0]) > (aHSize[0] + bHSize[0])) {
return false;
}
if (abs(aCenter[2] - bCenter[2]) > (aHSize[2] + bHSize[2])) {
return false;
}
return (abs(aCenter[1] - bCenter[1]) <= (aHSize[1] + bHSize[1]));
}
bool AABBVsAABB(const AABB& a, const AABB& b, glm::vec3& minimumTranslation)
{
minimumTranslation = glm::vec3(0, 0, 0);
const glm::vec3& aMax = a.MaxCorner();
const glm::vec3& bMax = b.MaxCorner();
const glm::vec3& aMin = a.MinCorner();
const glm::vec3& bMin = b.MinCorner();
const glm::vec3& bSize = b.Size();
const glm::vec3& aSize = a.Size();
float minOffset = INFINITY;
float off;
auto axisesIntersecting = glm::tvec3<bool, glm::highp>(false, false, false);
for (int i = 0; i < 3; ++i) {
off = bMax[i] - aMin[i];
if (off > 0 && off < bSize[i] + aSize[i]) {
if (off < minOffset) {
minimumTranslation = glm::vec3();
minimumTranslation[i] = minOffset = off;
}
axisesIntersecting[i] = true;
}
off = aMax[i] - bMin[i];
if (off > 0 && off < bSize[i] + aSize[i]) {
if (off < minOffset) {
minOffset = off;
minimumTranslation = glm::vec3();
minimumTranslation[i] = -off;
}
axisesIntersecting[i] = true;
}
}
return glm::all(axisesIntersecting);
}
bool RayVsModel(const Ray& ray,
const std::vector<RawModel::Vertex>& modelVertices,
const std::vector<unsigned int>& modelIndices)
{
for (int i = 0; i < modelIndices.size(); ++i) {
glm::vec3 v0 = modelVertices[modelIndices[i]].Position;
glm::vec3 e1 = modelVertices[modelIndices[++i]].Position - v0; //v1 - v0
glm::vec3 e2 = modelVertices[modelIndices[++i]].Position - v0; //v2 - v0
glm::vec3 m = ray.Origin() - v0;
glm::vec3 MxE1 = glm::cross(m, e1);
glm::vec3 DxE2 = glm::cross(ray.Direction(), e2);
float DetInv = glm::dot(e1, DxE2);
if (std::abs(DetInv) < FLT_EPSILON) {
continue;
}
DetInv = 1.0f / DetInv;
float u = glm::dot(m, DxE2) * DetInv;
float v = glm::dot(ray.Direction(), MxE1) * DetInv;
//u,v can be very close to 0 but still negative sometimes. added a deltafactor to compensate for that problem
if ((u + 0.001f) < 0 || (v + 0.001f) < 0 || 1 < u + v) {
continue;
}
//Here, u and v are positive, u+v <= 1, and if distance is positive - triangle is hit.
if (0 <= glm::dot(e2, MxE1) * DetInv) {
return true;
}
}
return false;
}
bool RayVsModel(const Ray& ray,
const std::vector<RawModel::Vertex>& modelVertices,
const std::vector<unsigned int>& modelIndices,
float& outDistance,
float& outUCoord,
float& outVCoord)
{
outDistance = INFINITY;
bool hit = false;
for (int i = 0; i < modelIndices.size(); ++i) {
glm::vec3 v0 = modelVertices[modelIndices[i]].Position;
glm::vec3 e1 = modelVertices[modelIndices[++i]].Position - v0; //v1 - v0
glm::vec3 e2 = modelVertices[modelIndices[++i]].Position - v0; //v2 - v0
glm::vec3 m = ray.Origin() - v0;
glm::vec3 MxE1 = glm::cross(m, e1);
glm::vec3 DxE2 = glm::cross(ray.Direction(), e2);//pVec
float DetInv = glm::dot(e1, DxE2);
if (std::abs(DetInv) < FLT_EPSILON) {
continue;
}
DetInv = 1.0f / DetInv;
float dist = glm::dot(e2, MxE1) * DetInv;
if (dist >= outDistance) {
continue;
}
float u = glm::dot(m, DxE2) * DetInv;
float v = glm::dot(ray.Direction(), MxE1) * DetInv;
//u,v can be very close to 0 but still negative sometimes. added a deltafactor to compensate for that problem
//If u and v are positive, u+v <= 1, dist is positive, and less than closest.
if (0 <= (u + 0.001f) && 0 <= (v + 0.001f) && u + v <= 1 && 0 <= dist) {
outDistance = dist;
outUCoord = u;
outVCoord = v;
hit = true;
}
}
return hit;
}
bool RayVsModel(const Ray& ray,
const std::vector<RawModel::Vertex>& modelVertices,
const std::vector<unsigned int>& modelIndices,
glm::vec3& outHitPosition)
{
float u;
float v;
float dist;
bool hit = RayVsModel(ray, modelVertices, modelIndices, dist, u, v);
outHitPosition = ray.Origin() + dist * ray.Direction();
return hit;
}
bool IsSameBoxProbably(const AABB& first, const AABB& second, const float epsilon)
{
const glm::vec3& ma1 = first.MaxCorner();
const glm::vec3& ma2 = first.MaxCorner();
const glm::vec3& mi1 = second.MinCorner();
const glm::vec3& mi2 = second.MinCorner();
return (std::abs(ma1.x - ma2.x) < epsilon) &&
(std::abs(mi1.x - mi2.x) < epsilon) &&
(std::abs(ma1.z - ma2.z) < epsilon) &&
(std::abs(mi1.z - mi2.z) < epsilon) &&
(std::abs(ma1.y - ma2.y) < epsilon) &&
(std::abs(mi1.y - mi2.y) < epsilon);
}
bool attachAABBComponentFromModel(World* world, EntityID id)
{
if (!world->HasComponent(id, "Model")) {
return false;
}
ComponentWrapper model = world->GetComponent(id, "Model");
ComponentWrapper collision = world->AttachComponent(id, "AABB");
Model* modelRes = ResourceManager::Load<Model>(model["Resource"]);
if (modelRes == nullptr) {
return false;
}
glm::mat4 modelMatrix = modelRes->m_Matrix;
glm::vec3 mini = glm::vec3(INFINITY, INFINITY, INFINITY);
glm::vec3 maxi = glm::vec3(-INFINITY, -INFINITY, -INFINITY);
for (const auto& v : modelRes->m_Vertices) {
const auto& wPos = modelMatrix * glm::vec4(v.Position.x, v.Position.y, v.Position.z, 1);
maxi.x = std::max(wPos.x, maxi.x);
maxi.y = std::max(wPos.y, maxi.y);
maxi.z = std::max(wPos.z, maxi.z);
mini.x = std::min(wPos.x, mini.x);
mini.y = std::min(wPos.y, mini.y);
mini.z = std::min(wPos.z, mini.z);
}
collision["BoxCenter"] = 0.5f * (maxi + mini);
collision["BoxSize"] = maxi - mini;
return true;
}
bool GetEntityBox(World* world, ComponentWrapper& AABBComponent, AABB& outBox)
{
ComponentWrapper& cTrans = world->GetComponent(AABBComponent.EntityID, "Transform");
ComponentWrapper model = world->GetComponent(AABBComponent.EntityID, "Model");
Model* modelRes = ResourceManager::Load<Model>(model["Resource"]);
outBox.CreateFromCenter(AABBComponent["BoxCenter"], AABBComponent["BoxSize"]);
glm::vec3 mini = outBox.MinCorner();
glm::vec3 maxi = outBox.MaxCorner();
if (modelRes == nullptr) {
return false;
}
glm::mat4 modelMatrix = modelRes->m_Matrix *
glm::translate(glm::mat4(), (glm::vec3)cTrans["Position"]) *
glm::scale((glm::vec3)cTrans["Scale"]);
outBox = AABB(modelMatrix * glm::vec4(mini.x, mini.y, mini.z, 1),
modelMatrix * glm::vec4(maxi.x, maxi.y, maxi.z, 1));
return true;
}
bool GetEntityBox(World* world, EntityID entity, AABB& outBox, bool forceBoxFromModel)
{
if (!world->HasComponent(entity, "AABB")) {
if (forceBoxFromModel) {
if (!attachAABBComponentFromModel(world, entity))
return false;
} else {
return false;
}
}
ComponentWrapper& cBox = world->GetComponent(entity, "AABB");
return GetEntityBox(world, cBox, outBox);
}
}
+40
View File
@@ -0,0 +1,40 @@
#include "Collision/Collision.h"
#include "Collision/CollisionSystem.h"
#include "Core/AABB.h"
void CollisionSystem::UpdateComponent(World * world, ComponentWrapper & cAABB, double dt)
{
//Right now, cAABB is a component attached to any entity that should be collideable.
AABB thisBox;
if (!Collision::GetEntityBox(world, cAABB, thisBox)) {
return;
}
//Press 'Z' to enable/disable collision.
if (zPress) {
return;
}
//Here, mover should be an object that moves, currently only players.
for (auto& mover : *world->GetComponents("Player")) {
if (cAABB.EntityID == mover.EntityID) {
continue;
}
AABB otherBox;
if (!Collision::GetEntityBox(world, mover.EntityID, otherBox)) {
continue;
}
glm::vec3 resolveTranslation;
if (Collision::AABBVsAABB(otherBox, thisBox, resolveTranslation)) {
ComponentWrapper& trans = world->GetComponent(mover.EntityID, "Transform");
//TODO: Special treatment if both are movers.
trans["Position"] = (glm::vec3)trans["Position"] + resolveTranslation;
}
}
}
bool CollisionSystem::OnKeyUp(const Events::KeyUp & event)
{
if (event.KeyCode == GLFW_KEY_Z) {
zPress = !zPress;
}
return false;
}
+81
View File
@@ -0,0 +1,81 @@
#include "Collision/TriggerSystem.h"
#include "Collision/Collision.h"
#include "Core/AABB.h"
#include "Rendering/Model.h"
void TriggerSystem::UpdateComponent(World* world, ComponentWrapper& trigger, double dt)
{
//Currently only players can trigger things.
auto players = world->GetComponents("Player");
if (players == nullptr) {
return;
}
EntityID tId = trigger.EntityID;
AABB triggerBox;
//The trigger *should* have a bounding box, or something, to test against so it can be triggered.
if (!Collision::GetEntityBox(world, tId, triggerBox, true)) {
return;
}
for (auto& pc : *players) {
EntityID pId = pc.EntityID;
AABB playerBox;
//The player can't trigger anything without an AABB.
if (!Collision::GetEntityBox(world, pId, playerBox, true)) {
continue;
}
if (!Collision::AABBVsAABB(triggerBox, playerBox)) {
//Entity is not touching the trigger,
//Throw event if it was previously.
if (throwLeaveIfWasInTrigger(m_EntitiesTouchingTrigger[tId], pId, tId)) {
continue;
}
//This only occurs if the entity was completely inside the trigger one frame,
//then completely outside the trigger, e.g. when dying and respawning.
throwLeaveIfWasInTrigger(m_EntitiesCompletelyInTrigger[tId], pId, tId);
} else {
//Entity is at least touching the trigger.
AABB completelyInsideBox;
completelyInsideBox.CreateFromCenter(triggerBox.Center(), triggerBox.Size() - 2.0f * playerBox.Size());
if (Collision::AABBVsAABB(completelyInsideBox, playerBox) &&
glm::all(glm::greaterThan(triggerBox.Size(), playerBox.Size()))) {
//Entity is completely inside the trigger.
//If it was only touching before, it is erased.
m_EntitiesTouchingTrigger[tId].erase(pId);
std::unordered_set<EntityID>& completeSet = m_EntitiesCompletelyInTrigger[tId];
if (completeSet.count(pId) == 0) {
//If it wasn't completely in the trigger, throw Enter and add to the set.
completeSet.insert(pId);
publish<Events::TriggerEnter>(pId, tId);
}
} else {
//Entity is only touching the trigger.
std::unordered_set<EntityID>& touchSet = m_EntitiesTouchingTrigger[tId];
std::unordered_set<EntityID>& completeSet = m_EntitiesCompletelyInTrigger[tId];
const auto& it = completeSet.find(pId);
//If it was completely inside before.
if (it != completeSet.end()) {
completeSet.erase(it);
touchSet.insert(pId);
//If it was completely outside before.
} else if (touchSet.count(pId) == 0) {
publish<Events::TriggerTouch>(pId, tId);
touchSet.insert(pId);
}
//Else, it was touching the trigger last frame too and nothing is done.
}
}
}
}
bool TriggerSystem::throwLeaveIfWasInTrigger(std::unordered_set<EntityID>& triggerSet, EntityID pId, EntityID tId)
{
const auto& it = triggerSet.find(pId);
if (it != triggerSet.end()) {
//If it was in the trigger, but not anymore, throw leaveEvent and erase from the set.
triggerSet.erase(it);
publish<Events::TriggerLeave>(pId, tId);
return true;
}
return false;
}
+34
View File
@@ -0,0 +1,34 @@
#include "Core/AABB.h"
#include "Common.h"
AABB::AABB(const glm::vec3& minPos, const glm::vec3& maxPos)
: m_MinCorner(minPos)
, m_MaxCorner(maxPos)
, m_Center(0.5f * (maxPos + minPos))
, m_HalfSize(0.5f * (maxPos - minPos))
{
DEBUG_IF(glm::any(glm::lessThan(m_MaxCorner, m_MinCorner))) {
LOG_WARNING("AABB maxCorner coordinates are not greater than minCorner");
m_MaxCorner.x = glm::max(m_MaxCorner.x, m_MinCorner.x);
m_MinCorner.x = glm::min(m_MaxCorner.x, m_MinCorner.x);
m_MaxCorner.y = glm::max(m_MaxCorner.y, m_MinCorner.y);
m_MinCorner.y = glm::min(m_MaxCorner.y, m_MinCorner.y);
m_MaxCorner.z = glm::max(m_MaxCorner.z, m_MinCorner.z);
m_MinCorner.z = glm::min(m_MaxCorner.z, m_MinCorner.z);
}
}
AABB::AABB(const glm::vec4& minPos, const glm::vec4& maxPos)
: AABB(glm::vec3(minPos), glm::vec3(maxPos))
{}
void AABB::CreateFromCenter(const glm::vec3& center, const glm::vec3& size)
{
m_Center = center;
m_HalfSize = 0.5f * size;
m_MinCorner = m_Center - m_HalfSize;
m_MaxCorner = m_Center + m_HalfSize;
}
AABB::~AABB()
{}
+8 -2
View File
@@ -19,7 +19,7 @@ bool ComponentPoolForwardIterator::operator!=(const ComponentPoolForwardIterator
return m_MemoryPoolIterator != other.m_MemoryPoolIterator;
}
ComponentPoolForwardIterator& ComponentPoolForwardIterator::operator++(int)
ComponentPoolForwardIterator ComponentPoolForwardIterator::operator++(int)
{
ComponentPoolForwardIterator copyIter(*this);
operator++();
@@ -50,10 +50,16 @@ ComponentWrapper ComponentPool::GetByEntity(EntityID ent)
return ComponentWrapper(m_ComponentInfo, m_EntityToComponent.at(ent));
}
bool ComponentPool::KnowsEntity(EntityID ent)
{
return m_EntityToComponent.find(ent) != m_EntityToComponent.end();
}
void ComponentPool::Delete(ComponentWrapper& wrapper)
{
m_EntityToComponent.erase(wrapper.EntityID);
m_Pool.Free(wrapper.Data);
m_Pool.Free(wrapper.Data - sizeof(EntityID));
}
ComponentPool::iterator ComponentPool::begin() const
+48 -34
View File
@@ -415,6 +415,7 @@ std::size_t EntityXMLFile::getTypeStride(std::string typeName)
std::map<std::string, size_t> typeStrides{
{ "bool", sizeof(bool) },
{ "int", sizeof(int) },
{ "float", sizeof(float) },
{ "double", sizeof(double) },
{ "string", sizeof(std::string) },
{ "Vector", sizeof(glm::vec3) },
@@ -430,12 +431,12 @@ float EntityXMLFile::getFloatAttribute(const xercesc::DOMElement* element, const
{
using namespace xercesc;
XSValue::Status status;
XSValue* val = XSValue::getActualValue(element->getAttribute(XSTR(attribute)), xercesc::XSValue::DataType::dt_float, status);
XSValue* val = XSValue::getActualValue(element->getAttribute(XSTR(attribute)), xercesc::XSValue::DataType::dt_double, status);
if (val == nullptr) {
LOG_ERROR("Element \"%s\" doesn't have an \"%s\" attribute!", XSTR(element->getTagName()), attribute);
return 0.f;
} else {
return val->fData.fValue.f_float;
return static_cast<float>(val->fData.fValue.f_double);
}
}
@@ -443,39 +444,52 @@ void EntityXMLFile::writeData(const xercesc::DOMElement* element, std::string ty
{
using namespace xercesc;
XSValue::DataType dataType = XSValue::getDataType(XSTR(typeName.c_str()));
if (dataType == XSValue::DataType::dt_MAXCOUNT) {
if (typeName == "Vector") {
glm::vec3 vec;
vec.x = getFloatAttribute(element, "X");
vec.y = getFloatAttribute(element, "Y");
vec.z = getFloatAttribute(element, "Z");
memcpy(outData, reinterpret_cast<char*>(&vec), getTypeStride(typeName));
} else if (typeName == "Color") {
glm::vec4 vec;
vec.r = getFloatAttribute(element, "R");
vec.g = getFloatAttribute(element, "G");
vec.b = getFloatAttribute(element, "B");
vec.a = getFloatAttribute(element, "A");
memcpy(outData, reinterpret_cast<char*>(&vec), getTypeStride(typeName));
} else if (typeName == "Quaternion") {
glm::quat q;
q.x = getFloatAttribute(element, "X");
q.y = getFloatAttribute(element, "Y");
q.z = getFloatAttribute(element, "Z");
q.w = getFloatAttribute(element, "W");
memcpy(outData, reinterpret_cast<char*>(&q), getTypeStride(typeName));
}
} else if (dataType == XSValue::DataType::dt_string) {
char* str = XMLString::transcode(element->getTextContent());
std::string standardString(str);
new (outData) std::string(str);
XMLString::release(&str);
//memcpy(outData, reinterpret_cast<char*>(&standardString), getTypeStride(typeName));
} else {
if (typeName == "Vector") {
glm::vec3 vec;
vec.x = getFloatAttribute(element, "X");
vec.y = getFloatAttribute(element, "Y");
vec.z = getFloatAttribute(element, "Z");
memcpy(outData, reinterpret_cast<char*>(&vec), getTypeStride(typeName));
} else if (typeName == "Color") {
glm::vec4 vec;
vec.r = getFloatAttribute(element, "R");
vec.g = getFloatAttribute(element, "G");
vec.b = getFloatAttribute(element, "B");
vec.a = getFloatAttribute(element, "A");
memcpy(outData, reinterpret_cast<char*>(&vec), getTypeStride(typeName));
} else if (typeName == "Quaternion") {
glm::quat q;
q.x = getFloatAttribute(element, "X");
q.y = getFloatAttribute(element, "Y");
q.z = getFloatAttribute(element, "Z");
q.w = getFloatAttribute(element, "W");
memcpy(outData, reinterpret_cast<char*>(&q), getTypeStride(typeName));
} else if (typeName == "float") {
XSValue::Status status;
XSValue* val = XSValue::getActualValue(element->getTextContent(), dataType, status);
memcpy(outData, reinterpret_cast<char*>(&val->fData.fValue), getTypeStride(typeName));
XSValue* val = XSValue::getActualValue(element->getTextContent(), xercesc::XSValue::DataType::dt_float, status);
memcpy(outData, reinterpret_cast<char*>(&val->fData.fValue.f_float), getTypeStride(typeName));
} else if (typeName == "double") {
XSValue::Status status;
XSValue* val = XSValue::getActualValue(element->getTextContent(), xercesc::XSValue::DataType::dt_double, status);
memcpy(outData, reinterpret_cast<char*>(&val->fData.fValue.f_double), getTypeStride(typeName));
} else if (typeName == "bool") {
XSValue::Status status;
XSValue* val = XSValue::getActualValue(element->getTextContent(), xercesc::XSValue::DataType::dt_boolean, status);
memcpy(outData, reinterpret_cast<char*>(&val->fData.fValue.f_bool), getTypeStride(typeName));
} else {
XSValue::DataType dataType = XSValue::getDataType(XSTR(typeName.c_str()));
if (dataType == XSValue::DataType::dt_string) {
char* str = XMLString::transcode(element->getTextContent());
std::string standardString(str);
new (outData) std::string(str);
XMLString::release(&str);
//memcpy(outData, reinterpret_cast<char*>(&standardString), getTypeStride(typeName));
} else {
//XSValue::Status status;
//XSValue* val = XSValue::getActualValue(element->getTextContent(), dataType, status);
//memcpy(outData, reinterpret_cast<char*>(&val->fData.fValue), getTypeStride(typeName));
LOG_WARNING("Unknown native data type: %s", typeName.c_str());
}
}
}
+26 -19
View File
@@ -2,21 +2,24 @@
BaseEventRelay::~BaseEventRelay()
{
if (m_Broker != nullptr) {
if (m_Broker != nullptr) {
m_Broker->Unsubscribe(*this);
}
}
}
void EventBroker::Unsubscribe(BaseEventRelay &relay) // ?
void EventBroker::Unsubscribe(BaseEventRelay& relay) // ?
{
if (m_IsProcessing) {
m_RelaysToUnsubscribe.push_back(&relay);
} else {
unsubscribeImmediate(relay);
}
auto identifier = std::make_tuple(relay.m_EventID, relay.m_ContextTypeName, relay.m_EventTypeName);
relay.m_Broker = nullptr;
if (m_IsProcessing) {
m_RelaysToUnsubscribe.push_back(identifier);
} else {
unsubscribeImmediate(identifier);
}
}
void EventBroker::Subscribe(BaseEventRelay &relay)
void EventBroker::Subscribe(BaseEventRelay& relay)
{
if (m_IsProcessing) {
m_RelaysToSubscribe.push_back(&relay);
@@ -38,12 +41,11 @@ int EventBroker::Process(std::string contextTypeName)
int eventsProcessed = 0;
for (auto &pair : *m_EventQueueRead) {
std::string &eventTypeName = pair.first;
std::string& eventTypeName = pair.first;
std::shared_ptr<Event> event = pair.second;
auto itpair = relays.equal_range(eventTypeName);
for (auto it2 = itpair.first; it2 != itpair.second; it2++)
{
for (auto it2 = itpair.first; it2 != itpair.second; it2++) {
std::string name = it2->first;
BaseEventRelay* relay = it2->second;
relay->Receive(event);
@@ -60,8 +62,8 @@ int EventBroker::Process(std::string contextTypeName)
m_RelaysToSubscribe.clear();
// Process pending unsubscriptions
for (auto& r : m_RelaysToUnsubscribe) {
unsubscribeImmediate(*r);
for (auto& identifier : m_RelaysToUnsubscribe) {
unsubscribeImmediate(identifier);
}
m_RelaysToUnsubscribe.clear();
@@ -81,21 +83,26 @@ void EventBroker::Clear()
void EventBroker::subscribeImmediate(BaseEventRelay& relay)
{
relay.m_Broker = this;
relay.m_EventID = m_NextEventID++;
m_ContextRelays[relay.m_ContextTypeName].insert(std::make_pair(relay.m_EventTypeName, &relay));
}
void EventBroker::unsubscribeImmediate(BaseEventRelay& relay)
void EventBroker::unsubscribeImmediate(std::tuple<EventID, ContextTypeName_t, EventTypeName_t> identifier)
{
auto contextIt = m_ContextRelays.find(relay.m_ContextTypeName);
EventID eventID;
ContextTypeName_t contextTypeName;
EventTypeName_t eventTypeName;
std::tie(eventID, contextTypeName, eventTypeName) = identifier;
auto contextIt = m_ContextRelays.find(contextTypeName);
if (contextIt == m_ContextRelays.end()) {
return;
}
auto eventRelays = contextIt->second;
auto itpair = eventRelays.equal_range(relay.m_EventTypeName);
auto itpair = eventRelays.equal_range(eventTypeName);
for (auto it = itpair.first; it != itpair.second; ++it) {
if (it->second == &relay) {
relay.m_Broker = nullptr;
if (it->second->m_EventID == eventID) {
eventRelays.erase(it);
break;
}
+51
View File
@@ -1,10 +1,17 @@
#include "Core/InputManager.h"
std::vector<unsigned int> InputManager::GLFWCharCallbackQueue;
std::vector<std::pair<double, double>> InputManager::GLFWScrollCallbackQueue;
std::vector<std::string> InputManager::GLFWDropCallbackQueue;
void InputManager::Initialize()
{
// TODO: Gamepad
//m_LastGamepadAxisState = std::array<GamepadAxisState, XUSER_MAX_COUNT>();
//m_LastGamepadButtonState = std::array<GamepadButtonState, XUSER_MAX_COUNT>();
glfwSetCharCallback(m_GLFWWindow, &InputManager::GLFWCharCallback);
glfwSetScrollCallback(m_GLFWWindow, &InputManager::GLFWScrollCallback);
glfwSetDropCallback(m_GLFWWindow, &InputManager::GLFWDropCallback);
EVENT_SUBSCRIBE_MEMBER(m_ELockMouse, &InputManager::OnLockMouse);
EVENT_SUBSCRIBE_MEMBER(m_EUnlockMouse, &InputManager::OnUnlockMouse);
@@ -36,6 +43,15 @@ void InputManager::Update(double dt)
}
}
// Keyboard text input
for (unsigned int& c : GLFWCharCallbackQueue) {
Events::KeyboardChar e;
e.Timestamp = glfwGetTime();
e.Char = c;
m_EventBroker->Publish(e);
}
GLFWCharCallbackQueue.clear();
// Mouse buttons
for (int i = 0; i <= GLFW_MOUSE_BUTTON_LAST; ++i) {
m_CurrentMouseState[i] = glfwGetMouseButton(m_GLFWWindow, i);
@@ -73,6 +89,22 @@ void InputManager::Update(double dt)
m_EventBroker->Publish(e);
}
// Mouse scroll
for (auto& pair : GLFWScrollCallbackQueue) {
Events::MouseScroll e;
std::tie(e.DeltaX, e.DeltaY) = pair;
m_EventBroker->Publish(e);
}
GLFWScrollCallbackQueue.clear();
// File drop
for (auto& path : GLFWDropCallbackQueue) {
Events::FileDropped e;
e.Path = path;
m_EventBroker->Publish(e);
}
GLFWDropCallbackQueue.clear();
// // Lock mouse while holding LMB
// if (m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT])
// {
@@ -196,6 +228,25 @@ void InputManager::PublishGamepadButtonIfChanged(int gamepadID, Gamepad::Button
}
}
void InputManager::GLFWCharCallback(GLFWwindow* window, unsigned int c)
{
GLFWCharCallbackQueue.push_back(c);
}
void InputManager::GLFWScrollCallback(GLFWwindow* window, double xoffset, double yoffset)
{
GLFWScrollCallbackQueue.push_back(std::make_pair(xoffset, yoffset));
}
void InputManager::GLFWDropCallback(GLFWwindow* window, int count, const char* paths[])
{
for (int i = 0; i < count; i++) {
GLFWDropCallbackQueue.push_back(std::string(paths[i]));
}
}
bool InputManager::OnLockMouse(const Events::LockMouse &event)
{
m_MouseLocked = true;
+377
View File
@@ -0,0 +1,377 @@
#include <vector>
#include <algorithm>
#include <bitset>
#include "Core/OctTree.h"
#include "Collision/Collision.h"
namespace
{
//To be able to sort nodes based on distance to ray origin.
struct ChildInfo
{
int Index;
float Distance;
};
bool isFirstLower(const ChildInfo& first, const ChildInfo& second)
{
return first.Distance < second.Distance;
}
}
OctTree::OctTree()
: OctTree(AABB(), 0)
{}
OctTree::OctTree(const AABB& octTreeBounds, int subDivisions)
: m_Root(new OctChild(octTreeBounds, subDivisions, m_StaticObjects, m_DynamicObjects))
, m_UpdatedOnce(false)
{}
OctTree::~OctTree()
{
delete m_Root;
}
void OctTree::AddDynamicObject(const AABB& box)
{
m_Root->AddDynamicObject(box);
m_DynamicObjects.push_back(box);
}
void OctTree::AddStaticObject(const AABB& box)
{
m_Root->AddStaticObject(box);
m_StaticObjects.push_back(box);
}
void OctTree::BoxesInSameRegion(const AABB& box, std::vector<AABB>& outBoxes)
{
falsifyObjectChecks();
m_Root->BoxesInSameRegion(box, outBoxes);
}
void OctTree::ClearObjects()
{
m_StaticObjects.clear();
m_DynamicObjects.clear();
m_Root->ClearObjects();
}
void OctTree::ClearDynamicObjects()
{
m_DynamicObjects.clear();
m_Root->ClearDynamicObjects();
}
bool OctTree::RayCollides(const Ray& ray, Output& data)
{
falsifyObjectChecks();
data.CollideDistance = -1;
return m_Root->RayCollides(ray, data);
}
bool OctTree::BoxCollides(const AABB& boxToTest, AABB& outBoxIntersected)
{
falsifyObjectChecks();
return m_Root->BoxCollides(boxToTest, outBoxIntersected);
}
void OctTree::falsifyObjectChecks()
{
for (auto& obj : m_StaticObjects) {
obj.Checked = false;
}
for (auto& obj : m_DynamicObjects) {
obj.Checked = false;
}
}
OctTree::OctChild::OctChild(const AABB& octTreeBounds,
int subDivisions,
std::vector<ContainedObject>& staticObjects,
std::vector<ContainedObject>& dynamicObjects)
: m_Box(octTreeBounds)
, m_StaticObjectsRef(staticObjects)
, m_DynamicObjectsRef(dynamicObjects)
{
if (subDivisions == 0) {
for (OctChild*& c : m_Children) {
c = nullptr;
}
} else {
--subDivisions;
for (int i = 0; i < 8; ++i) {
glm::vec3 minPos, maxPos;
const glm::vec3& parentMin = m_Box.MinCorner();
const glm::vec3& parentMax = m_Box.MaxCorner();
const glm::vec3& parentCenter = m_Box.Center();
std::bitset<3> bits(i);
//If child is 4,5,6,7.
if (bits.test(2)) {
minPos.x = parentCenter.x;
maxPos.x = parentMax.x;
} else {
minPos.x = parentMin.x;
maxPos.x = parentCenter.x;
}
//If child is 2,3,6,7
if (bits.test(1)) {
minPos.y = parentCenter.y;
maxPos.y = parentMax.y;
} else {
minPos.y = parentMin.y;
maxPos.y = parentCenter.y;
}
//If child is 1,3,5,7
if (bits.test(0)) {
minPos.z = parentCenter.z;
maxPos.z = parentMax.z;
} else {
minPos.z = parentMin.z;
maxPos.z = parentCenter.z;
}
m_Children[i] = new OctChild(AABB(minPos, maxPos), subDivisions, m_StaticObjectsRef, m_DynamicObjectsRef);
}
}
}
OctTree::OctChild::~OctChild()
{
for (OctChild*& c : m_Children) {
if (c != nullptr) {
delete c;
c = nullptr;
}
}
}
bool OctTree::OctChild::BoxCollides(const AABB& boxToTest, AABB& outBoxIntersected) const
{
if (hasChildren()) {
for (int i : childIndicesContainingBox(boxToTest)) {
if (m_Children[i]->BoxCollides(boxToTest, outBoxIntersected))
return true;
}
} else {
for (int i : m_StaticObjIndices) {
if (!m_StaticObjectsRef[i].Checked) {
const AABB& objBox = m_StaticObjectsRef[i].Box;
if (Collision::AABBVsAABB(boxToTest, objBox)) {
outBoxIntersected = objBox;
return true;
}
m_StaticObjectsRef[i].Checked = true;
}
}
for (int i : m_DynamicObjIndices) {
if (!m_DynamicObjectsRef[i].Checked) {
const AABB& objBox = m_DynamicObjectsRef[i].Box;
if (!Collision::IsSameBoxProbably(boxToTest, objBox) &&
Collision::AABBVsAABB(boxToTest, objBox)) {
outBoxIntersected = objBox;
return true;
}
m_DynamicObjectsRef[i].Checked = true;
}
}
}
return false;
}
bool OctTree::OctChild::RayCollides(const Ray& ray, Output& data) const
{
//If the node AABB is missed, everything it contains is missed.
if (Collision::RayAABBIntr(ray, m_Box)) {
//If the ray shoots the tree, and it is a parent to 8 children :o
if (hasChildren()) {
//Sort children according to their distance from the ray origin.
std::vector<ChildInfo> childInfos;
childInfos.reserve(8);
for (int i = 0; i < 8; ++i) {
childInfos.push_back({ i, glm::distance(ray.Origin(), m_Children[i]->m_Box.Center()) });
}
std::sort(childInfos.begin(), childInfos.end(), isFirstLower);
//Loop through the children, starting with the one closest to the ray origin. I.e the first to be hit.
for (const ChildInfo& info : childInfos) {
if (m_Children[info.Index]->RayCollides(ray, data)) {
return true;
}
}
} else {
//Check against boxes in the node.
float minDist = INFINITY;
bool intersected = false;
for (int i : m_StaticObjIndices) {
float dist;
//If we haven't tested against this object before, and the ray hits.
if (!m_StaticObjectsRef[i].Checked &&
Collision::RayVsAABB(ray, m_StaticObjectsRef[i].Box, dist)) {
minDist = std::min(dist, minDist);
intersected = true;
}
m_StaticObjectsRef[i].Checked = true;
}
for (int i : m_DynamicObjIndices) {
float dist;
//If we haven't tested against this object before, and the ray hits.
if (!m_DynamicObjectsRef[i].Checked &&
Collision::RayVsAABB(ray, m_DynamicObjectsRef[i].Box, dist)) {
minDist = std::min(dist, minDist);
intersected = true;
}
m_DynamicObjectsRef[i].Checked = true;
}
data.CollideDistance = minDist;
return intersected;
}
}
return false;
}
void OctTree::OctChild::AddDynamicObject(const AABB& box)
{
if (hasChildren()) {
for (auto i : childIndicesContainingBox(box)) {
m_Children[i]->AddDynamicObject(box);
}
} else {
//Since it hasn't been added yet to the real object list, the index is after the last =size.
m_DynamicObjIndices.push_back((int)m_DynamicObjectsRef.size());
}
}
void OctTree::OctChild::AddStaticObject(const AABB& box)
{
if (hasChildren()) {
for (auto i : childIndicesContainingBox(box)) {
m_Children[i]->AddStaticObject(box);
}
} else {
//Since it hasn't been added yet to the real object list, the index is after the last =size.
m_StaticObjIndices.push_back((int)m_StaticObjectsRef.size());
}
}
void OctTree::OctChild::BoxesInSameRegion(const AABB& box, std::vector<AABB>& outBoxes) const
{
if (hasChildren()) {
for (auto i : childIndicesContainingBox(box)) {
m_Children[i]->BoxesInSameRegion(box, outBoxes);
}
} else {
size_t startIndex = outBoxes.size();
int numDuplicates = 0;
outBoxes.resize(outBoxes.size() + m_StaticObjIndices.size() + m_DynamicObjIndices.size());
for (size_t i = 0; i < m_StaticObjIndices.size(); ++i){
ContainedObject& obj = m_StaticObjectsRef[m_StaticObjIndices[i]];
if (obj.Checked) {
++numDuplicates;
} else {
obj.Checked = true;
outBoxes[startIndex + i - numDuplicates] = obj.Box;
}
}
for (size_t i = 0; i < m_DynamicObjIndices.size(); ++i) {
ContainedObject& obj = m_DynamicObjectsRef[m_DynamicObjIndices[i]];
if (obj.Checked) {
++numDuplicates;
} else {
obj.Checked = true;
outBoxes[startIndex + i - numDuplicates] = obj.Box;
}
}
for (size_t i = 0; i < numDuplicates; ++i) {
outBoxes.pop_back();
}
}
}
void OctTree::OctChild::ClearObjects()
{
if (hasChildren()) {
for (OctChild*& c : m_Children) {
c->ClearObjects();
}
} else {
m_DynamicObjIndices.clear();
m_StaticObjIndices.clear();
}
}
void OctTree::OctChild::ClearDynamicObjects()
{
if (hasChildren()) {
for (OctChild*& c : m_Children) {
c->ClearObjects();
}
} else {
m_DynamicObjIndices.clear();
}
}
//: 3 7
//:
//: 2 6
//: |
//: 1 5 \ y
//: z
//: 0 4 0 x-->
//
// child: 0 1 2 3 4 5 6 7
// x : - - - - + + + +
// y : - - + + - - + +
// z : - + - + - + - +
int OctTree::OctChild::childIndexContainingPoint(const glm::vec3& point) const
{
const glm::vec3& c = m_Box.Center();
return (1 << 2) * (point.x >= c.x) | (1 << 1) * (point.y >= c.y) | (point.z >= c.z);
}
std::vector<int> OctTree::OctChild::childIndicesContainingBox(const AABB& box) const
{
int minInd = childIndexContainingPoint(box.MinCorner());
int maxInd = childIndexContainingPoint(box.MaxCorner());
//Because of the predictable ordering of the child indices,
//the number of bits set when xor:ing the indices will determine the number of children containing the box.
std::bitset<3> bits(minInd ^ maxInd);
switch (bits.count()) {
//Box contained completely in one child.
case 0:
return{ minInd };
//Two children.
case 1:
return{ minInd, maxInd };
//Four children.
case 2:
{
std::vector<int> ret;
//Bit-hax to calculate the correct 4 children containing the box.
//This works because of the childrens index determine what part of
//the dimensions they are responsible for (which octant).
bits.flip();
//At this point the bits necessarily have exactly one bit set.
for (int c = 0; c < 8; ++c) {
//If the child index have the same bit set as the bits, add box to it.
if (bits.to_ulong() & c) {
ret.push_back(c);
}
}
return ret;
}
case 3: //Eight children.
return{ 0,1,2,3,4,5,6,7 };
default:
return std::vector<int>();
}
}
inline bool OctTree::OctChild::hasChildren() const
{
return m_Children[0] != nullptr;
}
View File
+11 -5
View File
@@ -100,7 +100,7 @@ Resource* ResourceManager::Load(std::string resourceType, std::string resourceNa
LOG_WARNING("Hot-loading resource \"%s\"", resourceName.c_str());
}
return CreateResource(resourceType, resourceName, parent);
return CreateResource(resourceType, resourceName, parent);
}
Resource* ResourceManager::CreateResource(std::string resourceType, std::string resourceName, Resource* parent)
@@ -112,10 +112,16 @@ Resource* ResourceManager::CreateResource(std::string resourceType, std::string
}
// Call the factory function
Resource* resource = facIt->second(resourceName);
// Store IDs
resource->TypeID = GetTypeID(resourceType);
resource->ResourceID = GetNewResourceID(resource->TypeID);
Resource* resource;
try {
resource = facIt->second(resourceName);
// Store IDs
resource->TypeID = GetTypeID(resourceType);
resource->ResourceID = GetNewResourceID(resource->TypeID);
} catch (const std::exception& e) {
resource = nullptr;
LOG_ERROR("Failed to load resource \"%s\" of type \"%s\": %s", resourceName.c_str(), resourceType.c_str(), e.what());
}
// Cache
m_ResourceCache[std::make_pair(resourceType, resourceName)] = resource;
m_ResourceFromName[resourceName] = resource;
+65 -3
View File
@@ -11,12 +11,43 @@ EntityID World::CreateEntity(EntityID parent /*= 0*/)
{
EntityID newEntity = generateEntityID();
m_EntityParents[newEntity] = parent;
if (parent != 0) {
m_EntityChildren.insert(std::make_pair(parent, newEntity));
}
m_EntityChildren.insert(std::make_pair(parent, newEntity));
return newEntity;
}
void World::DeleteEntity(EntityID entity)
{
// Delete components
for (auto& pair : m_ComponentPools) {
auto& pool = pair.second;
if (pool->KnowsEntity(entity)) {
auto& c = pool->GetByEntity(entity);
pool->Delete(c);
}
}
// Loop through children
std::vector<EntityID> childrenToDelete;
auto children = m_EntityChildren.equal_range(entity);
for (auto it = children.first; it != children.second; ++it) {
childrenToDelete.push_back(it->second);
}
for (auto& child : childrenToDelete) {
DeleteEntity(child);
}
EntityID parent = m_EntityParents.at(entity);
m_EntityParents.erase(entity);
auto parentChildren = m_EntityChildren.equal_range(parent);
for (auto it = parentChildren.first; it != parentChildren.second; ++it) {
if (it->second == entity) {
m_EntityChildren.erase(it);
break;
}
}
}
void World::RegisterComponent(ComponentInfo& ci)
{
m_ComponentPools[ci.Name] = new ComponentPool(ci);
@@ -35,12 +66,27 @@ ComponentWrapper World::AttachComponent(EntityID entity, std::string componentTy
return c;
}
bool World::HasComponent(EntityID entity, std::string componentType)
{
ComponentPool* pool = m_ComponentPools.at(componentType);
return pool->KnowsEntity(entity);
}
ComponentWrapper World::GetComponent(EntityID entity, std::string componentType)
{
ComponentPool* pool = m_ComponentPools.at(componentType);
return pool->GetByEntity(entity);
}
void World::DeleteComponent(EntityID entity, std::string componentType)
{
ComponentPool* pool = m_ComponentPools.at(componentType);
ComponentWrapper c = pool->GetByEntity(entity);
return pool->Delete(c);
}
const ComponentPool* World::GetComponents(std::string componentType)
{
auto it = m_ComponentPools.find(componentType);
@@ -53,6 +99,22 @@ EntityID World::GetParent(EntityID entity)
return m_EntityParents.at(entity);
}
void World::SetParent(EntityID entity, EntityID parent)
{
EntityID lastParent = m_EntityParents.at(entity);
auto parentChildren = m_EntityChildren.equal_range(lastParent);
for (auto it = parentChildren.first; it != parentChildren.second; it++) {
if (it->second == entity) {
m_EntityChildren.erase(it);
break;
}
}
m_EntityParents[entity] = parent;
m_EntityChildren.insert(std::make_pair(parent, entity));
}
EntityID World::generateEntityID()
{
// TODO: Make EntityID generation smarter
+596
View File
@@ -0,0 +1,596 @@
#include "Editor/EditorSystem.h"
#define IMGUI_DEFINE_MATH_OPERATORS
#include <imgui/imgui_internal.h>
EditorSystem::EditorSystem(EventBroker* eventBroker, IRenderer* renderer)
: ImpureSystem(eventBroker)
, m_Renderer(renderer)
{
auto config = ResourceManager::Load<ConfigFile>("Config.ini");
m_Enabled = config->Get<bool>("Debug.EditorEnabled", false);
m_Visible = m_Enabled;
if (!m_Enabled) {
return;
}
EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &EditorSystem::OnInputCommand);
EVENT_SUBSCRIBE_MEMBER(m_EMousePress, &EditorSystem::OnMousePress);
EVENT_SUBSCRIBE_MEMBER(m_EMouseRelease, &EditorSystem::OnMouseRelease);
EVENT_SUBSCRIBE_MEMBER(m_EMouseMove, &EditorSystem::OnMouseMove);
EVENT_SUBSCRIBE_MEMBER(m_EPicking, &EditorSystem::OnPicking);
EVENT_SUBSCRIBE_MEMBER(m_EFileDropped, &EditorSystem::OnFileDropped);
}
void EditorSystem::Update(World* world, double dt)
{
m_World = world;
if (!m_Enabled) {
return;
}
if (!m_Visible) {
return;
}
updateWidget();
drawUI(world, dt);
// Clear drop queue if it wasn't handled by any UI element
if (!m_LastDroppedFile.empty()) {
m_LastDroppedFile = "";
}
}
bool EditorSystem::OnInputCommand(const Events::InputCommand& e)
{
if (e.Command == "ToggleEditor" && e.Value > 0) {
m_Visible = !m_Visible;
}
if (e.Command == "EditorToolMove" && e.Value > 0) {
setWidgetMode(WidgetMode::Translate);
}
if (e.Command == "EditorToolRotate" && e.Value > 0) {
setWidgetMode(WidgetMode::Rotate);
}
if (e.Command == "EditorToolScale" && e.Value > 0) {
setWidgetMode(WidgetMode::Scale);
}
if (e.Command == "EditorToggleTransformSpace" && e.Value > 0) {
if (m_WidgetSpace == WidgetSpace::Global) {
setWidgetSpace(WidgetSpace::Local);
} else if (m_WidgetSpace == WidgetSpace::Local) {
setWidgetSpace(WidgetSpace::Global);
}
}
return true;
}
bool EditorSystem::OnMousePress(const Events::MousePress& e)
{
if (e.Button == GLFW_MOUSE_BUTTON_RIGHT) {
m_PickingQueue.push_back(glm::vec2((int)e.X, (int)e.Y));
}
return true;
}
bool EditorSystem::OnMouseMove(const Events::MouseMove& e)
{
if (m_Widget == 0) {
return false;
}
if (m_Selection == 0) {
return false;
}
auto widgetTransform = m_World->GetComponent(m_Widget, "Transform");
glm::vec3 widgetOrientation = widgetTransform["Orientation"];
glm::quat totalOrientation = m_Renderer->Camera()->Orientation() * glm::inverse(glm::quat(widgetOrientation));
int width;
int height;
glfwGetFramebufferSize(m_Renderer->Window(), &width, &height);
Rectangle res(width, height);
glm::vec2 delta2(res.Width / 2.f + e.DeltaX, res.Height / 2.f + -e.DeltaY);
glm::vec3 deltaWorld = ScreenCoords::ToWorldPos(
delta2,
m_WidgetPickingDepth,
res,
m_Renderer->Camera()->ProjectionMatrix(),
glm::toMat4(glm::inverse(totalOrientation))
);
glm::vec3 origin = ScreenCoords::ToWorldPos(
glm::vec2(res.Width / 2.f, res.Height / 2.f),
m_WidgetPickingDepth,
res,
m_Renderer->Camera()->ProjectionMatrix(),
glm::toMat4(glm::inverse(totalOrientation))
);
deltaWorld = deltaWorld - origin;
glm::vec3 movement = deltaWorld * m_WidgetCurrentAxis;
if (glm::length2(m_WidgetCurrentAxis) > 0.f) {
auto widgetTransform = m_World->GetComponent(m_Widget, "Transform");
if (m_WidgetMode == WidgetMode::Translate) {
if (m_WidgetSpace == WidgetSpace::Global) {
EntityID parent = m_World->GetParent(m_Selection);
glm::quat inverseParentOrientation;
if (parent != 0) {
inverseParentOrientation = glm::inverse(RenderQueueFactory::AbsoluteOrientation(m_World, parent));
}
(glm::vec3&)m_World->GetComponent(m_Selection, "Transform")["Position"] += inverseParentOrientation * movement;
} else if (m_WidgetSpace == WidgetSpace::Local) {
auto selectionTransform = m_World->GetComponent(m_Selection, "Transform");
(glm::vec3&)selectionTransform["Position"] += glm::quat((glm::vec3)selectionTransform["Orientation"]) * movement;
}
} else if (m_WidgetMode == WidgetMode::Rotate) {
glm::vec3 finalMovement;
finalMovement.x = -deltaWorld.y * m_WidgetCurrentAxis.x;
finalMovement.y = deltaWorld.x * m_WidgetCurrentAxis.y;
finalMovement.z = deltaWorld.y * m_WidgetCurrentAxis.z;
if (m_WidgetSpace == WidgetSpace::Global) {
EntityID parent = m_World->GetParent(m_Selection);
glm::quat parentOrientation;
if (parent != 0) {
parentOrientation = RenderQueueFactory::AbsoluteOrientation(m_World, parent);
}
glm::vec3& selectionOrientation = m_World->GetComponent(m_Selection, "Transform")["Orientation"];
//glm::quat currentOrientation = RenderQueueFactory::AbsoluteOrientation(m_World, m_Selection);
glm::quat currentOrientation = parentOrientation * glm::quat(selectionOrientation);
glm::quat deltaOrientation(finalMovement);
selectionOrientation = glm::eulerAngles(glm::inverse(parentOrientation) * (deltaOrientation * currentOrientation));
} else if (m_WidgetSpace == WidgetSpace::Local) {
glm::vec3& selectionOrientation = m_World->GetComponent(m_Selection, "Transform")["Orientation"];
glm::quat currentOrientation(selectionOrientation);
glm::quat deltaOrientation(finalMovement);
selectionOrientation = glm::eulerAngles(currentOrientation * deltaOrientation);
}
} else if (m_WidgetMode == WidgetMode::Scale) {
glm::vec3& scaleX = m_World->GetComponent(m_WidgetX, "Transform")["Scale"];
glm::vec3& scaleY = m_World->GetComponent(m_WidgetY, "Transform")["Scale"];
glm::vec3& scaleZ = m_World->GetComponent(m_WidgetZ, "Transform")["Scale"];
if (m_WidgetCurrentAxis.x > 0 && m_WidgetCurrentAxis.y > 0 && m_WidgetCurrentAxis.z > 0) {
float movementLength = glm::length(movement);
float dot = glm::dot((glm::vec3)widgetOrientation, movement);
movement = glm::vec3(movementLength) * glm::sign(dot);
(glm::vec3&)m_World->GetComponent(m_WidgetOrigin, "Transform")["Scale"] += movement;
}
if (m_WidgetCurrentAxis.x > 0) {
scaleX.x += movement.x;
}
if (m_WidgetCurrentAxis.y > 0) {
scaleY.y += movement.y;
}
if (m_WidgetCurrentAxis.z > 0) {
scaleZ.z += movement.z;
}
(glm::vec3&)m_World->GetComponent(m_Selection, "Transform")["Scale"] += movement;
}
}
/*LOG_DEBUG("DELTA %f", e.DeltaX);
if (e.X < 0) {
glfwSetCursorPos(m_Renderer->Window(), width - 1, e.Y);
}
if (e.X >= width) {
glfwSetCursorPos(m_Renderer->Window(), 0, e.Y);
}*/
return true;
}
bool EditorSystem::OnMouseRelease(const Events::MouseRelease& e)
{
if (glm::length2(m_WidgetCurrentAxis) > 0.f) {
m_WidgetCurrentAxis = glm::vec3(0.f);
//setWidgetMode(m_WidgetMode);
}
return true;
}
bool EditorSystem::OnPicking(const Events::Picking& e)
{
for (auto& pos : m_PickingQueue) {
auto result = e.Pick(pos);
EntityID entity = result.Entity;
if (glm::length2(m_WidgetCurrentAxis) > 0.f) {
} else {
LOG_INFO("Selected %i", entity);
if (entity != 0) {
EntityID parent = m_World->GetParent(entity);
if (parent == m_Widget) {
m_WidgetCurrentAxis = glm::vec3(
(entity == m_WidgetX) || (entity == m_WidgetOrigin) || (entity == m_WidgetPlaneY || entity == m_WidgetPlaneZ),
(entity == m_WidgetY) || (entity == m_WidgetOrigin) || (entity == m_WidgetPlaneX || entity == m_WidgetPlaneZ),
(entity == m_WidgetZ) || (entity == m_WidgetOrigin) || (entity == m_WidgetPlaneX || entity == m_WidgetPlaneY)
);
m_WidgetPickingDepth = result.Depth;
//auto widgetTransform = m_World->GetComponent(m_Widget, "Transform");
//auto selectionTransform = m_World->GetComponent(m_Selection, "Transform");
//widgetTransform["Position"] = (glm::vec3)selectionTransform["Position"];
} else {
ImGui::SetActiveID(0, nullptr);
m_Selection = entity;
setWidgetMode(m_WidgetMode);
}
} else {
m_Selection = 0;
}
}
}
m_PickingQueue.clear();
return true;
};
bool EditorSystem::OnFileDropped(const Events::FileDropped& e)
{
m_LastDroppedFile = boost::filesystem::path(e.Path).lexically_relative(boost::filesystem::current_path()).string();
std::replace(m_LastDroppedFile.begin(), m_LastDroppedFile.end(), '\\', '/');
return true;
}
void EditorSystem::updateWidget()
{
if (m_Widget == 0) {
m_Widget = m_World->CreateEntity();
m_World->AttachComponent(m_Widget, "Transform");
m_WidgetX = m_World->CreateEntity(m_Widget);
m_World->AttachComponent(m_WidgetX, "Transform");
m_World->AttachComponent(m_WidgetX, "Model");
m_WidgetPlaneX = m_World->CreateEntity(m_Widget);
m_World->AttachComponent(m_WidgetPlaneX, "Transform");
m_World->AttachComponent(m_WidgetPlaneX, "Model");
m_World->GetComponent(m_WidgetPlaneX, "Model")["Resource"] = "Models/WidgetPlaneX.obj";
m_WidgetY = m_World->CreateEntity(m_Widget);
m_World->AttachComponent(m_WidgetY, "Transform");
m_World->AttachComponent(m_WidgetY, "Model");
m_WidgetPlaneY = m_World->CreateEntity(m_Widget);
m_World->AttachComponent(m_WidgetPlaneY, "Transform");
m_World->AttachComponent(m_WidgetPlaneY, "Model");
m_World->GetComponent(m_WidgetPlaneY, "Model")["Resource"] = "Models/WidgetPlaneY.obj";
m_WidgetZ = m_World->CreateEntity(m_Widget);
m_World->AttachComponent(m_WidgetZ, "Transform");
m_World->AttachComponent(m_WidgetZ, "Model");
m_WidgetPlaneZ = m_World->CreateEntity(m_Widget);
m_World->AttachComponent(m_WidgetPlaneZ, "Transform");
m_World->AttachComponent(m_WidgetPlaneZ, "Model");
m_World->GetComponent(m_WidgetPlaneZ, "Model")["Resource"] = "Models/WidgetPlaneZ.obj";
m_WidgetOrigin = m_World->CreateEntity(m_Widget);
m_World->AttachComponent(m_WidgetOrigin, "Transform");
m_World->AttachComponent(m_WidgetOrigin, "Model");
setWidgetMode(WidgetMode::Translate);
}
if (m_Selection != 0) {
auto widgetTransform = m_World->GetComponent(m_Widget, "Transform");
glm::vec3 selectionPosition = RenderQueueFactory::AbsolutePosition(m_World, m_Selection);
widgetTransform["Position"] = selectionPosition;
if (m_WidgetSpace == WidgetSpace::Local) {
widgetTransform["Orientation"] = glm::eulerAngles(RenderQueueFactory::AbsoluteOrientation(m_World, m_Selection));
}
}
}
void EditorSystem::setWidgetMode(WidgetMode newMode)
{
if (m_Widget == 0) {
return;
}
auto widgetTransform = m_World->GetComponent(m_Widget, "Transform");
widgetTransform["Orientation"] = glm::vec3(0.f);
m_World->GetComponent(m_WidgetX, "Transform")["Scale"] = glm::vec3(1.f);
m_World->GetComponent(m_WidgetPlaneX, "Model")["Visible"] = false;
m_World->GetComponent(m_WidgetY, "Transform")["Scale"] = glm::vec3(1.f);
m_World->GetComponent(m_WidgetPlaneY, "Model")["Visible"] = false;
m_World->GetComponent(m_WidgetZ, "Transform")["Scale"] = glm::vec3(1.f);
m_World->GetComponent(m_WidgetPlaneZ, "Model")["Visible"] = false;
m_World->GetComponent(m_WidgetOrigin, "Transform")["Scale"] = glm::vec3(1.f);
m_World->GetComponent(m_WidgetOrigin, "Model")["Visible"] = false;
if (newMode == WidgetMode::Translate) {
m_World->GetComponent(m_WidgetX, "Model")["Resource"] = "Models/TranslationWidgetX.obj";
m_World->GetComponent(m_WidgetY, "Model")["Resource"] = "Models/TranslationWidgetY.obj";
m_World->GetComponent(m_WidgetZ, "Model")["Resource"] = "Models/TranslationWidgetZ.obj";
// Temporarily disabled for local space until I can figure out what's wrong with the math
if (m_WidgetSpace != WidgetSpace::Local) {
m_World->GetComponent(m_WidgetPlaneX, "Model")["Visible"] = true;
m_World->GetComponent(m_WidgetPlaneY, "Model")["Visible"] = true;
m_World->GetComponent(m_WidgetPlaneZ, "Model")["Visible"] = true;
}
if (m_Selection != 0) {
if (m_WidgetSpace == WidgetSpace::Local) {
auto selectionTransform = m_World->GetComponent(m_Selection, "Transform");
widgetTransform["Orientation"] = glm::eulerAngles(RenderQueueFactory::AbsoluteOrientation(m_World, m_Selection));
}
}
} else if (newMode == WidgetMode::Scale) {
m_World->GetComponent(m_WidgetX, "Model")["Resource"] = "Models/ScaleWidgetX.obj";
m_World->GetComponent(m_WidgetY, "Model")["Resource"] = "Models/ScaleWidgetY.obj";
m_World->GetComponent(m_WidgetZ, "Model")["Resource"] = "Models/ScaleWidgetZ.obj";
m_World->GetComponent(m_WidgetOrigin, "Model")["Visible"] = true;
m_World->GetComponent(m_WidgetOrigin, "Model")["Resource"] = "Models/ScaleWidgetOrigin.obj";
if (m_Selection != 0) {
auto selectionTransform = m_World->GetComponent(m_Selection, "Transform");
widgetTransform["Orientation"] = glm::eulerAngles(RenderQueueFactory::AbsoluteOrientation(m_World, m_Selection));
}
} else if (newMode == WidgetMode::Rotate) {
m_World->GetComponent(m_WidgetX, "Model")["Resource"] = "Models/RotationWidgetX.obj";
m_World->GetComponent(m_WidgetY, "Model")["Resource"] = "Models/RotationWidgetY.obj";
m_World->GetComponent(m_WidgetZ, "Model")["Resource"] = "Models/RotationWidgetZ.obj";
if (m_Selection != 0) {
auto selectionTransform = m_World->GetComponent(m_Selection, "Transform");
if (m_WidgetSpace == WidgetSpace::Local) {
widgetTransform["Orientation"] = glm::eulerAngles(RenderQueueFactory::AbsoluteOrientation(m_World, m_Selection));
}
}
}
m_WidgetMode = newMode;
}
void EditorSystem::setWidgetSpace(WidgetSpace space)
{
m_WidgetSpace = space;
setWidgetMode(m_WidgetMode);
}
void EditorSystem::drawUI(World* world, double dt)
{
ImGui::ShowTestWindow();
//ImGui::ShowStyleEditor();
if (ImGui::BeginMainMenuBar()) {
if (ImGui::BeginMenu("File")) {
if (ImGui::MenuItem("New")) { }
if (ImGui::MenuItem("Open", "Ctrl+O")) { }
if (ImGui::MenuItem("Save", "Ctrl+S")) { }
if (ImGui::MenuItem("Save As...", "Ctrl+Shift+S")) { }
ImGui::Separator();
if (ImGui::MenuItem("Close Editor", "F1")) { }
ImGui::EndMenu();
}
ImGui::SameLine();
if (ImGui::Button("Move")) {
setWidgetMode(WidgetMode::Translate);
}
ImGui::SameLine();
if (ImGui::Button("Rotate")) {
setWidgetMode(WidgetMode::Rotate);
}
ImGui::SameLine();
if (ImGui::Button("Scale")) {
setWidgetMode(WidgetMode::Scale);
}
ImGui::SameLine();
if (m_WidgetSpace == WidgetSpace::Global) {
if (ImGui::Button("(Global)")) {
setWidgetSpace(WidgetSpace::Local);
}
} else if (m_WidgetSpace == WidgetSpace::Local) {
if (ImGui::Button("(Local)")) {
setWidgetSpace(WidgetSpace::Global);
}
}
ImGui::EndMainMenuBar();
}
std::string title = std::string("Components #") + std::to_string(m_Selection) + std::string("###Components");
if (ImGui::Begin(title.c_str())) {
if (m_Selection != 0) {
auto& pools = world->GetComponentPools();
std::vector<const char*> componentTypes;
for (auto& pair : pools) {
// Only add components the entity doesn't already have
if (!pair.second->KnowsEntity(m_Selection)) {
componentTypes.push_back(pair.first.c_str());
}
}
int item = -1;
ImGui::PushItemWidth(ImGui::GetWindowContentRegionWidth() - 5.f);
if (ImGui::Combo("", &item, componentTypes.data(), componentTypes.size())) {
if (item != -1) {
std::string chosenType = std::string(componentTypes.at(item));
world->AttachComponent(m_Selection, chosenType);
}
}
ImGui::PopItemWidth();
for (auto& pair : pools) {
const std::string& componentType = pair.first;
auto pool = pair.second;
if (!pool->KnowsEntity(m_Selection)) {
continue;
}
auto& ci = pool->ComponentInfo();
bool deletePressed = createDeleteButton(componentType);
if (deletePressed) {
world->DeleteComponent(m_Selection, componentType);
continue;
}
if (ImGui::CollapsingHeader(componentType.c_str())) {
if (!ci.Meta.Annotation.empty()) {
ImGui::Text(ci.Meta.Annotation.c_str());
}
auto& component = world->GetComponent(m_Selection, componentType);
for (auto& pair : ci.FieldTypes) {
const std::string& field = pair.first;
const std::string& type = pair.second;
ImGui::PushID(field.c_str());
if (type == "Vector") {
auto& val = component.Property<glm::vec3>(field);
if (field == "Scale") {
ImGui::DragFloat3("", glm::value_ptr(val), 0.1f, 0.f, std::numeric_limits<float>::max());
} else if (field == "Orientation") {
glm::vec3 tempVal = glm::fmod(val, glm::vec3(glm::two_pi<float>()));
if (ImGui::SliderFloat3("", glm::value_ptr(tempVal), 0.f, glm::two_pi<float>())) {
val = tempVal;
}
} else {
ImGui::DragFloat3("", glm::value_ptr(val), 0.1f, std::numeric_limits<float>::lowest(), std::numeric_limits<float>::max());
}
} else if (type == "Color") {
auto& val = component.Property<glm::vec4>(field);
ImGui::ColorEdit4("", glm::value_ptr(val), true);
} else if (type == "string") {
std::string& val = component.Property<std::string>(field);
char tempString[1024];
memcpy(tempString, val.c_str(), std::min(val.length() + 1, sizeof(tempString)));
if (ImGui::InputText("", tempString, sizeof(tempString))) {
val = std::string(tempString);
LOG_DEBUG("%s::%s changed!", componentType.c_str(), field.c_str());
}
// DROP STUFF
if (ImGui::IsItemHovered() && !m_LastDroppedFile.empty()) {
val = m_LastDroppedFile;
m_LastDroppedFile = "";
}
} else if (type == "double") {
float tempVal = static_cast<float>(component.Property<double>(field));
if (ImGui::InputFloat("", &tempVal, 0.01f, 1.f)) {
component.SetProperty(field, static_cast<double>(tempVal));
}
} else if (type == "bool") {
auto& val = component.Property<bool>(field);
ImGui::Checkbox("", &val);
} else {
ImGui::TextDisabled(type.c_str());
}
ImGui::PopID();
ImGui::SameLine();
ImGui::Text(field.c_str());
if (ImGui::IsItemHovered()) {
ImGui::SetTooltip("field annotation goes here");
}
}
}
}
}
}
ImGui::End();
if (ImGui::Begin("Entitites")) {
static EntityID draggingEntity = 0;
auto entityChildren = world->GetEntityChildren();
std::function<void(EntityID)> recurse = [&](EntityID parent) {
auto range = entityChildren.equal_range(parent);
for (auto it = range.first; it != range.second; it++) {
ImVec2 pos = ImGui::GetCursorScreenPos();
float width = ImGui::GetContentRegionAvailWidth();
ImRect bb(pos + ImVec2(20, 0), pos + ImVec2(width, 13));
auto window = ImGui::GetCurrentWindow();
if (m_Selection == it->second) {
const ImU32 col = window->Color(ImGuiCol_HeaderActive);
window->DrawList->AddRectFilled(bb.Min, bb.Max, col);
}
ImGuiID id = window->GetID((std::string("#SelectButton") + std::to_string(it->second)).c_str());
bool hovered = false;
bool held = false;
if (ImGui::ButtonBehavior(bb, id, &hovered, &held)) {
m_Selection = it->second;
}
if (held) {
ImVec2 entityDragDelta = ImGui::GetMouseDragDelta(0);
if (std::abs(entityDragDelta.x) > 0 && std::abs(entityDragDelta.y) > 0) {
if (draggingEntity == 0) {
draggingEntity = it->second;
LOG_DEBUG("Started drag of entity %i", draggingEntity);
}
ImGui::SetNextWindowPos(ImGui::GetIO().MousePos + ImVec2(20, 0));
ImGui::Begin("Change parent", nullptr, ImVec2(0, 0), 0.3f, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings);
ImGui::Text("#%i", draggingEntity);
ImGui::End();
}
}
ImGui::SetNextTreeNodeOpened(true, ImGuiSetCond_Once);
if (ImGui::TreeNode((std::string("#") + std::to_string(it->second)).c_str())) {
if (draggingEntity != 0 && ImGui::IsItemHoveredRect() && ImGui::IsMouseReleased(0)) {
LOG_DEBUG("Changed parent of %i to %i", draggingEntity, it->second);
changeParent(draggingEntity, it->second);
draggingEntity = 0;
}
if (ImGui::BeginPopupContextItem("item context menu")) {
if (ImGui::Button("Add")) {
EntityID entity = world->CreateEntity(it->second);
world->AttachComponent(entity, "Transform");
}
ImGui::SameLine();
if (ImGui::Button("Delete")) {
world->DeleteEntity(it->second);
ImGui::CloseCurrentPopup();
if (m_Selection == it->second) {
m_Selection = 0;
}
}
ImGui::EndPopup();
}
recurse(it->second);
ImGui::TreePop();
}
}
};
recurse(0);
}
ImGui::End();
}
bool EditorSystem::createDeleteButton(std::string componentType)
{
float width = ImGui::GetContentRegionAvailWidth();
ImGuiWindow* window = ImGui::GetCurrentWindow();
auto pos = ImGui::GetCursorScreenPos() + ImVec2(width - 14.f, 1);
ImRect bb = ImRect(pos, pos + ImVec2(14.f, 14.f));
std::string idString = "#DELETE";
idString += componentType;
ImGuiID id = window->GetID(idString.c_str());
bool hovered;
bool held;
bool pressed = ImGui::ButtonBehavior(bb, id, &hovered, &held);
//ImU32 col = window->Color((held && hovered) ? ImGuiCol_CloseButtonActive : hovered ? ImGuiCol_CloseButtonHovered : ImGuiCol_CloseButton);
ImU32 col = window->Color((held && hovered) ? ImGuiCol_CloseButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
window->DrawList->AddCircleFilled(bb.GetCenter(), 7.f, col, 16);
return pressed;
}
void EditorSystem::changeParent(EntityID entity, EntityID newParent)
{
if (entity == newParent) {
return;
}
// An entity can't be a child to one of its own children
auto children = m_World->GetEntityChildren().equal_range(entity);
for (auto it = children.first; it != children.second; it++) {
if (it->second == newParent) {
return;
}
}
m_World->SetParent(entity, newParent);
}
+326 -3
View File
@@ -1,11 +1,334 @@
#include "Network\Client.h"
#include "Network/Client.h"
Client::Client()
using namespace boost::asio::ip;
Client::Client(ConfigFile* config) : m_Socket(m_IOService)
{
// Default is local host
std::string address = config->Get<std::string>("Networking.Address", "127.0.0.1");
int port = config->Get<int>("Networking.Port", 13);
m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address::from_string(address), port);
// Set up network stream
m_PlayerName = config->Get<std::string>("Networking.Name", "Raptorcopter");
m_NextSnapshot.InputForward = "";
m_NextSnapshot.InputRight = "";
}
Client::~Client()
{
}
void Client::Start(World* world, EventBroker* eventBroker)
{
m_WasStarted = true;
m_EventBroker = eventBroker;
m_World = world;
// Subscribe to events
m_EInputCommand = decltype(m_EInputCommand)(std::bind(&Client::OnInputCommand, this, std::placeholders::_1));
m_EventBroker->Subscribe(m_EInputCommand);
//while (m_PlayerName.size() > 7) {
// LOG_INFO("Please enter your name (No longer than 7 characters):");
// std::cin >> m_PlayerName;
//}
m_Socket.connect(m_ReceiverEndpoint);
LOG_INFO("I am client. BIP BOP");
}
void Client::Update()
{
readFromServer();
}
void Client::Close()
{
if (m_WasStarted) {
disconnect();
m_ThreadIsRunning = false;
m_EventBroker->Unsubscribe(m_EInputCommand);
}
}
void Client::readFromServer()
{
if (m_Socket.available()) {
bytesRead = receive(readBuf, INPUTSIZE);
if (bytesRead > 0) {
Packet packet(readBuf, bytesRead);
parseMessageType(packet);
}
}
std::clock_t currentTime = std::clock();
if (snapshotInterval < (1000 * (currentTime - previousSnapshotMessage) / (double)CLOCKS_PER_SEC)) {
if (isConnected()) {
sendSnapshotToServer();
}
previousSnapshotMessage = currentTime;
}
}
void Client::sendSnapshotToServer()
{
// Reset previouse key state in snapshot.
m_NextSnapshot.InputForward = "";
m_NextSnapshot.InputRight = "";
auto player = m_World->GetComponent(m_PlayerDefinitions[m_PlayerID].EntityID, "Player");
// See if any movement keys are down
// We dont care if it's overwritten by later
// if statement. Watcha gonna do, right!
if (player["Forward"]) {
m_NextSnapshot.InputForward = "+Forward";
}
if (player["Left"]) {
m_NextSnapshot.InputRight = "-Right";
}
if (player["Back"]) {
m_NextSnapshot.InputForward = "-Forward";
}
if (player["Right"]) {
m_NextSnapshot.InputRight = "+Right";
}
if (m_NextSnapshot.InputForward != "") {
Packet packet(MessageType::Event, m_SendPacketID);
packet.WriteString(m_NextSnapshot.InputForward);
send(packet);
} else {
Packet packet(MessageType::Event, m_SendPacketID);
packet.WriteString("0Forward");
send(packet);
}
if (m_NextSnapshot.InputRight != "") {
Packet packet(MessageType::Event, m_SendPacketID);
packet.WriteString(m_NextSnapshot.InputRight);
send(packet);
} else {
Packet packet(MessageType::Event, m_SendPacketID);
packet.WriteString("0Right");
send(packet);
}
}
void Client::parseMessageType(Packet& packet)
{
int messageType = packet.ReadPrimitive<int>();
if (messageType == -1)
return;
// Read packet ID
m_PreviousPacketID = m_PacketID; // Set previous packet id
m_PacketID = packet.ReadPrimitive<int>(); //Read new packet id
//IdentifyPacketLoss();
switch (static_cast<MessageType>(messageType)) {
case MessageType::Connect:
parseConnect(packet);
break;
case MessageType::ClientPing:
parsePing();
break;
case MessageType::ServerPing:
parseServerPing();
break;
case MessageType::Message:
break;
case MessageType::Snapshot:
parseSnapshot(packet);
break;
case MessageType::Disconnect:
break;
case MessageType::Event:
parseEventMessage(packet);
break;
default:
break;
}
}
void Client::parseConnect(Packet& packet)
{
m_PlayerID = packet.ReadPrimitive<int>();
LOG_INFO("%i: I am player: %i", m_PacketID, m_PlayerID);
}
void Client::parsePing()
{
m_DurationOfPingTime = 1000 * (std::clock() - m_StartPingTime) / static_cast<double>(CLOCKS_PER_SEC);
LOG_INFO("%i: response time with ctime(ms): %f", m_PacketID, m_DurationOfPingTime);
}
void Client::parseServerPing()
{
Packet packet(MessageType::ServerPing, m_SendPacketID);
packet.WriteString("Ping recieved");
send(packet);
}
void Client::parseEventMessage(Packet& packet)
{
int Id = -1;
std::string command = packet.ReadString();
if (command.find("+Player") != std::string::npos) {
Id = packet.ReadPrimitive<int>();
// Sett Player name
m_PlayerDefinitions[Id].Name = command.erase(0, 7);
} else {
LOG_INFO("%i: Event message: %s", m_PacketID, command.c_str());
}
}
void Client::parseSnapshot(Packet& packet)
{
std::string tempName;
for (size_t i = 0; i < MAXCONNECTIONS; i++) {
// We're checking for empty name for now. This might not be the best way,
// but it is to avoid sending redundant data.
tempName = packet.ReadString();
// Apply the position data read to the player entity
// New player connected on the server side
if (m_PlayerDefinitions[i].Name == "" && tempName != "") {
m_PlayerDefinitions[i].Name = tempName;
m_PlayerDefinitions[i].EntityID = createPlayer();
} else if (m_PlayerDefinitions[i].Name != "" && tempName == "") {
// Someone disconnected
// TODO: Insert code here
break;
} else if (m_PlayerDefinitions[i].Name == "" && tempName == "") {
// Not a connected player
break;
}
if (m_PlayerDefinitions[i].EntityID != -1) {
// Move player to server position
int dataSize = m_World->GetComponent(m_PlayerDefinitions[i].EntityID, "Transform").Info.Meta.Stride;
memcpy(m_World->GetComponent(m_PlayerDefinitions[i].EntityID, "Transform").Data, packet.ReadData(dataSize), dataSize);
}
}
}
int Client::receive(char* data, size_t length)
{
boost::system::error_code error;
int bytesReceived = m_Socket.receive_from(boost
::asio::buffer((void*)data, length),
m_ReceiverEndpoint,
0, error);
if (error) {
//LOG_ERROR("receive: %s", error.message().c_str());
}
return bytesReceived;
}
void Client::send(Packet& packet)
{
m_Socket.send_to(boost::asio::buffer(
packet.Data(),
packet.Size()),
m_ReceiverEndpoint, 0);
}
void Client::connect()
{
Packet packet(MessageType::Connect, m_SendPacketID);
packet.WriteString(m_PlayerName);
m_StartPingTime = std::clock();
send(packet);
}
void Client::disconnect()
{
Packet packet(MessageType::Connect, m_SendPacketID);
packet.WriteString("+Disconnect");
send(packet);
}
void Client::ping()
{
Packet packet(MessageType::Connect, m_SendPacketID);
packet.WriteString("Ping");
m_StartPingTime = std::clock();
send(packet);
}
void Client::moveMessageHead(char*& data, size_t& length, size_t stepSize)
{
data += stepSize;
length -= stepSize;
}
bool Client::OnInputCommand(const Events::InputCommand & e)
{
if (isConnected()) {
ComponentWrapper& player = m_World->GetComponent(m_PlayerDefinitions[m_PlayerID].EntityID, "Player");
if (e.Command == "Forward") {
if (e.Value > 0) {
(bool&)player["Forward"] = true;
(bool&)player["Back"] = false;
} else if (e.Value < 0) {
(bool&)player["Back"] = true;
(bool&)player["Forward"] = false;
} else {
(bool&)player["Forward"] = false;
(bool&)player["Back"] = false;
}
}
if (e.Command == "Right") {
if (e.Value > 0) {
(bool&)player["Right"] = true;
(bool&)player["Left"] = false;
} else if (e.Value < 0) {
(bool&)player["Left"] = true;
(bool&)player["Right"] = false;
} else {
(bool&)player["Left"] = false;
(bool&)player["Right"] = false;
}
}
}
if (e.Command == "ConnectToServer") { // Connect for now
connect();
}
return false;
}
void Client::identifyPacketLoss()
{
// if no packets lost, difference should be equal to 1
int difference = m_PacketID - m_PreviousPacketID;
if (difference != 1) {
LOG_INFO("%i Packet(s) were lost...", difference);
}
}
bool Client::isConnected()
{
if (m_PlayerID != -1) {
if (m_PlayerDefinitions[m_PlayerID].EntityID != -1) {
return true;
}
}
return false;
}
EntityID Client::createPlayer()
{
EntityID entityID = m_World->CreateEntity();
ComponentWrapper transform = m_World->AttachComponent(entityID, "Transform");
ComponentWrapper model = m_World->AttachComponent(entityID, "Model");
model["Resource"] = "Models/Core/UnitSphere.obj";
ComponentWrapper player = m_World->AttachComponent(entityID, "Player");
return entityID;
}
+72
View File
@@ -0,0 +1,72 @@
#include "Network/Packet.h"
Packet::Packet(MessageType type, unsigned int& packetID)
{
m_Data = new char[m_MaxPacketSize];
// Create message header
// Add message type
int messageType = static_cast<int>(type);
Packet::WritePrimitive<int>(messageType);
packetID = packetID % 1000; // Packet id modulos
Packet::WritePrimitive<int>(packetID);
packetID++;
}
// Create message
Packet::Packet(char* data, const int sizeOfPacket)
{
// Resize message
m_MaxPacketSize = sizeOfPacket;
// Copy data newly allocated memory
m_Data = new char[sizeOfPacket];
memcpy(m_Data, data, sizeOfPacket);
m_Offset = sizeOfPacket;
}
Packet::~Packet()
{
delete[] m_Data;
}
void Packet::WriteString(std::string str)
{
// Message, add one extra byte for null terminator
int sizeOfString = str.size() + 1;
if (m_Offset + sizeOfString > m_MaxPacketSize) {
LOG_WARNING("Package::WriteString(): Data size in packet exceeded maximum package size.\n");
}
memcpy(m_Data + m_Offset, str.data(), sizeOfString * sizeof(char));
m_Offset += sizeOfString * sizeof(char);
}
void Packet::WriteData(char * data, int sizeOfData)
{
if (m_Offset + sizeOfData > m_MaxPacketSize) {
LOG_WARNING("Packet::WriteData(): Data size in packet exceeded maximum packet size.\n");
}
memcpy(m_Data + m_Offset, data, sizeOfData);
m_Offset += sizeOfData;
}
std::string Packet::ReadString()
{
std::string returnValue(m_Data + m_ReturnDataOffset);
if (m_Offset < m_ReturnDataOffset + returnValue.size()) {
LOG_WARNING("packet ReadString(): Oh no! You are trying to remove things outside my memory kingdom");
return "PopFrontString Failed";
}
// +1 for null terminator.
m_ReturnDataOffset += returnValue.size() + 1;
return returnValue;
}
char * Packet::ReadData(int SizeOfData)
{
if (m_Offset < m_ReturnDataOffset + SizeOfData) {
LOG_WARNING("packet ReadData(): Oh no! You are trying to remove things outside my memory kingdom");
return nullptr;
}
unsigned int oldReturnDataOffset = m_ReturnDataOffset;
m_ReturnDataOffset += SizeOfData;
return (m_Data + oldReturnDataOffset);
}
+350 -6
View File
@@ -1,11 +1,355 @@
#include "Network\Server.h"
#include "Network/Server.h"
Server::Server()
{
}
Server::Server() : m_Socket(m_IOService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 13))
{ }
Server::~Server()
{
{ }
void Server::Start(World* world, EventBroker* eventBroker)
{
m_World = world;
m_EventBroker = eventBroker;
for (size_t i = 0; i < MAXCONNECTIONS; i++) {
m_StopTimes[i] = std::clock();
}
LOG_INFO("I am Server. BIP BOP\n");
}
void Server::Update()
{
readFromClients();
}
void Server::Close()
{
m_ThreadIsRunning = false;
}
void Server::readFromClients()
{
// m_ThreadIsRunning might be unnecessary but the
// program crashed if it executed m_Socket.available()
// when closing the program.
if (m_Socket.available()) {
try {
bytesRead = receive(readBuffer, INPUTSIZE);
Packet packet(readBuffer, bytesRead);
parseMessageType(packet);
} catch (const std::exception& err) {
//LOG_ERROR("%i: Read from client crashed %s", m_PacketID, err.what());
}
}
std::clock_t currentTime = std::clock();
// Send snapshot
if (snapshotInterval < (1000 * (currentTime - previousSnapshotMessage) / (double)CLOCKS_PER_SEC)) {
sendSnapshot();
previousSnapshotMessage = currentTime;
}
// Send pings each
if (intervalMs < (1000 * (currentTime - previousePingMessage) / (double)CLOCKS_PER_SEC)) {
sendPing();
previousePingMessage = currentTime;
}
// Time out logic
if (checkTimeOutInterval < (1000 * (currentTime - timOutTimer) / (double)CLOCKS_PER_SEC)) {
checkForTimeOuts();
timOutTimer = currentTime;
}
}
void Server::parseMessageType(Packet& packet)
{
int messageType = packet.ReadPrimitive<int>(); // Read what type off message was sent from server
// Read packet ID
m_PreviousPacketID = m_PacketID; // Set previous packet id
m_PacketID = packet.ReadPrimitive<int>(); //Read new packet id
//IdentifyPacketLoss();
switch (static_cast<MessageType>(messageType)) {
case MessageType::Connect:
parseConnect(packet);
break;
case MessageType::ClientPing:
//parseClientPing();
break;
case MessageType::ServerPing:
parseServerPing();
break;
case MessageType::Message:
break;
case MessageType::Snapshot:
parseSnapshot(packet);
break;
case MessageType::Disconnect:
parseDisconnect();
break;
case MessageType::Event:
parseEvent(packet);
break;
default:
break;
}
}
int Server::receive(char * data, size_t length)
{
length = m_Socket.receive_from(
boost::asio::buffer((void*)data
, length)
, m_ReceiverEndpoint, 0);
return length;
}
void Server::send(Packet& packet, int playerID)
{
m_Socket.send_to(
boost::asio::buffer(packet.Data(), packet.Size()),
m_PlayerDefinitions[playerID].Endpoint,
0);
}
void Server::send(Packet & packet)
{
m_Socket.send_to(
boost::asio::buffer(
packet.Data(),
packet.Size()),
m_ReceiverEndpoint,
0);
}
void Server::moveMessageHead(char *& data, size_t & length, size_t stepSize)
{
data += stepSize;
length -= stepSize;
}
void Server::broadcast(std::string message)
{
Packet packet(MessageType::Event, m_SendPacketID);
packet.WriteString(message);
for (int i = 0; i < MAXCONNECTIONS; i++) {
if (m_PlayerDefinitions[i].Endpoint.address() != boost::asio::ip::address()) {
send(packet, i);
}
}
}
void Server::broadcast(Packet& packet)
{
for (int i = 0; i < MAXCONNECTIONS; ++i) {
if (m_PlayerDefinitions[i].Endpoint.address() != boost::asio::ip::address()) {
send(packet, i);
}
}
}
void Server::sendSnapshot()
{
Packet packet(MessageType::Snapshot, m_SendPacketID);
for (size_t i = 0; i < MAXCONNECTIONS; i++) {
// Send an empty name if there is no player connected on this position.
packet.WriteString(m_PlayerDefinitions[i].Name);
if (m_PlayerDefinitions[i].EntityID == -1) {
continue;
}
// Pack transfrom component into data packet
auto transform = m_World->GetComponent(m_PlayerDefinitions[i].EntityID, "Transform");
packet.WriteData(transform.Data, transform.Info.Meta.Stride);
}
broadcast(packet);
}
void Server::sendPing()
{
// Prints connected players ping
for (size_t i = 0; i < MAXCONNECTIONS; i++) {
if (m_PlayerDefinitions[i].Endpoint.address() != boost::asio::ip::address()) {
int ping = 1000 * (m_StopTimes[i] - m_StartPingTime) / static_cast<double>(CLOCKS_PER_SEC);
LOG_INFO("%i: Player %i's ping: %i", m_PacketID, i, ping);
}
}
// Create ping message
Packet packet(MessageType::ServerPing, m_SendPacketID);
packet.WriteString("Ping from server");
// Time message
m_StartPingTime = std::clock();
// Send message
broadcast(packet);
}
void Server::checkForTimeOuts()
{
int timeOutTimeMs = 5000;
int startPing = 1000 * m_StartPingTime
/ static_cast<double>(CLOCKS_PER_SEC);
for (size_t i = 0; i < MAXCONNECTIONS; i++) {
if (m_PlayerDefinitions[i].Endpoint.address() != boost::asio::ip::address()) {
int stopPing = 1000 * m_StopTimes[i]
/ static_cast<double>(CLOCKS_PER_SEC);
if (startPing > stopPing + timeOutTimeMs) {
LOG_INFO("Player %i timed out!", i);
disconnect(i);
}
}
}
}
void Server::disconnect(int i)
{
broadcast("A player disconnected");
LOG_INFO("Player %i disconnected/timed out", i);
// Remove enteties and stuff
m_PlayerDefinitions[i].Endpoint = boost::asio::ip::udp::endpoint();
m_PlayerDefinitions[i].EntityID = -1;
m_PlayerDefinitions[i].Name = "";
}
void Server::parseEvent(Packet& packet)
{
size_t i;
for (i = 0; i < MAXCONNECTIONS; i++) {
if (m_PlayerDefinitions[i].Endpoint.address() == m_ReceiverEndpoint.address()) {
break;
}
}
// If no player matches the address return.
if (i >= 8)
return;
unsigned int entityId = m_PlayerDefinitions[i].EntityID;
std::string eventString = packet.ReadString();
if ("+Forward" == eventString) {
m_World->GetComponent(entityId, "Player")["Forward"] = true;
m_World->GetComponent(entityId, "Player")["Back"] = false;
} else if ("-Forward" == eventString) {
m_World->GetComponent(entityId, "Player")["Forward"] = false;
m_World->GetComponent(entityId, "Player")["Back"] = true;
} else if ("0Forward" == eventString) {
m_World->GetComponent(entityId, "Player")["Forward"] = false;
m_World->GetComponent(entityId, "Player")["Back"] = false;
}
if ("+Right" == eventString) {
m_World->GetComponent(entityId, "Player")["Left"] = false;
m_World->GetComponent(entityId, "Player")["Right"] = true;
} else if ("-Right" == eventString) {
m_World->GetComponent(entityId, "Player")["Right"] = false;
m_World->GetComponent(entityId, "Player")["Left"] = true;
} else if ("0Right" == eventString) {
m_World->GetComponent(entityId, "Player")["Right"] = false;
m_World->GetComponent(entityId, "Player")["Left"] = false;
}
}
void Server::parseConnect(Packet& packet)
{
LOG_INFO("Parsing connections");
// Check if player is already connected
for (int i = 0; i < MAXCONNECTIONS; i++) {
if (m_PlayerDefinitions[i].Endpoint.address() == m_ReceiverEndpoint.address()) {
return;
}
}
for (int i = 0; i < MAXCONNECTIONS; i++) {
if (m_PlayerDefinitions[i].Endpoint.address() == boost::asio::ip::address()) {
// Create new player
m_PlayerDefinitions[i].EntityID = createPlayer();
m_PlayerDefinitions[i].Endpoint = m_ReceiverEndpoint;
m_PlayerDefinitions[i].Name = packet.ReadString();
m_StopTimes[i] = std::clock();
LOG_INFO("Player \"%s\" connected on IP: %s", m_PlayerDefinitions[i].Name, m_PlayerDefinitions[i].Endpoint.address().to_string());
Packet packet(MessageType::Connect, m_SendPacketID);
packet.WritePrimitive<int>(i); // Player ID
send(packet, i);
// Send notification that a player has connected
std::string str = m_PacketID + "Player " + m_PlayerDefinitions[i].Name + " connected on: "
+ m_PlayerDefinitions[i].Endpoint.address().to_string();
broadcast(str);
break;
}
}
}
void Server::parseDisconnect()
{
LOG_INFO("%i: Parsing disconnect", m_PacketID);
for (int i = 0; i < MAXCONNECTIONS; i++) {
if (m_PlayerDefinitions[i].Endpoint.address() == m_ReceiverEndpoint.address()) {
disconnect(i);
break;
}
}
}
void Server::parseClientPing()
{
LOG_INFO("%i: Parsing ping", m_PacketID);
// Return ping
Packet packet(MessageType::ClientPing, m_SendPacketID);
packet.WriteString("Ping received");
send(packet); // This dosen't work for multiple users
}
void Server::parseServerPing()
{
for (int i = 0; i < MAXCONNECTIONS; i++) {
if (m_PlayerDefinitions[i].Endpoint.address() == m_ReceiverEndpoint.address()) {
m_StopTimes[i] = std::clock();
break;
}
}
}
// NOT USED
void Server::parseSnapshot(Packet& packet)
{
// Does no logic. Returns snapshot if client request one
// The snapshot is not a real snapshot tho...
for (int i = 0; i < MAXCONNECTIONS; i++) {
if (m_PlayerDefinitions[i].Endpoint.address() != boost::asio::ip::address()) {
m_Socket.send_to(
boost::asio::buffer("I'm sending a snapshot to you guys!"),
m_PlayerDefinitions[i].Endpoint,
0);
}
}
}
void Server::identifyPacketLoss()
{
// if no packets lost, difference should be equal to 1
int difference = m_PacketID - m_PreviousPacketID;
if (difference != 1) {
LOG_INFO("%i Packet(s) were lost...", difference);
}
}
EntityID Server::createPlayer()
{
EntityID entityID = m_World->CreateEntity();
ComponentWrapper transform = m_World->AttachComponent(entityID, "Transform");
transform["Position"] = glm::vec3(-1.5f, 0.f, 0.f);
ComponentWrapper model = m_World->AttachComponent(entityID, "Model");
model["Resource"] = "Models/Core/UnitSphere.obj";
model["Color"] = glm::vec4(rand()%255 / 255.f, rand()%255 / 255.f, rand() %255 / 255.f, 1.f);
ComponentWrapper player = m_World->AttachComponent(entityID, "Player");
return entityID;
}
+65
View File
@@ -0,0 +1,65 @@
#include "Rendering/DrawFinalPass.h"
DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass)
{
m_Renderer = renderer;
m_LightCullingPass = lightCullingPass;
InitializeTextures();
InitializeShaderPrograms();
}
void DrawFinalPass::InitializeTextures()
{
m_WhiteTexture = ResourceManager::Load<Texture>("Textures/Core/Blank.png");
}
void DrawFinalPass::InitializeShaderPrograms()
{
m_ForwardPlusProgram = ResourceManager::Load<ShaderProgram>("#ForwardPlusProgram");
m_ForwardPlusProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/ForwardPlus.vert.glsl")));
m_ForwardPlusProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/ForwardPlus.frag.glsl")));
m_ForwardPlusProgram->Compile();
m_ForwardPlusProgram->Link();
}
void DrawFinalPass::Draw(RenderQueueCollection& rq)
{
GLERROR("DrawFinalPass::Draw: Pre");
DrawFinalPassState state;
m_ForwardPlusProgram->Bind();
GLuint shaderHandle = m_ForwardPlusProgram->GetHandle();
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, m_LightCullingPass->LightSSBO());
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightCullingPass->LightGridSSBO());
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightCullingPass->LightIndexSSBO());
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(m_Renderer->Camera()->ViewMatrix()));
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(m_Renderer->Camera()->ProjectionMatrix()));
//TODO: Render: Add code for more jobs than modeljobs.
for (auto &job : rq.Forward) {
auto modelJob = std::dynamic_pointer_cast<ModelJob>(job);
if(modelJob) {
//TODO: Kolla upp "header/include/common" shader saken så man slipper skicka in asmycket uniforms
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->ModelMatrix));
glUniform4fv(glGetUniformLocation(shaderHandle, "Color"), 1, glm::value_ptr(modelJob->Color));
if(modelJob->DiffuseTexture != nullptr) {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, modelJob->DiffuseTexture->m_Texture);
} else {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture);
}
glBindVertexArray(modelJob->Model->VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer);
glDrawElementsBaseVertex(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, 0, modelJob->StartIndex);
continue;
}
}
GLERROR("DrawFinalPass::Draw: END");
}
@@ -0,0 +1,17 @@
#include "Rendering/DrawFinalPassState.h"
DrawFinalPassState::DrawFinalPassState()
{
BindFramebuffer(0);
Enable(GL_DEPTH_TEST);
Enable(GL_CULL_FACE);
ClearColor(glm::vec4(200.f / 255, 0.f / 255, 200.f / 255, 0.f));
Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
DrawFinalPassState::~DrawFinalPassState()
{
}
+69
View File
@@ -0,0 +1,69 @@
#include "Rendering/DrawScenePass.h"
DrawScenePass::DrawScenePass(IRenderer* renderer)
{
m_Renderer = renderer;
InitializeTextures();
InitializeShaderPrograms();
}
void DrawScenePass::InitializeTextures()
{
m_WhiteTexture = ResourceManager::Load<Texture>("Textures/Core/Blank.png");
}
void DrawScenePass::InitializeShaderPrograms()
{
m_BasicForwardProgram = ResourceManager::Load<ShaderProgram>("#BasicForwardProgram");
m_BasicForwardProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/BasicForward.vert.glsl")));
m_BasicForwardProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/BasicForward.frag.glsl")));
m_BasicForwardProgram->Compile();
m_BasicForwardProgram->Link();
}
void DrawScenePass::Draw(RenderQueueCollection& rq)
{
//glBindFramebuffer(GL_FRAMEBUFFER, 0);
GLERROR("DrawScenePass::Draw: Pre");
DrawScenePassState state;
m_BasicForwardProgram->Bind();
//TODO: Render: Add code for more jobs than modeljobs.
for (auto &job : rq.Forward) {
auto modelJob = std::dynamic_pointer_cast<ModelJob>(job);
if (modelJob) {
GLuint ShaderHandle = m_BasicForwardProgram->GetHandle();
//TODO: Kolla upp "header/include/common" shader saken så man slipper skicka in asmycket uniforms
glUniformMatrix4fv(glGetUniformLocation(ShaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->ModelMatrix));
glUniformMatrix4fv(glGetUniformLocation(ShaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(m_Renderer->Camera()->ViewMatrix()));
glUniformMatrix4fv(glGetUniformLocation(ShaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(m_Renderer->Camera()->ProjectionMatrix()));
glUniform4fv(glGetUniformLocation(ShaderHandle, "Color"), 1, glm::value_ptr(modelJob->Color));
//TODO: Renderer: bättre textur felhantering samt fler texturer stöd
if (modelJob->DiffuseTexture != nullptr) {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, modelJob->DiffuseTexture->m_Texture);
} else {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture);
}
glBindVertexArray(modelJob->Model->VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer);
glDrawElementsBaseVertex(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, 0, modelJob->StartIndex);
continue;
}
auto spriteJob = std::dynamic_pointer_cast<SpriteJob>(job);
if(spriteJob)
{
//Hello im a sprite, please draw me.
}
}
GLERROR("DrawScenePass::Draw: End");
}

Some files were not shown because too many files have changed in this diff Show More