forked from gameprogcpp/code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLevelLoader.cpp
More file actions
513 lines (450 loc) · 14.1 KB
/
LevelLoader.cpp
File metadata and controls
513 lines (450 loc) · 14.1 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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
// ----------------------------------------------------------------
// From Game Programming in C++ by Sanjay Madhav
// Copyright (C) 2017 Sanjay Madhav. All rights reserved.
//
// Released under the BSD License
// See LICENSE in root directory for full details.
// ----------------------------------------------------------------
#include "LevelLoader.h"
#include <fstream>
#include <vector>
#include <SDL/SDL.h>
#include "Game.h"
#include "Renderer.h"
#include "Actor.h"
#include "BallActor.h"
#include "FollowActor.h"
#include "PlaneActor.h"
#include "TargetActor.h"
#include "Component.h"
#include "AudioComponent.h"
#include "BallMove.h"
#include "BoxComponent.h"
#include "CameraComponent.h"
#include "FollowCamera.h"
#include "MeshComponent.h"
#include "MoveComponent.h"
#include "SkeletalMeshComponent.h"
#include "SpriteComponent.h"
#include "MirrorCamera.h"
#include "PointLightComponent.h"
#include "TargetComponent.h"
#include <rapidjson/stringbuffer.h>
#include <rapidjson/prettywriter.h>
const int LevelVersion = 1;
// Declare map of actors to spawn functions
std::unordered_map<std::string, ActorFunc> LevelLoader::sActorFactoryMap
{
{ "Actor", &Actor::Create<Actor> },
{ "BallActor", &Actor::Create<BallActor> },
{ "FollowActor", &Actor::Create<FollowActor> },
{ "PlaneActor", &Actor::Create<PlaneActor> },
{ "TargetActor", &Actor::Create<TargetActor> },
};
std::unordered_map<std::string, std::pair<int, ComponentFunc>> LevelLoader::sComponentFactoryMap
{
{ "AudioComponent", { Component::TAudioComponent, &Component::Create<AudioComponent>} },
{ "BallMove", { Component::TBallMove, &Component::Create<BallMove> } },
{ "BoxComponent", { Component::TBoxComponent, &Component::Create<BoxComponent> } },
{ "CameraComponent", { Component::TCameraComponent, &Component::Create<CameraComponent> } },
{ "FollowCamera", { Component::TFollowCamera, &Component::Create<FollowCamera> } },
{ "MeshComponent", { Component::TMeshComponent, &Component::Create<MeshComponent> } },
{ "MoveComponent", { Component::TMoveComponent, &Component::Create<MoveComponent> } },
{ "SkeletalMeshComponent", { Component::TSkeletalMeshComponent, &Component::Create<SkeletalMeshComponent> } },
{ "SpriteComponent", { Component::TSpriteComponent, &Component::Create<SpriteComponent> } },
{ "MirrorCamera", { Component::TMirrorCamera, &Component::Create<MirrorCamera> } },
{ "PointLightComponent", { Component::TPointLightComponent, &Component::Create<PointLightComponent> }},
{ "TargetComponent",{ Component::TTargetComponent, &Component::Create<TargetComponent> } },
};
bool LevelLoader::LoadLevel(Game* game, const std::string& fileName)
{
rapidjson::Document doc;
if (!LoadJSON(fileName, doc))
{
SDL_Log("Failed to load level %s", fileName.c_str());
return false;
}
int version = 0;
if (!JsonHelper::GetInt(doc, "version", version) ||
version != LevelVersion)
{
SDL_Log("Incorrect level file version for %s", fileName.c_str());
return false;
}
// Handle any global properties
const rapidjson::Value& globals = doc["globalProperties"];
if (globals.IsObject())
{
LoadGlobalProperties(game, globals);
}
// Handle any actors
const rapidjson::Value& actors = doc["actors"];
if (actors.IsArray())
{
LoadActors(game, actors);
}
return true;
}
bool LevelLoader::LoadJSON(const std::string& fileName, rapidjson::Document& outDoc)
{
// Load the file from disk into an ifstream in binary mode,
// loaded with stream buffer at the end (ate)
std::ifstream file(fileName, std::ios::in | std::ios::binary | std::ios::ate);
if (!file.is_open())
{
SDL_Log("File %s not found", fileName.c_str());
return false;
}
// Get the current position in stream buffer, which is size of file
std::ifstream::pos_type fileSize = file.tellg();
// Seek back to start of file
file.seekg(0, std::ios::beg);
// Create a vector of size + 1 (for null terminator)
std::vector<char> bytes(static_cast<size_t>(fileSize) + 1);
// Read in bytes into vector
file.read(bytes.data(), static_cast<size_t>(fileSize));
// Load raw data into RapidJSON document
outDoc.Parse(bytes.data());
if (!outDoc.IsObject())
{
SDL_Log("File %s is not valid JSON", fileName.c_str());
return false;
}
return true;
}
void LevelLoader::SaveLevel(Game* game, const std::string& fileName)
{
// Create the document and root object
rapidjson::Document doc;
doc.SetObject();
// Write the version
JsonHelper::AddInt(doc.GetAllocator(), doc, "version", LevelVersion);
// Globals
rapidjson::Value globals(rapidjson::kObjectType);
SaveGlobalProperties(doc.GetAllocator(), game, globals);
doc.AddMember("globalProperties", globals, doc.GetAllocator());
// Actors
rapidjson::Value actors(rapidjson::kArrayType);
SaveActors(doc.GetAllocator(), game, actors);
doc.AddMember("actors", actors, doc.GetAllocator());
// Save JSON to string buffer
rapidjson::StringBuffer buffer;
// Use PrettyWriter for pretty output (otherwise use Writer)
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
doc.Accept(writer);
const char* output = buffer.GetString();
// Write output to file
std::ofstream outFile(fileName);
if (outFile.is_open())
{
outFile << output;
}
}
void LevelLoader::LoadGlobalProperties(Game* game, const rapidjson::Value& inObject)
{
// Get ambient light
Vector3 ambient;
if (JsonHelper::GetVector3(inObject, "ambientLight", ambient))
{
game->GetRenderer()->SetAmbientLight(ambient);
}
// Get directional light
const rapidjson::Value& dirObj = inObject["directionalLight"];
if (dirObj.IsObject())
{
DirectionalLight& light = game->GetRenderer()->GetDirectionalLight();
// Set direction/color, if they exist
JsonHelper::GetVector3(dirObj, "direction", light.mDirection);
JsonHelper::GetVector3(dirObj, "color", light.mDiffuseColor);
}
}
void LevelLoader::LoadActors(Game* game, const rapidjson::Value& inArray)
{
// Loop through array of actors
for (rapidjson::SizeType i = 0; i < inArray.Size(); i++)
{
const rapidjson::Value& actorObj = inArray[i];
if (actorObj.IsObject())
{
// Get the type
std::string type;
if (JsonHelper::GetString(actorObj, "type", type))
{
// Is this type in the map?
auto iter = sActorFactoryMap.find(type);
if (iter != sActorFactoryMap.end())
{
// Construct with function stored in map
Actor* actor = iter->second(game, actorObj["properties"]);
// Get the actor's components
if (actorObj.HasMember("components"))
{
const rapidjson::Value& components = actorObj["components"];
if (components.IsArray())
{
LoadComponents(actor, components);
}
}
}
else
{
SDL_Log("Unknown actor type %s", type.c_str());
}
}
}
}
}
void LevelLoader::LoadComponents(Actor* actor, const rapidjson::Value& inArray)
{
// Loop through array of components
for (rapidjson::SizeType i = 0; i < inArray.Size(); i++)
{
const rapidjson::Value& compObj = inArray[i];
if (compObj.IsObject())
{
// Get the type
std::string type;
if (JsonHelper::GetString(compObj, "type", type))
{
auto iter = sComponentFactoryMap.find(type);
if (iter != sComponentFactoryMap.end())
{
// Get the typeid of component
Component::TypeID tid = static_cast<Component::TypeID>(iter->second.first);
// Does the actor already have a component of this type?
Component* comp = actor->GetComponentOfType(tid);
if (comp == nullptr)
{
// It's a new component, call function from map
comp = iter->second.second(actor, compObj["properties"]);
}
else
{
// It already exists, just load properties
comp->LoadProperties(compObj["properties"]);
}
}
else
{
SDL_Log("Unknown component type %s", type.c_str());
}
}
}
}
}
void LevelLoader::SaveGlobalProperties(rapidjson::Document::AllocatorType& alloc,
Game* game, rapidjson::Value& inObject)
{
// Ambient light
JsonHelper::AddVector3(alloc, inObject, "ambientLight",
game->GetRenderer()->GetAmbientLight());
// Directional light
DirectionalLight& dirLight = game->GetRenderer()->GetDirectionalLight();
rapidjson::Value dirObj(rapidjson::kObjectType);
JsonHelper::AddVector3(alloc, dirObj, "direction", dirLight.mDirection);
JsonHelper::AddVector3(alloc, dirObj, "color", dirLight.mDiffuseColor);
inObject.AddMember("directionalLight", dirObj, alloc);
}
void LevelLoader::SaveActors(rapidjson::Document::AllocatorType& alloc,
Game* game, rapidjson::Value& inArray)
{
const auto& actors = game->GetActors();
for (const Actor* actor : actors)
{
// Make a JSON object
rapidjson::Value obj(rapidjson::kObjectType);
// Add type
JsonHelper::AddString(alloc, obj, "type", Actor::TypeNames[actor->GetType()]);
// Make object for properties
rapidjson::Value props(rapidjson::kObjectType);
// Save properties
actor->SaveProperties(alloc, props);
// Add the properties member
obj.AddMember("properties", props, alloc);
// Save components
rapidjson::Value components(rapidjson::kArrayType);
SaveComponents(alloc, actor, components);
obj.AddMember("components", components, alloc);
// Add actor to inArray
inArray.PushBack(obj, alloc);
}
}
void LevelLoader::SaveComponents(rapidjson::Document::AllocatorType& alloc,
const Actor* actor, rapidjson::Value& inArray)
{
const auto& components = actor->GetComponents();
for (const Component* comp : components)
{
// Make a JSON object
rapidjson::Value obj(rapidjson::kObjectType);
// Add type
JsonHelper::AddString(alloc, obj, "type", Component::TypeNames[comp->GetType()]);
// Make an object for properties
rapidjson::Value props(rapidjson::kObjectType);
// Save rest of properties
comp->SaveProperties(alloc, props);
// Add the member
obj.AddMember("properties", props, alloc);
// Add component to array
inArray.PushBack(obj, alloc);
}
}
bool JsonHelper::GetInt(const rapidjson::Value& inObject, const char* inProperty, int& outInt)
{
// Check if this property exists
auto itr = inObject.FindMember(inProperty);
if (itr == inObject.MemberEnd())
{
return false;
}
// Get the value type, and check it's an integer
auto& property = itr->value;
if (!property.IsInt())
{
return false;
}
// We have the property
outInt = property.GetInt();
return true;
}
bool JsonHelper::GetFloat(const rapidjson::Value& inObject, const char* inProperty, float& outFloat)
{
auto itr = inObject.FindMember(inProperty);
if (itr == inObject.MemberEnd())
{
return false;
}
auto& property = itr->value;
if (!property.IsDouble())
{
return false;
}
outFloat = property.GetDouble();
return true;
}
bool JsonHelper::GetString(const rapidjson::Value& inObject, const char* inProperty, std::string& outStr)
{
auto itr = inObject.FindMember(inProperty);
if (itr == inObject.MemberEnd())
{
return false;
}
auto& property = itr->value;
if (!property.IsString())
{
return false;
}
outStr = property.GetString();
return true;
}
bool JsonHelper::GetBool(const rapidjson::Value& inObject, const char* inProperty, bool& outBool)
{
auto itr = inObject.FindMember(inProperty);
if (itr == inObject.MemberEnd())
{
return false;
}
auto& property = itr->value;
if (!property.IsBool())
{
return false;
}
outBool = property.GetBool();
return true;
}
bool JsonHelper::GetVector3(const rapidjson::Value& inObject, const char* inProperty, Vector3& outVector)
{
auto itr = inObject.FindMember(inProperty);
if (itr == inObject.MemberEnd())
{
return false;
}
auto& property = itr->value;
if (!property.IsArray() || property.Size() != 3)
{
return false;
}
for (rapidjson::SizeType i = 0; i < 3; i++)
{
if (!property[i].IsDouble())
{
return false;
}
}
outVector.x = property[0].GetDouble();
outVector.y = property[1].GetDouble();
outVector.z = property[2].GetDouble();
return true;
}
bool JsonHelper::GetQuaternion(const rapidjson::Value& inObject, const char* inProperty, Quaternion& outQuat)
{
auto itr = inObject.FindMember(inProperty);
if (itr == inObject.MemberEnd())
{
return false;
}
auto& property = itr->value;
for (rapidjson::SizeType i = 0; i < 4; i++)
{
if (!property[i].IsDouble())
{
return false;
}
}
outQuat.x = property[0].GetDouble();
outQuat.y = property[1].GetDouble();
outQuat.z = property[2].GetDouble();
outQuat.w = property[3].GetDouble();
return true;
}
void JsonHelper::AddInt(rapidjson::Document::AllocatorType& alloc,
rapidjson::Value& inObject, const char* name, int value)
{
rapidjson::Value v(value);
inObject.AddMember(rapidjson::StringRef(name), v, alloc);
}
void JsonHelper::AddFloat(rapidjson::Document::AllocatorType& alloc,
rapidjson::Value& inObject, const char* name, float value)
{
rapidjson::Value v(value);
inObject.AddMember(rapidjson::StringRef(name), v, alloc);
}
void JsonHelper::AddString(rapidjson::Document::AllocatorType& alloc,
rapidjson::Value& inObject, const char* name, const std::string& value)
{
rapidjson::Value v;
v.SetString(value.c_str(), static_cast<rapidjson::SizeType>(value.length()),
alloc);
inObject.AddMember(rapidjson::StringRef(name), v, alloc);
}
void JsonHelper::AddBool(rapidjson::Document::AllocatorType& alloc,
rapidjson::Value& inObject, const char* name, bool value)
{
rapidjson::Value v(value);
inObject.AddMember(rapidjson::StringRef(name), v, alloc);
}
void JsonHelper::AddVector3(rapidjson::Document::AllocatorType& alloc,
rapidjson::Value& inObject, const char* name, const Vector3& value)
{
// Create an array
rapidjson::Value v(rapidjson::kArrayType);
// Push back elements
v.PushBack(rapidjson::Value(value.x).Move(), alloc);
v.PushBack(rapidjson::Value(value.y).Move(), alloc);
v.PushBack(rapidjson::Value(value.z).Move(), alloc);
// Add array to inObject
inObject.AddMember(rapidjson::StringRef(name), v, alloc);
}
void JsonHelper::AddQuaternion(rapidjson::Document::AllocatorType& alloc,
rapidjson::Value& inObject, const char* name, const Quaternion& value)
{
// Create an array
rapidjson::Value v(rapidjson::kArrayType);
// Push back elements
v.PushBack(rapidjson::Value(value.x).Move(), alloc);
v.PushBack(rapidjson::Value(value.y).Move(), alloc);
v.PushBack(rapidjson::Value(value.z).Move(), alloc);
v.PushBack(rapidjson::Value(value.w).Move(), alloc);
// Add array to inObject
inObject.AddMember(rapidjson::StringRef(name), v, alloc);
}