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