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