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