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