152 Commits

Author SHA1 Message Date
Jace f813f8d2ca What is this I don't even *falls asleep* 2014-05-27 10:25:52 +02:00
Jace f31b2b7ddb Merge branch 'render_queue'
Conflicts:
	src/GameWorld.cpp
	src/Renderer.cpp
	src/Shaders/Fragment.glsl
	src/Systems/PhysicsSystem.h
	vs11/Returngeance/Returngeance.vcxproj.filters
2014-05-27 09:35:52 +02:00
ViktorLjung f775864ed2 Fishy 2014-05-27 09:10:59 +02:00
Jace 7b622d530b No shadows and no skybox. 2014-05-27 08:35:39 +02:00
Jace 98167a806d Merge remote-tracking branch 'origin/deffered_rendering' into render_queue
Conflicts:
	src/Renderer.cpp
	src/Renderer.h
2014-05-27 07:10:50 +02:00
ViktorLjung c37df5c178 Damage and Spashdamage working, phantomShapes not really working 2014-05-27 07:04:29 +02:00
Jace d4b28a2228 Semi-working world rendering 2014-05-27 06:45:26 +02:00
Tleety 2db52ded2f Direction light working.
Cleaned up some code in Renderer.cpp
2014-05-27 03:09:52 +02:00
Jace 74239300bd Merge commit 'e3aab96a750d6e5d6f8ff42ffdb5a23a47ab929d' into render_queue
Conflicts:
	assets
	src/GameWorld.cpp
	src/Renderer.cpp
	src/Renderer.h
	src/Systems/RenderSystem.cpp
2014-05-26 04:21:08 +02:00
Jace 22442708cc One hell of a GUI interface (minus graphical)
"how does this even work lol"
2014-05-26 03:33:11 +02:00
Tleety 7d82c43df9 Started work on blend maps 2014-05-26 01:08:10 +02:00
ViktorLjung a0ee235473 Wrong assets 2014-05-26 01:04:31 +02:00
ViktorLjung 9a984dbb10 Broken 2014-05-26 01:03:25 +02:00
Jace 07c74ff9f5 I'll create a GUI interface using Visual Basic, see if I can track an IP address 2014-05-25 04:12:28 +02:00
Tleety e3aab96a75 Fixed forward rendering for transparensy 2014-05-25 01:52:57 +02:00
Jace 2fbcad4dbf Layer in render queue? 2014-05-24 20:32:54 +02:00
ViktorLjung dff888f82d Merge remote-tracking branch 'origin/master' into havok 2014-05-24 18:35:26 +02:00
ViktorLjung 60b8ad6799 Assets 2014-05-24 18:35:11 +02:00
Jace 1bf5a8464e Merge branch 'events' 2014-05-23 23:42:00 +02:00
Jace e48df894cf Better events 2014-05-23 23:41:34 +02:00
Tleety a9f2911e41 Shadows working, and looking totaly not shit.
Improved location of the shadowmap to always be infront of the camera.
2014-05-23 22:42:11 +02:00
ViktorLjung a674295a83 Collisionfilters 2014-05-22 22:05:06 +02:00
Jace 4102756e33 Beautifully broken 2014-05-22 22:04:54 +02:00
ViktorLjung 6137adf604 Rockets deleted properly 2014-05-21 18:30:16 +02:00
Tleety dbad1ee7f5 Work done on light and shadows. 2014-05-21 16:51:05 +02:00
Jace 6d3aa5d394 Red rocket 2014-05-20 04:34:44 +02:00
ViktorLjung 7e5cf8efaa Fuckhack 2014-05-20 03:41:10 +02:00
ViktorLjung fe400e9af8 Merge remote-tracking branch 'origin/particles'
Conflicts:
	src/GameWorld.cpp
	src/Systems/ParticleSystem.cpp
2014-05-20 03:40:44 +02:00
Tleety e414087816 Some work done on lights and normals and other buggs/fixes 2014-05-20 03:33:42 +02:00
ViktorLjung 609687d6b4 MULTIPLAYER 2014-05-20 01:43:59 +02:00
Stiffly 65acae410d Added Explosion function to particles 2014-05-20 00:38:30 +02:00
ViktorLjung ff58f881ae Merge branch 'havok' into gui
Conflicts:
	vs11/Returngeance/Returngeance.vcxproj.filters
2014-05-19 22:06:04 +02:00
ViktorLjung ec74d700be fix 2014-05-19 21:57:13 +02:00
Jace 40718407ac Merge remote-tracking branch 'origin/master' into gui
Conflicts:
	src/GameWorld.cpp
	src/InputManager.cpp
	src/Systems/RenderSystem.cpp
	vs11/Returngeance/Returngeance.vcxproj.filters
2014-05-19 21:51:25 +02:00
Tleety 82d5953c97 Specular maps working. 2014-05-19 21:36:28 +02:00
ViktorLjung 7f77db97a0 Convert functions working in debug 2014-05-19 19:59:17 +02:00
Jace bd7ba73bca Split screen working 2014-05-19 17:20:43 +02:00
Jace e07a0a2b1a More viewport stuff 2014-05-19 04:29:30 +02:00
Jace 3023391358 Merge remote-tracking branch 'origin/deffered_rendering' into gui
Conflicts:
	assets
	src/GameWorld.cpp
2014-05-19 03:15:40 +02:00
Tleety 7455f4b865 NormalMaps Working and started work on specular maps. 2014-05-19 01:01:46 +02:00
ViktorLjung 998ee3cfab Brakes working 2014-05-19 00:58:48 +02:00
Jace 539196cd45 Viewport stuff 2014-05-19 00:55:58 +02:00
ViktorLjung f14a83caa8 Assets 2014-05-18 23:59:18 +02:00
ViktorLjung 02243becee Recoil while firing, clamp inputs, merge Helicopter 2014-05-18 23:54:01 +02:00
ViktorLjung 85e5d7461c Merge remote-tracking branch 'origin/vehicle-helicopter' into havok
Conflicts:
	src/GameWorld.cpp
	vs11/Returngeance/Returngeance.vcxproj
2014-05-18 21:09:08 +02:00
ViktorLjung fd0bb18bd3 tank stuff 2014-05-18 21:07:03 +02:00
Stiffly 1a52b1d04c finlir 2014-05-18 20:32:10 +02:00
Jace a36d6c554a Merge branch 'master' into havok
Conflicts:
	assets
	src/GameWorld.cpp
	vs11/Returngeance/Returngeance.vcxproj.filters
2014-05-17 21:23:46 +02:00
ViktorLjung a8ecacab11 tank steering 2014-05-17 18:45:54 +02:00
Tleety 2520fba1b4 Merge remote-tracking branch 'origin/master' into deffered_rendering
Conflicts:
	assets
2014-05-17 18:10:48 +02:00
ViktorLjung 4d15d3e02c Collision callbacks 2014-05-17 18:06:56 +02:00
Tleety 67778f391a Working on shadows 2014-05-17 18:02:10 +02:00
Jace 542ad075ea ECS improved to make it less annoying to use
AddComponent<Components::Transform>(entity, "Transform")
is now
AddComponent<Components::Transform>(entity)
etc.
2014-05-17 17:46:17 +02:00
Jace 16d51c64c5 Meh-ish helicopter physics 2014-05-17 03:49:53 +02:00
Jace add27aa8f4 Back to working order 2014-05-17 01:21:40 +02:00
Jace d98badc59a Latest assets 2014-05-17 00:57:24 +02:00
Jace f180abcd63 Input System improved to allow for multiple inputs for same bind
Did not work properly between keyboard and controller before.
2014-05-17 00:53:51 +02:00
Jace 2a28f65c37 FreeSteeringSystem updated to allow for controller input 2014-05-17 00:50:45 +02:00
Jace 33b14b1859 Mouse locking event 2014-05-17 00:49:23 +02:00
Jace 44e376e815 Pls go away 2014-05-16 02:13:28 +02:00
Jace 9723d80742 And then Microsoft happened... 2014-05-15 21:50:49 +02:00
Jace 6684aa06b7 Merge branch 'master' into gui
Conflicts:
	src/GUI/Frame.h
	src/InputManager.cpp
2014-05-15 21:16:43 +02:00
ViktorLjung 05757b6112 assets 2014-05-15 19:30:44 +02:00
Jace bafa8d0a5d Merge remote-tracking branch 'origin/deffered_rendering'
Conflicts:
	assets
	src/Components/PointLight.h
	src/GameWorld.cpp
	src/Renderer.cpp
	src/Renderer.h
	vs11/Returngeance/Returngeance.vcxproj.filters
2014-05-13 04:07:24 +02:00
ViktorLjung ab58cbc08d Merge branch 'havok' of github.com:sippeangelo/Return-to-the-Return-of-Return-Fire-2-Returngeance into havok
Conflicts:
	src/GameWorld.cpp
	vs11/Returngeance/Returngeance.vcxproj.filters
2014-05-13 03:36:09 +02:00
ViktorLjung ce5b62cf6d Shots fired! ( ゚Д゚) 2014-05-13 03:32:58 +02:00
Jace d259811795 Xbox360 controller support 2014-05-13 02:24:42 +02:00
ViktorLjung 74d3269e35 Merge remote-tracking branch 'origin/particles' into havok
Conflicts:
	src/Components/Vehicle.h
2014-05-13 01:57:28 +02:00
Stiffly df13663ca8 Two emitters and following camera 2014-05-13 01:56:00 +02:00
ViktorLjung b9231e4d46 Shots need more work 2014-05-13 01:50:58 +02:00
Tleety ccd1393dac Fixed some shadow buggs. 2014-05-12 23:02:19 +02:00
Jace ad19848c1b WIP ECS GUI 2014-05-12 22:33:59 +02:00
ViktorLjung 38482431a1 Tank tower and barrel steering working 2014-05-12 22:33:53 +02:00
ViktorLjung 92e9fd1049 fixup! Fixed relative transform rotations (For real this time?) 2014-05-12 22:24:53 +02:00
Stiffly 19a2879104 Emitter childed to a wheel. BUG FIXED: Billboarding calculation. 2014-05-12 22:21:27 +02:00
ViktorLjung ddc41b88a7 Fixed relative transform rotations (For real this time?) 2014-05-12 22:15:21 +02:00
Stiffly 5d48ea7e2a not reversed input for Camera... 2014-05-12 22:05:56 +02:00
Tleety 4639a6e4c3 Working shadows, however ugly they are. 2014-05-12 18:03:39 +02:00
Stiffly 457ee84903 Merge remote-tracking branch 'origin/havok' into particles
Conflicts:
	src/Components/Vehicle.h
2014-05-12 15:43:41 +02:00
ViktorLjung 2aa51c3e90 Tank sterring event-based 2014-05-12 14:04:55 +02:00
ViktorLjung c8a77d5c3d Merge remote-tracking branch 'origin/master' into havok
Conflicts:
	assets
	src/GameWorld.cpp
	vs11/Returngeance/Returngeance.vcxproj.filters
2014-05-12 14:03:02 +02:00
Stiffly e0b5b72454 Merge remote-tracking branch 'origin/master' into particles
Conflicts:
	src/Components/Physics.h
	src/GameWorld.cpp
	src/World.cpp
	src/World.h
	vs11/Returngeance/Returngeance.vcxproj.filters
2014-05-12 13:55:48 +02:00
ViktorLjung d7e5630f1b Tank with 8 wheels 2014-05-11 01:52:00 +02:00
Jace b6372d44b8 Merge branch 'master' into gui 2014-05-11 01:46:12 +02:00
Jace 41177581c6 WIP Render Queue 2014-05-11 01:46:02 +02:00
Tleety d9ca9ac1f7 Removed unused code. 2014-05-11 01:09:06 +02:00
Tleety 37a8af6b65 Added being able to change attenuation in real time 2014-05-11 01:05:22 +02:00
Tleety 22d855a521 Fixed attenuation for lights. 2014-05-11 00:02:34 +02:00
Tleety c1c30b0019 Fixed lights and added a bad gamma correction 2014-05-10 19:51:48 +02:00
Jace d00ff3c2ed Assets now as Git submodule!
(cherry picked from commit 6e6a115ac3)
2014-05-10 19:44:29 +02:00
Jace 4c0b465c7f Assets now as Git submodule!
(cherry picked from commit 6e6a115ac3)
2014-05-10 19:39:29 +02:00
Jace 6e6a115ac3 Assets now as Git submodule! 2014-05-10 19:21:46 +02:00
Tleety 6e3ba0f077 Merge remote-tracking branch 'origin/master' into deffered_rendering 2014-05-10 17:45:01 +02:00
Tleety 1268b3d8fd Removed Unused code in renderer 2014-05-10 17:44:55 +02:00
ViktorLjung 5393113dee Merge branch 'havok' of github.com:sippeangelo/Return-to-the-Return-of-Return-Fire-2-Returngeance into havok
Conflicts:
	src/GameWorld.cpp
2014-05-07 22:33:35 +02:00
ViktorLjung ea69a9345d PhysicsSystem redesigned, more work is needed. 2014-05-07 22:29:03 +02:00
Stiffly 1a365bf069 Billboarding on sprites 2014-05-07 21:34:19 +02:00
Jace 7c18d0c778 Merge branch 'master' into gui 2014-05-06 18:08:32 +02:00
Jace c73da364f4 Derpy skybox un-derped 2014-05-06 18:08:13 +02:00
Jace 0e2a373053 Merge remote-tracking branch 'origin/master' into gui
Conflicts:
	src/GameWorld.cpp
	src/Systems/FreeSteeringSystem.cpp
	src/Systems/PhysicsSystem.cpp
	vs11/Returngeance/Returngeance.vcxproj.filters
2014-05-06 18:05:31 +02:00
Jace a232559bb1 FreeSteeringSystem converted to take input commands 2014-05-06 17:07:38 +02:00
Jace 8c8edd0e8e WIP InputController for easier command handling in systems 2014-05-06 14:33:02 +02:00
Stiffly 398b157b89 Rendering sprites 2014-05-06 13:52:34 +02:00
Jace 469b53c14d Updated model paths 2014-05-06 04:46:22 +02:00
Jace 0e068be77b Basic input binding and command publishing system 2014-05-05 09:17:58 +02:00
Jace 5e7537b903 Input events moved from InputSystem to new InputManager 2014-05-05 07:16:45 +02:00
Jace 330a212830 Rectangle comparison fixed 2014-05-05 07:15:47 +02:00
Stiffly 262d259681 Orientation interpolation complete (v.length() != glm::length(v), the latter is correct) 2014-05-01 02:00:10 +02:00
Stiffly fa9a610353 Almost correct Orientation calculation... 2014-04-29 14:21:52 +02:00
ViktorLjung dc32316bd7 Fixing suspension and car collision shape 2014-04-29 14:21:14 +02:00
Jace 9e8c3161e0 WIP Frame 2014-04-29 13:58:37 +02:00
Jace d0211ef8d6 Encapsulated Renderer WIDTH and HEIGHT variables. 2014-04-29 13:58:27 +02:00
Stiffly a13e9d32ec Generalized interpolation functions. (orientation spectrum not working properly (quaterions...)) 2014-04-29 11:51:57 +02:00
ViktorLjung f471d7732f Vehicle tuning 2014-04-29 03:47:09 +02:00
Stiffly 0feb983277 Made Interpolation functions look nicer 2014-04-28 19:56:18 +02:00
Jace 57d29d0db7 Started implementation of events for InputSystem and SoundSystem 2014-04-28 19:55:31 +02:00
ViktorLjung ed1df6dc60 Proper rotation of child physics objects 2014-04-28 19:51:13 +02:00
Stiffly 68761c9291 Angular velocity support 2014-04-28 19:12:51 +02:00
Stiffly ea4b7b005e Now use the CloneEntity() function to spawn new particles. 2014-04-28 17:56:05 +02:00
Stiffly d917be0135 Default values for ParticleEmitter.h 2014-04-28 17:55:51 +02:00
Jace 5e1355f3fe Optimizations
(cherry picked from commit 7e32946173)
2014-04-28 16:24:17 +02:00
Stiffly 0b8a3230c3 Fixed GetComponent bug which would create invalid components if the entity didn't have the requested component 2014-04-28 16:18:08 +02:00
Jace 6ba50c2d1e Fixed GetComponent bug which would create invalid components if the entity didn't have the requested component 2014-04-28 16:16:03 +02:00
Jace 5870a4d7bf Working event system! 2014-04-28 09:28:18 +02:00
Jace 22138a36aa MessageRelay renamed to EventRelay 2014-04-28 06:03:45 +02:00
Jace 55059c05fe Debugging Optimizations
Removed Basic Runtime Checks flag /RTC1
Added Maximize Speed flag /O2
Changed Debug Information Format flag /ZI -> /Zi
Added Enable Intrinsic Functions flag /Oi
2014-04-28 04:56:37 +02:00
Jace 7e32946173 Optimizations 2014-04-28 04:00:53 +02:00
ViktorLjung 00d27f0058 Physics now running on multiple threads 2014-04-28 02:06:08 +02:00
ViktorLjung 5f3b03fa6d Merge branch 'havok' of github.com:sippeangelo/Return-to-the-Return-of-Return-Fire-2-Returngeance into havok
Conflicts:
	src/GameWorld.cpp
	src/Systems/PhysicsSystem.cpp
	vs11/Returngeance/Returngeance.vcxproj.filters
