aboutsummaryrefslogtreecommitdiff
path: root/src/utils/scenefilereader.cpp
blob: ad744a5e1cbf0300181438c2e9b88cf778ea2810 (plain)
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
#include "scenefilereader.h"
#include "scenedata.h"

#include "glm/gtc/type_ptr.hpp"

#include <cassert>
#include <cstring>
#include <iostream>
#include <filesystem>

#include <QFile>
#include <QJsonArray>

#define ERROR_AT(e) "error at line " << e.lineNumber() << " col " << e.columnNumber() << ": "
#define PARSE_ERROR(e) std::cout << ERROR_AT(e) << "could not parse <" << e.tagName().toStdString() \
                                 << ">" << std::endl
#define UNSUPPORTED_ELEMENT(e) std::cout << ERROR_AT(e) << "unsupported element <" \
                                         << e.tagName().toStdString() << ">" << std::endl;

// Students, please ignore this file.
ScenefileReader::ScenefileReader(const std::string &name) {
    file_name = name;

    memset(&m_cameraData, 0, sizeof(SceneCameraData));
    memset(&m_globalData, 0, sizeof(SceneGlobalData));

    m_root = new SceneNode;

    m_templates.clear();
    m_nodes.clear();

    m_nodes.push_back(m_root);
}

ScenefileReader::~ScenefileReader() {
    // Delete all Scene Nodes
    for (unsigned int node = 0; node < m_nodes.size(); node++) {
        for (size_t i = 0; i < (m_nodes[node])->transformations.size(); i++)
        {
            delete (m_nodes[node])->transformations[i];
        }
        for (size_t i = 0; i < (m_nodes[node])->primitives.size(); i++)
        {
            delete (m_nodes[node])->primitives[i];
        }
        (m_nodes[node])->transformations.clear();
        (m_nodes[node])->primitives.clear();
        (m_nodes[node])->children.clear();
        delete m_nodes[node];
    }

    m_nodes.clear();
    m_templates.clear();
}

SceneGlobalData ScenefileReader::getGlobalData() const {
    return m_globalData;
}

SceneCameraData ScenefileReader::getCameraData() const {
    return m_cameraData;
}

SceneNode *ScenefileReader::getRootNode() const {
    return m_root;
}

// This is where it all goes down...
bool ScenefileReader::readJSON() {
    // Read the file
    QFile file(file_name.c_str());
    if (!file.open(QFile::ReadOnly)) {
        std::cout << "could not open " << file_name << std::endl;
        return false;
    }

    // Load the JSON document
    QByteArray fileContents = file.readAll();
    QJsonParseError jsonError;
    QJsonDocument doc = QJsonDocument::fromJson(fileContents, &jsonError);
    if (doc.isNull()) {
        std::cout << "could not parse " << file_name << std::endl;
        std::cout << "parse error at line " << jsonError.offset << ": "
                  << jsonError.errorString().toStdString() << std::endl;
        return false;
    }
    file.close();

    if (!doc.isObject()) {
        std::cout << "document is not an object" << std::endl;
        return false;
    }

    // Get the root element
    QJsonObject scenefile = doc.object();

    if (!scenefile.contains("globalData")) {
        std::cout << "missing required field \"globalData\" on root object" << std::endl;
        return false;
    }
    if (!scenefile.contains("cameraData")) {
        std::cout << "missing required field \"cameraData\" on root object" << std::endl;
        return false;
    }

    QStringList requiredFields = {"globalData", "cameraData"};
    QStringList optionalFields = {"name", "groups", "templateGroups"};
    // If other fields are present, raise an error
    QStringList allFields = requiredFields + optionalFields;
    for (auto &field : scenefile.keys()) {
        if (!allFields.contains(field)) {
            std::cout << "unknown field \"" << field.toStdString() << "\" on root object" << std::endl;
            return false;
        }
    }

    // Parse the global data
    if (!parseGlobalData(scenefile["globalData"].toObject())) {
        std::cout << "could not parse \"globalData\"" << std::endl;
        return false;
    }

    // Parse the camera data
    if (!parseCameraData(scenefile["cameraData"].toObject())) {
        std::cout << "could not parse \"cameraData\"" << std::endl;
        return false;
    }

    // Parse the template groups
    if (scenefile.contains("templateGroups")) {
        if (!parseTemplateGroups(scenefile["templateGroups"])) {
            return false;
        }
    }

    // Parse the groups
    if (scenefile.contains("groups")) {
        if (!parseGroups(scenefile["groups"], m_root)) {
            return false;
        }
    }

    std::cout << "Finished reading " << file_name << std::endl;
    return true;
}

/**
 * Parse a globalData field and fill in m_globalData.
 */
