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