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