svn merge -r 30913:30953 https://svn.blender.org/svnroot/bf-blender/trunk/blender
[blender.git] / source / blender / blenkernel / intern / anim.c
1 /** anim.c
2  *
3  *
4  * $Id$
5  *
6  * ***** BEGIN GPL LICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21  *
22  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 #include <stdio.h>
33 #include <math.h>
34 #include <string.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLI_blenlib.h"
39 #include "BLI_editVert.h"
40 #include "BLI_math.h"
41 #include "BLI_rand.h"
42
43
44 #include "DNA_anim_types.h"
45 #include "DNA_armature_types.h"
46 #include "DNA_group_types.h"
47 #include "DNA_key_types.h"
48 #include "DNA_meshdata_types.h"
49 #include "DNA_scene_types.h"
50 #include "DNA_vfont_types.h"
51
52 #include "BKE_anim.h"
53 #include "BKE_curve.h"
54 #include "BKE_DerivedMesh.h"
55 #include "BKE_depsgraph.h"
56 #include "BKE_font.h"
57 #include "BKE_group.h"
58 #include "BKE_global.h"
59 #include "BKE_key.h"
60 #include "BKE_lattice.h"
61 #include "BKE_main.h"
62 #include "BKE_mesh.h"
63 #include "BKE_object.h"
64 #include "BKE_particle.h"
65 #include "BKE_scene.h"
66 #include "BKE_utildefines.h"
67 #include "BKE_depsgraph.h"
68
69 #include "ED_curve.h" /* for ED_curve_nurbs */
70
71 // XXX bad level call...
72
73 /* --------------------- */
74 /* forward declarations */
75
76 static void object_duplilist_recursive(ID *id, Scene *scene, Object *ob, ListBase *duplilist, float par_space_mat[][4], int level, int animated);
77
78 /* ******************************************************************** */
79 /* Animation Visualisation */
80
81 /* Initialise the default settings for animation visualisation */
82 void animviz_settings_init(bAnimVizSettings *avs)
83 {
84         /* sanity check */
85         if (avs == NULL)
86                 return;
87                 
88         /* ghosting settings */
89         avs->ghost_bc= avs->ghost_ac= 10;
90         
91         avs->ghost_sf= 1; // xxx - take from scene instead?
92         avs->ghost_ef= 250; // xxx - take from scene instead?
93         
94         avs->ghost_step= 1;
95         
96         
97         /* path settings */
98         avs->path_bc= avs->path_ac= 10;
99         
100         avs->path_sf= 1; // xxx - take from scene instead?
101         avs->path_ef= 250; // xxx - take from scene instead?
102         
103         avs->path_viewflag= (MOTIONPATH_VIEW_KFRAS|MOTIONPATH_VIEW_KFNOS);
104         
105         avs->path_step= 1;
106 }
107
108 /* ------------------- */
109
110 /* Free the given motion path's cache */
111 void animviz_free_motionpath_cache(bMotionPath *mpath) 
112 {
113         /* sanity check */
114         if (mpath == NULL) 
115                 return;
116                 
117         /* free the path if necessary */
118         if (mpath->points)
119                 MEM_freeN(mpath->points);
120         
121         /* reset the relevant parameters */
122         mpath->points= NULL;
123         mpath->length= 0;
124 }
125
126 /* Free the given motion path instance and its data 
127  * NOTE: this frees the motion path given!
128  */
129 void animviz_free_motionpath(bMotionPath *mpath)
130 {
131         /* sanity check */
132         if (mpath == NULL)
133                 return;
134         
135         /* free the cache first */
136         animviz_free_motionpath_cache(mpath);
137         
138         /* now the instance itself */
139         MEM_freeN(mpath);
140 }
141
142 /* ------------------- */
143
144 /* Setup motion paths for the given data
145  *      - scene: current scene (for frame ranges, etc.)
146  *      - ob: object to add paths for (must be provided)
147  *      - pchan: posechannel to add paths for (optional; if not provided, object-paths are assumed)
148  */
149 bMotionPath *animviz_verify_motionpaths(Scene *scene, Object *ob, bPoseChannel *pchan)
150 {
151         bAnimVizSettings *avs;
152         bMotionPath *mpath, **dst;
153         
154         /* sanity checks */
155         if (ELEM(NULL, scene, ob))
156                 return NULL;
157                 
158         /* get destination data */
159         if (pchan) {
160                 /* paths for posechannel - assume that posechannel belongs to the object */
161                 avs= &ob->pose->avs;
162                 dst= &pchan->mpath;
163         }
164         else {
165                 /* paths for object */
166                 avs= &ob->avs;
167                 dst= &ob->mpath;
168         }
169         
170         /* if there is already a motionpath, just return that,
171          * but provided it's settings are ok 
172          */
173         if (*dst != NULL) {
174                 mpath= *dst;
175                 
176                 /* if range is not invalid, and/or length is set ok, just return */
177                 if ((mpath->start_frame != mpath->end_frame) && (mpath->length > 0))
178                         return mpath;
179         }
180         else {
181                 /* create a new motionpath, and assign it */
182                 mpath= MEM_callocN(sizeof(bMotionPath), "bMotionPath");
183                 *dst= mpath;
184         }
185         
186         /* set settings from the viz settings */
187         mpath->start_frame= avs->path_sf;
188         mpath->end_frame= avs->path_ef;
189         
190         mpath->length= mpath->end_frame - mpath->start_frame;
191         
192         if (avs->path_bakeflag & MOTIONPATH_BAKE_HEADS)
193                 mpath->flag |= MOTIONPATH_FLAG_BHEAD;
194         else
195                 mpath->flag &= ~MOTIONPATH_FLAG_BHEAD;
196         
197         /* allocate a cache */
198         mpath->points= MEM_callocN(sizeof(bMotionPathVert)*mpath->length, "bMotionPathVerts");
199         
200         /* tag viz settings as currently having some path(s) which use it */
201         avs->path_bakeflag |= MOTIONPATH_BAKE_HAS_PATHS;
202         
203         /* return it */
204         return mpath;
205 }
206
207 /* ------------------- */
208
209 /* Motion path needing to be baked (mpt) */
210 typedef struct MPathTarget {
211         struct MPathTarget *next, *prev;
212         
213         bMotionPath *mpath;                     /* motion path in question */
214         
215         Object *ob;                                     /* source object */
216         bPoseChannel *pchan;            /* source posechannel (if applicable) */
217 } MPathTarget;
218
219 /* ........ */
220
221 /* get list of motion paths to be baked for the given object
222  *      - assumes the given list is ready to be used
223  */
224 void animviz_get_object_motionpaths(Object *ob, ListBase *targets)
225 {
226         MPathTarget *mpt;
227         
228         /* object itself first */
229         if ((ob->avs.recalc & ANIMVIZ_RECALC_PATHS) && (ob->mpath)) {
230                 /* new target for object */
231                 mpt= MEM_callocN(sizeof(MPathTarget), "MPathTarget Ob");
232                 BLI_addtail(targets, mpt);
233                 
234                 mpt->mpath= ob->mpath;
235                 mpt->ob= ob;
236         }
237         
238         /* bones */
239         if ((ob->pose) && (ob->pose->avs.recalc & ANIMVIZ_RECALC_PATHS)) {
240                 bArmature *arm= ob->data;
241                 bPoseChannel *pchan;
242                 
243                 for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
244                         if ((pchan->bone) && (arm->layer & pchan->bone->layer) && (pchan->mpath)) {
245                                 /* new target for bone */
246                                 mpt= MEM_callocN(sizeof(MPathTarget), "MPathTarget PoseBone");
247                                 BLI_addtail(targets, mpt);
248                                 
249                                 mpt->mpath= pchan->mpath;
250                                 mpt->ob= ob;
251                                 mpt->pchan= pchan;
252                         }
253                 }
254         }
255 }
256
257 /* ........ */
258
259 /* Note on evaluation optimisations:
260  * Optimisations currently used here play tricks with the depsgraph in order to try and 
261  * evaluate as few objects as strictly necessary to get nicer performance under standard
262  * production conditions. For those people who really need the accurate version, 
263  * disable the ifdef (i.e. 1 -> 0) and comment out the call to motionpaths_calc_optimise_depsgraph()
264  */
265
266 /* tweak the object ordering to trick depsgraph into making MotionPath calculations run faster */
267 static void motionpaths_calc_optimise_depsgraph(Scene *scene, ListBase *targets)
268 {
269         Base *base, *baseNext;
270         MPathTarget *mpt;
271         
272         /* make sure our temp-tag isn't already in use */
273         for (base= scene->base.first; base; base= base->next)
274                 base->object->flag &= ~BA_TEMP_TAG;
275         
276         /* for each target, dump its object to the start of the list if it wasn't moved already */
277         for (mpt= targets->first; mpt; mpt= mpt->next) {
278                 for (base=scene->base.first; base; base=baseNext) {
279                         baseNext = base->next;
280                         
281                         if ((base->object == mpt->ob) && !(mpt->ob->flag & BA_TEMP_TAG)) {
282                                 BLI_remlink(&scene->base, base);
283                                 BLI_addhead(&scene->base, base);
284                                 
285                                 mpt->ob->flag |= BA_TEMP_TAG;
286                                 break; // we really don't need to continue anymore once this happens, but this line might really 'break'
287                         }
288                 }
289         }
290         
291         /* "brew me a list that's sorted a bit faster now depsy" */
292         DAG_scene_sort(G.main, scene);
293 }
294
295 /* update scene for current frame */
296 static void motionpaths_calc_update_scene(Scene *scene)
297 {
298 #if 1 // 'production' optimisations always on
299         Base *base, *last=NULL;
300         
301         /* only stuff that moves or needs display still */
302         DAG_scene_update_flags(G.main, scene, scene->lay);
303         
304         /* find the last object with the tag 
305          *      - all those afterwards are assumed to not be relevant for our calculations
306          */
307         // optimise further by moving out...
308         for (base=scene->base.first; base; base=base->next) {
309                 if (base->object->flag & BA_TEMP_TAG)
310                         last = base;
311         }
312         
313         /* perform updates for tagged objects */
314         // XXX: this will break if rigs depend on scene or other data that 
315         // is animated but not attached to/updatable from objects
316         for (base=scene->base.first; base; base=base->next) {
317                 /* update this object */
318                 object_handle_update(scene, base->object);
319                 
320                 /* if this is the last one we need to update, let's stop to save some time */
321                 if (base == last)
322                         break;
323         }
324 #else // original, 'always correct' version
325         /* do all updates 
326          *      - if this is too slow, resort to using a more efficient way 
327          *        that doesn't force complete update, but for now, this is the
328          *        most accurate way!
329          */
330         scene_update_for_newframe(G.main, scene, scene->lay); // XXX this is the best way we can get anything moving
331 #endif
332 }
333
334 /* ........ */
335
336 /* perform baking for the targets on the current frame */
337 static void motionpaths_calc_bake_targets(Scene *scene, ListBase *targets)
338 {
339         MPathTarget *mpt;
340         
341         /* for each target, check if it can be baked on the current frame */
342         for (mpt= targets->first; mpt; mpt= mpt->next) {        
343                 bMotionPath *mpath= mpt->mpath;
344                 bMotionPathVert *mpv;
345                 
346                 /* current frame must be within the range the cache works for 
347                  *      - is inclusive of the first frame, but not the last otherwise we get buffer overruns
348                  */
349                 if ((CFRA < mpath->start_frame) || (CFRA >= mpath->end_frame))
350                         continue;
351                 
352                 /* get the relevant cache vert to write to */
353                 mpv= mpath->points + (CFRA - mpath->start_frame);
354                 
355                 /* pose-channel or object path baking? */
356                 if (mpt->pchan) {
357                         /* heads or tails */
358                         if (mpath->flag & MOTIONPATH_FLAG_BHEAD) {
359                                 VECCOPY(mpv->co, mpt->pchan->pose_head);
360                         }
361                         else {
362                                 VECCOPY(mpv->co, mpt->pchan->pose_tail);
363                         }
364                         
365                         /* result must be in worldspace */
366                         mul_m4_v3(mpt->ob->obmat, mpv->co);
367                 }
368                 else {
369                         /* worldspace object location */
370                         VECCOPY(mpv->co, mpt->ob->obmat[3]);
371                 }
372         }
373 }
374
375 /* Perform baking of the given object's and/or its bones' transforms to motion paths 
376  *      - scene: current scene
377  *      - ob: object whose flagged motionpaths should get calculated
378  *      - recalc: whether we need to 
379  */
380 // TODO: include reports pointer?
381 void animviz_calc_motionpaths(Scene *scene, ListBase *targets)
382 {
383         MPathTarget *mpt;
384         int sfra, efra;
385         int cfra;
386         
387         /* sanity check */
388         if (ELEM(NULL, targets, targets->first))
389                 return;
390         
391         /* set frame values */
392         cfra = CFRA;
393         sfra = efra = cfra;
394         
395         // TODO: this method could be improved...
396         //      1) max range for standard baking
397         //      2) minimum range for recalc baking (i.e. between keyframes, but how?)
398         for (mpt= targets->first; mpt; mpt= mpt->next) {
399                 /* try to increase area to do (only as much as needed) */
400                 sfra= MIN2(sfra, mpt->mpath->start_frame);
401                 efra= MAX2(efra, mpt->mpath->end_frame);
402         }
403         if (efra <= sfra) return;
404         
405         /* optimise the depsgraph for faster updates */
406         // TODO: whether this is used should depend on some setting for the level of optimisations used
407         motionpaths_calc_optimise_depsgraph(scene, targets);
408         
409         /* calculate path over requested range */
410         for (CFRA=sfra; CFRA<=efra; CFRA++) {
411                 /* update relevant data for new frame */
412                 motionpaths_calc_update_scene(scene);
413                 
414                 /* perform baking for targets */
415                 motionpaths_calc_bake_targets(scene, targets);
416         }
417         
418         /* reset original environment */
419         CFRA= cfra;
420         motionpaths_calc_update_scene(scene);
421         
422         /* clear recalc flags from targets */
423         for (mpt= targets->first; mpt; mpt= mpt->next) {
424                 bAnimVizSettings *avs;
425                 
426                 /* get pointer to animviz settings for each target */
427                 if (mpt->pchan)
428                         avs= &mpt->ob->pose->avs;
429                 else    
430                         avs= &mpt->ob->avs;
431                 
432                 /* clear the flag requesting recalculation of targets */
433                 avs->recalc &= ~ANIMVIZ_RECALC_PATHS;
434         }
435 }
436
437 /* ******************************************************************** */
438 /* Curve Paths - for curve deforms and/or curve following */
439
440 /* free curve path data 
441  * NOTE: frees the path itself!
442  */
443 void free_path(Path *path)
444 {
445         if(path->data) MEM_freeN(path->data);
446         MEM_freeN(path);
447 }
448
449 /* calculate a curve-deform path for a curve 
450  *      - only called from displist.c -> makeDispListCurveTypes
451  */
452 void calc_curvepath(Object *ob)
453 {
454         BevList *bl;
455         BevPoint *bevp, *bevpn, *bevpfirst, *bevplast;
456         PathPoint *pp;
457         Curve *cu;
458         Nurb *nu;
459         Path *path;
460         float *fp, *dist, *maxdist, xyz[3];
461         float fac, d=0, fac1, fac2;
462         int a, tot, cycl=0;
463         ListBase *nurbs;
464         
465         /* in a path vertices are with equal differences: path->len = number of verts */
466         /* NOW WITH BEVELCURVE!!! */
467         
468         if(ob==NULL || ob->type != OB_CURVE) return;
469         cu= ob->data;
470
471         nurbs= BKE_curve_nurbs(cu);
472         nu= nurbs->first;
473
474         if(cu->path) free_path(cu->path);
475         cu->path= NULL;
476         
477         bl= cu->bev.first;
478         if(bl==NULL || !bl->nr) return;
479
480         cu->path=path= MEM_callocN(sizeof(Path), "calc_curvepath");
481         
482         /* if POLY: last vertice != first vertice */
483         cycl= (bl->poly!= -1);
484         
485         if(cycl) tot= bl->nr;
486         else tot= bl->nr-1;
487         
488         path->len= tot+1;
489         /* exception: vector handle paths and polygon paths should be subdivided at least a factor resolu */
490         if(path->len<nu->resolu*SEGMENTSU(nu)) path->len= nu->resolu*SEGMENTSU(nu);
491         
492         dist= (float *)MEM_mallocN((tot+1)*4, "calcpathdist");
493
494                 /* all lengths in *dist */
495         bevp= bevpfirst= (BevPoint *)(bl+1);
496         fp= dist;
497         *fp= 0;
498         for(a=0; a<tot; a++) {
499                 fp++;
500                 if(cycl && a==tot-1)
501                         sub_v3_v3v3(xyz, bevpfirst->vec, bevp->vec);
502                 else
503                         sub_v3_v3v3(xyz, (bevp+1)->vec, bevp->vec);
504                 
505                 *fp= *(fp-1)+len_v3(xyz);
506                 bevp++;
507         }
508         
509         path->totdist= *fp;
510         
511                 /* the path verts  in path->data */
512                 /* now also with TILT value */
513         pp= path->data = (PathPoint *)MEM_callocN(sizeof(PathPoint)*4*path->len, "pathdata"); // XXX - why *4? - in 2.4x each element was 4 and the size was 16, so better leave for now - Campbell
514         
515         bevp= bevpfirst;
516         bevpn= bevp+1;
517         bevplast= bevpfirst + (bl->nr-1);
518         fp= dist+1;
519         maxdist= dist+tot;
520         fac= 1.0f/((float)path->len-1.0f);
521                 fac = fac * path->totdist;
522         
523         for(a=0; a<path->len; a++) {
524                 
525                 d= ((float)a)*fac;
526                 
527                 /* we're looking for location (distance) 'd' in the array */
528                 while((d>= *fp) && fp<maxdist) {
529                         fp++;
530                         if(bevp<bevplast) bevp++;
531                         bevpn= bevp+1;
532                         if(bevpn>bevplast) {
533                                 if(cycl) bevpn= bevpfirst;
534                                 else bevpn= bevplast;
535                         }
536                 }
537                 
538                 fac1= *(fp)- *(fp-1);
539                 fac2= *(fp)-d;
540                 fac1= fac2/fac1;
541                 fac2= 1.0f-fac1;
542                 
543                 interp_v3_v3v3(pp->vec, bevp->vec, bevpn->vec, fac2);
544                 pp->vec[3]= fac1*bevp->alfa + fac2*bevpn->alfa;
545                 pp->radius= fac1*bevp->radius + fac2*bevpn->radius;
546                 pp->weight= fac1*bevp->weight + fac2*bevpn->weight;
547                 interp_qt_qtqt(pp->quat, bevp->quat, bevpn->quat, fac2);
548                 normalize_qt(pp->quat);
549                 
550                 pp++;
551         }
552         
553         MEM_freeN(dist);
554 }
555
556
557 /* is this only used internally?*/
558 int interval_test(int min, int max, int p1, int cycl)
559 {
560         if(cycl) {
561                 if(p1 < min) 
562                         p1=  ((p1 -min) % (max-min+1)) + max+1;
563                 else if(p1 > max)
564                         p1=  ((p1 -min) % (max-min+1)) + min;
565         }
566         else {
567                 if(p1 < min) p1= min;
568                 else if(p1 > max) p1= max;
569         }
570         return p1;
571 }
572
573
574 /* calculate the deformation implied by the curve path at a given parametric position, and returns whether this operation succeeded 
575  *      - *vec needs FOUR items!
576  *      - ctime is normalized range <0-1>
577  */
578 int where_on_path(Object *ob, float ctime, float *vec, float *dir, float *quat, float *radius, float *weight)   /* returns OK */
579 {
580         Curve *cu;
581         Nurb *nu;
582         BevList *bl;
583         Path *path;
584         PathPoint *pp, *p0, *p1, *p2, *p3;
585         float fac;
586         float data[4];
587         int cycl=0, s0, s1, s2, s3;
588
589         if(ob==NULL || ob->type != OB_CURVE) return 0;
590         cu= ob->data;
591         if(cu->path==NULL || cu->path->data==NULL) {
592                 printf("no path!\n");
593                 return 0;
594         }
595         path= cu->path;
596         pp= path->data;
597         
598         /* test for cyclic */
599         bl= cu->bev.first;
600         if (!bl) return 0;
601         if (!bl->nr) return 0;
602         if(bl->poly> -1) cycl= 1;
603
604         ctime *= (path->len-1);
605         
606         s1= (int)floor(ctime);
607         fac= (float)(s1+1)-ctime;
608
609         /* path->len is corected for cyclic */
610         s0= interval_test(0, path->len-1-cycl, s1-1, cycl);
611         s1= interval_test(0, path->len-1-cycl, s1, cycl);
612         s2= interval_test(0, path->len-1-cycl, s1+1, cycl);
613         s3= interval_test(0, path->len-1-cycl, s1+2, cycl);
614
615         p0= pp + s0;
616         p1= pp + s1;
617         p2= pp + s2;
618         p3= pp + s3;
619
620         /* note, commented out for follow constraint */
621         //if(cu->flag & CU_FOLLOW) {
622
623                 key_curve_tangent_weights(1.0f-fac, data, KEY_BSPLINE);
624
625                 interp_v3_v3v3v3v3(dir, p0->vec, p1->vec, p2->vec, p3->vec, data);
626
627                 /* make compatible with vectoquat */
628                 negate_v3(dir);
629         //}
630         
631         nu= cu->nurb.first;
632
633         /* make sure that first and last frame are included in the vectors here  */
634         if(nu->type == CU_POLY) key_curve_position_weights(1.0f-fac, data, KEY_LINEAR);
635         else if(nu->type == CU_BEZIER) key_curve_position_weights(1.0f-fac, data, KEY_LINEAR);
636         else if(s0==s1 || p2==p3) key_curve_position_weights(1.0f-fac, data, KEY_CARDINAL);
637         else key_curve_position_weights(1.0f-fac, data, KEY_BSPLINE);
638
639         vec[0]= data[0]*p0->vec[0] + data[1]*p1->vec[0] + data[2]*p2->vec[0] + data[3]*p3->vec[0] ; /* X */
640         vec[1]= data[0]*p0->vec[1] + data[1]*p1->vec[1] + data[2]*p2->vec[1] + data[3]*p3->vec[1] ; /* Y */
641         vec[2]= data[0]*p0->vec[2] + data[1]*p1->vec[2] + data[2]*p2->vec[2] + data[3]*p3->vec[2] ; /* Z */
642         vec[3]= data[0]*p0->vec[3] + data[1]*p1->vec[3] + data[2]*p2->vec[3] + data[3]*p3->vec[3] ; /* Tilt, should not be needed since we have quat still used */
643         /* Need to verify the quat interpolation is correct - XXX */
644
645         if (quat) {
646                 //float totfac, q1[4], q2[4];
647
648                 /* checks for totfac are needed when 'fac' is 1.0 key_curve_position_weights can assign zero
649                  * to more then one index in data which can give divide by zero error */
650 /*
651                 totfac= data[0]+data[1];
652                 if(totfac>0.000001)     interp_qt_qtqt(q1, p0->quat, p1->quat, data[0] / totfac);
653                 else                            QUATCOPY(q1, p1->quat);
654
655                 normalize_qt(q1);
656
657                 totfac= data[2]+data[3];
658                 if(totfac>0.000001)     interp_qt_qtqt(q2, p2->quat, p3->quat, data[2] / totfac);
659                 else                            QUATCOPY(q1, p3->quat);
660                 normalize_qt(q2);
661
662                 totfac = data[0]+data[1]+data[2]+data[3];
663                 if(totfac>0.000001)     interp_qt_qtqt(quat, q1, q2, (data[0]+data[1]) / totfac);
664                 else                            QUATCOPY(quat, q2);
665                 normalize_qt(quat);
666                 */
667                 // XXX - find some way to make quat interpolation work correctly, above code fails in rare but nasty cases.
668                 QUATCOPY(quat, p1->quat);
669         }
670
671         if(radius)
672                 *radius= data[0]*p0->radius + data[1]*p1->radius + data[2]*p2->radius + data[3]*p3->radius;
673
674         if(weight)
675                 *weight= data[0]*p0->weight + data[1]*p1->weight + data[2]*p2->weight + data[3]*p3->weight;
676
677         return 1;
678 }
679
680 /* ******************************************************************** */
681 /* Dupli-Geometry */
682
683 static DupliObject *new_dupli_object(ListBase *lb, Object *ob, float mat[][4], int lay, int index, int type, int animated)
684 {
685         DupliObject *dob= MEM_callocN(sizeof(DupliObject), "dupliobject");
686         
687         BLI_addtail(lb, dob);
688         dob->ob= ob;
689         copy_m4_m4(dob->mat, mat);
690         copy_m4_m4(dob->omat, ob->obmat);
691         dob->origlay= ob->lay;
692         dob->index= index;
693         dob->type= type;
694         dob->animated= (type == OB_DUPLIGROUP) && animated;
695         ob->lay= lay;
696         
697         return dob;
698 }
699
700 static void group_duplilist(ListBase *lb, Scene *scene, Object *ob, int level, int animated)
701 {
702         DupliObject *dob;
703         Group *group;
704         GroupObject *go;
705         float mat[4][4], tmat[4][4];
706         
707         if(ob->dup_group==NULL) return;
708         group= ob->dup_group;
709         
710         /* simple preventing of too deep nested groups */
711         if(level>MAX_DUPLI_RECUR) return;
712         
713         /* handles animated groups, and */
714         /* we need to check update for objects that are not in scene... */
715         group_handle_recalc_and_update(scene, ob, group);
716         animated= animated || group_is_animated(ob, group);
717         
718         for(go= group->gobject.first; go; go= go->next) {
719                 /* note, if you check on layer here, render goes wrong... it still deforms verts and uses parent imat */
720                 if(go->ob!=ob) {
721                         
722                         /* Group Dupli Offset, should apply after everything else */
723                         if (group->dupli_ofs[0] || group->dupli_ofs[1] || group->dupli_ofs[2]) {
724                                 copy_m4_m4(tmat, go->ob->obmat);
725                                 sub_v3_v3v3(tmat[3], tmat[3], group->dupli_ofs);
726                                 mul_m4_m4m4(mat, tmat, ob->obmat);
727                         } else {
728                                 mul_m4_m4m4(mat, go->ob->obmat, ob->obmat);
729                         }
730                         
731                         dob= new_dupli_object(lb, go->ob, mat, ob->lay, 0, OB_DUPLIGROUP, animated);
732
733                         /* check the group instance and object layers match, also that the object visible flags are ok. */
734                         if(     (dob->origlay & group->layer)==0 ||
735                                 (G.rendering==0 && dob->ob->restrictflag & OB_RESTRICT_VIEW) ||
736                                 (G.rendering && dob->ob->restrictflag & OB_RESTRICT_RENDER)
737                         ) {
738                                 dob->no_draw= 1;
739                         }
740                         else {
741                                 dob->no_draw= 0;
742                         }
743
744                         if(go->ob->transflag & OB_DUPLI) {
745                                 copy_m4_m4(dob->ob->obmat, dob->mat);
746                                 object_duplilist_recursive(&group->id, scene, go->ob, lb, ob->obmat, level+1, animated);
747                                 copy_m4_m4(dob->ob->obmat, dob->omat);
748                         }
749                 }
750         }
751 }
752
753 static void frames_duplilist(ListBase *lb, Scene *scene, Object *ob, int level, int animated)
754 {
755         extern int enable_cu_speed;     /* object.c */
756         Object copyob;
757         DupliObject *dob;
758         int cfrao, ok;
759         
760         /* simple preventing of too deep nested groups */
761         if(level>MAX_DUPLI_RECUR) return;
762         
763         cfrao= scene->r.cfra;
764         if(ob->parent==NULL && ob->constraints.first==NULL) return;
765
766         if(ob->transflag & OB_DUPLINOSPEED) enable_cu_speed= 0;
767         copyob= *ob;    /* store transform info */
768
769         for(scene->r.cfra= ob->dupsta; scene->r.cfra<=ob->dupend; scene->r.cfra++) {
770
771                 ok= 1;
772                 if(ob->dupoff) {
773                         ok= scene->r.cfra - ob->dupsta;
774                         ok= ok % (ob->dupon+ob->dupoff);
775                         if(ok < ob->dupon) ok= 1;
776                         else ok= 0;
777                 }
778                 if(ok) {
779 #if 0 // XXX old animation system
780                         do_ob_ipo(scene, ob);
781 #endif // XXX old animation system
782                         where_is_object_time(scene, ob, (float)scene->r.cfra);
783                         dob= new_dupli_object(lb, ob, ob->obmat, ob->lay, scene->r.cfra, OB_DUPLIFRAMES, animated);
784                         copy_m4_m4(dob->omat, copyob.obmat);
785                 }
786         }
787
788         *ob= copyob;    /* restore transform info */
789         scene->r.cfra= cfrao;
790         enable_cu_speed= 1;
791 }
792
793 typedef struct vertexDupliData {
794         ID *id; /* scene or group, for recursive loops */
795         int level;
796         int animated;
797         ListBase *lb;
798         float pmat[4][4];
799         float obmat[4][4]; /* Only used for dupliverts inside dupligroups, where the ob->obmat is modified */
800         Scene *scene;
801         Object *ob, *par;
802         float (*orco)[3];
803 } vertexDupliData;
804
805 /* ------------- */
806
807 static void vertex_dupli__mapFunc(void *userData, int index, float *co, float *no_f, short *no_s)
808 {
809         DupliObject *dob;
810         vertexDupliData *vdd= userData;
811         float vec[3], q2[4], mat[3][3], tmat[4][4], obmat[4][4];
812         
813         mul_v3_m4v3(vec, vdd->pmat, co);
814         sub_v3_v3(vec, vdd->pmat[3]);
815         add_v3_v3(vec, vdd->obmat[3]);
816         
817         copy_m4_m4(obmat, vdd->obmat);
818         VECCOPY(obmat[3], vec);
819         
820         if(vdd->par->transflag & OB_DUPLIROT) {
821                 if(no_f) {
822                         vec[0]= -no_f[0]; vec[1]= -no_f[1]; vec[2]= -no_f[2];
823                 }
824                 else if(no_s) {
825                         vec[0]= -no_s[0]; vec[1]= -no_s[1]; vec[2]= -no_s[2];
826                 }
827                 
828                 vec_to_quat( q2,vec, vdd->ob->trackflag, vdd->ob->upflag);
829                 
830                 quat_to_mat3( mat,q2);
831                 copy_m4_m4(tmat, obmat);
832                 mul_m4_m4m3(obmat, tmat, mat);
833         }
834         dob= new_dupli_object(vdd->lb, vdd->ob, obmat, vdd->par->lay, index, OB_DUPLIVERTS, vdd->animated);
835         if(vdd->orco)
836                 VECCOPY(dob->orco, vdd->orco[index]);
837         
838         if(vdd->ob->transflag & OB_DUPLI) {
839                 float tmpmat[4][4];
840                 copy_m4_m4(tmpmat, vdd->ob->obmat);
841                 copy_m4_m4(vdd->ob->obmat, obmat); /* pretend we are really this mat */
842                 object_duplilist_recursive((ID *)vdd->id, vdd->scene, vdd->ob, vdd->lb, obmat, vdd->level+1, vdd->animated);
843                 copy_m4_m4(vdd->ob->obmat, tmpmat);
844         }
845 }
846
847 static void vertex_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], int level, int animated)
848 {
849         Object *ob, *ob_iter;
850         Mesh *me= par->data;
851         Base *base = NULL;
852         DerivedMesh *dm;
853         vertexDupliData vdd;
854         Scene *sce = NULL;
855         Group *group = NULL;
856         GroupObject * go = NULL;
857         EditMesh *em;
858         float vec[3], no[3], pmat[4][4];
859         int lay, totvert, a, oblay;
860         
861         copy_m4_m4(pmat, par->obmat);
862         
863         /* simple preventing of too deep nested groups */
864         if(level>MAX_DUPLI_RECUR) return;
865         
866         em = BKE_mesh_get_editmesh(me);
867         
868         if(em) {
869                 dm= editmesh_get_derived_cage(scene, par, em, CD_MASK_BAREMESH);
870                 BKE_mesh_end_editmesh(me, em);
871         } else
872                 dm= mesh_get_derived_deform(scene, par, CD_MASK_BAREMESH);
873         
874         if(G.rendering) {
875                 vdd.orco= (float(*)[3])get_mesh_orco_verts(par);
876                 transform_mesh_orco_verts(me, vdd.orco, me->totvert, 0);
877         }
878         else
879                 vdd.orco= NULL;
880         
881         totvert = dm->getNumVerts(dm);
882
883         /* having to loop on scene OR group objects is NOT FUN */
884         if (GS(id->name) == ID_SCE) {
885                 sce = (Scene *)id;
886                 lay= sce->lay;
887                 base= sce->base.first;
888         } else {
889                 group = (Group *)id;
890                 lay= group->layer;
891                 go = group->gobject.first;
892         }
893         
894         /* Start looping on Scene OR Group objects */
895         while (base || go) { 
896                 if (sce) {
897                         ob_iter= base->object;
898                         oblay = base->lay;
899                 } else {
900                         ob_iter= go->ob;
901                         oblay = ob_iter->lay;
902                 }
903                 
904                 if (lay & oblay && scene->obedit!=ob_iter) {
905                         ob=ob_iter->parent;
906                         while(ob) {
907                                 if(ob==par) {
908                                         ob = ob_iter;
909         /* End Scene/Group object loop, below is generic */
910                                         
911                                         
912                                         /* par_space_mat - only used for groups so we can modify the space dupli's are in
913                                            when par_space_mat is NULL ob->obmat can be used instead of ob__obmat
914                                         */
915                                         if(par_space_mat)
916                                                 mul_m4_m4m4(vdd.obmat, ob->obmat, par_space_mat);
917                                         else
918                                                 copy_m4_m4(vdd.obmat, ob->obmat);
919
920                                         vdd.id= id;
921                                         vdd.level= level;
922                                         vdd.animated= animated;
923                                         vdd.lb= lb;
924                                         vdd.ob= ob;
925                                         vdd.scene= scene;
926                                         vdd.par= par;
927                                         copy_m4_m4(vdd.pmat, pmat);
928                                         
929                                         /* mballs have a different dupli handling */
930                                         if(ob->type!=OB_MBALL) ob->flag |= OB_DONE;     /* doesnt render */
931
932                                         if(me->edit_mesh) {
933                                                 dm->foreachMappedVert(dm, vertex_dupli__mapFunc, (void*) &vdd);
934                                         }
935                                         else {
936                                                 for(a=0; a<totvert; a++) {
937                                                         dm->getVertCo(dm, a, vec);
938                                                         dm->getVertNo(dm, a, no);
939                                                         
940                                                         vertex_dupli__mapFunc(&vdd, a, vec, no, NULL);
941                                                 }
942                                         }
943                                         
944                                         break;
945                                 }
946                                 ob= ob->parent;
947                         }
948                 }
949                 if (sce)        base= base->next;       /* scene loop */
950                 else            go= go->next;           /* group loop */
951         }
952
953         if(vdd.orco)
954                 MEM_freeN(vdd.orco);
955         dm->release(dm);
956 }
957
958 static void face_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], int level, int animated)
959 {
960         Object *ob, *ob_iter;
961         Base *base = NULL;
962         DupliObject *dob;
963         DerivedMesh *dm;
964         Mesh *me= par->data;
965         MTFace *mtface;
966         MFace *mface;
967         MVert *mvert;
968         float pmat[4][4], imat[3][3], (*orco)[3] = NULL, w;
969         int lay, oblay, totface, a;
970         Scene *sce = NULL;
971         Group *group = NULL;
972         GroupObject *go = NULL;
973         EditMesh *em;
974         float ob__obmat[4][4]; /* needed for groups where the object matrix needs to be modified */
975         
976         /* simple preventing of too deep nested groups */
977         if(level>MAX_DUPLI_RECUR) return;
978         
979         copy_m4_m4(pmat, par->obmat);
980         
981         em = BKE_mesh_get_editmesh(me);
982         if(em) {
983                 int totvert;
984                 
985                 dm= editmesh_get_derived_cage(scene, par, em, CD_MASK_BAREMESH);
986                 
987                 totface= dm->getNumFaces(dm);
988                 mface= MEM_mallocN(sizeof(MFace)*totface, "mface temp");
989                 dm->copyFaceArray(dm, mface);
990                 totvert= dm->getNumVerts(dm);
991                 mvert= MEM_mallocN(sizeof(MVert)*totvert, "mvert temp");
992                 dm->copyVertArray(dm, mvert);
993
994                 BKE_mesh_end_editmesh(me, em);
995         }
996         else {
997                 dm = mesh_get_derived_deform(scene, par, CD_MASK_BAREMESH);
998                 
999                 totface= dm->getNumFaces(dm);
1000                 mface= dm->getFaceArray(dm);
1001                 mvert= dm->getVertArray(dm);
1002         }
1003
1004         if(G.rendering) {
1005
1006                 orco= (float(*)[3])get_mesh_orco_verts(par);
1007                 transform_mesh_orco_verts(me, orco, me->totvert, 0);
1008                 mtface= me->mtface;
1009         }
1010         else {
1011                 orco= NULL;
1012                 mtface= NULL;
1013         }
1014         
1015         /* having to loop on scene OR group objects is NOT FUN */
1016         if (GS(id->name) == ID_SCE) {
1017                 sce = (Scene *)id;
1018                 lay= sce->lay;
1019                 base= sce->base.first;
1020         } else {
1021                 group = (Group *)id;
1022                 lay= group->layer;
1023                 go = group->gobject.first;
1024         }
1025         
1026         /* Start looping on Scene OR Group objects */
1027         while (base || go) { 
1028                 if (sce) {
1029                         ob_iter= base->object;
1030                         oblay = base->lay;
1031                 } else {
1032                         ob_iter= go->ob;
1033                         oblay = ob_iter->lay;
1034                 }
1035                 
1036                 if (lay & oblay && scene->obedit!=ob_iter) {
1037                         ob=ob_iter->parent;
1038                         while(ob) {
1039                                 if(ob==par) {
1040                                         ob = ob_iter;
1041         /* End Scene/Group object loop, below is generic */
1042                                         
1043                                         /* par_space_mat - only used for groups so we can modify the space dupli's are in
1044                                            when par_space_mat is NULL ob->obmat can be used instead of ob__obmat
1045                                         */
1046                                         if(par_space_mat)
1047                                                 mul_m4_m4m4(ob__obmat, ob->obmat, par_space_mat);
1048                                         else
1049                                                 copy_m4_m4(ob__obmat, ob->obmat);
1050                                         
1051                                         copy_m3_m4(imat, ob->parentinv);
1052                                                 
1053                                         /* mballs have a different dupli handling */
1054                                         if(ob->type!=OB_MBALL) ob->flag |= OB_DONE;     /* doesnt render */
1055
1056                                         for(a=0; a<totface; a++) {
1057                                                 int mv1 = mface[a].v1;
1058                                                 int mv2 = mface[a].v2;
1059                                                 int mv3 = mface[a].v3;
1060                                                 int mv4 = mface[a].v4;
1061                                                 float *v1= mvert[mv1].co;
1062                                                 float *v2= mvert[mv2].co;
1063                                                 float *v3= mvert[mv3].co;
1064                                                 float *v4= (mv4)? mvert[mv4].co: NULL;
1065                                                 float cent[3], quat[4], mat[3][3], mat3[3][3], tmat[4][4], obmat[4][4];
1066
1067                                                 /* translation */
1068                                                 if(v4)
1069                                                         cent_quad_v3(cent, v1, v2, v3, v4);
1070                                                 else
1071                                                         cent_tri_v3(cent, v1, v2, v3);
1072                                                 mul_m4_v3(pmat, cent);
1073                                                 
1074                                                 sub_v3_v3v3(cent, cent, pmat[3]);
1075                                                 add_v3_v3(cent, ob__obmat[3]);
1076                                                 
1077                                                 copy_m4_m4(obmat, ob__obmat);
1078                                                 
1079                                                 VECCOPY(obmat[3], cent);
1080                                                 
1081                                                 /* rotation */
1082                                                 tri_to_quat( quat,v1, v2, v3);
1083                                                 quat_to_mat3( mat,quat);
1084                                                 
1085                                                 /* scale */
1086                                                 if(par->transflag & OB_DUPLIFACES_SCALE) {
1087                                                         float size= v4? area_quad_v3(v1, v2, v3, v4): area_tri_v3(v1, v2, v3);
1088                                                         size= sqrt(size) * par->dupfacesca;
1089                                                         mul_m3_fl(mat, size);
1090                                                 }
1091                                                 
1092                                                 copy_m3_m3(mat3, mat);
1093                                                 mul_m3_m3m3(mat, imat, mat3);
1094                                                 
1095                                                 copy_m4_m4(tmat, obmat);
1096                                                 mul_m4_m4m3(obmat, tmat, mat);
1097                                                 
1098                                                 dob= new_dupli_object(lb, ob, obmat, par->lay, a, OB_DUPLIFACES, animated);
1099                                                 if(G.rendering) {
1100                                                         w= (mv4)? 0.25f: 1.0f/3.0f;
1101
1102                                                         if(orco) {
1103                                                                 VECADDFAC(dob->orco, dob->orco, orco[mv1], w);
1104                                                                 VECADDFAC(dob->orco, dob->orco, orco[mv2], w);
1105                                                                 VECADDFAC(dob->orco, dob->orco, orco[mv3], w);
1106                                                                 if(mv4)
1107                                                                         VECADDFAC(dob->orco, dob->orco, orco[mv4], w);
1108                                                         }
1109
1110                                                         if(mtface) {
1111                                                                 dob->uv[0] += w*mtface[a].uv[0][0];
1112                                                                 dob->uv[1] += w*mtface[a].uv[0][1];
1113                                                                 dob->uv[0] += w*mtface[a].uv[1][0];
1114                                                                 dob->uv[1] += w*mtface[a].uv[1][1];
1115                                                                 dob->uv[0] += w*mtface[a].uv[2][0];
1116                                                                 dob->uv[1] += w*mtface[a].uv[2][1];
1117
1118                                                                 if(mv4) {
1119                                                                         dob->uv[0] += w*mtface[a].uv[3][0];
1120                                                                         dob->uv[1] += w*mtface[a].uv[3][1];
1121                                                                 }
1122                                                         }
1123                                                 }
1124                                                 
1125                                                 if(ob->transflag & OB_DUPLI) {
1126                                                         float tmpmat[4][4];
1127                                                         copy_m4_m4(tmpmat, ob->obmat);
1128                                                         copy_m4_m4(ob->obmat, obmat); /* pretend we are really this mat */
1129                                                         object_duplilist_recursive((ID *)id, scene, ob, lb, ob->obmat, level+1, animated);
1130                                                         copy_m4_m4(ob->obmat, tmpmat);
1131                                                 }
1132                                         }
1133                                         
1134                                         break;
1135                                 }
1136                                 ob= ob->parent;
1137                         }
1138                 }
1139                 if (sce)        base= base->next;       /* scene loop */
1140                 else            go= go->next;           /* group loop */
1141         }
1142         
1143         if(em) {
1144                 MEM_freeN(mface);
1145                 MEM_freeN(mvert);
1146         }
1147
1148         if(orco)
1149                 MEM_freeN(orco);
1150         
1151         dm->release(dm);
1152 }
1153
1154 static void new_particle_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], ParticleSystem *psys, int level, int animated)
1155 {
1156         GroupObject *go;
1157         Object *ob=0, **oblist=0, obcopy, *obcopylist=0;
1158         DupliObject *dob;
1159         ParticleDupliWeight *dw;
1160         ParticleSimulationData sim = {scene, par, psys, psys_get_modifier(par, psys)};
1161         ParticleSettings *part;
1162         ParticleData *pa;
1163         ChildParticle *cpa=0;
1164         ParticleKey state;
1165         ParticleCacheKey *cache;
1166         float ctime, pa_time, scale = 1.0f;
1167         float tmat[4][4], mat[4][4], pamat[4][4], vec[3], size=0.0;
1168         float (*obmat)[4], (*oldobmat)[4];
1169         int lay, a, b, counter, hair = 0;
1170         int totpart, totchild, totgroup=0, pa_num;
1171
1172         if(psys==0) return;
1173         
1174         /* simple preventing of too deep nested groups */
1175         if(level>MAX_DUPLI_RECUR) return;
1176         
1177         part=psys->part;
1178
1179         if(part==0)
1180                 return;
1181
1182         if(!psys_check_enabled(par, psys))
1183                 return;
1184         
1185         ctime = bsystem_time(scene, par, (float)scene->r.cfra, 0.0);
1186
1187         totpart = psys->totpart;
1188         totchild = psys->totchild;
1189
1190         BLI_srandom(31415926 + psys->seed);
1191         
1192         lay= scene->lay;
1193         if((psys->renderdata || part->draw_as==PART_DRAW_REND) && ELEM(part->ren_as, PART_DRAW_OB, PART_DRAW_GR)) {
1194
1195                 /* first check for loops (particle system object used as dupli object) */
1196                 if(part->ren_as == PART_DRAW_OB) {
1197                         if(ELEM(part->dup_ob, NULL, par))
1198                                 return;
1199                 }
1200                 else { /*PART_DRAW_GR */
1201                         if(part->dup_group == NULL || part->dup_group->gobject.first == NULL)
1202                                 return;
1203
1204                         for(go=part->dup_group->gobject.first; go; go=go->next)
1205                                 if(go->ob == par)
1206                                         return;
1207                 }
1208
1209                 /* if we have a hair particle system, use the path cache */
1210                 if(part->type == PART_HAIR) {
1211                         if(psys->flag & PSYS_HAIR_DONE)
1212                                 hair= (totchild == 0 || psys->childcache) && psys->pathcache;
1213                         if(!hair)
1214                                 return;
1215                         
1216                         /* we use cache, update totchild according to cached data */
1217                         totchild = psys->totchildcache;
1218                         totpart = psys->totcached;
1219                 }
1220
1221                 psys_check_group_weights(part);
1222
1223                 psys->lattice = psys_get_lattice(&sim);
1224
1225                 /* gather list of objects or single object */
1226                 if(part->ren_as==PART_DRAW_GR) {
1227                         group_handle_recalc_and_update(scene, par, part->dup_group);
1228
1229                         if(part->draw & PART_DRAW_COUNT_GR) {
1230                                 for(dw=part->dupliweights.first; dw; dw=dw->next)
1231                                         totgroup += dw->count;
1232                         }
1233                         else {
1234                                 for(go=part->dup_group->gobject.first; go; go=go->next)
1235                                         totgroup++;
1236                         }
1237
1238                         /* we also copy the actual objects to restore afterwards, since
1239                          * where_is_object_time will change the object which breaks transform */
1240                         oblist = MEM_callocN(totgroup*sizeof(Object *), "dupgroup object list");
1241                         obcopylist = MEM_callocN(totgroup*sizeof(Object), "dupgroup copy list");
1242
1243                         
1244                         if(part->draw & PART_DRAW_COUNT_GR && totgroup) {
1245                                 dw = part->dupliweights.first;
1246
1247                                 for(a=0; a<totgroup; dw=dw->next) {
1248                                         for(b=0; b<dw->count; b++, a++) {
1249                                                 oblist[a] = dw->ob;
1250                                                 obcopylist[a] = *dw->ob;
1251                                         }
1252                                 }
1253                         }
1254                         else {
1255                                 go = part->dup_group->gobject.first;
1256                                 for(a=0; a<totgroup; a++, go=go->next) {
1257                                         oblist[a] = go->ob;
1258                                         obcopylist[a] = *go->ob;
1259                                 }
1260                         }
1261                 }
1262                 else {
1263                         ob = part->dup_ob;
1264                         obcopy = *ob;
1265                 }
1266
1267                 if(totchild==0 || part->draw & PART_DRAW_PARENT)
1268                         a = 0;
1269                 else
1270                         a = totpart;
1271
1272                 for(pa=psys->particles,counter=0; a<totpart+totchild; a++,pa++,counter++) {
1273                         if(a<totpart) {
1274                                 /* handle parent particle */
1275                                 if(pa->flag & (PARS_UNEXIST+PARS_NO_DISP))
1276                                         continue;
1277
1278                                 pa_num = pa->num;
1279                                 pa_time = pa->time;
1280                                 size = pa->size;
1281                         }
1282                         else {
1283                                 /* handle child particle */
1284                                 cpa = &psys->child[a - totpart];
1285
1286                                 pa_num = a;
1287                                 pa_time = psys->particles[cpa->parent].time;
1288                                 size = psys_get_child_size(psys, cpa, ctime, 0);
1289                         }
1290
1291                         if(part->ren_as==PART_DRAW_GR) {
1292                                 /* for groups, pick the object based on settings */
1293                                 if(part->draw&PART_DRAW_RAND_GR)
1294                                         b= BLI_rand() % totgroup;
1295                                 else if(part->from==PART_FROM_PARTICLE)
1296                                         b= pa_num % totgroup;
1297                                 else
1298                                         b= a % totgroup;
1299
1300                                 ob = oblist[b];
1301                                 obmat = oblist[b]->obmat;
1302                                 oldobmat = obcopylist[b].obmat;
1303                         }
1304                         else {
1305                                 obmat= ob->obmat;
1306                                 oldobmat= obcopy.obmat;
1307                         }
1308
1309                         if(hair) {
1310                                 /* hair we handle separate and compute transform based on hair keys */
1311                                 if(a < totpart) {
1312                                         cache = psys->pathcache[a];
1313                                         psys_get_dupli_path_transform(&sim, pa, 0, cache, pamat, &scale);
1314                                 }
1315                                 else {
1316                                         cache = psys->childcache[a-totpart];
1317                                         psys_get_dupli_path_transform(&sim, 0, cpa, cache, pamat, &scale);
1318                                 }
1319
1320                                 VECCOPY(pamat[3], cache->co);
1321                                 pamat[3][3]= 1.0f;
1322                                 
1323                         }
1324                         else {
1325                                 /* first key */
1326                                 state.time = ctime;
1327                                 if(psys_get_particle_state(&sim, a, &state, 0) == 0)
1328                                         continue;
1329
1330                                 quat_to_mat4( pamat,state.rot);
1331                                 VECCOPY(pamat[3], state.co);
1332                                 pamat[3][3]= 1.0f;
1333                         }
1334
1335                         if(part->ren_as==PART_DRAW_GR && psys->part->draw & PART_DRAW_WHOLE_GR) {
1336                                 for(go= part->dup_group->gobject.first, b=0; go; go= go->next, b++) {
1337                                         mul_m4_m4m4(tmat, oblist[b]->obmat, pamat);
1338                                         mul_mat3_m4_fl(tmat, size*scale);
1339                                         if(par_space_mat)
1340                                                 mul_m4_m4m4(mat, tmat, par_space_mat);
1341                                         else
1342                                                 copy_m4_m4(mat, tmat);
1343
1344                                         dob= new_dupli_object(lb, go->ob, mat, par->lay, counter, OB_DUPLIPARTS, animated);
1345                                         copy_m4_m4(dob->omat, obcopylist[b].obmat);
1346                                         if(G.rendering)
1347                                                 psys_get_dupli_texture(par, part, sim.psmd, pa, cpa, dob->uv, dob->orco);
1348                                 }
1349                         }
1350                         else {
1351                                 /* to give ipos in object correct offset */
1352                                 where_is_object_time(scene, ob, ctime-pa_time);
1353
1354                                 VECCOPY(vec, obmat[3]);
1355                                 obmat[3][0] = obmat[3][1] = obmat[3][2] = 0.0f;
1356                                 
1357                                 copy_m4_m4(mat, pamat);
1358
1359                                 mul_m4_m4m4(tmat, obmat, mat);
1360                                 mul_mat3_m4_fl(tmat, size*scale);
1361
1362                                 if(part->draw & PART_DRAW_GLOBAL_OB)
1363                                         VECADD(tmat[3], tmat[3], vec);
1364
1365                                 if(par_space_mat)
1366                                         mul_m4_m4m4(mat, tmat, par_space_mat);
1367                                 else
1368                                         copy_m4_m4(mat, tmat);
1369
1370                                 dob= new_dupli_object(lb, ob, mat, ob->lay, counter, OB_DUPLIPARTS, animated);
1371                                 copy_m4_m4(dob->omat, oldobmat);
1372                                 if(G.rendering)
1373                                         psys_get_dupli_texture(par, part, sim.psmd, pa, cpa, dob->uv, dob->orco);
1374                         }
1375                 }
1376
1377                 /* restore objects since they were changed in where_is_object_time */
1378                 if(part->ren_as==PART_DRAW_GR) {
1379                         for(a=0; a<totgroup; a++)
1380                                 *(oblist[a])= obcopylist[a];
1381                 }
1382                 else
1383                         *ob= obcopy;
1384         }
1385
1386         /* clean up */
1387         if(oblist)
1388                 MEM_freeN(oblist);
1389         if(obcopylist)
1390                 MEM_freeN(obcopylist);
1391
1392         if(psys->lattice) {
1393                 end_latt_deform(psys->lattice);
1394                 psys->lattice = NULL;
1395         }
1396 }
1397
1398 static Object *find_family_object(Object **obar, char *family, char ch)
1399 {
1400         Object *ob;
1401         int flen;
1402         
1403         if( obar[(int)ch] ) return obar[(int)ch];
1404         
1405         flen= strlen(family);
1406         
1407         ob= G.main->object.first;
1408         while(ob) {
1409                 if( ob->id.name[flen+2]==ch ) {
1410                         if( strncmp(ob->id.name+2, family, flen)==0 ) break;
1411                 }
1412                 ob= ob->id.next;
1413         }
1414         
1415         obar[(int)ch]= ob;
1416         
1417         return ob;
1418 }
1419
1420
1421 static void font_duplilist(ListBase *lb, Scene *scene, Object *par, int level, int animated)
1422 {
1423         Object *ob, *obar[256];
1424         Curve *cu;
1425         struct chartrans *ct, *chartransdata;
1426         float vec[3], obmat[4][4], pmat[4][4], fsize, xof, yof;
1427         int slen, a;
1428         
1429         /* simple preventing of too deep nested groups */
1430         if(level>MAX_DUPLI_RECUR) return;
1431         
1432         copy_m4_m4(pmat, par->obmat);
1433         
1434         /* in par the family name is stored, use this to find the other objects */
1435         
1436         chartransdata= BKE_text_to_curve(scene, par, FO_DUPLI);
1437         if(chartransdata==0) return;
1438         
1439         memset(obar, 0, 256*sizeof(void *));
1440         
1441         cu= par->data;
1442         slen= strlen(cu->str);
1443         fsize= cu->fsize;
1444         xof= cu->xof;
1445         yof= cu->yof;
1446         
1447         ct= chartransdata;
1448         
1449         for(a=0; a<slen; a++, ct++) {
1450                 
1451                 ob= find_family_object(obar, cu->family, cu->str[a]);
1452                 if(ob) {
1453                         vec[0]= fsize*(ct->xof - xof);
1454                         vec[1]= fsize*(ct->yof - yof);
1455                         vec[2]= 0.0;
1456                         
1457                         mul_m4_v3(pmat, vec);
1458                         
1459                         copy_m4_m4(obmat, par->obmat);
1460                         VECCOPY(obmat[3], vec);
1461                         
1462                         new_dupli_object(lb, ob, obmat, par->lay, a, OB_DUPLIVERTS, animated);
1463                 }
1464         }
1465         
1466         MEM_freeN(chartransdata);
1467 }
1468
1469 /* ------------- */
1470
1471 static void object_duplilist_recursive(ID *id, Scene *scene, Object *ob, ListBase *duplilist, float par_space_mat[][4], int level, int animated)
1472 {       
1473         if((ob->transflag & OB_DUPLI)==0)
1474                 return;
1475         
1476         /* Should the dupli's be generated for this object? - Respect restrict flags */
1477         if (G.rendering) {
1478                 if (ob->restrictflag & OB_RESTRICT_RENDER) {
1479                         return;
1480                 }
1481         } else {
1482                 if (ob->restrictflag & OB_RESTRICT_VIEW) {
1483                         return;
1484                 }
1485         }
1486
1487         if(ob->transflag & OB_DUPLIPARTS) {
1488                 ParticleSystem *psys = ob->particlesystem.first;
1489                 for(; psys; psys=psys->next)
1490                         new_particle_duplilist(duplilist, id, scene, ob, par_space_mat, psys, level+1, animated);
1491         }
1492         else if(ob->transflag & OB_DUPLIVERTS) {
1493                 if(ob->type==OB_MESH) {
1494                         vertex_duplilist(duplilist, id, scene, ob, par_space_mat, level+1, animated);
1495                 }
1496                 else if(ob->type==OB_FONT) {
1497                         if (GS(id->name)==ID_SCE) { /* TODO - support dupligroups */
1498                                 font_duplilist(duplilist, scene, ob, level+1, animated);
1499                         }
1500                 }
1501         }
1502         else if(ob->transflag & OB_DUPLIFACES) {
1503                 if(ob->type==OB_MESH)
1504                         face_duplilist(duplilist, id, scene, ob, par_space_mat, level+1, animated);
1505         }
1506         else if(ob->transflag & OB_DUPLIFRAMES) {
1507                 if (GS(id->name)==ID_SCE) { /* TODO - support dupligroups */
1508                         frames_duplilist(duplilist, scene, ob, level+1, animated);
1509                 }
1510         } else if(ob->transflag & OB_DUPLIGROUP) {
1511                 DupliObject *dob;
1512                 
1513                 group_duplilist(duplilist, scene, ob, level+1, animated); /* now recursive */
1514
1515                 if (level==0) {
1516                         for(dob= duplilist->first; dob; dob= dob->next)
1517                                 if(dob->type == OB_DUPLIGROUP)
1518                                         copy_m4_m4(dob->ob->obmat, dob->mat);
1519                 }
1520         }
1521 }
1522
1523 /* Returns a list of DupliObject
1524  * note; group dupli's already set transform matrix. see note in group_duplilist() */
1525 ListBase *object_duplilist(Scene *sce, Object *ob)
1526 {
1527         ListBase *duplilist= MEM_mallocN(sizeof(ListBase), "duplilist");
1528         duplilist->first= duplilist->last= NULL;
1529         object_duplilist_recursive((ID *)sce, sce, ob, duplilist, NULL, 0, 0);
1530         return duplilist;
1531 }
1532
1533 void free_object_duplilist(ListBase *lb)
1534 {
1535         DupliObject *dob;
1536         
1537         /* loop in reverse order, if object is instanced multiple times
1538            the original layer may not really be original otherwise, proper
1539            solution is more complicated */
1540         for(dob= lb->last; dob; dob= dob->prev) {
1541                 dob->ob->lay= dob->origlay;
1542                 copy_m4_m4(dob->ob->obmat, dob->omat);
1543         }
1544         
1545         BLI_freelistN(lb);
1546         MEM_freeN(lb);
1547 }
1548
1549 int count_duplilist(Object *ob)
1550 {
1551         if(ob->transflag & OB_DUPLI) {
1552                 if(ob->transflag & OB_DUPLIVERTS) {
1553                         if(ob->type==OB_MESH) {
1554                                 if(ob->transflag & OB_DUPLIVERTS) {
1555                                         ParticleSystem *psys = ob->particlesystem.first;
1556                                         int pdup=0;
1557
1558                                         for(; psys; psys=psys->next)
1559                                                 pdup += psys->totpart;
1560
1561                                         if(pdup==0){
1562                                                 Mesh *me= ob->data;
1563                                                 return me->totvert;
1564                                         }
1565                                         else
1566                                                 return pdup;
1567                                 }
1568                         }
1569                 }
1570                 else if(ob->transflag & OB_DUPLIFRAMES) {
1571                         int tot= ob->dupend - ob->dupsta; 
1572                         tot/= (ob->dupon+ob->dupoff);
1573                         return tot*ob->dupon;
1574                 }
1575         }
1576         return 1;
1577 }