bool ScenefileReader::parseGlobalData(const QJsonObject &globalData) {
    QStringList requiredFields = {"ambientCoeff", "diffuseCoeff", "specularCoeff"};
    QStringList optionalFields = {"transparentCoeff"};
    QStringList allFields = requiredFields + optionalFields;
    for (auto field : globalData.keys()) {
        if (!allFields.contains(field)) {
            std::cout << "unknown field \"" << field.toStdString() << "\" on globalData object" << std::endl;
            return false;
        }
    }
    for (auto field : requiredFields) {
        if (!globalData.contains(field)) {
            std::cout << "missing required field \"" << field.toStdString() << "\" on globalData object" << std::endl;
            return false;
        }
    }

    // Parse the global data
    if (globalData["ambientCoeff"].isDouble()) {
        m_globalData.ka = globalData["ambientCoeff"].toDouble();
    }
    else {
        std::cout << "globalData ambientCoeff must be a floating-point value" << std::endl;
        return false;
    }
    if (globalData["diffuseCoeff"].isDouble()) {
        m_globalData.kd = globalData["diffuseCoeff"].toDouble();
    }
    else {
        std::cout << "globalData diffuseCoeff must be a floating-point value" << std::endl;
        return false;
    }
    if (globalData["specularCoeff"].isDouble()) {
        m_globalData.ks = globalData["specularCoeff"].toDouble();
    }
    else {
        std::cout << "globalData specularCoeff must be a floating-point value" << std::endl;
        return false;
    }
    if (globalData.contains("transparentCoeff")) {
        if (globalData["transparentCoeff"].isDouble()) {
            m_globalData.kt = globalData["transparentCoeff"].toDouble();
        }
        else {
            std::cout << "globalData transparentCoeff must be a floating-point value" << std::endl;
            return false;
        }
    }

    return true;
}

/**
 * Parse a Light and add a new CS123SceneLightData to m_lights.
 */
