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