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