bool ScenefileReader::parseLightData(const QJsonObject &lightData, SceneNode *node) {
    QStringList requiredFields = {"type", "color"};
    QStringList optionalFields = {"name", "attenuationCoeff", "direction", "penumbra", "angle", "width", "height"};
    QStringList allFields = requiredFields + optionalFields;
    for (auto &field : lightData.keys()) {
        if (!allFields.contains(field)) {
            std::cout << "unknown field \"" << field.toStdString() << "\" on light object" << std::endl;
            return false;
        }
    }
    for (auto &field : requiredFields) {
        if (!lightData.contains(field)) {
            std::cout << "missing required field \"" << field.toStdString() << "\" on light object" << std::endl;
            return false;
        }
    }

    // Create a default light
    SceneLight *light = new SceneLight();
    memset(light, 0, sizeof(SceneLight));
    node->lights.push_back(light);

    light->dir = glm::vec4(0.f, 0.f, 0.f, 0.f);
    light->function = glm::vec3(1, 0, 0);

    // parse the color
    if (!lightData["color"].isArray()) {
        std::cout << "light color must be of type array" << std::endl;
        return false;
    }
    QJsonArray colorArray = lightData["color"].toArray();
    if (colorArray.size() != 3) {
        std::cout << "light color must be of size 3" << std::endl;
        return false;
    }
    if (!colorArray[0].isDouble() || !colorArray[1].isDouble() || !colorArray[2].isDouble()) {
        std::cout << "light color must contain floating-point values" << std::endl;
        return false;
    }
    light->color.r = colorArray[0].toDouble();
    light->color.g = colorArray[1].toDouble();
    light->color.b = colorArray[2].toDouble();

    // parse the type
    if (!lightData["type"].isString()) {
        std::cout << "light type must be of type string" << std::endl;
        return false;
    }
    std::string lightType = lightData["type"].toString().toStdString();

    // parse directional light
    if (lightType == "directional") {
        light->type = LightType::LIGHT_DIRECTIONAL;

        // parse direction
        if (!lightData.contains("direction")) {
            std::cout << "directional light must contain field \"direction\"" << std::endl;
            return false;
        }
        if (!lightData["direction"].isArray()) {
            std::cout << "directional light direction must be of type array" << std::endl;
            return false;
        }
        QJsonArray directionArray = lightData["direction"].toArray();
        if (directionArray.size() != 3) {
            std::cout << "directional light direction must be of size 3" << std::endl;
            return false;
        }
        if (!directionArray[0].isDouble() || !directionArray[1].isDouble() || !directionArray[2].isDouble()) {
            std::cout << "directional light direction must contain floating-point values" << std::endl;
            return false;
        }
        light->dir.x = directionArray[0].toDouble();
        light->dir.y = directionArray[1].toDouble();
        light->dir.z = directionArray[2].toDouble();
    }
    else if (lightType == "point") {
        light->type = LightType::LIGHT_POINT;

        // parse the attenuation coefficient
        if (!lightData.contains("attenuationCoeff")) {
            std::cout << "point light must contain field \"attenuationCoeff\"" << std::endl;
            return false;
        }
        if (!lightData["attenuationCoeff"].isArray()) {
            std::cout << "point light attenuationCoeff must be of type array" << std::endl;
            return false;
        }
        QJsonArray attenuationArray = lightData["attenuationCoeff"].toArray();
        if (attenuationArray.size() != 3) {
            std::cout << "point light attenuationCoeff must be of size 3" << std::endl;
            return false;
        }
        if (!attenuationArray[0].isDouble() || !attenuationArray[1].isDouble() || !attenuationArray[2].isDouble()) {
            std::cout << "ppoint light attenuationCoeff must contain floating-point values" << std::endl;
            return false;
        }
        light->function.x = attenuationArray[0].toDouble();
        light->function.y = attenuationArray[1].toDouble();
        light->function.z = attenuationArray[2].toDouble();
    }
    else if (lightType == "spot") {
        QStringList pointRequiredFields = {"direction", "penumbra", "angle", "attenuationCoeff"};
        for (auto &field : pointRequiredFields) {
            if (!lightData.contains(field)) {
                std::cout << "missing required field \"" << field.toStdString() << "\" on spotlight object" << std::endl;
                return false;
            }
        }
        light->type = LightType::LIGHT_SPOT;

        // parse direction
        if (!lightData["direction"].isArray()) {
            std::cout << "spotlight direction must be of type array" << std::endl;
            return false;
        }
        QJsonArray directionArray = lightData["direction"].toArray();
        if (directionArray.size() != 3) {
            std::cout << "spotlight direction must be of size 3" << std::endl;
            return false;
        }
        if (!directionArray[0].isDouble() || !directionArray[1].isDouble() || !directionArray[2].isDouble()) {
            std::cout << "spotlight direction must contain floating-point values" << std::endl;
            return false;
        }
        light->dir.x = directionArray[0].toDouble();
        light->dir.y = directionArray[1].toDouble();
        light->dir.z = directionArray[2].toDouble();

        // parse attenuation coefficient
        if (!lightData["attenuationCoeff"].isArray()) {
            std::cout << "spotlight attenuationCoeff must be of type array" << std::endl;
            return false;
        }
        QJsonArray attenuationArray = lightData["attenuationCoeff"].toArray();
        if (attenuationArray.size() != 3) {
            std::cout << "spotlight attenuationCoeff must be of size 3" << std::endl;
            return false;
        }
        if (!attenuationArray[0].isDouble() || !attenuationArray[1].isDouble() || !attenuationArray[2].isDouble()) {
            std::cout << "spotlight direction must contain floating-point values" << std::endl;
            return false;
        }
        light->function.x = attenuationArray[0].toDouble();
        light->function.y = attenuationArray[1].toDouble();
        light->function.z = attenuationArray[2].toDouble();

        // parse penumbra
        if (!lightData["penumbra"].isDouble()) {
            std::cout << "spotlight penumbra must be of type float" << std::endl;
            return false;
        }
        light->penumbra = lightData["penumbra"].toDouble() * M_PI / 180.f;

        // parse angle
        if (!lightData["angle"].isDouble()) {
            std::cout << "spotlight angle must be of type float" << std::endl;
            return false;
        }
        light->angle = lightData["angle"].toDouble() * M_PI / 180.f;
    }
    else if (lightType == "area") {
        light->type = LightType::LIGHT_AREA;

        QStringList pointRequiredFields = {"width", "height"};
        for (auto &field : pointRequiredFields) {
            if (!lightData.contains(field)) {
                std::cout << "missing required field \"" << field.toStdString() << "\" on area light object" << std::endl;
                return false;
            }
        }

        // parse width
        if (!lightData["width"].isDouble()) {
            std::cout << "arealight penumbra must be of type float" << std::endl;
            return false;
        }
        light->width = lightData["width"].toDouble();

        // parse height
        if (!lightData["height"].isDouble()) {
            std::cout << "arealight height must be of type float" << std::endl;
            return false;
        }
        light->height = lightData["height"].toDouble();

        // parse the attenuation coefficient
        if (!lightData.contains("attenuationCoeff")) {
            std::cout << "area light must contain field \"attenuationCoeff\"" << std::endl;
            return false;
        }
        if (!lightData["attenuationCoeff"].isArray()) {
            std::cout << "area light attenuationCoeff must be of type array" << std::endl;
            return false;
        }
        QJsonArray attenuationArray = lightData["attenuationCoeff"].toArray();
        if (attenuationArray.size() != 3) {
            std::cout << "area light attenuationCoeff must be of size 3" << std::endl;
            return false;
        }
        if (!attenuationArray[0].isDouble() || !attenuationArray[1].isDouble() || !attenuationArray[2].isDouble()) {
            std::cout << "area light attenuationCoeff must contain floating-point values" << std::endl;
            return false;
        }
        light->function.x = attenuationArray[0].toDouble();
        light->function.y = attenuationArray[1].toDouble();
        light->function.z = attenuationArray[2].toDouble();
    }
    else {
        std::cout << "unknown light type \"" << lightType << "\"" << std::endl;
        return false;
    }

    return true;
}

