Merging r39102 through r39120 from trunk into soc-2011-tomato
[blender.git] / source / blender / blenkernel / intern / object.c
1 /* object.c
2  *
3  * 
4  * $Id$
5  *
6  * ***** BEGIN GPL LICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21  *
22  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 /** \file blender/blenkernel/intern/object.c
33  *  \ingroup bke
34  */
35
36
37 #include <string.h>
38 #include <math.h>
39 #include <stdio.h>                      
40
41 #include "MEM_guardedalloc.h"
42
43 #include "DNA_anim_types.h"
44 #include "DNA_armature_types.h"
45 #include "DNA_camera_types.h"
46 #include "DNA_constraint_types.h"
47 #include "DNA_group_types.h"
48 #include "DNA_key_types.h"
49 #include "DNA_lamp_types.h"
50 #include "DNA_lattice_types.h"
51 #include "DNA_material_types.h"
52 #include "DNA_meta_types.h"
53 #include "DNA_meshdata_types.h"
54 #include "DNA_scene_types.h"
55 #include "DNA_screen_types.h"
56 #include "DNA_sequence_types.h"
57 #include "DNA_space_types.h"
58 #include "DNA_view3d_types.h"
59 #include "DNA_world_types.h"
60
61 #include "BLI_blenlib.h"
62 #include "BLI_editVert.h"
63 #include "BLI_math.h"
64 #include "BLI_pbvh.h"
65 #include "BLI_utildefines.h"
66
67 #include "BKE_main.h"
68 #include "BKE_global.h"
69 #include "BKE_idprop.h"
70 #include "BKE_armature.h"
71 #include "BKE_action.h"
72 #include "BKE_bullet.h"
73 #include "BKE_colortools.h"
74 #include "BKE_deform.h"
75 #include "BKE_DerivedMesh.h"
76 #include "BKE_animsys.h"
77 #include "BKE_anim.h"
78 #include "BKE_constraint.h"
79 #include "BKE_curve.h"
80 #include "BKE_displist.h"
81 #include "BKE_effect.h"
82 #include "BKE_fcurve.h"
83 #include "BKE_group.h"
84 #include "BKE_icons.h"
85 #include "BKE_key.h"
86 #include "BKE_lattice.h"
87 #include "BKE_library.h"
88 #include "BKE_mesh.h"
89 #include "BKE_mball.h"
90 #include "BKE_modifier.h"
91 #include "BKE_object.h"
92 #include "BKE_paint.h"
93 #include "BKE_particle.h"
94 #include "BKE_pointcache.h"
95 #include "BKE_property.h"
96 #include "BKE_sca.h"
97 #include "BKE_scene.h"
98 #include "BKE_sequencer.h"
99 #include "BKE_softbody.h"
100 #include "BKE_material.h"
101
102 #include "LBM_fluidsim.h"
103
104 #ifdef WITH_PYTHON
105 #include "BPY_extern.h"
106 #endif
107
108 #include "GPU_material.h"
109
110 /* Local function protos */
111 static void solve_parenting (Scene *scene, Object *ob, Object *par, float obmat[][4], float slowmat[][4], int simul);
112
113 float originmat[3][3];  /* after where_is_object(), can be used in other functions (bad!) */
114
115 void clear_workob(Object *workob)
116 {
117         memset(workob, 0, sizeof(Object));
118         
119         workob->size[0]= workob->size[1]= workob->size[2]= 1.0f;
120         workob->rotmode= ROT_MODE_EUL;
121 }
122
123 void copy_baseflags(struct Scene *scene)
124 {
125         Base *base= scene->base.first;
126         
127         while(base) {
128                 base->object->flag= base->flag;
129                 base= base->next;
130         }
131 }
132
133 void copy_objectflags(struct Scene *scene)
134 {
135         Base *base= scene->base.first;
136         
137         while(base) {
138                 base->flag= base->object->flag;
139                 base= base->next;
140         }
141 }
142
143 void update_base_layer(struct Scene *scene, Object *ob)
144 {
145         Base *base= scene->base.first;
146
147         while (base) {
148                 if (base->object == ob) base->lay= ob->lay;
149                 base= base->next;
150         }
151 }
152
153 void object_free_particlesystems(Object *ob)
154 {
155         while(ob->particlesystem.first){
156                 ParticleSystem *psys = ob->particlesystem.first;
157                 
158                 BLI_remlink(&ob->particlesystem,psys);
159                 
160                 psys_free(ob,psys);
161         }
162 }
163
164 void object_free_softbody(Object *ob)
165 {
166         if(ob->soft) {
167                 sbFree(ob->soft);
168                 ob->soft= NULL;
169         }
170 }
171
172 void object_free_bulletsoftbody(Object *ob)
173 {
174         if(ob->bsoft) {
175                 bsbFree(ob->bsoft);
176                 ob->bsoft= NULL;
177         }
178 }
179
180 void object_free_modifiers(Object *ob)
181 {
182         while (ob->modifiers.first) {
183                 ModifierData *md = ob->modifiers.first;
184                 
185                 BLI_remlink(&ob->modifiers, md);
186                 
187                 modifier_free(md);
188         }
189
190         /* particle modifiers were freed, so free the particlesystems as well */
191         object_free_particlesystems(ob);
192
193         /* same for softbody */
194         object_free_softbody(ob);
195 }
196
197 void object_link_modifiers(struct Object *ob, struct Object *from)
198 {
199         ModifierData *md;
200         object_free_modifiers(ob);
201
202         for (md=from->modifiers.first; md; md=md->next) {
203                 ModifierData *nmd = NULL;
204
205                 if(ELEM4(md->type, eModifierType_Hook, eModifierType_Softbody, eModifierType_ParticleInstance, eModifierType_Collision)) continue;
206
207                 nmd = modifier_new(md->type);
208                 modifier_copyData(md, nmd);
209                 BLI_addtail(&ob->modifiers, nmd);
210         }
211
212         copy_object_particlesystems(ob, from);
213         copy_object_softbody(ob, from);
214
215         // TODO: smoke?, cloth?
216 }
217
218 /* here we will collect all local displist stuff */
219 /* also (ab)used in depsgraph */
220 void object_free_display(Object *ob)
221 {
222         if(ob->derivedDeform) {
223                 ob->derivedDeform->needsFree = 1;
224                 ob->derivedDeform->release(ob->derivedDeform);
225                 ob->derivedDeform= NULL;
226         }
227         if(ob->derivedFinal) {
228                 ob->derivedFinal->needsFree = 1;
229                 ob->derivedFinal->release(ob->derivedFinal);
230                 ob->derivedFinal= NULL;
231         }
232         
233         freedisplist(&ob->disp);
234 }
235
236 void free_sculptsession(Object *ob)
237 {
238         if(ob && ob->sculpt) {
239                 SculptSession *ss = ob->sculpt;
240                 DerivedMesh *dm= ob->derivedFinal;
241
242                 if(ss->pbvh)
243                         BLI_pbvh_free(ss->pbvh);
244                 if(dm && dm->getPBVH)
245                         dm->getPBVH(NULL, dm); /* signal to clear */
246
247                 if(ss->texcache)
248                         MEM_freeN(ss->texcache);
249
250                 if(ss->layer_co)
251                         MEM_freeN(ss->layer_co);
252
253                 if(ss->orig_cos)
254                         MEM_freeN(ss->orig_cos);
255                 if(ss->deform_cos)
256                         MEM_freeN(ss->deform_cos);
257                 if(ss->deform_imats)
258                         MEM_freeN(ss->deform_imats);
259
260                 MEM_freeN(ss);
261
262                 ob->sculpt = NULL;
263         }
264 }
265
266 /* do not free object itself */
267 void free_object(Object *ob)
268 {
269         int a;
270         
271         object_free_display(ob);
272         
273         /* disconnect specific data */
274         if(ob->data) {
275                 ID *id= ob->data;
276                 id->us--;
277                 if(id->us==0) {
278                         if(ob->type==OB_MESH) unlink_mesh(ob->data);
279                         else if(ob->type==OB_CURVE) unlink_curve(ob->data);
280                         else if(ob->type==OB_MBALL) unlink_mball(ob->data);
281                 }
282                 ob->data= NULL;
283         }
284         
285         for(a=0; a<ob->totcol; a++) {
286                 if(ob->mat[a]) ob->mat[a]->id.us--;
287         }
288         if(ob->mat) MEM_freeN(ob->mat);
289         if(ob->matbits) MEM_freeN(ob->matbits);
290         ob->mat= NULL;
291         ob->matbits= NULL;
292         if(ob->bb) MEM_freeN(ob->bb); 
293         ob->bb= NULL;
294         if(ob->path) free_path(ob->path); 
295         ob->path= NULL;
296         if(ob->adt) BKE_free_animdata((ID *)ob);
297         if(ob->poselib) ob->poselib->id.us--;
298         if(ob->gpd) ((ID *)ob->gpd)->us--;
299         if(ob->defbase.first)
300                 BLI_freelistN(&ob->defbase);
301         if(ob->pose)
302                 free_pose(ob->pose);
303         if(ob->mpath)
304                 animviz_free_motionpath(ob->mpath);
305         free_properties(&ob->prop);
306         object_free_modifiers(ob);
307         
308         free_sensors(&ob->sensors);
309         free_controllers(&ob->controllers);
310         free_actuators(&ob->actuators);
311         
312         free_constraints(&ob->constraints);
313         
314         free_partdeflect(ob->pd);
315
316         if(ob->soft) sbFree(ob->soft);
317         if(ob->bsoft) bsbFree(ob->bsoft);
318         if(ob->gpulamp.first) GPU_lamp_free(ob);
319
320         free_sculptsession(ob);
321
322         if(ob->pc_ids.first) BLI_freelistN(&ob->pc_ids);
323 }
324
325 static void unlink_object__unlinkModifierLinks(void *userData, Object *ob, Object **obpoin)
326 {
327         Object *unlinkOb = userData;
328
329         if (*obpoin==unlinkOb) {
330                 *obpoin = NULL;
331                 ob->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME; // XXX: should this just be OB_RECALC_DATA?
332         }
333 }
334
335 void unlink_object(Object *ob)
336 {
337         Main *bmain= G.main;
338         Object *obt;
339         Material *mat;
340         World *wrld;
341         bScreen *sc;
342         Scene *sce;
343         Curve *cu;
344         Tex *tex;
345         Group *group;
346         Camera *camera;
347         bConstraint *con;
348         //bActionStrip *strip; // XXX animsys 
349         ModifierData *md;
350         ARegion *ar;
351         RegionView3D *rv3d;
352         int a, found;
353         
354         unlink_controllers(&ob->controllers);
355         unlink_actuators(&ob->actuators);
356         
357         /* check all objects: parents en bevels and fields, also from libraries */
358         // FIXME: need to check all animation blocks (drivers)
359         obt= bmain->object.first;
360         while(obt) {
361                 if(obt->proxy==ob)
362                         obt->proxy= NULL;
363                 if(obt->proxy_from==ob) {
364                         obt->proxy_from= NULL;
365                         obt->recalc |= OB_RECALC_OB;
366                 }
367                 if(obt->proxy_group==ob)
368                         obt->proxy_group= NULL;
369                 
370                 if(obt->parent==ob) {
371                         obt->parent= NULL;
372                         obt->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
373                 }
374                 
375                 modifiers_foreachObjectLink(obt, unlink_object__unlinkModifierLinks, ob);
376                 
377                 if ELEM(obt->type, OB_CURVE, OB_FONT) {
378                         cu= obt->data;
379
380                         if(cu->bevobj==ob) {
381                                 cu->bevobj= NULL;
382                                 obt->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
383                         }
384                         if(cu->taperobj==ob) {
385                                 cu->taperobj= NULL;
386                                 obt->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
387                         }
388                         if(cu->textoncurve==ob) {
389                                 cu->textoncurve= NULL;
390                                 obt->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
391                         }
392                 }
393                 else if(obt->type==OB_ARMATURE && obt->pose) {
394                         bPoseChannel *pchan;
395                         for(pchan= obt->pose->chanbase.first; pchan; pchan= pchan->next) {
396                                 for (con = pchan->constraints.first; con; con=con->next) {
397                                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
398                                         ListBase targets = {NULL, NULL};
399                                         bConstraintTarget *ct;
400                                         
401                                         if (cti && cti->get_constraint_targets) {
402                                                 cti->get_constraint_targets(con, &targets);
403                                                 
404                                                 for (ct= targets.first; ct; ct= ct->next) {
405                                                         if (ct->tar == ob) {
406                                                                 ct->tar = NULL;
407                                                                 strcpy(ct->subtarget, "");
408                                                                 obt->recalc |= OB_RECALC_DATA;
409                                                         }
410                                                 }
411                                                 
412                                                 if (cti->flush_constraint_targets)
413                                                         cti->flush_constraint_targets(con, &targets, 0);
414                                         }
415                                 }
416                                 if(pchan->custom==ob)
417                                         pchan->custom= NULL;
418                         }
419                 } else if(ELEM(OB_MBALL, ob->type, obt->type)) {
420                         if(is_mball_basis_for(obt, ob))
421                                 obt->recalc|= OB_RECALC_DATA;
422                 }
423                 
424                 sca_remove_ob_poin(obt, ob);
425                 
426                 for (con = obt->constraints.first; con; con=con->next) {
427                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
428                         ListBase targets = {NULL, NULL};
429                         bConstraintTarget *ct;
430                         
431                         if (cti && cti->get_constraint_targets) {
432                                 cti->get_constraint_targets(con, &targets);
433                                 
434                                 for (ct= targets.first; ct; ct= ct->next) {
435                                         if (ct->tar == ob) {
436                                                 ct->tar = NULL;
437                                                 strcpy(ct->subtarget, "");
438                                                 obt->recalc |= OB_RECALC_DATA;
439                                         }
440                                 }
441                                 
442                                 if (cti->flush_constraint_targets)
443                                         cti->flush_constraint_targets(con, &targets, 0);
444                         }
445                 }
446                 
447                 /* object is deflector or field */
448                 if(ob->pd) {
449                         if(obt->soft)
450                                 obt->recalc |= OB_RECALC_DATA;
451
452                         /* cloth */
453                         for(md=obt->modifiers.first; md; md=md->next)
454                                 if(md->type == eModifierType_Cloth)
455                                         obt->recalc |= OB_RECALC_DATA;
456                 }
457                 
458                 /* strips */
459 #if 0 // XXX old animation system
460                 for(strip= obt->nlastrips.first; strip; strip= strip->next) {
461                         if(strip->object==ob)
462                                 strip->object= NULL;
463                         
464                         if(strip->modifiers.first) {
465                                 bActionModifier *amod;
466                                 for(amod= strip->modifiers.first; amod; amod= amod->next)
467                                         if(amod->ob==ob)
468                                                 amod->ob= NULL;
469                         }
470                 }
471 #endif // XXX old animation system
472
473                 /* particle systems */
474                 if(obt->particlesystem.first) {
475                         ParticleSystem *tpsys= obt->particlesystem.first;
476                         for(; tpsys; tpsys=tpsys->next) {
477                                 BoidState *state = NULL;
478                                 BoidRule *rule = NULL;
479
480                                 ParticleTarget *pt = tpsys->targets.first;
481                                 for(; pt; pt=pt->next) {
482                                         if(pt->ob==ob) {
483                                                 pt->ob = NULL;
484                                                 obt->recalc |= OB_RECALC_DATA;
485                                                 break;
486                                         }
487                                 }
488
489                                 if(tpsys->target_ob==ob) {
490                                         tpsys->target_ob= NULL;
491                                         obt->recalc |= OB_RECALC_DATA;
492                                 }
493
494                                 if(tpsys->part->dup_ob==ob)
495                                         tpsys->part->dup_ob= NULL;
496
497                                 if(tpsys->part->phystype==PART_PHYS_BOIDS) {
498                                         ParticleData *pa;
499                                         BoidParticle *bpa;
500                                         int p;
501
502                                         for(p=0,pa=tpsys->particles; p<tpsys->totpart; p++,pa++) {
503                                                 bpa = pa->boid;
504                                                 if(bpa->ground == ob)
505                                                         bpa->ground = NULL;
506                                         }
507                                 }
508                                 if(tpsys->part->boids) {
509                                         for(state = tpsys->part->boids->states.first; state; state=state->next) {
510                                                 for(rule = state->rules.first; rule; rule=rule->next) {
511                                                         if(rule->type==eBoidRuleType_Avoid) {
512                                                                 BoidRuleGoalAvoid *gabr = (BoidRuleGoalAvoid*)rule;
513                                                                 if(gabr->ob==ob)
514                                                                         gabr->ob= NULL;
515                                                         }
516                                                         else if(rule->type==eBoidRuleType_FollowLeader) {
517                                                                 BoidRuleFollowLeader *flbr = (BoidRuleFollowLeader*)rule;
518                                                                 if(flbr->ob==ob)
519                                                                         flbr->ob= NULL;
520                                                         }
521                                                 }
522                                         }
523                                 }
524                         }
525                         if(ob->pd)
526                                 obt->recalc |= OB_RECALC_DATA;
527                 }
528
529                 obt= obt->id.next;
530         }
531         
532         /* materials */
533         mat= bmain->mat.first;
534         while(mat) {
535         
536                 for(a=0; a<MAX_MTEX; a++) {
537                         if(mat->mtex[a] && ob==mat->mtex[a]->object) {
538                                 /* actually, test for lib here... to do */
539                                 mat->mtex[a]->object= NULL;
540                         }
541                 }
542
543                 mat= mat->id.next;
544         }
545         
546         /* textures */
547         for(tex= bmain->tex.first; tex; tex= tex->id.next) {
548                 if(tex->env && (ob==tex->env->object)) tex->env->object= NULL;
549                 if(tex->pd  && (ob==tex->pd->object))  tex->pd->object= NULL;
550                 if(tex->vd  && (ob==tex->vd->object))  tex->vd->object= NULL;
551         }
552
553         /* worlds */
554         wrld= bmain->world.first;
555         while(wrld) {
556                 if(wrld->id.lib==NULL) {
557                         for(a=0; a<MAX_MTEX; a++) {
558                                 if(wrld->mtex[a] && ob==wrld->mtex[a]->object)
559                                         wrld->mtex[a]->object= NULL;
560                         }
561                 }
562                 
563                 wrld= wrld->id.next;
564         }
565                 
566         /* scenes */
567         sce= bmain->scene.first;
568         while(sce) {
569                 if(sce->id.lib==NULL) {
570                         if(sce->camera==ob) sce->camera= NULL;
571                         if(sce->toolsettings->skgen_template==ob) sce->toolsettings->skgen_template = NULL;
572                         if(sce->toolsettings->particle.object==ob) sce->toolsettings->particle.object= NULL;
573
574 #ifdef DURIAN_CAMERA_SWITCH
575                         {
576                                 TimeMarker *m;
577
578                                 for (m= sce->markers.first; m; m= m->next) {
579                                         if(m->camera==ob)
580                                                 m->camera= NULL;
581                                 }
582                         }
583 #endif
584                         if(sce->ed) {
585                                 Sequence *seq;
586                                 SEQ_BEGIN(sce->ed, seq)
587                                         if(seq->scene_camera==ob) {
588                                                 seq->scene_camera= NULL;
589                                         }
590                                 SEQ_END
591                         }
592                 }
593
594                 sce= sce->id.next;
595         }
596         
597 #if 0 // XXX old animation system
598         /* ipos */
599         ipo= bmain->ipo.first;
600         while(ipo) {
601                 if(ipo->id.lib==NULL) {
602                         IpoCurve *icu;
603                         for(icu= ipo->curve.first; icu; icu= icu->next) {
604                                 if(icu->driver && icu->driver->ob==ob)
605                                         icu->driver->ob= NULL;
606                         }
607                 }
608                 ipo= ipo->id.next;
609         }
610 #endif // XXX old animation system
611         
612         /* screens */
613         sc= bmain->screen.first;
614         while(sc) {
615                 ScrArea *sa= sc->areabase.first;
616                 while(sa) {
617                         SpaceLink *sl;
618
619                         for (sl= sa->spacedata.first; sl; sl= sl->next) {
620                                 if(sl->spacetype==SPACE_VIEW3D) {
621                                         View3D *v3d= (View3D*) sl;
622
623                                         found= 0;
624                                         if(v3d->camera==ob) {
625                                                 v3d->camera= NULL;
626                                                 found= 1;
627                                         }
628                                         if(v3d->localvd && v3d->localvd->camera==ob ) {
629                                                 v3d->localvd->camera= NULL;
630                                                 found += 2;
631                                         }
632
633                                         if (found) {
634                                                 if (sa->spacetype == SPACE_VIEW3D) {
635                                                         for (ar= sa->regionbase.first; ar; ar= ar->next) {
636                                                                 if (ar->regiontype==RGN_TYPE_WINDOW) {
637                                                                         rv3d= (RegionView3D *)ar->regiondata;
638                                                                         if (found == 1 || found == 3) {
639                                                                                 if (rv3d->persp == RV3D_CAMOB)
640                                                                                         rv3d->persp= RV3D_PERSP;
641                                                                         }
642                                                                         if (found == 2 || found == 3) {
643                                                                                 if (rv3d->localvd && rv3d->localvd->persp == RV3D_CAMOB)
644                                                                                         rv3d->localvd->persp= RV3D_PERSP;
645                                                                         }
646                                                                 }
647                                                         }
648                                                 }
649                                         }
650                                 }
651                                 else if(sl->spacetype==SPACE_OUTLINER) {
652                                         SpaceOops *so= (SpaceOops *)sl;
653
654                                         if(so->treestore) {
655                                                 TreeStoreElem *tselem= so->treestore->data;
656                                                 int a;
657                                                 for(a=0; a<so->treestore->usedelem; a++, tselem++) {
658                                                         if(tselem->id==(ID *)ob) tselem->id= NULL;
659                                                 }
660                                         }
661                                 }
662                                 else if(sl->spacetype==SPACE_BUTS) {
663                                         SpaceButs *sbuts= (SpaceButs *)sl;
664
665                                         if(sbuts->pinid==(ID *)ob) {
666                                                 sbuts->flag&= ~SB_PIN_CONTEXT;
667                                                 sbuts->pinid= NULL;
668                                         }
669                                 }
670                         }
671
672                         sa= sa->next;
673                 }
674                 sc= sc->id.next;
675         }
676
677         /* groups */
678         group= bmain->group.first;
679         while(group) {
680                 rem_from_group(group, ob, NULL, NULL);
681                 group= group->id.next;
682         }
683         
684         /* cameras */
685         camera= bmain->camera.first;
686         while(camera) {
687                 if (camera->dof_ob==ob) {
688                         camera->dof_ob = NULL;
689                 }
690                 camera= camera->id.next;
691         }
692 }
693
694 int exist_object(Object *obtest)
695 {
696         Object *ob;
697         
698         if(obtest==NULL) return 0;
699         
700         ob= G.main->object.first;
701         while(ob) {
702                 if(ob==obtest) return 1;
703                 ob= ob->id.next;
704         }
705         return 0;
706 }
707
708 void *add_camera(const char *name)
709 {
710         Camera *cam;
711         
712         cam=  alloc_libblock(&G.main->camera, ID_CA, name);
713
714         cam->lens= 35.0f;
715         cam->sensor_x = 32.f;
716         cam->sensor_y = 18.f;
717         cam->clipsta= 0.1f;
718         cam->clipend= 100.0f;
719         cam->drawsize= 0.5f;
720         cam->ortho_scale= 6.0;
721         cam->flag |= CAM_SHOWPASSEPARTOUT;
722         cam->passepartalpha = 0.5f;
723         
724         return cam;
725 }
726
727 Camera *copy_camera(Camera *cam)
728 {
729         Camera *camn;
730         
731         camn= copy_libblock(cam);
732         
733         return camn;
734 }
735
736
737
738 void make_local_camera(Camera *cam)
739 {
740         Main *bmain= G.main;
741         Object *ob;
742         int local=0, lib=0;
743
744         /* - only lib users: do nothing
745          * - only local users: set flag
746          * - mixed: make copy
747          */
748         
749         if(cam->id.lib==NULL) return;
750         if(cam->id.us==1) {
751                 cam->id.lib= NULL;
752                 cam->id.flag= LIB_LOCAL;
753                 new_id(&bmain->camera, (ID *)cam, NULL);
754                 return;
755         }
756         
757         for(ob= bmain->object.first; ob && ELEM(0, lib, local); ob= ob->id.next) {
758                 if(ob->data==cam) {
759                         if(ob->id.lib) lib= 1;
760                         else local= 1;
761                 }
762         }
763         
764         if(local && lib==0) {
765                 cam->id.lib= NULL;
766                 cam->id.flag= LIB_LOCAL;
767                 new_id(&bmain->camera, (ID *)cam, NULL);
768         }
769         else if(local && lib) {
770                 Camera *camn= copy_camera(cam);
771                 camn->id.us= 0;
772                 
773                 for(ob= bmain->object.first; ob; ob= ob->id.next) {
774                         if(ob->data == cam) {
775                                 if(ob->id.lib==NULL) {
776                                         ob->data= camn;
777                                         camn->id.us++;
778                                         cam->id.us--;
779                                 }
780                         }
781                 }
782         }
783 }
784
785 /* get the camera's dof value, takes the dof object into account */
786 float dof_camera(Object *ob)
787 {
788         Camera *cam = (Camera *)ob->data; 
789         if (ob->type != OB_CAMERA)
790                 return 0.0f;
791         if (cam->dof_ob) {      
792                 /* too simple, better to return the distance on the view axis only
793                  * return len_v3v3(ob->obmat[3], cam->dof_ob->obmat[3]); */
794                 float mat[4][4], imat[4][4], obmat[4][4];
795                 
796                 copy_m4_m4(obmat, ob->obmat);
797                 normalize_m4(obmat);
798                 invert_m4_m4(imat, obmat);
799                 mul_m4_m4m4(mat, cam->dof_ob->obmat, imat);
800                 return (float)fabs(mat[3][2]);
801         }
802         return cam->YF_dofdist;
803 }
804
805 void *add_lamp(const char *name)
806 {
807         Lamp *la;
808         
809         la=  alloc_libblock(&G.main->lamp, ID_LA, name);
810         
811         la->r= la->g= la->b= la->k= 1.0f;
812         la->haint= la->energy= 1.0f;
813         la->dist= 25.0f;
814         la->spotsize= 45.0f;
815         la->spotblend= 0.15f;
816         la->att2= 1.0f;
817         la->mode= LA_SHAD_BUF;
818         la->bufsize= 512;
819         la->clipsta= 0.5f;
820         la->clipend= 40.0f;
821         la->shadspotsize= 45.0f;
822         la->samp= 3;
823         la->bias= 1.0f;
824         la->soft= 3.0f;
825         la->compressthresh= 0.05f;
826         la->ray_samp= la->ray_sampy= la->ray_sampz= 1; 
827         la->area_size=la->area_sizey=la->area_sizez= 1.0f; 
828         la->buffers= 1;
829         la->buftype= LA_SHADBUF_HALFWAY;
830         la->ray_samp_method = LA_SAMP_HALTON;
831         la->adapt_thresh = 0.001f;
832         la->preview=NULL;
833         la->falloff_type = LA_FALLOFF_INVSQUARE;
834         la->curfalloff = curvemapping_add(1, 0.0f, 1.0f, 1.0f, 0.0f);
835         la->sun_effect_type = 0;
836         la->horizon_brightness = 1.0;
837         la->spread = 1.0;
838         la->sun_brightness = 1.0;
839         la->sun_size = 1.0;
840         la->backscattered_light = 1.0f;
841         la->atm_turbidity = 2.0f;
842         la->atm_inscattering_factor = 1.0f;
843         la->atm_extinction_factor = 1.0f;
844         la->atm_distance_factor = 1.0f;
845         la->sun_intensity = 1.0f;
846         la->skyblendtype= MA_RAMP_ADD;
847         la->skyblendfac= 1.0f;
848         la->sky_colorspace= BLI_XYZ_CIE;
849         la->sky_exposure= 1.0f;
850         
851         curvemapping_initialize(la->curfalloff);
852         return la;
853 }
854
855 Lamp *copy_lamp(Lamp *la)
856 {
857         Lamp *lan;
858         int a;
859         
860         lan= copy_libblock(la);
861
862         for(a=0; a<MAX_MTEX; a++) {
863                 if(lan->mtex[a]) {
864                         lan->mtex[a]= MEM_mallocN(sizeof(MTex), "copylamptex");
865                         memcpy(lan->mtex[a], la->mtex[a], sizeof(MTex));
866                         id_us_plus((ID *)lan->mtex[a]->tex);
867                 }
868         }
869         
870         lan->curfalloff = curvemapping_copy(la->curfalloff);
871         
872         if(la->preview)
873                 lan->preview = BKE_previewimg_copy(la->preview);
874         
875         return lan;
876 }
877
878 Lamp *localize_lamp(Lamp *la)
879 {
880         Lamp *lan;
881         int a;
882         
883         lan= copy_libblock(la);
884         BLI_remlink(&G.main->lamp, lan);
885
886         for(a=0; a<MAX_MTEX; a++) {
887                 if(lan->mtex[a]) {
888                         lan->mtex[a]= MEM_mallocN(sizeof(MTex), "localize_lamp");
889                         memcpy(lan->mtex[a], la->mtex[a], sizeof(MTex));
890                         /* free lamp decrements */
891                         id_us_plus((ID *)lan->mtex[a]->tex);
892                 }
893         }
894         
895         lan->curfalloff = curvemapping_copy(la->curfalloff);
896
897         lan->preview= NULL;
898         
899         return lan;
900 }
901
902 void make_local_lamp(Lamp *la)
903 {
904         Main *bmain= G.main;
905         Object *ob;
906         Lamp *lan;
907         int local=0, lib=0;
908
909         /* - only lib users: do nothing
910                 * - only local users: set flag
911                 * - mixed: make copy
912                 */
913         
914         if(la->id.lib==NULL) return;
915         if(la->id.us==1) {
916                 la->id.lib= NULL;
917                 la->id.flag= LIB_LOCAL;
918                 new_id(&bmain->lamp, (ID *)la, NULL);
919                 return;
920         }
921         
922         ob= bmain->object.first;
923         while(ob) {
924                 if(ob->data==la) {
925                         if(ob->id.lib) lib= 1;
926                         else local= 1;
927                 }
928                 ob= ob->id.next;
929         }
930         
931         if(local && lib==0) {
932                 la->id.lib= NULL;
933                 la->id.flag= LIB_LOCAL;
934                 new_id(&bmain->lamp, (ID *)la, NULL);
935         }
936         else if(local && lib) {
937                 lan= copy_lamp(la);
938                 lan->id.us= 0;
939                 
940                 ob= bmain->object.first;
941                 while(ob) {
942                         if(ob->data==la) {
943                                 
944                                 if(ob->id.lib==NULL) {
945                                         ob->data= lan;
946                                         lan->id.us++;
947                                         la->id.us--;
948                                 }
949                         }
950                         ob= ob->id.next;
951                 }
952         }
953 }
954
955 void free_camera(Camera *ca)
956 {
957         BKE_free_animdata((ID *)ca);
958 }
959
960 void free_lamp(Lamp *la)
961 {
962         MTex *mtex;
963         int a;
964
965         for(a=0; a<MAX_MTEX; a++) {
966                 mtex= la->mtex[a];
967                 if(mtex && mtex->tex) mtex->tex->id.us--;
968                 if(mtex) MEM_freeN(mtex);
969         }
970         
971         BKE_free_animdata((ID *)la);
972
973         curvemapping_free(la->curfalloff);
974         
975         BKE_previewimg_free(&la->preview);
976         BKE_icon_delete(&la->id);
977         la->id.icon_id = 0;
978 }
979
980 /* *************************************************** */
981
982 static void *add_obdata_from_type(int type)
983 {
984         switch (type) {
985         case OB_MESH: return add_mesh("Mesh");
986         case OB_CURVE: return add_curve("Curve", OB_CURVE);
987         case OB_SURF: return add_curve("Surf", OB_SURF);
988         case OB_FONT: return add_curve("Text", OB_FONT);
989         case OB_MBALL: return add_mball("Meta");
990         case OB_CAMERA: return add_camera("Camera");
991         case OB_LAMP: return add_lamp("Lamp");
992         case OB_LATTICE: return add_lattice("Lattice");
993         case OB_ARMATURE: return add_armature("Armature");
994         case OB_EMPTY: return NULL;
995         default:
996                 printf("add_obdata_from_type: Internal error, bad type: %d\n", type);
997                 return NULL;
998         }
999 }
1000
1001 static const char *get_obdata_defname(int type)
1002 {
1003         switch (type) {
1004         case OB_MESH: return "Mesh";
1005         case OB_CURVE: return "Curve";
1006         case OB_SURF: return "Surf";
1007         case OB_FONT: return "Text";
1008         case OB_MBALL: return "Mball";
1009         case OB_CAMERA: return "Camera";
1010         case OB_LAMP: return "Lamp";
1011         case OB_LATTICE: return "Lattice";
1012         case OB_ARMATURE: return "Armature";
1013         case OB_EMPTY: return "Empty";
1014         default:
1015                 printf("get_obdata_defname: Internal error, bad type: %d\n", type);
1016                 return "Empty";
1017         }
1018 }
1019
1020 /* more general add: creates minimum required data, but without vertices etc. */
1021 Object *add_only_object(int type, const char *name)
1022 {
1023         Object *ob;
1024
1025         ob= alloc_libblock(&G.main->object, ID_OB, name);
1026
1027         /* default object vars */
1028         ob->type= type;
1029         
1030         ob->col[0]= ob->col[1]= ob->col[2]= 1.0;
1031         ob->col[3]= 1.0;
1032         
1033         ob->size[0]= ob->size[1]= ob->size[2]= 1.0;
1034         
1035         /* objects should default to having Euler XYZ rotations, 
1036          * but rotations default to quaternions 
1037          */
1038         ob->rotmode= ROT_MODE_EUL;
1039
1040         unit_axis_angle(ob->rotAxis, &ob->rotAngle);
1041         unit_axis_angle(ob->drotAxis, &ob->drotAngle);
1042
1043         unit_qt(ob->quat);
1044         unit_qt(ob->dquat);
1045
1046         /* rotation locks should be 4D for 4 component rotations by default... */
1047         ob->protectflag = OB_LOCK_ROT4D;
1048         
1049         unit_m4(ob->constinv);
1050         unit_m4(ob->parentinv);
1051         unit_m4(ob->obmat);
1052         ob->dt= OB_TEXTURE;
1053         ob->empty_drawtype= OB_PLAINAXES;
1054         ob->empty_drawsize= 1.0;
1055
1056         if(type==OB_CAMERA || type==OB_LAMP) {
1057                 ob->trackflag= OB_NEGZ;
1058                 ob->upflag= OB_POSY;
1059         }
1060         else {
1061                 ob->trackflag= OB_POSY;
1062                 ob->upflag= OB_POSZ;
1063         }
1064         
1065         ob->dupon= 1; ob->dupoff= 0;
1066         ob->dupsta= 1; ob->dupend= 100;
1067         ob->dupfacesca = 1.0;
1068
1069         /* Game engine defaults*/
1070         ob->mass= ob->inertia= 1.0f;
1071         ob->formfactor= 0.4f;
1072         ob->damping= 0.04f;
1073         ob->rdamping= 0.1f;
1074         ob->anisotropicFriction[0] = 1.0f;
1075         ob->anisotropicFriction[1] = 1.0f;
1076         ob->anisotropicFriction[2] = 1.0f;
1077         ob->gameflag= OB_PROP|OB_COLLISION;
1078         ob->margin = 0.0;
1079         ob->init_state=1;
1080         ob->state=1;
1081         /* ob->pad3 == Contact Processing Threshold */
1082         ob->m_contactProcessingThreshold = 1.;
1083         
1084         /* NT fluid sim defaults */
1085         ob->fluidsimFlag = 0;
1086         ob->fluidsimSettings = NULL;
1087
1088         ob->pc_ids.first = ob->pc_ids.last = NULL;
1089         
1090         /* Animation Visualisation defaults */
1091         animviz_settings_init(&ob->avs);
1092
1093         return ob;
1094 }
1095
1096 /* general add: to scene, with layer from area and default name */
1097 /* creates minimum required data, but without vertices etc. */
1098 Object *add_object(struct Scene *scene, int type)
1099 {
1100         Object *ob;
1101         Base *base;
1102         char name[32];
1103
1104         BLI_strncpy(name, get_obdata_defname(type), sizeof(name));
1105         ob = add_only_object(type, name);
1106
1107         ob->data= add_obdata_from_type(type);
1108
1109         ob->lay= scene->lay;
1110         
1111         base= scene_add_base(scene, ob);
1112         scene_select_base(scene, base);
1113         ob->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
1114
1115         return ob;
1116 }
1117
1118 SoftBody *copy_softbody(SoftBody *sb)
1119 {
1120         SoftBody *sbn;
1121         
1122         if (sb==NULL) return(NULL);
1123         
1124         sbn= MEM_dupallocN(sb);
1125         sbn->totspring= sbn->totpoint= 0;
1126         sbn->bpoint= NULL;
1127         sbn->bspring= NULL;
1128         
1129         sbn->keys= NULL;
1130         sbn->totkey= sbn->totpointkey= 0;
1131         
1132         sbn->scratch= NULL;
1133
1134         sbn->pointcache= BKE_ptcache_copy_list(&sbn->ptcaches, &sb->ptcaches);
1135
1136         if(sb->effector_weights)
1137                 sbn->effector_weights = MEM_dupallocN(sb->effector_weights);
1138
1139         return sbn;
1140 }
1141
1142 BulletSoftBody *copy_bulletsoftbody(BulletSoftBody *bsb)
1143 {
1144         BulletSoftBody *bsbn;
1145
1146         if (bsb == NULL)
1147                 return NULL;
1148         bsbn = MEM_dupallocN(bsb);
1149         /* no pointer in this structure yet */
1150         return bsbn;
1151 }
1152
1153 static ParticleSystem *copy_particlesystem(ParticleSystem *psys)
1154 {
1155         ParticleSystem *psysn;
1156         ParticleData *pa;
1157         int p;
1158
1159         psysn= MEM_dupallocN(psys);
1160         psysn->particles= MEM_dupallocN(psys->particles);
1161         psysn->child= MEM_dupallocN(psys->child);
1162
1163         if(psys->part->type == PART_HAIR) {
1164                 for(p=0, pa=psysn->particles; p<psysn->totpart; p++, pa++)
1165                         pa->hair = MEM_dupallocN(pa->hair);
1166         }
1167
1168         if(psysn->particles && (psysn->particles->keys || psysn->particles->boid)) {
1169                 ParticleKey *key = psysn->particles->keys;
1170                 BoidParticle *boid = psysn->particles->boid;
1171
1172                 if(key)
1173                         key = MEM_dupallocN(key);
1174                 
1175                 if(boid)
1176                         boid = MEM_dupallocN(boid);
1177                 
1178                 for(p=0, pa=psysn->particles; p<psysn->totpart; p++, pa++) {
1179                         if(boid)
1180                                 pa->boid = boid++;
1181                         if(key) {
1182                                 pa->keys = key;
1183                                 key += pa->totkey;
1184                         }
1185                 }
1186         }
1187
1188         if(psys->clmd) {
1189                 psysn->clmd = (ClothModifierData *)modifier_new(eModifierType_Cloth);
1190                 modifier_copyData((ModifierData*)psys->clmd, (ModifierData*)psysn->clmd);
1191                 psys->hair_in_dm = psys->hair_out_dm = NULL;
1192         }
1193
1194         BLI_duplicatelist(&psysn->targets, &psys->targets);
1195
1196         psysn->pathcache= NULL;
1197         psysn->childcache= NULL;
1198         psysn->edit= NULL;
1199         psysn->frand= NULL;
1200         psysn->pdd= NULL;
1201         psysn->effectors= NULL;
1202         
1203         psysn->pathcachebufs.first = psysn->pathcachebufs.last = NULL;
1204         psysn->childcachebufs.first = psysn->childcachebufs.last = NULL;
1205         psysn->renderdata = NULL;
1206         
1207         psysn->pointcache= BKE_ptcache_copy_list(&psysn->ptcaches, &psys->ptcaches);
1208
1209         /* XXX - from reading existing code this seems correct but intended usage of
1210          * pointcache should /w cloth should be added in 'ParticleSystem' - campbell */
1211         if(psysn->clmd) {
1212                 psysn->clmd->point_cache= psysn->pointcache;
1213         }
1214
1215         id_us_plus((ID *)psysn->part);
1216
1217         return psysn;
1218 }
1219
1220 void copy_object_particlesystems(Object *obn, Object *ob)
1221 {
1222         ParticleSystemModifierData *psmd;
1223         ParticleSystem *psys, *npsys;
1224         ModifierData *md;
1225
1226         obn->particlesystem.first= obn->particlesystem.last= NULL;
1227         for(psys=ob->particlesystem.first; psys; psys=psys->next) {
1228                 npsys= copy_particlesystem(psys);
1229
1230                 BLI_addtail(&obn->particlesystem, npsys);
1231
1232                 /* need to update particle modifiers too */
1233                 for(md=obn->modifiers.first; md; md=md->next) {
1234                         if(md->type==eModifierType_ParticleSystem) {
1235                                 psmd= (ParticleSystemModifierData*)md;
1236                                 if(psmd->psys==psys)
1237                                         psmd->psys= npsys;
1238                         }
1239                 }
1240         }
1241 }
1242
1243 void copy_object_softbody(Object *obn, Object *ob)
1244 {
1245         if(ob->soft)
1246                 obn->soft= copy_softbody(ob->soft);
1247 }
1248
1249 static void copy_object_pose(Object *obn, Object *ob)
1250 {
1251         bPoseChannel *chan;
1252         
1253         /* note: need to clear obn->pose pointer first, so that copy_pose works (otherwise there's a crash) */
1254         obn->pose= NULL;
1255         copy_pose(&obn->pose, ob->pose, 1);     /* 1 = copy constraints */
1256
1257         for (chan = obn->pose->chanbase.first; chan; chan=chan->next){
1258                 bConstraint *con;
1259                 
1260                 chan->flag &= ~(POSE_LOC|POSE_ROT|POSE_SIZE);
1261                 
1262                 for (con= chan->constraints.first; con; con= con->next) {
1263                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1264                         ListBase targets = {NULL, NULL};
1265                         bConstraintTarget *ct;
1266                         
1267 #if 0 // XXX old animation system
1268                         /* note that we can't change lib linked ipo blocks. for making
1269                          * proxies this still works correct however because the object
1270                          * is changed to object->proxy_from when evaluating the driver. */
1271                         if(con->ipo && !con->ipo->id.lib) {
1272                                 IpoCurve *icu;
1273                                 
1274                                 con->ipo= copy_ipo(con->ipo);
1275                                 
1276                                 for(icu= con->ipo->curve.first; icu; icu= icu->next) {
1277                                         if(icu->driver && icu->driver->ob==ob)
1278                                                 icu->driver->ob= obn;
1279                                 }
1280                         }
1281 #endif // XXX old animation system
1282                         
1283                         if (cti && cti->get_constraint_targets) {
1284                                 cti->get_constraint_targets(con, &targets);
1285                                 
1286                                 for (ct= targets.first; ct; ct= ct->next) {
1287                                         if (ct->tar == ob)
1288                                                 ct->tar = obn;
1289                                 }
1290                                 
1291                                 if (cti->flush_constraint_targets)
1292                                         cti->flush_constraint_targets(con, &targets, 0);
1293                         }
1294                 }
1295         }
1296 }
1297
1298 static void copy_object_transform(Object *ob_tar, Object *ob_src)
1299 {
1300         copy_v3_v3(ob_tar->loc, ob_src->loc);
1301         copy_v3_v3(ob_tar->rot, ob_src->rot);
1302         copy_v3_v3(ob_tar->quat, ob_src->quat);
1303         copy_v3_v3(ob_tar->rotAxis, ob_src->rotAxis);
1304         ob_tar->rotAngle= ob_src->rotAngle;
1305         ob_tar->rotmode= ob_src->rotmode;
1306         copy_v3_v3(ob_tar->size, ob_src->size);
1307 }
1308
1309 Object *copy_object(Object *ob)
1310 {
1311         Object *obn;
1312         ModifierData *md;
1313         int a;
1314
1315         obn= copy_libblock(ob);
1316         
1317         if(ob->totcol) {
1318                 obn->mat= MEM_dupallocN(ob->mat);
1319                 obn->matbits= MEM_dupallocN(ob->matbits);
1320                 obn->totcol= ob->totcol;
1321         }
1322         
1323         if(ob->bb) obn->bb= MEM_dupallocN(ob->bb);
1324         obn->path= NULL;
1325         obn->flag &= ~OB_FROMGROUP;
1326         
1327         obn->modifiers.first = obn->modifiers.last= NULL;
1328         
1329         for (md=ob->modifiers.first; md; md=md->next) {
1330                 ModifierData *nmd = modifier_new(md->type);
1331                 BLI_strncpy(nmd->name, md->name, sizeof(nmd->name));
1332                 modifier_copyData(md, nmd);
1333                 BLI_addtail(&obn->modifiers, nmd);
1334         }
1335
1336         obn->prop.first = obn->prop.last = NULL;
1337         copy_properties(&obn->prop, &ob->prop);
1338         
1339         copy_sensors(&obn->sensors, &ob->sensors);
1340         copy_controllers(&obn->controllers, &ob->controllers);
1341         copy_actuators(&obn->actuators, &ob->actuators);
1342         
1343         if(ob->pose) {
1344                 copy_object_pose(obn, ob);
1345                 /* backwards compat... non-armatures can get poses in older files? */
1346                 if(ob->type==OB_ARMATURE)
1347                         armature_rebuild_pose(obn, obn->data);
1348         }
1349         defgroup_copy_list(&obn->defbase, &ob->defbase);
1350         copy_constraints(&obn->constraints, &ob->constraints, TRUE);
1351
1352         obn->mode = 0;
1353         obn->sculpt = NULL;
1354
1355         /* increase user numbers */
1356         id_us_plus((ID *)obn->data);
1357         id_us_plus((ID *)obn->gpd);
1358         id_lib_extern((ID *)obn->dup_group);
1359
1360         for(a=0; a<obn->totcol; a++) id_us_plus((ID *)obn->mat[a]);
1361         
1362         obn->disp.first= obn->disp.last= NULL;
1363         
1364         if(ob->pd){
1365                 obn->pd= MEM_dupallocN(ob->pd);
1366                 if(obn->pd->tex)
1367                         id_us_plus(&(obn->pd->tex->id));
1368                 if(obn->pd->rng)
1369                         obn->pd->rng = MEM_dupallocN(ob->pd->rng);
1370         }
1371         obn->soft= copy_softbody(ob->soft);
1372         obn->bsoft = copy_bulletsoftbody(ob->bsoft);
1373
1374         copy_object_particlesystems(obn, ob);
1375         
1376         obn->derivedDeform = NULL;
1377         obn->derivedFinal = NULL;
1378
1379         obn->gpulamp.first = obn->gpulamp.last = NULL;
1380         obn->pc_ids.first = obn->pc_ids.last = NULL;
1381
1382         obn->mpath= NULL;
1383         
1384         return obn;
1385 }
1386
1387 static void extern_local_object(Object *ob)
1388 {
1389         //bActionStrip *strip;
1390         ParticleSystem *psys;
1391
1392 #if 0 // XXX old animation system
1393         id_lib_extern((ID *)ob->action);
1394         id_lib_extern((ID *)ob->ipo);
1395 #endif // XXX old animation system
1396         id_lib_extern((ID *)ob->data);
1397         id_lib_extern((ID *)ob->dup_group);
1398         id_lib_extern((ID *)ob->poselib);
1399         id_lib_extern((ID *)ob->gpd);
1400
1401         extern_local_matarar(ob->mat, ob->totcol);
1402
1403 #if 0 // XXX old animation system
1404         for (strip=ob->nlastrips.first; strip; strip=strip->next) {
1405                 id_lib_extern((ID *)strip->act);
1406         }
1407 #endif // XXX old animation system
1408         for(psys=ob->particlesystem.first; psys; psys=psys->next)
1409                 id_lib_extern((ID *)psys->part);
1410 }
1411
1412 void make_local_object(Object *ob)
1413 {
1414         Main *bmain= G.main;
1415         Scene *sce;
1416         Base *base;
1417         int local=0, lib=0;
1418
1419         /* - only lib users: do nothing
1420          * - only local users: set flag
1421          * - mixed: make copy
1422          */
1423
1424         if(ob->id.lib==NULL) return;
1425         
1426         ob->proxy= ob->proxy_from= NULL;
1427         
1428         if(ob->id.us==1) {
1429                 ob->id.lib= NULL;
1430                 ob->id.flag= LIB_LOCAL;
1431                 new_id(&bmain->object, (ID *)ob, NULL);
1432         }
1433         else {
1434                 for(sce= bmain->scene.first; sce && ELEM(0, lib, local); sce= sce->id.next) {
1435                         if(object_in_scene(ob, sce)) {
1436                                 if(sce->id.lib) lib= 1;
1437                                 else local= 1;
1438                         }
1439                 }
1440
1441                 if(local && lib==0) {
1442                         ob->id.lib= NULL;
1443                         ob->id.flag= LIB_LOCAL;
1444                         new_id(&bmain->object, (ID *)ob, NULL);
1445                 }
1446                 else if(local && lib) {
1447                         Object *obn= copy_object(ob);
1448                         obn->id.us= 0;
1449                         
1450                         sce= bmain->scene.first;
1451                         while(sce) {
1452                                 if(sce->id.lib==NULL) {
1453                                         base= sce->base.first;
1454                                         while(base) {
1455                                                 if(base->object==ob) {
1456                                                         base->object= obn;
1457                                                         obn->id.us++;
1458                                                         ob->id.us--;
1459                                                 }
1460                                                 base= base->next;
1461                                         }
1462                                 }
1463                                 sce= sce->id.next;
1464                         }
1465                 }
1466         }
1467         
1468         extern_local_object(ob);
1469 }
1470
1471 /*
1472  * Returns true if the Object is a from an external blend file (libdata)
1473  */
1474 int object_is_libdata(Object *ob)
1475 {
1476         if (!ob) return 0;
1477         if (ob->proxy) return 0;
1478         if (ob->id.lib) return 1;
1479         return 0;
1480 }
1481
1482 /* Returns true if the Object data is a from an external blend file (libdata) */
1483 int object_data_is_libdata(Object *ob)
1484 {
1485         if(!ob) return 0;
1486         if(ob->proxy && (ob->data==NULL || ((ID *)ob->data)->lib==NULL)) return 0;
1487         if(ob->id.lib) return 1;
1488         if(ob->data==NULL) return 0;
1489         if(((ID *)ob->data)->lib) return 1;
1490
1491         return 0;
1492 }
1493
1494 /* *************** PROXY **************** */
1495
1496 /* when you make proxy, ensure the exposed layers are extern */
1497 static void armature_set_id_extern(Object *ob)
1498 {
1499         bArmature *arm= ob->data;
1500         bPoseChannel *pchan;
1501         unsigned int lay= arm->layer_protected;
1502         
1503         for (pchan = ob->pose->chanbase.first; pchan; pchan=pchan->next) {
1504                 if(!(pchan->bone->layer & lay))
1505                         id_lib_extern((ID *)pchan->custom);
1506         }
1507                         
1508 }
1509
1510 void object_copy_proxy_drivers(Object *ob, Object *target)
1511 {
1512         if ((target->adt) && (target->adt->drivers.first)) {
1513                 FCurve *fcu;
1514                 
1515                 /* add new animdata block */
1516                 if(!ob->adt)
1517                         ob->adt= BKE_id_add_animdata(&ob->id);
1518                 
1519                 /* make a copy of all the drivers (for now), then correct any links that need fixing */
1520                 free_fcurves(&ob->adt->drivers);
1521                 copy_fcurves(&ob->adt->drivers, &target->adt->drivers);
1522                 
1523                 for (fcu= ob->adt->drivers.first; fcu; fcu= fcu->next) {
1524                         ChannelDriver *driver= fcu->driver;
1525                         DriverVar *dvar;
1526                         
1527                         for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
1528                                 /* all drivers */
1529                                 DRIVER_TARGETS_LOOPER(dvar) 
1530                                 {
1531                                         if(dtar->id) {
1532                                                 if ((Object *)dtar->id == target)
1533                                                         dtar->id= (ID *)ob;
1534                                                 else {
1535                                                         /* only on local objects because this causes indirect links a -> b -> c,blend to point directly to a.blend
1536                                                          * when a.blend has a proxy thats linked into c.blend  */
1537                                                         if(ob->id.lib==NULL)
1538                                                                 id_lib_extern((ID *)dtar->id);
1539                                                 }
1540                                         }
1541                                 }
1542                                 DRIVER_TARGETS_LOOPER_END
1543                         }
1544                 }
1545         }
1546 }
1547
1548 /* proxy rule: lib_object->proxy_from == the one we borrow from, set temporally while object_update */
1549 /*             local_object->proxy == pointer to library object, saved in files and read */
1550 /*             local_object->proxy_group == pointer to group dupli-object, saved in files and read */
1551
1552 void object_make_proxy(Object *ob, Object *target, Object *gob)
1553 {
1554         /* paranoia checks */
1555         if(ob->id.lib || target->id.lib==NULL) {
1556                 printf("cannot make proxy\n");
1557                 return;
1558         }
1559         
1560         ob->proxy= target;
1561         ob->proxy_group= gob;
1562         id_lib_extern(&target->id);
1563         
1564         ob->recalc= target->recalc= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
1565         
1566         /* copy transform
1567          * - gob means this proxy comes from a group, just apply the matrix
1568          *   so the object wont move from its dupli-transform.
1569          *
1570          * - no gob means this is being made from a linked object,
1571          *   this is closer to making a copy of the object - in-place. */
1572         if(gob) {
1573                 ob->rotmode= target->rotmode;
1574                 mul_m4_m4m4(ob->obmat, target->obmat, gob->obmat);
1575                 if(gob->dup_group) { /* should always be true */
1576                         float tvec[3];
1577                         copy_v3_v3(tvec, gob->dup_group->dupli_ofs);
1578                         mul_mat3_m4_v3(ob->obmat, tvec);
1579                         sub_v3_v3(ob->obmat[3], tvec);
1580                 }
1581                 object_apply_mat4(ob, ob->obmat, FALSE, TRUE);
1582         }
1583         else {
1584                 copy_object_transform(ob, target);
1585                 ob->parent= target->parent;     /* libdata */
1586                 copy_m4_m4(ob->parentinv, target->parentinv);
1587         }
1588         
1589         /* copy animdata stuff - drivers only for now... */
1590         object_copy_proxy_drivers(ob, target);
1591
1592         /* skip constraints? */
1593         // FIXME: this is considered by many as a bug
1594         
1595         /* set object type and link to data */
1596         ob->type= target->type;
1597         ob->data= target->data;
1598         id_us_plus((ID *)ob->data);             /* ensures lib data becomes LIB_EXTERN */
1599         
1600         /* copy material and index information */
1601         ob->actcol= ob->totcol= 0;
1602         if(ob->mat) MEM_freeN(ob->mat);
1603         if(ob->matbits) MEM_freeN(ob->matbits);
1604         ob->mat = NULL;
1605         ob->matbits= NULL;
1606         if ((target->totcol) && (target->mat) && ELEM5(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL)) { //XXX OB_SUPPORT_MATERIAL
1607                 int i;
1608                 ob->colbits = target->colbits;
1609                 
1610                 ob->actcol= target->actcol;
1611                 ob->totcol= target->totcol;
1612                 
1613                 ob->mat = MEM_dupallocN(target->mat);
1614                 ob->matbits = MEM_dupallocN(target->matbits);
1615                 for(i=0; i<target->totcol; i++) {
1616                         /* dont need to run test_object_materials since we know this object is new and not used elsewhere */
1617                         id_us_plus((ID *)ob->mat[i]); 
1618                 }
1619         }
1620         
1621         /* type conversions */
1622         if(target->type == OB_ARMATURE) {
1623                 copy_object_pose(ob, target);   /* data copy, object pointers in constraints */
1624                 rest_pose(ob->pose);                    /* clear all transforms in channels */
1625                 armature_rebuild_pose(ob, ob->data);    /* set all internal links */
1626                 
1627                 armature_set_id_extern(ob);
1628         }
1629         else if (target->type == OB_EMPTY) {
1630                 ob->empty_drawtype = target->empty_drawtype;
1631                 ob->empty_drawsize = target->empty_drawsize;
1632         }
1633
1634         /* copy IDProperties */
1635         if(ob->id.properties) {
1636                 IDP_FreeProperty(ob->id.properties);
1637                 MEM_freeN(ob->id.properties);
1638                 ob->id.properties= NULL;
1639         }
1640         if(target->id.properties) {
1641                 ob->id.properties= IDP_CopyProperty(target->id.properties);
1642         }
1643
1644         /* copy drawtype info */
1645         ob->dt= target->dt;
1646 }
1647
1648
1649 /* *************** CALC ****************** */
1650
1651 /* there is also a timing calculation in drawobject() */
1652
1653
1654 // XXX THIS CRUFT NEEDS SERIOUS RECODING ASAP!
1655 /* ob can be NULL */
1656 float bsystem_time(struct Scene *scene, Object *UNUSED(ob), float cfra, float ofs)
1657 {
1658         /* returns float ( see BKE_curframe in scene.c) */
1659         cfra += scene->r.subframe;
1660         
1661         /* global time */
1662         if (scene)
1663                 cfra*= scene->r.framelen;       
1664         
1665 #if 0 // XXX old animation system
1666         if (ob) {
1667                 /* ofset frames */
1668                 if ((ob->ipoflag & OB_OFFS_PARENT) && (ob->partype & PARSLOW)==0) 
1669                         cfra-= give_timeoffset(ob);
1670         }
1671 #endif // XXX old animation system
1672         
1673         cfra-= ofs;
1674
1675         return cfra;
1676 }
1677
1678 void object_scale_to_mat3(Object *ob, float mat[][3])
1679 {
1680         float vec[3];
1681         add_v3_v3v3(vec, ob->size, ob->dsize);
1682         size_to_mat3( mat,vec);
1683 }
1684
1685
1686 void object_rot_to_mat3(Object *ob, float mat[][3])
1687 {
1688         float rmat[3][3], dmat[3][3];
1689         
1690         /* 'dmat' is the delta-rotation matrix, which will get (pre)multiplied
1691          * with the rotation matrix to yield the appropriate rotation
1692          */
1693
1694         /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
1695         if (ob->rotmode > 0) {
1696                 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
1697                 eulO_to_mat3(rmat, ob->rot, ob->rotmode);
1698                 eulO_to_mat3(dmat, ob->drot, ob->rotmode);
1699         }
1700         else if (ob->rotmode == ROT_MODE_AXISANGLE) {
1701                 /* axis-angle -  not really that great for 3D-changing orientations */
1702                 axis_angle_to_mat3(rmat, ob->rotAxis, ob->rotAngle);
1703                 axis_angle_to_mat3(dmat, ob->drotAxis, ob->drotAngle);
1704         }
1705         else {
1706                 /* quats are normalised before use to eliminate scaling issues */
1707                 float tquat[4];
1708                 
1709                 normalize_qt_qt(tquat, ob->quat);
1710                 quat_to_mat3(rmat, tquat);
1711                 
1712                 normalize_qt_qt(tquat, ob->dquat);
1713                 quat_to_mat3(dmat, tquat);
1714         }
1715         
1716         /* combine these rotations */
1717         mul_m3_m3m3(mat, dmat, rmat);
1718 }
1719
1720 void object_mat3_to_rot(Object *ob, float mat[][3], short use_compat)
1721 {
1722         switch(ob->rotmode) {
1723         case ROT_MODE_QUAT:
1724                 {
1725                         float dquat[4];
1726                         mat3_to_quat(ob->quat, mat);
1727                         normalize_qt_qt(dquat, ob->dquat);
1728                         invert_qt(dquat);
1729                         mul_qt_qtqt(ob->quat, dquat, ob->quat);
1730                 }
1731                 break;
1732         case ROT_MODE_AXISANGLE:
1733                 mat3_to_axis_angle(ob->rotAxis, &ob->rotAngle, mat);
1734                 sub_v3_v3(ob->rotAxis, ob->drotAxis);
1735                 ob->rotAngle -= ob->drotAngle;
1736                 break;
1737         default: /* euler */
1738                 {
1739                         float quat[4];
1740                         float dquat[4];
1741                         float tmat[3][3];
1742
1743                         /* without drot we could apply 'mat' directly */
1744                         mat3_to_quat(quat, mat);
1745                         eulO_to_quat(dquat, ob->drot, ob->rotmode);
1746                         invert_qt(dquat);
1747                         mul_qt_qtqt(quat, dquat, quat);
1748                         quat_to_mat3(tmat, quat);
1749                         /* end drot correction */
1750
1751                         if(use_compat)  mat3_to_compatible_eulO(ob->rot, ob->rot, ob->rotmode, tmat);
1752                         else                    mat3_to_eulO(ob->rot, ob->rotmode, tmat);
1753                 }
1754         }
1755 }
1756
1757 /* see pchan_apply_mat4() for the equivalent 'pchan' function */
1758 void object_apply_mat4(Object *ob, float mat[][4], const short use_compat, const short use_parent)
1759 {
1760         float rot[3][3];
1761
1762         if(use_parent && ob->parent) {
1763                 float rmat[4][4], diff_mat[4][4], imat[4][4];
1764                 mul_m4_m4m4(diff_mat, ob->parentinv, ob->parent->obmat);
1765                 invert_m4_m4(imat, diff_mat);
1766                 mul_m4_m4m4(rmat, mat, imat); /* get the parent relative matrix */
1767                 object_apply_mat4(ob, rmat, use_compat, FALSE);
1768                 
1769                 /* same as below, use rmat rather than mat */
1770                 mat4_to_loc_rot_size(ob->loc, rot, ob->size, rmat);
1771                 object_mat3_to_rot(ob, rot, use_compat);
1772         }
1773         else {
1774                 mat4_to_loc_rot_size(ob->loc, rot, ob->size, mat);
1775                 object_mat3_to_rot(ob, rot, use_compat);
1776         }
1777         
1778         sub_v3_v3(ob->loc, ob->dloc);
1779         sub_v3_v3(ob->size, ob->dsize);
1780         /* object_mat3_to_rot handles delta rotations */
1781 }
1782
1783 void object_to_mat3(Object *ob, float mat[][3]) /* no parent */
1784 {
1785         float smat[3][3];
1786         float rmat[3][3];
1787         /*float q1[4];*/
1788         
1789         /* size */
1790         object_scale_to_mat3(ob, smat);
1791
1792         /* rot */
1793         object_rot_to_mat3(ob, rmat);
1794         mul_m3_m3m3(mat, rmat, smat);
1795 }
1796
1797 void object_to_mat4(Object *ob, float mat[][4])
1798 {
1799         float tmat[3][3];
1800         
1801         object_to_mat3(ob, tmat);
1802         
1803         copy_m4_m3(mat, tmat);
1804
1805         add_v3_v3v3(mat[3], ob->loc, ob->dloc);
1806 }
1807
1808 /* extern */
1809 int enable_cu_speed= 1;
1810
1811 static void ob_parcurve(Scene *scene, Object *ob, Object *par, float mat[][4])
1812 {
1813         Curve *cu;
1814         float vec[4], dir[3], quat[4], radius, ctime;
1815         float timeoffs = 0.0, sf_orig = 0.0;
1816         
1817         unit_m4(mat);
1818         
1819         cu= par->data;
1820         if(cu->path==NULL || cu->path->data==NULL) /* only happens on reload file, but violates depsgraph still... fix! */
1821                 makeDispListCurveTypes(scene, par, 0);
1822         if(cu->path==NULL) return;
1823         
1824         /* exception, timeoffset is regarded as distance offset */
1825         if(cu->flag & CU_OFFS_PATHDIST) {
1826                 timeoffs = give_timeoffset(ob);
1827                 SWAP(float, sf_orig, ob->sf);
1828         }
1829         
1830         /* catch exceptions: feature for nla stride editing */
1831         if(ob->ipoflag & OB_DISABLE_PATH) {
1832                 ctime= 0.0f;
1833         }
1834         /* catch exceptions: curve paths used as a duplicator */
1835         else if(enable_cu_speed) {
1836                 /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated,
1837                  * but this will only work if it actually is animated... 
1838                  *
1839                  * we divide the curvetime calculated in the previous step by the length of the path, to get a time
1840                  * factor, which then gets clamped to lie within 0.0 - 1.0 range
1841                  */
1842                 if (IS_EQF(cu->pathlen, 0.0f) == 0)
1843                         ctime= cu->ctime / cu->pathlen;
1844                 else
1845                         ctime= cu->ctime;
1846
1847                 CLAMP(ctime, 0.0f, 1.0f);
1848         }
1849         else {
1850                 ctime= scene->r.cfra - give_timeoffset(ob);
1851                 if (IS_EQF(cu->pathlen, 0.0f) == 0)
1852                         ctime /= cu->pathlen;
1853                 
1854                 CLAMP(ctime, 0.0f, 1.0f);
1855         }
1856         
1857         /* time calculus is correct, now apply distance offset */
1858         if(cu->flag & CU_OFFS_PATHDIST) {
1859                 ctime += timeoffs/cu->path->totdist;
1860
1861                 /* restore */
1862                 SWAP(float, sf_orig, ob->sf);
1863         }
1864         
1865         
1866         /* vec: 4 items! */
1867         if( where_on_path(par, ctime, vec, dir, cu->flag & CU_FOLLOW ? quat:NULL, &radius, NULL) ) {
1868
1869                 if(cu->flag & CU_FOLLOW) {
1870 #if 0
1871                         float x1, q[4];
1872                         vec_to_quat( quat,dir, ob->trackflag, ob->upflag);
1873                         
1874                         /* the tilt */
1875                         normalize_v3(dir);
1876                         q[0]= (float)cos(0.5*vec[3]);
1877                         x1= (float)sin(0.5*vec[3]);
1878                         q[1]= -x1*dir[0];
1879                         q[2]= -x1*dir[1];
1880                         q[3]= -x1*dir[2];
1881                         mul_qt_qtqt(quat, q, quat);
1882 #else
1883                         quat_apply_track(quat, ob->trackflag, ob->upflag);
1884 #endif
1885                         normalize_qt(quat);
1886                         quat_to_mat4(mat, quat);
1887                 }
1888                 
1889                 if(cu->flag & CU_PATH_RADIUS) {
1890                         float tmat[4][4], rmat[4][4];
1891                         scale_m4_fl(tmat, radius);
1892                         mul_m4_m4m4(rmat, mat, tmat);
1893                         copy_m4_m4(mat, rmat);
1894                 }
1895
1896                 copy_v3_v3(mat[3], vec);
1897                 
1898         }
1899 }
1900
1901 static void ob_parbone(Object *ob, Object *par, float mat[][4])
1902 {       
1903         bPoseChannel *pchan;
1904         float vec[3];
1905         
1906         if (par->type!=OB_ARMATURE) {
1907                 unit_m4(mat);
1908                 return;
1909         }
1910         
1911         /* Make sure the bone is still valid */
1912         pchan= get_pose_channel(par->pose, ob->parsubstr);
1913         if (!pchan){
1914                 printf ("Object %s with Bone parent: bone %s doesn't exist\n", ob->id.name+2, ob->parsubstr);
1915                 unit_m4(mat);
1916                 return;
1917         }
1918
1919         /* get bone transform */
1920         copy_m4_m4(mat, pchan->pose_mat);
1921
1922         /* but for backwards compatibility, the child has to move to the tail */
1923         copy_v3_v3(vec, mat[1]);
1924         mul_v3_fl(vec, pchan->bone->length);
1925         add_v3_v3(mat[3], vec);
1926 }
1927
1928 static void give_parvert(Object *par, int nr, float *vec)
1929 {
1930         EditMesh *em;
1931         int a, count;
1932         
1933         vec[0]=vec[1]=vec[2]= 0.0f;
1934         
1935         if(par->type==OB_MESH) {
1936                 Mesh *me= par->data;
1937                 DerivedMesh *dm;
1938
1939                 em = BKE_mesh_get_editmesh(me);
1940                 dm = (em)? em->derivedFinal: par->derivedFinal;
1941                         
1942                 if(dm) {
1943                         MVert *mvert= dm->getVertArray(dm);
1944                         int *index = (int *)dm->getVertDataArray(dm, CD_ORIGINDEX);
1945                         int i, vindex, numVerts = dm->getNumVerts(dm);
1946
1947                         /* get the average of all verts with (original index == nr) */
1948                         count= 0;
1949                         for(i = 0; i < numVerts; i++) {
1950                                 vindex= (index)? index[i]: i;
1951
1952                                 if(vindex == nr) {
1953                                         add_v3_v3(vec, mvert[i].co);
1954                                         count++;
1955                                 }
1956                         }
1957
1958                         if (count==0) {
1959                                 /* keep as 0,0,0 */
1960                         } else if(count > 0) {
1961                                 mul_v3_fl(vec, 1.0f / count);
1962                         } else {
1963                                 /* use first index if its out of range */
1964                                 dm->getVertCo(dm, 0, vec);
1965                         }
1966                 }
1967
1968                 if(em)
1969                         BKE_mesh_end_editmesh(me, em);
1970         }
1971         else if (ELEM(par->type, OB_CURVE, OB_SURF)) {
1972                 Nurb *nu;
1973                 Curve *cu;
1974                 BPoint *bp;
1975                 BezTriple *bezt;
1976                 int found= 0;
1977                 ListBase *nurbs;
1978
1979                 cu= par->data;
1980                 nurbs= BKE_curve_nurbs(cu);
1981                 nu= nurbs->first;
1982
1983                 count= 0;
1984                 while(nu && !found) {
1985                         if(nu->type == CU_BEZIER) {
1986                                 bezt= nu->bezt;
1987                                 a= nu->pntsu;
1988                                 while(a--) {
1989                                         if(count==nr) {
1990                                                 found= 1;
1991                                                 VECCOPY(vec, bezt->vec[1]);
1992                                                 break;
1993                                         }
1994                                         count++;
1995                                         bezt++;
1996                                 }
1997                         }
1998                         else {
1999                                 bp= nu->bp;
2000                                 a= nu->pntsu*nu->pntsv;
2001                                 while(a--) {
2002                                         if(count==nr) {
2003                                                 found= 1;
2004                                                 memcpy(vec, bp->vec, sizeof(float)*3);
2005                                                 break;
2006                                         }
2007                                         count++;
2008                                         bp++;
2009                                 }
2010                         }
2011                         nu= nu->next;
2012                 }
2013
2014         }
2015         else if(par->type==OB_LATTICE) {
2016                 Lattice *latt= par->data;
2017                 BPoint *bp;
2018                 DispList *dl = find_displist(&par->disp, DL_VERTS);
2019                 float *co = dl?dl->verts:NULL;
2020                 
2021                 if(latt->editlatt) latt= latt->editlatt->latt;
2022                 
2023                 a= latt->pntsu*latt->pntsv*latt->pntsw;
2024                 count= 0;
2025                 bp= latt->def;
2026                 while(a--) {
2027                         if(count==nr) {
2028                                 if(co)
2029                                         memcpy(vec, co, 3*sizeof(float));
2030                                 else
2031                                         memcpy(vec, bp->vec, 3*sizeof(float));
2032                                 break;
2033                         }
2034                         count++;
2035                         if(co) co+= 3;
2036                         else bp++;
2037                 }
2038         }
2039 }
2040
2041 static void ob_parvert3(Object *ob, Object *par, float mat[][4])
2042 {
2043         float cmat[3][3], v1[3], v2[3], v3[3], q[4];
2044
2045         /* in local ob space */
2046         unit_m4(mat);
2047         
2048         if (ELEM4(par->type, OB_MESH, OB_SURF, OB_CURVE, OB_LATTICE)) {
2049                 
2050                 give_parvert(par, ob->par1, v1);
2051                 give_parvert(par, ob->par2, v2);
2052                 give_parvert(par, ob->par3, v3);
2053                                 
2054                 tri_to_quat( q,v1, v2, v3);
2055                 quat_to_mat3( cmat,q);
2056                 copy_m4_m3(mat, cmat);
2057                 
2058                 if(ob->type==OB_CURVE) {
2059                         VECCOPY(mat[3], v1);
2060                 }
2061                 else {
2062                         add_v3_v3v3(mat[3], v1, v2);
2063                         add_v3_v3(mat[3], v3);
2064                         mul_v3_fl(mat[3], 0.3333333f);
2065                 }
2066         }
2067 }
2068
2069 // XXX what the hell is this?
2070 static int no_parent_ipo=0;
2071 void set_no_parent_ipo(int val)
2072 {
2073         no_parent_ipo= val;
2074 }
2075
2076 void where_is_object_time(Scene *scene, Object *ob, float ctime)
2077 {
2078         float *fp1, *fp2, slowmat[4][4] = MAT4_UNITY;
2079         float stime=ctime, fac1, fac2;
2080         int a;
2081         
2082         /* new version: correct parent+vertexparent and track+parent */
2083         /* this one only calculates direct attached parent and track */
2084         /* is faster, but should keep track of timeoffs */
2085         
2086         if(ob==NULL) return;
2087         
2088         /* execute drivers only, as animation has already been done */
2089         BKE_animsys_evaluate_animdata(&ob->id, ob->adt, ctime, ADT_RECALC_DRIVERS);
2090         
2091         if(ob->parent) {
2092                 Object *par= ob->parent;
2093                 
2094                 // XXX depreceated - animsys
2095                 if(ob->ipoflag & OB_OFFS_PARENT) ctime-= give_timeoffset(ob);
2096                 
2097                 /* hurms, code below conflicts with depgraph... (ton) */
2098                 /* and even worse, it gives bad effects for NLA stride too (try ctime != par->ctime, with MBlur) */
2099                 if(no_parent_ipo==0 && stime != par->ctime) {
2100                         // only for ipo systems? 
2101                         Object tmp= *par;
2102                         
2103                         if(par->proxy_from);    // was a copied matrix, no where_is! bad...
2104                         else where_is_object_time(scene, par, ctime);
2105
2106                         solve_parenting(scene, ob, par, ob->obmat, slowmat, 0);
2107
2108                         *par= tmp;
2109                 }
2110                 else
2111                         solve_parenting(scene, ob, par, ob->obmat, slowmat, 0);
2112                 
2113                 if(ob->partype & PARSLOW) {
2114                         // include framerate
2115                         fac1= ( 1.0f / (1.0f + (float)fabs(give_timeoffset(ob))) );
2116                         if(fac1 >= 1.0f) return;
2117                         fac2= 1.0f-fac1;
2118                         
2119                         fp1= ob->obmat[0];
2120                         fp2= slowmat[0];
2121                         for(a=0; a<16; a++, fp1++, fp2++) {
2122                                 fp1[0]= fac1*fp1[0] + fac2*fp2[0];
2123                         }
2124                 }
2125         }
2126         else {
2127                 object_to_mat4(ob, ob->obmat);
2128         }
2129
2130         /* solve constraints */
2131         if (ob->constraints.first && !(ob->transflag & OB_NO_CONSTRAINTS)) {
2132                 bConstraintOb *cob;
2133                 
2134                 cob= constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2135                 
2136                 /* constraints need ctime, not stime. Some call where_is_object_time and bsystem_time */
2137                 solve_constraints (&ob->constraints, cob, ctime);
2138                 
2139                 constraints_clear_evalob(cob);
2140         }
2141         
2142         /* set negative scale flag in object */
2143         if(is_negative_m4(ob->obmat))   ob->transflag |= OB_NEG_SCALE;
2144         else                                                    ob->transflag &= ~OB_NEG_SCALE;
2145 }
2146
2147 /* get object transformation matrix without recalculating dependencies and
2148    constraints -- assume dependencies are already solved by depsgraph.
2149    no changes to object and it's parent would be done.
2150    used for bundles orientation in 3d space relative to parented blender camera */
2151 void where_is_object_mat(Scene *scene, Object *ob, float obmat[4][4])
2152 {
2153         float *fp1, *fp2, slowmat[4][4] = MAT4_UNITY;
2154         float fac1, fac2;
2155         int a;
2156
2157         if(ob->parent) {
2158                 Object *par= ob->parent;
2159
2160                 solve_parenting(scene, ob, par, obmat, slowmat, 1);
2161
2162                 if(ob->partype & PARSLOW) {
2163                         // include framerate
2164                         fac1= ( 1.0f / (1.0f + (float)fabs(give_timeoffset(ob))) );
2165                         if(fac1 >= 1.0f) return;
2166                         fac2= 1.0f-fac1;
2167
2168                         fp1= obmat[0];
2169                         fp2= slowmat[0];
2170                         for(a=0; a<16; a++, fp1++, fp2++) {
2171                                 fp1[0]= fac1*fp1[0] + fac2*fp2[0];
2172                         }
2173                 }
2174         }
2175         else {
2176                 object_to_mat4(ob, obmat);
2177         }
2178 }
2179
2180 static void solve_parenting (Scene *scene, Object *ob, Object *par, float obmat[][4], float slowmat[][4], int simul)
2181 {
2182         float totmat[4][4];
2183         float tmat[4][4];
2184         float locmat[4][4];
2185         float vec[3];
2186         int ok;
2187         
2188         object_to_mat4(ob, locmat);
2189         
2190         if(ob->partype & PARSLOW) copy_m4_m4(slowmat, obmat);
2191
2192         switch(ob->partype & PARTYPE) {
2193         case PAROBJECT:
2194                 ok= 0;
2195                 if(par->type==OB_CURVE) {
2196                         if( ((Curve *)par->data)->flag & CU_PATH ) {
2197                                 ob_parcurve(scene, ob, par, tmat);
2198                                 ok= 1;
2199                         }
2200                 }
2201                 
2202                 if(ok) mul_serie_m4(totmat, par->obmat, tmat, 
2203                         NULL, NULL, NULL, NULL, NULL, NULL);
2204                 else copy_m4_m4(totmat, par->obmat);
2205                 
2206                 break;
2207         case PARBONE:
2208                 ob_parbone(ob, par, tmat);
2209                 mul_serie_m4(totmat, par->obmat, tmat,         
2210                         NULL, NULL, NULL, NULL, NULL, NULL);
2211                 break;
2212                 
2213         case PARVERT1:
2214                 unit_m4(totmat);
2215                 if (simul){
2216                         VECCOPY(totmat[3], par->obmat[3]);
2217                 }
2218                 else{
2219                         give_parvert(par, ob->par1, vec);
2220                         mul_v3_m4v3(totmat[3], par->obmat, vec);
2221                 }
2222                 break;
2223         case PARVERT3:
2224                 ob_parvert3(ob, par, tmat);
2225                 
2226                 mul_serie_m4(totmat, par->obmat, tmat,         
2227                         NULL, NULL, NULL, NULL, NULL, NULL);
2228                 break;
2229                 
2230         case PARSKEL:
2231                 copy_m4_m4(totmat, par->obmat);
2232                 break;
2233         }
2234         
2235         // total 
2236         mul_serie_m4(tmat, totmat, ob->parentinv,         
2237                 NULL, NULL, NULL, NULL, NULL, NULL);
2238         mul_serie_m4(obmat, tmat, locmat,         
2239                 NULL, NULL, NULL, NULL, NULL, NULL);
2240         
2241         if (simul) {
2242
2243         }
2244         else{
2245                 // external usable originmat 
2246                 copy_m3_m4(originmat, tmat);
2247                 
2248                 // origin, voor help line
2249                 if( (ob->partype & PARTYPE)==PARSKEL ) {
2250                         VECCOPY(ob->orig, par->obmat[3]);
2251                 }
2252                 else {
2253                         VECCOPY(ob->orig, totmat[3]);
2254                 }
2255         }
2256
2257 }
2258
2259 void where_is_object(struct Scene *scene, Object *ob)
2260 {
2261         where_is_object_time(scene, ob, (float)scene->r.cfra);
2262 }
2263
2264
2265 void where_is_object_simul(Scene *scene, Object *ob)
2266 /* was written for the old game engine (until 2.04) */
2267 /* It seems that this function is only called
2268 for a lamp that is the child of another object */
2269 {
2270         Object *par;
2271         //Ipo *ipo;
2272         float *fp1, *fp2;
2273         float slowmat[4][4];
2274         float fac1, fac2;
2275         int a;
2276         
2277         /* NO TIMEOFFS */
2278         if(ob->parent) {
2279                 par= ob->parent;
2280                 
2281                 solve_parenting(scene, ob, par, ob->obmat, slowmat, 1);
2282
2283                 if(ob->partype & PARSLOW) {
2284
2285                         fac1= (float)(1.0/(1.0+ fabs(give_timeoffset(ob))));
2286                         fac2= 1.0f-fac1;
2287                         fp1= ob->obmat[0];
2288                         fp2= slowmat[0];
2289                         for(a=0; a<16; a++, fp1++, fp2++) {
2290                                 fp1[0]= fac1*fp1[0] + fac2*fp2[0];
2291                         }
2292                 }
2293                 
2294         }
2295         else {
2296                 object_to_mat4(ob, ob->obmat);
2297         }
2298         
2299         /* solve constraints */
2300         if (ob->constraints.first) {
2301                 bConstraintOb *cob;
2302                 
2303                 cob= constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2304                 solve_constraints(&ob->constraints, cob, (float)scene->r.cfra);
2305                 constraints_clear_evalob(cob);
2306         }
2307 }
2308
2309 /* for calculation of the inverse parent transform, only used for editor */
2310 void what_does_parent(Scene *scene, Object *ob, Object *workob)
2311 {
2312         clear_workob(workob);
2313         
2314         unit_m4(workob->obmat);
2315         unit_m4(workob->parentinv);
2316         unit_m4(workob->constinv);
2317         workob->parent= ob->parent;
2318
2319         workob->trackflag= ob->trackflag;
2320         workob->upflag= ob->upflag;
2321         
2322         workob->partype= ob->partype;
2323         workob->par1= ob->par1;
2324         workob->par2= ob->par2;
2325         workob->par3= ob->par3;
2326
2327         workob->constraints.first = ob->constraints.first;
2328         workob->constraints.last = ob->constraints.last;
2329
2330         BLI_strncpy(workob->parsubstr, ob->parsubstr, sizeof(workob->parsubstr));
2331
2332         where_is_object(scene, workob);
2333 }
2334
2335 BoundBox *unit_boundbox(void)
2336 {
2337         BoundBox *bb;
2338         float min[3] = {-1.0f,-1.0f,-1.0f}, max[3] = {-1.0f,-1.0f,-1.0f};
2339
2340         bb= MEM_callocN(sizeof(BoundBox), "bb");
2341         boundbox_set_from_min_max(bb, min, max);
2342         
2343         return bb;
2344 }
2345
2346 void boundbox_set_from_min_max(BoundBox *bb, float min[3], float max[3])
2347 {
2348         bb->vec[0][0]=bb->vec[1][0]=bb->vec[2][0]=bb->vec[3][0]= min[0];
2349         bb->vec[4][0]=bb->vec[5][0]=bb->vec[6][0]=bb->vec[7][0]= max[0];
2350         
2351         bb->vec[0][1]=bb->vec[1][1]=bb->vec[4][1]=bb->vec[5][1]= min[1];
2352         bb->vec[2][1]=bb->vec[3][1]=bb->vec[6][1]=bb->vec[7][1]= max[1];
2353
2354         bb->vec[0][2]=bb->vec[3][2]=bb->vec[4][2]=bb->vec[7][2]= min[2];
2355         bb->vec[1][2]=bb->vec[2][2]=bb->vec[5][2]=bb->vec[6][2]= max[2];
2356 }
2357
2358 BoundBox *object_get_boundbox(Object *ob)
2359 {
2360         BoundBox *bb= NULL;
2361         
2362         if(ob->type==OB_MESH) {
2363                 bb = mesh_get_bb(ob);
2364         }
2365         else if (ELEM3(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2366                 bb= ob->bb ? ob->bb : ( (Curve *)ob->data )->bb;
2367         }
2368         else if(ob->type==OB_MBALL) {
2369                 bb= ob->bb;
2370         }
2371         return bb;
2372 }
2373
2374 /* used to temporally disable/enable boundbox */
2375 void object_boundbox_flag(Object *ob, int flag, int set)
2376 {
2377         BoundBox *bb= object_get_boundbox(ob);
2378         if(bb) {
2379                 if(set) bb->flag |= flag;
2380                 else bb->flag &= ~flag;
2381         }
2382 }
2383
2384 void object_get_dimensions(Object *ob, float *value)
2385 {
2386         BoundBox *bb = NULL;
2387         
2388         bb= object_get_boundbox(ob);
2389         if (bb) {
2390                 float scale[3];
2391                 
2392                 mat4_to_size( scale,ob->obmat);
2393                 
2394                 value[0] = fabsf(scale[0]) * (bb->vec[4][0] - bb->vec[0][0]);
2395                 value[1] = fabsf(scale[1]) * (bb->vec[2][1] - bb->vec[0][1]);
2396                 value[2] = fabsf(scale[2]) * (bb->vec[1][2] - bb->vec[0][2]);
2397         } else {
2398                 value[0] = value[1] = value[2] = 0.f;
2399         }
2400 }
2401
2402 void object_set_dimensions(Object *ob, const float *value)
2403 {
2404         BoundBox *bb = NULL;
2405         
2406         bb= object_get_boundbox(ob);
2407         if (bb) {
2408                 float scale[3], len[3];
2409                 
2410                 mat4_to_size( scale,ob->obmat);
2411                 
2412                 len[0] = bb->vec[4][0] - bb->vec[0][0];
2413                 len[1] = bb->vec[2][1] - bb->vec[0][1];
2414                 len[2] = bb->vec[1][2] - bb->vec[0][2];
2415                 
2416                 if (len[0] > 0.f) ob->size[0] = value[0] / len[0];
2417                 if (len[1] > 0.f) ob->size[1] = value[1] / len[1];
2418                 if (len[2] > 0.f) ob->size[2] = value[2] / len[2];
2419         }
2420 }
2421
2422 void minmax_object(Object *ob, float *min, float *max)
2423 {
2424         BoundBox bb;
2425         float vec[3];
2426         int a;
2427         short change= FALSE;
2428         
2429         switch(ob->type) {
2430         case OB_CURVE:
2431         case OB_FONT:
2432         case OB_SURF:
2433                 {
2434                         Curve *cu= ob->data;
2435
2436                         if(cu->bb==NULL) tex_space_curve(cu);
2437                         bb= *(cu->bb);
2438
2439                         for(a=0; a<8; a++) {
2440                                 mul_m4_v3(ob->obmat, bb.vec[a]);
2441                                 DO_MINMAX(bb.vec[a], min, max);
2442                         }
2443                         change= TRUE;
2444                 }
2445                 break;
2446         case OB_LATTICE:
2447                 {
2448                         Lattice *lt= ob->data;
2449                         BPoint *bp= lt->def;
2450                         int u, v, w;
2451
2452                         for(w=0; w<lt->pntsw; w++) {
2453                                 for(v=0; v<lt->pntsv; v++) {
2454                                         for(u=0; u<lt->pntsu; u++, bp++) {
2455                                                 mul_v3_m4v3(vec, ob->obmat, bp->vec);
2456                                                 DO_MINMAX(vec, min, max);
2457                                         }
2458                                 }
2459                         }
2460                         change= TRUE;
2461                 }
2462                 break;
2463         case OB_ARMATURE:
2464                 if(ob->pose) {
2465                         bPoseChannel *pchan;
2466                         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2467                                 mul_v3_m4v3(vec, ob->obmat, pchan->pose_head);
2468                                 DO_MINMAX(vec, min, max);
2469                                 mul_v3_m4v3(vec, ob->obmat, pchan->pose_tail);
2470                                 DO_MINMAX(vec, min, max);
2471                         }
2472                         change= TRUE;
2473                 }
2474                 break;
2475         case OB_MESH:
2476                 {
2477                         Mesh *me= get_mesh(ob);
2478
2479                         if(me) {
2480                                 bb = *mesh_get_bb(ob);
2481
2482                                 for(a=0; a<8; a++) {
2483                                         mul_m4_v3(ob->obmat, bb.vec[a]);
2484                                         DO_MINMAX(bb.vec[a], min, max);
2485                                 }
2486                                 change= TRUE;
2487                         }
2488                 }
2489                 break;
2490         }
2491
2492         if(change == FALSE) {
2493                 DO_MINMAX(ob->obmat[3], min, max);
2494
2495                 copy_v3_v3(vec, ob->obmat[3]);
2496                 add_v3_v3(vec, ob->size);
2497                 DO_MINMAX(vec, min, max);
2498
2499                 copy_v3_v3(vec, ob->obmat[3]);
2500                 sub_v3_v3(vec, ob->size);
2501                 DO_MINMAX(vec, min, max);
2502         }
2503 }
2504
2505 int minmax_object_duplis(Scene *scene, Object *ob, float *min, float *max)
2506 {
2507         int ok= 0;
2508         if ((ob->transflag & OB_DUPLI)==0) {
2509                 return ok;
2510         } else {
2511                 ListBase *lb;
2512                 DupliObject *dob;
2513                 
2514                 lb= object_duplilist(scene, ob);
2515                 for(dob= lb->first; dob; dob= dob->next) {
2516                         if(dob->no_draw == 0) {
2517                                 BoundBox *bb= object_get_boundbox(dob->ob);
2518
2519                                 if(bb) {
2520                                         int i;
2521                                         for(i=0; i<8; i++) {
2522                                                 float vec[3];
2523                                                 mul_v3_m4v3(vec, dob->mat, bb->vec[i]);
2524                                                 DO_MINMAX(vec, min, max);
2525                                         }
2526
2527                                         ok= 1;
2528                                 }
2529                         }
2530                 }
2531                 free_object_duplilist(lb);      /* does restore */
2532         }
2533
2534         return ok;
2535 }
2536
2537 /* copied from DNA_object_types.h */
2538 typedef struct ObTfmBack {
2539         float loc[3], dloc[3], orig[3];
2540         float size[3], dsize[3];        /* scale and delta scale */
2541         float rot[3], drot[3];          /* euler rotation */
2542         float quat[4], dquat[4];        /* quaternion rotation */
2543         float rotAxis[3], drotAxis[3];  /* axis angle rotation - axis part */
2544         float rotAngle, drotAngle;      /* axis angle rotation - angle part */
2545         float obmat[4][4];              /* final worldspace matrix with constraints & animsys applied */
2546         float parentinv[4][4]; /* inverse result of parent, so that object doesn't 'stick' to parent */
2547         float constinv[4][4]; /* inverse result of constraints. doesn't include effect of parent or object local transform */
2548         float imat[4][4];       /* inverse matrix of 'obmat' for during render, old game engine, temporally: ipokeys of transform  */
2549 } ObTfmBack;
2550
2551 void *object_tfm_backup(Object *ob)
2552 {
2553         ObTfmBack *obtfm= MEM_mallocN(sizeof(ObTfmBack), "ObTfmBack");
2554         copy_v3_v3(obtfm->loc, ob->loc);
2555         copy_v3_v3(obtfm->dloc, ob->dloc);
2556         copy_v3_v3(obtfm->orig, ob->orig);
2557         copy_v3_v3(obtfm->size, ob->size);
2558         copy_v3_v3(obtfm->dsize, ob->dsize);
2559         copy_v3_v3(obtfm->rot, ob->rot);
2560         copy_v3_v3(obtfm->drot, ob->drot);
2561         copy_qt_qt(obtfm->quat, ob->quat);
2562         copy_qt_qt(obtfm->dquat, ob->dquat);
2563         copy_v3_v3(obtfm->rotAxis, ob->rotAxis);
2564         copy_v3_v3(obtfm->drotAxis, ob->drotAxis);
2565         obtfm->rotAngle= ob->rotAngle;
2566         obtfm->drotAngle= ob->drotAngle;
2567         copy_m4_m4(obtfm->obmat, ob->obmat);
2568         copy_m4_m4(obtfm->parentinv, ob->parentinv);
2569         copy_m4_m4(obtfm->constinv, ob->constinv);
2570         copy_m4_m4(obtfm->imat, ob->imat);
2571
2572         return (void *)obtfm;
2573 }
2574
2575 void object_tfm_restore(Object *ob, void *obtfm_pt)
2576 {
2577         ObTfmBack *obtfm= (ObTfmBack *)obtfm_pt;
2578         copy_v3_v3(ob->loc, obtfm->loc);
2579         copy_v3_v3(ob->dloc, obtfm->dloc);
2580         copy_v3_v3(ob->orig, obtfm->orig);
2581         copy_v3_v3(ob->size, obtfm->size);
2582         copy_v3_v3(ob->dsize, obtfm->dsize);
2583         copy_v3_v3(ob->rot, obtfm->rot);
2584         copy_v3_v3(ob->drot, obtfm->drot);
2585         copy_qt_qt(ob->quat, obtfm->quat);
2586         copy_qt_qt(ob->dquat, obtfm->dquat);
2587         copy_v3_v3(ob->rotAxis, obtfm->rotAxis);
2588         copy_v3_v3(ob->drotAxis, obtfm->drotAxis);
2589         ob->rotAngle= obtfm->rotAngle;
2590         ob->drotAngle= obtfm->drotAngle;
2591         copy_m4_m4(ob->obmat, obtfm->obmat);
2592         copy_m4_m4(ob->parentinv, obtfm->parentinv);
2593         copy_m4_m4(ob->constinv, obtfm->constinv);
2594         copy_m4_m4(ob->imat, obtfm->imat);
2595 }
2596
2597 /* proxy rule: lib_object->proxy_from == the one we borrow from, only set temporal and cleared here */
2598 /*           local_object->proxy      == pointer to library object, saved in files and read */
2599
2600 /* function below is polluted with proxy exceptions, cleanup will follow! */
2601
2602 /* the main object update call, for object matrix, constraints, keys and displist (modifiers) */
2603 /* requires flags to be set! */
2604 void object_handle_update(Scene *scene, Object *ob)
2605 {
2606         if(ob->recalc & OB_RECALC_ALL) {
2607                 /* speed optimization for animation lookups */
2608                 if(ob->pose)
2609                         make_pose_channels_hash(ob->pose);
2610
2611                 if(ob->recalc & OB_RECALC_DATA) {
2612                         if(ob->type==OB_ARMATURE) {
2613                                 /* this happens for reading old files and to match library armatures
2614                                    with poses we do it ahead of where_is_object to ensure animation
2615                                    is evaluated on the rebuilt pose, otherwise we get incorrect poses
2616                                    on file load */
2617                                 if(ob->pose==NULL || (ob->pose->flag & POSE_RECALC))
2618                                         armature_rebuild_pose(ob, ob->data);
2619                         }
2620                 }
2621
2622                 /* XXX new animsys warning: depsgraph tag OB_RECALC_DATA should not skip drivers, 
2623                    which is only in where_is_object now */
2624                 // XXX: should this case be OB_RECALC_OB instead?
2625                 if(ob->recalc & OB_RECALC_ALL) {
2626                         
2627                         if (G.f & G_DEBUG)
2628                                 printf("recalcob %s\n", ob->id.name+2);
2629                         
2630                         /* handle proxy copy for target */
2631                         if(ob->id.lib && ob->proxy_from) {
2632                                 // printf("ob proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2633                                 if(ob->proxy_from->proxy_group) {/* transform proxy into group space */
2634                                         Object *obg= ob->proxy_from->proxy_group;
2635                                         invert_m4_m4(obg->imat, obg->obmat);
2636                                         mul_m4_m4m4(ob->obmat, ob->proxy_from->obmat, obg->imat);
2637                                         if(obg->dup_group) { /* should always be true */
2638                                                 add_v3_v3(ob->obmat[3], obg->dup_group->dupli_ofs);
2639                                         }
2640                                 }
2641                                 else
2642                                         copy_m4_m4(ob->obmat, ob->proxy_from->obmat);
2643                         }
2644                         else
2645                                 where_is_object(scene, ob);
2646                 }
2647                 
2648                 if(ob->recalc & OB_RECALC_DATA) {
2649                         ID *data_id= (ID *)ob->data;
2650                         AnimData *adt= BKE_animdata_from_id(data_id);
2651                         float ctime= (float)scene->r.cfra; // XXX this is bad...
2652                         ListBase pidlist;
2653                         PTCacheID *pid;
2654                         
2655                         if (G.f & G_DEBUG)
2656                                 printf("recalcdata %s\n", ob->id.name+2);
2657
2658                         if(adt) {
2659                                 /* evaluate drivers */
2660                                 // XXX: for mesh types, should we push this to derivedmesh instead?
2661                                 BKE_animsys_evaluate_animdata(data_id, adt, ctime, ADT_RECALC_DRIVERS);
2662                         }
2663
2664                         /* includes all keys and modifiers */
2665                         switch(ob->type) {
2666                         case OB_MESH:
2667                                 {
2668 #if 0                           // XXX, comment for 2.56a release, background wont set 'scene->customdata_mask'
2669                                         EditMesh *em = (ob == scene->obedit)? BKE_mesh_get_editmesh(ob->data): NULL;
2670                                         BLI_assert((scene->customdata_mask & CD_MASK_BAREMESH) == CD_MASK_BAREMESH);
2671                                         if(em) {
2672                                                 makeDerivedMesh(scene, ob, em,  scene->customdata_mask); /* was CD_MASK_BAREMESH */
2673                                                 BKE_mesh_end_editmesh(ob->data, em);
2674                                         } else
2675                                                 makeDerivedMesh(scene, ob, NULL, scene->customdata_mask);
2676
2677 #else                           /* ensure CD_MASK_BAREMESH for now */
2678                                         EditMesh *em = (ob == scene->obedit)? BKE_mesh_get_editmesh(ob->data): NULL;
2679                                         unsigned int data_mask= scene->customdata_mask | ob->customdata_mask | CD_MASK_BAREMESH;
2680                                         if(em) {
2681                                                 makeDerivedMesh(scene, ob, em,  data_mask); /* was CD_MASK_BAREMESH */
2682                                                 BKE_mesh_end_editmesh(ob->data, em);
2683                                         } else
2684                                                 makeDerivedMesh(scene, ob, NULL, data_mask);
2685 #endif
2686
2687                                 }
2688                                 break;
2689
2690                         case OB_ARMATURE:
2691                                 if(ob->id.lib && ob->proxy_from) {
2692                                         // printf("pose proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2693                                         copy_pose_result(ob->pose, ob->proxy_from->pose);
2694                                 }
2695                                 else {
2696                                         where_is_pose(scene, ob);
2697                                 }
2698                                 break;
2699
2700                         case OB_MBALL:
2701                                 makeDispListMBall(scene, ob);
2702                                 break;
2703
2704                         case OB_CURVE:
2705                         case OB_SURF:
2706                         case OB_FONT:
2707                                 makeDispListCurveTypes(scene, ob, 0);
2708                                 break;
2709                                 
2710                         case OB_LATTICE:
2711                                 lattice_calc_modifiers(scene, ob);
2712                                 break;
2713                         }
2714
2715
2716                         if(ob->particlesystem.first) {
2717                                 ParticleSystem *tpsys, *psys;
2718                                 DerivedMesh *dm;
2719                                 ob->transflag &= ~OB_DUPLIPARTS;
2720                                 
2721                                 psys= ob->particlesystem.first;
2722                                 while(psys) {
2723                                         if(psys_check_enabled(ob, psys)) {
2724                                                 /* check use of dupli objects here */
2725                                                 if(psys->part && (psys->part->draw_as == PART_DRAW_REND || G.rendering) &&
2726                                                         ((psys->part->ren_as == PART_DRAW_OB && psys->part->dup_ob)
2727                                                         || (psys->part->ren_as == PART_DRAW_GR && psys->part->dup_group)))
2728                                                         ob->transflag |= OB_DUPLIPARTS;
2729
2730                                                 particle_system_update(scene, ob, psys);
2731                                                 psys= psys->next;
2732                                         }
2733                                         else if(psys->flag & PSYS_DELETE) {
2734                                                 tpsys=psys->next;
2735                                                 BLI_remlink(&ob->particlesystem, psys);
2736                                                 psys_free(ob,psys);
2737                                                 psys= tpsys;
2738                                         }
2739                                         else
2740                                                 psys= psys->next;
2741                                 }
2742
2743                                 if(G.rendering && ob->transflag & OB_DUPLIPARTS) {
2744                                         /* this is to make sure we get render level duplis in groups:
2745                                          * the derivedmesh must be created before init_render_mesh,
2746                                          * since object_duplilist does dupliparticles before that */
2747                                         dm = mesh_create_derived_render(scene, ob, CD_MASK_BAREMESH|CD_MASK_MTFACE|CD_MASK_MCOL);
2748                                         dm->release(dm);
2749
2750                                         for(psys=ob->particlesystem.first; psys; psys=psys->next)
2751                                                 psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated;
2752                                 }
2753                         }
2754
2755                         /* check if quick cache is needed */
2756                         BKE_ptcache_ids_from_object(&pidlist, ob, scene, MAX_DUPLI_RECUR);
2757
2758                         for(pid=pidlist.first; pid; pid=pid->next) {
2759                                 if((pid->cache->flag & PTCACHE_BAKED)
2760                                         || (pid->cache->flag & PTCACHE_QUICK_CACHE)==0)
2761                                         continue;
2762
2763                                 if(pid->cache->flag & PTCACHE_OUTDATED || (pid->cache->flag & PTCACHE_SIMULATION_VALID)==0) {
2764                                         scene->physics_settings.quick_cache_step =
2765                                                 scene->physics_settings.quick_cache_step ?
2766                                                 MIN2(scene->physics_settings.quick_cache_step, pid->cache->step) :
2767                                                 pid->cache->step;
2768                                 }
2769                         }
2770
2771                         BLI_freelistN(&pidlist);
2772                 }
2773
2774                 /* the no-group proxy case, we call update */
2775                 if(ob->proxy && ob->proxy_group==NULL) {
2776                         /* set pointer in library proxy target, for copying, but restore it */
2777                         ob->proxy->proxy_from= ob;
2778                         // printf("call update, lib ob %s proxy %s\n", ob->proxy->id.name, ob->id.name);
2779                         object_handle_update(scene, ob->proxy);
2780                 }
2781         
2782                 ob->recalc &= ~OB_RECALC_ALL;
2783         }
2784
2785         /* the case when this is a group proxy, object_update is called in group.c */
2786         if(ob->proxy) {
2787                 ob->proxy->proxy_from= ob;
2788                 // printf("set proxy pointer for later group stuff %s\n", ob->id.name);
2789         }
2790 }
2791
2792 float give_timeoffset(Object *ob) {
2793         if ((ob->ipoflag & OB_OFFS_PARENTADD) && ob->parent) {
2794                 return ob->sf + give_timeoffset(ob->parent);
2795         } else {
2796                 return ob->sf;
2797         }
2798 }
2799
2800 int give_obdata_texspace(Object *ob, short **texflag, float **loc, float **size, float **rot) {
2801         
2802         if (ob->data==NULL)
2803                 return 0;
2804         
2805         switch (GS(((ID *)ob->data)->name)) {
2806         case ID_ME:
2807         {
2808                 Mesh *me= ob->data;
2809                 if (texflag)    *texflag = &me->texflag;
2810                 if (loc)                *loc = me->loc;
2811                 if (size)               *size = me->size;
2812                 if (rot)                *rot = me->rot;
2813                 break;
2814         }
2815         case ID_CU:
2816         {
2817                 Curve *cu= ob->data;
2818                 if (texflag)    *texflag = &cu->texflag;
2819                 if (loc)                *loc = cu->loc;
2820                 if (size)               *size = cu->size;
2821                 if (rot)                *rot = cu->rot;
2822                 break;
2823         }
2824         case ID_MB:
2825         {
2826                 MetaBall *mb= ob->data;
2827                 if (texflag)    *texflag = &mb->texflag;
2828                 if (loc)                *loc = mb->loc;
2829                 if (size)               *size = mb->size;
2830                 if (rot)                *rot = mb->rot;
2831                 break;
2832         }
2833         default:
2834                 return 0;
2835         }
2836         return 1;
2837 }
2838
2839 /*
2840  * Test a bounding box for ray intersection
2841  * assumes the ray is already local to the boundbox space
2842  */
2843 int ray_hit_boundbox(struct BoundBox *bb, float ray_start[3], float ray_normal[3])
2844 {
2845         static int triangle_indexes[12][3] = {{0, 1, 2}, {0, 2, 3},
2846                                                                                   {3, 2, 6}, {3, 6, 7},
2847                                                                                   {1, 2, 6}, {1, 6, 5}, 
2848                                                                                   {5, 6, 7}, {4, 5, 7},
2849                                                                                   {0, 3, 7}, {0, 4, 7},
2850                                                                                   {0, 1, 5}, {0, 4, 5}};
2851         int result = 0;
2852         int i;
2853         
2854         for (i = 0; i < 12 && result == 0; i++)
2855         {
2856                 float lambda;
2857                 int v1, v2, v3;
2858                 v1 = triangle_indexes[i][0];
2859                 v2 = triangle_indexes[i][1];
2860                 v3 = triangle_indexes[i][2];
2861                 result = isect_ray_tri_v3(ray_start, ray_normal, bb->vec[v1], bb->vec[v2], bb->vec[v3], &lambda, NULL);
2862         }
2863         
2864         return result;
2865 }
2866
2867 static int pc_cmp(void *a, void *b)
2868 {
2869         LinkData *ad = a, *bd = b;
2870         if(GET_INT_FROM_POINTER(ad->data) > GET_INT_FROM_POINTER(bd->data))
2871                 return 1;
2872         else return 0;
2873 }
2874
2875 int object_insert_ptcache(Object *ob) 
2876 {
2877         LinkData *link = NULL;
2878         int i = 0;
2879
2880         BLI_sortlist(&ob->pc_ids, pc_cmp);
2881
2882         for(link=ob->pc_ids.first, i = 0; link; link=link->next, i++) 
2883         {
2884                 int index = GET_INT_FROM_POINTER(link->data);
2885
2886                 if(i < index)
2887                         break;
2888         }
2889
2890         link = MEM_callocN(sizeof(LinkData), "PCLink");
2891         link->data = SET_INT_IN_POINTER(i);
2892         BLI_addtail(&ob->pc_ids, link);
2893
2894         return i;
2895 }
2896
2897 void object_camera_mode(RenderData *rd, Object *camera)
2898 {
2899         rd->mode &= ~(R_ORTHO|R_PANORAMA);
2900         if(camera && camera->type==OB_CAMERA) {
2901                 Camera *cam= camera->data;
2902                 if(cam->type == CAM_ORTHO) rd->mode |= R_ORTHO;
2903                 if(cam->flag & CAM_PANORAMA) rd->mode |= R_PANORAMA;
2904         }
2905 }
2906
2907 /* 'lens' may be set for envmap only */
2908 void object_camera_matrix(
2909                 RenderData *rd, Object *camera, int winx, int winy, short field_second,
2910                 float winmat[][4], rctf *viewplane, float *clipsta, float *clipend, float *lens, float *sensor_x, float *ycor,
2911                 float *viewdx, float *viewdy
2912 ) {
2913         Camera *cam=NULL;
2914         float pixsize;
2915         float shiftx=0.0, shifty=0.0, winside, viewfac;
2916         short is_ortho= FALSE;
2917
2918         /* question mark */
2919         (*ycor)= rd->yasp / rd->xasp;
2920         if(rd->mode & R_FIELDS)
2921                 (*ycor) *= 2.0f;
2922
2923         if(camera->type==OB_CAMERA) {
2924                 cam= camera->data;
2925
2926                 if(cam->type == CAM_ORTHO) {
2927                         is_ortho= TRUE;
2928                 }
2929
2930                 /* solve this too... all time depending stuff is in convertblender.c?
2931                  * Need to update the camera early because it's used for projection matrices
2932                  * and other stuff BEFORE the animation update loop is done
2933                  * */
2934 #if 0 // XXX old animation system
2935                 if(cam->ipo) {
2936                         calc_ipo(cam->ipo, frame_to_float(re->scene, re->r.cfra));
2937                         execute_ipo(&cam->id, cam->ipo);
2938                 }
2939 #endif // XXX old animation system
2940                 shiftx=cam->shiftx;
2941                 shifty=cam->shifty;
2942                 (*lens)= cam->lens;
2943                 (*sensor_x)= cam->sensor_x;
2944                 (*clipsta)= cam->clipsta;
2945                 (*clipend)= cam->clipend;
2946         }
2947         else if(camera->type==OB_LAMP) {
2948                 Lamp *la= camera->data;
2949                 float fac= cosf((float)M_PI*la->spotsize/360.0f);
2950                 float phi= acos(fac);
2951
2952                 (*lens)= 16.0f*fac/sinf(phi);
2953                 if((*lens)==0.0f)
2954                         (*lens)= 35.0f;
2955                 (*clipsta)= la->clipsta;
2956                 (*clipend)= la->clipend;
2957         }
2958         else {  /* envmap exception... */;
2959                 if((*lens)==0.0f) /* is this needed anymore? */
2960                         (*lens)= 16.0f;
2961
2962                 if((*clipsta)==0.0f || (*clipend)==0.0f) {
2963                         (*clipsta)= 0.1f;
2964                         (*clipend)= 1000.0f;
2965                 }
2966         }
2967
2968         /* ortho only with camera available */
2969         if(cam && is_ortho) {
2970                 if(rd->xasp*winx >= rd->yasp*winy) {
2971                         viewfac= winx;
2972                 }
2973                 else {
2974                         viewfac= (*ycor) * winy;
2975                 }
2976                 /* ortho_scale == 1.0 means exact 1 to 1 mapping */
2977                 pixsize= cam->ortho_scale/viewfac;
2978         }
2979         else {
2980                 if(rd->xasp*winx >= rd->yasp*winy)      viewfac= ((*lens) * winx) / (*sensor_x);
2981                 else                                    viewfac= (*ycor) * ((*lens) * winy) / (*sensor_x);
2982                 pixsize= (*clipsta) / viewfac;
2983         }
2984
2985         /* viewplane fully centered, zbuffer fills in jittered between -.5 and +.5 */
2986         winside= MAX2(winx, winy);
2987         viewplane->xmin= -0.5f*(float)winx + shiftx*winside;
2988         viewplane->ymin= -0.5f*(*ycor)*(float)winy + shifty*winside;
2989         viewplane->xmax=  0.5f*(float)winx + shiftx*winside;
2990         viewplane->ymax=  0.5f*(*ycor)*(float)winy + shifty*winside;
2991
2992         if(field_second) {
2993                 if(rd->mode & R_ODDFIELD) {
2994                         viewplane->ymin-= 0.5f * (*ycor);
2995                         viewplane->ymax-= 0.5f * (*ycor);
2996                 }
2997                 else {
2998                         viewplane->ymin+= 0.5f * (*ycor);
2999                         viewplane->ymax+= 0.5f * (*ycor);
3000                 }
3001         }
3002         /* the window matrix is used for clipping, and not changed during OSA steps */
3003         /* using an offset of +0.5 here would give clip errors on edges */
3004         viewplane->xmin *= pixsize;
3005         viewplane->xmax *= pixsize;
3006         viewplane->ymin *= pixsize;
3007         viewplane->ymax *= pixsize;
3008
3009         (*viewdx)= pixsize;
3010         (*viewdy)= (*ycor) * pixsize;
3011
3012         if(is_ortho)
3013                 orthographic_m4(winmat, viewplane->xmin, viewplane->xmax, viewplane->ymin, viewplane->ymax, *clipsta, *clipend);
3014         else
3015                 perspective_m4(winmat, viewplane->xmin, viewplane->xmax, viewplane->ymin, viewplane->ymax, *clipsta, *clipend);
3016
3017 }
3018
3019 #if 0
3020 static int pc_findindex(ListBase *listbase, int index)
3021 {
3022         LinkData *link= NULL;
3023         int number= 0;
3024         
3025         if (listbase == NULL) return -1;
3026         
3027         link= listbase->first;
3028         while (link) {
3029                 if ((int)link->data == index)
3030                         return number;
3031                 
3032                 number++;
3033                 link= link->next;
3034         }
3035         
3036         return -1;
3037 }
3038
3039 void object_delete_ptcache(Object *ob, int index) 
3040 {
3041         int list_index = pc_findindex(&ob->pc_ids, index);
3042         LinkData *link = BLI_findlink(&ob->pc_ids, list_index);
3043         BLI_freelinkN(&ob->pc_ids, link);
3044 }
3045 #endif
3046
3047 /* shape key utility function */
3048
3049 /************************* Mesh ************************/
3050 static KeyBlock *insert_meshkey(Scene *scene, Object *ob, const char *name, int from_mix)
3051 {
3052         Mesh *me= ob->data;
3053         Key *key= me->key;
3054         KeyBlock *kb;
3055         int newkey= 0;
3056
3057         if(key == NULL) {
3058                 key= me->key= add_key((ID *)me);
3059                 key->type= KEY_RELATIVE;
3060                 newkey= 1;
3061         }
3062
3063         if(newkey || from_mix==FALSE) {
3064                 /* create from mesh */
3065                 kb= add_keyblock(key, name);
3066                 mesh_to_key(me, kb);
3067         }
3068         else {
3069                 /* copy from current values */
3070                 float *data= do_ob_key(scene, ob);
3071
3072                 /* create new block with prepared data */
3073                 kb= add_keyblock(key, name);
3074                 kb->data= data;
3075                 kb->totelem= me->totvert;
3076         }
3077
3078         return kb;
3079 }
3080 /************************* Lattice ************************/
3081 static KeyBlock *insert_lattkey(Scene *scene, Object *ob, const char *name, int from_mix)
3082 {
3083         Lattice *lt= ob->data;
3084         Key *key= lt->key;
3085         KeyBlock *kb;
3086         int newkey= 0;
3087
3088         if(key==NULL) {
3089                 key= lt->key= add_key( (ID *)lt);
3090                 key->type= KEY_RELATIVE;
3091                 newkey= 1;
3092         }
3093
3094         if(newkey || from_mix==FALSE) {
3095                 kb= add_keyblock(key, name);
3096                 if (!newkey) {
3097                         KeyBlock *basekb= (KeyBlock *)key->block.first;
3098                         kb->data= MEM_dupallocN(basekb->data);
3099                         kb->totelem= basekb->totelem;
3100                 }
3101                 else {
3102                         latt_to_key(lt, kb);
3103                 }
3104         }
3105         else {
3106                 /* copy from current values */
3107                 float *data= do_ob_key(scene, ob);
3108
3109                 /* create new block with prepared data */
3110                 kb= add_keyblock(key, name);
3111                 kb->totelem= lt->pntsu*lt->pntsv*lt->pntsw;
3112                 kb->data= data;
3113         }
3114
3115         return kb;
3116 }
3117 /************************* Curve ************************/
3118 static KeyBlock *insert_curvekey(Scene *scene, Object *ob, const char *name, int from_mix)
3119 {
3120         Curve *cu= ob->data;
3121         Key *key= cu->key;
3122         KeyBlock *kb;
3123         ListBase *lb= BKE_curve_nurbs(cu);
3124         int newkey= 0;
3125
3126         if(key==NULL) {
3127                 key= cu->key= add_key( (ID *)cu);
3128                 key->type = KEY_RELATIVE;
3129                 newkey= 1;
3130         }
3131
3132         if(newkey || from_mix==FALSE) {
3133                 /* create from curve */
3134                 kb= add_keyblock(key, name);
3135                 if (!newkey) {
3136                         KeyBlock *basekb= (KeyBlock *)key->block.first;
3137                         kb->data= MEM_dupallocN(basekb->data);
3138                         kb->totelem= basekb->totelem;
3139                 }
3140                 else {
3141                         curve_to_key(cu, kb, lb);
3142                 }
3143         }
3144         else {
3145                 /* copy from current values */
3146           &nbs