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