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