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