-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgame.cpp
More file actions
464 lines (386 loc) · 15.8 KB
/
game.cpp
File metadata and controls
464 lines (386 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
#include "precomp.h" // include (only) this in every .cpp file
#define NUM_TANKS_BLUE 1279
#define NUM_TANKS_RED 1279
#define TANK_MAX_HEALTH 1000
#define ROCKET_HIT_VALUE 60
#define PARTICLE_BEAM_HIT_VALUE 50
#define TANK_MAX_SPEED 1.5
#define HEALTH_BARS_OFFSET_X 0
#define HEALTH_BAR_HEIGHT 70
#define HEALTH_BAR_WIDTH 1
#define HEALTH_BAR_SPACING 0
#define MAX_FRAMES 2000
//Global performance timer
#define REF_PERFORMANCE 11871.4 //UPDATE THIS WITH YOUR REFERENCE PERFORMANCE (see console after 2k frames)
static timer perf_timer;
static float duration;
//Load sprite files and initialize sprites
static Surface* background_img = new Surface("assets/Background_Grass.png");
static Surface* tank_red_img = new Surface("assets/Tank_Proj2.png");
static Surface* tank_blue_img = new Surface("assets/Tank_Blue_Proj2.png");
static Surface* rocket_red_img = new Surface("assets/Rocket_Proj2.png");
static Surface* rocket_blue_img = new Surface("assets/Rocket_Blue_Proj2.png");
static Surface* particle_beam_img = new Surface("assets/Particle_Beam.png");
static Surface* smoke_img = new Surface("assets/Smoke.png");
static Surface* explosion_img = new Surface("assets/Explosion.png");
static Sprite background(background_img, 1);
static Sprite tank_red(tank_red_img, 12);
static Sprite tank_blue(tank_blue_img, 12);
static Sprite rocket_red(rocket_red_img, 12);
static Sprite rocket_blue(rocket_blue_img, 12);
static Sprite smoke(smoke_img, 4);
static Sprite explosion(explosion_img, 9);
static Sprite particle_beam_sprite(particle_beam_img, 3);
const static vec2 tank_size(14, 18);
const static vec2 rocket_size(25, 24);
const static float tank_radius = 12.f;
const static float rocket_radius = 10.f;
const static float tank_vs_tank_radius = ceil(sqrt(2 * tank_radius * tank_radius));
const static float tank_vs_rocket_radius = ceil(sqrt(2 * (tank_radius+rocket_radius) * (tank_radius+rocket_radius)));
const unsigned int Game::thread_count = thread::hardware_concurrency();
// -----------------------------------------------------------
// Initialize the application
// -----------------------------------------------------------
void Game::Init()
{
frame_count_font = new Font("assets/digital_small.png", "ABCDEFGHIJKLMNOPQRSTUVWXYZ:?!=-0123456789.");
tanks.reserve(NUM_TANKS_BLUE + NUM_TANKS_RED);
rockets.reserve(5000);
particle_beams.reserve(3);
uint rows = (uint)sqrt(NUM_TANKS_BLUE + NUM_TANKS_RED);
uint max_rows = 12;
float start_blue_x = tank_size.x + 10.0f;
float start_blue_y = tank_size.y + 80.0f;
float start_red_x = 980.0f;
float start_red_y = 100.0f;
float spacing = 15.0f;
//Spawn blue tanks
for (int i = 0; i < NUM_TANKS_BLUE; i++)
{
Tank* tank = new Tank(start_blue_x + ((i % max_rows) * spacing), start_blue_y + ((i / max_rows) * spacing), BLUE, &tank_blue, &smoke, 1200, 600, tank_radius, TANK_MAX_HEALTH, TANK_MAX_SPEED);
tanks.push_back(tank);
tanks_hash.tryInsertAt(tank->Get_Position(), tank);
}
//Spawn red tanks
for (int i = 0; i < NUM_TANKS_RED; i++)
{
Tank* tank = new Tank(start_red_x + ((i % max_rows) * spacing), start_red_y + ((i / max_rows) * spacing), RED, &tank_red, &smoke, 80, 80, tank_radius, TANK_MAX_HEALTH, TANK_MAX_SPEED);
tanks.push_back(tank);
tanks_hash.tryInsertAt(tank->Get_Position(), tank);
}
blue_tree = KDTree(tanks, 0, NUM_TANKS_BLUE);
red_tree = KDTree(tanks, NUM_TANKS_BLUE, NUM_TANKS_BLUE + NUM_TANKS_RED);
particle_beams.push_back(Particle_beam(vec2(SCRWIDTH / 2, SCRHEIGHT / 2), vec2(100, 50), &particle_beam_sprite, PARTICLE_BEAM_HIT_VALUE));
particle_beams.push_back(Particle_beam(vec2(80, 80), vec2(100, 50), &particle_beam_sprite, PARTICLE_BEAM_HIT_VALUE));
particle_beams.push_back(Particle_beam(vec2(1200, 600), vec2(100, 50), &particle_beam_sprite, PARTICLE_BEAM_HIT_VALUE));
}
// -----------------------------------------------------------
// Close down application
// -----------------------------------------------------------
void Game::Shutdown()
{
}
// -----------------------------------------------------------
// Iterates through all tanks and returns the closest enemy tank for the given tank
// -----------------------------------------------------------
Tank* Game::FindClosestEnemy(Tank* current_tank)
{
float closest_distance = numeric_limits<float>::infinity();
int closest_index = 0;
for (int i = 0; i < tanks.size(); i++)
{
if (tanks.at(i)->allignment != current_tank->allignment && tanks.at(i)->active)
{
float sqrDist = fabsf((tanks.at(i)->Get_Position() - current_tank->Get_Position()).sqrLength());
if (sqrDist < closest_distance)
{
closest_distance = sqrDist;
closest_index = i;
}
}
}
return tanks.at(closest_index);
}
template <typename Callable_T>
void Game::RunParallel(const Callable_T& callable, const int N, const unsigned int max_threads) noexcept
{
if (N >= max_threads)
{
std::atomic<int> jobs_running = 0;
for (auto i = 0; i < max_threads; i++)
{
if (i < (max_threads - 1))
{
jobs_running++;
pool.enqueue([&, i]() noexcept -> void
{
callable(float(N) / max_threads * i, float(N) / max_threads * (i + 1));
jobs_running--;
});
}
else
{
callable(float(N) / max_threads * i, float(N) / max_threads * (i + 1));
while (jobs_running) /*wait for all jobs to finish*/
;
}
}
}
else
{
callable(0, N);
}
}
// -----------------------------------------------------------
// Update the game state:
// Move all objects
// Update sprite frames
// Collision detection
// Targeting etc..
// -----------------------------------------------------------
void Game::Update(float deltaTime)
{
auto updateTanks = [&](int start, int end) noexcept
{
for (auto i = start; i < end; i++)
{
auto tank = tanks[i];
if (tank->active)
{
tanks_hash.forEachWithinBounds({tank->position, tank_vs_tank_radius}, [&](const SpatialHasher<Tank*>::Entry& oTank) noexcept
{
if (tank == oTank.object) return;
vec2 dir = tank->Get_Position() - oTank.object->Get_Position();
float dirSquaredLen = dir.sqrLength();
float colSquaredLen = (tank->Get_collision_radius() * tank->Get_collision_radius()) + (oTank.object->Get_collision_radius() * oTank.object->Get_collision_radius());
if (dirSquaredLen < colSquaredLen)
{
tank->Push(dir.normalized(), 1.f);
}
});
const auto old_position = tank->Get_Position();
tank->Tick();
tanks_hash.tryUpdateAt(old_position, tank->Get_Position(), tank);
}
}
};
RunParallel(updateTanks, tanks.size());
bool trees_rebuild = false;
for (int i = 0; i < tanks.size(); i++)
{
auto tank = tanks[i];
//Shoot at closest target if reloaded
if (tank->active && tank->Rocket_Reloaded())
{
if (trees_rebuild == false)
{
blue_tree.rebuild();
red_tree.rebuild();
trees_rebuild = true;
}
auto target = tank->allignment == BLUE ? red_tree.findNearestNeighbour(tank->position) : blue_tree.findNearestNeighbour(tank->position);
rockets.push_back(Rocket(tank->position, (target->Get_Position() - tank->position).normalized() * 3, rocket_radius, tank->allignment, ((tank->allignment == RED) ? &rocket_red : &rocket_blue)));
tank->Reload_Rocket();
}
}
//Update smoke plumes
for (Smoke& smoke : smokes)
{
smoke.Tick();
}
auto updateRockets = [&](int start, int end) noexcept
{
//Update rockets
for (auto i = start; i < end; i++)
{
auto& rocket = rockets[i];
rocket.Tick();
//Check if rocket collides with enemy tank, spawn explosion and if tank is destroyed spawn a smoke plume
tanks_hash.forEachWithinBounds({rocket.position, tank_vs_rocket_radius}, [&](const SpatialHasher<Tank*>::Entry& tank) noexcept
{
if (tank.object->active && (tank.object->allignment != rocket.allignment) && rocket.Intersects(tank.object->position, tank.object->collision_radius))
{
std::unique_lock<std::mutex>(explosions_mutex), explosions.push_back(Explosion(&explosion, tank.object->position));
if (tank.object->hit(ROCKET_HIT_VALUE))
{
std::unique_lock<std::mutex>(smokes_mutex), smokes.push_back(Smoke(smoke, tank.object->position - vec2(0, 48)));
}
rocket.active = false;
}
});
}
};
RunParallel(updateRockets, rockets.size());
//Remove exploded rockets with remove erase idiom
rockets.erase(std::remove_if(rockets.begin(), rockets.end(), [](const Rocket& rocket) { return !rocket.active; }), rockets.end());
//Update particle beams
for (Particle_beam& particle_beam : particle_beams)
{
particle_beam.tick();
//Damage all tanks within the damage window of the beam (the window is an axis-aligned bounding box)
tanks_hash.forEachWithinBounds({particle_beam.rectangle.min-tank_radius, particle_beam.rectangle.max+tank_radius}, [&](const SpatialHasher<Tank*>::Entry& tank) noexcept
{
if (tank.object->active && particle_beam.rectangle.intersectsCircle(tank.object->Get_Position(), tank.object->Get_collision_radius()))
{
if (tank.object->hit(particle_beam.damage))
{
smokes.push_back(Smoke(smoke, tank.object->position - vec2(0, 48)));
}
}
});
}
//Update explosion sprites and remove when done with remove erase idiom
for (Explosion& explosion : explosions)
{
explosion.Tick();
}
explosions.erase(std::remove_if(explosions.begin(), explosions.end(), [](const Explosion& explosion) { return explosion.done(); }), explosions.end());
}
void Game::Draw()
{
// clear the graphics window
screen->Clear(0);
//Draw background
background.Draw(screen, 0, 0);
//Draw sprites
for (int i = 0; i < NUM_TANKS_BLUE + NUM_TANKS_RED; i++)
{
tanks.at(i)->Draw(screen);
vec2 tPos = tanks.at(i)->Get_Position();
// tread marks
if ((tPos.x >= 0) && (tPos.x < SCRWIDTH) && (tPos.y >= 0) && (tPos.y < SCRHEIGHT))
background.GetBuffer()[(int)tPos.x + (int)tPos.y * SCRWIDTH] = SubBlend(background.GetBuffer()[(int)tPos.x + (int)tPos.y * SCRWIDTH], 0x808080);
}
for (Rocket& rocket : rockets)
{
rocket.Draw(screen);
}
for (Smoke& smoke : smokes)
{
smoke.Draw(screen);
}
auto drawParticleBeams = [&](int start, int end) noexcept
{
for (int i = start; i < end; i++)
{
particle_beams[i].Draw(screen);
}
};
RunParallel(drawParticleBeams, particle_beams.size(), 3);
for (Explosion& explosion : explosions)
{
explosion.Draw(screen);
}
//Draw sorted health bars
auto copy = tanks; //Copy tanks for mergesort
for (int t = 0; t < 2; t++)
{
const UINT16 NUM_TANKS = ((t < 1) ? NUM_TANKS_BLUE : NUM_TANKS_RED);
const UINT16 begin = ((t < 1) ? 0 : NUM_TANKS_BLUE);
splitmerge_tanks_health(tanks, copy, begin, begin + NUM_TANKS);
auto drawHealthBar = [&](int start, int end) noexcept
{
for (int i = start; i < end; i++)
{
int health_bar_start_x = i * (HEALTH_BAR_WIDTH + HEALTH_BAR_SPACING) + HEALTH_BARS_OFFSET_X;
int health_bar_start_y = (t < 1) ? 0 : (SCRHEIGHT - HEALTH_BAR_HEIGHT) - 1;
int health_bar_end_x = health_bar_start_x + HEALTH_BAR_WIDTH;
int health_bar_end_y = (t < 1) ? HEALTH_BAR_HEIGHT : SCRHEIGHT - 1;
screen->Bar(health_bar_start_x, health_bar_start_y, health_bar_end_x, health_bar_end_y, REDMASK);
screen->Bar(health_bar_start_x, health_bar_start_y + (int)((double)HEALTH_BAR_HEIGHT * (1 - ((double)tanks.at(begin + i)->health / (double)TANK_MAX_HEALTH))), health_bar_end_x, health_bar_end_y, GREENMASK);
}
};
RunParallel(drawHealthBar, NUM_TANKS);
}
}
void Tmpl8::Game::splitmerge_tanks_health_p(std::vector<Tank*>& A, std::vector<Tank*>& B, UINT16 begin, UINT16 end, int d) noexcept
{
if (end - begin <= 1)
return;
const auto middle = (end + begin) / 2;
if (d < thread_count)
{
auto f = pool.enqueue([&]() noexcept { splitmerge_tanks_health_p(B, A, begin, middle, d * 2); });
splitmerge_tanks_health_p(B, A, middle, end, d * 2);
f.wait();
}
else
{
splitmerge_tanks_health(B, A, begin, middle);
splitmerge_tanks_health(B, A, middle, end);
}
merge_tanks_health(B, A, begin, middle, end);
}
void Tmpl8::Game::splitmerge_tanks_health(std::vector<Tank*>& A, std::vector<Tank*>& B, UINT16 begin, UINT16 end) noexcept
{
if (end - begin <= 1)
return;
const auto middle = (end + begin) / 2;
splitmerge_tanks_health(B, A, begin, middle);
splitmerge_tanks_health(B, A, middle, end);
merge_tanks_health(B, A, begin, middle, end);
}
void Tmpl8::Game::merge_tanks_health(std::vector<Tank*>& A, std::vector<Tank*>& B, UINT16 begin, UINT16 middle, UINT16 end) noexcept
{
auto i = begin;
auto j = middle;
for (auto k = begin; k < end; k++)
{
if (i < middle && (j >= end || A[i]->health <= A[j]->health))
{
B[k] = A[i++];
}
else
{
B[k] = A[j++];
}
}
}
// -----------------------------------------------------------
// When we reach MAX_FRAMES print the duration and speedup multiplier
// Updating REF_PERFORMANCE at the top of this file with the value
// on your machine gives you an idea of the speedup your optimizations give
// -----------------------------------------------------------
void Tmpl8::Game::MeasurePerformance()
{
char buffer[128];
if (frame_count >= MAX_FRAMES)
{
if (!lock_update)
{
duration = perf_timer.elapsed();
cout << "Duration was: " << duration << " (Replace REF_PERFORMANCE with this value)" << endl;
lock_update = true;
}
frame_count--;
}
if (lock_update)
{
screen->Bar(420, 170, 870, 430, 0x030000);
int ms = (int)duration % 1000, sec = ((int)duration / 1000) % 60, min = ((int)duration / 60000);
sprintf(buffer, "%02i:%02i:%03i", min, sec, ms);
frame_count_font->Centre(screen, buffer, 200);
sprintf(buffer, "SPEEDUP: %4.1f", REF_PERFORMANCE / duration);
frame_count_font->Centre(screen, buffer, 340);
}
}
// -----------------------------------------------------------
// Main application tick function
// -----------------------------------------------------------
void Game::Tick(float deltaTime)
{
if (!lock_update)
{
Update(deltaTime);
}
Draw();
MeasurePerformance();
// print something in the graphics window
//screen->Print("hello world", 2, 2, 0xffffff);
// print something to the text window
//cout << "This goes to the console window." << std::endl;
//Print frame count
frame_count++;
string frame_count_string = "FRAME: " + std::to_string(frame_count);
frame_count_font->Print(screen, frame_count_string.c_str(), 350, 580);
}