hand-tracking and exhibits part one
[laserbrain_demo] / src / geom.cc
1 #include <algorithm>
2 #include <float.h>
3 #include "geom.h"
4 #include "app.h"
5
6 #define SPHERE(ptr)     ((Sphere*)ptr)
7 #define AABOX(ptr)      ((AABox*)ptr)
8 #define BOX(ptr)        ((Box*)ptr)
9 #define PLANE(ptr)      ((Plane*)ptr)
10
11 GeomObject::GeomObject()
12 {
13         type = GOBJ_UNKNOWN;
14 }
15
16 GeomObject::~GeomObject()
17 {
18 }
19
20 bool GeomObject::valid() const
21 {
22         return true;
23 }
24
25 void GeomObject::invalidate()
26 {
27 }
28
29 float GeomObject::distance(const Vec3 &v) const
30 {
31         return sqrt(distance_sq(v));
32 }
33
34 float GeomObject::signed_distance(const Vec3 &v) const
35 {
36         return sqrt(signed_distance_sq(v));
37 }
38
39 Sphere::Sphere()
40 {
41         type = GOBJ_SPHERE;
42         radius = 1.0;
43 }
44
45 Sphere::Sphere(const Vec3 &cent, float radius)
46         : center(cent)
47 {
48         type = GOBJ_SPHERE;
49         this->radius = radius;
50 }
51
52 bool Sphere::valid() const
53 {
54         return radius >= 0.0f;
55 }
56
57 void Sphere::invalidate()
58 {
59         center = Vec3(0, 0, 0);
60         radius = -1;
61 }
62
63 bool Sphere::intersect(const Ray &ray, HitPoint *hit) const
64 {
65         float a = dot(ray.dir, ray.dir);
66         float b = 2.0 * ray.dir.x * (ray.origin.x - center.x) +
67                 2.0 * ray.dir.y * (ray.origin.y - center.y) +
68                 2.0 * ray.dir.z * (ray.origin.z - center.z);
69         float c = dot(ray.origin, ray.origin) + dot(center, center) -
70                 2.0 * dot(ray.origin, center) - radius * radius;
71
72         float discr = b * b - 4.0 * a * c;
73         if(discr < 1e-4) {
74                 return false;
75         }
76
77         float sqrt_discr = sqrt(discr);
78         float t0 = (-b + sqrt_discr) / (2.0 * a);
79         float t1 = (-b - sqrt_discr) / (2.0 * a);
80
81         if(t0 < 1e-4)
82                 t0 = t1;
83         if(t1 < 1e-4)
84                 t1 = t0;
85
86         float t = t0 < t1 ? t0 : t1;
87         if(t < 1e-4) {
88                 return false;
89         }
90
91         // fill the HitPoint structure
92         if(hit) {
93                 hit->obj = this;
94                 hit->dist = t;
95                 hit->pos = ray.origin + ray.dir * t;
96                 hit->normal = (hit->pos - center) / radius;
97         }
98         return true;
99 }
100
101 bool Sphere::contains(const Vec3 &pt) const
102 {
103         return length_sq(pt - center) <= radius * radius;
104 }
105
106 float Sphere::distance_sq(const Vec3 &v) const
107 {
108         return std::max(length_sq(v - center) - radius * radius, 0.0f);
109 }
110
111 float Sphere::signed_distance_sq(const Vec3 &v) const
112 {
113         return length_sq(v - center) - radius * radius;
114 }
115
116 AABox::AABox()
117 {
118         type = GOBJ_AABOX;
119 }
120
121 AABox::AABox(const Vec3 &vmin, const Vec3 &vmax)
122         : min(vmin), max(vmax)
123 {
124         type = GOBJ_AABOX;
125 }
126
127 bool AABox::valid() const
128 {
129         return min.x <= max.x && min.y <= max.y && min.z <= max.z;
130 }
131
132 void AABox::invalidate()
133 {
134         min = Vec3(FLT_MAX, FLT_MAX, FLT_MAX);
135         max = Vec3(-FLT_MAX, -FLT_MAX, -FLT_MAX);
136 }
137
138 Vec3 AABox::get_corner(int idx) const
139 {
140         Vec3 v[] = {min, max};
141         static const int xidx[] = {0, 1, 1, 0, 0, 1, 1, 0};
142         static const int yidx[] = {0, 0, 0, 0, 1, 1, 1, 1};
143         static const int zidx[] = {0, 0, 1, 1, 0, 0, 1, 1};
144         return Vec3(v[xidx[idx]].x, v[yidx[idx]].y, v[zidx[idx]].z);
145 }
146
147 bool AABox::intersect(const Ray &ray, HitPoint *hit) const
148 {
149         Vec3 param[2] = {min, max};
150 #ifndef NDEBUG
151         Vec3 inv_dir;
152         if(fpexcept_enabled) {
153                 inv_dir.x = ray.dir.x == 0.0f ? 1.0f : 1.0f / ray.dir.x;
154                 inv_dir.y = ray.dir.y == 0.0f ? 1.0f : 1.0f / ray.dir.y;
155                 inv_dir.z = ray.dir.z == 0.0f ? 1.0f : 1.0f / ray.dir.z;
156         } else {
157                 inv_dir = Vec3(1.0 / ray.dir.x, 1.0 / ray.dir.y, 1.0 / ray.dir.z);
158         }
159 #else
160         Vec3 inv_dir(1.0 / ray.dir.x, 1.0 / ray.dir.y, 1.0 / ray.dir.z);
161 #endif
162         int sign[3] = {inv_dir.x < 0, inv_dir.y < 0, inv_dir.z < 0};
163
164         float tmin = (param[sign[0]].x - ray.origin.x) * inv_dir.x;
165         float tmax = (param[1 - sign[0]].x - ray.origin.x) * inv_dir.x;
166         float tymin = (param[sign[1]].y - ray.origin.y) * inv_dir.y;
167         float tymax = (param[1 - sign[1]].y - ray.origin.y) * inv_dir.y;
168
169         if(tmin > tymax || tymin > tmax) {
170                 return false;
171         }
172         if(tymin > tmin) {
173                 tmin = tymin;
174         }
175         if(tymax < tmax) {
176                 tmax = tymax;
177         }
178
179         float tzmin = (param[sign[2]].z - ray.origin.z) * inv_dir.z;
180         float tzmax = (param[1 - sign[2]].z - ray.origin.z) * inv_dir.z;
181
182         if(tmin > tzmax || tzmin > tmax) {
183                 return false;
184         }
185         if(tzmin > tmin) {
186                 tmin = tzmin;
187         }
188         if(tzmax < tmax) {
189                 tmax = tzmax;
190         }
191
192         float t = tmin < 1e-4 ? tmax : tmin;
193         if(t >= 1e-4) {
194
195                 if(hit) {
196                         hit->obj = this;
197                         hit->dist = t;
198                         hit->pos = ray.origin + ray.dir * t;
199
200                         float min_dist = FLT_MAX;
201                         Vec3 offs = min + (max - min) / 2.0;
202                         Vec3 local_hit = hit->pos - offs;
203
204                         static const Vec3 axis[] = {
205                                 Vec3(1, 0, 0), Vec3(0, 1, 0), Vec3(0, 0, 1)
206                         };
207                         //int tcidx[][2] = {{2, 1}, {0, 2}, {0, 1}};
208
209                         for(int i=0; i<3; i++) {
210                                 float dist = fabs((max[i] - offs[i]) - fabs(local_hit[i]));
211                                 if(dist < min_dist) {
212                                         min_dist = dist;
213                                         hit->normal = axis[i] * (local_hit[i] < 0.0 ? 1.0 : -1.0);
214                                         //hit->texcoord = Vec2(hit->pos[tcidx[i][0]], hit->pos[tcidx[i][1]]);
215                                 }
216                         }
217                 }
218                 return true;
219         }
220         return false;
221 }
222
223 bool AABox::contains(const Vec3 &v) const
224 {
225         return v.x >= min.x && v.y >= min.y && v.z >= min.z &&
226                 v.x <= max.x && v.y <= max.y && v.z <= max.z;
227 }
228
229 #define SQ(x)   ((x) * (x))
230 float AABox::distance_sq(const Vec3 &v) const
231 {
232         float dsq = 0.0f;
233
234         for(int i=0; i<3; i++) {
235                 if(v[i] < min[i]) dsq += SQ(min[i] - v[i]);
236                 if(v[i] > max[i]) dsq += SQ(v[i] - max[i]);
237         }
238         return dsq;
239 }
240
241 float AABox::signed_distance_sq(const Vec3 &v) const
242 {
243         if(!contains(v)) {
244                 return distance_sq(v);
245         }
246
247         float dsq = 0.0f;
248         for(int i=0; i<3; i++) {
249                 float dmin = v[i] - min[i];
250                 float dmax = max[i] - v[i];
251                 dsq -= dmin < dmax ? SQ(dmin) : SQ(dmax);
252         }
253         return dsq;
254 }
255
256 Box::Box()
257 {
258         type = GOBJ_BOX;
259 }
260
261 Box::Box(const AABox &aabox, const Mat4 &xform)
262         : xform(xform)
263 {
264         type = GOBJ_BOX;
265         min = aabox.min;
266         max = aabox.max;
267 }
268
269 void Box::invalidate()
270 {
271         AABox::invalidate();
272         xform = Mat4::identity;
273 }
274
275 Box::Box(const Vec3 &min, const Vec3 &max)
276         : AABox(min, max)
277 {
278         type = GOBJ_BOX;
279 }
280
281 Box::Box(const Vec3 &min, const Vec3 &max, const Mat4 &xform)
282         : AABox(min, max), xform(xform)
283 {
284         type = GOBJ_BOX;
285 }
286
287 // XXX all this shit is completely untested
288 Box::Box(const Vec3 &pos, const Vec3 &vi, const Vec3 &vj, const Vec3 &vk)
289 {
290         type = GOBJ_BOX;
291         float ilen = length(vi);
292         float jlen = length(vj);
293         float klen = length(vk);
294
295         min = Vec3(-ilen, -jlen, -klen);
296         max = Vec3(ilen, jlen, klen);
297
298         float si = ilen == 0.0 ? 1.0 : 1.0 / ilen;
299         float sj = jlen == 0.0 ? 1.0 : 1.0 / jlen;
300         float sk = klen == 0.0 ? 1.0 : 1.0 / klen;
301
302         xform = Mat4(vi * si, vj * sj, vk * sk);
303         xform.translate(pos);
304 }
305
306 Box::Box(const Vec3 *varr, int vcount)
307 {
308         type = GOBJ_BOX;
309         calc_bounding_aabox(this, varr, vcount);
310 }
311
312 Vec3 Box::get_corner(int idx) const
313 {
314         return xform * AABox::get_corner(idx);
315 }
316
317 bool Box::intersect(const Ray &ray, HitPoint *hit) const
318 {
319         Mat4 inv_xform = inverse(xform);
320         Mat4 dir_inv_xform = inv_xform.upper3x3();
321         Mat4 dir_xform = transpose(dir_inv_xform);
322         Ray local_ray = Ray(inv_xform * ray.origin, dir_inv_xform * ray.dir);
323
324         bool res = AABox::intersect(local_ray, hit);
325         if(!res || !hit) return res;
326
327         hit->pos = xform * hit->pos;
328         hit->normal = dir_xform * hit->normal;
329         hit->local_ray = local_ray;
330         hit->ray = ray;
331         return true;
332 }
333
334 bool Box::contains(const Vec3 &pt) const
335 {
336         // XXX is it faster to extract 6 planes and do dot products? sounds marginal
337         return AABox::contains(inverse(xform) * pt);
338 }
339
340 float Box::distance_sq(const Vec3 &v) const
341 {
342         return 0.0f;    // TODO
343 }
344
345 float Box::signed_distance_sq(const Vec3 &v) const
346 {
347         return 0.0f;    // TODO
348 }
349
350 Plane::Plane()
351         : normal(0.0, 1.0, 0.0)
352 {
353         type = GOBJ_PLANE;
354 }
355
356 Plane::Plane(const Vec3 &p, const Vec3 &norm)
357         : pt(p)
358 {
359         type = GOBJ_PLANE;
360         normal = normalize(norm);
361 }
362
363 Plane::Plane(const Vec3 &p1, const Vec3 &p2, const Vec3 &p3)
364         : pt(p1)
365 {
366         type = GOBJ_PLANE;
367         normal = normalize(cross(p2 - p1, p3 - p1));
368 }
369
370 Plane::Plane(const Vec3 &normal, float dist)
371 {
372         type = GOBJ_PLANE;
373         this->normal = normalize(normal);
374         pt = this->normal * dist;
375 }
376
377 bool Plane::intersect(const Ray &ray, HitPoint *hit) const
378 {
379         float ndotdir = dot(normal, ray.dir);
380         if(fabs(ndotdir) < 1e-4) {
381                 return false;
382         }
383
384         if(hit) {
385                 Vec3 ptdir = pt - ray.origin;
386                 float t = dot(normal, ptdir) / ndotdir;
387
388                 hit->dist = t;
389                 hit->pos = ray.origin + ray.dir * t;
390                 hit->normal = normal;
391                 hit->obj = this;
392         }
393         return true;
394 }
395
396 bool Plane::contains(const Vec3 &v) const
397 {
398         return dot(v, normal) <= 0.0;
399 }
400
401 float Plane::distance(const Vec3 &v) const
402 {
403         return std::max(dot(v - pt, normal), 0.0f);
404 }
405
406 float Plane::signed_distance(const Vec3 &v) const
407 {
408         return dot(v - pt, normal);
409 }
410
411 float Plane::distance_sq(const Vec3 &v) const
412 {
413         float d = distance(v);
414         return d * d;
415 }
416
417 float Plane::signed_distance_sq(const Vec3 &v) const
418 {
419         float d = distance(v);
420         return dot(v, normal) >= 0.0f ? d * d : -(d * d);
421 }
422
423
424 Disc::Disc()
425 {
426         type = GOBJ_DISC;
427         radius = 1.0;
428 }
429
430 Disc::Disc(const Vec3 &pt, const Vec3 &normal, float rad)
431         : Plane(pt, normal)
432 {
433         type = GOBJ_DISC;
434         radius = rad;
435 }
436
437 Disc::Disc(const Vec3 &normal, float dist, float rad)
438         : Plane(normal, dist)
439 {
440         type = GOBJ_DISC;
441         radius = rad;
442 }
443
444 bool Disc::valid() const
445 {
446         return radius >= 0.0f;
447 }
448
449 void Disc::invalidate()
450 {
451         radius = -1;
452 }
453
454 bool Disc::intersect(const Ray &ray, HitPoint *hit) const
455 {
456         HitPoint phit;
457         if(Plane::intersect(ray, &phit)) {
458                 if(length_sq(phit.pos - pt) <= radius * radius) {
459                         *hit = phit;
460                         return true;
461                 }
462         }
463         return false;
464 }
465
466 bool Disc::contains(const Vec3 &pt) const
467 {
468         Vec3 pj = proj_point_plane(pt, *this);
469         return length_sq(pj - this->pt) <= radius * radius;
470 }
471
472 float Disc::distance_sq(const Vec3 &v) const
473 {
474         return 0.0;     // TODO
475 }
476
477 float Disc::signed_distance_sq(const Vec3 &v) const
478 {
479         return 0.0;     // TODO
480 }
481
482
483 Vec3 proj_point_plane(const Vec3 &pt, const Plane &plane)
484 {
485         float dist = plane.signed_distance(pt);
486         return pt - plane.normal * dist;
487 }
488
489 // ---- bounding sphere calculations ----
490
491 bool calc_bounding_sphere(Sphere *sph, const GeomObject *obj)
492 {
493         if(!obj->valid()) {
494                 sph->invalidate();
495                 return true;
496         }
497
498         switch(obj->type) {
499         case GOBJ_SPHERE:
500                 *sph = *(Sphere*)obj;
501                 break;
502
503         case GOBJ_AABOX:
504                 sph->center = (AABOX(obj)->min + AABOX(obj)->max) * 0.5;
505                 sph->radius = length(AABOX(obj)->max - AABOX(obj)->min) * 0.5;
506                 break;
507
508         case GOBJ_BOX:
509                 sph->center = (BOX(obj)->min + BOX(obj)->max) * 0.5 + BOX(obj)->xform.get_translation();
510                 sph->radius = length(BOX(obj)->max - BOX(obj)->min) * 0.5;
511                 break;
512
513         case GOBJ_PLANE:
514         default:
515                 return false;
516         }
517         return true;
518 }
519
520 bool calc_bounding_sphere(Sphere *sph, const GeomObject *a, const GeomObject *b)
521 {
522         Sphere bsa, bsb;
523
524         if(!calc_bounding_sphere(&bsa, a) || !calc_bounding_sphere(&bsb, b)) {
525                 return false;
526         }
527
528         float dist = length(bsa.center - bsb.center);
529         float surf_dist = dist - (bsa.radius + bsb.radius);
530         float d1 = bsa.radius + surf_dist / 2.0;
531         float d2 = bsb.radius + surf_dist / 2.0;
532         float t = d1 / (d1 + d2);
533
534         if(t < 0.0) t = 0.0;
535         if(t > 1.0) t = 1.0;
536
537         sph->center = bsa.center * t + bsb.center * (1.0 - t);
538         sph->radius = std::max(dist * t + bsb.radius, dist * (1.0f - t) + bsa.radius);
539         return true;
540 }
541
542 bool calc_bounding_sphere(Sphere *sph, const GeomObject **objv, int num)
543 {
544         if(num <= 0) return false;
545
546         if(!calc_bounding_sphere(sph, objv[0])) {
547                 return false;
548         }
549
550         for(int i=1; i<num; i++) {
551                 if(!calc_bounding_sphere(sph, sph, objv[i])) {
552                         return false;
553                 }
554         }
555         return true;
556 }
557
558 bool calc_bounding_sphere(Sphere *sph, const Vec3 *v, int num, const Mat4 &xform)
559 {
560         if(num <= 0) return false;
561
562         sph->center = Vec3(0.0, 0.0, 0.0);
563         for(int i=0; i<num; i++) {
564                 sph->center += xform * v[i];
565         }
566         sph->center /= (float)num;
567
568         float rad_sq = 0.0f;
569         for(int i=0; i<num; i++) {
570                 Vec3 dir = xform * v[i] - sph->center;
571                 rad_sq = std::max(rad_sq, dot(dir, dir));
572         }
573         sph->radius = sqrt(rad_sq);
574         return true;
575 }
576
577 bool calc_bounding_aabox(AABox *box, const GeomObject *obj)
578 {
579         if(!obj->valid()) {
580                 box->invalidate();
581                 return true;
582         }
583
584         switch(obj->type) {
585         case GOBJ_AABOX:
586                 *box = *(AABox*)obj;
587                 break;
588
589         case GOBJ_BOX:
590                 {
591                         Vec3 v[8];
592                         for(int i=0; i<8; i++) {
593                                 v[i] = BOX(obj)->get_corner(i);
594                         }
595                         calc_bounding_aabox(box, v, 8);
596                 }
597                 break;
598
599         case GOBJ_SPHERE:
600                 {
601                         float r = SPHERE(obj)->radius;
602                         box->min = SPHERE(obj)->center - Vec3(r, r, r);
603                         box->max = SPHERE(obj)->center + Vec3(r, r, r);
604                 }
605                 break;
606
607         case GOBJ_PLANE:
608         default:
609                 return false;
610         }
611         return true;
612 }
613
614 bool calc_bounding_aabox(AABox *box, const GeomObject *a, const GeomObject *b)
615 {
616         AABox bba, bbb;
617
618         if(!calc_bounding_aabox(&bba, a) || !calc_bounding_aabox(&bbb, b)) {
619                 return false;
620         }
621
622         for(int i=0; i<3; i++) {
623                 box->min[i] = std::min(bba.min[i], bbb.min[i]);
624                 box->max[i] = std::max(bba.max[i], bbb.max[i]);
625         }
626         return true;
627 }
628
629 bool calc_bounding_aabox(AABox *box, const GeomObject **objv, int num)
630 {
631         if(num <= 0) return false;
632
633         if(!calc_bounding_aabox(box, objv[0])) {
634                 return false;
635         }
636
637         for(int i=1; i<num; i++) {
638                 if(!calc_bounding_aabox(box, box, objv[i])) {
639                         return false;
640                 }
641         }
642         return true;
643 }
644
645 bool calc_bounding_aabox(AABox *box, const Vec3 *v, int num, const Mat4 &xform)
646 {
647         if(num <= 0) return false;
648
649         box->min = box->max = xform * v[0];
650         for(int i=1; i<num; i++) {
651                 Vec3 p = xform * v[i];
652
653                 for(int j=0; j<3; j++) {
654                         box->min[j] = std::min(box->min[j], p[j]);
655                         box->max[j] = std::max(box->max[j], p[j]);
656                 }
657         }
658         return true;
659 }
660
661 bool calc_bounding_box(Box *box, const GeomObject *obj)
662 {
663         if(!obj->valid()) {
664                 box->invalidate();
665                 return true;
666         }
667
668         switch(obj->type) {
669         case GOBJ_BOX:
670                 *box = *(Box*)obj;
671                 break;
672
673         case GOBJ_AABOX:
674                 box->min = BOX(obj)->min;
675                 box->max = BOX(obj)->max;
676                 box->xform = Mat4::identity;
677                 break;
678
679         case GOBJ_SPHERE:
680                 {
681                         float r = SPHERE(obj)->radius;
682                         box->min = SPHERE(obj)->center - Vec3(r, r, r);
683                         box->max = SPHERE(obj)->center + Vec3(r, r, r);
684                         box->xform = Mat4::identity;
685                 }
686                 break;
687
688         case GOBJ_PLANE:
689         default:
690                 return false;
691         }
692         return true;
693 }
694
695 bool intersect_sphere_sphere(Disc *result, const Sphere &a, const Sphere &b)
696 {
697         Vec3 dir = b.center - a.center;
698
699         float dist_sq = length_sq(dir);
700         if(dist_sq <= 1e-8) return false;
701
702         float rsum = a.radius + b.radius;
703         float rdif = fabs(a.radius - b.radius);
704         if(dist_sq > rsum * rsum || dist_sq < rdif * rdif) {
705                 return false;
706         }
707
708         float dist = sqrt(dist_sq);
709         float t = (dist_sq + a.radius * a.radius - b.radius * b.radius) / (2.0 * sqrt(dist_sq));
710
711         result->pt = a.center + dir * t;
712         result->normal = dir / dist;
713         result->radius = sin(acos(t)) * a.radius;
714         return true;
715 }
716
717 bool intersect_plane_plane(Ray *result, const Plane &a, const Plane &b)
718 {
719         return false;   // TODO
720 }
721
722 bool intersect_sphere_plane(Sphere *result, const Sphere &s, const Plane &p)
723 {
724         return false;   // TODO
725 }
726
727 bool intersect_plane_sphere(Sphere *result, const Plane &p, const Sphere &s)
728 {
729         return false;   // TODO
730 }
731
732 bool intersect_aabox_aabox(AABox *res, const AABox &a, const AABox &b)
733 {
734         for(int i=0; i<3; i++) {
735                 res->min[i] = std::max(a.min[i], b.min[i]);
736                 res->max[i] = std::min(a.max[i], b.max[i]);
737
738                 if(res->max[i] < res->min[i]) {
739                         res->max[i] = res->min[i];
740                 }
741         }
742         return res->min.x != res->max.x && res->min.y != res->max.y && res->min.z != res->max.z;
743 }
744
745 bool collision_sphere_aabox(const Sphere &s, const AABox &b)
746 {
747         return b.distance_sq(s.center) <= s.radius * s.radius;
748 }