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