fd4569b17beaa9b888a2277660952d3951ebb324
[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 "treestore.h"
17 #include "logger.h"
18 #include "app.h"
19
20 #if defined(WIN32) || defined(__WIN32__)
21 #include <malloc.h>
22 #else
23 #include <alloca.h>
24 #endif
25
26 struct MaterialEdit {
27         std::regex name_re;
28         int attr;
29         Texture *tex;
30 };
31
32 static bool proc_node(MetaScene *mscn, struct ts_node *node);
33 static bool proc_scenefile(MetaScene *mscn, struct ts_node *node);
34 static bool proc_mtledit(MetaScene *mscn, MaterialEdit *med, struct ts_node *node);
35 static bool proc_music(MetaScene *mscn, struct ts_node *node);
36 static void apply_mtledit(Scene *scn, const MaterialEdit &med);
37 static void apply_mtledit(Material *mtl, const MaterialEdit &med);
38 static struct ts_attr *attr_inscope(struct ts_node *node, const char *name);
39
40 static void print_scene_graph(SceneNode *n, int level);
41
42
43 MetaScene::MetaScene()
44 {
45         walk_mesh = 0;
46         music = 0;
47 }
48
49 MetaScene::~MetaScene()
50 {
51         delete walk_mesh;
52         delete music;
53 }
54
55 bool MetaScene::load(const char *fname)
56 {
57         struct ts_node *root = ts_load(fname);
58         if(!root || strcmp(root->name, "scene") != 0) {
59                 ts_free_tree(root);
60                 error_log("failed to load scene metadata: %s\n", fname);
61                 return false;
62         }
63
64         bool res = proc_node(this, root);
65         ts_free_tree(root);
66
67         /*info_log("loaded scene: %s\n", fname);
68         info_log("scene graph:\n");
69         print_scene_graph(scn->nodes, 0);
70         */
71         return res;
72 }
73
74 void MetaScene::update(float dt)
75 {
76         int nscn = scenes.size();
77         for(int i=0; i<nscn; i++) {
78                 scenes[i]->update(dt);
79         }
80 }
81
82 void MetaScene::draw() const
83 {
84         int nscn = scenes.size();
85         for(int i=0; i<nscn; i++) {
86                 scenes[i]->draw();
87         }
88 }
89
90 SceneNode *MetaScene::find_node(const char *name) const
91 {
92         int num = scenes.size();
93         for(int i=0; i<num; i++) {
94                 SceneNode *n = scenes[i]->find_node(name);
95                 if(n) return n;
96         }
97         return 0;
98 }
99
100 SceneNode *MetaScene::match_node(const char *qstr) const
101 {
102         int num = scenes.size();
103         for(int i=0; i<num; i++) {
104                 SceneNode *n = scenes[i]->match_node(qstr);
105                 if(n) return n;
106         }
107         return 0;
108 }
109
110 std::list<SceneNode*> MetaScene::match_nodes(const char *qstr) const
111 {
112         std::list<SceneNode*> res;
113         int num = scenes.size();
114         for(int i=0; i<num; i++) {
115                 std::list<SceneNode*> tmp = scenes[i]->match_nodes(qstr);
116                 if(!tmp.empty()) {
117                         res.splice(res.end(), tmp);
118                 }
119         }
120         return std::move(res);
121 }
122
123 Scene *MetaScene::extract_nodes(const char *qstr)
124 {
125         Scene *scn = 0;
126         int nscn = scenes.size();
127         for(int i=0; i<nscn; i++) {
128                 Scene *tmp = scenes[i]->extract_nodes(qstr);
129                 if(tmp) {
130                         if(!scn) {
131                                 scn = tmp;
132                         } else {
133                                 scn->merge(tmp);
134                                 delete tmp;
135                         }
136                 }
137         }
138         return scn;
139 }
140
141 static bool proc_node(MetaScene *mscn, struct ts_node *node)
142 {
143         struct ts_node *c = node->child_list;
144         while(c) {
145                 if(!proc_node(mscn, c)) {
146                         return false;
147                 }
148                 c = c->next;
149         }
150
151         // do this last to allow other contents of the node to do their thing
152         if(strcmp(node->name, "scenefile") == 0) {
153                 return proc_scenefile(mscn, node);
154
155         } else if(strcmp(node->name, "remap") == 0) {
156                 const char *match = ts_get_attr_str(node, "match");
157                 const char *replace = ts_get_attr_str(node, "replace");
158                 if(match && replace) {
159                         mscn->datamap.map(match, replace);
160                 }
161
162         } else if(strcmp(node->name, "music") == 0) {
163                 return proc_music(mscn, node);
164         }
165
166         return true;
167 }
168
169
170
171 struct SceneData {
172         MetaScene *meta;
173         std::string walkmesh_regexp, spawn_regexp;
174         std::vector<MaterialEdit> mtledit;
175 };
176
177 /*! Processes a `scenefile` node. And kicks off scene loading (if necessary) by
178  * calling `SceneSet::get`.
179  */
180 static bool proc_scenefile(MetaScene *mscn, struct ts_node *node)
181 {
182         const char *fname = ts_get_attr_str(node, "file");
183         if(fname) {
184                 SceneData *sdat = new SceneData;
185                 sdat->meta = mscn;
186
187                 // datapath
188                 struct ts_attr *adpath = attr_inscope(node, "datapath");
189                 if(adpath && adpath->val.type == TS_STRING) {
190                         mscn->datamap.set_path(adpath->val.str);
191                 }
192
193                 // strip path
194                 struct ts_attr *aspath = attr_inscope(node, "strip_path");
195                 if(aspath && aspath->val.type == TS_NUMBER) {
196                         mscn->datamap.set_strip(aspath->val.inum);
197                 }
198
199                 // walkmesh
200                 struct ts_attr *awmesh = attr_inscope(node, "walkmesh");
201                 if(awmesh && awmesh->val.type == TS_STRING) {
202                         sdat->walkmesh_regexp = std::string(awmesh->val.str);
203                 }
204
205                 // spawn node
206                 struct ts_attr *awspawn = attr_inscope(node, "spawn");
207                 if(awspawn) {
208                         switch(awspawn->val.type) {
209                         case TS_VECTOR:
210                                 mscn->start_pos = Vec3(awspawn->val.vec[0], awspawn->val.vec[1],
211                                                 awspawn->val.vec[2]);
212                                 break;
213
214                         case TS_STRING:
215                         default:
216                                 sdat->spawn_regexp = std::string(awspawn->val.str);
217                         }
218                 }
219                 if((awspawn = attr_inscope(node, "spawn_rot")) && awspawn->val.type == TS_VECTOR) {
220                         Quat rot;
221                         rot.rotate(Vec3(1, 0, 0), deg_to_rad(awspawn->val.vec[0]));
222                         rot.rotate(Vec3(0, 1, 0), deg_to_rad(awspawn->val.vec[1]));
223                         rot.rotate(Vec3(0, 0, 1), deg_to_rad(awspawn->val.vec[2]));
224                         mscn->start_rot = rot;
225                 }
226
227                 int namesz = mscn->datamap.lookup(fname, 0, 0);
228                 char *namebuf = (char*)alloca(namesz + 1);
229                 if(mscn->datamap.lookup(fname, namebuf, namesz + 1)) {
230                         fname = namebuf;
231                 }
232
233                 // material edits are kept in a list to be applied when the scene has been loaded
234                 struct ts_node *child = node->child_list;
235                 while(child) {
236                         MaterialEdit medit;
237                         if(proc_mtledit(mscn, &medit, child)) {
238                                 sdat->mtledit.push_back(medit);
239                         }
240                         child = child->next;
241                 }
242
243                 Scene *newscn = sceneman.get(fname);
244                 /* NOTE: setting all these after get() is not a race condition, because
245                  * scene_loaded() which uses this, will only run in our main loop during
246                  * SceneSet::update() on the main thread.
247                  */
248                 newscn->datamap = mscn->datamap;
249                 mscn->datamap.clear();
250
251                 newscn->metascn = mscn;
252                 mscn->scndata[newscn] = sdat;
253         }
254         return true;
255 }
256
257 bool MetaScene::scene_loaded(Scene *newscn)
258 {
259         SceneData *sdat = (SceneData*)scndata[newscn];
260         if(!sdat) {
261                 error_log("MetaScene::scene_loaded called, but corresponding SceneData not found\n");
262                 return false;
263         }
264
265         // extract the walk mesh if necessary
266         Scene *wscn;
267         if(!sdat->walkmesh_regexp.empty() && (wscn = newscn->extract_nodes(sdat->walkmesh_regexp.c_str()))) {
268                 // apply all transformations to the meshes
269                 wscn->apply_xform();
270
271                 int nmeshes = wscn->meshes.size();
272                 for(int i=0; i<nmeshes; i++) {
273                         Mesh *m = wscn->meshes[i];
274
275                         if(walk_mesh) {
276                                 walk_mesh->append(*m);
277                         } else {
278                                 walk_mesh = m;
279                                 wscn->remove_mesh(m);   // to save it from destruction
280                         }
281                 }
282
283                 delete wscn;
284         }
285
286         // extract the spawn node
287         if(!sdat->spawn_regexp.empty() && (wscn = newscn->extract_nodes(sdat->spawn_regexp.c_str()))) {
288
289                 int nmeshes = wscn->meshes.size();
290                 int nnodes = wscn->nodes ? wscn->nodes->get_num_children() : 0;
291
292                 if(nmeshes) {
293                         Vec3 pos;
294                         for(int i=0; i<nmeshes; i++) {
295                                 const Sphere &bsph = wscn->meshes[i]->get_bsphere();
296                                 pos += bsph.center;
297                         }
298                         pos /= (float)nmeshes;
299                         sdat->meta->start_pos = pos;
300
301                 } else if(nnodes) {
302                         // just use the first one
303                         SceneNode *first = wscn->nodes->get_child(0);
304                         sdat->meta->start_pos = first->get_position();
305                         sdat->meta->start_rot = first->get_rotation();
306                 }
307                 delete wscn;
308         }
309
310         int num_medits = sdat->mtledit.size();
311         for(int i=0; i<num_medits; i++) {
312                 // perform material edits
313                 apply_mtledit(newscn, sdat->mtledit[i]);
314         }
315
316         scenes.push_back(newscn);
317         return true;
318 }
319
320 static bool proc_mtledit(MetaScene *mscn, MaterialEdit *med, struct ts_node *node)
321 {
322         if(strcmp(node->name, "mtledit") != 0) {
323                 return false;
324         }
325
326         const char *restr = ".*";
327         struct ts_attr *amtl = ts_get_attr(node, "material");
328         if(amtl && amtl->val.type == TS_STRING) {
329                 restr = amtl->val.str;
330         }
331
332         med->name_re = std::regex(restr);
333
334         node = node->child_list;
335         while(node) {
336                 struct ts_node *cn = node;
337                 node = node->next;
338
339                 if(strcmp(cn->name, "texture") == 0) {
340                         // add/change/remove a texture
341                         struct ts_attr *atype = ts_get_attr(cn, "type");
342                         struct ts_attr *afile = ts_get_attr(cn, "file");
343
344                         int textype = MTL_TEX_DIFFUSE;
345                         if(atype) {
346                                 if(atype->val.type == TS_STRING) {
347                                         textype = mtl_parse_type(atype->val.str);
348                                 } else if(atype->val.type == TS_NUMBER) {
349                                         textype = atype->val.inum;
350                                         if(textype < 0 || textype >= NUM_MTL_TEXTURES) {
351                                                 error_log("invalid texture in mtledit: %d\n", textype);
352                                                 continue;
353                                         }
354                                 } else {
355                                         error_log("unexpected texture type in mtledit: %s\n", atype->val.str);
356                                         continue;
357                                 }
358                         }
359
360                         med->attr = textype;
361
362                         if(!afile || !afile->val.str || !*afile->val.str) {
363                                 // remove
364                                 med->tex = 0;
365                         } else {
366                                 med->tex = texman.get_texture(afile->val.str, TEX_2D, &mscn->datamap);
367                         }
368                 }
369                 // TODO add more edit modes
370         }
371
372         return true;
373 }
374
375 static void apply_mtledit(Scene *scn, const MaterialEdit &med)
376 {
377         // search all the objects to find matching material names
378         int nobj = scn->objects.size();
379         for(int i=0; i<nobj; i++) {
380                 Object *obj = scn->objects[i];
381                 if(std::regex_match(obj->mtl.name, med.name_re)) {
382                         apply_mtledit(&obj->mtl, med);
383                 }
384         }
385 }
386
387 static bool proc_music(MetaScene *mscn, struct ts_node *node)
388 {
389         const char *fname = ts_get_attr_str(node, "file");
390         if(fname) {
391                 SceneData *sdat = new SceneData;
392                 sdat->meta = mscn;
393
394                 // datapath
395                 struct ts_attr *adpath = attr_inscope(node, "datapath");
396                 if(adpath && adpath->val.type == TS_STRING) {
397                         mscn->datamap.set_path(adpath->val.str);
398                 }
399
400                 int namesz = mscn->datamap.lookup(fname, 0, 0);
401                 char *namebuf = (char*)alloca(namesz + 1);
402                 if(mscn->datamap.lookup(fname, namebuf, namesz + 1)) {
403                         fname = namebuf;
404                 }
405
406                 OggVorbisStream *ovstream = new OggVorbisStream;
407                 if(!ovstream->open(fname)) {
408                         delete ovstream;
409                         return false;
410                 }
411
412                 delete mscn->music;
413                 mscn->music = ovstream;
414         }
415         return true;
416 }
417
418 static void apply_mtledit(Material *mtl, const MaterialEdit &med)
419 {
420         // TODO more edit modes...
421         if(med.tex) {
422                 mtl->add_texture(med.tex, med.attr);
423         } else {
424                 Texture *tex = mtl->stdtex[med.attr];
425                 if(tex) {
426                         mtl->remove_texture(tex);
427                 }
428         }
429 }
430
431 static struct ts_attr *attr_inscope(struct ts_node *node, const char *name)
432 {
433         struct ts_attr *attr = 0;
434
435         while(node && !(attr = ts_get_attr(node, name))) {
436                 node = node->parent;
437         }
438         return attr;
439 }
440
441 static void print_scene_graph(SceneNode *n, int level)
442 {
443         if(!n) return;
444
445         for(int i=0; i<level; i++) {
446                 info_log("  ");
447         }
448
449         int nobj = n->get_num_objects();
450         if(nobj) {
451                 info_log("%s - %d obj\n", n->get_name(), n->get_num_objects());
452         } else {
453                 info_log("%s\n", n->get_name());
454         }
455
456         for(int i=0; i<n->get_num_children(); i++) {
457                 print_scene_graph(n->get_child(i), level + 1);
458         }
459 }