reflection geometry finally correct
[laserbrain_demo] / src / metascene.cc
index b92e31f..eef5e65 100644 (file)
@@ -1,24 +1,84 @@
+/*! \file
+ * \brief Metascene implementation
+ *
+ * Loading starts at `MetaScene::load`, which calls `ts_load` (libtreestore)
+ * to load the metascene description tree into memory. Then `proc_node` is
+ * called at the root to recursively process the tree. `scenefile` nodes are
+ * handed over to `proc_scenefile`, which will trigger scene loading for any
+ * nodes with a `file` attribute. Scene loading is handled by requesting the
+ * filename from the scene resource manager, which is of type [SceneSet](\ref SceneSet).
+ */
+#include <assert.h>
+#include <string>
 #include <regex>
 #include "metascene.h"
 #include "scene.h"
-#include "datamap.h"
+#include "objmesh.h"
 #include "treestore.h"
 #include "logger.h"
+#include "app.h"
+#include "dbg_gui.h"
 
-#ifdef WIN32
+#if defined(WIN32) || defined(__WIN32__)
 #include <malloc.h>
 #else
 #include <alloca.h>
 #endif
 
-static bool proc_node(Scene *scn, struct ts_node *node);
-static bool proc_scenefile(Scene *scn, struct ts_node *node);
-static bool proc_mtledit(Scene *scn, struct ts_node *node);
+enum MaterialEditType {
+       MTL_EDIT_TEXTURE,
+       MTL_EDIT_MIRROR
+};
+
+struct MaterialEditTexture {
+       int attr;
+       Texture *tex;
+};
+
+struct MaterialEditMirror {
+       float reflectivity;
+       int plane;
+};
+
+struct MaterialEdit {
+       std::regex name_re;
+       MaterialEditType type;
+
+       MaterialEditTexture tex;
+       MaterialEditMirror mirror;
+};
+
+static bool proc_node(MetaScene *mscn, struct ts_node *node);
+static bool proc_scenefile(MetaScene *mscn, struct ts_node *node);
+static bool proc_mtledit(MetaScene *mscn, MaterialEdit *med, struct ts_node *node);
+static bool proc_music(MetaScene *mscn, struct ts_node *node);
+static void apply_mtledit(Scene *scn, const MaterialEdit &med);
+static void apply_mtledit(Material *mtl, const MaterialEdit &med);
 static struct ts_attr *attr_inscope(struct ts_node *node, const char *name);
 
 static void print_scene_graph(SceneNode *n, int level);
 
-bool load_scene(Scene *scn, const char *fname)
+
+MetaScene::MetaScene()
+{
+       walk_mesh = 0;
+       music = 0;
+       mirrors = 0;
+}
+
+MetaScene::~MetaScene()
+{
+       delete walk_mesh;
+       delete music;
+
+       while(mirrors) {
+               FlatMirror *m = mirrors;
+               mirrors = mirrors->next;
+               delete m;
+       }
+}
+
+bool MetaScene::load(const char *fname)
 {
        struct ts_node *root = ts_load(fname);
        if(!root || strcmp(root->name, "scene") != 0) {
@@ -27,20 +87,223 @@ bool load_scene(Scene *scn, const char *fname)
                return false;
        }
 
-       bool res = proc_node(scn, root);
+       bool res = proc_node(this, root);
        ts_free_tree(root);
 
-       info_log("loaded scene: %s\n", fname);
+       /*info_log("loaded scene: %s\n", fname);
        info_log("scene graph:\n");
        print_scene_graph(scn->nodes, 0);
+       */
        return res;
 }
 
