hand-tracking and exhibits part one
[laserbrain_demo] / src / exman.cc
1 #include <float.h>
2 #include <algorithm>
3 #include "exman.h"
4 #include "exhibit.h"
5 #include "blob_exhibit.h"
6 #include "treestore.h"
7 #include "app.h"
8 #include "geomdraw.h"
9
10 static Exhibit *create_exhibit(const char *type);
11 static void clean_desc_text(char *dest, const char *src);
12
13
14 ExhibitSlot::ExhibitSlot(Exhibit *ex)
15 {
16         this->ex = 0;
17
18         init(ex);
19 }
20
21 ExhibitSlot::~ExhibitSlot()
22 {
23         detach_exhibit();
24
25         SceneNode *par = node.get_parent();
26         if(par) {
27                 par->remove_child(&node);
28
29                 while(node.get_num_children()) {
30                         par->add_child(node.get_child(0));
31                 }
32         }
33 }
34
35
36 void ExhibitSlot::init(Exhibit *ex)
37 {
38         std::string node_name = "ExhibitSlot";
39         if(ex) {
40                 if(ex->get_name()) {
41                         node_name += std::string(":") + std::string(ex->get_name());
42                 }
43
44                 if(ex->node) {
45                         if(ex->node->get_parent()) {
46                                 ex->node->get_parent()->add_child(&node);
47                         }
48                         node.set_position(ex->node->get_node_position());
49                         node.set_rotation(ex->node->get_node_rotation());
50                         ex->node->set_position(Vec3(0, 0, 0));
51                         ex->node->set_rotation(Quat::identity);
52                 }
53                 attach_exhibit(ex);
54         } else {
55                 this->ex = 0;
56         }
57
58         node.set_name(node_name.c_str());
59 }
60
61 bool ExhibitSlot::empty() const
62 {
63         return ex == 0;
64 }
65
66 Exhibit *ExhibitSlot::get_exhibit() const
67 {
68         return ex;
69 }
70
71 /* In the process of attaching the exhibit, we also steal the exhibit's node
72  * from its previous parent, and reparent it to the slot's node. As the slot's
73  * node itself should have been made a child of the original parent of the
74  * exhibit during init(), the initial state is we're interjecting a null node in
75  * the scene graph between the exhibit and its original parent.
76  *
77  * Attaching to a slot, implicitly detaches from the previous slot.
78  */
79 bool ExhibitSlot::attach_exhibit(Exhibit *ex, ExSlotAttachMode mode)
80 {
81         if(!ex || this->ex) return false;
82
83         if(ex->prev_slot && ex->prev_slot->ex == ex) {
84                 ex->prev_slot->detach_exhibit();
85         }
86
87         if(mode != EXSLOT_ATTACH_TRANSIENT) {
88                 ex->prev_slot = this;
89         }
90
91         node.add_child(ex->node);
92         this->ex = ex;
93         return true;
94 }
95
96 bool ExhibitSlot::detach_exhibit()
97 {
98         if(!ex) return false;
99
100         node.remove_child(ex->node);
101         ex = 0;
102         return true;
103 }
104
105
106 // ---- exhibit manager implementation ----
107
108 ExhibitManager::ExhibitManager()
109 {
110         own_scn = 0;
111 }
112
113 ExhibitManager::~ExhibitManager()
114 {
115         clear();
116 }
117
118 void ExhibitManager::clear()
119 {
120         // not deleting exhibit objects, as they will be deleted the own_scn destructor
121         items.clear();
122
123         int num = (int)exslots.size();
124         for(int i=0; i<num; i++) {
125                 delete exslots[i];
126         }
127         exslots.clear();
128
129         delete own_scn; // this must be the last thing to destroy
130 }
131
132 void ExhibitManager::add(Exhibit *ex)
133 {
134         std::vector<Exhibit*>::iterator it = std::find(items.begin(), items.end(), ex);
135         if(it == items.end()) {
136                 items.push_back(ex);
137                 own_scn->add_object(ex);
138                 if(ex->node) own_scn->add_node(ex->node);
139         }
140 }
141
142 bool ExhibitManager::remove(Exhibit *ex)
143 {
144         std::vector<Exhibit*>::iterator it = std::find(items.begin(), items.end(), ex);
145         if(it != items.end()) {
146                 items.erase(it);
147                 own_scn->remove_object(ex);
148                 if(ex->node) own_scn->remove_node(ex->node);
149                 return true;
150         }
151         return false;
152 }
153
154 bool ExhibitManager::load(MetaScene *mscn, const char *fname)
155 {
156         struct ts_node *root = ts_load(fname);
157         if(!root || strcmp(root->name, "exhibits") != 0) {
158                 ts_free_tree(root);
159                 error_log("failed to load exhibits\n");
160                 return false;
161         }
162
163         /* create our own scene to manage all exhibits not already in an existing scene
164          * and add it to the metascene.
165          * Also exhibit drawing happens due to the renderer drawing the metascene
166          */
167         if(!own_scn) {
168                 own_scn = new Scene;
169                 own_scn->name = "ad-hoc exhibits";
170                 mscn->scenes.push_back(own_scn);
171         }
172
173         struct ts_node *iter = root->child_list;
174         while(iter) {
175                 struct ts_node *node = iter;
176                 iter = iter->next;
177
178                 SceneNode *snode = 0;
179
180                 if(strcmp(node->name, "item") == 0) {
181                         Exhibit *ex;
182                         const char *atype = ts_get_attr_str(node, "type");
183                         if(!atype || !(ex = create_exhibit(atype))) {
184                                 error_log("failed to create exhibit of type: %s\n", atype);
185                                 continue;
186                         }
187                         const char *alabel = ts_get_attr_str(node, "label");
188                         if(alabel) {
189                                 ex->set_name(alabel);
190                         }
191
192                         const char *amatch = ts_get_attr_str(node, "match_node");
193                         if(amatch) {
194                                 if(!(snode = mscn->match_node(amatch))) {
195                                         error_log("ExhibitManager::load: regexp \"%s\" didn't match any nodes\n",
196                                                         amatch ? amatch : "");
197                                         continue;
198                                 }
199                         }
200
201                         // add everything to our data structures
202                         // equivalent to add_exhibit(ex), but without all the searching
203                         own_scn->add_object(ex);
204                         if(!snode) {
205                                 snode = new SceneNode;
206                                 snode->set_name(ex->get_name());
207                                 own_scn->add_node(snode);
208                         }
209                         ex->set_node(snode);
210                         items.push_back(ex);
211
212                         float *apos = ts_get_attr_vec(node, "pos");
213                         if(apos) {
214                                 snode->set_position(Vec3(apos[0], apos[1], apos[2]));
215                         }
216                         float *arot_axis = ts_get_attr_vec(node, "rotaxis");
217                         if(arot_axis) {
218                                 float arot_angle = ts_get_attr_num(node, "rotangle", 0.0f);
219                                 Vec3 axis = Vec3(arot_axis[0], arot_axis[1], arot_axis[2]);
220                                 Quat q;
221                                 q.set_rotation(axis, deg_to_rad(arot_angle));
222                                 snode->set_rotation(q);
223                         }
224                         struct ts_attr *ascale = ts_get_attr(node, "scale");
225                         if(ascale) {
226                                 switch(ascale->val.type) {
227                                 case TS_NUMBER:
228                                         snode->set_scaling(Vec3(ascale->val.fnum, ascale->val.fnum, ascale->val.fnum));
229                                         break;
230                                 case TS_VECTOR:
231                                         snode->set_scaling(Vec3(ascale->val.vec[0], ascale->val.vec[1], ascale->val.vec[2]));
232                                 default:
233                                         break;
234                                 }
235                         }
236
237                         // create a new slot and attach the exhibit to it
238                         ExhibitSlot *slot = new ExhibitSlot(ex);
239                         exslots.push_back(slot);
240
241                         // grab any extra exhibit data
242                         const char *desc = ts_get_attr_str(node, "description");
243                         const char *voice = ts_get_attr_str(node, "voiceover");
244                         if(desc || voice) {
245                                 ExData exd;
246
247                                 if(desc) {
248                                         char *fixed_desc = new char[strlen(desc) + 1];
249                                         clean_desc_text(fixed_desc, desc);
250                                         exd.text = std::string(fixed_desc);
251                                         delete [] fixed_desc;
252                                 }
253                                 if(voice) {
254                                         exd.voice = new OggVorbisStream;
255                                         if(!exd.voice->open(voice)) {
256                                                 error_log("failed to open voiceover: %s\n", voice);
257                                                 delete exd.voice;
258                                                 exd.voice = 0;
259                                         }
260                                 }
261                                 ex->data.push_back(exd);
262                         }
263                 }
264         }
265
266         ts_free_tree(root);
267         return true;
268 }
269
270 ExSelection ExhibitManager::select(const Ray &ray) const
271 {
272         ExSelection nearest;
273         nearest.dist = FLT_MAX;
274
275         int nitems = items.size();
276         for(int i=0; i<nitems; i++) {
277                 ExSelection sel = items[i]->select(ray);
278                 if(sel && sel.dist < nearest.dist) {
279                         nearest = sel;
280                 }
281         }
282
283         return nearest;
284 }
285
286 ExSelection ExhibitManager::select(const Sphere &sph) const
287 {
288         int nitems = items.size();
289         for(int i=0; i<nitems; i++) {
290                 ExSelection sel = items[i]->select(sph);
291                 if(sel) {
292                         return sel;
293                 }
294         }
295         return ExSelection();
296 }
297
298 // TODO optimize
299 ExhibitSlot *ExhibitManager::nearest_empty_slot(const Vec3 &pos, float max_dist) const
300 {
301         ExhibitSlot *nearest = 0;
302         float nearest_sqdist = max_dist * max_dist;
303
304         int nslots = exslots.size();
305         for(int i=0; i<nslots; i++) {
306                 ExhibitSlot *slot = exslots[i];
307                 if(!slot->empty()) continue;
308
309                 Vec3 slotpos = slot->node.get_position();
310                 float dsq = length_sq(pos - slotpos);
311                 if(dsq < nearest_sqdist) {
312                         nearest = slot;
313                         nearest_sqdist = dsq;
314                 }
315         }
316
317         return nearest;
318 }
319
320 void ExhibitManager::stash_exhibit(Exhibit *ex)
321 {
322         // make sure it's not already stashed
323         if(std::find(stashed.begin(), stashed.end(), ex) != stashed.end()) {
324                 return;
325         }
326         stashed.push_back(ex);
327
328         ex->prev_slot = 0;
329         if(ex->node->get_parent()) {
330                 ex->node->get_parent()->remove_child(ex->node);
331         }
332 }
333
334 void ExhibitManager::update(float dt)
335 {
336         int num = items.size();
337         for(int i=0; i<num; i++) {
338                 // if the exhibit is not part of a scene graph, first call its
339                 // node's update function (otherwise it would have been called recursively earlier)
340                 if(items[i]->node && !items[i]->node->get_parent()) {
341                         items[i]->node->update(dt);
342                 }
343                 items[i]->update(dt);
344         }
345 }
346
347 void ExhibitManager::draw() const
348 {
349         int num = items.size();
350         for(int i=0; i<num; i++) {
351                 if(exsel_hover.ex == items[i]) {
352                         const AABox &bvol = items[i]->get_aabox();
353                         draw_geom_object(&bvol);
354                 }
355         }
356 }
357
358 static Exhibit *create_exhibit(const char *type)
359 {
360         if(strcmp(type, "static") == 0) {
361                 debug_log("creating static exhibit\n");
362                 return new Exhibit;
363         } else if(strcmp(type, "blobs") == 0) {
364                 debug_log("creating blobs exhibit\n");
365                 BlobExhibit *b = new BlobExhibit;
366                 if(!b->init()) {
367                         delete b;
368                         error_log("failed to initialize blobs exhibit\n");
369                         return 0;
370                 }
371                 return b;
372         }
373         error_log("unknown exhibit type: %s\n", type);
374         return 0;
375 }
376
377 /* clean up description text to be more easily layed out later.
378  * more specifically:
379  *  - remove redundant spaces
380  *  - remove all newlines except as paragraph separators
381  *  - remove all other whitespace chars
382  * destination buffer must be as large as the source buffer
383  */
384 static void clean_desc_text(char *dest, const char *src)
385 {
386         while(*src) {
387                 if(isspace(*src)) {
388                         if(*src == '\n' && *(src + 1) == '\n') {
389                                 *dest++ = '\n';
390                         } else {
391                                 *dest++ = ' ';
392                         }
393                         while(*src && isspace(*src)) ++src;
394                 } else {
395                         *dest++ = *src++;
396                 }
397         }
398         *dest = 0;
399 }