cleaned all trailing white space from source files.
[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 char * extension;
10    class_property char * extension
11    {
12       set { class_data(extension) = value; }
13       get { return class_data(extension); }
14    }
15
16    virtual bool ::Load(Object object, 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 = true;
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 < this.min.x) this.min.x = point.x;
536                if(point.y < this.min.y) this.min.y = point.y;
537                if(point.z < this.min.z) this.min.z = point.z;
538
539                if(point.x > this.max.x) this.max.x = point.x;
540                if(point.y > this.max.y) this.max.y = point.y;
541                if(point.z > this.max.z) this.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 = 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          if(flags.ownMesh)
638          {
639             DisplaySystem meshDisplaySystem = mesh.displaySystem;
640             mesh.Free(0);
641             if(meshDisplaySystem)
642                meshDisplaySystem.RemoveMesh(mesh);
643             delete mesh;
644          }
645
646          tracks.Free(FrameTrack::Free);
647
648          delete name;
649       }
650    }
651
652    bool Load(char * fileName, char * type, DisplaySystem displaySystem)
653    {
654       char ext[MAX_EXTENSION];
655       subclass(ObjectFormat) format;
656       OldLink link;
657       bool result = false;
658
659       if(!type && fileName)
660       {
661          type = GetExtension(fileName, ext);
662          strlwr(type);
663       }
664
665       for(link = class(ObjectFormat).derivatives.first; link; link = link.next)
666       {
667          format = link.data;
668          if(format.extension && !strcmp(format.extension, type))
669             break;
670       }
671       if(!link) format = null;
672
673       if(format)
674       {
675          if((format.Load(this, fileName, displaySystem)))
676             result = true;
677       }
678       /*if(!result)
679           ErrorLogCode(GERR_LOAD_OBJECT_FAILED, fileName);*/
680       return result;
681    }
682
683    void FreeMesh(DisplaySystem displaySystem)
684    {
685       if(this)
686       {
687          Object child;
688          mesh.Free(0);
689          for(child = children.first; child; child = child.next)
690             child.FreeMesh(displaySystem);
691       }
692    }
693
694    Object Find(char * name)
695    {
696       if(this && name)
697       {
698          Object child;
699
700          if(this.name && !strcmp(this.name, name))
701             return this;
702          else
703          {
704             for(child = children.first; child; child = child.next)
705             {
706                Object result = child.Find(name);
707                if(result)
708                   return result;
709             }
710          }
711       }
712       return null;
713    }
714
715    void Initialize(void)
716    {
717       if(this)
718       {
719          transform.scaling = { 1, 1, 1 };
720          transform.orientation = { 1,0,0,0 };
721          flags.root = true;
722          flags.transform = true;
723          matrix.Identity();
724       }
725    }
726
727    Mesh InitializeMesh(DisplaySystem displaySystem)
728    {
729       if(this)
730       {
731          flags.mesh = true;
732          if(!mesh)
733          {
734             mesh = Mesh { };
735             flags.ownMesh = true;
736          }
737          if(mesh)
738          {
739             FillBytes(mesh, 0, sizeof(class Mesh));
740             displaySystem.AddMesh(mesh);
741          }
742          matrix.Identity();
743          return mesh;
744       }
745       return null;
746    }
747
748    bool AddName(Object object, char * name)
749    {
750       bool result;
751       if(this)
752       {
753          char * newName = CopyString(name);
754          object.name = newName;
755          result = children.AddName(object);
756          if(result)
757             object.parent = this;
758          object.flags.transform = true;
759       }
760       return result;
761    }
762
763    // TODO: Add support to Merge Vertex Colors mesh feature
764    bool Merge(DisplaySystem displaySystem)
765    {
766       bool result = false;
767
768       if(!children.first)
769          result = true;
770       else
771       {
772          Object child, nextChild;
773          int nVertices = 0;
774          MeshFeatures flags = 0;
775          Mesh objectMesh = mesh;
776          bool freeMesh = this.flags.ownMesh;
777
778          mesh = Mesh { };
779          this.flags.ownMesh = true;
780          this.flags.mesh = true;
781          displaySystem.AddMesh(mesh);
782
783          // Count total number of vertices
784          if(objectMesh)
785          {
786             flags |= objectMesh.flags;
787             nVertices += objectMesh.nVertices;
788          }
789
790          for(child = children.first; child; child = child.next)
791          {
792             child.Merge(displaySystem);
793             if(child.mesh)
794             {
795                nVertices += child.mesh.nVertices;
796                flags |= child.mesh.flags;
797             }
798          }
799
800          if(mesh.Allocate(flags, nVertices, displaySystem))
801          {
802             int c;
803             int nTriangles = 0;
804             int vertexOffset = 0;
805             PrimitiveGroup group = null;
806
807             // Merge vertices
808
809             nVertices = 0;
810             if(objectMesh)
811             {
812                for(c = 0; c<objectMesh.nVertices; c++)
813                {
814                   mesh.vertices[nVertices] = objectMesh.vertices[c];
815
816                   if(objectMesh.normals)
817                      mesh.normals[nVertices] = objectMesh.normals[c];
818                   if(objectMesh.texCoords)
819                      mesh.texCoords[nVertices] = objectMesh.texCoords[c];
820
821                   nVertices++;
822                }
823             }
824
825             for(child = children.first; child; child = child.next)
826             {
827                Matrix matrix, normalMatrix;
828
829                matrix.Identity();
830                matrix.Scale(child.transform.scaling.x, child.transform.scaling.y, child.transform.scaling.z);
831
832                matrix.Rotate(child.transform.orientation);
833
834                normalMatrix = matrix;
835
836                matrix.Translate(child.transform.position.x, child.transform.position.y, child.transform.position.z);
837                if(child.mesh)
838                {
839                   for(c = 0; c<child.mesh.nVertices; c++)
840                   {
841                      mesh.vertices[nVertices].MultMatrix(child.mesh.vertices[c], matrix);
842                      if(child.mesh.normals)
843                         mesh.normals[nVertices].MultMatrix(child.mesh.normals[c], normalMatrix);
844                      if(child.mesh.texCoords)
845                         mesh.texCoords[nVertices] = child.mesh.texCoords[c];
846                      nVertices++;
847                   }
848                }
849             }
850
851             // Merge Indexed Primitive Groups
852             while(true)
853             {
854                int nIndices = 0;
855                PrimitiveGroupType type;
856                Material material = null;
857                bool foundGroup = false;
858
859                // Find first group type/material to process and determine how many indices are required
860                if(objectMesh)
861                {
862                   for(group = objectMesh.groups.first; group; group = group.next)
863                   {
864                      if(!foundGroup && !(group.type.vertexRange))
865                      {
866                         if(!FindMaterialAndType(mesh, group.material, group.type))
867                         {
868                            material = group.material;
869                            type = group.type;
870                            nIndices += group.nIndices;
871                            foundGroup = true;
872                         }
873                      }
874                      else if(material == group.material && type == group.type)
875                         nIndices += group.nIndices;
876                   }
877                }
878
879                for(child = children.first; child; child = child.next)
880                {
881                   if(child.mesh)
882                   {
883                      for(group = child.mesh.groups.first; group; group = group.next)
884                      {
885                         if(!foundGroup && !(group.type.vertexRange))
886                         {
887                            if(!FindMaterialAndType(mesh, group.material ? group.material : child.material, group.type))
888                            {
889                               material = group.material ? group.material : child.material;
890                               type = group.type;
891                               nIndices += group.nIndices;
892                               foundGroup = true;
893                            }
894                         }
895                         else if(material == (group.material ? group.material : child.material) && type == group.type)
896                            nIndices += group.nIndices;
897                      }
898                   }
899                }
900
901                // Merge with all similar groups
902                if(foundGroup)
903                {
904                   PrimitiveGroup newGroup = mesh.AddPrimitiveGroup(type, nIndices);
905                   if(newGroup)
906                   {
907                      newGroup.material = material;
908                      nIndices = 0;
909
910                      vertexOffset = 0;
911
912                      if(objectMesh)
913                      {
914                         for(group = objectMesh.groups.first; group; group = group.next)
915                         {
916                            if(newGroup.material == group.material && newGroup.type == group.type)
917                            {
918                               int c;
919                               for(c = 0; c<group.nIndices; c++)
920                                  newGroup.indices[nIndices++] = group.indices[c] + (uint16)vertexOffset;
921                            }
922                         }
923                         vertexOffset += objectMesh.nVertices;
924                      }
925
926                      for(child = children.first; child; child = child.next)
927                      {
928                         if(child.mesh)
929                         {
930                            for(group = child.mesh.groups.first; group; group = group.next)
931                            {
932                               if(newGroup.material == (group.material ? group.material : child.material) &&
933                                  newGroup.type == group.type)
934                               {
935                                  int c;
936                                  for(c = 0; c<group.nIndices; c++)
937                                     newGroup.indices[nIndices++] = group.indices[c] + (uint16)vertexOffset;
938                               }
939                            }
940                            vertexOffset += child.mesh.nVertices;
941                         }
942                      }
943                      mesh.UnlockPrimitiveGroup(newGroup);
944                   }
945                }
946                else
947                   break;
948             }
949
950             // Merge Non-Indexed Primitive Groups
951             vertexOffset = 0;
952
953             if(objectMesh)
954             {
955                for(group = objectMesh.groups.first; group; group = group.next)
956                {
957                   if(group.type.vertexRange)
958                   {
959                      PrimitiveGroup newGroup = mesh.AddPrimitiveGroup(group.type, 0);
960                      if(newGroup)
961                      {
962                         newGroup.material = group.material;
963                         newGroup.nVertices = group.nVertices;
964                         newGroup.first = group.first + vertexOffset;
965                      }
966                   }
967                }
968                vertexOffset += objectMesh.nVertices;
969             }
970
971             for(child = children.first; child; child = child.next)
972             {
973                if(child.mesh)
974                {
975                   for(group = child.mesh.groups.first; group; group = group.next)
976                   {
977                      if(group.type.vertexRange)
978                      {
979                         PrimitiveGroup newGroup = mesh.AddPrimitiveGroup(group.type, 0);
980                         if(newGroup)
981                         {
982                            newGroup.material = group.material ? group.material : child.material;
983                            newGroup.nVertices = group.nVertices;
984                            newGroup.first = group.first + vertexOffset;
985                         }
986                      }
987                   }
988                   vertexOffset += child.mesh.nVertices;
989                }
990             }
991
992             // Merge Triangles
993             if(objectMesh)
994                nTriangles = objectMesh.nPrimitives;
995
996             for(child = children.first; child; child = child.next)
997             {
998                if(child.mesh)
999                   nTriangles += child.mesh.nPrimitives;
1000             }
1001             mesh.primitives = new PrimitiveSingle[nTriangles];
1002             mesh.nPrimitives = 0;
1003             vertexOffset = 0;
1004             if(objectMesh)
1005             {
1006                for(c = 0; c<objectMesh.nPrimitives; c++)
1007                {
1008                   int i;
1009                   PrimitiveSingle * triangle = &mesh.primitives[mesh.nPrimitives++];
1010
1011                   mesh.AllocatePrimitive(triangle, objectMesh.primitives[c].type, objectMesh.primitives[c].nIndices);
1012                   triangle->material = objectMesh.primitives[c].material;
1013                   triangle->middle = objectMesh.primitives[c].middle;
1014                   triangle->plane = objectMesh.primitives[c].plane;
1015
1016                   memcpy(triangle->indices, objectMesh.primitives[c].indices, objectMesh.primitives[c].nIndices * sizeof(uint16));
1017
1018                   /*
1019                   *triangle = objectMesh.primitives[c];
1020                   objectMesh.primitives[c].indices = null;
1021                   objectMesh.primitives[c].data = null;
1022                   */
1023
1024                   for(i = 0; i<triangle->nIndices; i++)
1025                      triangle->indices[i] += (uint16)vertexOffset;
1026                   mesh.UnlockPrimitive(triangle);
1027                }
1028                vertexOffset += objectMesh.nVertices;
1029             }
1030             for(child = children.first; child; child = child.next)
1031             {
1032                if(child.mesh)
1033                {
1034                   for(c = 0; c<child.mesh.nPrimitives; c++)
1035                   {
1036                      int i;
1037                      PrimitiveSingle * triangle = &mesh.primitives[mesh.nPrimitives++];
1038
1039                      mesh.AllocatePrimitive(triangle, child.mesh.primitives[c].type, child.mesh.primitives[c].nIndices);
1040                      triangle->material = child.mesh.primitives[c].material ? child.mesh.primitives[c].material : child.material;
1041                      triangle->middle = child.mesh.primitives[c].middle;
1042                      triangle->plane = child.mesh.primitives[c].plane;
1043                      memcpy(triangle->indices, child.mesh.primitives[c].indices, child.mesh.primitives[c].nIndices * sizeof(uint16));
1044
1045                      /*
1046                      *triangle = child.mesh.primitives[c];
1047                      child.mesh.primitives[c].indices = null;
1048                      child.mesh.primitives[c].data = null;
1049                      */
1050
1051                      for(i = 0; i<triangle->nIndices; i++)
1052                         triangle->indices[i] += (uint16)vertexOffset;
1053                      mesh.UnlockPrimitive(triangle);
1054                   }
1055                   vertexOffset += child.mesh.nVertices;
1056                }
1057             }
1058
1059             // Free children
1060             for(child = children.first; child; child = nextChild)
1061             {
1062                nextChild = child.next;
1063                children.Remove(child);
1064                child.Free(displaySystem);
1065             }
1066
1067             mesh.ApplyTranslucency(this);
1068             // this.flags.translucent = true;
1069
1070             result = true;
1071
1072             mesh.Unlock(flags);
1073          }
1074          if(freeMesh)
1075          {
1076             if(objectMesh.displaySystem)
1077                objectMesh.displaySystem.RemoveMesh(objectMesh);
1078             delete objectMesh;
1079          }
1080          SetMinMaxRadius(true);
1081       }
1082       return result;
1083    }
1084
1085    void RotateEuler(Euler rotation, Euler min, Euler max)
1086    {
1087       Euler euler = eulerOrientation;//transform.orientation;
1088       euler.Add(euler, rotation);
1089
1090       if(min && max)
1091       {
1092          if(min.pitch && max.pitch)
1093             euler.pitch = Min(Max(euler.pitch, min.pitch), max.pitch);
1094          if(min.yaw && max.yaw)
1095             euler.yaw = Min(Max(euler.yaw, min.yaw), max.yaw);
1096          if(min.roll && max.roll)
1097             euler.roll = Min(Max(euler.roll, min.roll), max.roll);
1098       }
1099
1100       eulerOrientation = euler;
1101       transform.orientation = euler;
1102       UpdateTransform();
1103    }
1104
1105    void Move(Vector3D direction)
1106    {
1107       Matrix matrix;
1108       Vector3D offset;
1109
1110       matrix.RotationQuaternion(transform.orientation);
1111       offset.MultMatrix(direction, matrix);
1112       transform.position.Add(transform.position, offset);
1113       UpdateTransform();
1114    }
1115
1116    void UpdateTransform(void)
1117    {
1118       SetTransformDirty();
1119       _UpdateTransform();
1120       SetMinMaxRadius(false);
1121    }
1122
1123    void Animate(unsigned int frame)
1124    {
1125       if(this && startFrame != endFrame)
1126       {
1127          while(frame < startFrame) frame += (endFrame - startFrame + 1);
1128          while(frame > endFrame)   frame -= (endFrame - startFrame + 1);
1129
1130          this.frame = frame;
1131          _Animate(frame);
1132          _UpdateTransform();
1133          SetMinMaxRadius(false);
1134       }
1135    }
1136
1137    void DoubleSided(bool flag)
1138    {
1139       if(this)
1140       {
1141          Object child;
1142          mesh.DoubleSided(flag);
1143          for(child = children.first; child; child = child.next)
1144             child.DoubleSided(flag);
1145       }
1146    }
1147
1148    bool IntersectsGroundPolygon(int count, Pointf * pointfs)
1149    {
1150       bool result = false;
1151
1152       Pointf * p1;
1153       Pointf * p2;
1154       double minX = wmin.x, maxX = wmax.x;
1155       double minY = wmin.z, maxY = wmax.z;
1156       double delta = (maxX - minX)/2;
1157       double x = (maxX + minX)/2, y = (maxY + minY)/2;
1158       int c;
1159       for(c = 0; c<count; c++)
1160       {
1161          double d;
1162          p1 = &pointfs[c];
1163          p2 = &pointfs[(c == count-1) ? 0 : (c+1)];
1164
1165          if( (p1->x < minX) &&  (p2->x < minX) )
1166          {
1167             if((p1->y <= y) && (p2->y >  y) )
1168                result ^= true;
1169             else if( (p1->y >  y) && (p2->y <= y) )
1170                result ^= true;
1171          }
1172          else if(!((p1->x > maxX && p2->x > maxX) || (p1->y < minY && p2->y < minY) || (p1->y > maxY && p2->y > maxY)))
1173          {
1174             if(p1->y == p2->y)
1175             {
1176                d = y - p1->y;
1177                if (d < 0) d = -d;
1178                if (d < delta) return true;
1179             }
1180             else if(p1->x == p2->x)
1181             {
1182                d = x - p1->x;
1183                if(d < 0) d = -d;
1184                if(d < delta) return true;
1185                else if(p1->x > x) ;
1186                else if( (p1->y <= y) && (p2->y >  y) )
1187                   result ^= true;
1188                else if( (p1->y >  y) && (p2->y <= y) )
1189                   result ^= true;
1190             }
1191             else
1192             {
1193                float a, b, dy, dx;
1194
1195                a = p2->y - p1->y;
1196                b = p1->x - p2->x;
1197                dy =  a;
1198                dx = -b;
1199                d = a * x + b * y + (p2->x * p1->y) - (p2->y * p1->x);
1200                if (a < 0) a = -a;
1201                if (b < 0) b = -b;
1202                if (d < 0) d = -d;
1203
1204                if(d < a * delta)
1205                   return true;
1206                else if (d < b * delta)
1207                   return true;
1208                else if( ( (p1->y <= y) && (p2->y >  y) ) || ( (p1->y >  y) && (p2->y <= y) ) )
1209                {
1210                   double xdy;
1211
1212                   xdy = (dx * (y - p1->y)) + (dy * p1->x);
1213                   if(dy < 0)
1214                   {
1215                      if(xdy > x * dy)
1216                         result ^= true;
1217                   }
1218                   else if(xdy < x * dy)
1219                      result ^= true;
1220                }
1221             }
1222          }
1223       }
1224       return result;
1225    }
1226
1227    property Transform transform { set { transform = value; } get { value = transform; } };
1228    property Material material { set { material = value; } get { return material; } };
1229    property Vector3Df max { get { value = max; } };
1230    property Vector3Df min { get { value = min; } };
1231    property Vector3Df center { get { value = center; } };
1232    property float radius { get { return radius; } };
1233
1234    property Vector3D wmax { get { value = wmax; } };
1235    property Vector3D wmin { get { value = wmin; } };
1236    property Vector3D wcenter { get { value = wcenter; } };
1237    property double wradius { get { return wradius; } };
1238
1239    property void * tag { set { tag = value; } get { return tag; } };
1240    property int frame { set { Animate(value); } get { return frame; } };
1241    property int startFrame { set { startFrame = value; } get { return startFrame; } };
1242    property int endFrame { set { endFrame = value; } get { return endFrame; } };
1243
1244    property Mesh mesh { set { mesh = value; } get { return mesh; } };
1245    property Camera camera { get { return camera; } }; // Fix this with inheritance? camera inherit from Object?
1246    property Object firstChild { get { return children.first; } };
1247    property Object next { get { return next; } };
1248    property char * name { get { return name; } };
1249    property Matrix matrix { get { value = matrix; } };
1250    property Object cameraTarget { set { cameraTarget = value; } get { return cameraTarget; } };
1251    property OldList * tracks { /* set { tracks = value; } */ get { return &tracks; } };
1252    property ObjectFlags flags { set { flags = value; } get { return flags; } };
1253
1254 private:
1255    Object()
1256    {
1257       children.offset = (uint)&((Object)0).prev;
1258       transform.scaling = { 1, 1, 1 };
1259       transform.orientation = { 1,0,0,0 };
1260       flags.transform = true;
1261    }
1262
1263    ~Object()
1264    {
1265       Free(null);
1266    }
1267
1268    void SetTransformDirty()
1269    {
1270       Object child;
1271       flags.transform = true;
1272       for(child = children.first; child; child = child.next)
1273          child.SetTransformDirty();
1274    }
1275
1276    void _UpdateTransform()
1277    {
1278       if(flags.transform)
1279       {
1280          Object child;
1281          Matrix matrix;
1282
1283          // Cameras / Spot Lights must update their target first
1284          if(flags.camera && cameraTarget && cameraTarget.flags.transform)
1285             cameraTarget.UpdateTransform();
1286          else if(flags.light && light.flags.spot && light.target.flags.transform)
1287             light.target._UpdateTransform();
1288
1289          if(flags.camera && cameraTarget)
1290          {
1291             // DeterMine angle to look at target
1292             Vector3D position, direction;
1293             if(flags.root || !parent)
1294                position = transform.position;
1295             else
1296                position.MultMatrix(transform.position, parent.matrix);
1297
1298             direction.Subtract((Vector3D *)cameraTarget.matrix.m[3], position);
1299             transform.orientation.RotationDirection(direction);
1300
1301             // Add the roll
1302             transform.orientation.RotateRoll(roll);
1303          }
1304
1305          if(flags.light && light.flags.spot)
1306          {
1307             // DeterMine angle to look at target
1308             Vector3D position;
1309             if(flags.root || !parent)
1310                position = transform.position;
1311             else
1312                position.MultMatrix(transform.position, parent.matrix);
1313
1314             light.direction.Subtract((Vector3D *) light.target.matrix.m[3], position);
1315             light.direction.Normalize(light.direction);
1316             transform.orientation.RotationDirection(light.direction);
1317          }
1318
1319          matrix.Identity();
1320          matrix.Scale(transform.scaling.x, transform.scaling.y, transform.scaling.z);
1321          matrix.Rotate(transform.orientation);
1322          matrix.Translate(transform.position.x, transform.position.y, transform.position.z);
1323
1324          localMatrix = matrix;
1325
1326          // Compute transform (with ancestors)
1327          if(flags.root || !parent)
1328             this.matrix = matrix;
1329          else
1330             this.matrix.Multiply(matrix, parent.matrix);
1331
1332          flags.transform = false;
1333
1334          for(child = children.first; child; child = child.next)
1335          {
1336             if(child.flags.transform)
1337                child._UpdateTransform();
1338          }
1339       }
1340    }
1341
1342    void _Animate(unsigned int frame)
1343    {
1344       Object child;
1345       FrameTrack track;
1346
1347       for(track = tracks.first; track; track = track.next)
1348       {
1349          unsigned int c;
1350
1351          if(track.numKeys)
1352          {
1353             unsigned int prev = 0, next = track.numKeys - 1;
1354             FrameKey * prevKey = &track.keys[prev], * nextKey = &track.keys[next];
1355             float t = 0;
1356
1357             for(c = 0; c<track.numKeys; c++)
1358             {
1359                FrameKey * key = track.keys + c;
1360                if(key->frame <= frame) { prevKey = key; prev = c; }
1361                if(key->frame >= frame) { nextKey = key; next = c; break; }
1362             }
1363
1364             if(nextKey->frame != prevKey->frame)
1365                t = ease((float) (frame - prevKey->frame) / (nextKey->frame - prevKey->frame), prevKey->easeFrom, nextKey->easeTo);
1366
1367             switch(track.type.type)
1368             {
1369                case position:
1370                {
1371                   Vector3Df position;
1372                   track.Interpolate(position, prevKey->position, nextKey->position, prev, next, t);
1373                   transform.position = { (double)position.x, (double)position.y, (double)position.z };
1374                   break;
1375                }
1376                case scaling:
1377                   track.Interpolate(transform.scaling, prevKey->scaling, &nextKey->scaling, prev, next, t);
1378                   break;
1379                case rotation:
1380                   track.InterpolateQuat(transform.orientation, prevKey->orientation, nextKey->orientation, prev, next, t);
1381                   break;
1382                // Cameras
1383                case roll:
1384                   roll = track.InterpolateFloat(prevKey->roll, nextKey->roll, prev, next, t);
1385                   break;
1386                case fov:
1387                {
1388                   camera.fov = track.InterpolateFloat(prevKey->fov, nextKey->fov, prev, next, t);
1389                   /*
1390                   double mm = (camera.fov - 5.05659508373109) / 1.13613250717301;
1391                   camera.fov = 1248.58921609766 * pow(mm, -0.895625414990581);
1392                   */
1393                   //camera.Setup(camera.width, camera.height, camera.origin);
1394                   break;
1395                }
1396                // Lights
1397                case colorChange:
1398                {
1399                   track.Interpolate((Vector3Df *)&light.diffuse,
1400                      (Vector3Df *)&prevKey->color, (Vector3Df *)&nextKey->color, prev, next, t);
1401                   light.specular = light.diffuse;
1402                   break;
1403                }
1404                case fallOff:
1405                {
1406                   light.fallOff = track.InterpolateFloat(prevKey->fallOff, nextKey->fallOff, prev, next, t);
1407                   break;
1408                }
1409                case hotSpot:
1410                {
1411                   light.hotSpot = track.InterpolateFloat(prevKey->hotSpot, nextKey->hotSpot, prev, next, t);
1412                   break;
1413                }
1414             }
1415          }
1416       }
1417
1418       for(child = children.first; child; child = child.next)
1419          child._Animate(frame);
1420
1421       flags.transform = true;
1422    }
1423
1424    // Private for now
1425    FrustumPlacement InsideFrustum(Plane * planes)
1426    {
1427       FrustumPlacement result = inside;
1428
1429       int p;
1430       // First test: Sphere
1431       for(p = 0; p<6; p++)
1432       {
1433          Plane * plane = &planes[p];
1434          double dot = plane->normal.DotProduct(wcenter);
1435          double distance = dot + plane->d;
1436          if(distance < -wradius)
1437          {
1438             result = outside;
1439             break;
1440          }
1441          if(Abs(distance) < wradius)
1442             result = intersecting;
1443       }
1444
1445       if(result == intersecting)
1446       {
1447          // Second test: Bounding Box
1448          Vector3D box[8] =
1449          {
1450             { wmin.x, wmin.y, wmin.z },
1451             { wmin.x, wmin.y, wmax.z },
1452             { wmin.x, wmax.y, wmin.z },
1453             { wmin.x, wmax.y, wmax.z },
1454             { wmax.x, wmin.y, wmin.z },
1455             { wmax.x, wmin.y, wmax.z },
1456             { wmax.x, wmax.y, wmin.z },
1457             { wmax.x, wmax.y, wmax.z }
1458          };
1459            int numPlanesAllIn = 0;
1460          for(p = 0; p < 6; p++)
1461          {
1462             Plane * plane = &planes[p];
1463             int i;
1464             int numGoodPoints = 0;
1465             for(i = 0; i < 8; ++i)
1466             {
1467                double dot = plane->normal.DotProduct(box[i]);
1468                double distance = dot + plane->d;
1469                            if(distance > -1)
1470                   numGoodPoints++;
1471                    }
1472                    if(!numGoodPoints)
1473             {
1474                result = outside;
1475                break;
1476             }
1477             if(numGoodPoints == 8)
1478                numPlanesAllIn++;
1479            }
1480            if(numPlanesAllIn == 6)
1481                    result = inside;
1482       }
1483       return result;
1484    }
1485
1486    Object prev, next;
1487    char * name;
1488    Object parent;
1489    OldList children;
1490
1491    ObjectFlags flags;
1492
1493    OldList tracks;
1494    unsigned startFrame, endFrame;
1495    int frame;
1496    Vector3Df pivot;
1497    Transform transform;
1498    Matrix matrix;
1499    Matrix localMatrix;
1500    void * tag;
1501    Vector3Df min, max, center;
1502    Vector3D wmin, wmax, wcenter;
1503
1504    bool volume;
1505    float radius;
1506    double wradius;
1507    ColorRGB ambient;
1508
1509    /*public */union
1510    {
1511       // Mesh
1512       struct
1513       {
1514          Mesh mesh;
1515          Material material;
1516       };
1517
1518       // Light
1519       Light light;
1520
1521       // Camera
1522       struct
1523       {
1524          Camera camera;
1525          Object cameraTarget;
1526          double roll;
1527       };
1528    };
1529
1530    public property Light light
1531    {
1532       set
1533       {
1534          light = value;
1535       }
1536       get
1537       {
1538          value = light;
1539       }
1540    }
1541
1542    Euler eulerOrientation;
1543 };