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