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