svn merge ^/trunk/blender -r42221:42245
[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_editVert.h"
41 #include "BLI_math.h"
42 #include "BLI_rand.h"
43 #include "BLI_utildefines.h"
44
45 #include "DNA_anim_types.h"
46 #include "DNA_armature_types.h"
47 #include "DNA_group_types.h"
48 #include "DNA_key_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 /* Initialise 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 dependant 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, and returns whether this operation succeeded 
590  *      - *vec needs FOUR items!
591  *      - ctime is normalized range <0-1>
592  */
593 int where_on_path(Object *ob, float ctime, float *vec, float *dir, float *quat, float *radius, float *weight)   /* returns OK */
594 {
595         Curve *cu;
596         Nurb *nu;
597         BevList *bl;
598         Path *path;
599         PathPoint *pp, *p0, *p1, *p2, *p3;
600         float fac;
601         float data[4];
602         int cycl=0, s0, s1, s2, s3;
603
604         if(ob==NULL || ob->type != OB_CURVE) return 0;
605         cu= ob->data;
606         if(cu->path==NULL || cu->path->data==NULL) {
607                 printf("no path!\n");
608                 return 0;
609         }
610         path= cu->path;
611         pp= path->data;
612         
613         /* test for cyclic */
614         bl= cu->bev.first;
615         if (!bl) return 0;
616         if (!bl->nr) return 0;
617         if(bl->poly> -1) cycl= 1;
618
619         ctime *= (path->len-1);
620         
621         s1= (int)floor(ctime);
622         fac= (float)(s1+1)-ctime;
623
624         /* path->len is corected for cyclic */
625         s0= interval_test(0, path->len-1-cycl, s1-1, cycl);
626         s1= interval_test(0, path->len-1-cycl, s1, cycl);
627         s2= interval_test(0, path->len-1-cycl, s1+1, cycl);
628         s3= interval_test(0, path->len-1-cycl, s1+2, cycl);
629
630         p0= pp + s0;
631         p1= pp + s1;
632         p2= pp + s2;
633         p3= pp + s3;
634
635         /* note, commented out for follow constraint */
636         //if(cu->flag & CU_FOLLOW) {
637
638                 key_curve_tangent_weights(1.0f-fac, data, KEY_BSPLINE);
639
640                 interp_v3_v3v3v3v3(dir, p0->vec, p1->vec, p2->vec, p3->vec, data);
641
642                 /* make compatible with vectoquat */
643                 negate_v3(dir);
644         //}
645         
646         nu= cu->nurb.first;
647
648         /* make sure that first and last frame are included in the vectors here  */
649         if(nu->type == CU_POLY) key_curve_position_weights(1.0f-fac, data, KEY_LINEAR);
650         else if(nu->type == CU_BEZIER) key_curve_position_weights(1.0f-fac, data, KEY_LINEAR);
651         else if(s0==s1 || p2==p3) key_curve_position_weights(1.0f-fac, data, KEY_CARDINAL);
652         else key_curve_position_weights(1.0f-fac, data, KEY_BSPLINE);
653
654         vec[0]= data[0]*p0->vec[0] + data[1]*p1->vec[0] + data[2]*p2->vec[0] + data[3]*p3->vec[0] ; /* X */
655         vec[1]= data[0]*p0->vec[1] + data[1]*p1->vec[1] + data[2]*p2->vec[1] + data[3]*p3->vec[1] ; /* Y */
656         vec[2]= data[0]*p0->vec[2] + data[1]*p1->vec[2] + data[2]*p2->vec[2] + data[3]*p3->vec[2] ; /* Z */
657         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 */
658
659         if (quat) {
660                 float totfac, q1[4], q2[4];
661
662                 totfac= data[0]+data[3];
663                 if(totfac>FLT_EPSILON)  interp_qt_qtqt(q1, p0->quat, p3->quat, data[3] / totfac);
664                 else                                    copy_qt_qt(q1, p1->quat);
665
666                 totfac= data[1]+data[2];
667                 if(totfac>FLT_EPSILON)  interp_qt_qtqt(q2, p1->quat, p2->quat, data[2] / totfac);
668                 else                                    copy_qt_qt(q2, p3->quat);
669
670                 totfac = data[0]+data[1]+data[2]+data[3];
671                 if(totfac>FLT_EPSILON)  interp_qt_qtqt(quat, q1, q2, (data[1]+data[2]) / totfac);
672                 else                                    copy_qt_qt(quat, q2);
673         }
674
675         if(radius)
676                 *radius= data[0]*p0->radius + data[1]*p1->radius + data[2]*p2->radius + data[3]*p3->radius;
677
678         if(weight)
679                 *weight= data[0]*p0->weight + data[1]*p1->weight + data[2]*p2->weight + data[3]*p3->weight;
680
681         return 1;
682 }
683
684 /* ******************************************************************** */
685 /* Dupli-Geometry */
686
687 static DupliObject *new_dupli_object(ListBase *lb, Object *ob, float mat[][4], int lay, int index, int type, int animated)
688 {
689         DupliObject *dob= MEM_callocN(sizeof(DupliObject), "dupliobject");
690         
691         BLI_addtail(lb, dob);
692         dob->ob= ob;
693         copy_m4_m4(dob->mat, mat);
694         copy_m4_m4(dob->omat, ob->obmat);
695         dob->origlay= ob->lay;
696         dob->index= index;
697         dob->type= type;
698         dob->animated= (type == OB_DUPLIGROUP) && animated;
699         ob->lay= lay;
700         
701         return dob;
702 }
703
704 static void group_duplilist(ListBase *lb, Scene *scene, Object *ob, int level, int animated)
705 {
706         DupliObject *dob;
707         Group *group;
708         GroupObject *go;
709         float mat[4][4], tmat[4][4];
710         
711         if(ob->dup_group==NULL) return;
712         group= ob->dup_group;
713         
714         /* simple preventing of too deep nested groups */
715         if(level>MAX_DUPLI_RECUR) return;
716         
717         /* handles animated groups, and */
718         /* we need to check update for objects that are not in scene... */
719         group_handle_recalc_and_update(scene, ob, group);
720         animated= animated || group_is_animated(ob, group);
721         
722         for(go= group->gobject.first; go; go= go->next) {
723                 /* note, if you check on layer here, render goes wrong... it still deforms verts and uses parent imat */
724                 if(go->ob!=ob) {
725                         
726                         /* group dupli offset, should apply after everything else */
727                         if(!is_zero_v3(group->dupli_ofs)) {
728                                 copy_m4_m4(tmat, go->ob->obmat);
729                                 sub_v3_v3v3(tmat[3], tmat[3], group->dupli_ofs);
730                                 mul_m4_m4m4(mat, tmat, ob->obmat);
731                         }
732                         else {
733                                 mul_m4_m4m4(mat, go->ob->obmat, ob->obmat);
734                         }
735                         
736                         dob= new_dupli_object(lb, go->ob, mat, ob->lay, 0, OB_DUPLIGROUP, animated);
737
738                         /* check the group instance and object layers match, also that the object visible flags are ok. */
739                         if(     (dob->origlay & group->layer)==0 ||
740                                 (G.rendering==0 && dob->ob->restrictflag & OB_RESTRICT_VIEW) ||
741                                 (G.rendering && dob->ob->restrictflag & OB_RESTRICT_RENDER)
742                         ) {
743                                 dob->no_draw= 1;
744                         }
745                         else {
746                                 dob->no_draw= 0;
747                         }
748
749                         if(go->ob->transflag & OB_DUPLI) {
750                                 copy_m4_m4(dob->ob->obmat, dob->mat);
751                                 object_duplilist_recursive(&group->id, scene, go->ob, lb, ob->obmat, level+1, animated);
752                                 copy_m4_m4(dob->ob->obmat, dob->omat);
753                         }
754                 }
755         }
756 }
757
758 static void frames_duplilist(ListBase *lb, Scene *scene, Object *ob, int level, int animated)
759 {
760         extern int enable_cu_speed;     /* object.c */
761         Object copyob = {{NULL}};
762         int cfrao = scene->r.cfra;
763         int dupend = ob->dupend;
764         
765         /* simple prevention of too deep nested groups */
766         if (level > MAX_DUPLI_RECUR) return;
767         
768         /* if we don't have any data/settings which will lead to object movement,
769          * don't waste time trying, as it will all look the same...
770          */
771         if (ob->parent==NULL && ob->constraints.first==NULL && ob->adt==NULL) 
772                 return;
773         
774         /* make a copy of the object's original data (before any dupli-data overwrites it) 
775          * as we'll need this to keep track of unkeyed data
776          *      - this doesn't take into account other data that can be reached from the object,
777          *        for example it's shapekeys or bones, hence the need for an update flush at the end
778          */
779         copyob = *ob;
780         
781         /* duplicate over the required range */
782         if (ob->transflag & OB_DUPLINOSPEED) enable_cu_speed= 0;
783         
784         for (scene->r.cfra= ob->dupsta; scene->r.cfra<=dupend; scene->r.cfra++) {
785                 short ok= 1;
786                 
787                 /* - dupoff = how often a frames within the range shouldn't be made into duplis
788                  * - dupon = the length of each "skipping" block in frames
789                  */
790                 if (ob->dupoff) {
791                         ok= scene->r.cfra - ob->dupsta;
792                         ok= ok % (ob->dupon+ob->dupoff);
793                         ok= (ok < ob->dupon);
794                 }
795                 
796                 if (ok) {       
797                         DupliObject *dob;
798                         
799                         /* WARNING: doing animation updates in this way is not terribly accurate, as the dependencies
800                          * and/or other objects which may affect this object's transforms are not updated either.
801                          * However, this has always been the way that this worked (i.e. pre 2.5), so I guess that it'll be fine!
802                          */
803                         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 */
804                         where_is_object_time(scene, ob, (float)scene->r.cfra);
805                         
806                         dob= new_dupli_object(lb, ob, ob->obmat, ob->lay, scene->r.cfra, OB_DUPLIFRAMES, animated);
807                         copy_m4_m4(dob->omat, copyob.obmat);
808                 }
809         }
810
811         enable_cu_speed= 1;
812         
813         /* reset frame to original frame, then re-evaluate animation as above 
814          * as 2.5 animation data may have far-reaching consequences
815          */
816         scene->r.cfra= cfrao;
817         
818         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 */
819         where_is_object_time(scene, ob, (float)scene->r.cfra);
820         
821         /* but, to make sure unkeyed object transforms are still sane, 
822          * let's copy object's original data back over
823          */
824         *ob = copyob;
825 }
826
827 typedef struct vertexDupliData {
828         ID *id; /* scene or group, for recursive loops */
829         int level;
830         int animated;
831         ListBase *lb;
832         float pmat[4][4];
833         float obmat[4][4]; /* Only used for dupliverts inside dupligroups, where the ob->obmat is modified */
834         Scene *scene;
835         Object *ob, *par;
836         float (*orco)[3];
837 } vertexDupliData;
838
839 /* ------------- */
840
841 static void vertex_dupli__mapFunc(void *userData, int index, float *co, float *no_f, short *no_s)
842 {
843         DupliObject *dob;
844         vertexDupliData *vdd= userData;
845         float vec[3], q2[4], mat[3][3], tmat[4][4], obmat[4][4];
846         int origlay;
847         
848         mul_v3_m4v3(vec, vdd->pmat, co);
849         sub_v3_v3(vec, vdd->pmat[3]);
850         add_v3_v3(vec, vdd->obmat[3]);
851         
852         copy_m4_m4(obmat, vdd->obmat);
853         copy_v3_v3(obmat[3], vec);
854         
855         if(vdd->par->transflag & OB_DUPLIROT) {
856                 if(no_f) {
857                         vec[0]= -no_f[0]; vec[1]= -no_f[1]; vec[2]= -no_f[2];
858                 }
859                 else if(no_s) {
860                         vec[0]= -no_s[0]; vec[1]= -no_s[1]; vec[2]= -no_s[2];
861                 }
862                 
863                 vec_to_quat( q2,vec, vdd->ob->trackflag, vdd->ob->upflag);
864                 
865                 quat_to_mat3( mat,q2);
866                 copy_m4_m4(tmat, obmat);
867                 mul_m4_m4m3(obmat, tmat, mat);
868         }
869
870         origlay = vdd->ob->lay;
871         
872         dob= new_dupli_object(vdd->lb, vdd->ob, obmat, vdd->par->lay, index, OB_DUPLIVERTS, vdd->animated);
873
874         /* restore the original layer so that each dupli will have proper dob->origlay */
875         vdd->ob->lay = origlay;
876
877         if(vdd->orco)
878                 copy_v3_v3(dob->orco, vdd->orco[index]);
879         
880         if(vdd->ob->transflag & OB_DUPLI) {
881                 float tmpmat[4][4];
882                 copy_m4_m4(tmpmat, vdd->ob->obmat);
883                 copy_m4_m4(vdd->ob->obmat, obmat); /* pretend we are really this mat */
884                 object_duplilist_recursive((ID *)vdd->id, vdd->scene, vdd->ob, vdd->lb, obmat, vdd->level+1, vdd->animated);
885                 copy_m4_m4(vdd->ob->obmat, tmpmat);
886         }
887 }
888
889 static void vertex_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], int level, int animated)
890 {
891         Object *ob, *ob_iter;
892         Mesh *me= par->data;
893         Base *base = NULL;
894         DerivedMesh *dm;
895         vertexDupliData vdd;
896         Scene *sce = NULL;
897         Group *group = NULL;
898         GroupObject * go = NULL;
899         BMEditMesh *em;
900         float vec[3], no[3], pmat[4][4];
901         int totvert, a, oblay;
902         unsigned int lay;
903         
904         copy_m4_m4(pmat, par->obmat);
905         
906         /* simple preventing of too deep nested groups */
907         if(level>MAX_DUPLI_RECUR) return;
908         
909         em = me->edit_btmesh;
910         
911         if(em) {
912                 dm= editbmesh_get_derived_cage(scene, par, em, CD_MASK_BAREMESH);
913         } else
914                 dm= mesh_get_derived_deform(scene, par, CD_MASK_BAREMESH);
915         
916         if(G.rendering) {
917                 vdd.orco= (float(*)[3])get_mesh_orco_verts(par);
918                 transform_mesh_orco_verts(me, vdd.orco, me->totvert, 0);
919         }
920         else
921                 vdd.orco= NULL;
922         
923         totvert = dm->getNumVerts(dm);
924
925         /* having to loop on scene OR group objects is NOT FUN */
926         if (GS(id->name) == ID_SCE) {
927                 sce = (Scene *)id;
928                 lay= sce->lay;
929                 base= sce->base.first;
930         } else {
931                 group = (Group *)id;
932                 lay= group->layer;
933                 go = group->gobject.first;
934         }
935         
936         /* Start looping on Scene OR Group objects */
937         while (base || go) { 
938                 if (sce) {
939                         ob_iter= base->object;
940                         oblay = base->lay;
941                 } else {
942                         ob_iter= go->ob;
943                         oblay = ob_iter->lay;
944                 }
945                 
946                 if (lay & oblay && scene->obedit!=ob_iter) {
947                         ob=ob_iter->parent;
948                         while(ob) {
949                                 if(ob==par) {
950                                         ob = ob_iter;
951         /* End Scene/Group object loop, below is generic */
952                                         
953                                         
954                                         /* par_space_mat - only used for groups so we can modify the space dupli's are in
955                                            when par_space_mat is NULL ob->obmat can be used instead of ob__obmat
956                                         */
957                                         if(par_space_mat)
958                                                 mul_m4_m4m4(vdd.obmat, ob->obmat, par_space_mat);
959                                         else
960                                                 copy_m4_m4(vdd.obmat, ob->obmat);
961
962                                         vdd.id= id;
963                                         vdd.level= level;
964                                         vdd.animated= animated;
965                                         vdd.lb= lb;
966                                         vdd.ob= ob;
967                                         vdd.scene= scene;
968                                         vdd.par= par;
969                                         copy_m4_m4(vdd.pmat, pmat);
970                                         
971                                         /* mballs have a different dupli handling */
972                                         if(ob->type!=OB_MBALL) ob->flag |= OB_DONE;     /* doesnt render */
973
974                                         if(me->edit_btmesh) {
975                                                 dm->foreachMappedVert(dm, vertex_dupli__mapFunc, (void*) &vdd);
976                                         }
977                                         else {
978                                                 for(a=0; a<totvert; a++) {
979                                                         dm->getVertCo(dm, a, vec);
980                                                         dm->getVertNo(dm, a, no);
981                                                         
982                                                         vertex_dupli__mapFunc(&vdd, a, vec, no, NULL);
983                                                 }
984                                         }
985                                         if(sce) {
986                                                 /* Set proper layer in case of scene looping,
987                                                  * in case of groups the object layer will be
988                                                  * changed when it's duplicated due to the
989                                                  * group duplication.
990                                                  */
991                                                 ob->lay = vdd.par->lay;
992                                         }
993                                         
994                                         break;
995                                 }
996                                 ob= ob->parent;
997                         }
998                 }
999                 if (sce)        base= base->next;       /* scene loop */
1000                 else            go= go->next;           /* group loop */
1001         }
1002
1003         if(vdd.orco)
1004                 MEM_freeN(vdd.orco);
1005         dm->release(dm);
1006 }
1007
1008 static void face_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], int level, int animated)
1009 {
1010         Object *ob, *ob_iter;
1011         Base *base = NULL;
1012         DupliObject *dob;
1013         DerivedMesh *dm;
1014         Mesh *me= par->data;
1015         MLoopUV *mloopuv;
1016         MPoly *mpoly, *mp;
1017         MLoop *mloop;
1018         MVert *mvert;
1019         float pmat[4][4], imat[3][3], (*orco)[3] = NULL, w;
1020         int lay, oblay, totface, a;
1021         Scene *sce = NULL;
1022         Group *group = NULL;
1023         GroupObject *go = NULL;
1024         BMEditMesh *em;
1025         float ob__obmat[4][4]; /* needed for groups where the object matrix needs to be modified */
1026         
1027         /* simple preventing of too deep nested groups */
1028         if(level>MAX_DUPLI_RECUR) return;
1029         
1030         copy_m4_m4(pmat, par->obmat);
1031         em = me->edit_btmesh;
1032
1033         if(em) {
1034                 dm= editbmesh_get_derived_cage(scene, par, em, CD_MASK_BAREMESH);
1035         }
1036         else {
1037                 dm = mesh_get_derived_deform(scene, par, CD_MASK_BAREMESH);
1038         }
1039
1040         totface= dm->getNumFaces(dm);
1041         mpoly= dm->getPolyArray(dm);
1042         mloop= dm->getLoopArray(dm);
1043         mvert= dm->getVertArray(dm);
1044
1045         if(G.rendering) {
1046
1047                 orco= (float(*)[3])get_mesh_orco_verts(par);
1048                 transform_mesh_orco_verts(me, orco, me->totvert, 0);
1049                 mloopuv= me->mloopuv;
1050         }
1051         else {
1052                 orco= NULL;
1053                 mloopuv= NULL;
1054         }
1055         
1056         /* having to loop on scene OR group objects is NOT FUN */
1057         if (GS(id->name) == ID_SCE) {
1058                 sce = (Scene *)id;
1059                 lay= sce->lay;
1060                 base= sce->base.first;
1061         } else {
1062                 group = (Group *)id;
1063                 lay= group->layer;
1064                 go = group->gobject.first;
1065         }
1066         
1067         /* Start looping on Scene OR Group objects */
1068         while (base || go) { 
1069                 if (sce) {
1070                         ob_iter= base->object;
1071                         oblay = base->lay;
1072                 } else {
1073                         ob_iter= go->ob;
1074                         oblay = ob_iter->lay;
1075                 }
1076                 
1077                 if (lay & oblay && scene->obedit!=ob_iter) {
1078                         ob=ob_iter->parent;
1079                         while(ob) {
1080                                 if(ob==par) {
1081                                         ob = ob_iter;
1082         /* End Scene/Group object loop, below is generic */
1083                                         
1084                                         /* par_space_mat - only used for groups so we can modify the space dupli's are in
1085                                            when par_space_mat is NULL ob->obmat can be used instead of ob__obmat
1086                                         */
1087                                         if(par_space_mat)
1088                                                 mul_m4_m4m4(ob__obmat, ob->obmat, par_space_mat);
1089                                         else
1090                                                 copy_m4_m4(ob__obmat, ob->obmat);
1091                                         
1092                                         copy_m3_m4(imat, ob->parentinv);
1093                                                 
1094                                         /* mballs have a different dupli handling */
1095                                         if(ob->type!=OB_MBALL) ob->flag |= OB_DONE;     /* doesnt render */
1096
1097                                         for(a=0, mp= mpoly; a<totface; a++, mp++) {
1098                                                 int mv1;
1099                                                 int mv2;
1100                                                 int mv3;
1101                                                 /* int mv4; */ /* UNUSED */
1102                                                 float *v1;
1103                                                 float *v2;
1104                                                 float *v3;
1105                                                 /* float *v4; */ /* UNUSED */
1106                                                 float cent[3], quat[4], mat[3][3], mat3[3][3], tmat[4][4], obmat[4][4];
1107                                                 MLoop *loopstart= mloop + mp->loopstart;
1108
1109                                                 if (mp->totloop < 3) {
1110                                                         /* highly unlikely but to be safe */
1111                                                         continue;
1112                                                 }
1113                                                 else {
1114                                                         v1= mvert[(mv1= loopstart[0].v)].co;
1115                                                         v2= mvert[(mv2= loopstart[1].v)].co;
1116                                                         v3= mvert[(mv3= loopstart[2].v)].co;
1117                                                         /*
1118                                                         if (mp->totloop > 3) {
1119                                                                 v4= mvert[(mv4= loopstart[3].v)].co;
1120                                                         }
1121                                                         */
1122                                                 }
1123
1124                                                 /* translation */
1125                                                 mesh_calc_poly_center(mp, loopstart, mvert, cent);
1126
1127                                                 mul_m4_v3(pmat, cent);
1128                                                 
1129                                                 sub_v3_v3v3(cent, cent, pmat[3]);
1130                                                 add_v3_v3(cent, ob__obmat[3]);
1131                                                 
1132                                                 copy_m4_m4(obmat, ob__obmat);
1133                                                 
1134                                                 copy_v3_v3(obmat[3], cent);
1135                                                 
1136                                                 /* rotation */
1137                                                 tri_to_quat( quat,v1, v2, v3);
1138                                                 quat_to_mat3( mat,quat);
1139                                                 
1140                                                 /* scale */
1141                                                 if(par->transflag & OB_DUPLIFACES_SCALE) {
1142                                                         float size= mesh_calc_poly_area(mp, loopstart, mvert, NULL);
1143                                                         size= sqrtf(size) * par->dupfacesca;
1144                                                         mul_m3_fl(mat, size);
1145                                                 }
1146                                                 
1147                                                 copy_m3_m3(mat3, mat);
1148                                                 mul_m3_m3m3(mat, imat, mat3);
1149                                                 
1150                                                 copy_m4_m4(tmat, obmat);
1151                                                 mul_m4_m4m3(obmat, tmat, mat);
1152                                                 
1153                                                 dob= new_dupli_object(lb, ob, obmat, par->lay, a, OB_DUPLIFACES, animated);
1154                                                 if(G.rendering) {
1155                                                         w= 1.0f / (float)mp->totloop;
1156
1157                                                         if(orco) {
1158                                                                 int j;
1159                                                                 for (j = 0; j < mpoly->totloop; j++) {
1160                                                                         madd_v3_v3fl(dob->orco, orco[loopstart[j].v], w);
1161                                                                 }
1162                                                         }
1163
1164                                                         if(mloopuv) {
1165                                                                 int j;
1166                                                                 for (j = 0; j < mpoly->totloop; j++) {
1167                                                                         madd_v2_v2fl(dob->orco, mloopuv[loopstart[j].v].uv, w);
1168                                                                 }
1169                                                         }
1170                                                 }
1171                                                 
1172                                                 if(ob->transflag & OB_DUPLI) {
1173                                                         float tmpmat[4][4];
1174                                                         copy_m4_m4(tmpmat, ob->obmat);
1175                                                         copy_m4_m4(ob->obmat, obmat); /* pretend we are really this mat */
1176                                                         object_duplilist_recursive((ID *)id, scene, ob, lb, ob->obmat, level+1, animated);
1177                                                         copy_m4_m4(ob->obmat, tmpmat);
1178                                                 }
1179                                         }
1180                                         
1181                                         break;
1182                                 }
1183                                 ob= ob->parent;
1184                         }
1185                 }
1186                 if (sce)        base= base->next;       /* scene loop */
1187                 else            go= go->next;           /* group loop */
1188         }
1189
1190         if(orco)
1191                 MEM_freeN(orco);
1192         
1193         dm->release(dm);
1194 }
1195
1196 static void new_particle_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], ParticleSystem *psys, int level, int animated)
1197 {
1198         GroupObject *go;
1199         Object *ob=NULL, **oblist=NULL, obcopy, *obcopylist=NULL;
1200         DupliObject *dob;
1201         ParticleDupliWeight *dw;
1202         ParticleSettings *part;
1203         ParticleData *pa;
1204         ChildParticle *cpa=NULL;
1205         ParticleKey state;
1206         ParticleCacheKey *cache;
1207         float ctime, pa_time, scale = 1.0f;
1208         float tmat[4][4], mat[4][4], pamat[4][4], vec[3], size=0.0;
1209         float (*obmat)[4], (*oldobmat)[4];
1210         int a, b, counter, hair = 0;
1211         int totpart, totchild, totgroup=0 /*, pa_num */;
1212
1213         int no_draw_flag = PARS_UNEXIST;
1214
1215         if(psys==NULL) return;
1216         
1217         /* simple preventing of too deep nested groups */
1218         if(level>MAX_DUPLI_RECUR) return;
1219         
1220         part=psys->part;
1221
1222         if(part==NULL)
1223                 return;
1224
1225         if(!psys_check_enabled(par, psys))
1226                 return;
1227
1228         if(G.rendering == 0)
1229                 no_draw_flag |= PARS_NO_DISP;
1230         
1231         ctime = BKE_curframe(scene); /* NOTE: in old animsys, used parent object's timeoffset... */
1232
1233         totpart = psys->totpart;
1234         totchild = psys->totchild;
1235
1236         BLI_srandom(31415926 + psys->seed);
1237
1238         if((psys->renderdata || part->draw_as==PART_DRAW_REND) && ELEM(part->ren_as, PART_DRAW_OB, PART_DRAW_GR)) {
1239                 ParticleSimulationData sim= {NULL};
1240                 sim.scene= scene;
1241                 sim.ob= par;
1242                 sim.psys= psys;
1243                 sim.psmd= psys_get_modifier(par, psys);
1244                 /* make sure emitter imat is in global coordinates instead of render view coordinates */
1245                 invert_m4_m4(par->imat, par->obmat);
1246
1247                 /* first check for loops (particle system object used as dupli object) */
1248                 if(part->ren_as == PART_DRAW_OB) {
1249                         if(ELEM(part->dup_ob, NULL, par))
1250                                 return;
1251                 }
1252                 else { /*PART_DRAW_GR */
1253                         if(part->dup_group == NULL || part->dup_group->gobject.first == NULL)
1254                                 return;
1255
1256                         for(go=part->dup_group->gobject.first; go; go=go->next)
1257                                 if(go->ob == par)
1258                                         return;
1259                 }
1260
1261                 /* if we have a hair particle system, use the path cache */
1262                 if(part->type == PART_HAIR) {
1263                         if(psys->flag & PSYS_HAIR_DONE)
1264                                 hair= (totchild == 0 || psys->childcache) && psys->pathcache;
1265                         if(!hair)
1266                                 return;
1267                         
1268                         /* we use cache, update totchild according to cached data */
1269                         totchild = psys->totchildcache;
1270                         totpart = psys->totcached;
1271                 }
1272
1273                 psys_check_group_weights(part);
1274
1275                 psys->lattice = psys_get_lattice(&sim);
1276
1277                 /* gather list of objects or single object */
1278                 if(part->ren_as==PART_DRAW_GR) {
1279                         group_handle_recalc_and_update(scene, par, part->dup_group);
1280
1281                         if(part->draw & PART_DRAW_COUNT_GR) {
1282                                 for(dw=part->dupliweights.first; dw; dw=dw->next)
1283                                         totgroup += dw->count;
1284                         }
1285                         else {
1286                                 for(go=part->dup_group->gobject.first; go; go=go->next)
1287                                         totgroup++;
1288                         }
1289
1290                         /* we also copy the actual objects to restore afterwards, since
1291                          * where_is_object_time will change the object which breaks transform */
1292                         oblist = MEM_callocN(totgroup*sizeof(Object *), "dupgroup object list");
1293                         obcopylist = MEM_callocN(totgroup*sizeof(Object), "dupgroup copy list");
1294
1295                         
1296                         if(part->draw & PART_DRAW_COUNT_GR && totgroup) {
1297                                 dw = part->dupliweights.first;
1298
1299                                 for(a=0; a<totgroup; dw=dw->next) {
1300                                         for(b=0; b<dw->count; b++, a++) {
1301                                                 oblist[a] = dw->ob;
1302                                                 obcopylist[a] = *dw->ob;
1303                                         }
1304                                 }
1305                         }
1306                         else {
1307                                 go = part->dup_group->gobject.first;
1308                                 for(a=0; a<totgroup; a++, go=go->next) {
1309                                         oblist[a] = go->ob;
1310                                         obcopylist[a] = *go->ob;
1311                                 }
1312                         }
1313                 }
1314                 else {
1315                         ob = part->dup_ob;
1316                         obcopy = *ob;
1317                 }
1318
1319                 if(totchild==0 || part->draw & PART_DRAW_PARENT)
1320                         a = 0;
1321                 else
1322                         a = totpart;
1323
1324                 for(pa=psys->particles,counter=0; a<totpart+totchild; a++,pa++,counter++) {
1325                         if(a<totpart) {
1326                                 /* handle parent particle */
1327                                 if(pa->flag & no_draw_flag)
1328                                         continue;
1329
1330                                 /* pa_num = pa->num; */ /* UNUSED */
1331                                 pa_time = pa->time;
1332                                 size = pa->size;
1333                         }
1334                         else {
1335                                 /* handle child particle */
1336                                 cpa = &psys->child[a - totpart];
1337
1338                                 /* pa_num = a; */ /* UNUSED */
1339                                 pa_time = psys->particles[cpa->parent].time;
1340                                 size = psys_get_child_size(psys, cpa, ctime, NULL);
1341                         }
1342
1343                         /* some hair paths might be non-existent so they can't be used for duplication */
1344                         if(hair &&
1345                                 ((a < totpart && psys->pathcache[a]->steps < 0) ||
1346                                 (a >= totpart && psys->childcache[a-totpart]->steps < 0)))
1347                                 continue;
1348
1349                         if(part->ren_as==PART_DRAW_GR) {
1350                                 /* prevent divide by zero below [#28336] */
1351                                 if(totgroup == 0)
1352                                         continue;
1353
1354                                 /* for groups, pick the object based on settings */
1355                                 if(part->draw&PART_DRAW_RAND_GR)
1356                                         b= BLI_rand() % totgroup;
1357                                 else
1358                                         b= a % totgroup;
1359
1360                                 ob = oblist[b];
1361                                 obmat = oblist[b]->obmat;
1362                                 oldobmat = obcopylist[b].obmat;
1363                         }
1364                         else {
1365                                 obmat= ob->obmat;
1366                                 oldobmat= obcopy.obmat;
1367                         }
1368
1369                         if(hair) {
1370                                 /* hair we handle separate and compute transform based on hair keys */
1371                                 if(a < totpart) {
1372                                         cache = psys->pathcache[a];
1373                                         psys_get_dupli_path_transform(&sim, pa, NULL, cache, pamat, &scale);
1374                                 }
1375                                 else {
1376                                         cache = psys->childcache[a-totpart];
1377                                         psys_get_dupli_path_transform(&sim, NULL, cpa, cache, pamat, &scale);
1378                                 }
1379
1380                                 copy_v3_v3(pamat[3], cache->co);
1381                                 pamat[3][3]= 1.0f;
1382                                 
1383                         }
1384                         else {
1385                                 /* first key */
1386                                 state.time = ctime;
1387                                 if(psys_get_particle_state(&sim, a, &state, 0) == 0) {
1388                                         continue;
1389                                 }
1390                                 else {
1391                                         float tquat[4];
1392                                         normalize_qt_qt(tquat, state.rot);
1393                                         quat_to_mat4(pamat, tquat);
1394                                         copy_v3_v3(pamat[3], state.co);
1395                                         pamat[3][3]= 1.0f;
1396                                 }
1397                         }
1398
1399                         if(part->ren_as==PART_DRAW_GR && psys->part->draw & PART_DRAW_WHOLE_GR) {
1400                                 for(go= part->dup_group->gobject.first, b=0; go; go= go->next, b++) {
1401
1402                                         /* group dupli offset, should apply after everything else */
1403                                         if(!is_zero_v3(part->dup_group->dupli_ofs)) {
1404                                                 copy_m4_m4(tmat, oblist[b]->obmat);
1405                                                 sub_v3_v3v3(tmat[3], tmat[3], part->dup_group->dupli_ofs);
1406                                                 mul_m4_m4m4(tmat, tmat, pamat);
1407                                         }
1408                                         else {
1409                                                 mul_m4_m4m4(tmat, oblist[b]->obmat, pamat);
1410                                         }
1411
1412                                         mul_mat3_m4_fl(tmat, size*scale);
1413                                         if(par_space_mat)
1414                                                 mul_m4_m4m4(mat, tmat, par_space_mat);
1415                                         else
1416                                                 copy_m4_m4(mat, tmat);
1417
1418                                         dob= new_dupli_object(lb, go->ob, mat, par->lay, counter, OB_DUPLIPARTS, animated);
1419                                         copy_m4_m4(dob->omat, obcopylist[b].obmat);
1420                                         if(G.rendering)
1421                                                 psys_get_dupli_texture(psys, part, sim.psmd, pa, cpa, dob->uv, dob->orco);
1422                                 }
1423                         }
1424                         else {
1425                                 /* to give ipos in object correct offset */
1426                                 where_is_object_time(scene, ob, ctime-pa_time);
1427
1428                                 copy_v3_v3(vec, obmat[3]);
1429                                 obmat[3][0] = obmat[3][1] = obmat[3][2] = 0.0f;
1430
1431                                 /* particle rotation uses x-axis as the aligned axis, so pre-rotate the object accordingly */
1432                                 if((part->draw & PART_DRAW_ROTATE_OB) == 0) {
1433                                         float xvec[3], q[4];
1434                                         xvec[0] = -1.f;
1435                                         xvec[1] = xvec[2] = 0;
1436                                         vec_to_quat(q, xvec, ob->trackflag, ob->upflag);
1437                                         quat_to_mat4(obmat, q);
1438                                         obmat[3][3]= 1.0f;
1439                                 }
1440                                 
1441                                 /* Normal particles and cached hair live in global space so we need to
1442                                  * remove the real emitter's transformation before 2nd order duplication.
1443                                  */
1444                                 if(par_space_mat && GS(id->name) != ID_GR)
1445                                         mul_m4_m4m4(mat, pamat, psys->imat);
1446                                 else
1447                                         copy_m4_m4(mat, pamat);
1448
1449                                 mul_m4_m4m4(tmat, obmat, mat);
1450                                 mul_mat3_m4_fl(tmat, size*scale);
1451
1452                                 if(par_space_mat)
1453                                         mul_m4_m4m4(mat, tmat, par_space_mat);
1454                                 else
1455                                         copy_m4_m4(mat, tmat);
1456
1457                                 if(part->draw & PART_DRAW_GLOBAL_OB)
1458                                         add_v3_v3v3(mat[3], mat[3], vec);
1459
1460                                 dob= new_dupli_object(lb, ob, mat, ob->lay, counter, GS(id->name) == ID_GR ? OB_DUPLIGROUP : OB_DUPLIPARTS, animated);
1461                                 copy_m4_m4(dob->omat, oldobmat);
1462                                 if(G.rendering)
1463                                         psys_get_dupli_texture(psys, part, sim.psmd, pa, cpa, dob->uv, dob->orco);
1464                         }
1465                 }
1466
1467                 /* restore objects since they were changed in where_is_object_time */
1468                 if(part->ren_as==PART_DRAW_GR) {
1469                         for(a=0; a<totgroup; a++)
1470                                 *(oblist[a])= obcopylist[a];
1471                 }
1472                 else
1473                         *ob= obcopy;
1474         }
1475
1476         /* clean up */
1477         if(oblist)
1478                 MEM_freeN(oblist);
1479         if(obcopylist)
1480                 MEM_freeN(obcopylist);
1481
1482         if(psys->lattice) {
1483                 end_latt_deform(psys->lattice);
1484                 psys->lattice = NULL;
1485         }
1486 }
1487
1488 static Object *find_family_object(Object **obar, char *family, char ch)
1489 {
1490         Object *ob;
1491         int flen;
1492         
1493         if( obar[(int)ch] ) return obar[(int)ch];
1494         
1495         flen= strlen(family);
1496         
1497         ob= G.main->object.first;
1498         while(ob) {
1499                 if( ob->id.name[flen+2]==ch ) {
1500                         if( strncmp(ob->id.name+2, family, flen)==0 ) break;
1501                 }
1502                 ob= ob->id.next;
1503         }
1504         
1505         obar[(int)ch]= ob;
1506         
1507         return ob;
1508 }
1509
1510
1511 static void font_duplilist(ListBase *lb, Scene *scene, Object *par, int level, int animated)
1512 {
1513         Object *ob, *obar[256]= {NULL};
1514         Curve *cu;
1515         struct chartrans *ct, *chartransdata;
1516         float vec[3], obmat[4][4], pmat[4][4], fsize, xof, yof;
1517         int slen, a;
1518         
1519         /* simple preventing of too deep nested groups */
1520         if(level>MAX_DUPLI_RECUR) return;
1521         
1522         copy_m4_m4(pmat, par->obmat);
1523         
1524         /* in par the family name is stored, use this to find the other objects */
1525         
1526         chartransdata= BKE_text_to_curve(G.main, scene, par, FO_DUPLI);
1527         if(chartransdata==NULL) return;
1528
1529         cu= par->data;
1530         slen= strlen(cu->str);
1531         fsize= cu->fsize;
1532         xof= cu->xof;
1533         yof= cu->yof;
1534         
1535         ct= chartransdata;
1536         
1537         for(a=0; a<slen; a++, ct++) {
1538                 
1539                 ob= find_family_object(obar, cu->family, cu->str[a]);
1540                 if(ob) {
1541                         vec[0]= fsize*(ct->xof - xof);
1542                         vec[1]= fsize*(ct->yof - yof);
1543                         vec[2]= 0.0;
1544                         
1545                         mul_m4_v3(pmat, vec);
1546                         
1547                         copy_m4_m4(obmat, par->obmat);
1548                         copy_v3_v3(obmat[3], vec);
1549                         
1550                         new_dupli_object(lb, ob, obmat, par->lay, a, OB_DUPLIVERTS, animated);
1551                 }
1552         }
1553         
1554         MEM_freeN(chartransdata);
1555 }
1556
1557 /* ------------- */
1558
1559 static void object_duplilist_recursive(ID *id, Scene *scene, Object *ob, ListBase *duplilist, float par_space_mat[][4], int level, int animated)
1560 {       
1561         if((ob->transflag & OB_DUPLI)==0)
1562                 return;
1563         
1564         /* Should the dupli's be generated for this object? - Respect restrict flags */
1565         if (G.rendering) {
1566                 if (ob->restrictflag & OB_RESTRICT_RENDER) {
1567                         return;
1568                 }
1569         } else {
1570                 if (ob->restrictflag & OB_RESTRICT_VIEW) {
1571                         return;
1572                 }
1573         }
1574
1575         if(ob->transflag & OB_DUPLIPARTS) {
1576                 ParticleSystem *psys = ob->particlesystem.first;
1577                 for(; psys; psys=psys->next)
1578                         new_particle_duplilist(duplilist, id, scene, ob, par_space_mat, psys, level+1, animated);
1579         }
1580         else if(ob->transflag & OB_DUPLIVERTS) {
1581                 if(ob->type==OB_MESH) {
1582                         vertex_duplilist(duplilist, id, scene, ob, par_space_mat, level+1, animated);
1583                 }
1584                 else if(ob->type==OB_FONT) {
1585                         if (GS(id->name)==ID_SCE) { /* TODO - support dupligroups */
1586                                 font_duplilist(duplilist, scene, ob, level+1, animated);
1587                         }
1588                 }
1589         }
1590         else if(ob->transflag & OB_DUPLIFACES) {
1591                 if(ob->type==OB_MESH)
1592                         face_duplilist(duplilist, id, scene, ob, par_space_mat, level+1, animated);
1593         }
1594         else if(ob->transflag & OB_DUPLIFRAMES) {
1595                 if (GS(id->name)==ID_SCE) { /* TODO - support dupligroups */
1596                         frames_duplilist(duplilist, scene, ob, level+1, animated);
1597                 }
1598         } else if(ob->transflag & OB_DUPLIGROUP) {
1599                 DupliObject *dob;
1600                 
1601                 group_duplilist(duplilist, scene, ob, level+1, animated); /* now recursive */
1602
1603                 if (level==0) {
1604                         for(dob= duplilist->first; dob; dob= dob->next)
1605                                 if(dob->type == OB_DUPLIGROUP)
1606                                         copy_m4_m4(dob->ob->obmat, dob->mat);
1607                 }
1608         }
1609 }
1610
1611 /* Returns a list of DupliObject
1612  * note; group dupli's already set transform matrix. see note in group_duplilist() */
1613 ListBase *object_duplilist(Scene *sce, Object *ob)
1614 {
1615         ListBase *duplilist= MEM_mallocN(sizeof(ListBase), "duplilist");
1616         duplilist->first= duplilist->last= NULL;
1617         object_duplilist_recursive((ID *)sce, sce, ob, duplilist, NULL, 0, 0);
1618         return duplilist;
1619 }
1620
1621 void free_object_duplilist(ListBase *lb)
1622 {
1623         DupliObject *dob;
1624         
1625         /* loop in reverse order, if object is instanced multiple times
1626            the original layer may not really be original otherwise, proper
1627            solution is more complicated */
1628         for(dob= lb->last; dob; dob= dob->prev) {
1629                 dob->ob->lay= dob->origlay;
1630                 copy_m4_m4(dob->ob->obmat, dob->omat);
1631         }
1632         
1633         BLI_freelistN(lb);
1634         MEM_freeN(lb);
1635 }
1636
1637 int count_duplilist(Object *ob)
1638 {
1639         if(ob->transflag & OB_DUPLI) {
1640                 if(ob->transflag & OB_DUPLIVERTS) {
1641                         if(ob->type==OB_MESH) {
1642                                 if(ob->transflag & OB_DUPLIVERTS) {
1643                                         ParticleSystem *psys = ob->particlesystem.first;
1644                                         int pdup=0;
1645
1646                                         for(; psys; psys=psys->next)
1647                                                 pdup += psys->totpart;
1648
1649                                         if(pdup==0){
1650                                                 Mesh *me= ob->data;
1651                                                 return me->totvert;
1652                                         }
1653                                         else
1654                                                 return pdup;
1655                                 }
1656                         }
1657                 }
1658                 else if(ob->transflag & OB_DUPLIFRAMES) {
1659                         int tot= ob->dupend - ob->dupsta; 
1660                         tot/= (ob->dupon+ob->dupoff);
1661                         return tot*ob->dupon;
1662                 }
1663         }
1664         return 1;
1665 }