/**
 * Parse cameraData and fill in m_cameraData.
 */
bool ScenefileReader::parseCameraData(const QJsonObject &cameradata) {
    QStringList requiredFields = {"position", "up", "heightAngle"};
    QStringList optionalFields = {"aperture", "focalLength", "look", "focus"};
    QStringList allFields = requiredFields + optionalFields;
    for (auto &field : cameradata.keys()) {
        if (!allFields.contains(field)) {
            std::cout << "unknown field \"" << field.toStdString() << "\" on cameraData object" << std::endl;
            return false;
        }
    }
    for (auto &field : requiredFields) {
        if (!cameradata.contains(field)) {
            std::cout << "missing required field \"" << field.toStdString() << "\" on cameraData object" << std::endl;
            return false;
        }
    }

    // Must have either look or focus, but not both
    if (cameradata.contains("look") && cameradata.contains("focus")) {
        std::cout << "cameraData cannot contain both \"look\" and \"focus\"" << std::endl;
        return false;
    }

    // Parse the camera data
    if (cameradata["position"].isArray()) {
        QJsonArray position = cameradata["position"].toArray();
        if (position.size() != 3 && position.size() != 4) {
            std::cout << "cameraData position must have 3-4 elements" << std::endl;
            return false;
        }
        if (!position[0].isDouble() || !position[1].isDouble() || !position[2].isDouble() || (position.size() == 4 && !position[3].isDouble())) {
            std::cout << "cameraData position must be a floating-point value" << std::endl;
            return false;
        }
        m_cameraData.pos.x = position[0].toDouble();
        m_cameraData.pos.y = position[1].toDouble();
        m_cameraData.pos.z = position[2].toDouble();
        if (position.size() == 4) {
            m_cameraData.pos.w = position[3].toDouble();
        }
        else {
            m_cameraData.pos.w = 1.f;
        }
    }
    else {
        std::cout << "cameraData position must be an array" << std::endl;
        return false;
    }

    if (cameradata["up"].isArray()) {
        QJsonArray up = cameradata["up"].toArray();
        if (up.size() != 3 && up.size() != 4) {
            std::cout << "cameraData up must have 3-4 elements" << std::endl;
            return false;
        }
        if (!up[0].isDouble() || !up[1].isDouble() || !up[2].isDouble() || (up.size() == 4 && !up[3].isDouble())) {
            std::cout << "cameraData up must be a floating-point value" << std::endl;
            return false;
        }
        m_cameraData.up.x = up[0].toDouble();
        m_cameraData.up.y = up[1].toDouble();
        m_cameraData.up.z = up[2].toDouble();
        if (up.size() == 4) {
            m_cameraData.up.w = up[3].toDouble();
        }
        else {
            m_cameraData.up.w = 1.f;
        }
    }
    else {
        std::cout << "cameraData up must be an array" << std::endl;
        return false;
    }

    if (cameradata["heightAngle"].isDouble()) {
        m_cameraData.heightAngle = cameradata["heightAngle"].toDouble() * M_PI / 180.f;
    }
    else {
        std::cout << "cameraData heightAngle must be a floating-point value" << std::endl;
        return false;
    }

    if (cameradata.contains("aperture")) {
        if (cameradata["aperture"].isDouble()) {
            m_cameraData.aperture = cameradata["aperture"].toDouble();
        }
        else {
            std::cout << "cameraData aperture must be a floating-point value" << std::endl;
            return false;
        }
    }

    if (cameradata.contains("focalLength")) {
        if (cameradata["focalLength"].isDouble()) {
            m_cameraData.focalLength = cameradata["focalLength"].toDouble();
        }
        else {
            std::cout << "cameraData focalLength must be a floating-point value" << std::endl;
            return false;
        }
    }

    // Parse the look or focus
    // if the focus is specified, we will convert it to a look vector later
    if (cameradata.contains("look")) {
        if (cameradata["look"].isArray()) {
            QJsonArray look = cameradata["look"].toArray();
            if (look.size() != 3 && look.size() != 4) {
                std::cout << "cameraData look must have 3-4 elements" << std::endl;
                return false;
            }
            if (!look[0].isDouble() || !look[1].isDouble() || !look[2].isDouble() || (look.size() == 4 && !look[3].isDouble())) {
                std::cout << "cameraData look must be a floating-point value" << std::endl;
                return false;
            }
            m_cameraData.look.x = look[0].toDouble();
            m_cameraData.look.y = look[1].toDouble();
            m_cameraData.look.z = look[2].toDouble();
            if (look.size() == 4) {
                m_cameraData.look.w = look[3].toDouble();
            }
            else {
                m_cameraData.look.w = 1.f;
            }
        }
        else {
            std::cout << "cameraData look must be an array" << std::endl;
            return false;
        }
    }
    else if (cameradata.contains("focus")) {
        if (cameradata["focus"].isArray()) {
            QJsonArray focus = cameradata["focus"].toArray();
            if (focus.size() != 3 && focus.size() != 4) {
                std::cout << "cameraData focus must have 3-4 elements" << std::endl;
                return false;
            }
            if (!focus[0].isDouble() || !focus[1].isDouble() || !focus[2].isDouble() || (focus.size() == 4 && !focus[3].isDouble())) {
                std::cout << "cameraData focus must be a floating-point value" << std::endl;
                return false;
            }
            m_cameraData.look.x = focus[0].toDouble();
            m_cameraData.look.y = focus[1].toDouble();
            m_cameraData.look.z = focus[2].toDouble();
            if (focus.size() == 4) {
                m_cameraData.look.w = focus[3].toDouble();
            }
            else {
                m_cameraData.look.w = 1.f;
            }
        }
        else {
            std::cout << "cameraData focus must be an array" << std::endl;
            return false;
        }
    }

    // Convert the focus point (stored in the look vector) into a
    // look vector from the camera position to that focus point.
    if (cameradata.contains("focus")) {
        m_cameraData.look -= m_cameraData.pos;
    }

    return true;
}

