merge with trunk at r31523
[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 #include "DNA_anim_types.h"
44 #include "DNA_armature_types.h"
45 #include "DNA_group_types.h"
46 #include "DNA_key_types.h"
47 #include "DNA_meshdata_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_windowmanager_types.h"
50 #include "DNA_view3d_types.h"
51 #include "DNA_vfont_types.h"
52
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_tessmesh.h"
68 #include "BKE_depsgraph.h"
69
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         BMEditMesh *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 = me->edit_btmesh;
867         
868         if(em) {
869                 dm= editbmesh_get_derived_cage(scene, par, em, CD_MASK_BAREMESH);
870         } else
871                 dm= mesh_get_derived_deform(scene, par, CD_MASK_BAREMESH);
872         
873         if(G.rendering) {
874                 vdd.orco= (float(*)[3])get_mesh_orco_verts(par);
875                 transform_mesh_orco_verts(me, vdd.orco, me->totvert, 0);
876         }
877         else
878                 vdd.orco= NULL;
879         
880         totvert = dm->getNumVerts(dm);
881
882         /* having to loop on scene OR group objects is NOT FUN */
883         if (GS(id->name) == ID_SCE) {
884                 sce = (Scene *)id;
885                 lay= sce->lay;
886                 base= sce->base.first;
887         } else {
888                 group = (Group *)id;
889                 lay= group->layer;
890                 go = group->gobject.first;
891         }
892         
893         /* Start looping on Scene OR Group objects */
894         while (base || go) { 
895                 if (sce) {
896                         ob_iter= base->object;
897                         oblay = base->lay;
898                 } else {
899                         ob_iter= go->ob;
900                         oblay = ob_iter->lay;
901                 }
902                 
903                 if (lay & oblay && scene->obedit!=ob_iter) {
904                         ob=ob_iter->parent;
905                         while(ob) {
906                                 if(ob==par) {
907                                         ob = ob_iter;
908         /* End Scene/Group object loop, below is generic */
909                                         
910                                         
911                                         /* par_space_mat - only used for groups so we can modify the space dupli's are in
912                                            when par_space_mat is NULL ob->obmat can be used instead of ob__obmat
913                                         */
914                                         if(par_space_mat)
915                                                 mul_m4_m4m4(vdd.obmat, ob->obmat, par_space_mat);
916                                         else
917                                                 copy_m4_m4(vdd.obmat, ob->obmat);
918
919                                         vdd.id= id;
920                                         vdd.level= level;
921                                         vdd.animated= animated;
922                                         vdd.lb= lb;
923                                         vdd.ob= ob;
924                                         vdd.scene= scene;
925                                         vdd.par= par;
926                                         copy_m4_m4(vdd.pmat, pmat);
927                                         
928                                         /* mballs have a different dupli handling */
929                                         if(ob->type!=OB_MBALL) ob->flag |= OB_DONE;     /* doesnt render */
930
931                                         if(me->edit_btmesh) {
932                                                 dm->foreachMappedVert(dm, vertex_dupli__mapFunc, (void*) &vdd);
933                                         }
934                                         else {
935                                                 for(a=0; a<totvert; a++) {
936                                                         dm->getVertCo(dm, a, vec);
937                                                         dm->getVertNo(dm, a, no);
938                                                         
939                                                         vertex_dupli__mapFunc(&vdd, a, vec, no, NULL);
940                                                 }
941                                         }
942                                         
943                                         break;
944                                 }
945                                 ob= ob->parent;
946                         }
947                 }
948                 if (sce)        base= base->next;       /* scene loop */
949                 else            go= go->next;           /* group loop */
950         }
951
952         if(vdd.orco)
953                 MEM_freeN(vdd.orco);
954         dm->release(dm);
955 }
956
957 static void face_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], int level, int animated)
958 {
959         Object *ob, *ob_iter;
960         Base *base = NULL;
961         DupliObject *dob;
962         DerivedMesh *dm;
963         Mesh *me= par->data;
964         MTFace *mtface;
965         MFace *mface;
966         MVert *mvert;
967         float pmat[4][4], imat[3][3], (*orco)[3] = NULL, w;
968         int lay, oblay, totface, a;
969         Scene *sce = NULL;
970         Group *group = NULL;
971         GroupObject *go = NULL;
972         BMEditMesh *em;
973         float ob__obmat[4][4]; /* needed for groups where the object matrix needs to be modified */
974         
975         /* simple preventing of too deep nested groups */
976         if(level>MAX_DUPLI_RECUR) return;
977         
978         copy_m4_m4(pmat, par->obmat);
979         em = me->edit_btmesh;
980
981         if(em) {
982                 int totvert;
983                 dm= editbmesh_get_derived_cage(scene, par, em, CD_MASK_BAREMESH);
984                 
985                 totface= dm->getNumTessFaces(dm);
986                 mface= MEM_mallocN(sizeof(MFace)*totface, "mface temp");
987                 dm->copyTessFaceArray(dm, mface);
988                 totvert= dm->getNumVerts(dm);
989                 mvert= MEM_mallocN(sizeof(MVert)*totvert, "mvert temp");
990                 dm->copyVertArray(dm, mvert);
991         }
992         else {
993                 dm = mesh_get_derived_deform(scene, par, CD_MASK_BAREMESH);
994                 
995                 totface= dm->getNumTessFaces(dm);
996                 mface= dm->getTessFaceArray(dm);
997                 mvert= dm->getVertArray(dm);
998         }
999
1000         if(G.rendering) {
1001
1002                 orco= (float(*)[3])get_mesh_orco_verts(par);
1003                 transform_mesh_orco_verts(me, orco, me->totvert, 0);
1004                 mtface= me->mtface;
1005         }
1006         else {
1007                 orco= NULL;
1008                 mtface= NULL;
1009         }
1010         
1011         /* having to loop on scene OR group objects is NOT FUN */
1012         if (GS(id->name) == ID_SCE) {
1013                 sce = (Scene *)id;
1014                 lay= sce->lay;
1015                 base= sce->base.first;
1016         } else {
1017                 group = (Group *)id;
1018                 lay= group->layer;
1019                 go = group->gobject.first;
1020         }
1021         
1022         /* Start looping on Scene OR Group objects */
1023         while (base || go) { 
1024                 if (sce) {
1025                         ob_iter= base->object;
1026                         oblay = base->lay;
1027                 } else {
1028                         ob_iter= go->ob;
1029                         oblay = ob_iter->lay;
1030                 }
1031                 
1032                 if (lay & oblay && scene->obedit!=ob_iter) {
1033                         ob=ob_iter->parent;
1034                         while(ob) {
1035                                 if(ob==par) {
1036                                         ob = ob_iter;
1037         /* End Scene/Group object loop, below is generic */
1038                                         
1039                                         /* par_space_mat - only used for groups so we can modify the space dupli's are in
1040                                            when par_space_mat is NULL ob->obmat can be used instead of ob__obmat
1041                                         */
1042                                         if(par_space_mat)
1043                                                 mul_m4_m4m4(ob__obmat, ob->obmat, par_space_mat);
1044                                         else
1045                                                 copy_m4_m4(ob__obmat, ob->obmat);
1046                                         
1047                                         copy_m3_m4(imat, ob->parentinv);
1048                                                 
1049                                         /* mballs have a different dupli handling */
1050                                         if(ob->type!=OB_MBALL) ob->flag |= OB_DONE;     /* doesnt render */
1051
1052                                         for(a=0; a<totface; a++) {
1053                                                 int mv1 = mface[a].v1;
1054                                                 int mv2 = mface[a].v2;
1055                                                 int mv3 = mface[a].v3;
1056                                                 int mv4 = mface[a].v4;
1057                                                 float *v1= mvert[mv1].co;
1058                                                 float *v2= mvert[mv2].co;
1059                                                 float *v3= mvert[mv3].co;
1060                                                 float *v4= (mv4)? mvert[mv4].co: NULL;
1061                                                 float cent[3], quat[4], mat[3][3], mat3[3][3], tmat[4][4], obmat[4][4];
1062
1063                                                 /* translation */
1064                                                 if(v4)
1065                                                         cent_quad_v3(cent, v1, v2, v3, v4);
1066                                                 else
1067                                                         cent_tri_v3(cent, v1, v2, v3);
1068                                                 mul_m4_v3(pmat, cent);
1069                                                 
1070                                                 sub_v3_v3v3(cent, cent, pmat[3]);
1071                                                 add_v3_v3(cent, ob__obmat[3]);
1072                                                 
1073                                                 copy_m4_m4(obmat, ob__obmat);
1074                                                 
1075                                                 VECCOPY(obmat[3], cent);
1076                                                 
1077                                                 /* rotation */
1078                                                 tri_to_quat( quat,v1, v2, v3);
1079                                                 quat_to_mat3( mat,quat);
1080                                                 
1081                                                 /* scale */
1082                                                 if(par->transflag & OB_DUPLIFACES_SCALE) {
1083                                                         float size= v4? area_quad_v3(v1, v2, v3, v4): area_tri_v3(v1, v2, v3);
1084                                                         size= sqrt(size) * par->dupfacesca;
1085                                                         mul_m3_fl(mat, size);
1086                                                 }
1087                                                 
1088                                                 copy_m3_m3(mat3, mat);
1089                                                 mul_m3_m3m3(mat, imat, mat3);
1090                                                 
1091                                                 copy_m4_m4(tmat, obmat);
1092                                                 mul_m4_m4m3(obmat, tmat, mat);
1093                                                 
1094                                                 dob= new_dupli_object(lb, ob, obmat, par->lay, a, OB_DUPLIFACES, animated);
1095                                                 if(G.rendering) {
1096                                                         w= (mv4)? 0.25f: 1.0f/3.0f;
1097
1098                                                         if(orco) {
1099                                                                 VECADDFAC(dob->orco, dob->orco, orco[mv1], w);
1100                                                                 VECADDFAC(dob->orco, dob->orco, orco[mv2], w);
1101                                                                 VECADDFAC(dob->orco, dob->orco, orco[mv3], w);
1102                                                                 if(mv4)
1103                                                                         VECADDFAC(dob->orco, dob->orco, orco[mv4], w);
1104                                                         }
1105
1106                                                         if(mtface) {
1107                                                                 dob->uv[0] += w*mtface[a].uv[0][0];
1108                                                                 dob->uv[1] += w*mtface[a].uv[0][1];
1109                                                                 dob->uv[0] += w*mtface[a].uv[1][0];
1110                                                                 dob->uv[1] += w*mtface[a].uv[1][1];
1111                                                                 dob->uv[0] += w*mtface[a].uv[2][0];
1112                                                                 dob->uv[1] += w*mtface[a].uv[2][1];
1113
1114                                                                 if(mv4) {
1115                                                                         dob->uv[0] += w*mtface[a].uv[3][0];
1116                                                                         dob->uv[1] += w*mtface[a].uv[3][1];
1117                                                                 }
1118                                                         }
1119                                                 }
1120                                                 
1121                                                 if(ob->transflag & OB_DUPLI) {
1122                                                         float tmpmat[4][4];
1123                                                         copy_m4_m4(tmpmat, ob->obmat);
1124                                                         copy_m4_m4(ob->obmat, obmat); /* pretend we are really this mat */
1125                                                         object_duplilist_recursive((ID *)id, scene, ob, lb, ob->obmat, level+1, animated);
1126                                                         copy_m4_m4(ob->obmat, tmpmat);
1127                                                 }
1128                                         }
1129                                         
1130                                         break;
1131                                 }
1132                                 ob= ob->parent;
1133                         }
1134                 }
1135                 if (sce)        base= base->next;       /* scene loop */
1136                 else            go= go->next;           /* group loop */
1137         }
1138         
1139         if(em) {
1140                 MEM_freeN(mface);
1141                 MEM_freeN(mvert);
1142         }
1143
1144         if(orco)
1145                 MEM_freeN(orco);
1146         
1147         dm->release(dm);
1148 }
1149
1150 static void new_particle_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], ParticleSystem *psys, int level, int animated)
1151 {
1152         GroupObject *go;
1153         Object *ob=0, **oblist=0, obcopy, *obcopylist=0;
1154         DupliObject *dob;
1155         ParticleDupliWeight *dw;
1156         ParticleSimulationData sim = {scene, par, psys, psys_get_modifier(par, psys)};
1157         ParticleSettings *part;
1158         ParticleData *pa;
1159         ChildParticle *cpa=0;
1160         ParticleKey state;
1161         ParticleCacheKey *cache;
1162         float ctime, pa_time, scale = 1.0f;
1163         float tmat[4][4], mat[4][4], pamat[4][4], vec[3], size=0.0;
1164         float (*obmat)[4], (*oldobmat)[4];
1165         int lay, a, b, counter, hair = 0;
1166         int totpart, totchild, totgroup=0, pa_num;
1167
1168         if(psys==0) return;
1169         
1170         /* simple preventing of too deep nested groups */
1171         if(level>MAX_DUPLI_RECUR) return;
1172         
1173         part=psys->part;
1174
1175         if(part==0)
1176                 return;
1177
1178         if(!psys_check_enabled(par, psys))
1179                 return;
1180         
1181         ctime = bsystem_time(scene, par, (float)scene->r.cfra, 0.0);
1182
1183         totpart = psys->totpart;
1184         totchild = psys->totchild;
1185
1186         BLI_srandom(31415926 + psys->seed);
1187         
1188         lay= scene->lay;
1189         if((psys->renderdata || part->draw_as==PART_DRAW_REND) && ELEM(part->ren_as, PART_DRAW_OB, PART_DRAW_GR)) {
1190
1191                 /* first check for loops (particle system object used as dupli object) */
1192                 if(part->ren_as == PART_DRAW_OB) {
1193                         if(ELEM(part->dup_ob, NULL, par))
1194                                 return;
1195                 }
1196                 else { /*PART_DRAW_GR */
1197                         if(part->dup_group == NULL || part->dup_group->gobject.first == NULL)
1198                                 return;
1199
1200                         for(go=part->dup_group->gobject.first; go; go=go->next)
1201                                 if(go->ob == par)
1202                                         return;
1203                 }
1204
1205                 /* if we have a hair particle system, use the path cache */
1206                 if(part->type == PART_HAIR) {
1207                         if(psys->flag & PSYS_HAIR_DONE)
1208                                 hair= (totchild == 0 || psys->childcache) && psys->pathcache;
1209                         if(!hair)
1210                                 return;
1211                         
1212                         /* we use cache, update totchild according to cached data */
1213                         totchild = psys->totchildcache;
1214                         totpart = psys->totcached;
1215                 }
1216
1217                 psys_check_group_weights(part);
1218
1219                 psys->lattice = psys_get_lattice(&sim);
1220
1221                 /* gather list of objects or single object */
1222                 if(part->ren_as==PART_DRAW_GR) {
1223                         group_handle_recalc_and_update(scene, par, part->dup_group);
1224
1225                         if(part->draw & PART_DRAW_COUNT_GR) {
1226                                 for(dw=part->dupliweights.first; dw; dw=dw->next)
1227                                         totgroup += dw->count;
1228                         }
1229                         else {
1230                                 for(go=part->dup_group->gobject.first; go; go=go->next)
1231                                         totgroup++;
1232                         }
1233
1234                         /* we also copy the actual objects to restore afterwards, since
1235                          * where_is_object_time will change the object which breaks transform */
1236                         oblist = MEM_callocN(totgroup*sizeof(Object *), "dupgroup object list");
1237                         obcopylist = MEM_callocN(totgroup*sizeof(Object), "dupgroup copy list");
1238
1239                         
1240                         if(part->draw & PART_DRAW_COUNT_GR && totgroup) {
1241                                 dw = part->dupliweights.first;
1242
1243                                 for(a=0; a<totgroup; dw=dw->next) {
1244                                         for(b=0; b<dw->count; b++, a++) {
1245                                                 oblist[a] = dw->ob;
1246                                                 obcopylist[a] = *dw->ob;
1247                                         }
1248                                 }
1249                         }
1250                         else {
1251                                 go = part->dup_group->gobject.first;
1252                                 for(a=0; a<totgroup; a++, go=go->next) {
1253                                         oblist[a] = go->ob;
1254                                         obcopylist[a] = *go->ob;
1255                                 }
1256                         }
1257                 }
1258                 else {
1259                         ob = part->dup_ob;
1260                         obcopy = *ob;
1261                 }
1262
1263                 if(totchild==0 || part->draw & PART_DRAW_PARENT)
1264                         a = 0;
1265                 else
1266                         a = totpart;
1267
1268                 for(pa=psys->particles,counter=0; a<totpart+totchild; a++,pa++,counter++) {
1269                         if(a<totpart) {
1270                                 /* handle parent particle */
1271                                 if(pa->flag & (PARS_UNEXIST+PARS_NO_DISP))
1272                                         continue;
1273
1274                                 pa_num = pa->num;
1275                                 pa_time = pa->time;
1276                                 size = pa->size;
1277                         }
1278                         else {
1279                                 /* handle child particle */
1280                                 cpa = &psys->child[a - totpart];
1281
1282                                 pa_num = a;
1283                                 pa_time = psys->particles[cpa->parent].time;
1284                                 size = psys_get_child_size(psys, cpa, ctime, 0);
1285                         }
1286
1287                         if(part->ren_as==PART_DRAW_GR) {
1288                                 /* for groups, pick the object based on settings */
1289                                 if(part->draw&PART_DRAW_RAND_GR)
1290                                         b= BLI_rand() % totgroup;
1291                                 else if(part->from==PART_FROM_PARTICLE)
1292                                         b= pa_num % totgroup;
1293                                 else
1294                                         b= a % totgroup;
1295
1296                                 ob = oblist[b];
1297                                 obmat = oblist[b]->obmat;
1298                                 oldobmat = obcopylist[b].obmat;
1299                         }
1300                         else {
1301                                 obmat= ob->obmat;
1302                                 oldobmat= obcopy.obmat;
1303                         }
1304
1305                         if(hair) {
1306                                 /* hair we handle separate and compute transform based on hair keys */
1307                                 if(a < totpart) {
1308                                         cache = psys->pathcache[a];
1309                                         psys_get_dupli_path_transform(&sim, pa, 0, cache, pamat, &scale);
1310                                 }
1311                                 else {
1312                                         cache = psys->childcache[a-totpart];
1313                                         psys_get_dupli_path_transform(&sim, 0, cpa, cache, pamat, &scale);
1314                                 }
1315
1316                                 VECCOPY(pamat[3], cache->co);
1317                                 pamat[3][3]= 1.0f;
1318                                 
1319                         }
1320                         else {
1321                                 /* first key */
1322                                 state.time = ctime;
1323                                 if(psys_get_particle_state(&sim, a, &state, 0) == 0)
1324                                         continue;
1325
1326                                 quat_to_mat4( pamat,state.rot);
1327                                 VECCOPY(pamat[3], state.co);
1328                                 pamat[3][3]= 1.0f;
1329                         }
1330
1331                         if(part->ren_as==PART_DRAW_GR && psys->part->draw & PART_DRAW_WHOLE_GR) {
1332                                 for(go= part->dup_group->gobject.first, b=0; go; go= go->next, b++) {
1333                                         mul_m4_m4m4(tmat, oblist[b]->obmat, pamat);
1334                                         mul_mat3_m4_fl(tmat, size*scale);
1335                                         if(par_space_mat)
1336                                                 mul_m4_m4m4(mat, tmat, par_space_mat);
1337                                         else
1338                                                 copy_m4_m4(mat, tmat);
1339
1340                                         dob= new_dupli_object(lb, go->ob, mat, par->lay, counter, OB_DUPLIPARTS, animated);
1341                                         copy_m4_m4(dob->omat, obcopylist[b].obmat);
1342                                         if(G.rendering)
1343                                                 psys_get_dupli_texture(par, part, sim.psmd, pa, cpa, dob->uv, dob->orco);
1344                                 }
1345                         }
1346                         else {
1347                                 /* to give ipos in object correct offset */
1348                                 where_is_object_time(scene, ob, ctime-pa_time);
1349
1350                                 VECCOPY(vec, obmat[3]);
1351                                 obmat[3][0] = obmat[3][1] = obmat[3][2] = 0.0f;
1352                                 
1353                                 copy_m4_m4(mat, pamat);
1354
1355                                 mul_m4_m4m4(tmat, obmat, mat);
1356                                 mul_mat3_m4_fl(tmat, size*scale);
1357
1358                                 if(part->draw & PART_DRAW_GLOBAL_OB)
1359                                         VECADD(tmat[3], tmat[3], vec);
1360
1361                                 if(par_space_mat)
1362                                         mul_m4_m4m4(mat, tmat, par_space_mat);
1363                                 else
1364                                         copy_m4_m4(mat, tmat);
1365
1366                                 dob= new_dupli_object(lb, ob, mat, ob->lay, counter, OB_DUPLIPARTS, animated);
1367                                 copy_m4_m4(dob->omat, oldobmat);
1368                                 if(G.rendering)
1369                                         psys_get_dupli_texture(par, part, sim.psmd, pa, cpa, dob->uv, dob->orco);
1370                         }
1371                 }
1372
1373                 /* restore objects since they were changed in where_is_object_time */
1374                 if(part->ren_as==PART_DRAW_GR) {
1375                         for(a=0; a<totgroup; a++)
1376                                 *(oblist[a])= obcopylist[a];
1377                 }
1378                 else
1379                         *ob= obcopy;
1380         }
1381
1382         /* clean up */
1383         if(oblist)
1384                 MEM_freeN(oblist);
1385         if(obcopylist)
1386                 MEM_freeN(obcopylist);
1387
1388         if(psys->lattice) {
1389                 end_latt_deform(psys->lattice);
1390                 psys->lattice = NULL;
1391         }
1392 }
1393
1394 static Object *find_family_object(Object **obar, char *family, char ch)
1395 {
1396         Object *ob;
1397         int flen;
1398         
1399         if( obar[(int)ch] ) return obar[(int)ch];
1400         
1401         flen= strlen(family);
1402         
1403         ob= G.main->object.first;
1404         while(ob) {
1405                 if( ob->id.name[flen+2]==ch ) {
1406                         if( strncmp(ob->id.name+2, family, flen)==0 ) break;
1407                 }
1408                 ob= ob->id.next;
1409         }
1410         
1411         obar[(int)ch]= ob;
1412         
1413         return ob;
1414 }
1415
1416
1417 static void font_duplilist(ListBase *lb, Scene *scene, Object *par, int level, int animated)
1418 {
1419         Object *ob, *obar[256];
1420         Curve *cu;
1421         struct chartrans *ct, *chartransdata;
1422         float vec[3], obmat[4][4], pmat[4][4], fsize, xof, yof;
1423         int slen, a;
1424         
1425         /* simple preventing of too deep nested groups */
1426         if(level>MAX_DUPLI_RECUR) return;
1427         
1428         copy_m4_m4(pmat, par->obmat);
1429         
1430         /* in par the family name is stored, use this to find the other objects */
1431         
1432         chartransdata= BKE_text_to_curve(scene, par, FO_DUPLI);
1433         if(chartransdata==0) return;
1434         
1435         memset(obar, 0, 256*sizeof(void *));
1436         
1437         cu= par->data;
1438         slen= strlen(cu->str);
1439         fsize= cu->fsize;
1440         xof= cu->xof;
1441         yof= cu->yof;
1442         
1443         ct= chartransdata;
1444         
1445         for(a=0; a<slen; a++, ct++) {
1446                 
1447                 ob= find_family_object(obar, cu->family, cu->str[a]);
1448                 if(ob) {
1449                         vec[0]= fsize*(ct->xof - xof);
1450                         vec[1]= fsize*(ct->yof - yof);
1451                         vec[2]= 0.0;
1452                         
1453                         mul_m4_v3(pmat, vec);
1454                         
1455                         copy_m4_m4(obmat, par->obmat);
1456                         VECCOPY(obmat[3], vec);
1457                         
1458                         new_dupli_object(lb, ob, obmat, par->lay, a, OB_DUPLIVERTS, animated);
1459                 }
1460         }
1461         
1462         MEM_freeN(chartransdata);
1463 }
1464
1465 /* ------------- */
1466
1467 static void object_duplilist_recursive(ID *id, Scene *scene, Object *ob, ListBase *duplilist, float par_space_mat[][4], int level, int animated)
1468 {       
1469         if((ob->transflag & OB_DUPLI)==0)
1470                 return;
1471         
1472         /* Should the dupli's be generated for this object? - Respect restrict flags */
1473         if (G.rendering) {
1474                 if (ob->restrictflag & OB_RESTRICT_RENDER) {
1475                         return;
1476                 }
1477         } else {
1478                 if (ob->restrictflag & OB_RESTRICT_VIEW) {
1479                         return;
1480                 }
1481         }
1482
1483         if(ob->transflag & OB_DUPLIPARTS) {
1484                 ParticleSystem *psys = ob->particlesystem.first;
1485                 for(; psys; psys=psys->next)
1486                         new_particle_duplilist(duplilist, id, scene, ob, par_space_mat, psys, level+1, animated);
1487         }
1488         else if(ob->transflag & OB_DUPLIVERTS) {
1489                 if(ob->type==OB_MESH) {
1490                         vertex_duplilist(duplilist, id, scene, ob, par_space_mat, level+1, animated);
1491                 }
1492                 else if(ob->type==OB_FONT) {
1493                         if (GS(id->name)==ID_SCE) { /* TODO - support dupligroups */
1494                                 font_duplilist(duplilist, scene, ob, level+1, animated);
1495                         }
1496                 }
1497         }
1498         else if(ob->transflag & OB_DUPLIFACES) {
1499                 if(ob->type==OB_MESH)
1500                         face_duplilist(duplilist, id, scene, ob, par_space_mat, level+1, animated);
1501         }
1502         else if(ob->transflag & OB_DUPLIFRAMES) {
1503                 if (GS(id->name)==ID_SCE) { /* TODO - support dupligroups */
1504                         frames_duplilist(duplilist, scene, ob, level+1, animated);
1505                 }
1506         } else if(ob->transflag & OB_DUPLIGROUP) {
1507                 DupliObject *dob;
1508                 
1509                 group_duplilist(duplilist, scene, ob, level+1, animated); /* now recursive */
1510
1511                 if (level==0) {
1512                         for(dob= duplilist->first; dob; dob= dob->next)
1513                                 if(dob->type == OB_DUPLIGROUP)
1514                                         copy_m4_m4(dob->ob->obmat, dob->mat);
1515                 }
1516         }
1517 }
1518
1519 /* Returns a list of DupliObject
1520  * note; group dupli's already set transform matrix. see note in group_duplilist() */
1521 ListBase *object_duplilist(Scene *sce, Object *ob)
1522 {
1523         ListBase *duplilist= MEM_mallocN(sizeof(ListBase), "duplilist");
1524         duplilist->first= duplilist->last= NULL;
1525         object_duplilist_recursive((ID *)sce, sce, ob, duplilist, NULL, 0, 0);
1526         return duplilist;
1527 }
1528
1529 void free_object_duplilist(ListBase *lb)
1530 {
1531         DupliObject *dob;
1532         
1533         /* loop in reverse order, if object is instanced multiple times
1534            the original layer may not really be original otherwise, proper
1535            solution is more complicated */
1536         for(dob= lb->last; dob; dob= dob->prev) {
1537                 dob->ob->lay= dob->origlay;
1538                 copy_m4_m4(dob->ob->obmat, dob->omat);
1539         }
1540         
1541         BLI_freelistN(lb);
1542         MEM_freeN(lb);
1543 }
1544
1545 int count_duplilist(Object *ob)
1546 {
1547         if(ob->transflag & OB_DUPLI) {
1548                 if(ob->transflag & OB_DUPLIVERTS) {
1549                         if(ob->type==OB_MESH) {
1550                                 if(ob->transflag & OB_DUPLIVERTS) {
1551                                         ParticleSystem *psys = ob->particlesystem.first;
1552                                         int pdup=0;
1553
1554                                         for(; psys; psys=psys->next)
1555                                                 pdup += psys->totpart;
1556
1557                                         if(pdup==0){
1558                                                 Mesh *me= ob->data;
1559                                                 return me->totvert;
1560                                         }
1561                                         else
1562                                                 return pdup;
1563                                 }
1564                         }
1565                 }
1566                 else if(ob->transflag & OB_DUPLIFRAMES) {
1567                         int tot= ob->dupend - ob->dupsta; 
1568                         tot/= (ob->dupon+ob->dupoff);
1569                         return tot*ob->dupon;
1570                 }
1571         }
1572         return 1;
1573 }