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