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