svn merge ^/trunk/blender -r42080:42095
[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                 else fprintf(stderr, "%s: DerivedMesh is needed to solve parenting, object position can be wrong now\n", __func__);
1805         }
1806         else if (ELEM(par->type, OB_CURVE, OB_SURF)) {
1807                 Nurb *nu;
1808                 Curve *cu;
1809                 BPoint *bp;
1810                 BezTriple *bezt;
1811                 int found= 0;
1812                 ListBase *nurbs;
1813
1814                 cu= par->data;
1815                 nurbs= BKE_curve_nurbs(cu);
1816                 nu= nurbs->first;
1817
1818                 count= 0;
1819                 while(nu && !found) {
1820                         if(nu->type == CU_BEZIER) {
1821                                 bezt= nu->bezt;
1822                                 a= nu->pntsu;
1823                                 while(a--) {
1824                                         if(count==nr) {
1825                                                 found= 1;
1826                                                 copy_v3_v3(vec, bezt->vec[1]);
1827                                                 break;
1828                                         }
1829                                         count++;
1830                                         bezt++;
1831                                 }
1832                         }
1833                         else {
1834                                 bp= nu->bp;
1835                                 a= nu->pntsu*nu->pntsv;
1836                                 while(a--) {
1837                                         if(count==nr) {
1838                                                 found= 1;
1839                                                 memcpy(vec, bp->vec, sizeof(float)*3);
1840                                                 break;
1841                                         }
1842                                         count++;
1843                                         bp++;
1844                                 }
1845                         }
1846                         nu= nu->next;
1847                 }
1848
1849         }
1850         else if(par->type==OB_LATTICE) {
1851                 Lattice *latt= par->data;
1852                 BPoint *bp;
1853                 DispList *dl = find_displist(&par->disp, DL_VERTS);
1854                 float *co = dl?dl->verts:NULL;
1855                 
1856                 if(latt->editlatt) latt= latt->editlatt->latt;
1857                 
1858                 a= latt->pntsu*latt->pntsv*latt->pntsw;
1859                 count= 0;
1860                 bp= latt->def;
1861                 while(a--) {
1862                         if(count==nr) {
1863                                 if(co)
1864                                         memcpy(vec, co, 3*sizeof(float));
1865                                 else
1866                                         memcpy(vec, bp->vec, 3*sizeof(float));
1867                                 break;
1868                         }
1869                         count++;
1870                         if(co) co+= 3;
1871                         else bp++;
1872                 }
1873         }
1874 }
1875
1876 static void ob_parvert3(Object *ob, Object *par, float mat[][4])
1877 {
1878         float cmat[3][3], v1[3], v2[3], v3[3], q[4];
1879
1880         /* in local ob space */
1881         unit_m4(mat);
1882         
1883         if (ELEM4(par->type, OB_MESH, OB_SURF, OB_CURVE, OB_LATTICE)) {
1884                 
1885                 give_parvert(par, ob->par1, v1);
1886                 give_parvert(par, ob->par2, v2);
1887                 give_parvert(par, ob->par3, v3);
1888                                 
1889                 tri_to_quat( q,v1, v2, v3);
1890                 quat_to_mat3( cmat,q);
1891                 copy_m4_m3(mat, cmat);
1892                 
1893                 if(ob->type==OB_CURVE) {
1894                         copy_v3_v3(mat[3], v1);
1895                 }
1896                 else {
1897                         add_v3_v3v3(mat[3], v1, v2);
1898                         add_v3_v3(mat[3], v3);
1899                         mul_v3_fl(mat[3], 0.3333333f);
1900                 }
1901         }
1902 }
1903
1904 static int where_is_object_parslow(Object *ob, float obmat[4][4], float slowmat[4][4])
1905 {
1906         float *fp1, *fp2;
1907         float fac1, fac2;
1908         int a;
1909
1910         // include framerate
1911         fac1= ( 1.0f / (1.0f + fabsf(ob->sf)) );
1912         if(fac1 >= 1.0f) return 0;
1913         fac2= 1.0f-fac1;
1914
1915         fp1= obmat[0];
1916         fp2= slowmat[0];
1917         for(a=0; a<16; a++, fp1++, fp2++) {
1918                 fp1[0]= fac1*fp1[0] + fac2*fp2[0];
1919         }
1920
1921         return 1;
1922 }
1923
1924 void where_is_object_time(Scene *scene, Object *ob, float ctime)
1925 {
1926         float slowmat[4][4] = MAT4_UNITY;
1927         float stime=ctime;
1928         
1929         /* new version: correct parent+vertexparent and track+parent */
1930         /* this one only calculates direct attached parent and track */
1931         /* is faster, but should keep track of timeoffs */
1932         
1933         if(ob==NULL) return;
1934         
1935         /* execute drivers only, as animation has already been done */
1936         BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, ctime, ADT_RECALC_DRIVERS);
1937         
1938         if(ob->parent) {
1939                 Object *par= ob->parent;
1940                 
1941                 /* hurms, code below conflicts with depgraph... (ton) */
1942                 /* and even worse, it gives bad effects for NLA stride too (try ctime != par->ctime, with MBlur) */
1943                 if(stime != par->ctime) {
1944                         // only for ipo systems? 
1945                         Object tmp= *par;
1946                         
1947                         if(par->proxy_from);    // was a copied matrix, no where_is! bad...
1948                         else where_is_object_time(scene, par, ctime);
1949                         
1950                         solve_parenting(scene, ob, par, ob->obmat, slowmat, 0);
1951                         
1952                         *par= tmp;
1953                 }
1954                 else
1955                         solve_parenting(scene, ob, par, ob->obmat, slowmat, 0);
1956                 
1957                 /* "slow parent" is definitely not threadsafe, and may also give bad results jumping around 
1958                  * An old-fashioned hack which probably doesn't really cut it anymore
1959                  */
1960                 if(ob->partype & PARSLOW) {
1961                         if(!where_is_object_parslow(ob, ob->obmat, slowmat))
1962                                 return;
1963                 }
1964         }
1965         else {
1966                 object_to_mat4(ob, ob->obmat);
1967         }
1968
1969         /* solve constraints */
1970         if (ob->constraints.first && !(ob->transflag & OB_NO_CONSTRAINTS)) {
1971                 bConstraintOb *cob;
1972                 
1973                 cob= constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
1974                 
1975                 /* constraints need ctime, not stime. Some call where_is_object_time and bsystem_time */
1976                 solve_constraints (&ob->constraints, cob, ctime);
1977                 
1978                 constraints_clear_evalob(cob);
1979         }
1980         
1981         /* set negative scale flag in object */
1982         if(is_negative_m4(ob->obmat))   ob->transflag |= OB_NEG_SCALE;
1983         else                                                    ob->transflag &= ~OB_NEG_SCALE;
1984 }
1985
1986 /* get object transformation matrix without recalculating dependencies and
1987    constraints -- assume dependencies are already solved by depsgraph.
1988    no changes to object and it's parent would be done.
1989    used for bundles orientation in 3d space relative to parented blender camera */
1990 void where_is_object_mat(Scene *scene, Object *ob, float obmat[4][4])
1991 {
1992         float slowmat[4][4] = MAT4_UNITY;
1993
1994         if(ob->parent) {
1995                 Object *par= ob->parent;
1996
1997                 solve_parenting(scene, ob, par, obmat, slowmat, 1);
1998
1999                 if(ob->partype & PARSLOW)
2000                         where_is_object_parslow(ob, obmat, slowmat);
2001         }
2002         else {
2003                 object_to_mat4(ob, obmat);
2004         }
2005 }
2006
2007 static void solve_parenting (Scene *scene, Object *ob, Object *par, float obmat[][4], float slowmat[][4], int simul)
2008 {
2009         float totmat[4][4];
2010         float tmat[4][4];
2011         float locmat[4][4];
2012         float vec[3];
2013         int ok;
2014         
2015         object_to_mat4(ob, locmat);
2016         
2017         if(ob->partype & PARSLOW) copy_m4_m4(slowmat, obmat);
2018
2019         switch(ob->partype & PARTYPE) {
2020         case PAROBJECT:
2021                 ok= 0;
2022                 if(par->type==OB_CURVE) {
2023                         if( ((Curve *)par->data)->flag & CU_PATH ) {
2024                                 ob_parcurve(scene, ob, par, tmat);
2025                                 ok= 1;
2026                         }
2027                 }
2028                 
2029                 if(ok) mul_serie_m4(totmat, par->obmat, tmat, 
2030                         NULL, NULL, NULL, NULL, NULL, NULL);
2031                 else copy_m4_m4(totmat, par->obmat);
2032                 
2033                 break;
2034         case PARBONE:
2035                 ob_parbone(ob, par, tmat);
2036                 mul_serie_m4(totmat, par->obmat, tmat,         
2037                         NULL, NULL, NULL, NULL, NULL, NULL);
2038                 break;
2039                 
2040         case PARVERT1:
2041                 unit_m4(totmat);
2042                 if (simul){
2043                         copy_v3_v3(totmat[3], par->obmat[3]);
2044                 }
2045                 else{
2046                         give_parvert(par, ob->par1, vec);
2047                         mul_v3_m4v3(totmat[3], par->obmat, vec);
2048                 }
2049                 break;
2050         case PARVERT3:
2051                 ob_parvert3(ob, par, tmat);
2052                 
2053                 mul_serie_m4(totmat, par->obmat, tmat,         
2054                         NULL, NULL, NULL, NULL, NULL, NULL);
2055                 break;
2056                 
2057         case PARSKEL:
2058                 copy_m4_m4(totmat, par->obmat);
2059                 break;
2060         }
2061         
2062         // total 
2063         mul_serie_m4(tmat, totmat, ob->parentinv,         
2064                 NULL, NULL, NULL, NULL, NULL, NULL);
2065         mul_serie_m4(obmat, tmat, locmat,         
2066                 NULL, NULL, NULL, NULL, NULL, NULL);
2067         
2068         if (simul) {
2069
2070         }
2071         else{
2072                 // external usable originmat 
2073                 copy_m3_m4(originmat, tmat);
2074                 
2075                 // origin, voor help line
2076                 if( (ob->partype & PARTYPE)==PARSKEL ) {
2077                         copy_v3_v3(ob->orig, par->obmat[3]);
2078                 }
2079                 else {
2080                         copy_v3_v3(ob->orig, totmat[3]);
2081                 }
2082         }
2083
2084 }
2085
2086 void where_is_object(struct Scene *scene, Object *ob)
2087 {
2088         where_is_object_time(scene, ob, (float)scene->r.cfra);
2089 }
2090
2091
2092 void where_is_object_simul(Scene *scene, Object *ob)
2093 /* was written for the old game engine (until 2.04) */
2094 /* It seems that this function is only called
2095 for a lamp that is the child of another object */
2096 {
2097         Object *par;
2098         float *fp1, *fp2;
2099         float slowmat[4][4];
2100         float fac1, fac2;
2101         int a;
2102         
2103         /* NO TIMEOFFS */
2104         if(ob->parent) {
2105                 par= ob->parent;
2106                 
2107                 solve_parenting(scene, ob, par, ob->obmat, slowmat, 1);
2108                 
2109                 if(ob->partype & PARSLOW) {
2110                         fac1= (float)(1.0/(1.0+ fabs(ob->sf)));
2111                         fac2= 1.0f-fac1;
2112                         fp1= ob->obmat[0];
2113                         fp2= slowmat[0];
2114                         for(a=0; a<16; a++, fp1++, fp2++) {
2115                                 fp1[0]= fac1*fp1[0] + fac2*fp2[0];
2116                         }
2117                 }
2118         }
2119         else {
2120                 object_to_mat4(ob, ob->obmat);
2121         }
2122         
2123         /* solve constraints */
2124         if (ob->constraints.first) {
2125                 bConstraintOb *cob;
2126                 
2127                 cob= constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2128                 solve_constraints(&ob->constraints, cob, (float)scene->r.cfra);
2129                 constraints_clear_evalob(cob);
2130         }
2131 }
2132
2133 /* for calculation of the inverse parent transform, only used for editor */
2134 void what_does_parent(Scene *scene, Object *ob, Object *workob)
2135 {
2136         clear_workob(workob);
2137         
2138         unit_m4(workob->obmat);
2139         unit_m4(workob->parentinv);
2140         unit_m4(workob->constinv);
2141         workob->parent= ob->parent;
2142
2143         workob->trackflag= ob->trackflag;
2144         workob->upflag= ob->upflag;
2145         
2146         workob->partype= ob->partype;
2147         workob->par1= ob->par1;
2148         workob->par2= ob->par2;
2149         workob->par3= ob->par3;
2150
2151         workob->constraints.first = ob->constraints.first;
2152         workob->constraints.last = ob->constraints.last;
2153
2154         BLI_strncpy(workob->parsubstr, ob->parsubstr, sizeof(workob->parsubstr));
2155
2156         where_is_object(scene, workob);
2157 }
2158
2159 BoundBox *unit_boundbox(void)
2160 {
2161         BoundBox *bb;
2162         float min[3] = {-1.0f,-1.0f,-1.0f}, max[3] = {-1.0f,-1.0f,-1.0f};
2163
2164         bb= MEM_callocN(sizeof(BoundBox), "OB-BoundBox");
2165         boundbox_set_from_min_max(bb, min, max);
2166         
2167         return bb;
2168 }
2169
2170 void boundbox_set_from_min_max(BoundBox *bb, float min[3], float max[3])
2171 {
2172         bb->vec[0][0]=bb->vec[1][0]=bb->vec[2][0]=bb->vec[3][0]= min[0];
2173         bb->vec[4][0]=bb->vec[5][0]=bb->vec[6][0]=bb->vec[7][0]= max[0];
2174         
2175         bb->vec[0][1]=bb->vec[1][1]=bb->vec[4][1]=bb->vec[5][1]= min[1];
2176         bb->vec[2][1]=bb->vec[3][1]=bb->vec[6][1]=bb->vec[7][1]= max[1];
2177
2178         bb->vec[0][2]=bb->vec[3][2]=bb->vec[4][2]=bb->vec[7][2]= min[2];
2179         bb->vec[1][2]=bb->vec[2][2]=bb->vec[5][2]=bb->vec[6][2]= max[2];
2180 }
2181
2182 BoundBox *object_get_boundbox(Object *ob)
2183 {
2184         BoundBox *bb= NULL;
2185         
2186         if(ob->type==OB_MESH) {
2187                 bb = mesh_get_bb(ob);
2188         }
2189         else if (ELEM3(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2190                 bb= ob->bb ? ob->bb : ( (Curve *)ob->data )->bb;
2191         }
2192         else if(ob->type==OB_MBALL) {
2193                 bb= ob->bb;
2194         }
2195         return bb;
2196 }
2197
2198 /* used to temporally disable/enable boundbox */
2199 void object_boundbox_flag(Object *ob, int flag, int set)
2200 {
2201         BoundBox *bb= object_get_boundbox(ob);
2202         if(bb) {
2203                 if(set) bb->flag |= flag;
2204                 else bb->flag &= ~flag;
2205         }
2206 }
2207
2208 void object_get_dimensions(Object *ob, float *value)
2209 {
2210         BoundBox *bb = NULL;
2211         
2212         bb= object_get_boundbox(ob);
2213         if (bb) {
2214                 float scale[3];
2215                 
2216                 mat4_to_size( scale,ob->obmat);
2217                 
2218                 value[0] = fabsf(scale[0]) * (bb->vec[4][0] - bb->vec[0][0]);
2219                 value[1] = fabsf(scale[1]) * (bb->vec[2][1] - bb->vec[0][1]);
2220                 value[2] = fabsf(scale[2]) * (bb->vec[1][2] - bb->vec[0][2]);
2221         } else {
2222                 value[0] = value[1] = value[2] = 0.f;
2223         }
2224 }
2225
2226 void object_set_dimensions(Object *ob, const float *value)
2227 {
2228         BoundBox *bb = NULL;
2229         
2230         bb= object_get_boundbox(ob);
2231         if (bb) {
2232                 float scale[3], len[3];
2233                 
2234                 mat4_to_size( scale,ob->obmat);
2235                 
2236                 len[0] = bb->vec[4][0] - bb->vec[0][0];
2237                 len[1] = bb->vec[2][1] - bb->vec[0][1];
2238                 len[2] = bb->vec[1][2] - bb->vec[0][2];
2239                 
2240                 if (len[0] > 0.f) ob->size[0] = value[0] / len[0];
2241                 if (len[1] > 0.f) ob->size[1] = value[1] / len[1];
2242                 if (len[2] > 0.f) ob->size[2] = value[2] / len[2];
2243         }
2244 }
2245
2246 void minmax_object(Object *ob, float min[3], float max[3])
2247 {
2248         BoundBox bb;
2249         float vec[3];
2250         int a;
2251         short change= FALSE;
2252         
2253         switch(ob->type) {
2254         case OB_CURVE:
2255         case OB_FONT:
2256         case OB_SURF:
2257                 {
2258                         Curve *cu= ob->data;
2259
2260                         if(cu->bb==NULL) tex_space_curve(cu);
2261                         bb= *(cu->bb);
2262
2263                         for(a=0; a<8; a++) {
2264                                 mul_m4_v3(ob->obmat, bb.vec[a]);
2265                                 DO_MINMAX(bb.vec[a], min, max);
2266                         }
2267                         change= TRUE;
2268                 }
2269                 break;
2270         case OB_LATTICE:
2271                 {
2272                         Lattice *lt= ob->data;
2273                         BPoint *bp= lt->def;
2274                         int u, v, w;
2275
2276                         for(w=0; w<lt->pntsw; w++) {
2277                                 for(v=0; v<lt->pntsv; v++) {
2278                                         for(u=0; u<lt->pntsu; u++, bp++) {
2279                                                 mul_v3_m4v3(vec, ob->obmat, bp->vec);
2280                                                 DO_MINMAX(vec, min, max);
2281                                         }
2282                                 }
2283                         }
2284                         change= TRUE;
2285                 }
2286                 break;
2287         case OB_ARMATURE:
2288                 if(ob->pose) {
2289                         bPoseChannel *pchan;
2290                         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2291                                 mul_v3_m4v3(vec, ob->obmat, pchan->pose_head);
2292                                 DO_MINMAX(vec, min, max);
2293                                 mul_v3_m4v3(vec, ob->obmat, pchan->pose_tail);
2294                                 DO_MINMAX(vec, min, max);
2295                         }
2296                         change= TRUE;
2297                 }
2298                 break;
2299         case OB_MESH:
2300                 {
2301                         Mesh *me= get_mesh(ob);
2302
2303                         if(me) {
2304                                 bb = *mesh_get_bb(ob);
2305
2306                                 for(a=0; a<8; a++) {
2307                                         mul_m4_v3(ob->obmat, bb.vec[a]);
2308                                         DO_MINMAX(bb.vec[a], min, max);
2309                                 }
2310                                 change= TRUE;
2311                         }
2312                 }
2313                 break;
2314         }
2315
2316         if(change == FALSE) {
2317                 DO_MINMAX(ob->obmat[3], min, max);
2318
2319                 copy_v3_v3(vec, ob->obmat[3]);
2320                 add_v3_v3(vec, ob->size);
2321                 DO_MINMAX(vec, min, max);
2322
2323                 copy_v3_v3(vec, ob->obmat[3]);
2324                 sub_v3_v3(vec, ob->size);
2325                 DO_MINMAX(vec, min, max);
2326         }
2327 }
2328
2329 int minmax_object_duplis(Scene *scene, Object *ob, float *min, float *max)
2330 {
2331         int ok= 0;
2332         if ((ob->transflag & OB_DUPLI)==0) {
2333                 return ok;
2334         } else {
2335                 ListBase *lb;
2336                 DupliObject *dob;
2337                 
2338                 lb= object_duplilist(scene, ob);
2339                 for(dob= lb->first; dob; dob= dob->next) {
2340                         if(dob->no_draw == 0) {
2341                                 BoundBox *bb= object_get_boundbox(dob->ob);
2342
2343                                 if(bb) {
2344                                         int i;
2345                                         for(i=0; i<8; i++) {
2346                                                 float vec[3];
2347                                                 mul_v3_m4v3(vec, dob->mat, bb->vec[i]);
2348                                                 DO_MINMAX(vec, min, max);
2349                                         }
2350
2351                                         ok= 1;
2352                                 }
2353                         }
2354                 }
2355                 free_object_duplilist(lb);      /* does restore */
2356         }
2357
2358         return ok;
2359 }
2360
2361 void BKE_object_foreach_display_point(
2362         Object *ob, float obmat[4][4],
2363         void (*func_cb)(const float[3], void *), void *user_data)
2364 {
2365         float co[3];
2366
2367         if (ob->derivedFinal) {
2368                 DerivedMesh *dm= ob->derivedFinal;
2369                 MVert *mv= dm->getVertArray(dm);
2370                 int totvert= dm->getNumVerts(dm);
2371                 int i;
2372
2373                 for (i= 0; i < totvert; i++, mv++) {
2374                         mul_v3_m4v3(co, obmat, mv->co);
2375                         func_cb(co, user_data);
2376                 }
2377         }
2378         else if (ob->disp.first) {
2379                 DispList *dl;
2380
2381                 for (dl=ob->disp.first; dl; dl=dl->next) {
2382                         float *v3= dl->verts;
2383                         int totvert= dl->nr;
2384                         int i;
2385
2386                         for (i= 0; i < totvert; i++, v3+=3) {
2387                                 mul_v3_m4v3(co, obmat, v3);
2388                                 func_cb(co, user_data);
2389                         }
2390                 }
2391         }
2392 }
2393
2394 void BKE_scene_foreach_display_point(
2395         Scene *scene, View3D *v3d, const short flag,
2396         void (*func_cb)(const float[3], void *), void *user_data)
2397 {
2398         Base *base;
2399         Object *ob;
2400
2401         for(base= FIRSTBASE; base; base = base->next) {
2402                 if(BASE_VISIBLE(v3d, base) && (base->flag & flag) == flag) {
2403                         ob= base->object;
2404
2405                         if ((ob->transflag & OB_DUPLI)==0) {
2406                                 BKE_object_foreach_display_point(ob, ob->obmat, func_cb, user_data);
2407                         }
2408                         else {
2409                                 ListBase *lb;
2410                                 DupliObject *dob;
2411
2412                                 lb= object_duplilist(scene, ob);
2413                                 for(dob= lb->first; dob; dob= dob->next) {
2414                                         if(dob->no_draw == 0) {
2415                                                 BKE_object_foreach_display_point(dob->ob, dob->mat, func_cb, user_data);
2416                                         }
2417                                 }
2418                                 free_object_duplilist(lb);      /* does restore */
2419                         }
2420                 }
2421         }
2422 }
2423
2424 /* copied from DNA_object_types.h */
2425 typedef struct ObTfmBack {
2426         float loc[3], dloc[3], orig[3];
2427         float size[3], dsize[3];        /* scale and delta scale */
2428         float rot[3], drot[3];          /* euler rotation */
2429         float quat[4], dquat[4];        /* quaternion rotation */
2430         float rotAxis[3], drotAxis[3];  /* axis angle rotation - axis part */
2431         float rotAngle, drotAngle;      /* axis angle rotation - angle part */
2432         float obmat[4][4];              /* final worldspace matrix with constraints & animsys applied */
2433         float parentinv[4][4]; /* inverse result of parent, so that object doesn't 'stick' to parent */
2434         float constinv[4][4]; /* inverse result of constraints. doesn't include effect of parent or object local transform */
2435         float imat[4][4];       /* inverse matrix of 'obmat' for during render, old game engine, temporally: ipokeys of transform  */
2436 } ObTfmBack;
2437
2438 void *object_tfm_backup(Object *ob)
2439 {
2440         ObTfmBack *obtfm= MEM_mallocN(sizeof(ObTfmBack), "ObTfmBack");
2441         copy_v3_v3(obtfm->loc, ob->loc);
2442         copy_v3_v3(obtfm->dloc, ob->dloc);
2443         copy_v3_v3(obtfm->orig, ob->orig);
2444         copy_v3_v3(obtfm->size, ob->size);
2445         copy_v3_v3(obtfm->dsize, ob->dsize);
2446         copy_v3_v3(obtfm->rot, ob->rot);
2447         copy_v3_v3(obtfm->drot, ob->drot);
2448         copy_qt_qt(obtfm->quat, ob->quat);
2449         copy_qt_qt(obtfm->dquat, ob->dquat);
2450         copy_v3_v3(obtfm->rotAxis, ob->rotAxis);
2451         copy_v3_v3(obtfm->drotAxis, ob->drotAxis);
2452         obtfm->rotAngle= ob->rotAngle;
2453         obtfm->drotAngle= ob->drotAngle;
2454         copy_m4_m4(obtfm->obmat, ob->obmat);
2455         copy_m4_m4(obtfm->parentinv, ob->parentinv);
2456         copy_m4_m4(obtfm->constinv, ob->constinv);
2457         copy_m4_m4(obtfm->imat, ob->imat);
2458
2459         return (void *)obtfm;
2460 }
2461
2462 void object_tfm_restore(Object *ob, void *obtfm_pt)
2463 {
2464         ObTfmBack *obtfm= (ObTfmBack *)obtfm_pt;
2465         copy_v3_v3(ob->loc, obtfm->loc);
2466         copy_v3_v3(ob->dloc, obtfm->dloc);
2467         copy_v3_v3(ob->orig, obtfm->orig);
2468         copy_v3_v3(ob->size, obtfm->size);
2469         copy_v3_v3(ob->dsize, obtfm->dsize);
2470         copy_v3_v3(ob->rot, obtfm->rot);
2471         copy_v3_v3(ob->drot, obtfm->drot);
2472         copy_qt_qt(ob->quat, obtfm->quat);
2473         copy_qt_qt(ob->dquat, obtfm->dquat);
2474         copy_v3_v3(ob->rotAxis, obtfm->rotAxis);
2475         copy_v3_v3(ob->drotAxis, obtfm->drotAxis);
2476         ob->rotAngle= obtfm->rotAngle;
2477         ob->drotAngle= obtfm->drotAngle;
2478         copy_m4_m4(ob->obmat, obtfm->obmat);
2479         copy_m4_m4(ob->parentinv, obtfm->parentinv);
2480         copy_m4_m4(ob->constinv, obtfm->constinv);
2481         copy_m4_m4(ob->imat, obtfm->imat);
2482 }
2483
2484 /* proxy rule: lib_object->proxy_from == the one we borrow from, only set temporal and cleared here */
2485 /*           local_object->proxy      == pointer to library object, saved in files and read */
2486
2487 /* function below is polluted with proxy exceptions, cleanup will follow! */
2488
2489 /* the main object update call, for object matrix, constraints, keys and displist (modifiers) */
2490 /* requires flags to be set! */
2491 void object_handle_update(Scene *scene, Object *ob)
2492 {
2493         if(ob->recalc & OB_RECALC_ALL) {
2494                 /* speed optimization for animation lookups */
2495                 if(ob->pose)
2496                         make_pose_channels_hash(ob->pose);
2497
2498                 if(ob->recalc & OB_RECALC_DATA) {
2499                         if(ob->type==OB_ARMATURE) {
2500                                 /* this happens for reading old files and to match library armatures
2501                                    with poses we do it ahead of where_is_object to ensure animation
2502                                    is evaluated on the rebuilt pose, otherwise we get incorrect poses
2503                                    on file load */
2504                                 if(ob->pose==NULL || (ob->pose->flag & POSE_RECALC))
2505                                         armature_rebuild_pose(ob, ob->data);
2506                         }
2507                 }
2508
2509                 /* XXX new animsys warning: depsgraph tag OB_RECALC_DATA should not skip drivers, 
2510                    which is only in where_is_object now */
2511                 // XXX: should this case be OB_RECALC_OB instead?
2512                 if(ob->recalc & OB_RECALC_ALL) {
2513                         
2514                         if (G.f & G_DEBUG)
2515                                 printf("recalcob %s\n", ob->id.name+2);
2516                         
2517                         /* handle proxy copy for target */
2518                         if(ob->id.lib && ob->proxy_from) {
2519                                 // printf("ob proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2520                                 if(ob->proxy_from->proxy_group) {/* transform proxy into group space */
2521                                         Object *obg= ob->proxy_from->proxy_group;
2522                                         invert_m4_m4(obg->imat, obg->obmat);
2523                                         mul_m4_m4m4(ob->obmat, ob->proxy_from->obmat, obg->imat);
2524                                         if(obg->dup_group) { /* should always be true */
2525                                                 add_v3_v3(ob->obmat[3], obg->dup_group->dupli_ofs);
2526                                         }
2527                                 }
2528                                 else
2529                                         copy_m4_m4(ob->obmat, ob->proxy_from->obmat);
2530                         }
2531                         else
2532                                 where_is_object(scene, ob);
2533                 }
2534                 
2535                 if(ob->recalc & OB_RECALC_DATA) {
2536                         ID *data_id= (ID *)ob->data;
2537                         AnimData *adt= BKE_animdata_from_id(data_id);
2538                         float ctime= (float)scene->r.cfra; // XXX this is bad...
2539                         ListBase pidlist;
2540                         PTCacheID *pid;
2541                         
2542                         if (G.f & G_DEBUG)
2543                                 printf("recalcdata %s\n", ob->id.name+2);
2544
2545                         if(adt) {
2546                                 /* evaluate drivers */
2547                                 // XXX: for mesh types, should we push this to derivedmesh instead?
2548                                 BKE_animsys_evaluate_animdata(scene, data_id, adt, ctime, ADT_RECALC_DRIVERS);
2549                         }
2550
2551                         /* includes all keys and modifiers */
2552                         switch(ob->type) {
2553                         case OB_MESH:
2554                                 {
2555 #if 0                           // XXX, comment for 2.56a release, background wont set 'scene->customdata_mask'
2556                                         BMEditMesh *em = (ob == scene->obedit)? ((Mesh*)ob->data)->edit_btmesh : NULL;
2557                                         BLI_assert((scene->customdata_mask & CD_MASK_BAREMESH) == CD_MASK_BAREMESH);
2558                                         if(em) {
2559                                                 makeDerivedMesh(scene, ob, em,  scene->customdata_mask, 0); /* was CD_MASK_BAREMESH */
2560                                         }
2561                                         else {
2562                                                 makeDerivedMesh(scene, ob, NULL, scene->customdata_mask, 0);
2563                                         }
2564
2565 #else                           /* ensure CD_MASK_BAREMESH for now */
2566                                         BMEditMesh *em = (ob == scene->obedit)? ((Mesh*)ob->data)->edit_btmesh : NULL;
2567                                         if(em) {
2568                                                 makeDerivedMesh(scene, ob, em,  scene->customdata_mask | CD_MASK_BAREMESH, 0); /* was CD_MASK_BAREMESH */
2569                                         }
2570                                         else {
2571                                                 makeDerivedMesh(scene, ob, NULL, scene->customdata_mask | CD_MASK_BAREMESH, 0);
2572                                         }
2573 #endif
2574
2575                                 }
2576                                 break;
2577
2578                         case OB_ARMATURE:
2579                                 if(ob->id.lib && ob->proxy_from) {
2580                                         // printf("pose proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2581                                         copy_pose_result(ob->pose, ob->proxy_from->pose);
2582                                 }
2583                                 else {
2584                                         where_is_pose(scene, ob);
2585                                 }
2586                                 break;
2587
2588                         case OB_MBALL:
2589                                 makeDispListMBall(scene, ob);
2590                                 break;
2591
2592                         case OB_CURVE:
2593                         case OB_SURF:
2594                         case OB_FONT:
2595                                 makeDispListCurveTypes(scene, ob, 0);
2596                                 break;
2597                                 
2598                         case OB_LATTICE:
2599                                 lattice_calc_modifiers(scene, ob);
2600                                 break;
2601                         }
2602
2603
2604                         if(ob->particlesystem.first) {
2605                                 ParticleSystem *tpsys, *psys;
2606                                 DerivedMesh *dm;
2607                                 ob->transflag &= ~OB_DUPLIPARTS;
2608                                 
2609                                 psys= ob->particlesystem.first;
2610                                 while(psys) {
2611                                         if(psys_check_enabled(ob, psys)) {
2612                                                 /* check use of dupli objects here */
2613                                                 if(psys->part && (psys->part->draw_as == PART_DRAW_REND || G.rendering) &&
2614                                                         ((psys->part->ren_as == PART_DRAW_OB && psys->part->dup_ob)
2615                                                         || (psys->part->ren_as == PART_DRAW_GR && psys->part->dup_group)))
2616                                                         ob->transflag |= OB_DUPLIPARTS;
2617
2618                                                 particle_system_update(scene, ob, psys);
2619                                                 psys= psys->next;
2620                                         }
2621                                         else if(psys->flag & PSYS_DELETE) {
2622                                                 tpsys=psys->next;
2623                                                 BLI_remlink(&ob->particlesystem, psys);
2624                                                 psys_free(ob,psys);
2625                                                 psys= tpsys;
2626                                         }
2627                                         else
2628                                                 psys= psys->next;
2629                                 }
2630
2631                                 if(G.rendering && ob->transflag & OB_DUPLIPARTS) {
2632                                         /* this is to make sure we get render level duplis in groups:
2633                                          * the derivedmesh must be created before init_render_mesh,
2634                                          * since object_duplilist does dupliparticles before that */
2635                                         dm = mesh_create_derived_render(scene, ob, CD_MASK_BAREMESH|CD_MASK_MTFACE|CD_MASK_MCOL);
2636                                         dm->release(dm);
2637
2638                                         for(psys=ob->particlesystem.first; psys; psys=psys->next)
2639                                                 psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated;
2640                                 }
2641                         }
2642
2643                         /* check if quick cache is needed */
2644                         BKE_ptcache_ids_from_object(&pidlist, ob, scene, MAX_DUPLI_RECUR);
2645
2646                         for(pid=pidlist.first; pid; pid=pid->next) {
2647                                 if((pid->cache->flag & PTCACHE_BAKED)
2648                                         || (pid->cache->flag & PTCACHE_QUICK_CACHE)==0)
2649                                         continue;
2650
2651                                 if(pid->cache->flag & PTCACHE_OUTDATED || (pid->cache->flag & PTCACHE_SIMULATION_VALID)==0) {
2652                                         scene->physics_settings.quick_cache_step =
2653                                                 scene->physics_settings.quick_cache_step ?
2654                                                 MIN2(scene->physics_settings.quick_cache_step, pid->cache->step) :
2655                                                 pid->cache->step;
2656                                 }
2657                         }
2658
2659                         BLI_freelistN(&pidlist);
2660                 }
2661
2662                 /* the no-group proxy case, we call update */
2663                 if(ob->proxy && ob->proxy_group==NULL) {
2664                         /* set pointer in library proxy target, for copying, but restore it */
2665                         ob->proxy->proxy_from= ob;
2666                         // printf("call update, lib ob %s proxy %s\n", ob->proxy->id.name, ob->id.name);
2667                         object_handle_update(scene, ob->proxy);
2668                 }
2669         
2670                 ob->recalc &= ~OB_RECALC_ALL;
2671         }
2672
2673         /* the case when this is a group proxy, object_update is called in group.c */
2674         if(ob->proxy) {
2675                 ob->proxy->proxy_from= ob;
2676                 // printf("set proxy pointer for later group stuff %s\n", ob->id.name);
2677         }
2678 }
2679
2680 void object_sculpt_modifiers_changed(Object *ob)
2681 {
2682         SculptSession *ss= ob->sculpt;
2683
2684         if(!ss->cache) {
2685                 /* we free pbvh on changes, except during sculpt since it can't deal with
2686                    changing PVBH node organization, we hope topology does not change in
2687                    the meantime .. weak */
2688                 if(ss->pbvh) {
2689                                 BLI_pbvh_free(ss->pbvh);
2690                                 ss->pbvh= NULL;
2691                 }
2692
2693                 free_sculptsession_deformMats(ob->sculpt);
2694         } else {
2695                 PBVHNode **nodes;
2696                 int n, totnode;
2697
2698                 BLI_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode);
2699
2700                 for(n = 0; n < totnode; n++)
2701                         BLI_pbvh_node_mark_update(nodes[n]);
2702
2703                 MEM_freeN(nodes);
2704         }
2705 }
2706
2707 int give_obdata_texspace(Object *ob, short **texflag, float **loc, float **size, float **rot)
2708 {
2709         
2710         if (ob->data==NULL)
2711                 return 0;
2712         
2713         switch (GS(((ID *)ob->data)->name)) {
2714         case ID_ME:
2715         {
2716                 Mesh *me= ob->data;
2717                 if (texflag)    *texflag = &me->texflag;
2718                 if (loc)                *loc = me->loc;
2719                 if (size)               *size = me->size;
2720                 if (rot)                *rot = me->rot;
2721                 break;
2722         }
2723         case ID_CU:
2724         {
2725                 Curve *cu= ob->data;
2726                 if (texflag)    *texflag = &cu->texflag;
2727                 if (loc)                *loc = cu->loc;
2728                 if (size)               *size = cu->size;
2729                 if (rot)                *rot = cu->rot;
2730                 break;
2731         }
2732         case ID_MB:
2733         {
2734                 MetaBall *mb= ob->data;
2735                 if (texflag)    *texflag = &mb->texflag;
2736                 if (loc)                *loc = mb->loc;
2737                 if (size)               *size = mb->size;
2738                 if (rot)                *rot = mb->rot;
2739                 break;
2740         }
2741         default:
2742                 return 0;
2743         }
2744         return 1;
2745 }
2746
2747 /*
2748  * Test a bounding box for ray intersection
2749  * assumes the ray is already local to the boundbox space
2750  */
2751 int ray_hit_boundbox(struct BoundBox *bb, float ray_start[3], float ray_normal[3])
2752 {
2753         static int triangle_indexes[12][3] = {{0, 1, 2}, {0, 2, 3},
2754                                                                                   {3, 2, 6}, {3, 6, 7},
2755                                                                                   {1, 2, 6}, {1, 6, 5}, 
2756                                                                                   {5, 6, 7}, {4, 5, 7},
2757                                                                                   {0, 3, 7}, {0, 4, 7},
2758                                                                                   {0, 1, 5}, {0, 4, 5}};
2759         int result = 0;
2760         int i;
2761         
2762         for (i = 0; i < 12 && result == 0; i++)
2763         {
2764                 float lambda;
2765                 int v1, v2, v3;
2766                 v1 = triangle_indexes[i][0];
2767                 v2 = triangle_indexes[i][1];
2768                 v3 = triangle_indexes[i][2];
2769                 result = isect_ray_tri_v3(ray_start, ray_normal, bb->vec[v1], bb->vec[v2], bb->vec[v3], &lambda, NULL);
2770         }
2771         
2772         return result;
2773 }
2774
2775 static int pc_cmp(void *a, void *b)
2776 {
2777         LinkData *ad = a, *bd = b;
2778         if(GET_INT_FROM_POINTER(ad->data) > GET_INT_FROM_POINTER(bd->data))
2779                 return 1;
2780         else return 0;
2781 }
2782
2783 int object_insert_ptcache(Object *ob) 
2784 {
2785         LinkData *link = NULL;
2786         int i = 0;
2787
2788         BLI_sortlist(&ob->pc_ids, pc_cmp);
2789
2790         for(link=ob->pc_ids.first, i = 0; link; link=link->next, i++) 
2791         {
2792                 int index = GET_INT_FROM_POINTER(link->data);
2793
2794                 if(i < index)
2795                         break;
2796         }
2797
2798         link = MEM_callocN(sizeof(LinkData), "PCLink");
2799         link->data = SET_INT_IN_POINTER(i);
2800         BLI_addtail(&ob->pc_ids, link);
2801
2802         return i;
2803 }
2804
2805 #if 0
2806 static int pc_findindex(ListBase *listbase, int index)
2807 {
2808         LinkData *link= NULL;
2809         int number= 0;
2810         
2811         if (listbase == NULL) return -1;
2812         
2813         link= listbase->first;
2814         while (link) {
2815                 if ((int)link->data == index)
2816                         return number;
2817                 
2818                 number++;
2819                 link= link->next;
2820         }
2821         
2822         return -1;
2823 }
2824
2825 void object_delete_ptcache(Object *ob, int index) 
2826 {
2827         int list_index = pc_findindex(&ob->pc_ids, index);
2828         LinkData *link = BLI_findlink(&ob->pc_ids, list_index);
2829         BLI_freelinkN(&ob->pc_ids, link);
2830 }
2831 #endif
2832
2833 /* shape key utility function */
2834
2835 /************************* Mesh ************************/
2836 static KeyBlock *insert_meshkey(Scene *scene, Object *ob, const char *name, int from_mix)
2837 {
2838         Mesh *me= ob->data;
2839         Key *key= me->key;
2840         KeyBlock *kb;
2841         int newkey= 0;
2842
2843         if(key == NULL) {
2844                 key= me->key= add_key((ID *)me);
2845                 key->type= KEY_RELATIVE;
2846                 newkey= 1;
2847         }
2848
2849         if(newkey || from_mix==FALSE) {
2850                 /* create from mesh */
2851                 kb= add_keyblock(key, name);
2852                 mesh_to_key(me, kb);
2853         }
2854         else {
2855                 /* copy from current values */
2856                 float *data= do_ob_key(scene, ob);
2857
2858                 /* create new block with prepared data */
2859                 kb= add_keyblock(key, name);
2860                 kb->data= data;
2861                 kb->totelem= me->totvert;
2862         }
2863
2864         return kb;
2865 }
2866 /************************* Lattice ************************/
2867 static KeyBlock *insert_lattkey(Scene *scene, Object *ob, const char *name, int from_mix)
2868 {
2869         Lattice *lt= ob->data;
2870         Key *key= lt->key;
2871         KeyBlock *kb;
2872         int newkey= 0;
2873
2874         if(key==NULL) {
2875                 key= lt->key= add_key( (ID *)lt);
2876                 key->type= KEY_RELATIVE;
2877                 newkey= 1;
2878         }
2879
2880         if(newkey || from_mix==FALSE) {
2881                 kb= add_keyblock(key, name);
2882                 if (!newkey) {
2883                         KeyBlock *basekb= (KeyBlock *)key->block.first;
2884                         kb->data= MEM_dupallocN(basekb->data);
2885                         kb->totelem= basekb->totelem;
2886                 }
2887                 else {
2888                         latt_to_key(lt, kb);
2889                 }
2890         }
2891         else {
2892                 /* copy from current values */
2893                 float *data= do_ob_key(scene, ob);
2894
2895                 /* create new block with prepared data */
2896                 kb= add_keyblock(key, name);
2897                 kb->totelem= lt->pntsu*lt->pntsv*lt->pntsw;
2898                 kb->data= data;
2899         }
2900
2901         return kb;
2902 }
2903 /************************* Curve ************************/
2904 static KeyBlock *insert_curvekey(Scene *scene, Object *ob, const char *name, int from_mix)
2905 {
2906         Curve *cu= ob->data;
2907         Key *key= cu->key;
2908         KeyBlock *kb;
2909         ListBase *lb= BKE_curve_nurbs(cu);
2910         int newkey= 0;
2911
2912         if(key==NULL) {
2913                 key= cu->key= add_key( (ID *)cu);
2914                 key->type = KEY_RELATIVE;
2915                 newkey= 1;
2916         }
2917
2918         if(newkey || from_mix==FALSE) {
2919                 /* create from curve */
2920                 kb= add_keyblock(key, name);
2921                 if (!newkey) {
2922                         KeyBlock *basekb= (KeyBlock *)key->block.first;
2923                         kb->data= MEM_dupallocN(basekb->data);
2924                         kb->totelem= basekb->totelem;
2925                 }
2926                 else {
2927                         curve_to_key(cu, kb, lb);
2928                 }
2929         }
2930         else {
2931                 /* copy from current values */
2932                 float *data= do_ob_key(scene, ob);
2933
2934                 /* create new block with prepared data */
2935                 kb= add_keyblock(key, name);
2936                 kb->totelem= count_curveverts(lb);
2937                 kb->data= data;
2938         }
2939
2940         return kb;
2941 }
2942
2943 KeyBlock *object_insert_shape_key(Scene *scene, Object *ob, const char *name, int from_mix)
2944 {
2945         if(ob->type==OB_MESH)                                    return insert_meshkey(scene, ob, name, from_mix);
2946         else if ELEM(ob->type, OB_CURVE, OB_SURF)return insert_curvekey(scene, ob, name, from_mix);
2947         else if(ob->type==OB_LATTICE)                    return insert_lattkey(scene, ob, name, from_mix);
2948         else                                                                     return NULL;
2949 }
2950
2951 /* most important if this is modified it should _always_ return True, in certain
2952  * cases false positives are hard to avoid (shape keys for eg)
2953  */
2954 int object_is_modified(Scene *scene, Object *ob)
2955 {
2956         int flag= 0;
2957
2958         if(ob_get_key(ob)) {
2959                 flag |= eModifierMode_Render;
2960         }
2961         else {
2962                 ModifierData *md;
2963                 /* cloth */
2964                 for(md=modifiers_getVirtualModifierList(ob); md && (flag != (eModifierMode_Render | eModifierMode_Realtime)); md=md->next) {
2965                         if((flag & eModifierMode_Render) == 0   && modifier_isEnabled(scene, md, eModifierMode_Render))         flag |= eModifierMode_Render;
2966                         if((flag & eModifierMode_Realtime) == 0 && modifier_isEnabled(scene, md, eModifierMode_Realtime))       flag |= eModifierMode_Realtime;
2967                 }
2968         }
2969
2970         return flag;
2971 }
2972
2973 static void copy_object__forwardModifierLinks(void *UNUSED(userData), Object *UNUSED(ob), ID **idpoin)
2974 {
2975         /* this is copied from ID_NEW; it might be better to have a macro */
2976         if(*idpoin && (*idpoin)->newid) *idpoin = (*idpoin)->newid;
2977 }
2978
2979 void object_relink(Object *ob)
2980 {
2981         if(ob->id.lib)
2982                 return;
2983
2984         relink_constraints(&ob->constraints);
2985         if (ob->pose){
2986                 bPoseChannel *chan;
2987                 for (chan = ob->pose->chanbase.first; chan; chan=chan->next){
2988                         relink_constraints(&chan->constraints);
2989                 }
2990         }
2991         modifiers_foreachIDLink(ob, copy_object__forwardModifierLinks, NULL);
2992
2993         if(ob->adt)
2994                 BKE_relink_animdata(ob->adt);
2995
2996         ID_NEW(ob->parent);
2997
2998         ID_NEW(ob->proxy);
2999         ID_NEW(ob->proxy_group);
3000 }
3001
3002 MovieClip *object_get_movieclip(Scene *scene, Object *ob, int use_default)
3003 {
3004         MovieClip *clip= use_default ? scene->clip : NULL;
3005         bConstraint *con= ob->constraints.first, *scon= NULL;
3006
3007         while(con){
3008                 if(con->type==CONSTRAINT_TYPE_CAMERASOLVER){
3009                         if(scon==NULL || (scon->flag&CONSTRAINT_OFF))
3010                                 scon= con;
3011                 }
3012
3013                 con= con->next;
3014         }
3015
3016         if(scon) {
3017                 bCameraSolverConstraint *solver= scon->data;
3018                 if((solver->flag&CAMERASOLVER_ACTIVECLIP)==0)
3019                         clip= solver->clip;
3020                 else
3021                         clip= scene->clip;
3022         }
3023
3024         return clip;
3025 }