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