252899ce368db7b6387b3a6d0678e446f3eb3f1e
[sdk] / ecere / src / gfx / 3D / Object.ec
1 namespace gfx3D;
2
3 import "Display"
4
5 public enum FrustumPlacement { outside, inside, intersecting };
6
7 public class ObjectFormat
8 {
9    class_data const char * extension;
10    class_property const char * extension
11    {
12       set { class_data(extension) = value; }
13       get { return class_data(extension); }
14    }
15
16    virtual bool ::Load(Object object, const char * fileName, DisplaySystem displaySystem);
17 };
18
19 // TODO: Review these:
20 public class ObjectFlags
21 {
22 public:
23    bool root:1, viewSpace:1, ownMesh:1, translucent:1, flipWindings:1, keysLoaded:1, transform:1, mesh:1, light:1, camera:1;
24    int hierarchy:16:16;
25 };
26
27 public struct Transform
28 {
29    Vector3D position;
30    Quaternion orientation;
31    Vector3Df scaling;
32 };
33
34 /*static float ease(float t, float a, float b)
35 {
36    float k;
37    float s = a + b;
38
39    if (s == 0.0f) return t;
40    if (s > 1.0f)
41    {
42       a /= s;
43       b /= s;
44    }
45    k = 1.0f/(2.0f-a-b);
46    if (t < a) return (k/a)*t*t;
47    if (t < 1.0f - b) return k*(2.0f * t - a);
48    t = 1.0f - t;
49    return 1.0f - (k/b)*t*t;
50 }*/
51
52 public enum FrameTrackType : uint16 { position = 1, rotation, scaling, fov, roll, colorChange, morph, hotSpot, fallOff, hide };
53
54 public class FrameTrackBits
55 {
56    FrameTrackType type;
57    bool loop:1;
58 };
59
60 public struct FrameKey
61 {
62    unsigned int frame;
63    float tension, continuity, bias;
64    float easeFrom, easeTo;
65    union
66    {
67       Vector3Df position;
68       Quaternion orientation;
69       Vector3Df scaling;
70       float roll;
71       float fov;
72       ColorRGB color;
73       float hotSpot;
74       float fallOff;
75    };
76 };
77
78 enum SplinePart { splinePoint, splineA, splineB };
79
80 public class FrameTrack : struct
81 {
82    FrameTrack prev, next;
83    FrameTrackBits type;
84    unsigned int numKeys;
85    FrameKey * keys;
86
87    void Free(void)
88    {
89       delete keys;
90    }
91
92    ~FrameTrack()
93    {
94       Free();
95    }
96
97    float GetFloat(SplinePart what, unsigned int n)
98    {
99       float value;
100       FrameKey *kn_1, *kn, *kn1;
101       float pn_1, pn, pn1;
102       int d1, d2;
103
104       kn = &keys[n];
105       pn = kn->roll;
106
107       if(what == splinePoint)
108          value = pn;
109       else
110       {
111          if(n == 0)
112          {
113             kn1 = &keys[1];
114             pn1 = kn1->roll;
115
116             if(numKeys == 2)
117             {
118                value = pn1 - pn;
119                value *= 1.0f - kn->tension;
120                return value;
121             }
122             if(type.loop)
123             {
124                kn_1 = &keys[numKeys-2];
125                d1 = keys[numKeys-1].frame - kn_1->frame;
126                d2 = kn1->frame - kn->frame;
127             }
128             else
129             {
130                float a1;
131                value = pn1 - pn;
132                value *= 1.5f;
133
134                a1 = GetFloat(splineA, 1);
135                a1 *= 0.5f;
136
137                value -= a1;
138                value *= 1.0f - kn->tension;
139                return value;
140             }
141          }
142          else if(n == numKeys-1)
143          {
144             kn_1 = &keys[n-1];
145             pn_1 = kn_1->roll;
146
147             if(numKeys == 2)
148             {
149                value = pn - pn_1;
150                value *= 1.0f - kn->tension;
151                return value;
152             }
153             if(type.loop)
154             {
155                kn1 = &keys[1];
156                d1 = kn->frame - kn_1->frame;
157                d2 = kn1->frame - keys[0].frame;
158             }
159             else
160             {
161                float bn_1;
162                value = pn - pn_1;
163                value *= 1.5f;
164
165                bn_1 = GetFloat(splineB, n-1);
166                bn_1 *= 0.5f;
167
168                value -= bn_1;
169                value *= 1.0f - kn->tension;
170                return value;
171             }
172          }
173          else
174          {
175             kn_1 = &keys[n-1];
176             kn1 = &keys[n+1];
177             d1 = kn->frame - kn_1->frame;
178             d2 = kn1->frame - kn->frame;
179          }
180          {
181             float C, adjust;
182             float part1, part2;
183
184             pn_1 = kn_1->roll;
185             pn1 = kn1->roll;
186
187             if(what == splineA)
188             {
189                C = kn->continuity;
190                adjust = (float)d1;
191             }
192             else
193             {
194                C = -kn->continuity;
195                adjust = (float)d2;
196             }
197             adjust /= d1 + d2;
198             adjust = 0.5f + (1.0f - Abs(C))*(adjust - 0.5f);
199
200             part1 = pn - pn_1;
201             part1 *= (1.0f + kn->bias)*(1.0f - C);
202
203             part2 = pn1 - pn;
204             part2 *= (1.0f - kn->bias)*(1.0f + C);
205
206             value = part1 + part2;
207             value *= (1.0f - kn->tension)*adjust;
208          }
209       }
210       return value;
211    }
212
213    void GetVector(Vector3Df vector, SplinePart what, unsigned int n)
214    {
215       FrameKey *kn_1, *kn, *kn1;
216       Vector3Df *pn_1, *pn, *pn1;
217       int d1, d2;
218
219       kn = &keys[n];
220       pn = &kn->position;
221
222       if(what == splinePoint)
223          vector = *pn;
224       else
225       {
226          if(n == 0)
227          {
228             kn1 = &keys[1];
229             pn1 = &kn1->position;
230
231             if(numKeys == 2)
232             {
233                vector.Subtract(pn1, pn);
234                vector.Scale(vector, 1.0f - kn->tension);
235                return;
236             }
237             if(type.loop)
238             {
239                kn_1 = &keys[numKeys-2];
240                d1 = keys[numKeys-1].frame - kn_1->frame;
241                d2 = kn1->frame - kn->frame;
242             }
243             else
244             {
245                Vector3Df a1;
246                vector.Subtract(pn1, pn);
247                vector.Scale(vector, 1.5f);
248
249                GetVector(a1, splineA, 1);
250                a1.Scale(a1, 0.5f);
251
252                vector.Subtract(vector, a1);
253                vector.Scale(vector, 1.0f - kn->tension);
254                return;
255             }
256          }
257          else if(n == numKeys-1)
258          {
259             kn_1 = &keys[n-1];
260             pn_1 = &kn_1->position;
261
262             if(numKeys == 2)
263             {
264                vector.Subtract(pn, pn_1);
265                vector.Scale(vector, 1.0f - kn->tension);
266                return;
267             }
268             if(type.loop)
269             {
270                kn1 = &keys[1];
271                d1 = kn->frame - kn_1->frame;
272                d2 = kn1->frame - keys[0].frame;
273             }
274             else
275             {
276                Vector3Df bn_1;
277                vector.Subtract(pn, pn_1);
278                vector.Scale(vector, 1.5f);
279
280                GetVector(&bn_1, splineB, n-1);
281                bn_1.Scale(bn_1, 0.5f);
282
283                vector.Subtract(vector, bn_1);
284                vector.Scale(vector, 1.0f - kn->tension);
285                return;
286             }
287          }
288          else
289          {
290             kn_1 = &keys[n-1];
291             kn1 = &keys[n+1];
292             d1 = kn->frame - kn_1->frame;
293             d2 = kn1->frame - kn->frame;
294          }
295          {
296             float C, adjust;
297             Vector3Df part1, part2;
298
299             pn_1 = &kn_1->position;
300             pn1 = &kn1->position;
301
302             if(what == splineA)
303             {
304                C = kn->continuity;
305                adjust = (float)d1;
306             }
307             else
308             {
309                C = -kn->continuity;
310                adjust = (float)d2;
311             }
312             adjust /= d1 + d2;
313             adjust = 0.5f + (1.0f - Abs(C))*(adjust - 0.5f);
314
315             part1.Subtract(pn, pn_1);
316             part1.Scale(part1, (1.0f + kn->bias)*(1.0f - C));
317
318             part2.Subtract(pn1, pn);
319             part2.Scale(part2, (1.0f - kn->bias)*(1.0f + C));
320
321             vector.Add(part1, part2);
322             vector.Scale(vector, (1.0f - kn->tension)*adjust);
323          }
324       }
325    }
326
327    void GetQuaternion(Quaternion quat, SplinePart what, unsigned int n)
328    {
329       FrameKey *kn_1, *kn, *kn1;
330       Quaternion *qn_1, *qn, *qn1;
331       int d1, d2;
332
333       kn = &keys[n];
334       qn = &kn->orientation;
335
336       if (what == splinePoint)
337          quat = *qn;
338       else
339       {
340          if(n == 0)
341          {
342             kn1 = &keys[1];
343
344             if (!(type.loop) || numKeys <= 2)
345             {
346                qn1 = &kn1->orientation;
347                quat.Slerp(qn, qn1, (1.0f - kn->tension)*(1.0f + kn->continuity*kn->bias)/3.0f);
348                return;
349             }
350             else
351             {
352                kn_1= &keys[numKeys-2];
353                d1 = keys[numKeys-1].frame - kn_1->frame;
354                d2 = kn1->frame - kn->frame;
355             }
356          }
357          else if (n == numKeys-1)
358          {
359             kn_1 = &keys[n-1];
360
361             if (!(type.loop) || numKeys <= 2)
362             {
363                qn_1 = &kn_1->orientation;
364                quat.Slerp(qn, qn_1, (1.0f - kn->tension)*(1.0f - kn->continuity*kn->bias)/3.0f);
365                return;
366             }
367             else
368             {
369                kn1 = &keys[1];
370                d1 = kn->frame - kn_1->frame;
371                d2 = kn1->frame - keys[0].frame;
372             }
373          }
374          else
375          {
376             kn_1 = &keys[n-1];
377             kn1 = &keys[n+1];
378             d1 = kn->frame - kn_1->frame;
379             d2 = kn1->frame - kn->frame;
380          }
381          {
382             float f, adjust;
383             Quaternion g1, g2, tmp;
384
385             qn_1 = &kn_1->orientation;
386             qn1 = &kn1->orientation;
387
388             if (what == splineA)
389             {
390                f = 1.0f;
391                adjust = (float)d1;
392             }
393             else
394             {
395                f = -1.0f;
396                adjust = (float)d2;
397             }
398             adjust /= d1 + d2;
399             adjust = 0.5f + (1.0f - Abs(kn->continuity))*(adjust - 0.5f);
400
401             g1.Slerp(qn, qn_1,-(1.0f + kn->bias)/3.0f);
402             g2.Slerp(qn, qn1 , (1.0f - kn->bias)/3.0f);
403             tmp.Slerp(g1, g2, 0.5f + f*0.5f*kn->continuity);
404             quat.Slerp(qn, &tmp, f*(kn->tension - 1.0f)*adjust*2.0f);
405          }
406       }
407    }
408
409    void Interpolate(Vector3Df vector, Vector3Df prevVector, Vector3Df nextVector, int prev, int next, float t)
410    {
411       if(!t)
412          vector = prevVector;
413       else
414       {
415          Vector3Df p1 = prevVector, p2 = nextVector;
416          Vector3Df r1, r2;
417
418          GetVector(r1, splineB, prev);
419          GetVector(r2, splineA, next);
420
421          p1.Scale(p1, 2*t*t*t - 3*t*t + 1);
422          p2.Scale(p2,-2*t*t*t + 3*t*t);
423
424          r1.Scale(r1, t*t*t - 2*t*t + t);
425          r2.Scale(r2, t*t*t -   t*t);
426
427          vector = p1;
428          vector.Add(vector, r1);
429          vector.Add(vector, p2);
430          vector.Add(vector, r2);
431       }
432    }
433
434    void InterpolateQuat(Quaternion quat, Quaternion prevQuat, Quaternion nextQuat, int prev, int next, float t)
435    {
436       if(!t)
437          quat = prevQuat;
438       else
439       {
440          Quaternion a, b;
441          Quaternion q0, q1, q2;
442
443          GetQuaternion(b, splineB, prev);
444          GetQuaternion(a, splineA, next);
445
446          q0.Slerp(prevQuat, b, t);
447          q1.Slerp(b, a, t);
448          q2.Slerp(a, nextQuat, t);
449
450          q0.Slerp(q0, q1, t);
451          q1.Slerp(q1, q2, t);
452
453          quat.Slerp(q0, q1, t);
454       }
455    }
456
457    float InterpolateFloat(float prevValue, float nextValue, int prev, int next, float t)
458    {
459       float value;
460       if(!t)
461          value = prevValue;
462       else
463       {
464          float p1 = prevValue, p2 = nextValue;
465
466          float r1 = GetFloat(splineB, prev);
467          float r2 = GetFloat(splineA, next);
468
469          p1 *= 2*t*t*t - 3*t*t + 1;
470          p2 *= -2*t*t*t + 3*t*t;
471
472          r1 *= t*t*t - 2*t*t + t;
473          r2 *= t*t*t -   t*t;
474
475          value = p1 + r1 + p2 + r2;
476       }
477       return value;
478    }
479 };
480
481 static bool FindMaterialAndType(Mesh mesh, Material material, PrimitiveGroupType type)
482 {
483    PrimitiveGroup group;
484    for(group = mesh.groups.first; group; group = group.next)
485       if(group.material == material && group.type == type)
486          return true;
487    return false;
488 }
489
490 public class Object
491 {
492 public:
493    void SetMinMaxRadius(bool processMesh)
494    {
495       Object child;
496
497       if(flags.mesh && mesh)
498       {
499          if(processMesh)
500             mesh.SetMinMaxRadius();
501          min = mesh.min;
502          max = mesh.max;
503          volume = (max.x >= min.x && max.y >= min.y && max.z >= min.z);
504       }
505       else
506       {
507          min = { MAXFLOAT, MAXFLOAT, MAXFLOAT };
508          max = { -MAXFLOAT, -MAXFLOAT, -MAXFLOAT };
509          volume = false;
510       }
511       for(child = children.first; child; child = child.next)
512       {
513          child.SetMinMaxRadius(processMesh);
514
515          if(child.volume)
516          {
517             // Child Local + Child Object Transform
518             Vector3Df points[8] =
519             {
520                { child.min.x, child.min.y, child.min.z },
521                { child.min.x, child.min.y, child.max.z },
522                { child.min.x, child.max.y, child.min.z },
523                { child.min.x, child.max.y, child.max.z },
524                { child.max.x, child.min.y, child.min.z },
525                { child.max.x, child.min.y, child.max.z },
526                { child.max.x, child.max.y, child.min.z },
527                { child.max.x, child.max.y, child.max.z }
528             };
529             int c;
530             for(c = 0; c<8; c++)
531             {
532                Vector3Df point;
533                point.MultMatrix(points[c], child.localMatrix);
534
535                if(point.x < min.x) min.x = point.x;
536                if(point.y < min.y) min.y = point.y;
537                if(point.z < min.z) min.z = point.z;
538
539                if(point.x > max.x) max.x = point.x;
540                if(point.y > max.y) max.y = point.y;
541                if(point.z > max.z) max.z = point.z;
542             }
543             volume = true;
544          }
545       }
546
547       if(volume)
548       {
549          Vector3Df points[8] =
550          {
551             { min.x, min.y, min.z },
552             { min.x, min.y, max.z },
553             { min.x, max.y, min.z },
554             { min.x, max.y, max.z },
555             { max.x, min.y, min.z },
556             { max.x, min.y, max.z },
557             { max.x, max.y, min.z },
558             { max.x, max.y, max.z }
559          };
560          Vector3Df halfExtent;
561          Vector3D halfExtentd;
562
563          // Local
564          center.Add(min, max);
565          center.Scale(center, 0.5f);
566          halfExtent.Subtract(max, min);
567          halfExtent.Scale(halfExtent, 0.5f);
568          radius = halfExtent.length;
569
570          // World
571          {
572             Vector3D min { MAXFLOAT, MAXFLOAT, MAXFLOAT };
573             Vector3D max { -MAXFLOAT, -MAXFLOAT, -MAXFLOAT };
574             int c;
575             for(c = 0; c<8; c++)
576             {
577                Vector3D point;
578                point.MultMatrixf(points[c], matrix);
579
580                if(point.x < min.x) min.x = point.x;
581                if(point.y < min.y) min.y = point.y;
582                if(point.z < min.z) min.z = point.z;
583
584                if(point.x > max.x) max.x = point.x;
585                if(point.y > max.y) max.y = point.y;
586                if(point.z > max.z) max.z = point.z;
587             }
588             wmin = min;
589             wmax = max;
590          }
591          wcenter.Add(wmin, wmax);
592          wcenter.Scale(wcenter, 0.5f);
593
594          halfExtentd.Subtract(wmax, wmin);
595          halfExtentd.Scale(halfExtentd, 0.5);
596          wradius = halfExtentd.length;
597       }
598    }
599
600    void Duplicate(Object model)
601    {
602       if(model)
603       {
604          Object modelChild;
605
606          name = CopyString(model.name);
607          flags = model.flags;
608          flags.ownMesh = false;
609          mesh = model.mesh;
610          /*
611          min = model.min;
612          max = model.max;
613          radius = model.radius;
614          */
615          transform = model.transform;
616
617          for(modelChild = model.children.first; modelChild; modelChild = modelChild.next)
618          {
619             Object child { parent = this };
620             child.Duplicate(modelChild);
621             children.AddName(child);
622          }
623       }
624    }
625
626    void Free(DisplaySystem displaySystem)
627    {
628       if(this)
629       {
630          Object child;
631
632          while((child = children.first))
633          {
634             children.Remove(child);
635             child.Free(displaySystem);
636
637             // We did not do this before so as to keep transform on reloading for new DisplaySystem
638             // However since children are removed, it seems that purpose has been gone, we'd need
639             // a new mechanism to handle lost resources reloading...
640             delete child;
641          }
642          if(flags.ownMesh && mesh)
643          {
644             DisplaySystem meshDisplaySystem = mesh.displaySystem;
645             mesh.Free(0);
646             if(meshDisplaySystem)
647                meshDisplaySystem.RemoveMesh(mesh);
648             delete mesh;
649          }
650
651          tracks.Free(FrameTrack::Free);
652
653          delete name;
654       }
655    }
656
657    bool Load(const char * fileName, const char * type, DisplaySystem displaySystem)
658    {
659       char ext[MAX_EXTENSION];
660       subclass(ObjectFormat) format;
661       OldLink link;
662       bool result = false;
663
664       if(!type && fileName)
665          type = strlwr(GetExtension(fileName, ext));
666
667       for(link = class(ObjectFormat).derivatives.first; link; link = link.next)
668       {
669          format = link.data;
670          if(format.extension && !strcmp(format.extension, type))
671             break;
672       }
673       if(!link) format = null;
674
675       if(format)
676       {
677          if((format.Load(this, fileName, displaySystem)))
678             result = true;
679       }
680       /*if(!result)
681           ErrorLogCode(GERR_LOAD_OBJECT_FAILED, fileName);*/
682       return result;
683    }
684
685    void FreeMesh(DisplaySystem displaySystem)
686    {
687       if(this)
688       {
689          Object child;
690          mesh.Free(0);
691          for(child = children.first; child; child = child.next)
692             child.FreeMesh(displaySystem);
693       }
694    }
695
696    Object Find(const char * name)
697    {
698       if(this && name)
699       {
700          Object child;
701
702          if(this.name && !strcmp(this.name, name))
703             return this;
704          else
705          {
706             for(child = children.first; child; child = child.next)
707             {
708                Object result = child.Find(name);
709                if(result)
710                   return result;
711             }
712          }
713       }
714       return null;
715    }
716
717    void Initialize(void)
718    {
719       if(this)
720       {
721          transform.scaling = { 1, 1, 1 };
722          transform.orientation = { 1,0,0,0 };
723          flags.root = true;
724          flags.transform = true;
725          matrix.Identity();
726       }
727    }
728
729    Mesh InitializeMesh(DisplaySystem displaySystem)
730    {
731       if(this)
732       {
733          flags.mesh = true;
734          if(!mesh)
735          {
736             mesh = Mesh { };
737             flags.ownMesh = true;
738          }
739          if(mesh)
740          {
741             FillBytes(mesh, 0, sizeof(class Mesh));
742             displaySystem.AddMesh(mesh);
743          }
744          matrix.Identity();
745          return mesh;
746       }
747       return null;
748    }
749
750    bool AddName(Object object, const char * name)
751    {
752       bool result = false;
753       if(this)
754       {
755          char * newName = CopyString(name);
756          object.name = newName;
757          result = children.AddName(object);
758          if(result)
759             object.parent = this;
760          object.flags.transform = true;
761       }
762       return result;
763    }
764
765    // TODO: Add support to Merge Vertex Colors mesh feature
766    bool Merge(DisplaySystem displaySystem)
767    {
768       bool result = false;
769
770       if(!children.first && (!this.flags.mesh || this.flags.ownMesh))
771          result = true;
772       else
773       {
774          Object child, nextChild;
775          int nVertices = 0;
776          MeshFeatures flags = 0;
777          Mesh objectMesh = this.flags.mesh ? mesh : null;
778          bool freeMesh = this.flags.ownMesh;
779
780          // Count total number of vertices
781          if(objectMesh)
782          {
783             flags |= objectMesh.flags;
784             nVertices += objectMesh.nVertices;
785          }
786
787          for(child = children.first; child; child = child.next)
788          {
789             child.Merge(displaySystem);
790             if(child.mesh)
791             {
792                nVertices += child.mesh.nVertices;
793                flags |= child.mesh.flags;
794             }
795          }
796
797          if(!nVertices)
798             return true;
799
800          if(this.flags.camera)
801             delete camera;
802
803          mesh = Mesh { };
804          this.flags.ownMesh = true;
805          this.flags.mesh = true;
806          displaySystem.AddMesh(mesh);
807
808          if(mesh.Allocate(flags, nVertices, displaySystem))
809          {
810             int c;
811             int nTriangles = 0;
812             int vertexOffset = 0;
813             PrimitiveGroup group = null;
814
815             // Merge vertices
816
817             nVertices = 0;
818             if(objectMesh)
819             {
820                for(c = 0; c<objectMesh.nVertices; c++)
821                {
822                   mesh.vertices[nVertices] = objectMesh.vertices[c];
823
824                   if(objectMesh.normals)
825                      mesh.normals[nVertices] = objectMesh.normals[c];
826                   if(objectMesh.texCoords)
827                      mesh.texCoords[nVertices] = objectMesh.texCoords[c];
828
829                   nVertices++;
830                }
831             }
832
833             for(child = children.first; child; child = child.next)
834             {
835                Matrix matrix, normalMatrix;
836
837                matrix.Identity();
838                matrix.Scale(child.transform.scaling.x, child.transform.scaling.y, child.transform.scaling.z);
839
840                matrix.Rotate(child.transform.orientation);
841
842                normalMatrix = matrix;
843
844                matrix.Translate(child.transform.position.x, child.transform.position.y, child.transform.position.z);
845                if(child.flags.mesh && child.mesh)
846                {
847                   for(c = 0; c<child.mesh.nVertices; c++)
848                   {
849                      mesh.vertices[nVertices].MultMatrix(child.mesh.vertices[c], matrix);
850                      if(child.mesh.normals)
851                         mesh.normals[nVertices].MultMatrix(child.mesh.normals[c], normalMatrix);
852                      if(child.mesh.texCoords)
853                         mesh.texCoords[nVertices] = child.mesh.texCoords[c];
854                      nVertices++;
855                   }
856                }
857             }
858
859             // Merge Indexed Primitive Groups
860             while(true)
861             {
862                int nIndices = 0;
863                PrimitiveGroupType type = (PrimitiveGroupType)-1;
864                Material material = null;
865                bool foundGroup = false;
866
867                // Find first group type/material to process and determine how many indices are required
868                if(objectMesh)
869                {
870                   for(group = objectMesh.groups.first; group; group = group.next)
871                   {
872                      if(!foundGroup && !(group.type.vertexRange))
873                      {
874                         if(!FindMaterialAndType(mesh, group.material, group.type))
875                         {
876                            material = group.material;
877                            type = group.type;
878                            nIndices += group.nIndices;
879                            foundGroup = true;
880                         }
881                      }
882                      else if(material == group.material && type == group.type)
883                         nIndices += group.nIndices;
884                   }
885                }
886
887                for(child = children.first; child; child = child.next)
888                {
889                   if(child.flags.mesh && child.mesh)
890                   {
891                      for(group = child.mesh.groups.first; group; group = group.next)
892                      {
893                         if(!foundGroup && !(group.type.vertexRange))
894                         {
895                            if(!FindMaterialAndType(mesh, group.material ? group.material : child.material, group.type))
896                            {
897                               material = group.material ? group.material : child.material;
898                               type = group.type;
899                               nIndices += group.nIndices;
900                               foundGroup = true;
901                            }
902                         }
903                         else if(material == (group.material ? group.material : child.material) && type == group.type)
904                            nIndices += group.nIndices;
905                      }
906                   }
907                }
908
909                // Merge with all similar groups
910                if(foundGroup)
911                {
912                   PrimitiveGroup newGroup = mesh.AddPrimitiveGroup(type, nIndices);
913                   if(newGroup)
914                   {
915                      newGroup.material = material;
916                      nIndices = 0;
917
918                      vertexOffset = 0;
919
920                      if(objectMesh)
921                      {
922                         for(group = objectMesh.groups.first; group; group = group.next)
923                         {
924                            if(newGroup.material == group.material && newGroup.type == group.type)
925                            {
926                               int c;
927                               if(group.type.indices32bit)
928                                  for(c = 0; c<group.nIndices; c++)
929                                     newGroup.indices32[nIndices++] = group.indices32[c] + vertexOffset;
930                               else
931                                  for(c = 0; c<group.nIndices; c++)
932                                     newGroup.indices[nIndices++] = (uint16)(group.indices[c] + vertexOffset);
933                            }
934                         }
935                         vertexOffset += objectMesh.nVertices;
936                      }
937
938                      for(child = children.first; child; child = child.next)
939                      {
940                         if(child.flags.mesh && child.mesh)
941                         {
942                            for(group = child.mesh.groups.first; group; group = group.next)
943                            {
944                               if(newGroup.material == (group.material ? group.material : child.material) &&
945                                  newGroup.type == group.type)
946                               {
947                                  int c;
948                                  if(group.type.indices32bit)
949                                     for(c = 0; c<group.nIndices; c++)
950                                        newGroup.indices32[nIndices++] = group.indices32[c] + vertexOffset;
951                                  else
952                                     for(c = 0; c<group.nIndices; c++)
953                                        newGroup.indices[nIndices++] = (uint16)(group.indices[c] + vertexOffset);
954                               }
955                            }
956                            vertexOffset += child.mesh.nVertices;
957                         }
958                      }
959                      mesh.UnlockPrimitiveGroup(newGroup);
960                   }
961                }
962                else
963                   break;
964             }
965
966             // Merge Non-Indexed Primitive Groups
967             vertexOffset = 0;
968
969             if(objectMesh)
970             {
971                for(group = objectMesh.groups.first; group; group = group.next)
972                {
973                   if(group.type.vertexRange)
974                   {
975                      PrimitiveGroup newGroup = mesh.AddPrimitiveGroup(group.type, 0);
976                      if(newGroup)
977                      {
978                         newGroup.material = group.material;
979                         newGroup.nVertices = group.nVertices;
980                         newGroup.first = group.first + vertexOffset;
981                      }
982                   }
983                }
984                vertexOffset += objectMesh.nVertices;
985             }
986
987             for(child = children.first; child; child = child.next)
988             {
989                if(child.flags.mesh && child.mesh)
990                {
991                   for(group = child.mesh.groups.first; group; group = group.next)
992                   {
993                      if(group.type.vertexRange)
994                      {
995                         PrimitiveGroup newGroup = mesh.AddPrimitiveGroup(group.type, 0);
996                         if(newGroup)
997                         {
998                            newGroup.material = group.material ? group.material : child.material;
999                            newGroup.nVertices = group.nVertices;
1000                            newGroup.first = group.first + vertexOffset;
1001                         }
1002                      }
1003                   }
1004                   vertexOffset += child.mesh.nVertices;
1005                }
1006             }
1007
1008             // Merge Triangles
1009             if(objectMesh)
1010                nTriangles = objectMesh.nPrimitives;
1011
1012             for(child = children.first; child; child = child.next)
1013             {
1014                if(child.mesh)
1015                   nTriangles += child.mesh.nPrimitives;
1016             }
1017
1018             mesh.primitives = new PrimitiveSingle[nTriangles];
1019             mesh.nPrimitives = 0;
1020             vertexOffset = 0;
1021             if(objectMesh)
1022             {
1023                for(c = 0; c<objectMesh.nPrimitives; c++)
1024                {
1025                   int i;
1026                   PrimitiveSingle * triangle = &mesh.primitives[mesh.nPrimitives++];
1027                   PrimitiveSingle * src = &objectMesh.primitives[c];
1028
1029                   mesh.AllocatePrimitive(triangle, src->type, src->nIndices);
1030                   triangle->material = src->material;
1031                   triangle->middle = src->middle;
1032                   triangle->plane = src->plane;
1033
1034                   //*triangle = *src;
1035                   //src->indices = null;
1036                   //src->data = null;
1037
1038                   if(triangle->type.indices32bit)
1039                      for(i = 0; i<triangle->nIndices; i++)
1040                         triangle->indices32[i] = src->indices32[i] + vertexOffset;
1041                   else
1042                      for(i = 0; i<triangle->nIndices; i++)
1043                         triangle->indices[i] = (uint16)(src->indices[i] + vertexOffset);
1044                   mesh.UnlockPrimitive(triangle);
1045                }
1046                vertexOffset += objectMesh.nVertices;
1047             }
1048
1049             for(child = children.first; child; child = child.next)
1050             {
1051                if(child.flags.mesh && child.mesh)
1052                {
1053                   for(c = 0; c<child.mesh.nPrimitives; c++)
1054                   {
1055                      int i;
1056                      PrimitiveSingle * triangle = &mesh.primitives[mesh.nPrimitives++];
1057                      PrimitiveSingle * src = &child.mesh.primitives[c];
1058
1059                      mesh.AllocatePrimitive(triangle, src->type, src->nIndices);
1060                      triangle->material = src->material ? src->material : child.material;
1061                      triangle->middle = src->middle;
1062                      triangle->plane = src->plane;
1063
1064                      //*triangle = *src;
1065                      //src->indices = null;
1066                      //src->data = null;
1067
1068                      if(triangle->type.indices32bit)
1069                      {
1070                         for(i = 0; i<triangle->nIndices; i++)
1071                            triangle->indices32[i] = src->indices32[i] + vertexOffset;
1072                      }
1073                      else
1074                      {
1075                         for(i = 0; i<triangle->nIndices; i++)
1076                            triangle->indices[i] = (uint16)(src->indices[i] + vertexOffset);
1077                      }
1078                      mesh.UnlockPrimitive(triangle);
1079                   }
1080                   vertexOffset += child.mesh.nVertices;
1081                }
1082             }
1083
1084             // Free children
1085             for(child = children.first; child; child = nextChild)
1086             {
1087                nextChild = child.next;
1088                children.Remove(child);
1089                child.Free(displaySystem);
1090                delete child;
1091             }
1092
1093             mesh.ApplyTranslucency(this);
1094             // this.flags.translucent = true;
1095
1096             result = true;
1097
1098             mesh.Unlock(flags);
1099          }
1100          if(freeMesh && objectMesh)
1101          {
1102             if(objectMesh.displaySystem)
1103                objectMesh.displaySystem.RemoveMesh(objectMesh);
1104             delete objectMesh;
1105          }
1106          SetMinMaxRadius(true);
1107       }
1108       return result;
1109    }
1110
1111    void RotateEuler(Euler rotation, Euler min, Euler max)
1112    {
1113       // WARNING: 'eulerOrientation' is only updated by this function
1114       Euler euler = eulerOrientation;//transform.orientation;
1115       euler.Add(euler, rotation);
1116
1117       if(min && max)
1118       {
1119          if(min.pitch && max.pitch)
1120             euler.pitch = Min(Max(euler.pitch, min.pitch), max.pitch);
1121          if(min.yaw && max.yaw)
1122             euler.yaw = Min(Max(euler.yaw, min.yaw), max.yaw);
1123          if(min.roll && max.roll)
1124             euler.roll = Min(Max(euler.roll, min.roll), max.roll);
1125       }
1126
1127       eulerOrientation = euler;
1128       transform.orientation = euler;
1129       UpdateTransform();
1130    }
1131
1132    void Move(Vector3D direction)
1133    {
1134       Matrix matrix;
1135       Vector3D offset;
1136
1137       matrix.RotationQuaternion(transform.orientation);
1138       offset.MultMatrix(direction, matrix);
1139       transform.position.Add(transform.position, offset);
1140       UpdateTransform();
1141    }
1142
1143    void UpdateTransform(void)
1144    {
1145       SetTransformDirty();
1146       _UpdateTransform();
1147       SetMinMaxRadius(false);
1148    }
1149
1150    void Animate(unsigned int frame)
1151    {
1152       if(this && startFrame != endFrame)
1153       {
1154          while(frame < startFrame) frame += (endFrame - startFrame + 1);
1155          while(frame > endFrame)   frame -= (endFrame - startFrame + 1);
1156
1157          this.frame = frame;
1158          _Animate(frame);
1159          _UpdateTransform();
1160          SetMinMaxRadius(false);
1161       }
1162    }
1163
1164    void DoubleSided(bool flag)
1165    {
1166       if(this)
1167       {
1168          Object child;
1169          mesh.DoubleSided(flag);
1170          for(child = children.first; child; child = child.next)
1171             child.DoubleSided(flag);
1172       }
1173    }
1174
1175    bool IntersectsGroundPolygon(int count, Pointf * pointfs)
1176    {
1177       bool result = false;
1178
1179       Pointf * p1;
1180       Pointf * p2;
1181       double minX = wmin.x, maxX = wmax.x;
1182       double minY = wmin.z, maxY = wmax.z;
1183       double delta = (maxX - minX)/2;
1184       double x = (maxX + minX)/2, y = (maxY + minY)/2;
1185       int c;
1186       for(c = 0; c<count; c++)
1187       {
1188          double d;
1189          p1 = &pointfs[c];
1190          p2 = &pointfs[(c == count-1) ? 0 : (c+1)];
1191
1192          if( (p1->x < minX) &&  (p2->x < minX) )
1193          {
1194             if((p1->y <= y) && (p2->y >  y) )
1195                result ^= true;
1196             else if( (p1->y >  y) && (p2->y <= y) )
1197                result ^= true;
1198          }
1199          else if(!((p1->x > maxX && p2->x > maxX) || (p1->y < minY && p2->y < minY) || (p1->y > maxY && p2->y > maxY)))
1200          {
1201             if(p1->y == p2->y)
1202             {
1203                d = y - p1->y;
1204                if (d < 0) d = -d;
1205                if (d < delta) return true;
1206             }
1207             else if(p1->x == p2->x)
1208             {
1209                d = x - p1->x;
1210                if(d < 0) d = -d;
1211                if(d < delta) return true;
1212                else if(p1->x > x) ;
1213                else if( (p1->y <= y) && (p2->y >  y) )
1214                   result ^= true;
1215                else if( (p1->y >  y) && (p2->y <= y) )
1216                   result ^= true;
1217             }
1218             else
1219             {
1220                float a, b, dy, dx;
1221
1222                a = p2->y - p1->y;
1223                b = p1->x - p2->x;
1224                dy =  a;
1225                dx = -b;
1226                d = a * x + b * y + (p2->x * p1->y) - (p2->y * p1->x);
1227                if (a < 0) a = -a;
1228                if (b < 0) b = -b;
1229                if (d < 0) d = -d;
1230
1231                if(d < a * delta)
1232                   return true;
1233                else if (d < b * delta)
1234                   return true;
1235                else if( ( (p1->y <= y) && (p2->y >  y) ) || ( (p1->y >  y) && (p2->y <= y) ) )
1236                {
1237                   double xdy;
1238
1239                   xdy = (dx * (y - p1->y)) + (dy * p1->x);
1240                   if(dy < 0)
1241                   {
1242                      if(xdy > x * dy)
1243                         result ^= true;
1244                   }
1245                   else if(xdy < x * dy)
1246                      result ^= true;
1247                }
1248             }
1249          }
1250       }
1251       return result;
1252    }
1253
1254    property Transform transform { set { transform = value; eulerOrientation = transform.orientation; } get { value = transform; } };
1255    property Material material { set { material = value; } get { return material; } };
1256    property Vector3Df max { get { value = max; } };
1257    property Vector3Df min { get { value = min; } };
1258    property Vector3Df center { get { value = center; } };
1259    property float radius { get { return radius; } };
1260
1261    property Vector3D wmax { get { value = wmax; } };
1262    property Vector3D wmin { get { value = wmin; } };
1263    property Vector3D wcenter { get { value = wcenter; } };
1264    property double wradius { get { return wradius; } };
1265
1266    property void * tag { set { tag = value; } get { return tag; } };
1267    property int frame { set { Animate(value); } get { return frame; } };
1268    property int startFrame { set { startFrame = value; } get { return startFrame; } };
1269    property int endFrame { set { endFrame = value; } get { return endFrame; } };
1270
1271    property Mesh mesh { set { mesh = value; } get { return mesh; } };
1272    property Camera camera { get { return camera; } }; // Fix this with inheritance? camera inherit from Object?
1273    property Object firstChild { get { return children.first; } };
1274    property Object next { get { return next; } };
1275    property const char * name { get { return name; } };
1276    property Matrix matrix { get { value = matrix; } };
1277    property Object cameraTarget { set { cameraTarget = value; } get { return cameraTarget; } };
1278    property OldList * tracks { /* set { tracks = value; } */ get { return &tracks; } };
1279    property ObjectFlags flags { set { flags = value; } get { return flags; } };
1280
1281 private:
1282    Object()
1283    {
1284       children.offset = (uint)(uintptr)&((Object)0).prev;
1285       transform.scaling = { 1, 1, 1 };
1286       transform.orientation = { 1,0,0,0 };
1287       flags.transform = true;
1288    }
1289
1290    ~Object()
1291    {
1292       Free(null);
1293    }
1294
1295    void SetTransformDirty()
1296    {
1297       Object child;
1298       flags.transform = true;
1299       for(child = children.first; child; child = child.next)
1300          child.SetTransformDirty();
1301    }
1302
1303    void _UpdateTransform()
1304    {
1305       if(flags.transform)
1306       {
1307          Object child;
1308          Matrix matrix;
1309
1310          // Cameras / Spot Lights must update their target first
1311          if(flags.camera && cameraTarget && cameraTarget.flags.transform)
1312             cameraTarget.UpdateTransform();
1313          else if(flags.light && light.flags.spot && light.target && light.target.flags.transform)
1314             light.target._UpdateTransform();
1315
1316          if(flags.camera && cameraTarget)
1317          {
1318             // DeterMine angle to look at target
1319             Vector3D position, direction;
1320             if(flags.root || !parent)
1321                position = transform.position;
1322             else
1323                position.MultMatrix(transform.position, parent.matrix);
1324
1325             direction.Subtract((Vector3D *)cameraTarget.matrix.m[3], position);
1326             transform.orientation.RotationDirection(direction);
1327
1328             // Add the roll
1329             transform.orientation.RotateRoll(roll);
1330          }
1331
1332          if(flags.light && light.flags.spot)
1333          {
1334             // Determine angle to look at target
1335             Vector3D position;
1336             if(flags.root || !parent)
1337                position = transform.position;
1338             else
1339                position.MultMatrix(transform.position, parent.matrix);
1340
1341             if(light.target)
1342                light.direction.Subtract((Vector3D *) light.target.matrix.m[3], position);
1343             else
1344                light.direction = position; // TOCHECK: Why does this happen?
1345
1346             light.direction.Normalize(light.direction);
1347             transform.orientation.RotationDirection(light.direction);
1348          }
1349
1350          matrix.Identity();
1351          matrix.Scale(transform.scaling.x, transform.scaling.y, transform.scaling.z);
1352          matrix.Rotate(transform.orientation);
1353          matrix.Translate(transform.position.x, transform.position.y, transform.position.z);
1354
1355          localMatrix = matrix;
1356
1357          // Compute transform (with ancestors)
1358          if(flags.root || !parent)
1359             this.matrix = matrix;
1360          else
1361             this.matrix.Multiply(matrix, parent.matrix);
1362
1363          flags.transform = false;
1364
1365          for(child = children.first; child; child = child.next)
1366          {
1367             if(child.flags.transform)
1368                child._UpdateTransform();
1369          }
1370       }
1371    }
1372
1373    void _Animate(unsigned int frame)
1374    {
1375       Object child;
1376       FrameTrack track;
1377
1378       for(track = tracks.first; track; track = track.next)
1379       {
1380          unsigned int c;
1381
1382          if(track.numKeys)
1383          {
1384             unsigned int prev = 0, next = track.numKeys - 1;
1385             FrameKey * prevKey = &track.keys[prev], * nextKey = &track.keys[next];
1386             float t = 0;
1387
1388             for(c = 0; c<track.numKeys; c++)
1389             {
1390                FrameKey * key = track.keys + c;
1391                if(key->frame <= frame) { prevKey = key; prev = c; }
1392                if(key->frame >= frame) { nextKey = key; next = c; break; }
1393             }
1394
1395             if(nextKey->frame != prevKey->frame)
1396                t = ease((float) (frame - prevKey->frame) / (nextKey->frame - prevKey->frame), prevKey->easeFrom, nextKey->easeTo);
1397
1398             switch(track.type.type)
1399             {
1400                case position:
1401                {
1402                   Vector3Df position;
1403                   track.Interpolate(position, prevKey->position, nextKey->position, prev, next, t);
1404                   transform.position = { (double)position.x, (double)position.y, (double)position.z };
1405                   break;
1406                }
1407                case scaling:
1408                   track.Interpolate(transform.scaling, prevKey->scaling, &nextKey->scaling, prev, next, t);
1409                   break;
1410                case rotation:
1411                   track.InterpolateQuat(transform.orientation, prevKey->orientation, nextKey->orientation, prev, next, t);
1412                   break;
1413                // Cameras
1414                case roll:
1415                   roll = track.InterpolateFloat(prevKey->roll, nextKey->roll, prev, next, t);
1416                   break;
1417                case fov:
1418                {
1419                   camera.fov = track.InterpolateFloat(prevKey->fov, nextKey->fov, prev, next, t);
1420                   /*
1421                   double mm = (camera.fov - 5.05659508373109) / 1.13613250717301;
1422                   camera.fov = 1248.58921609766 * pow(mm, -0.895625414990581);
1423                   */
1424                   //camera.Setup(camera.width, camera.height, camera.origin);
1425                   break;
1426                }
1427                // Lights
1428                case colorChange:
1429                {
1430                   track.Interpolate((Vector3Df *)&light.diffuse,
1431                      (Vector3Df *)&prevKey->color, (Vector3Df *)&nextKey->color, prev, next, t);
1432                   light.specular = light.diffuse;
1433                   break;
1434                }
1435                case fallOff:
1436                {
1437                   light.fallOff = track.InterpolateFloat(prevKey->fallOff, nextKey->fallOff, prev, next, t);
1438                   break;
1439                }
1440                case hotSpot:
1441                {
1442                   light.hotSpot = track.InterpolateFloat(prevKey->hotSpot, nextKey->hotSpot, prev, next, t);
1443                   break;
1444                }
1445             }
1446          }
1447       }
1448
1449       for(child = children.first; child; child = child.next)
1450          child._Animate(frame);
1451
1452       flags.transform = true;
1453    }
1454
1455    // Private for now
1456    FrustumPlacement InsideFrustum(Plane * planes)
1457    {
1458       FrustumPlacement result = inside;
1459
1460       int p;
1461       // First test: Sphere
1462       for(p = 0; p<6; p++)
1463       {
1464          Plane * plane = &planes[p];
1465          double dot = plane->normal.DotProduct(wcenter);
1466          double distance = dot + plane->d;
1467          if(distance < -wradius)
1468          {
1469             result = outside;
1470             break;
1471          }
1472          if(Abs(distance) < wradius)
1473             result = intersecting;
1474       }
1475
1476       if(result == intersecting)
1477       {
1478          // Second test: Bounding Box
1479          Vector3D box[8] =
1480          {
1481             { wmin.x, wmin.y, wmin.z },
1482             { wmin.x, wmin.y, wmax.z },
1483             { wmin.x, wmax.y, wmin.z },
1484             { wmin.x, wmax.y, wmax.z },
1485             { wmax.x, wmin.y, wmin.z },
1486             { wmax.x, wmin.y, wmax.z },
1487             { wmax.x, wmax.y, wmin.z },
1488             { wmax.x, wmax.y, wmax.z }
1489          };
1490            int numPlanesAllIn = 0;
1491          for(p = 0; p < 6; p++)
1492          {
1493             Plane * plane = &planes[p];
1494             int i;
1495             int numGoodPoints = 0;
1496             for(i = 0; i < 8; ++i)
1497             {
1498                double dot = plane->normal.DotProduct(box[i]);
1499                double distance = dot + plane->d;
1500                            if(distance > -1)
1501                   numGoodPoints++;
1502                    }
1503                    if(!numGoodPoints)
1504             {
1505                result = outside;
1506                break;
1507             }
1508             if(numGoodPoints == 8)
1509                numPlanesAllIn++;
1510            }
1511            if(numPlanesAllIn == 6)
1512                    result = inside;
1513       }
1514       return result;
1515    }
1516
1517    Object prev, next;
1518    char * name;
1519    Object parent;
1520    OldList children;
1521
1522    ObjectFlags flags;
1523
1524    OldList tracks;
1525    unsigned startFrame, endFrame;
1526    int frame;
1527    Vector3Df pivot;
1528
1529    public Transform transform;
1530    public Matrix matrix;
1531    public Matrix localMatrix;
1532
1533    void * tag;
1534    Vector3Df min, max, center;
1535    Vector3D wmin, wmax, wcenter;
1536
1537    bool volume;
1538    float radius;
1539    double wradius;
1540    ColorRGB ambient;
1541
1542    /*public */union
1543    {
1544       // Mesh
1545       struct
1546       {
1547          Mesh mesh;
1548          Material material;
1549       };
1550
1551       // Light
1552       Light light;
1553
1554       // Camera
1555       struct
1556       {
1557          Camera camera;
1558          Object cameraTarget;
1559          double roll;
1560       };
1561    };
1562
1563    public property Light light
1564    {
1565       set
1566       {
1567          light = value;
1568       }
1569       get
1570       {
1571          value = light;
1572       }
1573    }
1574
1575    Euler eulerOrientation;
1576 };