bool ScenefileReader::parseTemplateGroups(const QJsonValue &templateGroups) {
    if (!templateGroups.isArray()) {
        std::cout << "templateGroups must be an array" << std::endl;
        return false;
    }

    QJsonArray templateGroupsArray = templateGroups.toArray();
    for (auto templateGroup : templateGroupsArray) {
        if (!templateGroup.isObject()) {
            std::cout << "templateGroup items must be of type object" << std::endl;
            return false;
        }

        if (!parseTemplateGroupData(templateGroup.toObject())) {
            return false;
        }
    }

    return true;
}

bool ScenefileReader::parseTemplateGroupData(const QJsonObject &templateGroup) {
    QStringList requiredFields = {"name"};
    QStringList optionalFields = {"translate", "rotate", "scale", "matrix", "lights", "primitives", "groups"};
    QStringList allFields = requiredFields + optionalFields;
    for (auto &field : templateGroup.keys()) {
        if (!allFields.contains(field)) {
            std::cout << "unknown field \"" << field.toStdString() << "\" on templateGroup object" << std::endl;
            return false;
        }
    }

    for (auto &field : requiredFields) {
        if (!templateGroup.contains(field)) {
            std::cout << "missing required field \"" << field.toStdString() << "\" on templateGroup object" << std::endl;
            return false;
        }
    }

    if (!templateGroup["name"].isString()) {
        std::cout << "templateGroup name must be a string" << std::endl;
    }
    if (m_templates.contains(templateGroup["name"].toString().toStdString())) {
        std::cout << "templateGroups cannot have the same" << std::endl;
    }

    SceneNode *templateNode = new SceneNode;
    m_nodes.push_back(templateNode);
    m_templates[templateGroup["name"].toString().toStdString()] = templateNode;

    return parseGroupData(templateGroup, templateNode);
}

/**
 * Parse a group object and create a new CS123SceneNode in m_nodes.
 * NAME OF NODE CANNOT REFERENCE TEMPLATE NODE
 */
