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