2014-04-27 08:13:57 +02:00
ViktorLjung 720cf3aa87 Added support for HkpExtendedMeshShape. 2014-04-27 08:08:00 +02:00
ViktorLjung cb6b0a58d8 Resource manager OBJ vs Model conflict fixed 2014-04-27 08:07:18 +02:00
Stiffly 04962155e3 Merge branch 'particles' of github.com:sippeangelo/Return-to-the-Return-of-Return-Fire-2-Returngeance into particles 2014-04-27 07:49:19 +02:00
Jace 04cafc53e2 Implemented entity cloning 2014-04-27 07:48:16 +02:00
Stiffly 28ac8980f2 tested and fixed scale and velocity interpolation. Fix: could not go from lesser value to larger. Added methods for interpolation. 2014-04-27 03:20:14 +02:00
Stiffly 023f49b0ec Implemented support for spread angle for particle emitter. 2014-04-27 00:17:21 +02:00
Stiffly 956e7cab7b BUG FIX: Iterator not increased incorrectly -> No longer a particle stuck in emitter. 2014-04-25 04:32:15 +02:00
Jace f02954a62c Box and Sphere components renamed to BoxShape and SphereShape 2014-04-25 01:05:53 +02:00
Stiffly 166a9f48f1 Added support for multiple emitters. (ParticleEmitter component now friend class to ParticleSystem) 2014-04-25 00:24:13 +02:00
ViktorLjung c4e127b154 Added VehicleSetup to Physics filter. 2014-04-24 23:30:46 +02:00
ViktorLjung be90953f22 Rigidbody position not updating in debug FIXED 2014-04-24 23:29:28 +02:00
Stiffly b07605594d Fixed loop, can't miss particles. (tried to add physics to particles) 2014-04-24 00:44:26 +02:00
Stiffly 5997ee2320 Added models and temporary "fly everywhere" direction to particles 2014-04-24 00:00:29 +02:00
Stiffly 07bc49e3c1 Bug fix: fixed time to correct resolution, seconds. 2014-04-23 22:46:19 +02:00
Stiffly 100f8f5be4 Bug fix: checked for particles not created 2014-04-23 21:33:43 +02:00
Jace dfd9425473 WIP Frame 2014-04-23 02:19:17 +02:00
Jace ee34b15cf1 Rectangle class. 2014-04-23 01:36:03 +02:00
Jace 1e2f7fdd5c Skeleton MessageRelay 2014-04-22 19:15:02 +02:00
Stiffly bdac6fa9f9 Added velocity interpolation 2014-04-22 18:58:41 +02:00
Stiffly 78d4dbf8c2 Added scale and color interpolation 2014-04-22 17:59:55 +02:00
Stiffly 55221cca12 Implemented Spawn and Remove function for particles. Also added a Particle component. 2014-04-22 16:52:14 +02:00
Stiffly 2efb5405eb Merge branch 'master' of github.com:sippeangelo/Return-to-the-Return-of-Return-Fire-2-Returngeance
Conflicts:
	vs11/Returngeance/Returngeance.vcxproj.filters
