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