├── .gitignore
├── .vscode
└── settings.json
├── AssignmentCppCheck.cppcheck
├── Engine
├── Engine.vcxproj
├── Engine.vcxproj.filters
├── General
│ ├── Actor.cpp
│ ├── Actor.h
│ ├── Components
│ │ ├── BoxCollider.h
│ │ ├── CircleCollider.h
│ │ ├── Follow.h
│ │ ├── IActorComponent.h
│ │ └── Physics.h
│ ├── Systems
│ │ ├── CollisionSystem.cpp
│ │ ├── CollisionSystem.h
│ │ ├── Input.cpp
│ │ └── Input.h
│ ├── World.cpp
│ └── World.h
├── Jobs
│ ├── Console
│ │ ├── ConsolePrint.Win32.cpp
│ │ └── ConsolePrint.h
│ ├── HashedString
│ │ ├── HashedString-inl.h
│ │ ├── HashedString.cpp
│ │ └── HashedString.h
│ ├── JobSystem
│ │ ├── IJob.cpp
│ │ ├── IJob.h
│ │ ├── INamed.h
│ │ ├── JobRunner.cpp
│ │ ├── JobRunner.h
│ │ ├── JobSystem.cpp
│ │ ├── JobSystem.h
│ │ ├── SharedJobQueue-inl.h
│ │ ├── SharedJobQueue.cpp
│ │ └── SharedJobQueue.h
│ └── Syncronization
│ │ ├── Events.cpp
│ │ ├── Events.h
│ │ ├── Mutex.cpp
│ │ ├── Mutex.h
│ │ ├── ScopeLock.h
│ │ ├── Semaphore.cpp
│ │ ├── Semaphore.h
│ │ ├── SingleWriterMultipleReader.h
│ │ └── WaitableObject.h
├── Math
│ ├── Math.h
│ ├── Matrix3.h
│ ├── Matrix4.h
│ ├── Vector.h
│ ├── Vector3.h
│ ├── Vector4.h
│ └── pchMath.h
├── Memory
│ ├── BitArray.cpp
│ ├── BitArray.h
│ ├── FixedSizeAllocator.cpp
│ ├── FixedSizeAllocator.h
│ ├── MemorySystem.cpp
│ ├── MemorySystem.h
│ ├── PoolAllocator.cpp
│ ├── PoolAllocator.h
│ └── SmartPointer
│ │ ├── RefCount.h
│ │ ├── SmartPtr.h
│ │ ├── SmartPtrConversion.h
│ │ └── WeakPtr.h
├── Render
│ └── GLibHelper.h
└── String
│ ├── String.cpp
│ └── String.h
├── EnginePlusPong.sln
├── Exports
├── GLib
│ ├── BasicTypes.h
│ ├── GLib.h
│ └── GLib.lib
└── json.hpp
├── FixedSizeAllocator.png
├── LICENSE.md
├── MemoryPoolAllocator.png
├── Pong
├── Assets
│ ├── BrickGreen.dds
│ ├── BrickRed.dds
│ ├── Circle.dds
│ ├── LeftPaddle.dds
│ ├── RightPaddle.dds
│ ├── Square.dds
│ └── WhiteSquareArrow.dds
├── Pong.cpp
├── Pong.vcxproj
├── Pong.vcxproj.filters
└── Saved
│ ├── Ball.json
│ ├── EditorState2.json
│ ├── EditorStatePong.json
│ ├── LeftPaddle.json
│ └── RightPaddle.json
├── README.md
└── ReadMe.txt
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | x64/
19 | x86/
20 | bld/
21 | [Bb]in/
22 | [Oo]bj/
23 | [Ll]og/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 | # Uncomment if you have tasks that create the project's static files in wwwroot
28 | #wwwroot/
29 |
30 | # MSTest test Results
31 | [Tt]est[Rr]esult*/
32 | [Bb]uild[Ll]og.*
33 |
34 | # NUNIT
35 | *.VisualState.xml
36 | TestResult.xml
37 |
38 | # Build Results of an ATL Project
39 | [Dd]ebugPS/
40 | [Rr]eleasePS/
41 | dlldata.c
42 |
43 | # DNX
44 | project.lock.json
45 | project.fragment.lock.json
46 | artifacts/
47 |
48 | *_i.c
49 | *_p.c
50 | *_i.h
51 | *.ilk
52 | *.meta
53 | *.obj
54 | *.pch
55 | *.pdb
56 | *.pgc
57 | *.pgd
58 | *.rsp
59 | *.sbr
60 | *.tlb
61 | *.tli
62 | *.tlh
63 | *.tmp
64 | *.tmp_proj
65 | *.log
66 | *.vspscc
67 | *.vssscc
68 | .builds
69 | *.pidb
70 | *.svclog
71 | *.scc
72 |
73 | # Chutzpah Test files
74 | _Chutzpah*
75 |
76 | # Visual C++ cache files
77 | ipch/
78 | *.aps
79 | *.ncb
80 | *.opendb
81 | *.opensdf
82 | *.sdf
83 | *.cachefile
84 | *.VC.db
85 | *.VC.VC.opendb
86 |
87 | # Visual Studio profiler
88 | *.psess
89 | *.vsp
90 | *.vspx
91 | *.sap
92 |
93 | # TFS 2012 Local Workspace
94 | $tf/
95 |
96 | # Guidance Automation Toolkit
97 | *.gpState
98 |
99 | # ReSharper is a .NET coding add-in
100 | _ReSharper*/
101 | *.[Rr]e[Ss]harper
102 | *.DotSettings.user
103 |
104 | # JustCode is a .NET coding add-in
105 | .JustCode
106 |
107 | # TeamCity is a build add-in
108 | _TeamCity*
109 |
110 | # DotCover is a Code Coverage Tool
111 | *.dotCover
112 |
113 | # NCrunch
114 | _NCrunch_*
115 | .*crunch*.local.xml
116 | nCrunchTemp_*
117 |
118 | # MightyMoose
119 | *.mm.*
120 | AutoTest.Net/
121 |
122 | # Web workbench (sass)
123 | .sass-cache/
124 |
125 | # Installshield output folder
126 | [Ee]xpress/
127 |
128 | # DocProject is a documentation generator add-in
129 | DocProject/buildhelp/
130 | DocProject/Help/*.HxT
131 | DocProject/Help/*.HxC
132 | DocProject/Help/*.hhc
133 | DocProject/Help/*.hhk
134 | DocProject/Help/*.hhp
135 | DocProject/Help/Html2
136 | DocProject/Help/html
137 |
138 | # Click-Once directory
139 | publish/
140 |
141 | # Publish Web Output
142 | *.[Pp]ublish.xml
143 | *.azurePubxml
144 | # TODO: Comment the next line if you want to checkin your web deploy settings
145 | # but database connection strings (with potential passwords) will be unencrypted
146 | #*.pubxml
147 | *.publishproj
148 |
149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
150 | # checkin your Azure Web App publish settings, but sensitive information contained
151 | # in these scripts will be unencrypted
152 | PublishScripts/
153 |
154 | # NuGet Packages
155 | *.nupkg
156 | # The packages folder can be ignored because of Package Restore
157 | **/packages/*
158 | # except build/, which is used as an MSBuild target.
159 | !**/packages/build/
160 | # Uncomment if necessary however generally it will be regenerated when needed
161 | #!**/packages/repositories.config
162 | # NuGet v3's project.json files produces more ignoreable files
163 | *.nuget.props
164 | *.nuget.targets
165 |
166 | # Microsoft Azure Build Output
167 | csx/
168 | *.build.csdef
169 |
170 | # Microsoft Azure Emulator
171 | ecf/
172 | rcf/
173 |
174 | # Windows Store app package directories and files
175 | AppPackages/
176 | BundleArtifacts/
177 | Package.StoreAssociation.xml
178 | _pkginfo.txt
179 |
180 | # Visual Studio cache files
181 | # files ending in .cache can be ignored
182 | *.[Cc]ache
183 | # but keep track of directories ending in .cache
184 | !*.[Cc]ache/
185 |
186 | # Others
187 | ClientBin/
188 | ~$*
189 | *~
190 | *.dbmdl
191 | *.dbproj.schemaview
192 | *.jfm
193 | *.pfx
194 | *.publishsettings
195 | node_modules/
196 | orleans.codegen.cs
197 |
198 | # Since there are multiple workflows, uncomment next line to ignore bower_components
199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
200 | #bower_components/
201 |
202 | # RIA/Silverlight projects
203 | Generated_Code/
204 |
205 | # Backup & report files from converting an old project file
206 | # to a newer Visual Studio version. Backup files are not needed,
207 | # because we have git ;-)
208 | _UpgradeReport_Files/
209 | Backup*/
210 | UpgradeLog*.XML
211 | UpgradeLog*.htm
212 |
213 | # SQL Server files
214 | *.mdf
215 | *.ldf
216 |
217 | # Business Intelligence projects
218 | *.rdl.data
219 | *.bim.layout
220 | *.bim_*.settings
221 |
222 | # Microsoft Fakes
223 | FakesAssemblies/
224 |
225 | # GhostDoc plugin setting file
226 | *.GhostDoc.xml
227 |
228 | # Node.js Tools for Visual Studio
229 | .ntvs_analysis.dat
230 |
231 | # Visual Studio 6 build log
232 | *.plg
233 |
234 | # Visual Studio 6 workspace options file
235 | *.opt
236 |
237 | # Visual Studio LightSwitch build output
238 | **/*.HTMLClient/GeneratedArtifacts
239 | **/*.DesktopClient/GeneratedArtifacts
240 | **/*.DesktopClient/ModelManifest.xml
241 | **/*.Server/GeneratedArtifacts
242 | **/*.Server/ModelManifest.xml
243 | _Pvt_Extensions
244 |
245 | # Paket dependency manager
246 | .paket/paket.exe
247 | paket-files/
248 |
249 | # FAKE - F# Make
250 | .fake/
251 |
252 | # JetBrains Rider
253 | .idea/
254 | *.sln.iml
255 |
256 | # CodeRush
257 | .cr/
258 |
259 | # Python Tools for Visual Studio (PTVS)
260 | __pycache__/
261 | *.pyc
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "files.associations": {
3 | "string": "cpp"
4 | }
5 | }
--------------------------------------------------------------------------------
/AssignmentCppCheck.cppcheck:
--------------------------------------------------------------------------------
1 |
2 |
3 | AssignmentCppCheck-cppcheck-build-dir
4 | Unspecified
5 | CppAssignments.sln
6 | false
7 | true
8 | false
9 | 10
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 | constParameter
19 |
20 |
21 |
--------------------------------------------------------------------------------
/Engine/Engine.vcxproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | Win32
7 |
8 |
9 | Release
10 | Win32
11 |
12 |
13 | Debug
14 | x64
15 |
16 |
17 | Release
18 | x64
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 | 15.0
86 | {D32EC244-7D50-4AFE-97D6-21816808F479}
87 | Win32Proj
88 | Engine
89 | 10.0.17763.0
90 |
91 |
92 |
93 | StaticLibrary
94 | true
95 | v141
96 | MultiByte
97 |
98 |
99 | StaticLibrary
100 | false
101 | v141
102 | true
103 | MultiByte
104 |
105 |
106 | StaticLibrary
107 | true
108 | v141
109 | MultiByte
110 |
111 |
112 | StaticLibrary
113 | false
114 | v141
115 | true
116 | MultiByte
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 | true
138 | $(SolutionDir)JobSystem;$(SolutionDir)Exports;$(IncludePath)
139 |
140 |
141 | true
142 | $(SolutionDir)JobSystem;$(SolutionDir)Exports;$(IncludePath)
143 |
144 |
145 | false
146 | $(SolutionDir)JobSystem;$(SolutionDir)Exports;$(IncludePath)
147 |
148 |
149 | false
150 | $(SolutionDir)JobSystem;$(SolutionDir)Exports;$(IncludePath)
151 |
152 |
153 |
154 | NotUsing
155 | Level3
156 | Disabled
157 | true
158 | _DEBUG;_LIB;%(PreprocessorDefinitions);CLASSIC_MAIN
159 | true
160 | Math/pchMath.h
161 |
162 |
163 | Windows
164 | true
165 |
166 |
167 |
168 |
169 | NotUsing
170 | Level3
171 | Disabled
172 | true
173 | WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions);CLASSIC_MAIN
174 | true
175 | Math/pchMath.h
176 |
177 |
178 | Windows
179 | true
180 |
181 |
182 |
183 |
184 | NotUsing
185 | Level3
186 | MaxSpeed
187 | true
188 | true
189 | true
190 | WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions);CLASSIC_MAIN
191 | true
192 | Math/pchMath.h
193 |
194 |
195 | Windows
196 | true
197 | true
198 | true
199 |
200 |
201 |
202 |
203 | NotUsing
204 | Level3
205 | MaxSpeed
206 | true
207 | true
208 | true
209 | NDEBUG;_LIB;%(PreprocessorDefinitions);CLASSIC_MAIN
210 | true
211 | Math/pchMath.h
212 |
213 |
214 | Windows
215 | true
216 | true
217 | true
218 |
219 |
220 |
221 |
222 |
223 |
--------------------------------------------------------------------------------
/Engine/Engine.vcxproj.filters:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF}
6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx
7 |
8 |
9 | {93995380-89BD-4b04-88EB-625FBE52EBFB}
10 | h;hh;hpp;hxx;hm;inl;inc;ipp;xsd
11 |
12 |
13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01}
14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms
15 |
16 |
17 | {401731cb-8649-479f-b29d-26c81aa6ae83}
18 |
19 |
20 | {baa1cc17-1aa6-4114-a4ea-bef45b9888ba}
21 |
22 |
23 | {6655fc5f-ca76-44f6-8cc1-dc9a91ad469e}
24 |
25 |
26 | {a284184a-fa02-4af6-a0ea-50155c336f2c}
27 |
28 |
29 | {0ccd3b9d-fb96-49af-89b5-d9bba84bfb61}
30 |
31 |
32 | {9941a002-288c-4ed6-a21e-89924901b540}
33 |
34 |
35 | {b2812732-c0ae-44c8-b650-1c60a3715597}
36 |
37 |
38 | {46187728-5eaf-43e2-97b3-2493b6c52b40}
39 |
40 |
41 | {d0d2b6da-2530-4b50-b7a0-55e11c8b6c80}
42 |
43 |
44 | {2df2c4d2-8cdb-4afd-9512-ad61f1eb6bf2}
45 |
46 |
47 | {cfe56c9f-1c35-47e3-b83e-5c853b4679d6}
48 |
49 |
50 | {e8c37ceb-cf9f-4421-9bbd-efbeaf68f010}
51 |
52 |
53 | {773000ef-7957-4076-ae22-41996235a762}
54 |
55 |
56 | {706ff25c-9d59-4a1b-98eb-364b95b3041b}
57 |
58 |
59 | {50d06f3a-5623-4453-bb4c-94a5b0f29d0d}
60 |
61 |
62 | {633621b2-1a2d-4594-b951-4f4aff6031e6}
63 |
64 |
65 | {f019dabf-989a-41bf-9c14-f622a17e3675}
66 |
67 |
68 | {c9421643-e2f4-43d4-a560-2e10ecc52ebf}
69 |
70 |
71 | {e66f519e-c8a4-4e23-947d-e2ff517243d9}
72 |
73 |
74 | {4b5b03a2-45c7-43db-a111-88e1b4bfd757}
75 |
76 |
77 | {3cb6d948-4e87-47ba-b4fd-38e809e12433}
78 |
79 |
80 | {29eead44-427f-4d69-abcb-97e50fb484ce}
81 |
82 |
83 |
84 |
85 | Header Files\General
86 |
87 |
88 | Header Files\Math
89 |
90 |
91 | Header Files\Math
92 |
93 |
94 | Header Files\General
95 |
96 |
97 | Header Files\String
98 |
99 |
100 | Header Files\Memory
101 |
102 |
103 | Header Files\Memory
104 |
105 |
106 | Header Files\Memory
107 |
108 |
109 | Header Files\Memory
110 |
111 |
112 | Header Files\General\Components
113 |
114 |
115 | Header Files\General\Components
116 |
117 |
118 | Header Files\General\Components
119 |
120 |
121 | Header Files\Memory\SmartPointer
122 |
123 |
124 | Header Files\Memory\SmartPointer
125 |
126 |
127 | Header Files\Memory\SmartPointer
128 |
129 |
130 | Header Files\General\Components
131 |
132 |
133 | Header Files\Jobs\Console
134 |
135 |
136 | Header Files\Jobs\HashedString
137 |
138 |
139 | Header Files\Jobs\HashedString
140 |
141 |
142 | Header Files\Jobs\JobSystem
143 |
144 |
145 | Header Files\Jobs\JobSystem
146 |
147 |
148 | Header Files\Jobs\JobSystem
149 |
150 |
151 | Header Files\Jobs\JobSystem
152 |
153 |
154 | Header Files\Jobs\JobSystem
155 |
156 |
157 | Header Files\Jobs\JobSystem
158 |
159 |
160 | Header Files\Jobs\Synchronization
161 |
162 |
163 | Header Files\Jobs\Synchronization
164 |
165 |
166 | Header Files\Jobs\Synchronization
167 |
168 |
169 | Header Files\Jobs\Synchronization
170 |
171 |
172 | Header Files\Jobs\Synchronization
173 |
174 |
175 | Header Files\Jobs\Synchronization
176 |
177 |
178 | Header Files\Math
179 |
180 |
181 | Header Files\General\Components
182 |
183 |
184 | Header Files\Math
185 |
186 |
187 | Header Files\Math
188 |
189 |
190 | Header Files\Math
191 |
192 |
193 | Header Files\Render
194 |
195 |
196 | Header Files\Math
197 |
198 |
199 | Header Files\Memory\SmartPointer
200 |
201 |
202 | Header Files\General\Systems
203 |
204 |
205 | Header Files\General\Systems
206 |
207 |
208 |
209 |
210 | Source Files\General
211 |
212 |
213 | Source Files\General
214 |
215 |
216 | Source Files\String
217 |
218 |
219 | Source Files\Memory
220 |
221 |
222 | Source Files\Memory
223 |
224 |
225 | Source Files\Memory
226 |
227 |
228 | Source Files\Memory
229 |
230 |
231 | Source Files\Jobs\Console
232 |
233 |
234 | Source Files\Jobs\HashedString
235 |
236 |
237 | Source Files\Jobs\JobSystem
238 |
239 |
240 | Source Files\Jobs\JobSystem
241 |
242 |
243 | Source Files\Jobs\JobSystem
244 |
245 |
246 | Source Files\Jobs\JobSystem
247 |
248 |
249 | Source Files\Jobs\Synchronization
250 |
251 |
252 | Source Files\Jobs\Synchronization
253 |
254 |
255 | Source Files\Jobs\Synchronization
256 |
257 |
258 | Source Files\General\Systems
259 |
260 |
261 | Source Files\General\Systems
262 |
263 |
264 |
--------------------------------------------------------------------------------
/Engine/General/Actor.cpp:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "Actor.h"
4 | #include "../Math/Math.h"
5 | #include "Components/IActorComponent.h"
6 | #include "World.h"
7 | #include "Components/Physics.h"
8 |
9 |
10 |
11 |
12 | ////////////////////////////////////////////////////////////////////// Constructors and Destructors
13 | Actor::Actor(World* world, const std::string name, Vector2 position)
14 | {
15 | this->name = name;
16 | this->position = position;
17 | this->world_ = world;
18 | }
19 | Actor::~Actor()
20 | {
21 | for (IActorComponent* component : mComponents)
22 | {
23 | delete component;
24 | }
25 | }
26 | Actor &Actor::operator = (const Actor &other)
27 | {
28 | this->name = other.name;
29 | this->position = other.position;
30 | this->world_ = other.world_;
31 | return *this;
32 | }
33 | ////////////////////////////////////////////////////////////////////// Constructors and Destructors
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 | ////////////////////////////////////////////////////////////////////// BeginPlay & Tick
46 | void Actor::BeginPlay()
47 | {
48 | const size_t nComponents = mComponents.size();
49 | for (size_t i = 0; i < nComponents; i++)
50 | {
51 | if (mComponents[i])
52 | {
53 | mComponents[i]->BeginPlay();
54 | }
55 | }
56 | }
57 | void Actor::Tick(const float DeltaSeconds)
58 | {
59 | const size_t nComponents = mComponents.size();
60 | for (size_t i = 0; i < nComponents; i++)
61 | {
62 | if (mComponents[i])
63 | {
64 | mComponents[i]->Tick(DeltaSeconds);
65 | }
66 | }
67 | }
68 | ////////////////////////////////////////////////////////////////////// BeginPlay & Tick
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 | ////////////////////////////////////////////////////////////////////// Components
81 | void Actor::AddComponent(IActorComponent* actorComponent)
82 | {
83 | if (actorComponent)
84 | mComponents.push_back(actorComponent);
85 | }
86 | ////////////////////////////////////////////////////////////////////// Components
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 | ////////////////////////////////////////////////////////////////////// Components
102 | void Actor::OnCollisionStay(SmartPtr & otherActor)
103 | {
104 | if (otherActor == world_->GetPlayerActor() || world_->GetPlayerActor() == this)
105 | {
106 | PhysicsComponent * otherComp = otherActor->GetComponent();
107 | PhysicsComponent * myComp = GetComponent();
108 |
109 | if (otherComp && myComp)
110 | {
111 | myComp->AddForce((position - otherActor->position).getNormalized() * 10.0f, true);
112 | }
113 | }
114 | }
115 |
116 | void Actor::OnHit(SmartPtr & otherActor)
117 | {
118 |
119 | }
120 | ////////////////////////////////////////////////////////////////////// Components
--------------------------------------------------------------------------------
/Engine/General/Actor.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include "../Math/pchMath.h"
5 | #include
6 | #include "../Memory/SmartPointer/SmartPtr.h"
7 |
8 |
9 | namespace GLib {
10 | namespace Sprites {
11 | struct Sprite;
12 | }
13 | }
14 |
15 | class IActorComponent;
16 | class World;
17 |
18 | enum EMobility
19 | {
20 | Static,
21 | Moveable
22 | };
23 |
24 | class Actor {
25 | public:
26 | Actor(World* world, const std::string name, Vector2 position);
27 | virtual ~Actor();
28 | Actor &operator = (const Actor &other);
29 |
30 |
31 | virtual void BeginPlay();
32 | virtual void Tick(const float DeltaSeconds);
33 |
34 |
35 | void AddComponent(IActorComponent* actorComponent);
36 | template T* GetComponent()
37 | {
38 | for (auto& component : mComponents)
39 | {
40 | T* ptr = dynamic_cast(component);
41 | if (ptr != nullptr)
42 | return ptr;
43 | }
44 | return nullptr;
45 | }
46 |
47 | virtual void OnHit(SmartPtr & otherActor);
48 | virtual void OnCollisionStay(SmartPtr & otherActor);
49 |
50 |
51 |
52 |
53 | inline Vector2 GetVelocity() const { return velocity; }
54 | inline void SetVelocity(const Vector2 i_velocity) { velocity = i_velocity; }
55 |
56 | inline EMobility GetMobility() const { return mobility; }
57 | inline void SetMobility(const EMobility i_mobility) { mobility = i_mobility; }
58 |
59 |
60 |
61 |
62 | public:
63 | std::string name;
64 | GLib::Sprites::Sprite * sprite;
65 | Vector2 position = Vector2{ 0,0 };
66 | float zRotation;
67 | World * world_;
68 | bool bDebugTrigger = false;
69 | bool bDestroyedOnHit = false;
70 |
71 | private:
72 | std::vector mComponents;
73 | EMobility mobility = Moveable;
74 | Vector2 velocity;
75 | };
76 |
77 |
78 |
--------------------------------------------------------------------------------
/Engine/General/Components/BoxCollider.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "IActorComponent.h"
4 | #include "../Actor.h"
5 | #include "../../Math/Vector3.h"
6 |
7 | struct AABB
8 | {
9 | Vector3 Center;
10 | Vector3 Extents;
11 |
12 | AABB(const Vector3 i_center, const Vector3 i_extents) : Center(i_center), Extents(i_extents)
13 | {}
14 | };
15 |
16 | class BoxColliderComponent : public IActorComponent
17 | {
18 | public:
19 | BoxColliderComponent(SmartPtr & actorRef, const Vector3 i_center, const Vector3 i_extents) : IActorComponent(actorRef), aabb(i_center, i_extents) {}
20 |
21 | void SetBounds(const Vector3 i_center, const Vector3 i_extents)
22 | {
23 | aabb.Center = i_center;
24 | aabb.Extents = i_extents;
25 | }
26 |
27 | AABB getBounds() const
28 | {
29 | return aabb;
30 | }
31 |
32 | private:
33 | AABB aabb;
34 | };
35 |
--------------------------------------------------------------------------------
/Engine/General/Components/CircleCollider.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "IActorComponent.h"
4 | #include "../Actor.h"
5 |
6 | class CircleColliderComponent : public IActorComponent
7 | {
8 | public:
9 | CircleColliderComponent(SmartPtr & actorRef, float r) : IActorComponent(actorRef), radius(r) {}
10 |
11 | void SetRadius(float r)
12 | {
13 | radius = r;
14 | }
15 |
16 | float GetRadius() const
17 | {
18 | return radius;
19 | }
20 |
21 | private:
22 | float radius = 1.f;
23 | };
24 |
--------------------------------------------------------------------------------
/Engine/General/Components/Follow.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "../Actor.h"
4 | #include "IActorComponent.h"
5 | #include "../World.h"
6 | #include "Physics.h"
7 |
8 |
9 | class FollowComponent : public IActorComponent
10 | {
11 | public:
12 | // Fixed Arguments
13 | FollowComponent(SmartPtr & actorRef, WeakPtr i_targetActorRef, const bool i_bShouldFollow = true, const float i_followForce = 1.0f)
14 | : IActorComponent(actorRef), targetActorRef(i_targetActorRef), bShouldFollow(i_bShouldFollow), followForce(i_followForce)
15 | {}
16 |
17 | // Variable Arguments
18 | FollowComponent(SmartPtr & actorRef) : IActorComponent(actorRef)
19 | {}
20 |
21 | void BeginPlay() override
22 | {
23 | SmartPtr actor;
24 | this->actor.acquire(actor);
25 |
26 | physicsComp = actor->GetComponent();
27 | }
28 |
29 | void Tick(const float DeltaSeconds) override
30 | {
31 | SmartPtr actor;
32 | this->actor.acquire(actor);
33 |
34 | SmartPtr targetActor;
35 | this->targetActorRef.acquire(targetActor);
36 |
37 |
38 | if (!physicsComp)
39 | physicsComp = actor->GetComponent();
40 |
41 |
42 | if (targetActor && physicsComp && bShouldFollow)
43 | {
44 | const Vector2 direction = (targetActor->position - actor->position).getNormalized();
45 | physicsComp->AddForce(direction * followForce);
46 | }
47 | }
48 |
49 | void SetFollow(WeakPtr & i_targetActorRef, const bool i_bShouldFollow)
50 | {
51 | targetActorRef = i_targetActorRef;
52 | bShouldFollow = i_bShouldFollow;
53 | }
54 |
55 | public:
56 | WeakPtr targetActorRef;
57 | bool bShouldFollow = false;
58 | float followForce = 1.0f;
59 |
60 | private:
61 | PhysicsComponent * physicsComp = nullptr;
62 | };
63 |
--------------------------------------------------------------------------------
/Engine/General/Components/IActorComponent.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "../Actor.h"
4 | #include "../../Memory/SmartPointer/WeakPtr.h"
5 |
6 | class IActorComponent
7 | {
8 | protected:
9 | WeakPtr actor;
10 |
11 | public:
12 | IActorComponent(SmartPtr & actorRef) : actor(actorRef) {};
13 | virtual ~IActorComponent() = default;
14 | virtual void BeginPlay() {}
15 | virtual void Tick(const float DeltaSeconds) {}
16 | };
--------------------------------------------------------------------------------
/Engine/General/Components/Physics.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "../Actor.h"
4 | #include "IActorComponent.h"
5 | #include "../World.h"
6 | #include
7 |
8 |
9 | class PhysicsComponent : public IActorComponent
10 | {
11 | public:
12 | // Fixed Arguments
13 | PhysicsComponent(SmartPtr & actorRef, const float i_mass = 1.f, const float i_gravityScale = 1.f, const float i_linearDrag = 0.0001f)
14 | : IActorComponent(actorRef), mass(i_mass <= 0.f ? 0.0001f : i_mass), gravityScale(i_gravityScale), linearDrag(i_linearDrag)
15 | {}
16 |
17 | // Variable Arguments
18 | PhysicsComponent(SmartPtr & actorRef, const size_t n ...) : IActorComponent(actorRef)
19 | {
20 | if (n < 3)
21 | {
22 | printf("NOT ENOUGH PARAMETERS FOUND! | %s @ %d\n", __FILE__, __LINE__);
23 | }
24 | else
25 | {
26 | va_list varList;
27 | va_start(varList, n);
28 | const float i_mass = static_cast(va_arg(varList, double));
29 | mass = i_mass < 0.0001f ? 0.0001f : i_mass;
30 | gravityScale = static_cast(va_arg(varList, double));
31 | linearDrag = static_cast(va_arg(varList, double));
32 | va_end(varList);
33 | }
34 | }
35 |
36 | void Tick(const float DeltaSeconds) override
37 | {
38 | if (DeltaSeconds > 0.5f) return;
39 | SmartPtr actor;
40 | this->actor.acquire(actor);
41 | if (!actor)
42 | {
43 | netForce = Vector2::Zero();
44 | netImpulse = Vector2::Zero();
45 | }
46 |
47 | AddForce(Vector2::Down() * gravityScale);
48 |
49 | if (linearDrag < 0.0f) linearDrag = 0.0f;
50 | const Vector2 currentVelocity = actor->GetVelocity();
51 | AddForce(currentVelocity * currentVelocity.getMagnitude() * -1 * linearDrag * DeltaSeconds);
52 |
53 | const float deltaSeconds = actor->world_->GetDeltaSeconds();
54 | const Vector2 accelFromForce = netForce * 1000.f / mass;
55 | const Vector2 accelFromImpulse = netImpulse / mass;
56 | const Vector2 newVelocity = currentVelocity + (accelFromForce * deltaSeconds) + accelFromImpulse;
57 |
58 | const Vector2 displacement = (currentVelocity + newVelocity) / 2.f * deltaSeconds;
59 | if (!xConstraint)
60 | actor->position.x += displacement.x;
61 | if (!yConstraint)
62 | actor->position.y += displacement.y;
63 |
64 | actor->SetVelocity(newVelocity);
65 | netForce = Vector2::Zero();
66 | netImpulse = Vector2::Zero();
67 | }
68 |
69 | void AddForce(const Vector2 input, const bool isImpulse = false)
70 | {
71 | isImpulse ? netImpulse += input : netForce += input;
72 | }
73 |
74 | void SetConstraints(const bool x, const bool y)
75 | {
76 | xConstraint = x;
77 | yConstraint = y;
78 | }
79 |
80 |
81 |
82 | private:
83 | // Config
84 | float mass = 1.f;
85 | float gravityScale = 1.f;
86 | float linearDrag = 0.0001f;
87 |
88 | bool xConstraint = false;
89 | bool yConstraint = false;
90 |
91 | // Intermediates
92 | Vector2 netForce;
93 | Vector2 netImpulse;
94 | };
95 |
--------------------------------------------------------------------------------
/Engine/General/Systems/CollisionSystem.cpp:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "CollisionSystem.h"
4 | #include "../Components/BoxCollider.h"
5 | #include "../Components/Physics.h"
6 | #include "../Actor.h"
7 |
8 |
9 | CollisionSystem::CollisionSystem(World * _world)
10 | {
11 | this->world = _world;
12 | }
13 |
14 | void CollisionSystem::operator()(int milliseconds)
15 | {
16 | while (!world->GetIsGameOver())
17 | {
18 | if (world->GetGameTime() < 1.0f) continue;
19 | //RunCheck();
20 | }
21 | }
22 |
23 | void CollisionSystem::Run()
24 | {
25 | // -------------------------------------------------- DETECTION
26 | collisionDataArray.clear();
27 |
28 | if (!world->GetIsGamePaused())
29 | {
30 | std::vector> & tempActors = world->GetAllWeakActorRefs();
31 | //world->CurrentActorsMutex.lock();
32 | /*for (auto actor : tempActors)
33 | {
34 | if (!actor)
35 | printf("Viper");
36 |
37 | SmartPtr smartRef;
38 | actor.acquire(smartRef);
39 | actor.acquire(smartRef);
40 | if (actor.acquire(smartRef))
41 | printf("Viper");
42 | if (!smartRef)
43 | printf("Viper");
44 | }*/
45 | //world->CurrentActorsMutex.unlock();
46 | //return; // TESTING
47 | //world->CurrentActorsMutex.lock();
48 | const float DeltaSeconds = world->GetDeltaSeconds();
49 | std::vector> & actors = world->GetAllWeakActorRefs();
50 | const size_t actorsLen = actors.size();
51 | /*if (actorsLen < 1)
52 | continue;*/
53 |
54 | for (unsigned int i = 0; i < actorsLen - 1; i++)
55 | {
56 | SmartPtr myActor;
57 | actors[i].acquire(myActor);
58 | if (!myActor) continue;
59 | const BoxColliderComponent * myCollider = myActor->GetComponent();
60 | if (!myCollider) continue;
61 |
62 | for (int j = i + 1; j < actorsLen; j++)
63 | {
64 | SmartPtr otherActor;
65 | actors[j].acquire(otherActor);
66 | if (!otherActor || otherActor == myActor) continue;
67 |
68 | const BoxColliderComponent * otherCollider = otherActor->GetComponent();
69 | if (!otherCollider) continue;
70 |
71 |
72 |
73 |
74 | // COLLISION LOGIC
75 | float tMyEnter = 9999;
76 | float tOtherEnter = 9999;
77 | float tMyExit = 9999;
78 | float tOtherExit = 9999;
79 |
80 | const AABB myBounds = myCollider->getBounds();
81 | const AABB otherBounds = otherCollider->getBounds();
82 |
83 |
84 | const Matrix4 mOtherRot = Matrix4::ZRotation(otherActor->zRotation);
85 | const Matrix4 mOtherTrans = Matrix4::Translation(otherActor->position);
86 | const Matrix4 mOtherToWorld = mOtherTrans * mOtherRot;
87 | const Matrix4 mWorldToOther = mOtherToWorld.inverse();
88 |
89 | const Matrix4 mMyRot = Matrix4::ZRotation(myActor->zRotation);
90 | const Matrix4 mMyTrans = Matrix4::Translation(myActor->position);
91 | const Matrix4 mMyToWorld = mMyTrans * mMyRot;
92 | const Matrix4 mWorldToMy = mMyToWorld.inverse();
93 |
94 |
95 | const Matrix4 mOtherToMy = mWorldToMy * mOtherToWorld;
96 | const Matrix4 mMyToOther = mWorldToOther * mMyToWorld;
97 |
98 | const Vector4 myVelocity = myActor->GetVelocity();
99 | const Vector4 otherVelocity = otherActor->GetVelocity();
100 | const Vector4 myWorldRelativeVelocity = myVelocity - otherVelocity;
101 | const Vector4 otherWorldRelativeVelocity = myWorldRelativeVelocity.getInverse();
102 |
103 |
104 |
105 |
106 | //////////////////////////////////////////////////////////////////////////////////////////////////// MY TEST
107 | const Vector4 otherCenterInMy = mOtherToMy * Vector4(otherBounds.Center, 1.f);
108 |
109 | const Vector4 otherExtentsXInMy = mOtherToMy * Vector4(otherBounds.Extents.x / 2, 0, 0, 0);
110 | const Vector4 otherExtentsYInMy = mOtherToMy * Vector4(0, otherBounds.Extents.y / 2, 0, 0);
111 |
112 | const float otherProjectionXOntoMyEnd = fabs(otherExtentsXInMy.x) + fabs(otherExtentsYInMy.x);
113 | const float otherProjectionYOntoMyEnd = fabs(otherExtentsXInMy.y) + fabs(otherExtentsYInMy.y);
114 |
115 |
116 | // Velocity Based Detection
117 | const Vector4 otherLocalRelativeVelocity = mMyRot * otherWorldRelativeVelocity;
118 |
119 | Vector4 myHitNormal;
120 | float myNormalTime = 0.f;
121 |
122 |
123 | float tMyH0 = -1;
124 | float tMyH1 = -1;
125 | bool bMyHSkip = false;
126 | if (Math::IsNearlyZero(otherLocalRelativeVelocity.x))
127 | bMyHSkip = true;
128 | else
129 | {
130 | const float tR = ((myBounds.Center.x - (myBounds.Extents.x / 2)) - (otherCenterInMy.x + otherProjectionXOntoMyEnd)) / otherLocalRelativeVelocity.x;
131 | const float tL = ((myBounds.Center.x + (myBounds.Extents.x / 2)) - (otherCenterInMy.x - otherProjectionXOntoMyEnd)) / otherLocalRelativeVelocity.x;
132 | if (tR < tL)
133 | {
134 | myHitNormal = Vector2::Right();
135 | myNormalTime = tR;
136 | }
137 | else
138 | {
139 | myHitNormal = Vector2::Left();
140 | myNormalTime = tR;
141 | }
142 | tMyH0 = min(tR, tL);
143 | tMyH1 = max(tR, tL);
144 | }
145 |
146 |
147 | float tMyV0 = -1;
148 | float tMyV1 = -1;
149 | bool bMyVSkip = false;
150 | if (Math::IsNearlyZero(otherLocalRelativeVelocity.y))
151 | bMyVSkip = true;
152 | else
153 | {
154 | const float tU = ((myBounds.Center.y - (myBounds.Extents.y / 2)) - (otherCenterInMy.y + otherProjectionYOntoMyEnd)) / otherLocalRelativeVelocity.y;
155 | const float tD = ((myBounds.Center.y + (myBounds.Extents.y / 2)) - (otherCenterInMy.y - otherProjectionYOntoMyEnd)) / otherLocalRelativeVelocity.y;
156 | if (tU < tD && tU < myNormalTime)
157 | {
158 | myHitNormal = Vector2::Up();
159 | myNormalTime = tU;
160 | }
161 | if (tD < tU && tD < myNormalTime)
162 | {
163 | myHitNormal = Vector2::Down();
164 | myNormalTime = tD;
165 | }
166 | tMyV0 = min(tU, tD);
167 | tMyV1 = max(tU, tD);
168 | }
169 |
170 |
171 |
172 |
173 | float tMyInMax = -1;
174 | float tMyOutMin = -1;
175 | int tMyModeIndicator = -1;
176 | bool bMySkip = false;
177 |
178 | if (!bMyHSkip && !bMyVSkip)
179 | {
180 | tMyInMax = max(tMyH0, tMyV0);
181 | tMyOutMin = min(tMyH1, tMyV1);
182 | if (tMyInMax < tMyOutMin)
183 | {
184 | tMyEnter = tMyInMax;
185 | tMyExit = tMyOutMin;
186 | }
187 | tMyModeIndicator = 0;
188 | }
189 | if (!bMyHSkip/* && bH*/ && bMyVSkip)
190 | {
191 | tMyInMax = tMyH0;
192 | tMyOutMin = tMyH1;
193 | tMyEnter = tMyInMax;
194 | tMyExit = tMyOutMin;
195 | tMyModeIndicator = 1;
196 | }
197 | if (bMyHSkip && !bMyVSkip/* && bV*/)
198 | {
199 | tMyInMax = tMyV0;
200 | tMyOutMin = tMyV1;
201 | tMyEnter = tMyInMax;
202 | tMyExit = tMyOutMin;
203 | tMyModeIndicator = 2;
204 | }
205 | if (bMyHSkip && bMyVSkip)
206 | {
207 | bMySkip = true;
208 | }
209 |
210 | //myHitNormal = mMyToWorld * Vector4(myHitNormal);
211 | //////////////////////////////////////////////////////////////////////////////////////////////////// MY TEST
212 |
213 |
214 |
215 |
216 |
217 | //////////////////////////////////////////////////////////////////////////////////////////////////// OTHER TEST
218 | const Vector4 myCenterInOther = mMyToOther * Vector4(myBounds.Center, 1.f);
219 |
220 | const Vector4 myExtentsXInOther = mMyToOther * Vector4(myBounds.Extents.x / 2, 0, 0, 0);
221 | const Vector4 myExtentsYInOther = mMyToOther * Vector4(0, myBounds.Extents.y / 2, 0, 0);
222 |
223 | const float myProjectionXOntoOtherEnd = fabs(myExtentsXInOther.x) + fabs(myExtentsYInOther.x);
224 | const float myProjectionYOntoOtherEnd = fabs(myExtentsXInOther.y) + fabs(myExtentsYInOther.y);
225 |
226 |
227 | // Velocity Based Detection
228 | const Vector4 myLocalRelativeVelocity = mOtherRot * myWorldRelativeVelocity;
229 |
230 | float tOtherH0 = -1;
231 | float tOtherH1 = -1;
232 | bool bOtherHSkip = false;
233 | if (Math::IsNearlyZero(myLocalRelativeVelocity.x))
234 | bOtherHSkip = true;
235 | else
236 | {
237 | const float tR = ((otherBounds.Center.x - (otherBounds.Extents.x / 2)) - (myCenterInOther.x + myProjectionXOntoOtherEnd)) / myLocalRelativeVelocity.x;
238 | const float tL = ((otherBounds.Center.x + (otherBounds.Extents.x / 2)) - (myCenterInOther.x - myProjectionXOntoOtherEnd)) / myLocalRelativeVelocity.x;
239 | tOtherH0 = min(tR, tL);
240 | tOtherH1 = max(tR, tL);
241 | }
242 |
243 |
244 | float tOtherV0 = -1;
245 | float tOtherV1 = -1;
246 | bool bOtherVSkip = false;
247 | if (Math::IsNearlyZero(myLocalRelativeVelocity.y))
248 | bOtherVSkip = true;
249 | else
250 | {
251 | const float tU = ((otherBounds.Center.y - (otherBounds.Extents.y / 2)) - (myCenterInOther.y + myProjectionYOntoOtherEnd)) / myLocalRelativeVelocity.y;
252 | const float tD = ((otherBounds.Center.y + (otherBounds.Extents.y / 2)) - (myCenterInOther.y - myProjectionYOntoOtherEnd)) / myLocalRelativeVelocity.y;
253 | tOtherV0 = min(tU, tD);
254 | tOtherV1 = max(tU, tD);
255 | }
256 |
257 |
258 |
259 |
260 | float tOtherInMax = -1;
261 | float tOtherOutMin = -1;
262 | int tOtherModeIndicator = -1;
263 | bool bOtherSkip = false;
264 |
265 | if (!bOtherHSkip && !bOtherVSkip)
266 | {
267 | tOtherInMax = max(tOtherH0, tOtherV0);
268 | tOtherOutMin = min(tOtherH1, tOtherV1);
269 | if (tOtherInMax < tOtherOutMin)
270 | {
271 | tOtherEnter = tOtherInMax;
272 | tOtherExit = tOtherOutMin;
273 | }
274 | tOtherModeIndicator = 0;
275 | }
276 | if (!bOtherHSkip && bOtherVSkip)
277 | {
278 | tOtherInMax = tOtherH0;
279 | tOtherOutMin = tOtherH1;
280 | tOtherEnter = tOtherInMax;
281 | tOtherExit = tOtherOutMin;
282 | tOtherModeIndicator = 1;
283 | }
284 | if (bOtherHSkip && !bOtherVSkip)
285 | {
286 | tOtherInMax = tOtherV0;
287 | tOtherOutMin = tOtherV1;
288 | tOtherEnter = tOtherInMax;
289 | tOtherExit = tOtherOutMin;
290 | tOtherModeIndicator = 2;
291 | }
292 | if (bOtherHSkip && bOtherVSkip)
293 | {
294 | bOtherSkip = true;
295 | }
296 | //////////////////////////////////////////////////////////////////////////////////////////////////// OTHER TEST
297 |
298 |
299 |
300 | if (bMySkip && bOtherSkip)
301 | continue;
302 |
303 | if (myActor->bDebugTrigger)
304 | myActor->bDebugTrigger = false;
305 |
306 |
307 | // FINALIZE
308 | const float tFinalEnter = max(tMyEnter, tOtherEnter);
309 | const float tFinalExit = min(tMyExit, tOtherExit);
310 | if (tMyEnter < 0 && tMyExit > 0 && tOtherEnter < 0 && tOtherExit > 0)
311 | {
312 | if (myActor->GetMobility() == EMobility::Moveable) myActor->OnCollisionStay(otherActor);
313 | if (otherActor->GetMobility() == EMobility::Moveable) otherActor->OnCollisionStay(myActor);
314 |
315 | if (myActor->bDestroyedOnHit) world->DeleteActor(myActor);
316 | if (otherActor->bDestroyedOnHit) world->DeleteActor(otherActor);
317 | }
318 |
319 | if (tMyEnter > 0 && tMyEnter < DeltaSeconds && tMyExit > 0 && tOtherEnter > 0 && tOtherEnter < DeltaSeconds && tOtherExit > 0)
320 | {
321 | collisionDataArray.push_back(CollisionData{ myActor, otherActor, tFinalEnter });
322 | }
323 | }
324 | }
325 |
326 |
327 |
328 |
329 |
330 |
331 |
332 |
333 | // -------------------------------------------------- RESOLUTION
334 | float tLeftInFrame = DeltaSeconds;
335 | while (!collisionDataArray.empty() && tLeftInFrame > 0)
336 | {
337 | unsigned int dataIndex = 0;
338 | for (unsigned int i = 1; i < collisionDataArray.size(); i++)
339 | if (collisionDataArray[i].enterTime < collisionDataArray[dataIndex].enterTime)
340 | dataIndex = i;
341 |
342 |
343 | tLeftInFrame -= collisionDataArray[dataIndex].enterTime;
344 | for (auto weakRef : actors)
345 | {
346 | SmartPtr actor;
347 | weakRef.acquire(actor);
348 | if (actor->GetMobility() == EMobility::Moveable) actor->position += actor->GetVelocity() * collisionDataArray[dataIndex].enterTime;
349 | }
350 |
351 |
352 | SmartPtr actor1 = collisionDataArray[dataIndex].actor1;
353 | SmartPtr actor2 = collisionDataArray[dataIndex].actor2;
354 |
355 | const float actor1Speed = actor1->GetVelocity().getMagnitude();
356 | const float actor2Speed = actor2->GetVelocity().getMagnitude();
357 | if (actor1->GetMobility() == EMobility::Moveable) actor1->SetVelocity((actor1->position - actor2->position).getNormalized() * ((actor2Speed + actor1Speed) / 2));
358 | if (actor2->GetMobility() == EMobility::Moveable) actor2->SetVelocity((actor2->position - actor1->position).getNormalized() * ((actor2Speed + actor1Speed) / 2));
359 |
360 | if (actor1->bDestroyedOnHit) world->DeleteActor(actor1);
361 | if (actor2->bDestroyedOnHit) world->DeleteActor(actor2);
362 |
363 | collisionDataArray.erase(collisionDataArray.begin() + dataIndex);
364 | }
365 | //world->CurrentActorsMutex.unlock();
366 | }
367 | }
--------------------------------------------------------------------------------
/Engine/General/Systems/CollisionSystem.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "../World.h"
4 |
5 | struct CollisionData
6 | {
7 | SmartPtr actor1;
8 | SmartPtr actor2;
9 | float enterTime;
10 |
11 | CollisionData & operator = (const CollisionData & otherCollisionData)
12 | {
13 | if (this == &otherCollisionData)
14 | return *this;
15 | actor1 = otherCollisionData.actor1;
16 | actor2 = otherCollisionData.actor2;
17 | enterTime = otherCollisionData.enterTime;
18 | return *this;
19 | }
20 | };
21 |
22 |
23 |
24 | class CollisionSystem
25 | {
26 | World * world;
27 | std::vector collisionDataArray;
28 |
29 | public:
30 | CollisionSystem(World * _world);
31 | void operator()(int milliseconds);
32 |
33 | void Run();
34 | };
--------------------------------------------------------------------------------
/Engine/General/Systems/Input.cpp:
--------------------------------------------------------------------------------
1 | #include "Input.h"
2 |
3 | std::vector * Input::keysDown;
4 |
5 | Input::Input()
6 | {
7 | keysDown = new std::vector();
8 | }
9 |
10 | Input::~Input()
11 | {
12 | delete keysDown;
13 | }
14 |
15 |
16 | void Input::Keyboard_KeyPress(unsigned int i_VKeyID, bool bWentDown)
17 | {
18 | if (bWentDown)
19 | keysDown->push_back(i_VKeyID);
20 | else
21 | {
22 | for (unsigned int i = 0; i < keysDown->size(); i++)
23 | {
24 | if ((*keysDown)[i] == i_VKeyID)
25 | {
26 | keysDown->erase(keysDown->begin() + i);
27 | }
28 | }
29 | }
30 | }
31 |
32 | bool Input::Keyboard_IsKeyDown(unsigned i_VKeyID)
33 | {
34 | for (unsigned int key : *keysDown)
35 | {
36 | if (key == i_VKeyID)
37 | return true;
38 | }
39 | return false;
40 | }
--------------------------------------------------------------------------------
/Engine/General/Systems/Input.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 |
6 | class Input
7 | {
8 | static std::vector * keysDown;
9 |
10 | public:
11 | Input();
12 | ~Input();
13 | static bool Keyboard_IsKeyDown(unsigned int i_VKeyID);
14 | static void Keyboard_KeyPress(unsigned int i_VKeyID, bool bWentDown);
15 | };
16 |
--------------------------------------------------------------------------------
/Engine/General/World.cpp:
--------------------------------------------------------------------------------
1 | #include "World.h"
2 | #include "Windows.h"
3 | #include "../Render/GLibHelper.h"
4 | #include "GLib/GLib.h"
5 | #include
6 | #include "Components/BoxCollider.h"
7 | #include "Systems/Input.h"
8 | #include "Components/Physics.h"
9 | #include "Components/Follow.h"
10 | #include "Systems/CollisionSystem.h"
11 | using json = nlohmann::json;
12 |
13 |
14 | //////////////////////////////////////////////////////////////////////////////////////////////////// INIT/EXIT
15 | World::World(HINSTANCE i_hinstance, int i_cmdShow)
16 | {
17 | collisionSystem = new CollisionSystem(this);
18 | inputSystem = new Input();
19 |
20 | const bool bSuccess = GLib::Initialize(i_hinstance, i_cmdShow, "Viper Engine Output", -1, 800, 600);
21 | assert(bSuccess);
22 |
23 | GLib::SetKeyStateChangeCallback(Input::Keyboard_KeyPress);
24 | }
25 |
26 |
27 | World::~World()
28 | {
29 | delete collisionSystem;
30 | delete inputSystem;
31 | }
32 | //////////////////////////////////////////////////////////////////////////////////////////////////// INIT/EXIT
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 | //////////////////////////////////////////////////////////////////////////////////////////////////// ACTORS
45 | std::vector> World::GetAllActors() const
46 | {
47 | return actors;
48 | }
49 | void World::SpawnActor(SmartPtr & ref, const std::string name, const Vector2 spawn_location)
50 | {
51 | CurrentActorsMutex.lock();
52 | const SmartPtr actor(new Actor(this, name, spawn_location));
53 | ref = actor;
54 | actors.push_back(actor);
55 | UpdateWeakActorRefs();
56 | CurrentActorsMutex.unlock();
57 | }
58 |
59 | void World::SpawnQueuedActors()
60 | {
61 | if (!actorsToAdd.empty())
62 | {
63 | CurrentActorsMutex.lock();
64 | for (SmartPtr queuedActor : actorsToAdd)
65 | {
66 | actors.push_back(queuedActor);
67 | }
68 | actorsToAdd.clear();
69 | CurrentActorsMutex.unlock();
70 | }
71 | }
72 |
73 |
74 | void World::QueueNewActor(SmartPtr& ref, const std::string name, Vector2 spawn_location)
75 | {
76 | NewActorsMutex.lock();
77 | const SmartPtr actor(new Actor(this, name, spawn_location));
78 | ref = actor;
79 | actorsToAdd.push_back(actor);
80 | NewActorsMutex.unlock();
81 | }
82 |
83 |
84 |
85 |
86 |
87 |
88 | void World::LoadScene(const std::string filePath)
89 | {
90 | std::ifstream file(filePath, std::ios_base::in);
91 | std::string fileData(
92 | (std::istreambuf_iterator(file)),
93 | std::istreambuf_iterator()
94 | );
95 | auto editorState = json::parse(fileData);
96 |
97 | for (const json & actorData : editorState["actors"])
98 | {
99 | SmartPtr ref;
100 | SpawnActorFromJson(actorData, ref);
101 | }
102 | }
103 |
104 | void World::SpawnPrefab(SmartPtr & ref, const std::string filePath)
105 | {
106 | std::ifstream file(filePath, std::ios_base::in);
107 | std::string fileData(
108 | (std::istreambuf_iterator(file)),
109 | std::istreambuf_iterator()
110 | );
111 | auto actorData = json::parse(fileData);
112 | SpawnActorFromJson(actorData, ref);
113 | }
114 |
115 | void World::SpawnActorFromJson(const nlohmann::json & actorData, SmartPtr & ref)
116 | {
117 | // Set Position
118 | Vector2 spawnPos = Vector2::Zero();
119 | float spawnRot = 0.0f;
120 | Vector2 spawnVelocity = Vector2::Zero();
121 | if (actorData.contains("initial-position"))
122 | {
123 | const json & posData = actorData["initial-position"];
124 | spawnPos = { posData[0], posData[1] };
125 | }
126 |
127 | if (actorData.contains("initial-rotation"))
128 | {
129 | const json & posData = actorData["initial-rotation"];
130 | spawnRot = posData.get();
131 | }
132 |
133 | if (actorData.contains("initial-velocity"))
134 | {
135 | const json & velData = actorData["initial-velocity"];
136 | spawnVelocity = { velData[0], velData[1] };
137 | }
138 |
139 | // Set Name
140 | std::string actorName;
141 | if (actorData.contains("name"))
142 | {
143 | const json jName = actorData["name"];
144 | actorName = jName.get();
145 | }
146 |
147 | ////////// Spawn Actor
148 | SpawnActor(ref, actorName, spawnPos);
149 | ref->zRotation = spawnRot * 3.14159265359f / 180.f;
150 | ref->SetVelocity(spawnVelocity);
151 |
152 | if (actorData.contains("mobility") && actorData["mobility"].get() == "static")
153 | ref->SetMobility(EMobility::Static);
154 |
155 | // Set Sprite
156 | if (actorData.contains("sprite-path"))
157 | {
158 | auto spritePath = actorData["sprite-path"].get();
159 | ref->sprite = GLibHelper::CreateSprite(spritePath.data());
160 | }
161 |
162 | // Set Components
163 | for (const json & comp : actorData["components"])
164 | {
165 | auto componentType = comp["type"].get();
166 | const size_t nParams = comp.size();
167 |
168 | // Physics
169 | if (componentType == "PhysicsComponent")
170 | {
171 | const float mass = comp["mass"].get();
172 | const float gravityScale = comp["gravity-scale"].get();
173 | const float linearDrag = comp["linear-drag"].get();
174 | PhysicsComponent * newPhysicsComp = new PhysicsComponent(
175 | ref,
176 | nParams,
177 | mass,
178 | gravityScale,
179 | linearDrag
180 | );
181 | ref->AddComponent(newPhysicsComp);
182 |
183 | if (comp.contains("constraints"))
184 | {
185 | const json & constraints = comp["constraints"];
186 | newPhysicsComp->SetConstraints(constraints[0].get(), constraints[1].get());
187 | }
188 | }
189 |
190 | // BoxCollider
191 | if (componentType == "BoxColliderComponent")
192 | {
193 | const Vector3 boxExtents{ comp["size"][0], comp["size"][1], 0.f };
194 | ref->AddComponent(new BoxColliderComponent(ref, Vector3::Zero(), boxExtents));
195 | }
196 |
197 | // Follow
198 | if (componentType == "FollowComponent")
199 | {
200 | auto followComp = new FollowComponent(ref);
201 | if (playerActor)
202 | {
203 | followComp->targetActorRef = playerActor;
204 | followComp->bShouldFollow = comp["should-follow"].get();
205 | followComp->followForce = comp["follow-force"].get();
206 | }
207 | ref->AddComponent(followComp);
208 | }
209 | }
210 |
211 | // Set Player Actor
212 | if (actorData.contains("player-actor") && actorData["player-actor"].get())
213 | playerActor = ref;
214 | }
215 |
216 | void World::DeleteActor(SmartPtr & actor)
217 | {
218 | for (size_t i = 0; i < actors.size(); i++)
219 | {
220 | SmartPtr & cmpActor = actors.at(i);
221 | if (cmpActor == actor)
222 | {
223 | //actors[i] = nullptr;
224 | const auto spriteRef = cmpActor->sprite;
225 | if (spriteRef)
226 | {
227 | GLib::Sprites::Release(spriteRef);
228 | cmpActor->sprite = nullptr;
229 | }
230 | actors.erase(actors.begin() + i);
231 | break;
232 | }
233 | }
234 | UpdateWeakActorRefs();
235 | }
236 |
237 | void World::DeleteAllActors()
238 | {
239 | playerActor = nullptr;
240 | for (SmartPtr & ref : actors)
241 | {
242 | if (ref->sprite)
243 | GLib::Sprites::Release(ref->sprite);
244 | ref = nullptr;
245 | }
246 | actors.clear();
247 | UpdateWeakActorRefs();
248 | }
249 |
250 |
251 | // PlayerActor
252 | void World::SetPlayerActor(SmartPtr & actor)
253 | {
254 | playerActor = actor;
255 | }
256 | WeakPtr & World::GetPlayerActor()
257 | {
258 | return playerActor;
259 | }
260 |
261 |
262 | // WeakRefs
263 | void World::UpdateWeakActorRefs()
264 | {
265 | CurrentActorRefsMutex.lock();
266 | actorRefs.clear();
267 | for (SmartPtr & actor : GetAllActors())
268 | actorRefs.emplace_back(actor);
269 | CurrentActorRefsMutex.unlock();
270 | }
271 | std::vector>& World::GetAllWeakActorRefs()
272 | {
273 | return actorRefs;
274 | }
275 | //////////////////////////////////////////////////////////////////////////////////////////////////// ACTORS
276 |
277 |
278 |
279 |
280 |
281 |
282 |
283 |
284 |
285 |
286 |
287 |
288 | //////////////////////////////////////////////////////////////////////////////////////////////////// RENDER
289 | bool World::RenderAllActors()
290 | {
291 | // Pre-Render
292 | bool serviceInput;
293 | GLib::Service(serviceInput);
294 | if (serviceInput) return false;
295 |
296 | GLib::BeginRendering();
297 | GLib::Sprites::BeginRendering();
298 |
299 | for (WeakPtr & weakRef : actorRefs)
300 | {
301 | SmartPtr actor;
302 | weakRef.acquire(actor);
303 | if (actor && actor->sprite)
304 | {
305 | GLib::Point2D Offset = { actor->position.x, actor->position.y };
306 | RenderSprite(*actor->sprite, Offset, actor->zRotation);
307 | }
308 | }
309 |
310 | // Post-Render
311 | GLib::Sprites::EndRendering();
312 | GLib::EndRendering();
313 | return true;
314 | }
315 | //////////////////////////////////////////////////////////////////////////////////////////////////// RENDER
316 |
317 |
318 |
319 |
320 |
321 |
322 |
323 |
324 |
325 |
326 |
327 |
328 | //////////////////////////////////////////////////////////////////////////////////////////////////// EVENTS
329 | void World::BeginPlayAll()
330 | {
331 | CurrentActorsMutex.lock();
332 | for (WeakPtr & weakRef : actorRefs)
333 | {
334 | SmartPtr actor;
335 | weakRef.acquire(actor);
336 | if (actor) actor->BeginPlay();
337 | }
338 |
339 | // Time keeping
340 | LARGE_INTEGER lgInt;
341 | QueryPerformanceCounter(&lgInt);
342 | lastTimePoint = lgInt.QuadPart;
343 | CurrentActorsMutex.unlock();
344 | }
345 | void World::TickAll()
346 | {
347 | CurrentActorsMutex.lock();
348 | for (WeakPtr & weakRef : actorRefs)
349 | {
350 | SmartPtr actor;
351 | weakRef.acquire(actor);
352 | if (actor) actor->Tick(deltaSeconds);
353 | }
354 |
355 | collisionSystem->Run();
356 |
357 | // Time keeping
358 | LARGE_INTEGER lgInt;
359 | QueryPerformanceCounter(&lgInt);
360 | QueryPerformanceFrequency(&pcFrequency);
361 | deltaSeconds = float(lgInt.QuadPart - lastTimePoint) / float(pcFrequency.QuadPart);
362 | lastTimePoint = lgInt.QuadPart;
363 | totalSeconds += deltaSeconds;
364 | CurrentActorsMutex.unlock();
365 | }
366 | void World::EndPlay()
367 | {
368 | isGameOver = true;
369 | }
370 | bool World::GetIsGameOver() const
371 | {
372 | return isGameOver;
373 | }
374 | bool World::GetIsGamePaused() const
375 | {
376 | return isGamePaused;
377 | }
378 | void World::PauseToggle()
379 | {
380 | isGamePaused = !isGamePaused;
381 | }
382 |
383 |
384 | float World::GetDeltaSeconds() const
385 | {
386 | return static_cast(deltaSeconds);
387 | }
388 | float World::GetGameTime() const
389 | {
390 | return totalSeconds;
391 | }
392 | void World::Shutdown()
393 | {
394 | DeleteAllActors();
395 | GLib::Shutdown();
396 | delete this;
397 | }
398 | //////////////////////////////////////////////////////////////////////////////////////////////////// EVENTS
--------------------------------------------------------------------------------
/Engine/General/World.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 | #include "Windows.h"
6 | #include "Actor.h"
7 | #include "../Memory/SmartPointer/WeakPtr.h"
8 | #include
9 | #include "json.hpp"
10 |
11 | class CollisionSystem;
12 | class Input;
13 |
14 |
15 | class World
16 | {
17 | public:
18 | World(HINSTANCE i_hinstance, int i_cmdShow);
19 | ~World();
20 |
21 | std::vector> GetAllActors() const;
22 | void SpawnActor(SmartPtr & ref, const std::string name, Vector2 spawn_location);
23 | void SpawnPrefab(SmartPtr & ref, const std::string filePath);
24 | void SpawnActorFromJson(const nlohmann::json & actorData, SmartPtr & ref);
25 | void SpawnQueuedActors();
26 | void QueueNewActor(SmartPtr & ref, const std::string name, Vector2 spawn_location);
27 | void LoadScene(const std::string filePath);
28 | bool RenderAllActors();
29 | void DeleteActor(SmartPtr & actor);
30 | void DeleteAllActors();
31 | void SetPlayerActor(SmartPtr & actor);
32 | WeakPtr & GetPlayerActor();
33 | std::vector> & GetAllWeakActorRefs();
34 | void UpdateWeakActorRefs();
35 |
36 | void TickAll();
37 | void BeginPlayAll();
38 | void EndPlay();
39 | void Shutdown();
40 | bool GetIsGameOver() const;
41 | bool GetIsGamePaused() const;
42 | void PauseToggle();
43 | float GetDeltaSeconds() const;
44 | float GetGameTime() const;
45 |
46 |
47 | std::mutex CurrentActorsMutex;
48 | std::mutex CurrentActorRefsMutex;
49 |
50 | private:
51 | std::vector> actors;
52 | std::vector> actorRefs;
53 |
54 | CollisionSystem * collisionSystem;
55 | Input * inputSystem;
56 |
57 | std::mutex NewActorsMutex;
58 | std::vector> actorsToAdd;
59 |
60 |
61 |
62 |
63 | WeakPtr playerActor;
64 | bool isGameOver = false;
65 | bool isGamePaused = false;
66 | __int64 lastTimePoint;
67 | LARGE_INTEGER pcFrequency;
68 | float deltaSeconds;
69 | float totalSeconds;
70 | };
--------------------------------------------------------------------------------
/Engine/Jobs/Console/ConsolePrint.Win32.cpp:
--------------------------------------------------------------------------------
1 | #include // for va_
2 | #include // for vsprintf_s()
3 | #include // for OutputDebugStringA(). Uggh.. this pulls in a lot of Windows specific stuff
4 |
5 | namespace Engine
6 | {
7 |
8 | void ConsolePrint( const char * i_pFmt, const char * i_pFile, unsigned int i_Line, ... )
9 | {
10 | const size_t lenTemp = 128;
11 | char strTemp[lenTemp] = "DEBUG: %s %u: ";
12 |
13 | strcat_s( strTemp, i_pFmt );
14 |
15 | const size_t lenOutput = 256;
16 | char strOutput[lenOutput];
17 |
18 | // define a variable argument list variable
19 | va_list args;
20 |
21 | // initialize it. second parameter is variable immediately
22 | // preceeding variable arguments
23 | va_start( args, i_pFmt );
24 |
25 | // (safely) print our formatted string to a char buffer
26 | vsprintf_s( strOutput, lenOutput, strTemp, args );
27 |
28 | va_end( args );
29 |
30 | OutputDebugStringA( strOutput );
31 | }
32 |
33 | } // namespace Engine
--------------------------------------------------------------------------------
/Engine/Jobs/Console/ConsolePrint.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | namespace Engine
4 | {
5 |
6 | void ConsolePrint( const char * i_pFmt, const char * i_pFile, unsigned int i_Line, ... );
7 |
8 | } // namespace Engine
9 |
10 | // This is how we handle variable argument pre-processor macros
11 | // This is only supported by compilers that support the C99 standard
12 | #if defined(_DEBUG) && !defined(DISABLE_DEBUG_PRINT)
13 | #define DEBUG_PRINT(fmt,...) Engine::ConsolePrint((fmt),__FILE__,__LINE__,__VA_ARGS__)
14 | #else
15 | // This is one way we create a do nothing (NO OP) macro that doesn't
16 | // generate a compiler warning or error
17 | #define DEBUG_PRINT(fmt,...) void(0)
18 | #endif
19 |
--------------------------------------------------------------------------------
/Engine/Jobs/HashedString/HashedString-inl.h:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | namespace Engine
5 | {
6 | inline HashedString::HashedString( ) :
7 | m_Hash( Hash( "" ) )
8 | {
9 | }
10 |
11 | inline HashedString::HashedString( const char * i_string ) :
12 | m_Hash( Hash( i_string ) )
13 | #ifdef DEBUG_KEEP_STRING
14 | , m_pString( strdup( i_string ) )
15 | #endif
16 | {
17 | }
18 |
19 | inline HashedString::HashedString( const HashedString & i_other ) :
20 | m_Hash( i_other.m_Hash )
21 | #ifdef DEBUG_KEEP_STRING
22 | , m_pString( strdup( i_other.m_pString ) )
23 | #endif
24 | {
25 | }
26 |
27 | inline HashedString::~HashedString()
28 | {
29 | #ifdef DEBUG_KEEP_STRING
30 | if( m_pString )
31 | free( m_pString )
32 | #endif
33 |
34 | }
35 |
36 | inline HashedString & HashedString::operator=( const HashedString & i_other )
37 | {
38 | m_Hash = i_other.m_Hash;
39 |
40 | #ifdef DEBUG_KEEP_STRING
41 | if( m_pString )
42 | free( m_pString )
43 |
44 | m_pString = i_other.m_pString;
45 | #endif
46 |
47 | return *this;
48 | }
49 |
50 | inline unsigned int HashedString::Get( void ) const
51 | {
52 | return m_Hash;
53 | }
54 |
55 | inline bool HashedString::operator==( const HashedString & i_other ) const
56 | {
57 | return m_Hash == i_other.m_Hash;
58 | }
59 |
60 | inline bool HashedString::operator<( const HashedString & i_other ) const
61 | {
62 | return m_Hash < i_other.m_Hash;
63 | }
64 | } // namespace Engine
65 |
--------------------------------------------------------------------------------
/Engine/Jobs/HashedString/HashedString.cpp:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | #include "HashedString.h"
4 |
5 | namespace Engine
6 | {
7 |
8 | unsigned int HashedString::Hash( const char * i_string )
9 | {
10 | assert( i_string );
11 |
12 | return Hash( reinterpret_cast( const_cast( i_string ) ), strlen( i_string ) );
13 | }
14 |
15 | unsigned int HashedString::Hash( const void * i_bytes, size_t i_bytecount )
16 | {
17 | // FNV hash, http://isthe.com/chongo/tech/comp/fnv/
18 |
19 | register const unsigned char * p = static_cast( i_bytes );
20 | unsigned int hash = 2166136261;
21 |
22 | for( size_t i = 0; i < i_bytecount; ++i )
23 | hash = 16777619 * (hash ^ p[i]);
24 |
25 | return hash ^ (hash >> 16);
26 | } ;
27 |
28 | } // namespace Engine
--------------------------------------------------------------------------------
/Engine/Jobs/HashedString/HashedString.h:
--------------------------------------------------------------------------------
1 | #ifndef __HASHED_STRING_H
2 | #define __HASHED_STRING_H
3 |
4 | namespace Engine
5 | {
6 |
7 | class HashedString
8 | {
9 | public:
10 | HashedString();
11 | ~HashedString();
12 |
13 | HashedString( const char * i_string );
14 | HashedString( const HashedString & i_other );
15 | HashedString & operator=( const HashedString & i_other );
16 |
17 | unsigned int Get() const;
18 |
19 | bool operator==( const HashedString & i_other ) const;
20 | bool operator<( const HashedString & i_other ) const;
21 |
22 | static unsigned int Hash( const char * i_string );
23 | static unsigned int Hash( const void * i_bytes, size_t i_count );
24 | private:
25 | unsigned int m_Hash;
26 |
27 | #ifdef DEBUG_KEEP_STRING
28 | const char * m_pString;
29 | #endif
30 | } ;
31 |
32 | } // namespace Engine
33 |
34 | #include "HashedString-inl.h"
35 |
36 | #endif // __HASHED_STRING_H
--------------------------------------------------------------------------------
/Engine/Jobs/JobSystem/IJob.cpp:
--------------------------------------------------------------------------------
1 | #include "IJob.h"
2 |
3 | #include
4 |
5 | namespace Engine
6 | {
7 | namespace JobSystem
8 | {
9 | CRITICAL_SECTION IJob::m_Shutdown;
10 | bool IJob::m_bShutdown = false;
11 |
12 | void IJob::Shutdown()
13 | {
14 | static bool bInited = false;
15 | if (bInited == false)
16 | {
17 | InitializeCriticalSection(&m_Shutdown);
18 | bInited = true;
19 | }
20 |
21 | EnterCriticalSection(&m_Shutdown);
22 | m_bShutdown = true;
23 | LeaveCriticalSection(&m_Shutdown);
24 | }
25 |
26 | } // namespace JobSystem
27 | } // namespace Engine
--------------------------------------------------------------------------------
/Engine/Jobs/JobSystem/IJob.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 |
5 | #include "INamed.h"
6 |
7 | namespace Engine
8 | {
9 | namespace JobSystem
10 | {
11 | class IJob
12 | #ifdef _DEBUG
13 | : public INamed
14 | #endif
15 | {
16 | public:
17 | IJob(const char* i_pName) :
18 | INamed(i_pName)
19 | {}
20 |
21 | virtual ~IJob() { }
22 | virtual void Run() = 0;
23 |
24 | static void Shutdown();
25 | static bool ShutdownRequested();
26 | private:
27 | static CRITICAL_SECTION m_Shutdown;
28 | static bool m_bShutdown;
29 | };
30 |
31 | inline bool IJob::ShutdownRequested()
32 | {
33 | return m_bShutdown;
34 | }
35 |
36 | } // namespace JobSystem
37 | } // namespace Engine
--------------------------------------------------------------------------------
/Engine/Jobs/JobSystem/INamed.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | namespace Engine
5 | {
6 | namespace JobSystem
7 | {
8 | class INamed
9 | {
10 | public:
11 | INamed(const char* i_pName = nullptr) :
12 | m_Name(i_pName ? i_pName : "")
13 | {}
14 |
15 | void SetName(const char* i_pName)
16 | {
17 | m_Name = i_pName;
18 | }
19 | const char* GetName(void) const
20 | {
21 | return m_Name.c_str();
22 | }
23 |
24 | private:
25 | std::string m_Name;
26 | };
27 |
28 | } // namespace JobSystem
29 | } // namespace Engine
--------------------------------------------------------------------------------
/Engine/Jobs/JobSystem/JobRunner.cpp:
--------------------------------------------------------------------------------
1 | #include "JobRunner.h"
2 |
3 | #include
4 |
5 | #include "JobSystem.h"
6 | #include "../Console/ConsolePrint.h"
7 |
8 | namespace Engine
9 | {
10 | namespace JobSystem
11 | {
12 |
13 | DWORD WINAPI JobRunner(void* i_pThreadInput)
14 | {
15 | assert(i_pThreadInput);
16 | assert(((JobRunnerInput*)i_pThreadInput)->i_pQueue);
17 |
18 | JobRunnerInput* pInput = reinterpret_cast(i_pThreadInput);
19 | SharedJobQueue* pQueue = reinterpret_cast(pInput->i_pQueue);
20 |
21 | DEBUG_PRINT("JobRunner \"%s\": Starting Queue \"%s\".\n", pInput->m_ThreadName.c_str(), pQueue->GetName() ? pQueue->GetName() : "Unknown");
22 |
23 | bool bDone = false;
24 |
25 | do
26 | {
27 | DEBUG_PRINT("JobRunner \"%s\": Acquiring Job.\n", pInput->m_ThreadName.c_str());
28 | struct JobData* pJob = pQueue->GetWhenAvailable();
29 | if (pJob)
30 | {
31 | DEBUG_PRINT("JobRunner \"%s\": Starting Job \"%s\" on Processor %d.\n", pInput->m_ThreadName.c_str(), pJob->Name.c_str(), GetCurrentProcessorNumber());
32 |
33 | pJob->Function();
34 |
35 | DEBUG_PRINT("JobRunner \"%s\": Finished Job \"%s\".\n", pInput->m_ThreadName.c_str(), pJob->Name.c_str());
36 | delete pJob;
37 | pQueue->JobFinished();
38 | bDone = ShutdownRequested();
39 | }
40 | else
41 | bDone = ShutdownRequested();
42 |
43 | } while (bDone == false);
44 |
45 | #ifdef _DEBUG
46 | DEBUG_PRINT("JobRunner \"%s\": Shutting down.\n", pInput->m_ThreadName.c_str());
47 | #endif
48 | return 0;
49 | }
50 |
51 | } // namespace JobSystem
52 | } // namespace Engine
53 |
--------------------------------------------------------------------------------
/Engine/Jobs/JobSystem/JobRunner.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "SharedJobQueue.h"
4 |
5 | namespace Engine
6 | {
7 | namespace JobSystem
8 | {
9 |
10 | struct JobRunnerInput
11 | {
12 | SharedJobQueue* i_pQueue;
13 | #ifdef _DEBUG
14 | std::string m_ThreadName;
15 | #endif
16 | };
17 |
18 | DWORD WINAPI JobRunner(void* i_pJobRunnerInput);
19 |
20 | } // namespace JobSystem
21 | } // namespace Engine
22 |
--------------------------------------------------------------------------------
/Engine/Jobs/JobSystem/JobSystem.cpp:
--------------------------------------------------------------------------------
1 | #include "JobSystem.h"
2 |
3 | #include
4 | #include