bool ScenefileReader::parseGroupData(const QJsonObject &object, SceneNode *node) {
    QStringList optionalFields = {"name", "translate", "rotate", "scale", "matrix", "lights", "primitives", "groups"};
    QStringList allFields = optionalFields;
    for (auto &field : object.keys()) {
        if (!allFields.contains(field)) {
            std::cout << "unknown field \"" << field.toStdString() << "\" on group object" << std::endl;
            return false;
        }
    }

    // parse translation if defined
    if (object.contains("translate")) {
        if (!object["translate"].isArray()) {
            std::cout << "group translate must be of type array" << std::endl;
            return false;
        }

        QJsonArray translateArray = object["translate"].toArray();
        if (translateArray.size() != 4 && translateArray.size() != 3) {
            std::cout << "group translate must have 3-4 elements" << std::endl;
            return false;
        }
        if (!translateArray[0].isDouble() || !translateArray[1].isDouble() || !translateArray[2].isDouble() || (translateArray.size() == 4 && !translateArray[3].isDouble())) {
            std::cout << "group translate must contain floating-point values" << std::endl;
            return false;
        }

        SceneTransformation *translation = new SceneTransformation();
        translation->type = TransformationType::TRANSFORMATION_TRANSLATE;
        translation->translate.x = translateArray[0].toDouble();
        translation->translate.y = translateArray[1].toDouble();
        translation->translate.z = translateArray[2].toDouble();
        if (translateArray.size() == 4)
            translation->translate.w = translateArray[3].toDouble();

        node->transformations.push_back(translation);
    }

    // parse rotation if defined
    if (object.contains("rotate")) {
        if (!object["rotate"].isArray()) {
            std::cout << "group rotate must be of type array" << std::endl;
            return false;
        }

        QJsonArray rotateArray = object["rotate"].toArray();
        if (rotateArray.size() != 7 && rotateArray.size() != 4) {
            std::cout << "group rotate must have 4 or 7 elements" << std::endl;
            return false;
        }
        if (!rotateArray[0].isDouble() || !rotateArray[1].isDouble() || !rotateArray[2].isDouble() || !rotateArray[3].isDouble() || (rotateArray.size() == 7 && (!rotateArray[4].isDouble() || !rotateArray[5].isDouble() || !rotateArray[6].isDouble()))) {
            std::cout << "group rotate must contain floating-point values" << std::endl;
            return false;
        }

        SceneTransformation *rotation = new SceneTransformation();
        rotation->type = TransformationType::TRANSFORMATION_ROTATE;
        rotation->rotate3.x = rotateArray[0].toDouble();
        rotation->rotate3.y = rotateArray[1].toDouble();
        rotation->rotate3.z = rotateArray[2].toDouble();
        if (rotateArray.size() == 7) {
            rotation->rotateW.x = rotateArray[4].toDouble();
            rotation->rotateW.y = rotateArray[5].toDouble();
            rotation->rotateW.z = rotateArray[6].toDouble();
        } else {
            rotation->rotateW.x = 0;
            rotation->rotateW.y = 0;
            rotation->rotateW.z = 0;
        }
        rotation->angle = rotateArray[(rotateArray.size() == 7) ? 3 : 6].toDouble() * M_PI / 180.f;

        node->transformations.push_back(rotation);
    }

    // parse scale if defined
    if (object.contains("scale")) {
        if (!object["scale"].isArray()) {
            std::cout << "group scale must be of type array" << std::endl;
            return false;
        }

        QJsonArray scaleArray = object["scale"].toArray();
        if (scaleArray.size() != 4 && scaleArray.size() != 3) {
            std::cout << "group scale must have 3-4 elements" << std::endl;
            return false;
        }
        if (!scaleArray[0].isDouble() || !scaleArray[1].isDouble() || !scaleArray[2].isDouble() || (scaleArray.size() == 4 && !scaleArray[3].isDouble())) {
            std::cout << "group scale must contain floating-point values" << std::endl;
            return false;
        }

        SceneTransformation *scale = new SceneTransformation();
        scale->type = TransformationType::TRANSFORMATION_SCALE;
        scale->scale.x = scaleArray[0].toDouble();
        scale->scale.y = scaleArray[1].toDouble();
        scale->scale.z = scaleArray[2].toDouble();
        if (scaleArray.size() == 4)
            scale->scale.w = scaleArray[3].toDouble();

        node->transformations.push_back(scale);
    }

    // parse matrix if defined
    if (object.contains("matrix")) {
        if (!object["matrix"].isArray()) {
            std::cout << "group matrix must be of type array of array" << std::endl;
            return false;
        }

        QJsonArray matrixArray = object["matrix"].toArray();
        if (matrixArray.size() != 5 && matrixArray.size() != 4) {
            std::cout << "group matrix must be 4x4 or 5x5" << std::endl;
            return false;
        }

        SceneTransformation *matrixTransformation = new SceneTransformation();
        matrixTransformation->type = TransformationType::TRANSFORMATION_MATRIX;

        float *matrixPtr = glm::value_ptr(matrixTransformation->matrix);
        float *matrixRightPtr = glm::value_ptr(matrixTransformation->matrixRight4d);
        int rowIndex = 0;
        for (auto row : matrixArray) {
            if (rowIndex == 4) break; // skip the last row

            if (!row.isArray()) {
                std::cout << "group matrix must be of type array of array" << std::endl;
                return false;
            }

            QJsonArray rowArray = row.toArray();
            if (rowArray.size() != 5 && rowArray.size() != 4) {
                std::cout << "group matrix must be 4x4 or 5x5" << std::endl;
                return false;
            }

            int colIndex = 0;
            for (auto val : rowArray) {
                if (!val.isDouble()) {
                    std::cout << "group matrix must contain all floating-point values" << std::endl;
                    return false;
                }

                // fill in column-wise
                if (colIndex == 4) {
                    matrixRightPtr[rowIndex] = (float)val.toDouble();
                } else {
                    matrixPtr[colIndex * 4 + rowIndex] = (float)val.toDouble();
                }
                colIndex++;
            }
            rowIndex++;
        }

        node->transformations.push_back(matrixTransformation);
    }

    // parse lights if any
    if (object.contains("lights")) {
        if (!object["lights"].isArray()) {
            std::cout << "group lights must be of type array" << std::endl;
            return false;
        }
        QJsonArray lightsArray = object["lights"].toArray();
        for (auto light : lightsArray) {
            if (!light.isObject()) {
                std::cout << "light must be of type object" << std::endl;
                return false;
            }

            if (!parseLightData(light.toObject(), node)) {
                return false;
            }
        }
    }

    // parse primitives if any
    if (object.contains("primitives")) {
        if (!object["primitives"].isArray()) {
            std::cout << "group primitives must be of type array" << std::endl;
            return false;
        }
        QJsonArray primitivesArray = object["primitives"].toArray();
        for (auto primitive : primitivesArray) {
            if (!primitive.isObject()) {
                std::cout << "primitive must be of type object" << std::endl;
                return false;
            }

            if (!parsePrimitive(primitive.toObject(), node)) {
                return false;
            }
        }
    }

    // parse children groups if any
    if (object.contains("groups")) {
        if (!parseGroups(object["groups"], node)) {
            return false;
        }
    }

    return true;
}