-static bool proc_node(Scene *scn, struct ts_node *node)
+void MetaScene::update(float dt)
+{
+       bool expanded;
+       static char text[256];
+       if(debug_gui) {
+               ImGui::Begin("MetaScene nodes", 0, 0);
+               ImGui::Columns(2);
+
+               static bool once;
+               if(!once) {
+                       float x = ImGui::GetColumnOffset(1);
+                       ImGui::SetColumnOffset(1, x * 1.55);
+                       once = true;
+               }
+       }
+
+       int nscn = scenes.size();
+       for(int i=0; i<nscn; i++) {
+
+               if(debug_gui) {
+                       if(scenes[i]->name.empty()) {
+                               sprintf(text, "scene %3d", i);
+                       } else {
+                               sprintf(text, "scene %3d: %s", i, scenes[i]->name.c_str());
+                       }
+                       expanded = parent_expanded = ImGui::TreeNode(text);
+                       ImGui::NextColumn();
+                       ImGui::NextColumn();
+               }
+
+               scenes[i]->update(dt);
+
+               if(debug_gui && expanded) {
+                       ImGui::TreePop();
+               }
+       }
+
+       if(debug_gui) {
+               ImGui::Columns(1);
+               ImGui::End();
+       }
+}
+
+// XXX not used, renderer draws
+void MetaScene::draw() const
+{
+       error_log("Don't call MetaScene::draw, use the Renderer\n");
+       int nscn = scenes.size();
+       for(int i=0; i<nscn; i++) {
+               scenes[i]->draw();
+       }
+}
+
+SceneNode *MetaScene::find_node(const char *name) const
+{
+       int num = scenes.size();
+       for(int i=0; i<num; i++) {
+               SceneNode *n = scenes[i]->find_node(name);
+               if(n) return n;
+       }
+       return 0;
+}
+
+SceneNode *MetaScene::match_node(const char *qstr) const
+{
+       int num = scenes.size();
+       for(int i=0; i<num; i++) {
+               SceneNode *n = scenes[i]->match_node(qstr);
+               if(n) return n;
+       }
+       return 0;
+}
+
+std::list<SceneNode*> MetaScene::match_nodes(const char *qstr) const
+{
+       std::list<SceneNode*> res;
+       int num = scenes.size();
+       for(int i=0; i<num; i++) {
+               std::list<SceneNode*> tmp = scenes[i]->match_nodes(qstr);
+               if(!tmp.empty()) {
+                       res.splice(res.end(), tmp);
+               }
+       }
+       return res;     // hopefully it'll be moved
+}
+
+Scene *MetaScene::extract_nodes(const char *qstr)
+{
+       Scene *scn = 0;
+       int nscn = scenes.size();
+       for(int i=0; i<nscn; i++) {
+               Scene *tmp = scenes[i]->extract_nodes(qstr);
+               if(tmp) {
+                       if(!scn) {
+                               scn = tmp;
+                       } else {
+                               scn->merge(tmp);
+                               delete tmp;
+                       }
+               }
+       }
+       return scn;
+}
+
+int MetaScene::calc_mirror_planes()
+{
+       FlatMirror *planes = 0;
+
+       int num_mirrors = 0;
+       while(mirrors) {
+               FlatMirror *m = mirrors;
+               mirrors = mirrors->next;
+               delete m;
+       }
+       mirrors = 0;
+       objmirror.clear();
+
+       int numscn = scenes.size();
+       for(int i=0; i<numscn; i++) {
+               Scene *scn = scenes[i];
+
+               int numobj = scn->objects.size();
+               for(int j=0; j<numobj; j++) {
+                       Object *obj = scn->objects[j];
+
+                       if(obj->mtl.flat_mirror && obj->get_type() == OBJ_MESH) {
+                               const Mesh *mesh = ((ObjMesh*)obj)->mesh;
+                               if(!mesh) continue;
+
+                               FlatMirror *mir = new FlatMirror;
+                               mir->reflect = obj->mtl.reflect;
+                               mir->node = obj->node;
+
+                               if(obj->mtl.flat_mirror == MTL_MIRROR_AUTO) {
+                                       // grab the first triangle and make a plane
+                                       Triangle face = Triangle(0, (const Vec3*)mesh->get_attrib_data(MESH_ATTR_VERTEX),
+                                                       mesh->get_index_data());
+                                       face.calc_normal();
+
+                                       mir->plane.pt = face.v[0];
+                                       mir->plane.normal = face.normal;
+                               } else {
+                                       int plane_idx = obj->mtl.flat_mirror - MTL_MIRROR_AABB_PX;
+                                       mir->plane = obj->get_aabox().get_plane(plane_idx);
+                               }
+
+                               mir->wplane = mir->plane;
+                               if(obj->node) {
+                                       const Mat4 &xform = obj->node->get_matrix();
+                                       mir->wplane.pt = xform * mir->wplane.pt;
+                                       mir->wplane.normal = normalize(xform.upper3x3() * mir->wplane.normal);
+                               }
+
+                               // check to see if we have found this mirror plane already
+                               bool found = false;
+                               FlatMirror *node = planes;
+                               while(node) {
+                                       float d1 = dot(mir->wplane.normal, mir->wplane.pt);
+                                       float d2 = dot(node->wplane.normal, node->wplane.pt);
+
+                                       if(1.0f - dot(mir->wplane.normal, node->wplane.normal) < 1e-4f &&
+                                                       fabs(d1 - d2) < 1e-4) {
+                                               found = true;
+                                               break;
+                                       }
+                                       node = node->next;
+                               }
+
+                               debug_log("[%s@%s] mirror plane: local(%g %g %g %g), world(%g %g %g %g)%s\n",
+                                               obj->get_name(), obj->node ? obj->node->get_name() : "<no-node>",
+                                               mir->plane.normal.x, mir->plane.normal.y, mir->plane.normal.z,
+                                               dot(mir->plane.normal, mir->plane.pt), mir->wplane.normal.x, mir->wplane.normal.y,
+                                               mir->wplane.normal.z, dot(mir->wplane.normal, mir->wplane.pt), found ? " duplicate" : "");
+
+                               if(!found) {
+                                       mir->next = mirrors;
+                                       mirrors = mir;
+
+                                       node = new FlatMirror;
+                                       node->wplane = mir->wplane;
+                                       node->next = planes;
+                                       planes = node;
+
+                                       mir->objects.push_back(obj);
+                                       objmirror[obj] = mir;   // associate with object
+                                       ++num_mirrors;
+                               } else {
+                                       delete mir;
+                               }
+                       }
+               }
+       }
+
+       while(planes) {
+               FlatMirror *tmp = planes;
+               planes = planes->next;
+               delete tmp;
+       }
+
+       return num_mirrors;
+}
+
+static bool proc_node(MetaScene *mscn, struct ts_node *node)
 {
        struct ts_node *c = node->child_list;
        while(c) {
-               if(!proc_node(scn, c)) {
+               if(!proc_node(mscn, c)) {
                        return false;
                }
                c = c->next;
@@ -48,86 +311,186 @@ static bool proc_node(Scene *scn, struct ts_node *node)
 
        // do this last to allow other contents of the node to do their thing
        if(strcmp(node->name, "scenefile") == 0) {
-               return proc_scenefile(scn, node);
+               return proc_scenefile(mscn, node);
 
        } else if(strcmp(node->name, "remap") == 0) {
                const char *match = ts_get_attr_str(node, "match");
                const char *replace = ts_get_attr_str(node, "replace");
                if(match && replace) {
-                       datamap_map(match, replace);
+                       mscn->datamap.map(match, replace);
                }
+
+       } else if(strcmp(node->name, "music") == 0) {
+               return proc_music(mscn, node);
        }
 
        return true;
 }
 
-static bool proc_scenefile(Scene *scn, struct ts_node *node)
+
+
+struct SceneData {
+       MetaScene *meta;
+       std::string walkmesh_regexp, spawn_regexp;
+       std::vector<MaterialEdit> mtledit;
+};
+
+/*! Processes a `scenefile` node. And kicks off scene loading (if necessary) by
+ * calling `SceneSet::get`.
+ */
+static bool proc_scenefile(MetaScene *mscn, struct ts_node *node)
 {
        const char *fname = ts_get_attr_str(node, "file");
        if(fname) {
+               SceneData *sdat = new SceneData;
+               sdat->meta = mscn;
+
                // datapath
                struct ts_attr *adpath = attr_inscope(node, "datapath");
                if(adpath && adpath->val.type == TS_STRING) {
-                       info_log("adding data path: %s\n", adpath->val.str);
-                       datamap_set_path(adpath->val.str);
+                       mscn->datamap.set_path(adpath->val.str);
+               }
+
+               // strip path
+               struct ts_attr *aspath = attr_inscope(node, "strip_path");
+               if(aspath && aspath->val.type == TS_NUMBER) {
+                       mscn->datamap.set_strip(aspath->val.inum);
                }
 
                // walkmesh
-               char *walkmesh_regexp = 0;
                struct ts_attr *awmesh = attr_inscope(node, "walkmesh");
                if(awmesh && awmesh->val.type == TS_STRING) {
-                       walkmesh_regexp = awmesh->val.str;
+                       sdat->walkmesh_regexp = std::string(awmesh->val.str);
                }
 
-               int namesz = datamap_lookup(fname, 0, 0);
+               // spawn node
+               struct ts_attr *awspawn = attr_inscope(node, "spawn");
+               if(awspawn) {
+                       switch(awspawn->val.type) {
+                       case TS_VECTOR:
+                               mscn->start_pos = Vec3(awspawn->val.vec[0], awspawn->val.vec[1],
+                                               awspawn->val.vec[2]);
+                               break;
+
+                       case TS_STRING:
+                       default:
+                               sdat->spawn_regexp = std::string(awspawn->val.str);
+                       }
+               }
+               if((awspawn = attr_inscope(node, "spawn_rot")) && awspawn->val.type == TS_VECTOR) {
+                       Quat rot;
+                       rot.rotate(Vec3(1, 0, 0), deg_to_rad(awspawn->val.vec[0]));
+                       rot.rotate(Vec3(0, 1, 0), deg_to_rad(awspawn->val.vec[1]));
+                       rot.rotate(Vec3(0, 0, 1), deg_to_rad(awspawn->val.vec[2]));
+                       mscn->start_rot = rot;
+               }
+
+               int namesz = mscn->datamap.lookup(fname, 0, 0);
                char *namebuf = (char*)alloca(namesz + 1);
-               if(datamap_lookup(fname, namebuf, namesz + 1)) {
+               if(mscn->datamap.lookup(fname, namebuf, namesz + 1)) {
                        fname = namebuf;
                }
 
-               Scene *newscn = new Scene(scn->texset);
-               if(!(newscn->load(fname, SCNLOAD_FLIPTEX))) {   // TODO unhardcode FLIPTEX
-                       return false;
+               // material edits are kept in a list to be applied when the scene has been loaded
+               struct ts_node *child = node->child_list;
+               while(child) {
+                       MaterialEdit medit;
+                       if(proc_mtledit(mscn, &medit, child)) {
+                               sdat->mtledit.push_back(medit);
+                       }
+                       child = child->next;
                }
 
-               // extract the walk mesh if necessary
-               Scene *wscn;
-               if(walkmesh_regexp && (wscn = newscn->extract_nodes(walkmesh_regexp))) {
-                       // apply all transformations to the meshes
-                       wscn->apply_xform();
+               Scene *newscn = sceneman.get(fname);
+               /* NOTE: setting all these after get() is not a race condition, because
+                * scene_loaded() which uses this, will only run in our main loop during
+                * SceneSet::update() on the main thread.
+                */
+               newscn->datamap = mscn->datamap;
+               mscn->datamap.clear();
 
-                       int nmeshes = wscn->meshes.size();
-                       for(int i=0; i<nmeshes; i++) {
-                               Mesh *m = wscn->meshes[i];
+               newscn->metascn = mscn;
+               mscn->scndata[newscn] = sdat;
+       }
+       return true;
+}
 
-                               if(newscn->walk_mesh) {
-                                       newscn->walk_mesh->append(*m);
-                               } else {
-                                       newscn->walk_mesh = m;
-                                       wscn->remove_mesh(m);   // to save it from destruction
-                               }
-                       }
+bool MetaScene::scene_loaded(Scene *newscn)
+{
+       SceneData *sdat = (SceneData*)scndata[newscn];
+       if(!sdat) {
+               error_log("MetaScene::scene_loaded called, but corresponding SceneData not found\n");
+               return false;
+       }
+
+       // extract the walk mesh if necessary
+       Scene *wscn;
+       if(!sdat->walkmesh_regexp.empty() && (wscn = newscn->extract_nodes(sdat->walkmesh_regexp.c_str()))) {
+               // apply all transformations to the meshes
+               wscn->apply_xform();
+
+               int nmeshes = wscn->meshes.size();
+               for(int i=0; i<nmeshes; i++) {
+                       Mesh *m = wscn->meshes[i];
 
-                       delete wscn;
+                       if(walk_mesh) {
+                               walk_mesh->append(*m);
+                       } else {
+                               walk_mesh = m;
+                               wscn->remove_mesh(m);   // to save it from destruction
+                       }
                }
 
-               // perform material edits
-               struct ts_node *child = node->child_list;
-               while(child) {
-                       proc_mtledit(newscn, child); // ignores any non-mtledit nodes, no need to check
-                       child = child->next;
+               delete wscn;
+       }
+
+       // extract the spawn node
+       if(!sdat->spawn_regexp.empty() && (wscn = newscn->extract_nodes(sdat->spawn_regexp.c_str()))) {
+
+               int nmeshes = wscn->meshes.size();
+               int nnodes = wscn->nodes ? wscn->nodes->get_num_children() : 0;
+
+               if(nmeshes) {
+                       Vec3 pos;
+                       for(int i=0; i<nmeshes; i++) {
+                               const Sphere &bsph = wscn->meshes[i]->get_bsphere();
+                               pos += bsph.center;
+                       }
+                       pos /= (float)nmeshes;
+                       sdat->meta->start_pos = pos;
+
+               } else if(nnodes) {
+                       // just use the first one
+                       SceneNode *first = wscn->nodes->get_child(0);
+                       sdat->meta->start_pos = first->get_position();
+                       sdat->meta->start_rot = first->get_rotation();
                }
+               delete wscn;
+       }
 
-               scn->merge(newscn);
-               delete newscn;
+       int num_medits = sdat->mtledit.size();
+       for(int i=0; i<num_medits; i++) {
+               // perform material edits
+               apply_mtledit(newscn, sdat->mtledit[i]);
        }
-       //datamap_reset();      // TODO this should be push/pop instead of hard reset
 
+       scenes.push_back(newscn);
        return true;
 }
 
-static void mtledit(Material *mtl, TextureSet *texset, struct ts_node *node)
+static bool proc_mtledit(MetaScene *mscn, MaterialEdit *med, struct ts_node *node)
 {
+       if(strcmp(node->name, "mtledit") != 0) {
+               return false;
+       }
+
+       const char *restr = ".*";
+       struct ts_attr *amtl = ts_get_attr(node, "material");
+       if(amtl && amtl->val.type == TS_STRING) {
+               restr = amtl->val.str;
+       }
+       med->name_re = std::regex(restr);
+
        node = node->child_list;
        while(node) {
                struct ts_node *cn = node;
@@ -154,44 +517,137 @@ static void mtledit(Material *mtl, TextureSet *texset, struct ts_node *node)
                                }
                        }
 
+                       med->tex.attr = textype;
+
                        if(!afile || !afile->val.str || !*afile->val.str) {
                                // remove
-                               mtl->textures[textype] = 0;
+                               med->tex.tex = 0;
                        } else {
-                               Texture *tex = texset->get_texture(afile->val.str, TEX_2D);
-                               mtl->add_texture(tex, textype);
+                               med->tex.tex = texman.get_texture(afile->val.str, TEX_2D, &mscn->datamap);
                        }
+
+                       med->type = MTL_EDIT_TEXTURE;
+                       break;
                }
-               // TODO add more edit modes
-       }
-}
 
-static bool proc_mtledit(Scene *scn, struct ts_node *node)
-{
-       if(strcmp(node->name, "mtledit") != 0) {
-               return false;
-       }
+               if(strcmp(cn->name, "mirror") == 0) {
+                       // make this object a flat mirror (hopefully the object is flat otherwise this won't work)
+                       float refl = 1.0f;
+                       int plane = MTL_MIRROR_AUTO;
 
-       const char *mtl_regexp = ".*";
-       struct ts_attr *amtl = ts_get_attr(node, "material");
-       if(amtl && amtl->val.type == TS_STRING) {
-               mtl_regexp = amtl->val.str;
+                       struct ts_attr *aplane = ts_get_attr(cn, "plane");
+                       if(aplane) {
+                               if(aplane->val.type == TS_NUMBER) {
+                                       plane = MTL_MIRROR_AABB_PX + aplane->val.inum;
+                               } else {
+                                       char csign, caxis;
+                                       if(sscanf(aplane->val.str, "aabb%c%c", &csign, &caxis) != 2 || (csign != '+' && csign != '-')) {
+                                               error_log("invalid reflect plane specifier: %s\n", aplane->val.str);
+                                               continue;
+                                       }
+
+                                       switch(tolower(caxis)) {
+                                       case 'x':
+                                               plane = csign == '+' ? MTL_MIRROR_AABB_PX : MTL_MIRROR_AABB_NX;
+                                               break;
+                                       case 'y':
+                                               plane = csign == '+' ? MTL_MIRROR_AABB_PY : MTL_MIRROR_AABB_NY;
+                                               break;
+                                       case 'z':
+                                               plane = csign == '+' ? MTL_MIRROR_AABB_PZ : MTL_MIRROR_AABB_NZ;
+                                               break;
+                                       default:
+                                               error_log("invalid reflect plane specifier: %s\n", aplane->val.str);
+                                               continue;
+                                       }
+                               }
+                       }
+
+                       struct ts_attr *arefl = ts_get_attr(cn, "reflect");
+                       if(arefl) {
+                               if(arefl->val.type == TS_NUMBER) {
+                                       refl = arefl->val.fnum;
+                               } else {
+                                       error_log("invalid reflect attribute in mirror mtledit: %s\n", arefl->val.str);
+                                       continue;
+                               }
+                       }
+
+                       med->type = MTL_EDIT_MIRROR;
+                       med->mirror.reflectivity = refl;
+                       med->mirror.plane = plane;
+                       break;
+               }
        }
 
-       // search all the objects to find matching material names
-       std::regex re{mtl_regexp};
+       return true;
+}
 
+static void apply_mtledit(Scene *scn, const MaterialEdit &med)
+{
+       // search all the objects to find matching material names
        int nobj = scn->objects.size();
        for(int i=0; i<nobj; i++) {
                Object *obj = scn->objects[i];
-               if(std::regex_match(obj->get_name(), re)) {
-                       mtledit(&obj->mtl, scn->texset, node);
+               if(std::regex_match(obj->mtl.name, med.name_re)) {
+                       apply_mtledit(&obj->mtl, med);
                }
        }
+}
+
+static bool proc_music(MetaScene *mscn, struct ts_node *node)
+{
+       const char *fname = ts_get_attr_str(node, "file");
+       if(fname) {
+               SceneData *sdat = new SceneData;
+               sdat->meta = mscn;
+
+               // datapath
+               struct ts_attr *adpath = attr_inscope(node, "datapath");
+               if(adpath && adpath->val.type == TS_STRING) {
+                       mscn->datamap.set_path(adpath->val.str);
+               }
+
+               int namesz = mscn->datamap.lookup(fname, 0, 0);
+               char *namebuf = (char*)alloca(namesz + 1);
+               if(mscn->datamap.lookup(fname, namebuf, namesz + 1)) {
+                       fname = namebuf;
+               }
 
+               OggVorbisStream *ovstream = new OggVorbisStream;
+               if(!ovstream->open(fname)) {
+                       delete ovstream;
+                       return false;
+               }
+
+               delete mscn->music;
+               mscn->music = ovstream;
+       }
        return true;
 }
 
+static void apply_mtledit(Material *mtl, const MaterialEdit &med)
+{
+       // TODO more edit modes...
+       switch(med.type) {
+       case MTL_EDIT_TEXTURE:
+               if(med.tex.tex) {
+                       mtl->add_texture(med.tex.tex, med.tex.attr);
+               } else {
+                       Texture *tex = mtl->stdtex[med.tex.attr];
+                       if(tex) {
+                               mtl->remove_texture(tex);
+                       }
+               }
+               break;
+
+       case MTL_EDIT_MIRROR:
+               mtl->flat_mirror = med.mirror.plane;
+               mtl->reflect = med.mirror.reflectivity;
+               break;
+       }
+}
+
 static struct ts_attr *attr_inscope(struct ts_node *node, const char *name)
 {
        struct ts_attr *attr = 0;