2014-04-22 11:08:10 +02:00
Stiffly 5e402af093 Added ParticleSystem skeleton plus basic temporary implementation. 2014-04-17 00:08:27 +02:00
148 changed files with 8293 additions and 1411 deletions
-1
View File
@@ -31,5 +31,4 @@ ipch/
Ankh.NoLoad Ankh.NoLoad
*.orig *.orig
assets/
!libs/*.lib !libs/*.lib
+4
View File
@@ -0,0 +1,4 @@
[submodule "assets"]
path = assets
url = returngeance@shard.imon.nu:Assets
branch = master
Submodule
+1
Submodule assets added at bc811a1b39
+21 -34
View File
@@ -1,25 +1,21 @@
#include "PrecompiledHeader.h" #include "PrecompiledHeader.h"
#include "Camera.h" #include "Camera.h"
Camera::Camera(float yFOV, float aspectRatio, float nearClip, float farClip) Camera::Camera(float yFOV, float nearClip, float farClip)
{ {
m_FOV = yFOV; m_FOV = yFOV;
m_AspectRatio = aspectRatio;
m_NearClip = nearClip; m_NearClip = nearClip;
m_FarClip = farClip; m_FarClip = farClip;
m_Position = glm::vec3(0.0); m_Position = glm::vec3(0.0);
/*m_Pitch = 0.f;
m_Yaw = 0.f;*/
UpdateProjectionMatrix();
UpdateViewMatrix(); UpdateViewMatrix();
} }
//glm::vec3 Camera::Forward() glm::vec3 Camera::Forward()
//{ {
// return glm::rotate(glm::vec3(0.f, 0.f, -1.f), -m_Yaw, glm::vec3(0.f, 1.f, 0.f)); return m_Orientation * glm::vec3(0, 0, -1);
//} }
// //
//glm::vec3 Camera::Right() //glm::vec3 Camera::Right()
//{ //{
@@ -34,20 +30,14 @@ Camera::Camera(float yFOV, float aspectRatio, float nearClip, float farClip)
// return orientation; // return orientation;
//} //}
void Camera::AspectRatio(float val) void Camera::SetPosition(glm::vec3 val)
{
m_AspectRatio = val;
UpdateProjectionMatrix();
}
void Camera::Position(glm::vec3 val)
{ {
m_Position = val; m_Position = val;
UpdateViewMatrix(); UpdateViewMatrix();
} }
void Camera::Orientation(glm::quat val) void Camera::SetOrientation(glm::quat val)
{ {
m_Orientation = val; m_Orientation = val;
UpdateViewMatrix(); UpdateViewMatrix();
@@ -65,35 +55,32 @@ void Camera::Orientation(glm::quat val)
// UpdateViewMatrix(); // UpdateViewMatrix();
//} //}
void Camera::UpdateProjectionMatrix()
{
m_ProjectionMatrix = glm::perspective(
m_FOV,
m_AspectRatio,
m_NearClip,
m_FarClip
);
}
void Camera::UpdateViewMatrix() void Camera::UpdateViewMatrix()
{ {
m_ViewMatrix = glm::toMat4(glm::inverse(m_Orientation)) * glm::translate(-m_Position); m_ViewMatrix = glm::toMat4(glm::inverse(m_Orientation)) * glm::translate(-m_Position);
} }
void Camera::FOV(float val) void Camera::SetFOV(float val)
{ {
m_FOV = val; m_FOV = val;
UpdateProjectionMatrix();
} }
void Camera::NearClip(float val) void Camera::SetNearClip(float val)
{ {
m_NearClip = val; m_NearClip = val;
UpdateProjectionMatrix();
} }
void Camera::FarClip(float val) void Camera::SetFarClip(float val)
{ {
m_FarClip = val; m_FarClip = val;
UpdateProjectionMatrix(); }
}
glm::mat4 Camera::ProjectionMatrix(float aspectRatio)
{
return glm::perspective(
m_FOV,
aspectRatio,
m_NearClip,
m_FarClip
);
}
+7 -19
View File
@@ -1,60 +1,48 @@
#ifndef Camera_h__ #ifndef Camera_h__
#define Camera_h__ #define Camera_h__
//#include "PrecompiledHeader.h"
class Camera class Camera
{ {
public: public:
Camera(float yFOV, float aspectRatio, float nearClip, float farClip); Camera(float yFOV, float nearClip, float farClip);
glm::vec3 Forward(); glm::vec3 Forward();
glm::vec3 Right(); glm::vec3 Right();
float AspectRatio() const { return m_AspectRatio; }
void AspectRatio(float val);
glm::vec3 Position() const { return m_Position; } glm::vec3 Position() const { return m_Position; }
void Position(glm::vec3 val); void SetPosition(glm::vec3 val);
glm::quat Orientation() const { return m_Orientation; } glm::quat Orientation() const { return m_Orientation; }
void Orientation(glm::quat val); void SetOrientation(glm::quat val);
/*float Pitch() const { return m_Pitch; } /*float Pitch() const { return m_Pitch; }
void Pitch(float val); void Pitch(float val);
float Yaw() const { return m_Yaw; } float Yaw() const { return m_Yaw; }
void Yaw(float val);*/ void Yaw(float val);*/
glm::mat4 ProjectionMatrix() const { return m_ProjectionMatrix; } glm::mat4 ProjectionMatrix(float aspectRatio);
void ProjectionMatrix(glm::mat4 val) { m_ProjectionMatrix = val; }
glm::mat4 ViewMatrix() const { return m_ViewMatrix; } glm::mat4 ViewMatrix() const { return m_ViewMatrix; }
void ViewMatrix(glm::mat4 val) { m_ViewMatrix = val; }
float FOV() const { return m_FOV; } float FOV() const { return m_FOV; }
void FOV(float val); void SetFOV(float val);
float NearClip() const { return m_NearClip; } float NearClip() const { return m_NearClip; }
void NearClip(float val); void SetNearClip(float val);
float FarClip() const { return m_FarClip; } float FarClip() const { return m_FarClip; }
void FarClip(float val); void SetFarClip(float val);
private: private:
void UpdateProjectionMatrix();
void UpdateViewMatrix(); void UpdateViewMatrix();
float m_FOV; float m_FOV;
float m_AspectRatio;
float m_NearClip; float m_NearClip;
float m_FarClip; float m_FarClip;
glm::vec3 m_Position; glm::vec3 m_Position;
glm::quat m_Orientation; glm::quat m_Orientation;
//float m_Pitch;
//float m_Yaw;
glm::mat4 m_ProjectionMatrix;
glm::mat4 m_ViewMatrix; glm::mat4 m_ViewMatrix;
}; };
+2
View File
@@ -7,6 +7,8 @@
struct Component struct Component
{ {
EntityID Entity; EntityID Entity;
virtual Component* Clone() const = 0;
}; };
class ComponentFactory : public Factory<Component*> { }; class ComponentFactory : public Factory<Component*> { };
+23
View File
@@ -0,0 +1,23 @@
#ifndef BarrelSteering_h__
#define BarrelSteering_h__
#include "Component.h"
namespace Components
{
struct BarrelSteering : Component
{
BarrelSteering()
: TurnSpeed(1.f), Axis(glm::vec3(0,1,0)){ }
float TurnSpeed;
glm::vec3 Axis;
EntityID ShotTemplate;
float ShotSpeed;
virtual BarrelSteering* Clone() const override { return new BarrelSteering(*this); }
};
}
#endif // BarrelSteering_h__
@@ -6,14 +6,16 @@
namespace Components namespace Components
{ {
struct Box : Component struct BoxShape : Component
{ {
Box() BoxShape()
: Width(1.f), Height(1.f), Depth(1.f){ } : Width(1.f), Height(1.f), Depth(1.f){ }
float Width; float Width;
float Height; float Height;
float Depth; float Depth;
virtual BoxShape* Clone() const override { return new BoxShape(*this); }
}; };
} }
+7 -1
View File
@@ -2,17 +2,23 @@
#define Components_Camera_h__ #define Components_Camera_h__
#include "Component.h" #include "Component.h"
#include "Entity.h"
namespace Components namespace Components
{ {
struct Camera : Component struct Camera : Component
{ {
Camera() : FOV(glm::radians(45.f)), NearClip(0.1f), FarClip(100.f) { } Camera()
: FOV(glm::radians(45.f))
, NearClip(0.1f)
, FarClip(100.f) { }
float FOV; float FOV;
float NearClip; float NearClip;
float FarClip; float FarClip;
virtual Camera* Clone() const override { return new Camera(*this); }
}; };
} }
+2
View File
@@ -13,6 +13,8 @@ struct DirectionalLight : Component
float MaxRange; float MaxRange;
float SpecularIntensity; float SpecularIntensity;
Color Color; Color Color;
virtual DirectionalLight* Clone() const override { return new DirectionalLight(*this); }
}; };
} }
View File
+17
View File
@@ -0,0 +1,17 @@
#ifndef Components_Flag_h__
#define Components_Flag_h__
#include "Component.h"
namespace Components
{
struct Flag : Component
{
virtual Flag* Clone() const override { return new Flag(*this); }
};
}
#endif // Components_TankShell_h__
+17
View File
@@ -0,0 +1,17 @@
#ifndef Components_FrameTimer_h__
#define Components_FrameTimer_h__
#include "Component.h"
namespace Components
{
struct FrameTimer : public Component
{
int Frames;
virtual FrameTimer* Clone() const override { return new FrameTimer(*this); }
};
}
#endif // Components_FrameTimer_h__
+2
View File
@@ -9,6 +9,8 @@ struct FreeSteering : Component
{ {
FreeSteering() : Speed(35) { } FreeSteering() : Speed(35) { }
float Speed; float Speed;
virtual FreeSteering* Clone() const override { return new FreeSteering(*this); }
}; };
} }
+21
View File
@@ -0,0 +1,21 @@
#ifndef Components_Health_h__
#define Components_Health_h__
#include "Component.h"
namespace Components
{
struct Health : Component
{
Health()
: health(1.0f){ }
float health;
virtual Health* Clone() const override { return new Health(*this); }
};
}
#endif // Components_Health_h__
+16
View File
@@ -0,0 +1,16 @@
#ifndef HelicopterSteering_h__
#define HelicopterSteering_h__
#include "Component.h"
namespace Components
{
struct HelicopterSteering : Component
{
HelicopterSteering* Clone() const override { return new HelicopterSteering(*this); }
};
}
#endif // HelicopterSteering_h__
+20
View File
@@ -0,0 +1,20 @@
#ifndef Components_HingeConstraint_h__
#define Components_HingeConstraint_h__
#include "Component.h"
namespace Components
{
struct HingeConstraint : Component
{
EntityID LinkedEntity;
glm::vec3 Pivot;
glm::vec3 Axis;
virtual HingeConstraint* Clone() const override { return new HingeConstraint(*this); }
};
}
#endif // Components_HingeConstraint_h__
+10 -10
View File
@@ -1,10 +1,6 @@
#ifndef Components_Input_h__ #ifndef Components_Input_h__
#define Components_Input_h__ #define Components_Input_h__
#include <array>
#include <GLFW/glfw3.h>
#include "Component.h" #include "Component.h"
namespace Components namespace Components
@@ -12,12 +8,16 @@ namespace Components
struct Input : Component struct Input : Component
{ {
std::array<int, GLFW_KEY_LAST+1> KeyState; /*Input()
std::array<int, GLFW_KEY_LAST+1> LastKeyState; : Keyboard(false)
std::array<int, GLFW_MOUSE_BUTTON_LAST+1> MouseState; , Mouse(false)
std::array<int, GLFW_MOUSE_BUTTON_LAST+1> LastMouseState; , GamepadID(0) { }
float dX, dY;
float WheelDelta; bool Keyboard;
bool Mouse;
int GamepadID;*/
virtual Input* Clone() const override { return new Input(*this); }
}; };
} }
+19
View File
@@ -0,0 +1,19 @@
#ifndef Components_MeshShape_h__
#define Components_MeshShape_h__
#include <string>
#include "Component.h"
namespace Components
{
struct MeshShape : Component
{
std::string ResourceName;
virtual MeshShape* Clone() const override { return new MeshShape(*this); }
};
}
#endif // !Components_MeshShape_h__
+2
View File
@@ -16,6 +16,8 @@ struct Model : Component
Color Color; Color Color;
bool Visible; bool Visible;
bool ShadowCaster; bool ShadowCaster;
virtual Model* Clone() const override { return new Model(*this); }
}; };
} }
+25
View File
@@ -0,0 +1,25 @@
#ifndef Components_Particle_h__
#define Components_Particle_h__
#include "System.h"
#include "Component.h"
#include "Color.h"
#include <vector>
namespace Components
{
struct Particle : Component
{
std::vector<Color> ColorSpectrum;
std::vector<glm::vec3> ScaleSpectrum;
double LifeTime;
std::vector<glm::vec3> VelocitySpectrum;
std::vector<float> AngularVelocitySpectrum;
std::vector<glm::vec3> OrientationSpectrum; //Keep?
virtual Particle* Clone() const override { return new Particle(*this); }
};
}
#endif // !Components_Particle_h__
+25 -5
View File
@@ -5,20 +5,40 @@
#include "Color.h" #include "Color.h"
#include <vector> #include <vector>
namespace Systems { class ParticleSystem; }
namespace Components namespace Components
{ {
struct ParticleEmitter : Component struct ParticleEmitter : Component
{ {
int ParticleTemplate; friend class Systems::ParticleSystem;
ParticleEmitter()
: SpawnFrequency(0)
, SpawnCount(0)
, SpreadAngle(0)
, LifeTime(0)
, TimeSinceLastSpawn(100) { } // TEMP fulhack så att partiklarna spawnar direkt
EntityID ParticleTemplate;
float SpawnFrequency; float SpawnFrequency;
float Speed;
int SpawnCount; int SpawnCount;
std::vector<Color> ColorSpectrum; std::vector<Color> ColorSpectrum;
std::vector<float> ScaleSpectrum; std::vector<glm::vec3> ScaleSpectrum;
float SpreadAngle; float SpreadAngle;
float LifeTime; double LifeTime;
std::vector<float[3]> VelocitySpectrum; bool UseGoalVelocity;
std::vector<float[3]> AngularVelocitySpectrum; glm::vec3 GoalVelocity;
std::vector<float> AngularVelocitySpectrum;
std::vector<glm::vec3> OrientationSpectrum; //Keep?
private:
double TimeSinceLastSpawn;
virtual ParticleEmitter* Clone() const override { return new ParticleEmitter(*this); }
}; };
} }
+25 -1
View File
@@ -9,10 +9,34 @@ namespace Components
struct Physics : Component struct Physics : Component
{ {
Physics() Physics()
: Mass(0.f), Static(false){} : Mass(1.f), Static(false), Phantom(false), CalculateCenterOfMass(true), CenterOfMass(glm::vec3(0)), InitialLinearVelocity(glm::vec3(0)), InitialAngularVelocity(glm::vec3(0)),
LinearDamping(0.f), AngularDamping(0.05f), GravityFactor(1.f), Friction(0.5f), Restitution(0.4f), MaxLinearVelocity(200.f), MaxAngularVelocity(200.f),
CollisionLayer(0), CollisionSystemGroup(0), CollisionSubSystemId(0), CollisionSubSystemDontCollideWith(0), CollisionEvent(false){}
float Mass; float Mass;
bool Static; bool Static;
bool Phantom;
bool CalculateCenterOfMass;
glm::vec3 CenterOfMass;
glm::vec3 InitialLinearVelocity;
glm::vec3 InitialAngularVelocity;
float LinearDamping;
float AngularDamping;
float GravityFactor;
float Friction;
float Restitution;
float MaxLinearVelocity;
float MaxAngularVelocity;
int CollisionLayer;
int CollisionSystemGroup;
int CollisionSubSystemId;
int CollisionSubSystemDontCollideWith;
bool CollisionEvent;
virtual Physics* Clone() const override { return new Physics(*this); }
}; };
} }
+21
View File
@@ -0,0 +1,21 @@
#ifndef Player_h__
#define Player_h__
#include "Component.h"
namespace Components
{
struct Player : Component
{
Player()
: ID(0) { }
int ID;
virtual Player* Clone() const override { return new Player(*this); }
};
}
#endif // Player_h__
+15 -4
View File
@@ -9,15 +9,26 @@ namespace Components
struct PointLight : Component struct PointLight : Component
{ {
float Intensity; PointLight()
float MaxRange; : Specular(1.0f, 1.0f, 1.0f)
float constantAttenuation, linearAttenuation, quadraticAttenuation; , Diffuse(1.0f, 1.0f, 1.0f)
float spotExponent; , specularExponent(50.0f)
, ConstantAttenuation(1.0f)
, LinearAttenuation(0.f)
, QuadraticAttenuation(3.f)
, Radius(5.f)
{ }
float ConstantAttenuation, LinearAttenuation, QuadraticAttenuation;
float Radius;
Color color; Color color;
glm::vec3 Specular; glm::vec3 Specular;
glm::vec3 Diffuse; glm::vec3 Diffuse;
float specularExponent; float specularExponent;
float Scale;
virtual PointLight* Clone() const override { return new PointLight(*this); }
}; };
} }
+2
View File
@@ -17,6 +17,8 @@ struct SoundEmitter : Component
float Pitch; float Pitch;
bool Loop; bool Loop;
std::string Path; std::string Path;
virtual SoundEmitter* Clone() const override { return new SoundEmitter(*this); }
}; };
} }
@@ -6,12 +6,14 @@
namespace Components namespace Components
{ {
struct Sphere : Component struct SphereShape : Component
{ {
Sphere() SphereShape()
: Radius(1.f){ } : Radius(1.f){ }
float Radius; float Radius;
virtual SphereShape* Clone() const override { return new SphereShape(*this); }
}; };
} }
+2
View File
@@ -13,6 +13,8 @@ struct Sprite : Component
{ {
std::string SpriteFile; std::string SpriteFile;
Color Color; Color Color;
virtual Sprite* Clone() const override { return new Sprite(*this); }
}; };
} }
+23
View File
@@ -0,0 +1,23 @@
#ifndef Components_TankShell_h__
#define Components_TankShell_h__
#include "Component.h"
namespace Components
{
struct TankShell : Component
{
TankShell()
: Damage(1.0f){ }
float Damage;
float ExplosionRadius;
float ExplosionStrength;
virtual TankShell* Clone() const override { return new TankShell(*this); }
};
}
#endif // Components_TankShell_h__
+17
View File
@@ -0,0 +1,17 @@
#ifndef TankSteering_h__
#define TankSteering_h__
#include "Component.h"
namespace Components
{
struct TankSteering : Component
{
EntityID Player;
EntityID Turret;
EntityID Barrel;
TankSteering* Clone() const override { return new TankSteering(*this); }
};
}
#endif // TankSteering_h__
+6 -1
View File
@@ -6,7 +6,12 @@
namespace Components namespace Components
{ {
struct Template : Component { }; struct Template
: public Component
{
virtual Template* Clone() const override { return nullptr; }
};
} }
#endif // !Components_Template_h__ #endif // !Components_Template_h__
+17
View File
@@ -0,0 +1,17 @@
#ifndef Components_Timer_h__
#define Components_Timer_h__
#include "Component.h"
namespace Components
{
struct Timer : public Component
{
double Time;
virtual Timer* Clone() const override { return new Timer(*this); }
};
}
#endif // Components_Timer_h__
+20
View File
@@ -0,0 +1,20 @@
#ifndef TowerSteering_h__
#define TowerSteering_h__
#include "Component.h"
namespace Components
{
struct TowerSteering : Component
{
TowerSteering()
: TurnSpeed(1.f), Axis(glm::vec3(0,1,0)){ }
float TurnSpeed;
glm::vec3 Axis;
virtual TowerSteering* Clone() const override { return new TowerSteering(*this); }
};
}
#endif // TowerSteering_h__
+3 -1
View File
@@ -6,7 +6,7 @@
namespace Components namespace Components
{ {
struct Transform : Component struct Transform : public Component
{ {
Transform() Transform()
: Scale(glm::vec3(1.f)) { } : Scale(glm::vec3(1.f)) { }
@@ -15,6 +15,8 @@ struct Transform : Component
glm::quat Orientation; glm::quat Orientation;
glm::vec3 Velocity; glm::vec3 Velocity;
glm::vec3 Scale; glm::vec3 Scale;
virtual Transform* Clone() const override { return new Transform(*this); }
}; };
} }
+17
View File
@@ -0,0 +1,17 @@
#ifndef Trigger_h__
#define Trigger_h__
#include "Component.h"
namespace Components
{
struct Trigger : Component
{
bool TriggerOnce;
virtual Trigger* Clone() const override { return new Trigger(*this); }
};
}
#endif // Trigger_h__
+22
View File
@@ -0,0 +1,22 @@
#ifndef TriggerExplosion_h__
#define TriggerExplosion_h__
#include "Component.h"
namespace Components
{
struct TriggerExplosion : Component
{
TriggerExplosion()
: MaxVelocity(1.f), Radius(1.f){ }
// Velocity = (1 - (distance / radius)^2) * Strength;
float MaxVelocity;
float Radius; //HACK: Radius should only be in the SphereShapeComponent
virtual TriggerExplosion* Clone() const override { return new TriggerExplosion(*this); }
};
}
#endif // TriggerExplosion_h__
+7 -1
View File
@@ -10,7 +10,8 @@ namespace Components
struct Vehicle : Component struct Vehicle : Component
{ {
Vehicle() Vehicle()
: MaxTorque(500.0f), MinRPM(1000.0f), OptimalRPM(5500.0f), MaxRPM(7500.0f), MaxSteeringAngle(35), TopSpeed(50.0f) { } : MaxTorque(1000.0f), MinRPM(1000.0f), OptimalRPM(3000.0f), MaxRPM(4000.0f), MaxSteeringAngle(35), TopSpeed(130.0f),
MaxSpeedFullSteeringAngle(40.0f), SpringDamping(1.f){ }
float MaxTorque; float MaxTorque;
float MinRPM; float MinRPM;
@@ -18,7 +19,12 @@ struct Vehicle : Component
float MaxRPM; float MaxRPM;
// Degrees // Degrees
float MaxSteeringAngle; float MaxSteeringAngle;
//TopSpeed not working fully yet
float TopSpeed; float TopSpeed;
float MaxSpeedFullSteeringAngle;
float SpringDamping;
Vehicle* Clone() const override { return new Vehicle(*this); }
}; };
} }
+29
View File
@@ -0,0 +1,29 @@
#ifndef Components_Viewport_h__
#define Components_Viewport_h__
#include "Component.h"
namespace Components
{
struct Viewport : Component
{
Viewport()
: Left(0.f)
, Top(0.f)
, Right(1.f)
, Bottom(1.f)
, Camera(0) { }
float Left;
float Top;
float Right;
float Bottom;
EntityID Camera;
virtual Viewport* Clone() const override { return new Viewport(*this); }
};
}
#endif // Components_Viewport_h__
+5 -1
View File
@@ -14,7 +14,7 @@ struct Wheel : Component
Wheel() Wheel()
: AxleID(0), Radius(0), Width(0), Mass(0), Steering(false), DownDirection(glm::vec3(0, -1, 0)), Friction(1.5f), SlipAngle(0.0f), : AxleID(0), Radius(0), Width(0), Mass(0), Steering(false), DownDirection(glm::vec3(0, -1, 0)), Friction(1.5f), SlipAngle(0.0f),
MaxBreakingTorque(1500.0f), ConnectedToHandbrake(false), SuspensionStrength(50.0f) { } MaxBreakingTorque(50000.f), ConnectedToHandbrake(false), SuspensionStrength(50.0f), TorqueRatio(0.25f) { }
// The Hardpoint MUST be positioned INSIDE the chassis. // The Hardpoint MUST be positioned INSIDE the chassis.
glm::vec3 Hardpoint; glm::vec3 Hardpoint;
@@ -30,10 +30,14 @@ struct Wheel : Component
float SlipAngle; float SlipAngle;
float MaxBreakingTorque; float MaxBreakingTorque;
bool ConnectedToHandbrake; bool ConnectedToHandbrake;
// The wheels total TorqueRatio must be equal to 1
float TorqueRatio;
private: private:
int ID; int ID;
glm::quat OriginalOrientation; glm::quat OriginalOrientation;
Wheel* Clone() const override { return new Wheel(*this); }
}; };
} }
+18
View File
@@ -0,0 +1,18 @@
#ifndef Components_WheelPair_h__
#define Components_WheelPair_h__
#include "Component.h"
namespace Components
{
struct WheelPair : Component
{
// Flag for pair wheels
virtual WheelPair* Clone() const override { return new WheelPair(*this); }
};
}
#endif // Components_WheelPair_h__
+46 -8
View File
@@ -1,19 +1,42 @@
#include <string> #include <string>
#include <sstream> #include <sstream>
#include "ResourceManager.h"
#include "OBJ.h"
#include "Model.h"
#include "Texture.h"
#include "EventBroker.h"
#include "RenderQueue.h"
#include "Renderer.h" #include "Renderer.h"
#include "GameWorld.h" #include "InputManager.h"
#include "GUI/Frame.h"
#include "GUI/GameFrame.h"
class Engine class Engine
{ {
public: public:
Engine(int argc, char* argv[]) Engine(int argc, char* argv[])
{ {
m_Renderer = std::make_shared<Renderer>(); m_EventBroker = std::make_shared<EventBroker>();
m_ResourceManager = std::make_shared<ResourceManager>();
m_ResourceManager->RegisterType("OBJ", [](std::string resourceName) { return new OBJ(resourceName); });
auto rm = m_ResourceManager;
m_ResourceManager->RegisterType("Model", [rm](std::string resourceName) { return new Model(rm, *rm->Load<OBJ>("OBJ", resourceName)); });
m_ResourceManager->RegisterType("Texture", [](std::string resourceName) { return new Texture(resourceName); });
m_Renderer = std::make_shared<Renderer>(m_ResourceManager);
m_Renderer->Initialize(); m_Renderer->Initialize();
m_World = std::make_shared<GameWorld>(m_Renderer); m_InputManager = std::make_shared<InputManager>(m_Renderer->GetWindow(), m_EventBroker);
m_World->Initialize();
m_FrameStack = new GUI::Frame(m_EventBroker, m_ResourceManager);
m_FrameStack->Width = 1280;
m_FrameStack->Height = 720;
new GUI::GameFrame(m_FrameStack, "GameFrame");
//m_World = std::make_shared<GameWorld>(m_EventBroker, m_ResourceManager);
//m_World->Initialize();
m_LastTime = glfwGetTime(); m_LastTime = glfwGetTime();
} }
@@ -23,19 +46,34 @@ public:
void Tick() void Tick()
{ {
double currentTime = glfwGetTime(); double currentTime = glfwGetTime();
double dt = currentTime - m_LastTime; double dt = currentTime - m_LastTime;
m_LastTime = currentTime; m_LastTime = currentTime;
m_World->Update(dt); // Update input
m_Renderer->Draw(dt); m_InputManager->Update(dt);
// Update frame stack
m_EventBroker->Process<GUI::Frame>();
m_FrameStack->UpdateLayered(dt);
// Render scene
m_FrameStack->DrawLayered(m_Renderer);
m_Renderer->Swap();
// Swap event queues
m_EventBroker->Clear();
glfwPollEvents(); glfwPollEvents();
} }
private: private:
std::shared_ptr<ResourceManager> m_ResourceManager;
std::shared_ptr<EventBroker> m_EventBroker;
std::shared_ptr<Renderer> m_Renderer; std::shared_ptr<Renderer> m_Renderer;
std::shared_ptr<InputManager> m_InputManager;
GUI::Frame* m_FrameStack;
// TODO: This should ultimately live in GameFrame // TODO: This should ultimately live in GameFrame
std::shared_ptr<GameWorld> m_World; //std::shared_ptr<GameWorld> m_World;
double m_LastTime; double m_LastTime;
}; };
+68
View File
@@ -0,0 +1,68 @@
#include "PrecompiledHeader.h"
#include "EventBroker.h"
#include "Events/BindKey.h"
BaseEventRelay::~BaseEventRelay()
{
if (m_Broker != nullptr)
{
m_Broker->Unsubscribe(*this);
}
}
void EventBroker::Unsubscribe(BaseEventRelay &relay) // ?
{
auto contextIt = m_ContextRelays.find(relay.m_ContextTypeName);
if (contextIt == m_ContextRelays.end())
return;
auto eventRelays = contextIt->second;
auto itpair = eventRelays.equal_range(relay.m_EventTypeName);
for (auto it = itpair.first; it != itpair.second; ++it)
{
if (it->second == &relay)
{
eventRelays.erase(it);
break;
}
}
}
void EventBroker::Subscribe(BaseEventRelay &relay)
{
relay.m_Broker = this;
m_ContextRelays[relay.m_ContextTypeName].insert(std::make_pair(relay.m_EventTypeName, &relay));
}
int EventBroker::Process(std::string contextTypeName)
{
auto it = m_ContextRelays.find(contextTypeName);
if (it == m_ContextRelays.end())
return 0;
EventRelays_t &relays = it->second;
int eventsProcessed = 0;
for (auto &pair : *m_EventQueueRead)
{
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)
{
auto relay = it2->second;
relay->Receive(event);
eventsProcessed++;
}
}
return eventsProcessed;
}
void EventBroker::Clear()
{
std::swap(m_EventQueueRead, m_EventQueueWrite);
m_EventQueueWrite->clear();
}
+149
View File
@@ -0,0 +1,149 @@
#ifndef MessageRelay_h__
#define MessageRelay_h__
#include <typeinfo>
#include <functional>
#include <map>
#include <unordered_map>
#include <list>
#define EVENT_SUBSCRIBE_MEMBER(relay, handler) \
relay = decltype(relay)(std::bind(handler, this, std::placeholders::_1)); \
EventBroker->Subscribe(relay);
struct Event
{
protected:
Event() { }
};
class EventBroker;
class BaseEventRelay
{
friend class EventBroker;
protected:
BaseEventRelay(std::string contextTypeName, std::string eventTypeName)
: m_ContextTypeName(contextTypeName)
, m_EventTypeName(eventTypeName)
, m_Broker(nullptr) { }
~BaseEventRelay();
public:
virtual bool Receive(const std::shared_ptr<Event> event) = 0;
protected:
std::string m_ContextTypeName;
std::string m_EventTypeName;
EventBroker* m_Broker;
};
template <typename ContextType, typename EventType>
class EventRelay : public BaseEventRelay
{
public:
typedef std::function<bool(const EventType&)> CallbackType;
EventRelay()
: m_Callback(nullptr)
, BaseEventRelay(typeid(ContextType).name(), typeid(EventType).name()) { }
EventRelay(CallbackType callback)
: m_Callback(callback)
, BaseEventRelay(typeid(ContextType).name(), typeid(EventType).name()) { }
protected:
bool Receive(const std::shared_ptr<Event> event) override;
private:
CallbackType m_Callback;
};
template <typename ContextType, typename EventType>
bool EventRelay<ContextType, EventType>::Receive(const std::shared_ptr<Event> event)
{
if (m_Callback != nullptr)
{
return m_Callback(*static_cast<const EventType*>(event.get()));
}
else
{
return false;
}
}
class EventBroker
{
template <typename ContextType, typename EventType> friend class EventRelay;
public:
EventBroker()
{
m_EventQueueRead = std::make_shared<EventQueue_t>();
m_EventQueueWrite = std::make_shared<EventQueue_t>();
}
void Subscribe(BaseEventRelay &relay);
template <typename EventType>
void Publish(const EventType &event);
// Process all events no matter the context.
/*void Process()
{
}*/
/*
Process all events in a given context.
Returns: Number of events processed
*/
template <typename ContextType>
int Process();
int Process(std::string contextTypeName);
void Clear();
void Unsubscribe(BaseEventRelay &relay);
template <typename ContextType>
void UnsubscribeAll();
private:
typedef std::string ContextTypeName_t; // typeid(ContextType).name()
typedef std::string EventTypeName_t; // typeid(EventType).name()
typedef std::unordered_multimap<EventTypeName_t, BaseEventRelay*> EventRelays_t;
typedef std::unordered_map<ContextTypeName_t, EventRelays_t> ContextRelays_t;
ContextRelays_t m_ContextRelays;
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;
};
template <typename EventType>
void EventBroker::Publish(const EventType &event)
{
/*auto itpair = m_Subscribers.equal_range(typeid(EventType).name());
for (auto it = itpair.first; it != itpair.second; ++it)
{
it->second->Receive(event);
}*/
m_EventQueueWrite->push_back(std::make_pair(typeid(EventType).name(), std::shared_ptr<EventType>(new EventType(event))));
}
template <typename ContextType>
int EventBroker::Process()
{
const std::string contextTypeName = typeid(ContextType).name();
return Process(contextTypeName);
}
template <typename ContextType>
void EventBroker::UnsubscribeAll()
{
const std::string contextTypeName = typeid(ContextType).name();
auto contextIt = m_ContextRelays.find(contextTypeName);
if (contextIt != m_ContextRelays.end())
{
m_ContextRelays.erase(contextIt);
}
}
#endif // MessageRelay_h__
+18
View File
@@ -0,0 +1,18 @@
#ifndef Events_ApplyForce_h__
#define Events_ApplyForce_h__
#include "Entity.h"
#include "EventBroker.h"
namespace Events
{
struct ApplyForce : Event
{
EntityID Entity;
double DeltaTime;
glm::vec3 Force;
};
}
#endif // Events_ApplyForce_h__
+18
View File
@@ -0,0 +1,18 @@
#ifndef Events_ApplyPointImpulse_h__
#define Events_ApplyPointImpulse_h__
#include "Entity.h"
#include "EventBroker.h"
namespace Events
{
struct ApplyPointImpulse : Event
{
EntityID Entity;
glm::vec3 Position;
glm::vec3 Impulse;
};
}
#endif // Events_ApplyPointImpulse_h__
+21
View File
@@ -0,0 +1,21 @@
#ifndef Events_BindGamepadAxis_h__
#define Events_BindGamepadAxis_h__
#include <boost/any.hpp>
#include "EventBroker.h"
#include "Events/GamepadAxis.h"
namespace Events
{
struct BindGamepadAxis : Event
{
Gamepad::Axis Axis;
std::string Command;
float Value;
};
}
#endif // Events_BindGamepadAxis_h__
+21
View File
@@ -0,0 +1,21 @@
#ifndef Events_BindGamepadButton_h__
#define Events_BindGamepadButton_h__
#include <boost/any.hpp>
#include "EventBroker.h"
#include "Events/GamepadButton.h"
namespace Events
{
struct BindGamepadButton : Event
{
Gamepad::Button Button;
std::string Command;
float Value;
};
}
#endif // Events_BindGamepadButton_h__
+20
View File
@@ -0,0 +1,20 @@
#ifndef Events_BindKey_h__
#define Events_BindKey_h__
#include <boost/any.hpp>
#include "EventBroker.h"
namespace Events
{
struct BindKey : Event
{
int KeyCode;
std::string Command;
float Value;
};
}
#endif // Events_BindKey_h__
+18
View File
@@ -0,0 +1,18 @@
#ifndef Events_BindMouseButton_h__
#define Events_BindMouseButton_h__
#include "EventBroker.h"
namespace Events
{
struct BindMouseButton : Event
{
int Button;
std::string Command;
float Value;
};
}
#endif // Events_BindMouseButton_h__
+16
View File
@@ -0,0 +1,16 @@
#ifndef Events_CastRay_h__
#define Events_CastRay_h__
#include "EventBroker.h"
namespace Events
{
struct CastRay : Event
{
glm::vec3 Direction;
};
}
#endif // Events_CastRay_h__
+18
View File
@@ -0,0 +1,18 @@
#ifndef Events_Collision_h__
#define Events_Collision_h__
#include "Entity.h"
#include "EventBroker.h"
namespace Events
{
struct Collision : Event
{
EntityID Entity1;
EntityID Entity2;
};
}
#endif // Events_Collision_h__
+17
View File
@@ -0,0 +1,17 @@
#ifndef Events_Damage_h__
#define Events_Damage_h__
#include "Entity.h"
#include "EventBroker.h"
namespace Events
{
struct Damage : Event
{
EntityID Entity;
float damage;
};
}
#endif // Events_Damage_h__
+18
View File
@@ -0,0 +1,18 @@
#ifndef Events_DisableCollisions_h__
#define Events_DisableCollisions_h__
#include "Entity.h"
#include "EventBroker.h"
namespace Events
{
struct DisableCollisions : Event
{
int Layer1;
int Layer2;
};
}
#endif // Events_DisableCollisions_h__
+18
View File
@@ -0,0 +1,18 @@
#ifndef Events_EnableCollisions_h__
#define Events_EnableCollisions_h__
#include "Entity.h"
#include "EventBroker.h"
namespace Events
{
struct EnableCollisions : Event
{
int Layer1;
int Layer2;
};
}
#endif // Events_EnableCollisions_h__
+17
View File
@@ -0,0 +1,17 @@
#ifndef Events_EnterTrigger_h__
#define Events_EnterTrigger_h__
#include "Entity.h"
#include "EventBroker.h"
namespace Events
{
struct EnterTrigger : Event
{
EntityID Entity1;
EntityID Entity2;
};
}
#endif // Events_EnterTrigger_h__
+32
View File
@@ -0,0 +1,32 @@
#ifndef Events_GamepadAxis_h__
#define Events_GamepadAxis_h__
#include "EventBroker.h"
namespace Gamepad
{
enum class Axis
{
LeftX,
LeftY,
RightX,
RightY,
LeftTrigger,
RightTrigger,
LAST = RightTrigger
};
}
namespace Events
{
struct GamepadAxis : Event
{
int GamepadID;
Gamepad::Axis Axis;
float Value;
};
}
#endif // Events_GamepadAxis_h__
+45
View File
@@ -0,0 +1,45 @@
#ifndef Events_GamepadButton_h__
#define Events_GamepadButton_h__
#include "EventBroker.h"
namespace Gamepad
{
enum class Button
{
Up,
Down,
Left,
Right,
Start,
Back,
LeftThumb,
RightThumb,
LeftShoulder,
RightShoulder,
A,
B,
X,
Y,
LAST = Y
};
}
namespace Events
{
struct GamepadButtonDown : Event
{
int GamepadID;
Gamepad::Button Button;
};
struct GamepadButtonUp : Event
{
int GamepadID;
Gamepad::Button Button;
};
}
#endif // Events_GamepadButton_h__
+20
View File
@@ -0,0 +1,20 @@
#ifndef Events_InputCommand_h__
#define Events_InputCommand_h__
#include <boost/any.hpp>
#include "EventBroker.h"
namespace Events
{
struct InputCommand : Event
{
unsigned int PlayerID;
std::string Command;
float Value;
};
}
#endif // Events_InputCommand_h__
+16
View File
@@ -0,0 +1,16 @@
#ifndef Events_KeyDown_h__
#define Events_KeyDown_h__
#include "EventBroker.h"
namespace Events
{
struct KeyDown : Event
{
int KeyCode;
};
}
#endif // Events_KeyDown_h__
+16
View File
@@ -0,0 +1,16 @@
#ifndef Events_KeyUp_h__
#define Events_KeyUp_h__
#include "EventBroker.h"
namespace Events
{
struct KeyUp : Event
{
int KeyCode;
};
}
#endif // Events_KeyUp_h__
+14
View File
@@ -0,0 +1,14 @@
#ifndef Events_LockMouse_h__
#define Events_LockMouse_h__
#include "EventBroker.h"
namespace Events
{
struct LockMouse : Event { };
struct UnlockMouse : Event { };
}
#endif // Events_LockMouse_h__
+17
View File
@@ -0,0 +1,17 @@
#ifndef Events_MouseMove_h__
#define Events_MouseMove_h__
#include "EventBroker.h"
namespace Events
{
struct MouseMove : Event
{
double X, Y;
double DeltaX, DeltaY;
};
}
#endif // Events_MouseMove_h__
+17
View File
@@ -0,0 +1,17 @@
#ifndef Events_MousePress_h__
#define Events_MousePress_h__
#include "EventBroker.h"
namespace Events
{
struct MousePress : Event
{
int Button;
double X, Y;
};
}
#endif // Events_MousePress_h__
+17
View File
@@ -0,0 +1,17 @@
#ifndef Events_MouseRelease_h__
#define Events_MouseRelease_h__
#include "EventBroker.h"
namespace Events
{
struct MouseRelease : Event
{
int Button;
double X, Y;
};
}
#endif // Events_MouseRelease_h__
+17
View File
@@ -0,0 +1,17 @@
#ifndef Event_PlaySound_h__
#define Event_PlaySound_h__
#include "EventBroker.h"
namespace Events
{
struct PlaySound : Event
{
EntityID Emitter;
std::string Resource;
};
}
#endif // Event_PlaySound_h__
+17
View File
@@ -0,0 +1,17 @@
#ifndef Events_RayIntersection_h__
#define Events_RayIntersection_h__
#include "EventBroker.h"
#include "Entity.h"
namespace Events
{
struct RayIntersection : Event
{
EntityID Entity;
};
}
#endif // Events_RayIntersection_h__
+17
View File
@@ -0,0 +1,17 @@
#ifndef Events_SetVelocity_h__
#define Events_SetVelocity_h__
#include "Entity.h"
#include "EventBroker.h"
namespace Events
{
struct SetVelocity : Event
{
EntityID Entity;
glm::vec3 Velocity;
};
}
#endif // Events_SetVelocity_h__
+18
View File
@@ -0,0 +1,18 @@
#ifndef Events_SetViewportCamera_h__
#define Events_SetViewportCamera_h__
#include "EventBroker.h"
#include "Entity.h"
namespace Events
{
struct SetViewportCamera : Event
{
std::string ViewportFrame;
EntityID CameraEntity;
};
}
#endif // Events_SetViewportCamera_h__
+19
View File
@@ -0,0 +1,19 @@
#ifndef Events_TankSteer_h__
#define Events_TankSteer_h__
#include "Entity.h"
#include "EventBroker.h"
namespace Events
{
struct TankSteer : Event
{
EntityID Entity;
float PositionX;
float PositionY;
bool Handbrake;
};
}
#endif // Events_TankSteer_h__
+22 -2
View File
@@ -10,12 +10,18 @@ template <typename T>
class Factory class Factory
{ {
public: public:
void Register(std::string name, std::function<T(void)> factoryFunction) /*void Register(std::string name, std::function<T(void)> factoryFunction)
{ {
m_FactoryFunctions[name] = factoryFunction; m_FactoryFunctions[name] = factoryFunction;
}*/
template <typename T2>
void Register(std::function<T(void)> factoryFunction)
{
m_FactoryFunctions[typeid(T2).name()] = factoryFunction;
} }
T Create(std::string name) /*T Create(std::string name)
{ {
auto it = m_FactoryFunctions.find(name); auto it = m_FactoryFunctions.find(name);
if (it != m_FactoryFunctions.end()) if (it != m_FactoryFunctions.end())
@@ -26,6 +32,20 @@ public:
{ {
return nullptr; return nullptr;
} }
}*/
template <typename T2>
T Create()
{
auto it = m_FactoryFunctions.find(typeid(T2).name());
if (it != m_FactoryFunctions.end())
{
return it->second();
}
else
{
return nullptr;
}
} }
private: private:
+160
View File
@@ -0,0 +1,160 @@
#ifndef GUI_Frame_h__
#define GUI_Frame_h__
#include <memory>
#include <map>
#include "Util/Rectangle.h"
#include "EventBroker.h"
#include "ResourceManager.h"
#include "Renderer.h"
#include "RenderQueue.h"
#include "Texture.h"
namespace GUI
{
class Frame : public Rectangle
{
public:
enum class Anchor
{
Left,
Right,
Top,
Bottom
};
// Set up a base frame with an event broker
Frame(std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr<::ResourceManager> resourceManager)
: EventBroker(eventBroker)
, ResourceManager(resourceManager)
, Rectangle()
, m_Name("UIParent")
, m_Layer(0)
{ }
// Create a frame as a child
Frame(Frame* parent, std::string name)
: Rectangle(static_cast<Rectangle>(*parent)) // Clone parent rectangle using copy constructor
, m_Name(name)
, m_Layer(0)
{ SetParent(std::shared_ptr<Frame>(parent)); }
::RenderQueue RenderQueue;
std::shared_ptr<Frame> Parent() const { return m_Parent; }
void SetParent(std::shared_ptr<Frame> parent)
{
if (parent == nullptr)
{
LOG_ERROR("Failed to create frame \"%s\": Invalid parent", m_Name.c_str());
return;
}
m_Layer = parent->Layer() + 1;
parent->AddChild(std::shared_ptr<Frame>(this));
m_Parent = parent;
EventBroker = parent->EventBroker;
ResourceManager = parent->ResourceManager;
}
void AddChild(std::shared_ptr<Frame> child)
{
m_Children[child->m_Layer].insert(std::make_pair(child->Name(), child));
if (m_Parent)
{
m_Parent->AddChild(child);
}
}
typedef std::map<std::string, std::shared_ptr<Frame>>::const_iterator FrameChildrenIterator;
std::string Name() const { return m_Name; }
void SetName(std::string val) { m_Name = val; }
int Layer() const { return m_Layer; }
int Left() const override
{
if (m_Parent)
return m_Parent->Left() + X;
else
return X;
}
int Right() const override
{
return Left() + Width;
}
int Top() const override
{
if (m_Parent)
return m_Parent->Top() + Y;
else
return Y;
}
int Bottom() const override
{
return Top() + Height;
}
Rectangle AbsoluteRectangle()
{
return Rectangle(Left(), Top(), Width, Height);
}
void UpdateLayered(double dt)
{
// Update ourselves
this->Update(dt);
// Update children
for (auto &pairLayer : m_Children)
{
auto children = pairLayer.second;
for (auto &pairChild : children)
{
auto child = pairChild.second;
child->Update(dt);
}
}
}
virtual void Update(double dt) { }
void DrawLayered(std::shared_ptr<Renderer> renderer)
{
// Draw ourselves
renderer->SetViewport(AbsoluteRectangle());
this->Draw(renderer);
// Draw children
for (auto &pairLayer : m_Children)
{
auto children = pairLayer.second;
for (auto &pairChild : children)
{
auto child = pairChild.second;
Rectangle rect = child->AbsoluteRectangle();
renderer->SetViewport(rect);
child->Draw(renderer);
}
}
}
virtual void Draw(std::shared_ptr<Renderer> renderer) { }
protected:
std::shared_ptr<::EventBroker> EventBroker;
std::shared_ptr<::ResourceManager> ResourceManager;
std::string m_Name;
int m_Layer;
std::shared_ptr<Frame> m_Parent;
typedef std::multimap<std::string, std::shared_ptr<Frame>> Children_t; // name -> frame
std::map<int, Children_t> m_Children; // layer -> Children_t
};
}
#endif // GUI_Frame_h__
+62
View File
@@ -0,0 +1,62 @@
#ifndef GUI_GameFrame_h__
#define GUI_GameFrame_h__
#include "GUI/Frame.h"
#include "GUI/WorldFrame.h"
#include "GUI/Viewport.h"
#include "GUI/TextureFrame.h"
#include "Events/Damage.h"
#include "GameWorld.h"
namespace GUI
{
class GameFrame : public Frame
{
public:
GameFrame(Frame* parent, std::string name)
: Frame(parent, name)
{
EVENT_SUBSCRIBE_MEMBER(m_EDamage, &GameFrame::OnDamage);
m_World = std::make_shared<GameWorld>(EventBroker, ResourceManager);
auto worldFrame = new WorldFrame(this, "GameWorldFrame", m_World);
{
vp1 = new Viewport(worldFrame, "Viewport1", m_World);
vp1->X = 0;
vp1->Width = 640;
vp2 = new Viewport(worldFrame, "Viewport2", m_World);
vp2->X = vp1->Right();
vp2->Width = 640;
tex = new TextureFrame(vp1, "TextureFrameThingy");
tex->SetTexture("Textures/GUI/hurt.png");
}
m_World->Initialize();
}
void Update(double dt)
{
}
bool OnDamage(const Events::Damage &event)
{
//tex->SetTexture("Textures/GUI/hurt.png");
return false;
}
private:
EventRelay<Frame, Events::Damage> m_EDamage;
std::shared_ptr<GameWorld> m_World;
Viewport* vp1;
Viewport* vp2;
TextureFrame* tex;
};
}
#endif // GUI_GameFrame_h__
+43
View File
@@ -0,0 +1,43 @@
#ifndef GUI_TextureFrame_h__
#define GUI_TextureFrame_h__
#include "GUI/Frame.h"
#include "Texture.h"
namespace GUI
{
class TextureFrame : public Frame
{
public:
TextureFrame(Frame* parent, std::string name)
: Frame(parent, name) { }
void Draw(std::shared_ptr<Renderer> renderer) override
{
if (m_Texture == nullptr)
return;
RenderQueue.Clear();
SpriteJob job;
job.TextureID = m_Texture->ResourceID;
job.Texture = *m_Texture;
RenderQueue.Add(job);
renderer->SetCamera(nullptr);
renderer->DrawFrame(RenderQueue);
}
std::shared_ptr<::Texture> Texture() const { return m_Texture; }
void SetTexture(std::string resourceName)
{
m_Texture = std::shared_ptr<::Texture>(ResourceManager->Load<::Texture>("Texture", resourceName));
}
protected:
std::shared_ptr<::Texture> m_Texture;
};
}
#endif // GUI_TextureFrame_h__
+80
View File
@@ -0,0 +1,80 @@
#ifndef GUI_Viewport_h__
#define GUI_Viewport_h__
#include <memory>
#include "GUI/Frame.h"
#include "World.h"
#include "Systems/TransformSystem.h"
#include "Components/Transform.h"
#include "Components/Camera.h"
#include "RenderQueue.h"
#include "Camera.h"
namespace GUI
{
class Viewport : public Frame
{
public:
Viewport(Frame* parent, std::string name, std::shared_ptr<World> world)
: Frame(parent, name)
, m_World(world)
{ }
EntityID CameraEntity() const { return m_CameraEntity; }
void SetCameraEntity(EntityID cameraEntity)
{
m_CameraEntity = cameraEntity;
auto transformComponent = m_World->GetComponent<Components::Transform>(cameraEntity);
if (!transformComponent)
return;
auto cameraComponent = m_World->GetComponent<Components::Camera>(cameraEntity);
if (!cameraComponent)
return;
m_Camera = std::make_shared<Camera>(cameraComponent->FOV, cameraComponent->NearClip, cameraComponent->FarClip);
}
void Update(double dt) override
{
if (!m_TransformSystem)
m_TransformSystem = m_World->GetSystem<Systems::TransformSystem>();
auto transformComponent = m_World->GetComponent<Components::Transform>(m_CameraEntity);
if (!transformComponent)
return;
auto cameraComponent = m_World->GetComponent<Components::Camera>(m_CameraEntity);
if (!cameraComponent)
return;
Components::Transform absoluteTransform = m_TransformSystem->AbsoluteTransform(m_CameraEntity);
m_Camera->SetFOV(cameraComponent->FOV);
m_Camera->SetNearClip(cameraComponent->NearClip);
m_Camera->SetFarClip(cameraComponent->FarClip);
m_Camera->SetPosition(absoluteTransform.Position);
m_Camera->SetOrientation(absoluteTransform.Orientation);
}
void Draw(std::shared_ptr<Renderer> renderer) override
{
if (!m_Camera)
return;
renderer->SetCamera(m_Camera);
renderer->DrawWorld(m_Parent->RenderQueue);
}
private:
std::shared_ptr<World> m_World;
std::shared_ptr<Systems::TransformSystem> m_TransformSystem;
std::shared_ptr<Camera> m_Camera;
EntityID m_CameraEntity;
};
}
#endif // GUI_Viewport_h__
+150
View File
@@ -0,0 +1,150 @@
#ifndef GUI_WorldFrame_h__
#define GUI_WorldFrame_h__
#include "GUI/Frame.h"
#include "GUI/Viewport.h"
#include "RenderQueue.h"
#include "World.h"
#include "Systems/TransformSystem.h"
#include "Events/SetViewportCamera.h"
#include "Components/Transform.h"
#include "Components/Model.h"
#include "Components/Sprite.h"
#include "Components/PointLight.h"
namespace GUI
{
class WorldFrame : public Frame
{
public:
WorldFrame(Frame* parent, std::string name, std::shared_ptr<World> world)
: Frame(parent, name)
, m_World(world)
{
EVENT_SUBSCRIBE_MEMBER(m_ESetViewportCamera, &WorldFrame::OnSetViewportCamera);
}
void Update(double dt) override
{
if (!m_TransformSystem)
m_TransformSystem = m_World->GetSystem<Systems::TransformSystem>();
m_World->Update(dt);
}
void Draw(std::shared_ptr<Renderer> renderer) override
{
RenderQueue.Clear();
renderer->ClearPointLights();
for (auto &pair : *m_World->GetEntities())
{
EntityID entity = pair.first;
auto transform = m_World->GetComponent<Components::Transform>(entity);
if (!transform)
continue;
auto modelComponent = m_World->GetComponent<Components::Model>(entity);
if (modelComponent)
{
auto modelAsset = ResourceManager->Load<Model>("Model", modelComponent->ModelFile);
if (modelAsset)
{
Components::Transform absoluteTransform = m_TransformSystem->AbsoluteTransform(entity);
glm::mat4 modelMatrix = glm::translate(glm::mat4(), absoluteTransform.Position)
* glm::toMat4(absoluteTransform.Orientation)
* glm::scale(absoluteTransform.Scale);
EnqueueModel(modelAsset, modelMatrix);
}
}
auto spriteComponent = m_World->GetComponent<Components::Sprite>(entity);
if (spriteComponent)
{
auto textureAsset = ResourceManager->Load<Texture>("Texture", spriteComponent->SpriteFile);
if (textureAsset)
{
Components::Transform absoluteTransform = m_TransformSystem->AbsoluteTransform(entity);
glm::quat orientation2D = glm::angleAxis(glm::eulerAngles(absoluteTransform.Orientation).z, glm::vec3(0, 0, -1));
glm::mat4 modelMatrix = glm::translate(absoluteTransform.Position)
* glm::toMat4(orientation2D)
* glm::scale(absoluteTransform.Scale);
EnqueueSprite(textureAsset, modelMatrix);
}
}
auto pointLightComponent = m_World->GetComponent<Components::PointLight>(entity);
if (pointLightComponent)
{
glm::vec3 position = m_TransformSystem->AbsolutePosition(entity);
renderer->AddPointLightToDraw(
position,
pointLightComponent->Specular,
pointLightComponent->Diffuse,
pointLightComponent->specularExponent,
pointLightComponent->ConstantAttenuation,
pointLightComponent->LinearAttenuation,
pointLightComponent->QuadraticAttenuation,
pointLightComponent->Radius
);
}
}
}
protected:
std::shared_ptr<World> m_World;
private:
EventRelay<Frame, Events::SetViewportCamera> m_ESetViewportCamera;
bool OnSetViewportCamera(const Events::SetViewportCamera &event)
{
// Search next layer for viewports and update cameras
auto itpair = m_Children[m_Layer + 1].equal_range(event.ViewportFrame);
for (auto it = itpair.first; it != itpair.second; ++it)
{
auto viewportFrame = std::dynamic_pointer_cast<GUI::Viewport>(it->second);
if (!viewportFrame)
continue;
viewportFrame->SetCameraEntity(event.CameraEntity);
}
return true;
}
std::shared_ptr<Systems::TransformSystem> m_TransformSystem;
void EnqueueModel(Model* model, glm::mat4 modelMatrix)
{
for (auto texGroup : model->TextureGroups)
{
ModelJob job;
job.TextureID = texGroup.Texture->ResourceID;
job.DiffuseTexture = *texGroup.Texture;
job.NormalTexture = (texGroup.NormalMap) ? *texGroup.NormalMap : 0;
job.SpecularTexture = (texGroup.SpecularMap) ? *texGroup.SpecularMap : 0;
job.VAO = model->VAO;
job.StartIndex = texGroup.StartIndex;
job.EndIndex = texGroup.EndIndex;
job.ModelMatrix = modelMatrix;
RenderQueue.Add(job);
}
}
void EnqueueSprite(Texture* texture, glm::mat4 modelMatrix)
{
SpriteJob job;
job.TextureID = texture->ResourceID;
job.Texture = *texture;
job.ModelMatrix = modelMatrix;
RenderQueue.Add(job);
}
};
}
#endif // GUI_WorldFrame_h__
+1230 -209
View File
File diff suppressed because it is too large Load Diff
+26 -6
View File
@@ -7,36 +7,53 @@
#include "Systems/TransformSystem.h" #include "Systems/TransformSystem.h"
//#include "Systems/CollisionSystem.h" //#include "Systems/CollisionSystem.h"
#include "Systems/InputSystem.h" #include "Systems/InputSystem.h"
#include "Systems/DebugSystem.h"
//#include "Systems/LevelGenerationSystem.h" //#include "Systems/LevelGenerationSystem.h"
//#include "Systems/ParticleSystem.h" #include "Systems/ParticleSystem.h"
//#include "Systems/PlayerSystem.h" //#include "Systems/PlayerSystem.h"
#include "Systems/FreeSteeringSystem.h" #include "Systems/FreeSteeringSystem.h"
#include "Systems/TankSteeringSystem.h"
#include "Systems/HelicopterSteeringSystem.h"
#include "Systems/RenderSystem.h" #include "Systems/RenderSystem.h"
#include "Systems/SoundSystem.h" #include "Systems/SoundSystem.h"
#include "Systems/PhysicsSystem.h" #include "Systems/PhysicsSystem.h"
#include "Systems/TriggerSystem.h"
#include "Systems/TimerSystem.h"
#include "Systems/DamageSystem.h"
#include "Components/Camera.h" #include "Components/Camera.h"
#include "Components/DirectionalLight.h" #include "Components/DirectionalLight.h"
#include "Components/Input.h" #include "Components/Input.h"
#include "Components/Model.h" #include "Components/Model.h"
#include "Components/ParticleEmitter.h" #include "Components/ParticleEmitter.h"
#include "Components/Particle.h"
#include "Components/PointLight.h" #include "Components/PointLight.h"
#include "Components/SoundEmitter.h" #include "Components/SoundEmitter.h"
#include "Components/Sprite.h" #include "Components/Sprite.h"
#include "Components/Template.h" #include "Components/Template.h"
#include "Components/Transform.h" #include "Components/Transform.h"
#include "Components/Viewport.h"
#include "Components/Physics.h" #include "Components/Physics.h"
#include "Components/Sphere.h" #include "Components/SphereShape.h"
#include "Components/Box.h" #include "Components/BoxShape.h"
#include "Components/Vehicle.h" #include "Components/Vehicle.h"
#include "Components/Wheel.h" #include "Components/Wheel.h"
#include "Components/HingeConstraint.h"
#include "Components/TankSteering.h"
#include "Components/TowerSteering.h"
#include "Components/BarrelSteering.h"
#include "Components/Player.h"
#include "Components/Health.h"
#include "Components/Trigger.h"
#include "Components/Flag.h"
class GameWorld : public World class GameWorld : public World
{ {
public: public:
GameWorld(std::shared_ptr<Renderer> renderer) GameWorld(std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr<::ResourceManager> resourceManager)
: m_Renderer(renderer), World() { } : World(eventBroker, resourceManager)
{ }
void Initialize(); void Initialize();
@@ -47,7 +64,10 @@ public:
void Update(double dt); void Update(double dt);
private: private:
std::shared_ptr<Renderer> m_Renderer; void BindKey(int keyCode, std::string command, float value);
void BindMouseButton(int button, std::string command, float value);
void BindGamepadAxis(Gamepad::Axis axis, std::string command, float value);
void BindGamepadButton(Gamepad::Button button, std::string command, float value);
}; };
#endif // GameWorld_h__ #endif // GameWorld_h__
+34
View File
@@ -0,0 +1,34 @@
#ifndef InputController_h__
#define InputController_h__
#include <memory>
#include "EventBroker.h"
#include "Events/InputCommand.h"
#include "Events/MouseMove.h"
template <typename EventContext>
class InputController
{
public:
InputController(std::shared_ptr<::EventBroker> eventBroker)
: EventBroker(eventBroker) { Initialize(); }
virtual void Initialize()
{
EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &InputController::OnCommand);
EVENT_SUBSCRIBE_MEMBER(m_EMouseMove, &InputController::OnMouseMove);
}
virtual bool OnCommand(const Events::InputCommand &event) { return false; }
virtual bool OnMouseMove(const Events::MouseMove &event) { return false; }
protected:
std::shared_ptr<::EventBroker> EventBroker;
private:
EventRelay<EventContext, Events::InputCommand> m_EInputCommand;
EventRelay<EventContext, Events::MouseMove> m_EMouseMove;
};
#endif // InputController_h__
+231
View File
@@ -0,0 +1,231 @@
#include "PrecompiledHeader.h"
#include "InputManager.h"
#include <XInput.h>
void InputManager::Initialize()
{
m_LastGamepadAxisState = std::array<GamepadAxisState, XUSER_MAX_COUNT>();
m_LastGamepadButtonState = std::array<GamepadButtonState, XUSER_MAX_COUNT>();
EVENT_SUBSCRIBE_MEMBER(m_ELockMouse, &InputManager::OnLockMouse);
EVENT_SUBSCRIBE_MEMBER(m_EUnlockMouse, &InputManager::OnUnlockMouse);
}
void InputManager::Update(double dt)
{
EventBroker->Process<InputManager>();
m_LastKeyState = m_CurrentKeyState;
m_LastMouseState = m_CurrentMouseState;
m_LastMouseX = m_CurrentMouseX;
m_LastMouseY = m_CurrentMouseY;
// Keyboard input
for (int i = 0; i <= GLFW_KEY_LAST; ++i)
{
m_CurrentKeyState[i] = glfwGetKey(m_GLFWWindow, i);
if (m_CurrentKeyState[i] != m_LastKeyState[i])
{
// Publish key events
if (m_CurrentKeyState[i])
{
Events::KeyDown e;
e.KeyCode = i;
EventBroker->Publish(e);
}
else
{
Events::KeyUp e;
e.KeyCode = i;
EventBroker->Publish(e);
}
}
}
// Mouse buttons
for (int i = 0; i <= GLFW_MOUSE_BUTTON_LAST; ++i)
{
m_CurrentMouseState[i] = glfwGetMouseButton(m_GLFWWindow, i);
if (m_CurrentMouseState[i] != m_LastMouseState[i])
{
double x, y;
glfwGetCursorPos(m_GLFWWindow, &x, &y);
// Publish mouse button events
if (m_CurrentMouseState[i])
{
Events::MousePress e;
e.Button = i;
e.X = x;
e.Y = y;
EventBroker->Publish(e);
}
else
{
Events::MouseRelease e;
e.Button = i;
e.X = x;
e.Y = y;
EventBroker->Publish(e);
}
}
}
// Mouse movement
glfwGetCursorPos(m_GLFWWindow, &m_CurrentMouseX, &m_CurrentMouseY);
m_CurrentMouseDeltaX = m_CurrentMouseX - m_LastMouseX;
m_CurrentMouseDeltaY = m_CurrentMouseY - m_LastMouseY;
if (m_CurrentMouseDeltaX != 0 || m_CurrentMouseDeltaY != 0)
{
// Publish mouse move events
Events::MouseMove e;
e.X = m_CurrentMouseX;
e.Y = m_CurrentMouseY;
e.DeltaX = m_CurrentMouseDeltaX;
e.DeltaY = m_CurrentMouseDeltaY;
EventBroker->Publish(e);
}
// // Lock mouse while holding LMB
// if (m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT])
// {
// m_LastMouseX = m_Renderer->Width() / 2.f; // xpos;
// m_LastMouseY = m_Renderer->Height() / 2.f; // ypos;
// glfwSetCursorPos(m_GLFWWindow, m_LastMouseX, m_LastMouseY);
// }
// // Hide/show cursor with LMB
// if (m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT] && !m_LastMouseState[GLFW_MOUSE_BUTTON_LEFT])
// {
// glfwSetInputMode(m_GLFWWindow, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
// }
// if (!m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT] && m_LastMouseState[GLFW_MOUSE_BUTTON_LEFT])
// {
// glfwSetInputMode(m_GLFWWindow, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
// }
// Xbox360 controller
//using namespace ;
DWORD dwResult;
for (int i = 0; i < MAX_GAMEPADS; i++)
{
XINPUT_STATE state = { 0 };
// Simply get the state of the controller from XInput.
dwResult = XInputGetState(i, &state);
if (dwResult == 0)
{
if(std::abs(state.Gamepad.sThumbLX) <= XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE)
state.Gamepad.sThumbLX = 0;
if(std::abs(state.Gamepad.sThumbLY) <= XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE)
state.Gamepad.sThumbLY = 0;
if(std::abs(state.Gamepad.sThumbRX) <= XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE)
state.Gamepad.sThumbRX = 0;
if(std::abs(state.Gamepad.sThumbRY) <= XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE)
state.Gamepad.sThumbRY = 0;
if(std::abs(state.Gamepad.bLeftTrigger) <= XINPUT_GAMEPAD_TRIGGER_THRESHOLD)
state.Gamepad.bLeftTrigger = 0;
if(std::abs(state.Gamepad.bRightTrigger) <= XINPUT_GAMEPAD_TRIGGER_THRESHOLD)
state.Gamepad.bRightTrigger = 0;
m_CurrentGamepadAxisState[i][static_cast<int>(Gamepad::Axis::LeftX)] = state.Gamepad.sThumbLX / 32767.f;
m_CurrentGamepadAxisState[i][static_cast<int>(Gamepad::Axis::LeftY)] = state.Gamepad.sThumbLY / 32767.f;
m_CurrentGamepadAxisState[i][static_cast<int>(Gamepad::Axis::RightX)] = state.Gamepad.sThumbRX / 32767.f;
m_CurrentGamepadAxisState[i][static_cast<int>(Gamepad::Axis::RightY)] = state.Gamepad.sThumbRY / 32767.f;
m_CurrentGamepadAxisState[i][static_cast<int>(Gamepad::Axis::LeftTrigger)] = state.Gamepad.bLeftTrigger / 255.f;
m_CurrentGamepadAxisState[i][static_cast<int>(Gamepad::Axis::RightTrigger)] = state.Gamepad.bRightTrigger / 255.f;
PublishGamepadAxisIfChanged(i, Gamepad::Axis::LeftX);
PublishGamepadAxisIfChanged(i, Gamepad::Axis::LeftY);
PublishGamepadAxisIfChanged(i, Gamepad::Axis::RightX);
PublishGamepadAxisIfChanged(i, Gamepad::Axis::RightY);
PublishGamepadAxisIfChanged(i, Gamepad::Axis::LeftTrigger);
PublishGamepadAxisIfChanged(i, Gamepad::Axis::RightTrigger);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::Up)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_UP);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::Down)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_DOWN);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::Left)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_LEFT);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::Right)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_RIGHT);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::Start)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_START);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::Back)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_BACK);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::LeftThumb)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_THUMB);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::RightThumb)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_THUMB);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::LeftShoulder)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::RightShoulder)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::A)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_A);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::B)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_B);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::X)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_X);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::Y)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_Y);
PublishGamepadButtonIfChanged(i, Gamepad::Button::Up);
PublishGamepadButtonIfChanged(i, Gamepad::Button::Down);
PublishGamepadButtonIfChanged(i, Gamepad::Button::Left);
PublishGamepadButtonIfChanged(i, Gamepad::Button::Right);
PublishGamepadButtonIfChanged(i, Gamepad::Button::Start);
PublishGamepadButtonIfChanged(i, Gamepad::Button::Back);
PublishGamepadButtonIfChanged(i, Gamepad::Button::LeftThumb);
PublishGamepadButtonIfChanged(i, Gamepad::Button::RightThumb);
PublishGamepadButtonIfChanged(i, Gamepad::Button::LeftShoulder);
PublishGamepadButtonIfChanged(i, Gamepad::Button::RightShoulder);
PublishGamepadButtonIfChanged(i, Gamepad::Button::A);
PublishGamepadButtonIfChanged(i, Gamepad::Button::B);
PublishGamepadButtonIfChanged(i, Gamepad::Button::X);
PublishGamepadButtonIfChanged(i, Gamepad::Button::Y);
}
}
m_LastKeyState = m_CurrentKeyState;
m_LastMouseState = m_CurrentMouseState;
m_LastMouseX = m_CurrentMouseX;
m_LastMouseY = m_CurrentMouseY;
m_LastGamepadAxisState = m_CurrentGamepadAxisState;
m_LastGamepadButtonState = m_CurrentGamepadButtonState;
}
void InputManager::PublishGamepadAxisIfChanged(int gamepadID, Gamepad::Axis axis)
{
float currentValue = m_CurrentGamepadAxisState[gamepadID][static_cast<int>(axis)];
float lastValue = m_LastGamepadAxisState[gamepadID][static_cast<int>(axis)];
if (currentValue != lastValue)
{
Events::GamepadAxis e;
e.GamepadID = gamepadID;
e.Axis = axis;
e.Value = currentValue;
EventBroker->Publish(e);
}
}
void InputManager::PublishGamepadButtonIfChanged(int gamepadID, Gamepad::Button button)
{
bool currentState = m_CurrentGamepadButtonState[gamepadID][static_cast<int>(button)];
float lastState = m_LastGamepadButtonState[gamepadID][static_cast<int>(button)];
if (currentState != lastState)
{
if (currentState == true)
{
Events::GamepadButtonDown e;
e.GamepadID = gamepadID;
e.Button = button;
EventBroker->Publish(e);
}
else
{
Events::GamepadButtonUp e;
e.GamepadID = gamepadID;
e.Button = button;
EventBroker->Publish(e);
}
}
}
bool InputManager::OnLockMouse(const Events::LockMouse &event)
{
m_MouseLocked = true;
glfwSetInputMode(m_GLFWWindow, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
return true;
}
bool InputManager::OnUnlockMouse(const Events::UnlockMouse &event)
{
m_MouseLocked = false;
glfwSetInputMode(m_GLFWWindow, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
return true;
}
+67
View File
@@ -0,0 +1,67 @@
#ifndef InputManager_h__
#define InputManager_h__
#include <array>
#include "EventBroker.h"
#include "Events/KeyDown.h"
#include "Events/KeyUp.h"
#include "Events/MousePress.h"
#include "Events/MouseRelease.h"
#include "Events/MouseMove.h"
#include "Events/LockMouse.h"
#include "Events/GamepadAxis.h"
#include "Events/GamepadButton.h"
class InputManager
{
public:
InputManager(GLFWwindow* window, std::shared_ptr<::EventBroker> eventBroker)
: m_GLFWWindow(window)
, EventBroker(eventBroker)
, m_CurrentKeyState()
, m_LastKeyState()
, m_CurrentMouseState()
, m_LastMouseState()
, m_CurrentMouseX(0), m_CurrentMouseY(0)
, m_LastMouseX(0), m_LastMouseY(0)
, m_CurrentMouseDeltaX(0), m_CurrentMouseDeltaY(0)
, m_MouseLocked(false)
{ Initialize(); }
void Initialize();
static const short MAX_GAMEPADS = 4;
void Update(double dt);
private:
GLFWwindow* m_GLFWWindow;
std::shared_ptr<::EventBroker> EventBroker;
EventRelay<InputManager, Events::LockMouse> m_ELockMouse;
bool OnLockMouse(const Events::LockMouse &event);
EventRelay<InputManager, Events::UnlockMouse> m_EUnlockMouse;
bool OnUnlockMouse(const Events::UnlockMouse &event);
std::array<int, GLFW_KEY_LAST+1> m_CurrentKeyState;
std::array<int, GLFW_KEY_LAST+1> m_LastKeyState;
std::array<int, GLFW_MOUSE_BUTTON_LAST+1> m_CurrentMouseState;
std::array<int, GLFW_MOUSE_BUTTON_LAST+1> m_LastMouseState;
typedef std::array<float, static_cast<int>(Gamepad::Axis::LAST) + 1> GamepadAxisState;
std::array<GamepadAxisState, MAX_GAMEPADS> m_CurrentGamepadAxisState;
std::array<GamepadAxisState, MAX_GAMEPADS> m_LastGamepadAxisState;
typedef std::array<bool, static_cast<int>(Gamepad::Button::LAST) + 1> GamepadButtonState;
std::array<GamepadButtonState, MAX_GAMEPADS> m_CurrentGamepadButtonState;
std::array<GamepadButtonState, MAX_GAMEPADS> m_LastGamepadButtonState;
double m_CurrentMouseX, m_CurrentMouseY;
double m_LastMouseX, m_LastMouseY;
double m_CurrentMouseDeltaX, m_CurrentMouseDeltaY;
bool m_MouseLocked;
void PublishGamepadAxisIfChanged(int gamepadID, Gamepad::Axis axis);
void PublishGamepadButtonIfChanged(int gamepadID, Gamepad::Button button);
};
#endif // InputManager_h__
+144 -3
View File
@@ -1,7 +1,7 @@
#include "PrecompiledHeader.h" #include "PrecompiledHeader.h"
#include "Model.h" #include "Model.h"
Model::Model(OBJ &obj, ResourceManager* rm) Model::Model(std::shared_ptr<ResourceManager> rm, OBJ &obj)
{ {
OBJ::MaterialInfo* currentMaterial = nullptr; OBJ::MaterialInfo* currentMaterial = nullptr;
TextureGroup* currentTexGroup = nullptr; TextureGroup* currentTexGroup = nullptr;
@@ -22,10 +22,24 @@ Model::Model(OBJ &obj, ResourceManager* rm)
auto texture = std::shared_ptr<Texture>(rm->Load<Texture>("Texture", currentMaterial->DiffuseTexture.FileName)); auto texture = std::shared_ptr<Texture>(rm->Load<Texture>("Texture", currentMaterial->DiffuseTexture.FileName));
// TODO: Load normal map // TODO: Load normal map
std::shared_ptr<Texture> normalMap = nullptr; std::shared_ptr<Texture> normalMap = nullptr;
if (!currentMaterial->NormalMap.FileName.empty())
{
normalMap = std::shared_ptr<Texture>(rm->Load<Texture>("Texture", currentMaterial->NormalMap.FileName));
}
else
{
normalMap = std::shared_ptr<Texture>(rm->Load<Texture>("Texture", "Textures/NeutralNormalMap.png"));
}
// Load specular map // Load specular map
std::shared_ptr<Texture> specularMap = nullptr; std::shared_ptr<Texture> specularMap = nullptr;
if (!currentMaterial->SpecularMap.FileName.empty()) if (!currentMaterial->SpecularMap.FileName.empty())
{
specularMap = std::shared_ptr<Texture>(rm->Load<Texture>("Texture", currentMaterial->SpecularMap.FileName)); specularMap = std::shared_ptr<Texture>(rm->Load<Texture>("Texture", currentMaterial->SpecularMap.FileName));
}
else
{
specularMap = std::shared_ptr<Texture>(rm->Load<Texture>("Texture", "Textures/NeutralSpecularMap.png"));
}
// TODO: Load material parameters // TODO: Load material parameters
// Create new texture group (start index of new group is upcoming index) // Create new texture group (start index of new group is upcoming index)
@@ -34,6 +48,21 @@ Model::Model(OBJ &obj, ResourceManager* rm)
currentTexGroup = &TextureGroups.back(); currentTexGroup = &TextureGroups.back();
} }
/*std::unordered_map<int, glm::vec3> similarNormals;
std::unordered_map<int, int> normalCount;
for (auto &faceDef : face.Definitions)
{
if (faceDef.NormalIndex == 0)
continue;
similarNormals[faceDef.VertexIndex - 1] += normal;
normalCount[faceDef.VertexIndex - 1]++;
int index = pair.first;
glm::vec3 averagedNormal = ;
Normals[]
}*/
// Face definitions // Face definitions
for (auto faceDef : face.Definitions) for (auto faceDef : face.Definitions)
{ {
@@ -63,7 +92,9 @@ Model::Model(OBJ &obj, ResourceManager* rm)
if (Vertices.size() > 0) if (Vertices.size() > 0)
{ {
CreateBuffers(Vertices, Normals, TextureCoords); CreateTangents();
//getSimilarVertexIndex();
CreateBuffers(Vertices, Normals, TangentNormals, BiTangentNormals, TextureCoords);
} }
else else
{ {
@@ -71,7 +102,7 @@ Model::Model(OBJ &obj, ResourceManager* rm)
} }
} }
void Model::CreateBuffers( std::vector<glm::vec3> vertices, std::vector<glm::vec3> normals, std::vector<glm::vec2>textureCoords) void Model::CreateBuffers( std::vector<glm::vec3> vertices, std::vector<glm::vec3> normals, std::vector<glm::vec3> tangents, std::vector<glm::vec3> biTangents, std::vector<glm::vec2>textureCoords)
{ {
LOG_INFO("Generating VertexBuffer"); LOG_INFO("Generating VertexBuffer");
@@ -100,6 +131,32 @@ void Model::CreateBuffers( std::vector<glm::vec3> vertices, std::vector<glm::vec
LOG_WARNING("Created empty normal buffer!"); LOG_WARNING("Created empty normal buffer!");
} }
LOG_INFO("Generating TangentNormalsBuffer");
glGenBuffers(1, &TangentNormalsBuffer);
if (tangents.size() > 0)
{
glBindBuffer(GL_ARRAY_BUFFER, TangentNormalsBuffer);
glBufferData(GL_ARRAY_BUFFER, tangents.size() * sizeof(glm::vec3), &tangents[0], GL_STATIC_DRAW);
GLERROR("GLEW: BufferFail, TangentNormalsBuffer");
}
else
{
LOG_WARNING("Created empty tangent buffer!");
}
LOG_INFO("Generating BiTangentNormalsBuffer");
glGenBuffers(1, &BiTangentNormalsBuffer);
if (biTangents.size() > 0)
{
glBindBuffer(GL_ARRAY_BUFFER, BiTangentNormalsBuffer);
glBufferData(GL_ARRAY_BUFFER, biTangents.size() * sizeof(glm::vec3), &biTangents[0], GL_STATIC_DRAW);
GLERROR("GLEW: BufferFail, BiTangentNormalsBuffer");
}
else
{
LOG_WARNING("Created empty biTangent buffer!");
}
LOG_INFO("Generating textureCoordBuffer"); LOG_INFO("Generating textureCoordBuffer");
glGenBuffers(1, &TextureCoordBuffer); glGenBuffers(1, &TextureCoordBuffer);
@@ -130,10 +187,94 @@ void Model::CreateBuffers( std::vector<glm::vec3> vertices, std::vector<glm::vec
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, 0);
GLERROR("GLEW: BufferFail5"); GLERROR("GLEW: BufferFail5");
glBindBuffer(GL_ARRAY_BUFFER, TangentNormalsBuffer);
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 0, 0);
GLERROR("GLEW: BufferFail5");
glBindBuffer(GL_ARRAY_BUFFER, BiTangentNormalsBuffer);
glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 0, 0);
GLERROR("GLEW: BufferFail5");
glEnableVertexAttribArray(0); glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1); glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2); glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glEnableVertexAttribArray(4);
GLERROR("GLEW: BufferFail5"); GLERROR("GLEW: BufferFail5");
} }
bool Model::IsNear( float v1, float v2 )
{
return fabs(v1 - v2) < 0.001f;
}
void Model::getSimilarVertexIndex()
{
for(int i = 0; i < Vertices.size(); i++)
{
for(int t = 0; t < Vertices.size(); t++)
{
if(i != t)
{
if(IsNear(Vertices[i].x, Vertices[t].x)
&& IsNear(Vertices[i].y, Vertices[t].y)
&& IsNear(Vertices[i].z, Vertices[t].z)
)
{
glm::vec3 tempNormal, tempTangent, tempBiTangent;
tempNormal = Normals[i] + Normals[t];
tempTangent = TangentNormals[i] + TangentNormals[t];
tempBiTangent = BiTangentNormals[i] + BiTangentNormals[t];
Normals[i] = tempNormal;
Normals[t] = tempNormal;
TangentNormals[i] = tempTangent;
TangentNormals[t] = tempTangent;
BiTangentNormals[i] = tempBiTangent;
BiTangentNormals[t] = tempBiTangent;
}
}
}
}
}
void Model::CreateTangents()
{
for(int i = 0; i < Vertices.size(); i += 3)
{
glm::vec3 v0 = Vertices[i];
glm::vec3 v1 = Vertices[i+1];
glm::vec3 v2 = Vertices[i+2];
glm::vec2 uv0 = TextureCoords[i];
glm::vec2 uv1 = TextureCoords[i+1];
glm::vec2 uv2 = TextureCoords[i+2];
//Calculate the edge of the triangle
glm::vec3 edge1 = v1-v0;
glm::vec3 edge2 = v2-v0;
glm::vec2 deltaUV1 = uv1 - uv0;
glm::vec2 deltaUV2 = uv2 - uv0;
float r = 1.0f / (deltaUV1.x * deltaUV2.y - deltaUV1.y * deltaUV2.x);
glm::vec3 tangent, biTangent;
tangent = (edge1 * deltaUV2.y - edge2 * deltaUV1.y) * r;
biTangent = (edge2 * deltaUV1.x - edge1 * deltaUV2.x) * r;
TangentNormals.push_back(tangent);
TangentNormals.push_back(tangent);
TangentNormals.push_back(tangent);
BiTangentNormals.push_back(biTangent);
BiTangentNormals.push_back(biTangent);
BiTangentNormals.push_back(biTangent);
}
}
+12 -2
View File
@@ -17,7 +17,7 @@
class Model : public Resource class Model : public Resource
{ {
public: public:
Model(OBJ &obj, ResourceManager* rm); Model(std::shared_ptr<ResourceManager> resourceManager, OBJ &obj);
struct TextureGroup struct TextureGroup
{ {
@@ -38,10 +38,14 @@ public:
private: private:
std::vector<glm::vec3> Normals; std::vector<glm::vec3> Normals;
std::vector<glm::vec3> TangentNormals;
std::vector<glm::vec3> BiTangentNormals;
std::vector<glm::vec2> TextureCoords; std::vector<glm::vec2> TextureCoords;
GLuint VertexBuffer; GLuint VertexBuffer;
GLuint NormalBuffer; GLuint NormalBuffer;
GLuint TangentNormalsBuffer;
GLuint BiTangentNormalsBuffer;
GLuint TextureCoordBuffer; GLuint TextureCoordBuffer;
bool Loadobj( bool Loadobj(
@@ -53,9 +57,15 @@ private:
void CreateBuffers( void CreateBuffers(
std::vector<glm::vec3> _Vertices, std::vector<glm::vec3> _Vertices,
std::vector<glm::vec3> _Normals, std::vector<glm::vec3> _Normals,
std::vector<glm::vec3> _Tangents,
std::vector<glm::vec3> _BiTangents,
std::vector<glm::vec2>_TextureCoords std::vector<glm::vec2>_TextureCoords
); );
void CreateTangents();
bool IsNear(float v1, float v2);
void getSimilarVertexIndex();
}; };
#endif // Model_h__ #endif // Model_h__
+1 -1
View File
@@ -9,7 +9,7 @@ bool OBJ::LoadFromFile(std::string filename)
std::ifstream file(m_Path.string()); std::ifstream file(m_Path.string());
if (!file.is_open()) if (!file.is_open())
{ {
LOG_ERROR("Failed to open .obj \"%s\"", m_Path.string().c_str()); LOG_ERROR("Failed to open .obj \"%s\": %s", m_Path.string().c_str(), strerror(errno));
return false; return false;
} }
+3 -1
View File
@@ -12,7 +12,9 @@
#include <boost/filesystem/path.hpp> #include <boost/filesystem/path.hpp>
#include <boost/program_options.hpp> #include <boost/program_options.hpp>
class OBJ #include "ResourceManager.h"
class OBJ : public Resource
{ {
public: public:
struct MaterialInfo struct MaterialInfo
+21 -22
View File
@@ -7,13 +7,13 @@
void VehicleSetup::buildVehicle(World *world, const hkpWorld* physicsWorld, hkpVehicleInstance& vehicle, EntityID vehicleEntity, std::vector<EntityID> wheelEntities) void VehicleSetup::buildVehicle(World *world, const hkpWorld* physicsWorld, hkpVehicleInstance& vehicle, EntityID vehicleEntity, std::vector<EntityID> wheelEntities)
{ {
auto vehicleComponent = world->GetComponent<Components::Vehicle>(vehicleEntity, "Vehicle"); auto vehicleComponent = world->GetComponent<Components::Vehicle>(vehicleEntity);
WheelData wheelData; WheelData wheelData;
for (int i = 0; i < wheelEntities.size(); i++) for (int i = 0; i < wheelEntities.size(); i++)
{ {
wheelData.WheelComponent = world->GetComponent<Components::Wheel>(wheelEntities[i], "Wheel"); wheelData.WheelComponent = world->GetComponent<Components::Wheel>(wheelEntities[i]);
wheelData.TransformComponent = world->GetComponent<Components::Transform>(wheelEntities[i], "Transform"); wheelData.TransformComponent = world->GetComponent<Components::Transform>(wheelEntities[i]);
m_Wheels.push_back(wheelData); m_Wheels.push_back(wheelData);
} }
@@ -22,7 +22,7 @@ void VehicleSetup::buildVehicle(World *world, const hkpWorld* physicsWorld, hkpV
// //
vehicle.m_data = new hkpVehicleData; vehicle.m_data = new hkpVehicleData;
vehicle.m_driverInput = new hkpVehicleDefaultAnalogDriverInput; vehicle.m_driverInput = new hkpVehicleDefaultAnalogDriverInput;
vehicle.m_steering = new hkpVehicleDefaultSteering; vehicle.m_steering = new TankSteering;
vehicle.m_engine = new hkpVehicleDefaultEngine; vehicle.m_engine = new hkpVehicleDefaultEngine;
vehicle.m_transmission = new hkpVehicleDefaultTransmission; vehicle.m_transmission = new hkpVehicleDefaultTransmission;
vehicle.m_brake = new hkpVehicleDefaultBrake; vehicle.m_brake = new hkpVehicleDefaultBrake;
@@ -48,7 +48,6 @@ void VehicleSetup::buildVehicle(World *world, const hkpWorld* physicsWorld, hkpV
setupWheelCollide(physicsWorld, vehicle, *static_cast<hkpVehicleRayCastWheelCollide*>(vehicle.m_wheelCollide)); setupWheelCollide(physicsWorld, vehicle, *static_cast<hkpVehicleRayCastWheelCollide*>(vehicle.m_wheelCollide));
// //
// Check that all components are present. // Check that all components are present.
// //
@@ -105,7 +104,7 @@ void VehicleSetup::setupVehicleData(const hkpWorld* world, hkpVehicleData& data
data.m_torquePitchFactor = 0.5f; data.m_torquePitchFactor = 0.5f;
data.m_torqueYawFactor = 0.35f; data.m_torqueYawFactor = 0.35f;
data.m_chassisUnitInertiaYaw = 1.0f; data.m_chassisUnitInertiaYaw = 0.8f;
data.m_chassisUnitInertiaRoll = 1.0f; data.m_chassisUnitInertiaRoll = 1.0f;
data.m_chassisUnitInertiaPitch = 1.0f; data.m_chassisUnitInertiaPitch = 1.0f;
@@ -165,7 +164,7 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultS
// [mph/h] The steering angle decreases linearly // [mph/h] The steering angle decreases linearly
// based on your overall max speed of the vehicle. // based on your overall max speed of the vehicle.
steering.m_maxSpeedFullSteeringAngle = 70.0f * (1.605f / 3.6f); //MPH???! steering.m_maxSpeedFullSteeringAngle = vehicleComponent.MaxSpeedFullSteeringAngle; // * (1.605f / 3.6f); //MPH???!
for (int i = 0; i < m_Wheels.size(); i++) for (int i = 0; i < m_Wheels.size(); i++)
{ {
@@ -198,20 +197,21 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultT
transmission.m_gearsRatio.setSize(numberOfGears); transmission.m_gearsRatio.setSize(numberOfGears);
transmission.m_wheelsTorqueRatio.setSize(data.m_numWheels); transmission.m_wheelsTorqueRatio.setSize(data.m_numWheels);
transmission.m_downshiftRPM = 3500.0f; transmission.m_downshiftRPM = 3500.0f; //HACK: Should be in VehicleComponent
transmission.m_upshiftRPM = 6500.0f; transmission.m_upshiftRPM = 7000.0f;
transmission.m_clutchDelayTime = 0.0f; transmission.m_clutchDelayTime = 0.0f;
transmission.m_reverseGearRatio = 1.0f; transmission.m_reverseGearRatio = 1.0f;
transmission.m_gearsRatio[0] = 2.0f; transmission.m_gearsRatio[0] = 3.0f;
transmission.m_gearsRatio[1] = 1.5f; transmission.m_gearsRatio[1] = 2.25f;
transmission.m_gearsRatio[2] = 1.0f; transmission.m_gearsRatio[2] = 1.5f;
transmission.m_gearsRatio[3] = 0.75f; transmission.m_gearsRatio[3] = 1.0f;
transmission.m_wheelsTorqueRatio[0] = 0.2f;
transmission.m_wheelsTorqueRatio[1] = 0.2f; for(int i = 0; i < m_Wheels.size(); i++)
transmission.m_wheelsTorqueRatio[2] = 0.3f; {
transmission.m_wheelsTorqueRatio[3] = 0.3f; // The wheels total TorqueRatio must be equal to 1
transmission.m_wheelsTorqueRatio[i] = m_Wheels[i].WheelComponent->TorqueRatio;
}
transmission.m_primaryTransmissionRatio = hkpVehicleDefaultTransmission::calculatePrimaryTransmissionRatio( transmission.m_primaryTransmissionRatio = hkpVehicleDefaultTransmission::calculatePrimaryTransmissionRatio(
vehicleComponent.TopSpeed, vehicleComponent.TopSpeed,
@@ -246,9 +246,8 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultS
suspension.m_wheelParams[i].m_length = suspensionLength; suspension.m_wheelParams[i].m_length = suspensionLength;
suspension.m_wheelSpringParams[i].m_strength = m_Wheels[i].WheelComponent->SuspensionStrength; suspension.m_wheelSpringParams[i].m_strength = m_Wheels[i].WheelComponent->SuspensionStrength;
const float wd = 3.0f; suspension.m_wheelSpringParams[i].m_dampingCompression = vehicleComponent.SpringDamping;
suspension.m_wheelSpringParams[i].m_dampingCompression = wd; suspension.m_wheelSpringParams[i].m_dampingRelaxation = vehicleComponent.SpringDamping;
suspension.m_wheelSpringParams[i].m_dampingRelaxation = wd;
suspension.m_wheelParams[i].m_hardpointChassisSpace.set(m_Wheels[i].WheelComponent->Hardpoint.x, m_Wheels[i].WheelComponent->Hardpoint.y, m_Wheels[i].WheelComponent->Hardpoint.z); suspension.m_wheelParams[i].m_hardpointChassisSpace.set(m_Wheels[i].WheelComponent->Hardpoint.x, m_Wheels[i].WheelComponent->Hardpoint.y, m_Wheels[i].WheelComponent->Hardpoint.z);
@@ -267,7 +266,7 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultA
aerodynamics.m_liftCoefficient = -0.3f; aerodynamics.m_liftCoefficient = -0.3f;
// Extra gavity applies in world space (independent of m_chassisCoordinateSystem). // Extra gavity applies in world space (independent of m_chassisCoordinateSystem).
aerodynamics.m_extraGravityws.set(0.0f, -5.0f, 0.0f); aerodynamics.m_extraGravityws.set(0.0f, -8.0f, 0.0f); // fuck this shit
} }
void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultVelocityDamper& velocityDamper, Components::Vehicle vehicleComponent) void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultVelocityDamper& velocityDamper, Components::Vehicle vehicleComponent)
+30 -1
View File
@@ -21,6 +21,7 @@
#include <Physics2012/Vehicle/Engine/Default/hkpVehicleDefaultEngine.h> #include <Physics2012/Vehicle/Engine/Default/hkpVehicleDefaultEngine.h>
#include <Physics2012/Vehicle/VelocityDamper/Default/hkpVehicleDefaultVelocityDamper.h> #include <Physics2012/Vehicle/VelocityDamper/Default/hkpVehicleDefaultVelocityDamper.h>
#include <Physics2012/Vehicle/Steering/Default/hkpVehicleDefaultSteering.h> #include <Physics2012/Vehicle/Steering/Default/hkpVehicleDefaultSteering.h>
#include <Physics2012/Vehicle/Steering/hkpVehicleSteering.h>
#include <Physics2012/Vehicle/Suspension/Default/hkpVehicleDefaultSuspension.h> #include <Physics2012/Vehicle/Suspension/Default/hkpVehicleDefaultSuspension.h>
#include <Physics2012/Vehicle/Transmission/Default/hkpVehicleDefaultTransmission.h> #include <Physics2012/Vehicle/Transmission/Default/hkpVehicleDefaultTransmission.h>
#include <Physics2012/Vehicle/WheelCollide/RayCast/hkpVehicleRayCastWheelCollide.h> #include <Physics2012/Vehicle/WheelCollide/RayCast/hkpVehicleRayCastWheelCollide.h>
@@ -32,6 +33,32 @@
#include "Components/Wheel.h" #include "Components/Wheel.h"
#include "Components/Transform.h" #include "Components/Transform.h"
/// Tank specific steering implementation. Rear wheels steer in opposite direction
/// to front wheels.
class TankSteering: public hkpVehicleDefaultSteering
{
public:
virtual void calcSteering(const hkReal deltaTime, const hkpVehicleInstance* vehicle, const hkpVehicleDriverInput::FilteredDriverInputOutput& filteredInfoOutput, SteeringAnglesOutput& steeringOutput )
{
hkpVehicleDefaultSteering::calcMainSteeringAngle( deltaTime, vehicle, filteredInfoOutput, steeringOutput );
// Wheels.
for (int w_it = 0; w_it < m_doesWheelSteer.getSize(); w_it++)
{
if ( m_doesWheelSteer[w_it] )
{
steeringOutput.m_wheelsSteeringAngle [w_it] = steeringOutput.m_mainSteeringAngle;
}
else
{
// Steer with front and back wheels to simulate a tank.
steeringOutput.m_wheelsSteeringAngle [w_it] = -steeringOutput.m_mainSteeringAngle;
}
}
}
};
class VehicleSetup class VehicleSetup
{ {
public: public:
@@ -42,8 +69,9 @@ public:
{ {
Components::Wheel* WheelComponent; Components::Wheel* WheelComponent;
Components::Transform* TransformComponent; Components::Transform* TransformComponent;
};
};
std::vector<WheelData> m_Wheels; std::vector<WheelData> m_Wheels;
virtual void setupVehicleData(const hkpWorld* world, hkpVehicleData& data); virtual void setupVehicleData(const hkpWorld* world, hkpVehicleData& data);
@@ -58,6 +86,7 @@ public:
virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultVelocityDamper& velocityDamper, Components::Vehicle vehicleComponent); virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultVelocityDamper& velocityDamper, Components::Vehicle vehicleComponent);
virtual void setupWheelCollide(const hkpWorld* world, const hkpVehicleInstance& vehicle, hkpVehicleRayCastWheelCollide& wheelCollide); virtual void setupWheelCollide(const hkpWorld* world, const hkpVehicleInstance& vehicle, hkpVehicleRayCastWheelCollide& wheelCollide);
}; };
#endif // Physics_Vehicle_h__ #endif // Physics_Vehicle_h__
+93
View File
@@ -0,0 +1,93 @@
#ifndef RenderQueue_h__
#define RenderQueue_h__
#include <cstdint>
#include <forward_list>
#include "ResourceManager.h"
#include "Texture.h"
#include "Model.h"
class RenderQueue;
struct RenderJob
{
friend class RenderQueue;
protected:
uint64_t Hash;
virtual void CalculateHash() = 0;
bool operator<(const RenderJob& rhs)
{
return this->Hash < rhs.Hash;
}
};
struct ModelJob : RenderJob
{
unsigned int ShaderID;
unsigned int TextureID;
GLuint ShaderProgram;
GLuint DiffuseTexture;
GLuint NormalTexture;
GLuint SpecularTexture;
GLuint VAO;
unsigned int StartIndex;
unsigned int EndIndex;
glm::mat4 ModelMatrix;
void CalculateHash() override
{
Hash = TextureID;
}
};
struct SpriteJob : RenderJob
{
unsigned int ShaderID;
unsigned int TextureID;
GLuint ShaderProgram;
GLuint Texture;
glm::mat4 ModelMatrix;
void CalculateHash() override
{
Hash = TextureID;
}
};
class RenderQueue
{
public:
template <typename T>
void Add(T &job)
{
job.CalculateHash();
m_Jobs.push_front(std::shared_ptr<T>(new T(job)));
m_Jobs.sort();
}
void Clear()
{
m_Jobs.clear();
}
std::forward_list<std::shared_ptr<RenderJob>>::const_iterator begin()
{
return m_Jobs.begin();
}
std::forward_list<std::shared_ptr<RenderJob>>::const_iterator end()
{
return m_Jobs.end();
}
private:
std::forward_list<std::shared_ptr<RenderJob>> m_Jobs;
};
#endif // RenderQueue_h__
+742 -398
View File
File diff suppressed because it is too large Load Diff
+89 -24
View File
@@ -13,6 +13,8 @@
#include "Components/PointLight.h" #include "Components/PointLight.h"
#include "Skybox.h" #include "Skybox.h"
#include "ResourceManager.h" #include "ResourceManager.h"
#include "Util/Rectangle.h"
#include "RenderQueue.h"
class Renderer class Renderer
{ {
@@ -21,37 +23,57 @@ public:
glm::mat4 viewMatrix; glm::mat4 viewMatrix;
glm::mat4 projectionMatrix; glm::mat4 projectionMatrix;
int HEIGHT, WIDTH;
int Width() const { return m_Width; }
int Height() const { return m_Height; }
std::list<std::tuple<Model*, glm::mat4, bool, bool>> ModelsToRender; std::list<std::tuple<Model*, glm::mat4, bool, bool>> ModelsToRender;
int Lights; std::list<std::tuple<Texture*, glm::mat4, glm::vec3>> TexturesToRender;
std::vector<glm::vec3> Light_position;
std::vector<glm::vec3> Light_specular;
std::vector<glm::vec3> Light_diffuse;
std::vector<float> Light_specularExponent;
std::vector<float> Light_constantAttenuation;
std::vector<float> Light_linearAttenuation;
std::vector<float> Light_quadraticAttenuation;
std::vector<float> Light_spotExponent;
std::list<std::tuple<glm::mat4, bool>> AABBsToRender; std::list<std::tuple<glm::mat4, bool>> AABBsToRender;
Renderer(); Renderer(std::shared_ptr<::ResourceManager> resourceManager);
void Initialize(); void Initialize();
void Draw(double dt); void Draw(double dt);
void DrawText(); void DrawText();
void RegisterViewport(int identifier, float left, float top, float right, float bottom);
void RegisterCamera(int identifier, float FOV, float nearClip, float farClip);
void UpdateViewport(int viewportIdentifier, int cameraIdentifier);
void UpdateCamera(int cameraIdentifier, glm::vec3 position, glm::quat orientation, float FOV, float nearClip, float farClip);
#pragma region NEWSTUFF
void SetViewport(const Rectangle &viewport)
{
m_Viewport = viewport;
}
void SetCamera(std::shared_ptr<Camera> camera)
{
m_Camera = camera;
}
void DrawFrame(RenderQueue &rq);
void DrawWorld(RenderQueue &rq);
void Swap();
#pragma endregion
void AddModelToDraw(Model* model, glm::vec3 position, glm::quat orientation, glm::vec3 scale, bool visible, bool shadowCaster); void AddModelToDraw(Model* model, glm::vec3 position, glm::quat orientation, glm::vec3 scale, bool visible, bool shadowCaster);
void AddTextureToDraw(Texture* texture, glm::vec3 position, glm::quat orientation, glm::vec3 scale);
void AddTextToDraw(); void AddTextToDraw();
void AddPointLightToDraw( void AddPointLightToDraw(
glm::vec3 _position, glm::vec3 _position,
glm::vec3 _specular, glm::vec3 _specular,
glm::vec3 _diffuse, glm::vec3 _diffuse,
float _specularExponent float _specularExponent,
float _ConstantAttenuation,
float _LinearAttenuation,
float _QuadraticAttenuation,
float _radius
); );
void ClearPointLights();
void AddAABBToDraw(glm::vec3 origin, glm::vec3 volumeVector, bool colliding); void AddAABBToDraw(glm::vec3 origin, glm::vec3 volumeVector, bool colliding);
void LoadContent(); void LoadContent();
@@ -69,9 +91,40 @@ public:
void SetSphereModel(Model* _model); void SetSphereModel(Model* _model);
private: private:
std::shared_ptr<::ResourceManager> ResourceManager;
int m_Width, m_Height;
struct Viewport
{
float Left;
float Top;
float Right;
float Bottom;
std::shared_ptr<Camera> Camera;
};
std::unordered_map<int, Viewport> m_Viewports;
std::unordered_map<int, std::shared_ptr<Camera>> m_Cameras;
Rectangle m_Viewport;
std::shared_ptr<Camera> m_Camera;
struct Light
{
glm::vec3 Position;
glm::vec3 Specular;
glm::vec3 Diffuse;
float SpecularExponent;
glm::mat4 SphereModelMatrix;
float ConstantAttenuation, LinearAttenuation, QuadraticAttenuation, Radius;
};
float Gamma;
std::list<Light> Lights;
GLFWwindow* m_Window; GLFWwindow* m_Window;
GLint m_glVersion[2]; GLint m_glVersion[2];
GLchar* m_glVendor; GLchar* m_glVendor;
@@ -79,6 +132,7 @@ private:
bool m_DrawNormals; bool m_DrawNormals;
bool m_DrawWireframe; bool m_DrawWireframe;
bool m_DrawBounds; bool m_DrawBounds;
float CAtt, LAtt, QAtt;
std::shared_ptr<Skybox> m_Skybox; std::shared_ptr<Skybox> m_Skybox;
@@ -86,6 +140,10 @@ private:
glm::vec3 m_SunPosition; glm::vec3 m_SunPosition;
glm::vec3 m_SunTarget; glm::vec3 m_SunTarget;
glm::mat4 m_SunProjection; glm::mat4 m_SunProjection;
glm::vec2 m_SunProjection_width;
glm::vec2 m_SunProjection_height;
glm::vec2 m_SunProjection_length;
GLuint m_DebugAABB; GLuint m_DebugAABB;
GLuint m_ShadowFrameBuffer; GLuint m_ShadowFrameBuffer;
@@ -95,25 +153,26 @@ private:
GLuint m_fDiffuseTexture; GLuint m_fDiffuseTexture;
GLuint m_fPositionTexture; GLuint m_fPositionTexture;
GLuint m_fNormalsTexture; GLuint m_fNormalsTexture;
GLuint m_fSpecularTexture;
GLuint m_fBlendTexture; GLuint m_fBlendTexture;
GLuint m_fbLightingPass; GLuint m_fbLightingPass;
GLuint m_fLightingTexture; GLuint m_fLightingTexture;
GLuint m_fShadowTexture;
GLuint m_fDepthBuffer; GLuint m_fDepthBuffer;
GLenum draw_bufs[2]; GLenum draw_bufs[2];
glm::mat4 lM[5];
GLuint m_ScreenQuad; GLuint m_ScreenQuad;
Model* m_sphereModel; Model* m_sphereModel;
bool m_QuadView; bool m_QuadView;
std::shared_ptr<Camera> m_Camera;
ShaderProgram m_ShaderProgram; ShaderProgram m_ShaderProgram;
ShaderProgram m_FirstPassProgram; ShaderProgram m_FirstPassProgram;
ShaderProgram m_SecondPassProgram; ShaderProgram m_SecondPassProgram;
ShaderProgram m_SecondPassProgram_Debug; ShaderProgram m_SecondPassProgram_Debug;
ShaderProgram m_FinalPassProgram; ShaderProgram m_FinalPassProgram;
ShaderProgram m_SunPassProgram;
ShaderProgram m_ForwardRendering;
ShaderProgram m_ShaderProgramNormals; ShaderProgram m_ShaderProgramNormals;
ShaderProgram m_ShaderProgramShadows; ShaderProgram m_ShaderProgramShadows;
@@ -126,14 +185,20 @@ private:
void ClearStuff(); void ClearStuff();
void DrawScene(); void DrawScene();
void DrawModels(ShaderProgram &shader); void DrawModels(ShaderProgram &shader);
void DrawShadowMap(); void DrawShadowMap(RenderQueue &rq);
void CreateShadowMap(int resolution); void CreateShadowMap(int resolution);
void FrameBufferTextures(); void FrameBufferTextures();
void DrawFBO(); void DrawFBO();
void DrawFBOScene(); void DrawFBO2();
void DrawLightScene(); void DrawFBOScene(RenderQueue &rq);
void DrawLightScene(RenderQueue &rq);
void DrawSunLightScene();
void BindFragDataLocation(); void BindFragDataLocation();
void CreateLightMatrix(); glm::mat4 CreateLightMatrix(Light &_light);
void UpdateSunProjection();
void CreateNormalMapTangent();
void ForwardRendering();
GLuint CreateQuad(); GLuint CreateQuad();
void DrawDebugShadowMap(); void DrawDebugShadowMap();
+4 -4
View File
@@ -16,7 +16,7 @@ Resource* ResourceManager::CreateResource(std::string resourceType, std::string
resource->TypeID = GetTypeID(resourceType); resource->TypeID = GetTypeID(resourceType);
resource->ResourceID = GetNewResourceID(resource->TypeID); resource->ResourceID = GetNewResourceID(resource->TypeID);
// Cache // Cache
m_ResourceCache[resourceName] = resource; m_ResourceCache[std::make_pair(resourceType, resourceName)] = resource;
return resource; return resource;
} }
@@ -28,7 +28,7 @@ void ResourceManager::RegisterType(std::string resourceType, std::function<Resou
void ResourceManager::Preload(std::string resourceType, std::string resourceName) void ResourceManager::Preload(std::string resourceType, std::string resourceName)
{ {
if (IsResourceLoaded(resourceName)) if (IsResourceLoaded(resourceType, resourceName))
{ {
LOG_WARNING("Attempted to preload resource \"%s\" multiple times!", resourceName); LOG_WARNING("Attempted to preload resource \"%s\" multiple times!", resourceName);
return; return;
@@ -54,7 +54,7 @@ unsigned int ResourceManager::GetNewResourceID(unsigned int typeID)
return m_ResourceCount[typeID]++; return m_ResourceCount[typeID]++;
} }
bool ResourceManager::IsResourceLoaded(std::string resourceName) bool ResourceManager::IsResourceLoaded(std::string resourceType, std::string resourceName)
{ {
return m_ResourceCache.find(resourceName) != m_ResourceCache.end(); return m_ResourceCache.find(std::make_pair(resourceType, resourceName)) != m_ResourceCache.end();
} }
+5 -4
View File
@@ -6,6 +6,7 @@
#include <vector> #include <vector>
#include <unordered_map> #include <unordered_map>
#include "Util/UnorderedMapPair.h"
#include "Factory.h" #include "Factory.h"
class Resource class Resource
@@ -28,7 +29,7 @@ public:
void Preload(std::string resourceType, std::string resourceName); void Preload(std::string resourceType, std::string resourceName);
// Checks if a resource is in cache // Checks if a resource is in cache
bool IsResourceLoaded(std::string resourceName); bool IsResourceLoaded(std::string resourceType, std::string resourceName);
template <typename T> template <typename T>
// Hot-loads a resource and caches it for future use // Hot-loads a resource and caches it for future use
@@ -40,7 +41,7 @@ public:
private: private:
std::unordered_map<std::string, std::function<Resource*(std::string)>> m_FactoryFunctions; // type -> factory function std::unordered_map<std::string, std::function<Resource*(std::string)>> m_FactoryFunctions; // type -> factory function
std::unordered_map<std::string, Resource*> m_ResourceCache; // name -> resource std::unordered_map<std::pair<std::string, std::string>, Resource*> m_ResourceCache; // (type, name) -> resource
// TODO: Getters for IDs // TODO: Getters for IDs
unsigned int m_CurrentResourceTypeID; unsigned int m_CurrentResourceTypeID;
@@ -60,7 +61,7 @@ private:
template <typename T> template <typename T>
T* ResourceManager::Load(std::string resourceType, std::string resourceName) T* ResourceManager::Load(std::string resourceType, std::string resourceName)
{ {
auto it = m_ResourceCache.find(resourceName); auto it = m_ResourceCache.find(std::make_pair(resourceType, resourceName));
if (it != m_ResourceCache.end()) if (it != m_ResourceCache.end())
return static_cast<T*>(it->second); return static_cast<T*>(it->second);
@@ -79,7 +80,7 @@ T* ResourceManager::Load(std::string resourceType, std::string resourceName)
template <typename T> template <typename T>
T* ResourceManager::Fetch(std::string resourceName) const T* ResourceManager::Fetch(std::string resourceName) const
{ {
auto it = m_ResourceCache.find(resourceName); auto it = m_ResourceCache.find(std::make_pair(resourceType, resourceName));
if (it == m_ResourceCache.end()) if (it == m_ResourceCache.end())
{ {
LOG_ERROR("Failed to fetch resource \"%s\": Resource not loaded!", resourceName.c_str()); LOG_ERROR("Failed to fetch resource \"%s\": Resource not loaded!", resourceName.c_str());
+38 -1
View File
@@ -155,4 +155,41 @@ void ShaderProgram::Bind()
void ShaderProgram::Unbind() void ShaderProgram::Unbind()
{ {
glActiveShaderProgram(0, 0); glActiveShaderProgram(0, 0);
} }
void ShaderProgram::LoadFromFolder(std::string folderPath)
{
auto path = boost::filesystem::path(folderPath);
if (!boost::filesystem::is_directory(path))
{
LOG_ERROR("Failed to load shader program: \"%s\" is not a directory", folderPath.c_str());
return;
}
for (auto it = boost::filesystem::directory_iterator(path); it != boost::filesystem::directory_iterator(); it++)
{
std::string filename = it->path().filename().string();
if (filename == "Vertex.glsl")
{
AddShader(std::shared_ptr<Shader>(new VertexShader(filename)));
}
else if (filename == "Fragment.glsl")
{
AddShader(std::shared_ptr<Shader>(new FragmentShader(filename)));
}
else if (filename == "Geometry.glsl")
{
AddShader(std::shared_ptr<Shader>(new GeometryShader(filename)));
}
}
}
void ShaderProgram::BindFragDataLocation(int colorNumber, std::string name)
{
if (m_ShaderProgramHandle == 0)
return;
glBindFragDataLocation(m_ShaderProgramHandle, colorNumber, name.c_str());
}
+16 -2
View File
@@ -6,6 +6,11 @@
#include <fstream> #include <fstream>
#include <vector> #include <vector>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include "ResourceManager.h"
class Shader class Shader
{ {
public: public:
@@ -57,23 +62,32 @@ public:
: ShaderType(fileName) { } : ShaderType(fileName) { }
}; };
class ShaderProgram class ShaderProgram : public Resource
{ {
public: public:
ShaderProgram() ShaderProgram()
: m_ShaderProgramHandle(0) { } : m_ShaderProgramHandle(0)
{ }
ShaderProgram(std::string folderPath)
: m_ShaderProgramHandle(0)
{ }
~ShaderProgram(); ~ShaderProgram();
void AddShader(std::shared_ptr<Shader> shader); void AddShader(std::shared_ptr<Shader> shader);
void BindFragDataLocation(int colorNumber, std::string name);
void Compile(); void Compile();
GLuint Link(); GLuint Link();
GLuint GetHandle(); GLuint GetHandle();
operator GLuint() const { return m_ShaderProgramHandle; }
void Bind(); void Bind();
void Unbind(); void Unbind();
private: private:
GLuint m_ShaderProgramHandle; GLuint m_ShaderProgramHandle;
std::vector<std::shared_ptr<Shader>> m_Shaders; std::vector<std::shared_ptr<Shader>> m_Shaders;
void LoadFromFolder(std::string folderPath);
}; };
#endif // ShaderProgram_h__ #endif // ShaderProgram_h__
+9 -1
View File
@@ -1,9 +1,11 @@
#version 430 #version 430
uniform vec3 La; uniform vec3 La;
uniform float Gamma;
layout (binding=0) uniform sampler2D DiffuseTexture; layout (binding=0) uniform sampler2D DiffuseTexture;
layout (binding=1) uniform sampler2D LightingTexture; layout (binding=1) uniform sampler2D LightingTexture;
layout (binding=2) uniform sampler2D ShadowTexture;
in VertexData in VertexData
{ {
@@ -17,6 +19,12 @@ void main()
{ {
vec4 DiffuseTexel = texture(DiffuseTexture, Input.TextureCoord); vec4 DiffuseTexel = texture(DiffuseTexture, Input.TextureCoord);
vec4 LightingTexel = texture(LightingTexture, Input.TextureCoord); vec4 LightingTexel = texture(LightingTexture, Input.TextureCoord);
vec4 ShadowTexel = texture(ShadowTexture, Input.TextureCoord);
FragmentColor = DiffuseTexel * vec4(La, 1.0) + LightingTexel; //FragmentColor = LightingTexel + vec4(LightingTexel.a, LightingTexel.a, LightingTexel.a, 0.0);
//FragmentColor = DiffuseTexel;
FragmentColor = DiffuseTexel * (vec4(La, 0.0) + vec4(LightingTexel.rgb, 0.0)) + vec4(LightingTexel.a, LightingTexel.a, LightingTexel.a, 0.0);
//FragmentColor = vec4(pow(_FragmentColor.rgb, vec3(1.0 / Gamma)), _FragmentColor.a);
} }
+18
View File
@@ -0,0 +1,18 @@
#version 430
layout(binding=0) uniform sampler2D texture0;
in VertexData {
vec3 Position;
vec3 Normal;
vec2 TextureCoord;
} Input;
out vec4 fragmentColor;
void main() {
// Texture
vec4 texel = texture(texture0, Input.TextureCoord);
fragmentColor = texel;
}
+25
View File
@@ -0,0 +1,25 @@
#version 430
uniform mat4 MVP;
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 vec2 TextureCoord;
out VertexData {
vec3 Position;
vec3 Normal;
vec2 TextureCoord;
} Output;
void main()
{
gl_Position = MVP * vec4(Position, 1.0);
Output.Position = Position;
Output.Normal = Normal;
Output.TextureCoord = TextureCoord;
}
+74 -4
View File
@@ -1,26 +1,96 @@
#version 430 #version 430
layout (binding=0) uniform sampler2D DiffuseTexture; layout (binding=0) uniform sampler2D DiffuseTexture;
layout (binding=1) uniform sampler2D ShadowTexture;
layout (binding=2) uniform sampler2D NormalMapTexture;
layout (binding=3) uniform sampler2D SpecularMapTexture;
//TerrainTextures
layout (binding=4) uniform sampler2D AsphaltTexture;
layout (binding=5) uniform sampler2D GrassTexture;
layout (binding=6) uniform sampler2D SandTexture;
layout (binding=7) uniform sampler2D BlendMap;
uniform float texScale; //Determines how many times the textures will loop over the terrain
uniform vec3 SunDirection_cameraspace;
uniform mat4 V;
in VertexData in VertexData
{ {
vec3 Position; vec3 Position;
vec3 Normal; vec3 Normal;
vec2 TextureCoord; vec2 TextureCoord;
vec4 ShadowCoord;
vec3 Tangent;
vec3 BiTangent;
} Input; } Input;
out vec4 frag_Diffuse; out vec4 frag_Diffuse;
out vec4 frag_Position; out vec4 frag_Position;
out vec4 frag_Normal; out vec4 frag_Normal;
out vec4 frag_Specular;
float Shadow(vec4 ShadowCoord, vec3 normal)
{
return 1.0;
if (Input.ShadowCoord.x < 0.0 || Input.ShadowCoord.x > 1.0 || Input.ShadowCoord.y < 0.0 || Input.ShadowCoord.y > 1.0)
return 0.9;
//Variable bias
vec3 n = normalize(normal);
vec3 l = normalize(SunDirection_cameraspace);
float cosTheta = clamp(dot(n, l), 0.0, 1.0);
float bias = tan(acos(cosTheta));
bias = clamp(bias, 0.0, 0.00003);
//Fixed bias
bias = 0;
if( texture(ShadowTexture, Input.ShadowCoord.xy).z < ShadowCoord.z + bias)
{
return 0.6;
}
else
{
return 1.0;
}
}
void main() void main()
{ {
// Diffuse Texture //Fixa så den bara gör detta om modellen har en blend map
frag_Diffuse = texture2D(DiffuseTexture, Input.TextureCoord); //vvvvvv
vec4 Blend = texture2D(BlendMap, Input.TextureCoord.st );
vec4 AsphaltTexel = texture2D(AsphaltTexture, Input.TextureCoord.st * texScale);
vec4 GrassTexel = texture2D(GrassTexture, Input.TextureCoord.st * texScale);
vec4 SandTexel = texture2D(SandTexture, Input.TextureCoord.st * texScale);
//Mix the Terrain-textures together
AsphaltTexel *= Blend.r;
GrassTexel = mix(AsphaltTexel, GrassTexel, Blend.g);
vec4 tex = mix(GrassTexel, SandTexel, Blend.b);
//^^^^^^
//Fixa så den bara gör detta om modellen har en blend map
// G-buffer Position // G-buffer Position
frag_Position = vec4(Input.Position.xyz, 0.0); frag_Position = vec4(Input.Position.xyz, 1.0);
// G-buffer Normal // G-buffer Normal
frag_Normal = vec4(Input.Normal, 0.0); mat3 TBN = mat3(Input.Tangent, Input.BiTangent, Input.Normal);
frag_Normal = normalize(vec4(TBN * vec3(texture(NormalMapTexture, Input.TextureCoord)), 0.0));
//frag_Diffuse = normalize(vec4(TBN * vec3(texture(NormalMapTexture, Input.TextureCoord)), 0.0));
//frag_Normal = vec4(Input.Normal, 0.0);
// Diffuse Texture
//frag_Diffuse = tex;
frag_Diffuse = texture(DiffuseTexture, Input.TextureCoord) * Shadow(Input.ShadowCoord, vec3(frag_Normal));
//G-buffer Specular
frag_Specular = texture(SpecularMapTexture, Input.TextureCoord);
} }
+17 -25
View File
@@ -2,6 +2,7 @@
layout (binding=0) uniform sampler2D PositionTexture; layout (binding=0) uniform sampler2D PositionTexture;
layout (binding=1) uniform sampler2D NormalsTexture; layout (binding=1) uniform sampler2D NormalsTexture;
layout (binding=2) uniform sampler2D SpecularTexture;
uniform vec2 ViewportSize; uniform vec2 ViewportSize;
uniform mat4 MVP; uniform mat4 MVP;
@@ -12,15 +13,19 @@ uniform vec3 la;
uniform vec3 ls; uniform vec3 ls;
uniform vec3 ld; uniform vec3 ld;
uniform vec3 lp; uniform vec3 lp;
uniform float LightRadius; uniform float specularExponent;
const float specularExponent = 50.0;
uniform vec3 CameraPosition; uniform vec3 CameraPosition;
uniform float ConstantAttenuation;
uniform float LinearAttenuation;
uniform float QuadraticAttenuation;
uniform float LightRadius;
const vec3 ks = vec3(1.0, 0.0, 0.0); const vec3 ks = vec3(1.0, 1.0, 1.0);
const vec3 kd = vec3(0.8, 0.8, 0.8); const vec3 kd = vec3(1.0, 1.0, 1.0);
const vec3 ka = vec3(1.0, 1.0, 1.0); const vec3 ka = vec3(1.0, 1.0, 1.0);
const float kshine = 1.0; const float kshine = 1.0;
in VertexData in VertexData
{ {
vec3 Position; vec3 Position;
@@ -29,7 +34,7 @@ in VertexData
out vec4 FragColor; out vec4 FragColor;
vec4 phong4(vec3 position, vec3 normal) vec4 phong(vec3 position, vec3 normal, vec3 specular)
{ {
// Diffuse // Diffuse
vec3 lightPos = vec3(V * vec4(lp, 1.0)); vec3 lightPos = vec3(V * vec4(lp, 1.0));
@@ -44,30 +49,15 @@ vec4 phong4(vec3 position, vec3 normal)
vec3 surfaceToViewer = normalize(-position); vec3 surfaceToViewer = normalize(-position);
vec3 halfWay = normalize(surfaceToViewer + directionToLight); vec3 halfWay = normalize(surfaceToViewer + directionToLight);
float dotSpecular = max(dot(halfWay, normal), 0.0); float dotSpecular = max(dot(halfWay, normal), 0.0);
float specularFactor = pow(dotSpecular, specularExponent * 2); float specularFactor = pow(dotSpecular, specularExponent);
vec3 Is = ks * ls * specularFactor; vec3 Is = specular.r * ls * specularFactor;
//Attenuation //Attenuation
float dist = distance(lightPos, position); float dist = distance(lightPos, position);
float attenuation = -log(min(1.0, dist / LightRadius));
//float attenuation = 1.0 / (1.0 - 0.0001 * pow(dist, 2));
//float attenuation = clamp(0.0, 1.0, 1.0 / (0.001 + (0.001 * dist) + (0.001 * dist * dist))); float attenuation = pow(max(0.0f, 1.0 - (dist / LightRadius)), 2);
//float attenuation = 1.0 / dot(directionToLight, directionToLight); return vec4((Id) * attenuation, Is.r * attenuation);
//float att_s = 5;
//float attenuation = pow(dist, 2) / pow(5.0, 2);
//attenuation = 1.0 / (1.0 + attenuation * att_s);
//att_s = 1.0 / (1.0 + att_s);
//attenuation = attenuation / (1.0 - att_s);
float radius = 5.0;
float alpha = dist / radius;
float dampingFactor = 1.0 - pow(alpha, 3);
return vec4((Id + Is) * attenuation, 1.0);
} }
void main() void main()
@@ -75,6 +65,8 @@ void main()
vec2 TextureCoord = gl_FragCoord.xy / ViewportSize; vec2 TextureCoord = gl_FragCoord.xy / ViewportSize;
vec4 PositionTexel = texture(PositionTexture, TextureCoord); vec4 PositionTexel = texture(PositionTexture, TextureCoord);
vec4 NormalTexel = texture(NormalsTexture, TextureCoord); vec4 NormalTexel = texture(NormalsTexture, TextureCoord);
vec4 SpecularTexel = texture(SpecularTexture, TextureCoord);
FragColor = phong4(vec3(PositionTexel), vec3(NormalTexel)); FragColor = phong(vec3(PositionTexel), vec3(NormalTexel), vec3(SpecularTexel));
//FragColor = NormalTexel;
} }
+61
View File
@@ -0,0 +1,61 @@
#version 430
layout (binding=0) uniform sampler2D PositionTexture;
layout (binding=1) uniform sampler2D NormalsTexture;
layout (binding=2) uniform sampler2D SpecularTexture;
uniform vec2 ViewportSize;
uniform mat4 MVP;
uniform mat4 M;
uniform mat4 V;
uniform mat4 P;
uniform vec3 CameraPosition;
uniform vec3 directionToSun;
const vec3 ks = vec3(1.0, 1.0, 1.0);
const vec3 kd = vec3(1.0, 1.0, 1.0);
const vec3 ka = vec3(1.0, 1.0, 1.0);
const float kshine = 1.0;
const vec3 SunDiffuseLight = vec3(0.3, 0.3, 0.3);
const vec3 SunSpecularLight = vec3(1.0, 1.0, 1.0);
const vec3 SunPos = directionToSun*vec3(100);
const float specularExponent = 5;
in VertexData
{
vec3 Position;
vec2 TextureCoord;
} Input;
out vec4 FragColor;
vec4 phong(vec3 position, vec3 normal, vec3 specular)
{
//Diffuse Sunlight
vec3 directionToLight = normalize(vec3(V * vec4(directionToSun, 0.0)));
float dotProdLight = dot(directionToLight, normal);
dotProdLight = max(dotProdLight, 0.0);
vec3 sId = kd * SunDiffuseLight * dotProdLight;
//Specular Sunlight
vec3 surfaceToViewer = normalize(-position);
vec3 halfWay = normalize(surfaceToViewer + directionToLight);
float dotSpecular = max(dot(halfWay, normal), 0.0);
float specularFactorSun = pow(dotSpecular, specularExponent);
vec3 sIs = specular.r * SunSpecularLight * specularFactorSun;
return vec4((sId), sIs.r);
}
void main()
{
vec2 TextureCoord = gl_FragCoord.xy / ViewportSize;
vec4 PositionTexel = texture(PositionTexture, TextureCoord);
vec4 NormalTexel = texture(NormalsTexture, TextureCoord);
vec4 SpecularTexel = texture(SpecularTexture, TextureCoord);
FragColor = phong(vec3(PositionTexel), vec3(normalize(NormalTexel)), vec3(SpecularTexel));
//FragColor = NormalTexel;
}
+21
View File
@@ -0,0 +1,21 @@
#version 430
uniform mat4 MVP;
layout (location = 0) in vec3 Position;
layout (location = 2) in vec2 TextureCoord;
uniform mat4 depthBiasMVP;
out VertexData
{
vec3 Position;
vec2 TextureCoord;
} Output;
void main()
{
gl_Position = MVP * vec4(Position, 1.0);
Output.Position = Position;
Output.TextureCoord = (vec2(Position) + 1.0) / 2.0;
}

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