bool ScenefileReader::parseGroups(const QJsonValue &groups, SceneNode *parent) {
    if (!groups.isArray()) {
        std::cout << "groups must be of type array" << std::endl;
        return false;
    }

    QJsonArray groupsArray = groups.toArray();
    for (auto group : groupsArray) {
        if (!group.isObject()) {
            std::cout << "group items must be of type object" << std::endl;
            return false;
        }

        QJsonObject groupData = group.toObject();
        if (groupData.contains("name")) {
            if (!groupData["name"].isString()) {
                std::cout << "group name must be of type string" << std::endl;
                return false;
            }

            // if its a reference to a template group append it
            std::string groupName = groupData["name"].toString().toStdString();
            if (m_templates.contains(groupName)) {
                parent->children.push_back(m_templates[groupName]);
                continue;
            }
        }

        SceneNode *node = new SceneNode;
        m_nodes.push_back(node);
        parent->children.push_back(node);

        if (!parseGroupData(group.toObject(), node)) {
            return false;
        }
    }

    return true;
}

/**
 * Parse an <object type="primitive"> tag into node.
 */
bool ScenefileReader::parsePrimitive(const QJsonObject &prim, SceneNode *node) {
    QStringList requiredFields = {"type"};
    QStringList optionalFields = {
        "meshFile", "ambient", "diffuse", "specular", "reflective", "transparent", "shininess", "ior",
        "blend", "textureFile", "textureU", "textureV", "bumpMapFile", "bumpMapU", "bumpMapV"};

    QStringList allFields = requiredFields + optionalFields;
    for (auto field : prim.keys()) {
        if (!allFields.contains(field)) {
            std::cout << "unknown field \"" << field.toStdString() << "\" on primitive object" << std::endl;
            return false;
        }
    }
    for (auto field : requiredFields) {
        if (!prim.contains(field)) {
            std::cout << "missing required field \"" << field.toStdString() << "\" on primitive object" << std::endl;
            return false;
        }
    }

    if (!prim["type"].isString()) {
        std::cout << "primitive type must be of type string" << std::endl;
        return false;
    }
    std::string primType = prim["type"].toString().toStdString();

    // Default primitive
    ScenePrimitive *primitive = new ScenePrimitive();
    SceneMaterial &mat = primitive->material;
    mat.clear();
    primitive->type = PrimitiveType::PRIMITIVE_CUBE;
    mat.textureMap.isUsed = false;
    mat.bumpMap.isUsed = false;
    mat.cDiffuse.r = mat.cDiffuse.g = mat.cDiffuse.b = 1;
    node->primitives.push_back(primitive);

    std::filesystem::path basepath = std::filesystem::path(file_name).parent_path().parent_path();
    if (primType == "sphere")
        primitive->type = PrimitiveType::PRIMITIVE_SPHERE;
    else if (primType == "cube")
        primitive->type = PrimitiveType::PRIMITIVE_CUBE;
    else if (primType == "cylinder")
        primitive->type = PrimitiveType::PRIMITIVE_CYLINDER;
    else if (primType == "cone")
        primitive->type = PrimitiveType::PRIMITIVE_CONE;
    else if (primType == "mesh") {
        primitive->type = PrimitiveType::PRIMITIVE_MESH;
        if (!prim.contains("meshFile")) {
            std::cout << "primitive type mesh must contain field meshFile" << std::endl;
            return false;
        }
        if (!prim["meshFile"].isString()) {
            std::cout << "primitive meshFile must be of type string" << std::endl;
            return false;
        }

        std::filesystem::path relativePath(prim["meshFile"].toString().toStdString());
        primitive->meshfile = (basepath / relativePath).string();
    }
    else {
        std::cout << "unknown primitive type \"" << primType << "\"" << std::endl;
        return false;
    }

    if (prim.contains("ambient")) {
        if (!prim["ambient"].isArray()) {
            std::cout << "primitive ambient must be of type array" << std::endl;
            return false;
        }
        QJsonArray ambientArray = prim["ambient"].toArray();
        if (ambientArray.size() != 3) {
            std::cout << "primitive ambient array must be of size 3" << std::endl;
            return false;
        }

        for (int i = 0; i < 3; i++) {
            if (!ambientArray[i].isDouble()) {
                std::cout << "primitive ambient must contain floating-point values" << std::endl;
                return false;
            }

            mat.cAmbient[i] = ambientArray[i].toDouble();
        }
    }

    if (prim.contains("diffuse")) {
        if (!prim["diffuse"].isArray()) {
            std::cout << "primitive diffuse must be of type array" << std::endl;
            return false;
        }
        QJsonArray diffuseArray = prim["diffuse"].toArray();
        if (diffuseArray.size() != 3) {
            std::cout << "primitive diffuse array must be of size 3" << std::endl;
            return false;
        }

        for (int i = 0; i < 3; i++) {
            if (!diffuseArray[i].isDouble()) {
                std::cout << "primitive diffuse must contain floating-point values" << std::endl;
                return false;
            }

            mat.cDiffuse[i] = diffuseArray[i].toDouble();
        }
    }

    if (prim.contains("specular")) {
        if (!prim["specular"].isArray()) {
            std::cout << "primitive specular must be of type array" << std::endl;
            return false;
        }
        QJsonArray specularArray = prim["specular"].toArray();
        if (specularArray.size() != 3) {
            std::cout << "primitive specular array must be of size 3" << std::endl;
            return false;
        }

        for (int i = 0; i < 3; i++) {
            if (!specularArray[i].isDouble()) {
                std::cout << "primitive specular must contain floating-point values" << std::endl;
                return false;
            }

            mat.cSpecular[i] = specularArray[i].toDouble();
        }
    }

    if (prim.contains("reflective")) {
        if (!prim["reflective"].isArray()) {
            std::cout << "primitive reflective must be of type array" << std::endl;
            return false;
        }
        QJsonArray reflectiveArray = prim["reflective"].toArray();
        if (reflectiveArray.size() != 3) {
            std::cout << "primitive reflective array must be of size 3" << std::endl;
            return false;
        }

        for (int i = 0; i < 3; i++) {
            if (!reflectiveArray[i].isDouble()) {
                std::cout << "primitive reflective must contain floating-point values" << std::endl;
                return false;
            }

            mat.cReflective[i] = reflectiveArray[i].toDouble();
        }
    }

    if (prim.contains("transparent")) {
        if (!prim["transparent"].isArray()) {
            std::cout << "primitive transparent must be of type array" << std::endl;
            return false;
        }
        QJsonArray transparentArray = prim["transparent"].toArray();
        if (transparentArray.size() != 3) {
            std::cout << "primitive transparent array must be of size 3" << std::endl;
            return false;
        }

        for (int i = 0; i < 3; i++) {
            if (!transparentArray[i].isDouble()) {
                std::cout << "primitive transparent must contain floating-point values" << std::endl;
                return false;
            }

            mat.cTransparent[i] = transparentArray[i].toDouble();
        }
    }

    if (prim.contains("shininess")) {
        if (!prim["shininess"].isDouble()) {
            std::cout << "primitive shininess must be of type float" << std::endl;
            return false;
        }

        mat.shininess = (float) prim["shininess"].toDouble();
    }

    if (prim.contains("ior")) {
        if (!prim["ior"].isDouble()) {
            std::cout << "primitive ior must be of type float" << std::endl;
            return false;
        }

        mat.ior = (float) prim["ior"].toDouble();
    }

    if (prim.contains("blend")) {
        if (!prim["blend"].isDouble()) {
            std::cout << "primitive blend must be of type float" << std::endl;
            return false;
        }

        mat.blend = (float)prim["blend"].toDouble();
    }

    if (prim.contains("textureFile")) {
        if (!prim["textureFile"].isString()) {
            std::cout << "primitive textureFile must be of type string" << std::endl;
            return false;
        }
        std::filesystem::path fileRelativePath(prim["textureFile"].toString().toStdString());

        mat.textureMap.filename = (basepath / fileRelativePath).string();
        mat.textureMap.repeatU = prim.contains("textureU") && prim["textureU"].isDouble() ? prim["textureU"].toDouble() : 1;
        mat.textureMap.repeatV = prim.contains("textureV") && prim["textureV"].isDouble() ? prim["textureV"].toDouble() : 1;
        mat.textureMap.isUsed = true;
    }

    if (prim.contains("bumpMapFile")) {
        if (!prim["bumpMapFile"].isString()) {
            std::cout << "primitive bumpMapFile must be of type string" << std::endl;
            return false;
        }
        std::filesystem::path fileRelativePath(prim["bumpMapFile"].toString().toStdString());

        mat.bumpMap.filename = (basepath / fileRelativePath).string();
        mat.bumpMap.repeatU = prim.contains("bumpMapU") && prim["bumpMapU"].isDouble() ? prim["bumpMapU"].toDouble() : 1;
        mat.bumpMap.repeatV = prim.contains("bumpMapV") && prim["bumpMapV"].isDouble() ? prim["bumpMapV"].toDouble() : 1;
        mat.bumpMap.isUsed = true;
    }

    return true;
}