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