More silly mistakes
[laserbrain_demo] / src / metascene.cc
1 /*! \file
2  * \brief Metascene implementation
3  *
4  * Loading starts at `MetaScene::load`, which calls `ts_load` (libtreestore)
5  * to load the metascene description tree into memory. Then `proc_node` is
6  * called at the root to recursively process the tree. `scenefile` nodes are
7  * handed over to `proc_scenefile`, which will trigger scene loading for any
8  * nodes with a `file` attribute. Scene loading is handled by requesting the
9  * filename from the scene resource manager, which is of type [SceneSet](\ref SceneSet).
10  */
11 #include <assert.h>
12 #include <string>
13 #include <regex>
14 #include "metascene.h"
15 #include "scene.h"
16 #include "objmesh.h"
17 #include "treestore.h"
18 #include "logger.h"
19 #include "app.h"
20 #include "dbg_gui.h"
21
22 #if defined(WIN32) || defined(__WIN32__)
23 #include <malloc.h>
24 #else
25 #include <alloca.h>
26 #endif
27
28 enum MaterialEditType {
29         MTL_EDIT_TEXTURE,
30         MTL_EDIT_MIRROR
31 };
32
33 struct MaterialEditTexture {
34         int attr;
35         Texture *tex;
36 };
37
38 struct MaterialEditMirror {
39         float reflectivity;
40         int plane;
41 };
42
43 struct MaterialEdit {
44         std::regex name_re;
45         MaterialEditType type;
46
47         MaterialEditTexture tex;
48         MaterialEditMirror mirror;
49 };
50
51 static bool proc_node(MetaScene *mscn, struct ts_node *node);
52 static bool proc_scenefile(MetaScene *mscn, struct ts_node *node);
53 static bool proc_mtledit(MetaScene *mscn, MaterialEdit *med, struct ts_node *node);
54 static bool proc_music(MetaScene *mscn, struct ts_node *node);
55 static void apply_mtledit(Scene *scn, const MaterialEdit &med);
56 static void apply_mtledit(Material *mtl, const MaterialEdit &med);
57 static struct ts_attr *attr_inscope(struct ts_node *node, const char *name);
58
59 static void print_scene_graph(SceneNode *n, int level);
60
61
62 MetaScene::MetaScene()
63 {
64         walk_mesh = 0;
65         music = 0;
66         mirrors = 0;
67 }
68
69 MetaScene::~MetaScene()
70 {
71         delete walk_mesh;
72         delete music;
73
74         while(mirrors) {
75                 FlatMirror *m = mirrors;
76                 mirrors = mirrors->next;
77                 delete m;
78         }
79 }
80
81 bool MetaScene::load(const char *fname)
82 {
83         struct ts_node *root = ts_load(fname);
84         if(!root || strcmp(root->name, "scene") != 0) {
85                 ts_free_tree(root);
86                 error_log("failed to load scene metadata: %s\n", fname);
87                 return false;
88         }
89
90         bool res = proc_node(this, root);
91         ts_free_tree(root);
92
93         /*info_log("loaded scene: %s\n", fname);
94         info_log("scene graph:\n");
95         print_scene_graph(scn->nodes, 0);
96         */
97         return res;
98 }
99
100 void MetaScene::update(float dt)
101 {
102         bool expanded;
103         static char text[256];
104         if(debug_gui) {
105                 ImGui::Begin("MetaScene nodes", 0, 0);
106                 ImGui::Columns(2);
107
108                 static bool once;
109                 if(!once) {
110                         float x = ImGui::GetColumnOffset(1);
111                         ImGui::SetColumnOffset(1, x * 1.55);
112                         once = true;
113                 }
114         }
115
116         int nscn = scenes.size();
117         for(int i=0; i<nscn; i++) {
118
119                 if(debug_gui) {
120                         if(scenes[i]->name.empty()) {
121                                 sprintf(text, "scene %3d", i);
122                         } else {
123                                 sprintf(text, "scene %3d: %s", i, scenes[i]->name.c_str());
124                         }
125                         expanded = parent_expanded = ImGui::TreeNode(text);
126                         ImGui::NextColumn();
127                         ImGui::NextColumn();
128                 }
129
130                 scenes[i]->update(dt);
131
132                 if(debug_gui && expanded) {
133                         ImGui::TreePop();
134                 }
135         }
136
137         if(debug_gui) {
138                 ImGui::Columns(1);
139                 ImGui::End();
140         }
141 }
142
143 // XXX not used, renderer draws
144 void MetaScene::draw() const
145 {
146         error_log("Don't call MetaScene::draw, use the Renderer\n");
147         int nscn = scenes.size();
148         for(int i=0; i<nscn; i++) {
149                 scenes[i]->draw();
150         }
151 }
152
153 SceneNode *MetaScene::find_node(const char *name) const
154 {
155         int num = scenes.size();
156         for(int i=0; i<num; i++) {
157                 SceneNode *n = scenes[i]->find_node(name);
158                 if(n) return n;
159         }
160         return 0;
161 }
162
163 SceneNode *MetaScene::match_node(const char *qstr) const
164 {
165         int num = scenes.size();
166         for(int i=0; i<num; i++) {
167                 SceneNode *n = scenes[i]->match_node(qstr);
168                 if(n) return n;
169         }
170         return 0;
171 }
172
173 std::list<SceneNode*> MetaScene::match_nodes(const char *qstr) const
174 {
175         std::list<SceneNode*> res;
176         int num = scenes.size();
177         for(int i=0; i<num; i++) {
178                 std::list<SceneNode*> tmp = scenes[i]->match_nodes(qstr);
179                 if(!tmp.empty()) {
180                         res.splice(res.end(), tmp);
181                 }
182         }
183         return res;     // hopefully it'll be moved
184 }
185
186 Scene *MetaScene::extract_nodes(const char *qstr)
187 {
188         Scene *scn = 0;
189         int nscn = scenes.size();
190         for(int i=0; i<nscn; i++) {
191                 Scene *tmp = scenes[i]->extract_nodes(qstr);
192                 if(tmp) {
193                         if(!scn) {
194                                 scn = tmp;
195                         } else {
196                                 scn->merge(tmp);
197                                 delete tmp;
198                         }
199                 }
200         }
201         return scn;
202 }
203
204 int MetaScene::calc_mirror_planes()
205 {
206         int num_mirrors = 0;
207         while(mirrors) {
208                 FlatMirror *m = mirrors;
209                 mirrors = mirrors->next;
210                 delete m;
211         }
212         mirrors = 0;
213         objmirror.clear();
214
215         int numscn = scenes.size();
216         for(int i=0; i<numscn; i++) {
217                 Scene *scn = scenes[i];
218
219                 int numobj = scn->objects.size();
220                 for(int j=0; j<numobj; j++) {
221                         Object *obj = scn->objects[j];
222
223                         if(obj->mtl.flat_mirror && obj->get_type() == OBJ_MESH) {
224                                 const Mesh *mesh = ((ObjMesh*)obj)->mesh;
225                                 if(!mesh) continue;
226
227                                 FlatMirror *mir = new FlatMirror;
228                                 mir->reflect = obj->mtl.reflect;
229                                 mir->node = obj->node;
230
231                                 if(obj->mtl.flat_mirror == MTL_MIRROR_AUTO) {
232                                         // grab the first triangle and make a plane
233                                         Triangle face = Triangle(0, (const Vec3*)mesh->get_attrib_data(MESH_ATTR_VERTEX),
234                                                         mesh->get_index_data());
235                                         face.calc_normal();
236
237                                         mir->plane.pt = face.v[0];
238                                         mir->plane.normal = face.normal;
239                                 } else {
240                                         int plane_idx = obj->mtl.flat_mirror - MTL_MIRROR_AABB_PX;
241                                         mir->plane = obj->get_aabox().get_plane(plane_idx);
242                                 }
243
244                                 mir->wplane = mir->plane;
245                                 if(obj->node) {
246                                         const Mat4 &xform = obj->node->get_matrix();
247                                         mir->wplane.pt = xform * mir->wplane.pt;
248                                         mir->wplane.normal = normalize(xform.upper3x3() * mir->wplane.normal);
249                                 }
250
251                                 // check to see if we have found this mirror plane already
252                                 bool found = false;
253                                 FlatMirror *node = mirrors;
254                                 while(node) {
255                                         float d1 = dot(mir->wplane.normal, mir->wplane.pt);
256                                         float d2 = dot(node->wplane.normal, node->wplane.pt);
257
258                                         if(1.0f - dot(mir->wplane.normal, node->wplane.normal) < 1e-4f &&
259                                                         fabs(d1 - d2) < 1e-4) {
260                                                 found = true;
261                                                 break;
262                                         }
263                                         node = node->next;
264                                 }
265
266                                 debug_log("[%s@%s] mirror plane: local(%g %g %g %g), world(%g %g %g %g)%s\n",
267                                                 obj->get_name(), obj->node ? obj->node->get_name() : "<no-node>",
268                                                 mir->plane.normal.x, mir->plane.normal.y, mir->plane.normal.z,
269                                                 dot(mir->plane.normal, mir->plane.pt), mir->wplane.normal.x, mir->wplane.normal.y,
270                                                 mir->wplane.normal.z, dot(mir->wplane.normal, mir->wplane.pt), found ? " duplicate" : "");
271
272                                 if(!found) {
273                                         mir->next = mirrors;
274                                         mirrors = mir;
275
276                                         mir->objects.push_back(obj);
277                                         objmirror[obj] = mir;   // associate with object
278                                         ++num_mirrors;
279                                 } else {
280                                         node->objects.push_back(obj);
281                                         delete mir;
282                                 }
283                         }
284                 }
285         }
286
287         return num_mirrors;
288 }
289
290 static bool proc_node(MetaScene *mscn, struct ts_node *node)
291 {
292         struct ts_node *c = node->child_list;
293         while(c) {
294                 if(!proc_node(mscn, c)) {
295                         return false;
296                 }
297                 c = c->next;
298         }
299
300         // do this last to allow other contents of the node to do their thing
301         if(strcmp(node->name, "scenefile") == 0) {
302                 return proc_scenefile(mscn, node);
303
304         } else if(strcmp(node->name, "remap") == 0) {
305                 const char *match = ts_get_attr_str(node, "match");
306                 const char *replace = ts_get_attr_str(node, "replace");
307                 if(match && replace) {
308                         mscn->datamap.map(match, replace);
309                 }
310
311         } else if(strcmp(node->name, "music") == 0) {
312                 return proc_music(mscn, node);
313         }
314
315         return true;
316 }
317
318
319
320 struct SceneData {
321         MetaScene *meta;
322         std::string walkmesh_regexp, spawn_regexp;
323         std::vector<MaterialEdit> mtledit;
324 };
325
326 /*! Processes a `scenefile` node. And kicks off scene loading (if necessary) by
327  * calling `SceneSet::get`.
328  */
329 static bool proc_scenefile(MetaScene *mscn, struct ts_node *node)
330 {
331         const char *fname = ts_get_attr_str(node, "file");
332         if(fname) {
333                 SceneData *sdat = new SceneData;
334                 sdat->meta = mscn;
335
336                 // datapath
337                 struct ts_attr *adpath = attr_inscope(node, "datapath");
338                 if(adpath && adpath->val.type == TS_STRING) {
339                         mscn->datamap.set_path(adpath->val.str);
340                 }
341
342                 // strip path
343                 struct ts_attr *aspath = attr_inscope(node, "strip_path");
344                 if(aspath && aspath->val.type == TS_NUMBER) {
345                         mscn->datamap.set_strip(aspath->val.inum);
346                 }
347
348                 // walkmesh
349                 struct ts_attr *awmesh = attr_inscope(node, "walkmesh");
350                 if(awmesh && awmesh->val.type == TS_STRING) {
351                         sdat->walkmesh_regexp = std::string(awmesh->val.str);
352                 }
353
354                 // spawn node
355                 struct ts_attr *awspawn = attr_inscope(node, "spawn");
356                 if(awspawn) {
357                         switch(awspawn->val.type) {
358                         case TS_VECTOR:
359                                 mscn->start_pos = Vec3(awspawn->val.vec[0], awspawn->val.vec[1],
360                                                 awspawn->val.vec[2]);
361                                 break;
362
363                         case TS_STRING:
364                         default:
365                                 sdat->spawn_regexp = std::string(awspawn->val.str);
366                         }
367                 }
368                 if((awspawn = attr_inscope(node, "spawn_rot")) && awspawn->val.type == TS_VECTOR) {
369                         Quat rot;
370                         rot.rotate(Vec3(1, 0, 0), deg_to_rad(awspawn->val.vec[0]));
371                         rot.rotate(Vec3(0, 1, 0), deg_to_rad(awspawn->val.vec[1]));
372                         rot.rotate(Vec3(0, 0, 1), deg_to_rad(awspawn->val.vec[2]));
373                         mscn->start_rot = rot;
374                 }
375
376                 int namesz = mscn->datamap.lookup(fname, 0, 0);
377                 char *namebuf = (char*)alloca(namesz + 1);
378                 if(mscn->datamap.lookup(fname, namebuf, namesz + 1)) {
379                         fname = namebuf;
380                 }
381
382                 // material edits are kept in a list to be applied when the scene has been loaded
383                 struct ts_node *child = node->child_list;
384                 while(child) {
385                         MaterialEdit medit;
386                         if(proc_mtledit(mscn, &medit, child)) {
387                                 sdat->mtledit.push_back(medit);
388                         }
389                         child = child->next;
390                 }
391
392                 Scene *newscn = sceneman.get(fname);
393                 /* NOTE: setting all these after get() is not a race condition, because
394                  * scene_loaded() which uses this, will only run in our main loop during
395                  * SceneSet::update() on the main thread.
396                  */
397                 newscn->datamap = mscn->datamap;
398                 mscn->datamap.clear();
399
400                 newscn->metascn = mscn;
401                 mscn->scndata[newscn] = sdat;
402         }
403         return true;
404 }
405
406 bool MetaScene::scene_loaded(Scene *newscn)
407 {
408         SceneData *sdat = (SceneData*)scndata[newscn];
409         if(!sdat) {
410                 error_log("MetaScene::scene_loaded called, but corresponding SceneData not found\n");
411                 return false;
412         }
413
414         // extract the walk mesh if necessary
415         Scene *wscn;
416         if(!sdat->walkmesh_regexp.empty() && (wscn = newscn->extract_nodes(sdat->walkmesh_regexp.c_str()))) {
417                 // apply all transformations to the meshes
418                 wscn->apply_xform();
419
420                 int nmeshes = wscn->meshes.size();
421                 for(int i=0; i<nmeshes; i++) {
422                         Mesh *m = wscn->meshes[i];
423
424                         if(walk_mesh) {
425                                 walk_mesh->append(*m);
426                         } else {
427                                 walk_mesh = m;
428                                 wscn->remove_mesh(m);   // to save it from destruction
429                         }
430                 }
431
432                 delete wscn;
433         }
434
435         // extract the spawn node
436         if(!sdat->spawn_regexp.empty() && (wscn = newscn->extract_nodes(sdat->spawn_regexp.c_str()))) {
437
438                 int nmeshes = wscn->meshes.size();
439                 int nnodes = wscn->nodes ? wscn->nodes->get_num_children() : 0;
440
441                 if(nmeshes) {
442                         Vec3 pos;
443                         for(int i=0; i<nmeshes; i++) {
444                                 const Sphere &bsph = wscn->meshes[i]->get_bsphere();
445                                 pos += bsph.center;
446                         }
447                         pos /= (float)nmeshes;
448                         sdat->meta->start_pos = pos;
449
450                 } else if(nnodes) {
451                         // just use the first one
452                         SceneNode *first = wscn->nodes->get_child(0);
453                         sdat->meta->start_pos = first->get_position();
454                         sdat->meta->start_rot = first->get_rotation();
455                 }
456                 delete wscn;
457         }
458
459         int num_medits = sdat->mtledit.size();
460         for(int i=0; i<num_medits; i++) {
461                 // perform material edits
462                 apply_mtledit(newscn, sdat->mtledit[i]);
463         }
464
465         scenes.push_back(newscn);
466         return true;
467 }
468
469 static bool proc_mtledit(MetaScene *mscn, MaterialEdit *med, struct ts_node *node)
470 {
471         if(strcmp(node->name, "mtledit") != 0) {
472                 return false;
473         }
474
475         const char *restr = ".*";
476         struct ts_attr *amtl = ts_get_attr(node, "material");
477         if(amtl && amtl->val.type == TS_STRING) {
478                 restr = amtl->val.str;
479         }
480         med->name_re = std::regex(restr);
481
482         node = node->child_list;
483         while(node) {
484                 struct ts_node *cn = node;
485                 node = node->next;
486
487                 if(strcmp(cn->name, "texture") == 0) {
488                         // add/change/remove a texture
489                         struct ts_attr *atype = ts_get_attr(cn, "type");
490                         struct ts_attr *afile = ts_get_attr(cn, "file");
491
492                         int textype = MTL_TEX_DIFFUSE;
493                         if(atype) {
494                                 if(atype->val.type == TS_STRING) {
495                                         textype = mtl_parse_type(atype->val.str);
496                                 } else if(atype->val.type == TS_NUMBER) {
497                                         textype = atype->val.inum;
498                                         if(textype < 0 || textype >= NUM_MTL_TEXTURES) {
499                                                 error_log("invalid texture in mtledit: %d\n", textype);
500                                                 continue;
501                                         }
502                                 } else {
503                                         error_log("unexpected texture type in mtledit: %s\n", atype->val.str);
504                                         continue;
505                                 }
506                         }
507
508                         med->tex.attr = textype;
509
510                         if(!afile || !afile->val.str || !*afile->val.str) {
511                                 // remove
512                                 med->tex.tex = 0;
513                         } else {
514                                 med->tex.tex = texman.get_texture(afile->val.str, TEX_2D, &mscn->datamap);
515                         }
516
517                         med->type = MTL_EDIT_TEXTURE;
518                         break;
519                 }
520
521                 if(strcmp(cn->name, "mirror") == 0) {
522                         // make this object a flat mirror (hopefully the object is flat otherwise this won't work)
523                         float refl = 1.0f;
524                         int plane = MTL_MIRROR_AUTO;
525
526                         struct ts_attr *aplane = ts_get_attr(cn, "plane");
527                         if(aplane) {
528                                 if(aplane->val.type == TS_NUMBER) {
529                                         plane = MTL_MIRROR_AABB_PX + aplane->val.inum;
530                                 } else {
531                                         char csign, caxis;
532                                         if(sscanf(aplane->val.str, "aabb%c%c", &csign, &caxis) != 2 || (csign != '+' && csign != '-')) {
533                                                 error_log("invalid reflect plane specifier: %s\n", aplane->val.str);
534                                                 continue;
535                                         }
536
537                                         switch(tolower(caxis)) {
538                                         case 'x':
539                                                 plane = csign == '+' ? MTL_MIRROR_AABB_PX : MTL_MIRROR_AABB_NX;
540                                                 break;
541                                         case 'y':
542                                                 plane = csign == '+' ? MTL_MIRROR_AABB_PY : MTL_MIRROR_AABB_NY;
543                                                 break;
544                                         case 'z':
545                                                 plane = csign == '+' ? MTL_MIRROR_AABB_PZ : MTL_MIRROR_AABB_NZ;
546                                                 break;
547                                         default:
548                                                 error_log("invalid reflect plane specifier: %s\n", aplane->val.str);
549                                                 continue;
550                                         }
551                                 }
552                         }
553
554                         struct ts_attr *arefl = ts_get_attr(cn, "reflect");
555                         if(arefl) {
556                                 if(arefl->val.type == TS_NUMBER) {
557                                         refl = arefl->val.fnum;
558                                 } else {
559                                         error_log("invalid reflect attribute in mirror mtledit: %s\n", arefl->val.str);
560                                         continue;
561                                 }
562                         }
563
564                         med->type = MTL_EDIT_MIRROR;
565                         med->mirror.reflectivity = refl;
566                         med->mirror.plane = plane;
567                         break;
568                 }
569         }
570
571         return true;
572 }
573
574 static void apply_mtledit(Scene *scn, const MaterialEdit &med)
575 {
576         // search all the objects to find matching material names
577         int nobj = scn->objects.size();
578         for(int i=0; i<nobj; i++) {
579                 Object *obj = scn->objects[i];
580                 if(std::regex_match(obj->mtl.name, med.name_re)) {
581                         apply_mtledit(&obj->mtl, med);
582                 }
583         }
584 }
585
586 static bool proc_music(MetaScene *mscn, struct ts_node *node)
587 {
588         const char *fname = ts_get_attr_str(node, "file");
589         if(fname) {
590                 SceneData *sdat = new SceneData;
591                 sdat->meta = mscn;
592
593                 // datapath
594                 struct ts_attr *adpath = attr_inscope(node, "datapath");
595                 if(adpath && adpath->val.type == TS_STRING) {
596                         mscn->datamap.set_path(adpath->val.str);
597                 }
598
599                 int namesz = mscn->datamap.lookup(fname, 0, 0);
600                 char *namebuf = (char*)alloca(namesz + 1);
601                 if(mscn->datamap.lookup(fname, namebuf, namesz + 1)) {
602                         fname = namebuf;
603                 }
604
605                 OggVorbisStream *ovstream = new OggVorbisStream;
606                 if(!ovstream->open(fname)) {
607                         delete ovstream;
608                         return false;
609                 }
610
611                 delete mscn->music;
612                 mscn->music = ovstream;
613         }
614         return true;
615 }
616
617 static void apply_mtledit(Material *mtl, const MaterialEdit &med)
618 {
619         // TODO more edit modes...
620         switch(med.type) {
621         case MTL_EDIT_TEXTURE:
622                 if(med.tex.tex) {
623                         mtl->add_texture(med.tex.tex, med.tex.attr);
624                 } else {
625                         Texture *tex = mtl->stdtex[med.tex.attr];
626                         if(tex) {
627                                 mtl->remove_texture(tex);
628                         }
629                 }
630                 break;
631
632         case MTL_EDIT_MIRROR:
633                 mtl->flat_mirror = med.mirror.plane;
634                 mtl->reflect = med.mirror.reflectivity;
635                 break;
636         }
637 }
638
639 static struct ts_attr *attr_inscope(struct ts_node *node, const char *name)
640 {
641         struct ts_attr *attr = 0;
642
643         while(node && !(attr = ts_get_attr(node, name))) {
644                 node = node->parent;
645         }
646         return attr;
647 }
648
649 static void print_scene_graph(SceneNode *n, int level)
650 {
651         if(!n) return;
652
653         for(int i=0; i<level; i++) {
654                 info_log("  ");
655         }
656
657         int nobj = n->get_num_objects();
658         if(nobj) {
659                 info_log("%s - %d obj\n", n->get_name(), n->get_num_objects());
660         } else {
661                 info_log("%s\n", n->get_name());
662         }
663
664         for(int i=0; i<n->get_num_children(); i++) {
665                 print_scene_graph(n->get_child(i), level + 1);
666         }
667 }