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