Keyed physics refresh:
[blender-staging.git] / source / blender / blenkernel / intern / object.c
1 /* object.c
2  *
3  * 
4  * $Id$
5  *
6  * ***** BEGIN GPL LICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21  *
22  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 #include <string.h>
33 #include <math.h>
34 #include <stdio.h>                      
35
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
39
40 #include "MEM_guardedalloc.h"
41
42 #include "DNA_anim_types.h"
43 #include "DNA_action_types.h"
44 #include "DNA_armature_types.h"
45 #include "DNA_camera_types.h"
46 #include "DNA_constraint_types.h"
47 #include "DNA_curve_types.h"
48 #include "DNA_group_types.h"
49 #include "DNA_lamp_types.h"
50 #include "DNA_lattice_types.h"
51 #include "DNA_material_types.h"
52 #include "DNA_mesh_types.h"
53 #include "DNA_meta_types.h"
54 #include "DNA_curve_types.h"
55 #include "DNA_meshdata_types.h"
56 #include "DNA_modifier_types.h"
57 #include "DNA_nla_types.h"
58 #include "DNA_object_types.h"
59 #include "DNA_object_force.h"
60 #include "DNA_object_fluidsim.h"
61 #include "DNA_outliner_types.h"
62 #include "DNA_particle_types.h"
63 #include "DNA_scene_types.h"
64 #include "DNA_screen_types.h"
65 #include "DNA_space_types.h"
66 #include "DNA_texture_types.h"
67 #include "DNA_userdef_types.h"
68 #include "DNA_view3d_types.h"
69 #include "DNA_world_types.h"
70
71 #include "BLI_blenlib.h"
72 #include "BLI_arithb.h"
73 #include "BLI_editVert.h"
74
75 #include "BKE_utildefines.h"
76
77 #include "BKE_main.h"
78 #include "BKE_global.h"
79
80 #include "BKE_armature.h"
81 #include "BKE_action.h"
82 #include "BKE_bullet.h"
83 #include "BKE_colortools.h"
84 #include "BKE_deform.h"
85 #include "BKE_DerivedMesh.h"
86 #include "BKE_nla.h"
87 #include "BKE_animsys.h"
88 #include "BKE_anim.h"
89 #include "BKE_blender.h"
90 #include "BKE_constraint.h"
91 #include "BKE_curve.h"
92 #include "BKE_displist.h"
93 #include "BKE_group.h"
94 #include "BKE_icons.h"
95 #include "BKE_key.h"
96 #include "BKE_lattice.h"
97 #include "BKE_library.h"
98 #include "BKE_mesh.h"
99 #include "BKE_mball.h"
100 #include "BKE_modifier.h"
101 #include "BKE_object.h"
102 #include "BKE_particle.h"
103 #include "BKE_pointcache.h"
104 #include "BKE_property.h"
105 #include "BKE_sca.h"
106 #include "BKE_scene.h"
107 #include "BKE_screen.h"
108 #include "BKE_softbody.h"
109
110 #include "LBM_fluidsim.h"
111
112 #ifndef DISABLE_PYTHON
113 #include "BPY_extern.h"
114 #endif
115
116 #include "GPU_material.h"
117
118 /* Local function protos */
119 static void solve_parenting (Scene *scene, Object *ob, Object *par, float obmat[][4], float slowmat[][4], int simul);
120
121 float originmat[3][3];  /* after where_is_object(), can be used in other functions (bad!) */
122
123 void clear_workob(Object *workob)
124 {
125         memset(workob, 0, sizeof(Object));
126         
127         workob->size[0]= workob->size[1]= workob->size[2]= 1.0;
128         
129 }
130
131 void copy_baseflags(struct Scene *scene)
132 {
133         Base *base= scene->base.first;
134         
135         while(base) {
136                 base->object->flag= base->flag;
137                 base= base->next;
138         }
139 }
140
141 void copy_objectflags(struct Scene *scene)
142 {
143         Base *base= scene->base.first;
144         
145         while(base) {
146                 base->flag= base->object->flag;
147                 base= base->next;
148         }
149 }
150
151 void update_base_layer(struct Scene *scene, Object *ob)
152 {
153         Base *base= scene->base.first;
154
155         while (base) {
156                 if (base->object == ob) base->lay= ob->lay;
157                 base= base->next;
158         }
159 }
160
161 void object_free_particlesystems(Object *ob)
162 {
163         while(ob->particlesystem.first){
164                 ParticleSystem *psys = ob->particlesystem.first;
165
166                 BLI_remlink(&ob->particlesystem,psys);
167
168                 psys_free(ob,psys);
169         }
170 }
171
172 void object_free_softbody(Object *ob)
173 {
174         if(ob->soft) {
175                 sbFree(ob->soft);
176                 ob->soft= NULL;
177         }
178 }
179
180 void object_free_bulletsoftbody(Object *ob)
181 {
182         if(ob->bsoft) {
183                 bsbFree(ob->bsoft);
184                 ob->bsoft= NULL;
185         }
186 }
187
188 void object_free_modifiers(Object *ob)
189 {
190         while (ob->modifiers.first) {
191                 ModifierData *md = ob->modifiers.first;
192
193                 BLI_remlink(&ob->modifiers, md);
194
195                 modifier_free(md);
196         }
197
198         /* particle modifiers were freed, so free the particlesystems as well */
199         object_free_particlesystems(ob);
200
201         /* same for softbody */
202         object_free_softbody(ob);
203 }
204
205 /* here we will collect all local displist stuff */
206 /* also (ab)used in depsgraph */
207 void object_free_display(Object *ob)
208 {
209         if(ob->derivedDeform) {
210                 ob->derivedDeform->needsFree = 1;
211                 ob->derivedDeform->release(ob->derivedDeform);
212                 ob->derivedDeform= NULL;
213         }
214         if(ob->derivedFinal) {
215                 ob->derivedFinal->needsFree = 1;
216                 ob->derivedFinal->release(ob->derivedFinal);
217                 ob->derivedFinal= NULL;
218         }
219         
220         freedisplist(&ob->disp);
221 }
222
223 /* do not free object itself */
224 void free_object(Object *ob)
225 {
226         int a;
227         
228         object_free_display(ob);
229         
230         /* disconnect specific data */
231         if(ob->data) {
232                 ID *id= ob->data;
233                 id->us--;
234                 if(id->us==0) {
235                         if(ob->type==OB_MESH) unlink_mesh(ob->data);
236                         else if(ob->type==OB_CURVE) unlink_curve(ob->data);
237                         else if(ob->type==OB_MBALL) unlink_mball(ob->data);
238                 }
239                 ob->data= 0;
240         }
241         
242         for(a=0; a<ob->totcol; a++) {
243                 if(ob->mat[a]) ob->mat[a]->id.us--;
244         }
245         if(ob->mat) MEM_freeN(ob->mat);
246         ob->mat= 0;
247         if(ob->bb) MEM_freeN(ob->bb); 
248         ob->bb= 0;
249         if(ob->path) free_path(ob->path); 
250         ob->path= 0;
251         if(ob->adt) BKE_free_animdata((ID *)ob);
252         if(ob->poselib) ob->poselib->id.us--;
253         if(ob->dup_group) ob->dup_group->id.us--;
254         if(ob->defbase.first)
255                 BLI_freelistN(&ob->defbase);
256         if(ob->pose)
257                 free_pose(ob->pose);
258         free_properties(&ob->prop);
259         object_free_modifiers(ob);
260         
261         free_sensors(&ob->sensors);
262         free_controllers(&ob->controllers);
263         free_actuators(&ob->actuators);
264         
265         free_constraints(&ob->constraints);
266
267 #ifndef DISABLE_PYTHON  
268         BPY_free_scriptlink(&ob->scriptlink);
269 #endif
270         
271         if(ob->pd){
272                 if(ob->pd->tex)
273                         ob->pd->tex->id.us--;
274                 MEM_freeN(ob->pd);
275         }
276         if(ob->soft) sbFree(ob->soft);
277         if(ob->bsoft) bsbFree(ob->bsoft);
278         if(ob->gpulamp.first) GPU_lamp_free(ob);
279 }
280
281 static void unlink_object__unlinkModifierLinks(void *userData, Object *ob, Object **obpoin)
282 {
283         Object *unlinkOb = userData;
284
285         if (*obpoin==unlinkOb) {
286                 *obpoin = NULL;
287                 ob->recalc |= OB_RECALC;
288         }
289 }
290 void unlink_object(Scene *scene, Object *ob)
291 {
292         Object *obt;
293         Material *mat;
294         World *wrld;
295         bScreen *sc;
296         Scene *sce;
297         Curve *cu;
298         Tex *tex;
299         Group *group;
300         Camera *camera;
301         bConstraint *con;
302         //bActionStrip *strip; // XXX animsys 
303         ModifierData *md;
304         int a;
305         
306         unlink_controllers(&ob->controllers);
307         unlink_actuators(&ob->actuators);
308         
309         /* check all objects: parents en bevels and fields, also from libraries */
310         obt= G.main->object.first;
311         while(obt) {
312                 if(obt->proxy==ob)
313                         obt->proxy= NULL;
314                 if(obt->proxy_from==ob) {
315                         obt->proxy_from= NULL;
316                         obt->recalc |= OB_RECALC_OB;
317                 }
318                 if(obt->proxy_group==ob)
319                         obt->proxy_group= NULL;
320                 
321                 if(obt->parent==ob) {
322                         obt->parent= NULL;
323                         obt->recalc |= OB_RECALC;
324                 }
325                 
326                 if(obt->track==ob) {
327                         obt->track= NULL;
328                         obt->recalc |= OB_RECALC_OB;
329                 }
330                 
331                 modifiers_foreachObjectLink(obt, unlink_object__unlinkModifierLinks, ob);
332                 
333                 if ELEM(obt->type, OB_CURVE, OB_FONT) {
334                         cu= obt->data;
335
336                         if(cu->bevobj==ob) {
337                                 cu->bevobj= NULL;
338                                 obt->recalc |= OB_RECALC;
339                         }
340                         if(cu->taperobj==ob) {
341                                 cu->taperobj= NULL;
342                                 obt->recalc |= OB_RECALC;
343                         }
344                         if(cu->textoncurve==ob) {
345                                 cu->textoncurve= NULL;
346                                 obt->recalc |= OB_RECALC;
347                         }
348                 }
349                 else if(obt->type==OB_ARMATURE && obt->pose) {
350                         bPoseChannel *pchan;
351                         for(pchan= obt->pose->chanbase.first; pchan; pchan= pchan->next) {
352                                 for (con = pchan->constraints.first; con; con=con->next) {
353                                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
354                                         ListBase targets = {NULL, NULL};
355                                         bConstraintTarget *ct;
356                                         
357                                         if (cti && cti->get_constraint_targets) {
358                                                 cti->get_constraint_targets(con, &targets);
359                                                 
360                                                 for (ct= targets.first; ct; ct= ct->next) {
361                                                         if (ct->tar == ob) {
362                                                                 ct->tar = NULL;
363                                                                 strcpy(ct->subtarget, "");
364                                                                 obt->recalc |= OB_RECALC_DATA;
365                                                         }
366                                                 }
367                                                 
368                                                 if (cti->flush_constraint_targets)
369                                                         cti->flush_constraint_targets(con, &targets, 0);
370                                         }
371                                 }
372                                 if(pchan->custom==ob)
373                                         pchan->custom= NULL;
374                         }
375                 }
376                 
377                 sca_remove_ob_poin(obt, ob);
378                 
379                 for (con = obt->constraints.first; con; con=con->next) {
380                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
381                         ListBase targets = {NULL, NULL};
382                         bConstraintTarget *ct;
383                         
384                         if (cti && cti->get_constraint_targets) {
385                                 cti->get_constraint_targets(con, &targets);
386                                 
387                                 for (ct= targets.first; ct; ct= ct->next) {
388                                         if (ct->tar == ob) {
389                                                 ct->tar = NULL;
390                                                 strcpy(ct->subtarget, "");
391                                                 obt->recalc |= OB_RECALC_DATA;
392                                         }
393                                 }
394                                 
395                                 if (cti->flush_constraint_targets)
396                                         cti->flush_constraint_targets(con, &targets, 0);
397                         }
398                 }
399                 
400                 /* object is deflector or field */
401                 if(ob->pd) {
402                         if(obt->soft)
403                                 obt->recalc |= OB_RECALC_DATA;
404
405                         /* cloth */
406                         for(md=obt->modifiers.first; md; md=md->next)
407                                 if(md->type == eModifierType_Cloth)
408                                         obt->recalc |= OB_RECALC_DATA;
409                 }
410                 
411                 /* strips */
412 #if 0 // XXX old animation system
413                 for(strip= obt->nlastrips.first; strip; strip= strip->next) {
414                         if(strip->object==ob)
415                                 strip->object= NULL;
416                         
417                         if(strip->modifiers.first) {
418                                 bActionModifier *amod;
419                                 for(amod= strip->modifiers.first; amod; amod= amod->next)
420                                         if(amod->ob==ob)
421                                                 amod->ob= NULL;
422                         }
423                 }
424 #endif // XXX old animation system
425
426                 /* particle systems */
427                 if(obt->particlesystem.first) {
428                         ParticleSystem *tpsys= obt->particlesystem.first;
429                         for(; tpsys; tpsys=tpsys->next) {
430                                 KeyedParticleTarget *kpt = tpsys->keyed_targets.first;
431                                 for(; kpt; kpt=kpt->next) {
432                                         if(kpt->ob==ob) {
433                                                 BLI_remlink(&tpsys->keyed_targets, kpt);
434                                                 MEM_freeN(kpt);
435                                                 obt->recalc |= OB_RECALC_DATA;
436                                                 break;
437                                         }
438                                 }
439
440                                 if(tpsys->target_ob==ob) {
441                                         tpsys->target_ob= NULL;
442                                         obt->recalc |= OB_RECALC_DATA;
443                                 }
444
445                                 if(tpsys->part->dup_ob==ob)
446                                         tpsys->part->dup_ob= NULL;
447
448                                 if(tpsys->part->flag&PART_STICKY) {
449                                         ParticleData *pa;
450                                         int p;
451
452                                         for(p=0,pa=tpsys->particles; p<tpsys->totpart; p++,pa++) {
453                                                 if(pa->stick_ob==ob) {
454                                                         pa->stick_ob= 0;
455                                                         pa->flag &= ~PARS_STICKY;
456                                                 }
457                                         }
458                                 }
459                         }
460                         if(ob->pd)
461                                 obt->recalc |= OB_RECALC_DATA;
462                 }
463
464                 obt= obt->id.next;
465         }
466         
467         /* materials */
468         mat= G.main->mat.first;
469         while(mat) {
470         
471                 for(a=0; a<MAX_MTEX; a++) {
472                         if(mat->mtex[a] && ob==mat->mtex[a]->object) {
473                                 /* actually, test for lib here... to do */
474                                 mat->mtex[a]->object= NULL;
475                         }
476                 }
477
478                 mat= mat->id.next;
479         }
480         
481         /* textures */
482         tex= G.main->tex.first;
483         while(tex) {
484                 if(tex->env) {
485                         if(tex->env->object == ob) tex->env->object= NULL;
486                 }
487                 tex= tex->id.next;
488         }
489         
490         /* mballs (scene==NULL when called from library.c) */
491         if(scene && ob->type==OB_MBALL) {
492                 obt= find_basis_mball(scene, ob);
493                 if(obt) freedisplist(&obt->disp);
494         }
495         
496         /* worlds */
497         wrld= G.main->world.first;
498         while(wrld) {
499                 if(wrld->id.lib==NULL) {
500                         for(a=0; a<MAX_MTEX; a++) {
501                                 if(wrld->mtex[a] && ob==wrld->mtex[a]->object)
502                                         wrld->mtex[a]->object= NULL;
503                         }
504                 }
505                 
506                 wrld= wrld->id.next;
507         }
508                 
509         /* scenes */
510         sce= G.main->scene.first;
511         while(sce) {
512                 if(sce->id.lib==NULL) {
513                         if(sce->camera==ob) sce->camera= NULL;
514                         if(sce->toolsettings->skgen_template==ob) sce->toolsettings->skgen_template = NULL;
515                 }
516                 sce= sce->id.next;
517         }
518         
519 #if 0 // XXX old animation system
520         /* ipos */
521         ipo= G.main->ipo.first;
522         while(ipo) {
523                 if(ipo->id.lib==NULL) {
524                         IpoCurve *icu;
525                         for(icu= ipo->curve.first; icu; icu= icu->next) {
526                                 if(icu->driver && icu->driver->ob==ob)
527                                         icu->driver->ob= NULL;
528                         }
529                 }
530                 ipo= ipo->id.next;
531         }
532 #endif // XXX old animation system
533         
534         /* screens */
535         sc= G.main->screen.first;
536         while(sc) {
537                 ScrArea *sa= sc->areabase.first;
538                 while(sa) {
539                         SpaceLink *sl;
540
541                         for (sl= sa->spacedata.first; sl; sl= sl->next) {
542                                 if(sl->spacetype==SPACE_VIEW3D) {
543                                         View3D *v3d= (View3D*) sl;
544
545                                         if(v3d->camera==ob) {
546                                                 v3d->camera= NULL;
547                                                 // XXX if(v3d->persp==V3D_CAMOB) v3d->persp= V3D_PERSP;
548                                         }
549                                         if(v3d->localvd && v3d->localvd->camera==ob ) {
550                                                 v3d->localvd->camera= NULL;
551                                                 // XXX if(v3d->localvd->persp==V3D_CAMOB) v3d->localvd->persp= V3D_PERSP;
552                                         }
553                                 }
554                                 else if(sl->spacetype==SPACE_OUTLINER) {
555                                         SpaceOops *so= (SpaceOops *)sl;
556
557                                         if(so->treestore) {
558                                                 TreeStoreElem *tselem= so->treestore->data;
559                                                 int a;
560                                                 for(a=0; a<so->treestore->usedelem; a++, tselem++) {
561                                                         if(tselem->id==(ID *)ob) tselem->id= NULL;
562                                                 }
563                                         }
564                                 }
565                         }
566
567                         sa= sa->next;
568                 }
569                 sc= sc->id.next;
570         }
571
572         /* groups */
573         group= G.main->group.first;
574         while(group) {
575                 rem_from_group(group, ob);
576                 group= group->id.next;
577         }
578         
579         /* cameras */
580         camera= G.main->camera.first;
581         while(camera) {
582                 if (camera->dof_ob==ob) {
583                         camera->dof_ob = NULL;
584                 }
585                 camera= camera->id.next;
586         }
587 }
588
589 int exist_object(Object *obtest)
590 {
591         Object *ob;
592         
593         if(obtest==NULL) return 0;
594         
595         ob= G.main->object.first;
596         while(ob) {
597                 if(ob==obtest) return 1;
598                 ob= ob->id.next;
599         }
600         return 0;
601 }
602
603 void *add_camera(char *name)
604 {
605         Camera *cam;
606         
607         cam=  alloc_libblock(&G.main->camera, ID_CA, name);
608
609         cam->lens= 35.0f;
610         cam->angle= 49.14f;
611         cam->clipsta= 0.1f;
612         cam->clipend= 100.0f;
613         cam->drawsize= 0.5f;
614         cam->ortho_scale= 6.0;
615         cam->flag |= CAM_SHOWTITLESAFE;
616         cam->passepartalpha = 0.2f;
617         
618         return cam;
619 }
620
621 Camera *copy_camera(Camera *cam)
622 {
623         Camera *camn;
624         
625         camn= copy_libblock(cam);
626         camn->adt= BKE_copy_animdata(cam->adt);
627
628 #ifndef DISABLE_PYTHON
629         BPY_copy_scriptlink(&camn->scriptlink);
630 #endif  
631         return camn;
632 }
633
634
635
636 void make_local_camera(Camera *cam)
637 {
638         Object *ob;
639         Camera *camn;
640         int local=0, lib=0;
641
642         /* - only lib users: do nothing
643             * - only local users: set flag
644             * - mixed: make copy
645             */
646         
647         if(cam->id.lib==0) return;
648         if(cam->id.us==1) {
649                 cam->id.lib= 0;
650                 cam->id.flag= LIB_LOCAL;
651                 new_id(0, (ID *)cam, 0);
652                 return;
653         }
654         
655         ob= G.main->object.first;
656         while(ob) {
657                 if(ob->data==cam) {
658                         if(ob->id.lib) lib= 1;
659                         else local= 1;
660                 }
661                 ob= ob->id.next;
662         }
663         
664         if(local && lib==0) {
665                 cam->id.lib= 0;
666                 cam->id.flag= LIB_LOCAL;
667                 new_id(0, (ID *)cam, 0);
668         }
669         else if(local && lib) {
670                 camn= copy_camera(cam);
671                 camn->id.us= 0;
672                 
673                 ob= G.main->object.first;
674                 while(ob) {
675                         if(ob->data==cam) {
676                                 
677                                 if(ob->id.lib==0) {
678                                         ob->data= camn;
679                                         camn->id.us++;
680                                         cam->id.us--;
681                                 }
682                         }
683                         ob= ob->id.next;
684                 }
685         }
686 }
687
688 /* get the camera's dof value, takes the dof object into account */
689 float dof_camera(Object *ob)
690 {
691         Camera *cam = (Camera *)ob->data; 
692         if (ob->type != OB_CAMERA)
693                 return 0.0f;
694         if (cam->dof_ob) {      
695                 /* too simple, better to return the distance on the view axis only
696                  * return VecLenf(ob->obmat[3], cam->dof_ob->obmat[3]); */
697                 float mat[4][4], obmat[4][4];
698                 
699                 Mat4CpyMat4(obmat, ob->obmat);
700                 Mat4Ortho(obmat);
701                 Mat4Invert(ob->imat, obmat);
702                 Mat4MulMat4(mat, cam->dof_ob->obmat, ob->imat);
703                 return (float)fabs(mat[3][2]);
704         }
705         return cam->YF_dofdist;
706 }
707
708 void *add_lamp(char *name)
709 {
710         Lamp *la;
711         
712         la=  alloc_libblock(&G.main->lamp, ID_LA, name);
713         
714         la->r= la->g= la->b= la->k= 1.0f;
715         la->haint= la->energy= 1.0f;
716         la->dist= 20.0f;
717         la->spotsize= 45.0f;
718         la->spotblend= 0.15f;
719         la->att2= 1.0f;
720         la->mode= LA_SHAD_BUF;
721         la->bufsize= 512;
722         la->clipsta= 0.5f;
723         la->clipend= 40.0f;
724         la->shadspotsize= 45.0f;
725         la->samp= 3;
726         la->bias= 1.0f;
727         la->soft= 3.0f;
728         la->ray_samp= la->ray_sampy= la->ray_sampz= 1; 
729         la->area_size=la->area_sizey=la->area_sizez= 1.0f; 
730         la->buffers= 1;
731         la->buftype= LA_SHADBUF_HALFWAY;
732         la->ray_samp_method = LA_SAMP_HALTON;
733         la->adapt_thresh = 0.001f;
734         la->preview=NULL;
735         la->falloff_type = LA_FALLOFF_INVLINEAR;
736         la->curfalloff = curvemapping_add(1, 0.0f, 1.0f, 1.0f, 0.0f);
737         la->sun_effect_type = 0;
738         la->horizon_brightness = 1.0;
739         la->spread = 1.0;
740         la->sun_brightness = 1.0;
741         la->sun_size = 1.0;
742         la->backscattered_light = 1.0f;
743         la->atm_turbidity = 2.0f;
744         la->atm_inscattering_factor = 1.0f;
745         la->atm_extinction_factor = 1.0f;
746         la->atm_distance_factor = 1.0f;
747         la->sun_intensity = 1.0f;
748         la->skyblendtype= MA_RAMP_ADD;
749         la->skyblendfac= 1.0f;
750         la->sky_colorspace= BLI_CS_CIE;
751         la->sky_exposure= 1.0f;
752         
753         curvemapping_initialize(la->curfalloff);
754         return la;
755 }
756
757 Lamp *copy_lamp(Lamp *la)
758 {
759         Lamp *lan;
760         int a;
761         
762         lan= copy_libblock(la);
763
764         for(a=0; a<MAX_MTEX; a++) {
765                 if(lan->mtex[a]) {
766                         lan->mtex[a]= MEM_mallocN(sizeof(MTex), "copylamptex");
767                         memcpy(lan->mtex[a], la->mtex[a], sizeof(MTex));
768                         id_us_plus((ID *)lan->mtex[a]->tex);
769                 }
770         }
771         
772         lan->curfalloff = curvemapping_copy(la->curfalloff);
773         
774 #if 0 // XXX old animation system
775         id_us_plus((ID *)lan->ipo);
776 #endif // XXX old animation system
777
778         if (la->preview) lan->preview = BKE_previewimg_copy(la->preview);
779 #ifndef DISABLE_PYTHON
780         BPY_copy_scriptlink(&la->scriptlink);
781 #endif
782         return lan;
783 }
784
785 void make_local_lamp(Lamp *la)
786 {
787         Object *ob;
788         Lamp *lan;
789         int local=0, lib=0;
790
791         /* - only lib users: do nothing
792             * - only local users: set flag
793             * - mixed: make copy
794             */
795         
796         if(la->id.lib==0) return;
797         if(la->id.us==1) {
798                 la->id.lib= 0;
799                 la->id.flag= LIB_LOCAL;
800                 new_id(0, (ID *)la, 0);
801                 return;
802         }
803         
804         ob= G.main->object.first;
805         while(ob) {
806                 if(ob->data==la) {
807                         if(ob->id.lib) lib= 1;
808                         else local= 1;
809                 }
810                 ob= ob->id.next;
811         }
812         
813         if(local && lib==0) {
814                 la->id.lib= 0;
815                 la->id.flag= LIB_LOCAL;
816                 new_id(0, (ID *)la, 0);
817         }
818         else if(local && lib) {
819                 lan= copy_lamp(la);
820                 lan->id.us= 0;
821                 
822                 ob= G.main->object.first;
823                 while(ob) {
824                         if(ob->data==la) {
825                                 
826                                 if(ob->id.lib==0) {
827                                         ob->data= lan;
828                                         lan->id.us++;
829                                         la->id.us--;
830                                 }
831                         }
832                         ob= ob->id.next;
833                 }
834         }
835 }
836
837 void free_camera(Camera *ca)
838 {
839 #ifndef DISABLE_PYTHON
840         BPY_free_scriptlink(&ca->scriptlink);
841 #endif
842         BKE_free_animdata((ID *)ca);
843 }
844
845 void free_lamp(Lamp *la)
846 {
847         MTex *mtex;
848         int a;
849
850         /* scriptlinks */
851 #ifndef DISABLE_PYTHON
852         BPY_free_scriptlink(&la->scriptlink);
853 #endif
854
855         for(a=0; a<MAX_MTEX; a++) {
856                 mtex= la->mtex[a];
857                 if(mtex && mtex->tex) mtex->tex->id.us--;
858                 if(mtex) MEM_freeN(mtex);
859         }
860         
861         BKE_free_animdata((ID *)la);
862
863         curvemapping_free(la->curfalloff);
864         
865         BKE_previewimg_free(&la->preview);
866         BKE_icon_delete(&la->id);
867         la->id.icon_id = 0;
868 }
869
870 void *add_wave()
871 {
872         return 0;
873 }
874
875
876 /* *************************************************** */
877
878 static void *add_obdata_from_type(int type)
879 {
880         switch (type) {
881         case OB_MESH: return add_mesh("Mesh");
882         case OB_CURVE: return add_curve("Curve", OB_CURVE);
883         case OB_SURF: return add_curve("Surf", OB_SURF);
884         case OB_FONT: return add_curve("Text", OB_FONT);
885         case OB_MBALL: return add_mball("Meta");
886         case OB_CAMERA: return add_camera("Camera");
887         case OB_LAMP: return add_lamp("Lamp");
888         case OB_LATTICE: return add_lattice("Lattice");
889         case OB_WAVE: return add_wave();
890         case OB_ARMATURE: return add_armature("Armature");
891         case OB_EMPTY: return NULL;
892         default:
893                 printf("add_obdata_from_type: Internal error, bad type: %d\n", type);
894                 return NULL;
895         }
896 }
897
898 static char *get_obdata_defname(int type)
899 {
900         switch (type) {
901         case OB_MESH: return "Mesh";
902         case OB_CURVE: return "Curve";
903         case OB_SURF: return "Surf";
904         case OB_FONT: return "Font";
905         case OB_MBALL: return "Mball";
906         case OB_CAMERA: return "Camera";
907         case OB_LAMP: return "Lamp";
908         case OB_LATTICE: return "Lattice";
909         case OB_WAVE: return "Wave";
910         case OB_ARMATURE: return "Armature";
911         case OB_EMPTY: return "Empty";
912         default:
913                 printf("get_obdata_defname: Internal error, bad type: %d\n", type);
914                 return "Empty";
915         }
916 }
917
918 /* more general add: creates minimum required data, but without vertices etc. */
919 Object *add_only_object(int type, char *name)
920 {
921         Object *ob;
922
923         ob= alloc_libblock(&G.main->object, ID_OB, name);
924
925         /* default object vars */
926         ob->type= type;
927         /* ob->transflag= OB_QUAT; */
928
929 #if 0 /* not used yet */
930         QuatOne(ob->quat);
931         QuatOne(ob->dquat);
932 #endif 
933
934         ob->col[0]= ob->col[1]= ob->col[2]= 1.0;
935         ob->col[3]= 1.0;
936
937         ob->loc[0]= ob->loc[1]= ob->loc[2]= 0.0;
938         ob->rot[0]= ob->rot[1]= ob->rot[2]= 0.0;
939         ob->size[0]= ob->size[1]= ob->size[2]= 1.0;
940
941         Mat4One(ob->constinv);
942         Mat4One(ob->parentinv);
943         Mat4One(ob->obmat);
944         ob->dt= OB_SHADED;
945         if(U.flag & USER_MAT_ON_OB) ob->colbits= -1;
946         ob->empty_drawtype= OB_ARROWS;
947         ob->empty_drawsize= 1.0;
948
949         if(type==OB_CAMERA || type==OB_LAMP) {
950                 ob->trackflag= OB_NEGZ;
951                 ob->upflag= OB_POSY;
952         }
953         else {
954                 ob->trackflag= OB_POSY;
955                 ob->upflag= OB_POSZ;
956         }
957         
958 #if 0 // XXX old animation system
959         ob->ipoflag = OB_OFFS_OB+OB_OFFS_PARENT;
960         ob->ipowin= ID_OB;      /* the ipowin shown */
961 #endif // XXX old animation system
962         
963         ob->dupon= 1; ob->dupoff= 0;
964         ob->dupsta= 1; ob->dupend= 100;
965         ob->dupfacesca = 1.0;
966
967         /* Game engine defaults*/
968         ob->mass= ob->inertia= 1.0f;
969         ob->formfactor= 0.4f;
970         ob->damping= 0.04f;
971         ob->rdamping= 0.1f;
972         ob->anisotropicFriction[0] = 1.0f;
973         ob->anisotropicFriction[1] = 1.0f;
974         ob->anisotropicFriction[2] = 1.0f;
975         ob->gameflag= OB_PROP|OB_COLLISION;
976         ob->margin = 0.0;
977         /* ob->pad3 == Contact Processing Threshold */
978         ob->m_contactProcessingThreshold = 1.;
979         
980         /* NT fluid sim defaults */
981         ob->fluidsimFlag = 0;
982         ob->fluidsimSettings = NULL;
983
984         return ob;
985 }
986
987 /* general add: to scene, with layer from area and default name */
988 /* creates minimum required data, but without vertices etc. */
989 Object *add_object(struct Scene *scene, int type)
990 {
991         Object *ob;
992         Base *base;
993         char name[32];
994
995         strcpy(name, get_obdata_defname(type));
996         ob = add_only_object(type, name);
997
998         ob->data= add_obdata_from_type(type);
999
1000         ob->lay= scene->lay;
1001
1002         base= scene_add_base(scene, ob);
1003         scene_select_base(scene, base);
1004         ob->recalc |= OB_RECALC;
1005
1006         return ob;
1007 }
1008
1009 SoftBody *copy_softbody(SoftBody *sb)
1010 {
1011         SoftBody *sbn;
1012         
1013         if (sb==NULL) return(NULL);
1014         
1015         sbn= MEM_dupallocN(sb);
1016         sbn->totspring= sbn->totpoint= 0;
1017         sbn->bpoint= NULL;
1018         sbn->bspring= NULL;
1019         
1020         sbn->keys= NULL;
1021         sbn->totkey= sbn->totpointkey= 0;
1022         
1023         sbn->scratch= NULL;
1024
1025         sbn->pointcache= BKE_ptcache_copy(sb->pointcache);
1026
1027         return sbn;
1028 }
1029
1030 BulletSoftBody *copy_bulletsoftbody(BulletSoftBody *bsb)
1031 {
1032         BulletSoftBody *bsbn;
1033
1034         if (bsb == NULL)
1035                 return NULL;
1036         bsbn = MEM_dupallocN(bsb);
1037         /* no pointer in this structure yet */
1038         return bsbn;
1039 }
1040
1041 ParticleSystem *copy_particlesystem(ParticleSystem *psys)
1042 {
1043         ParticleSystem *psysn;
1044         ParticleData *pa;
1045         int a;
1046
1047         psysn= MEM_dupallocN(psys);
1048         psysn->particles= MEM_dupallocN(psys->particles);
1049         psysn->child= MEM_dupallocN(psys->child);
1050         if(psysn->particles->keys)
1051                 psysn->particles->keys = MEM_dupallocN(psys->particles->keys);
1052
1053         for(a=0, pa=psysn->particles; a<psysn->totpart; a++, pa++) {
1054                 if(pa->hair)
1055                         pa->hair= MEM_dupallocN(pa->hair);
1056                 if(a)
1057                         pa->keys= (pa-1)->keys + (pa-1)->totkey;
1058         }
1059
1060         if(psys->soft) {
1061                 psysn->soft= copy_softbody(psys->soft);
1062                 psysn->soft->particles = psysn;
1063         }
1064
1065         if(psys->keyed_targets.first)
1066                 BLI_duplicatelist(&psysn->keyed_targets, &psys->keyed_targets);
1067         
1068         psysn->pathcache= NULL;
1069         psysn->childcache= NULL;
1070         psysn->edit= NULL;
1071         psysn->effectors.first= psysn->effectors.last= 0;
1072         
1073         psysn->pathcachebufs.first = psysn->pathcachebufs.last = NULL;
1074         psysn->childcachebufs.first = psysn->childcachebufs.last = NULL;
1075         psysn->reactevents.first = psysn->reactevents.last = NULL;
1076         psysn->renderdata = NULL;
1077         
1078         psysn->pointcache= BKE_ptcache_copy(psys->pointcache);
1079
1080         id_us_plus((ID *)psysn->part);
1081
1082         return psysn;
1083 }
1084
1085 void copy_object_particlesystems(Object *obn, Object *ob)
1086 {
1087         ParticleSystemModifierData *psmd;
1088         ParticleSystem *psys, *npsys;
1089         ModifierData *md;
1090
1091         obn->particlesystem.first= obn->particlesystem.last= NULL;
1092         for(psys=ob->particlesystem.first; psys; psys=psys->next) {
1093                 npsys= copy_particlesystem(psys);
1094
1095                 BLI_addtail(&obn->particlesystem, npsys);
1096
1097                 /* need to update particle modifiers too */
1098                 for(md=obn->modifiers.first; md; md=md->next) {
1099                         if(md->type==eModifierType_ParticleSystem) {
1100                                 psmd= (ParticleSystemModifierData*)md;
1101                                 if(psmd->psys==psys)
1102                                         psmd->psys= npsys;
1103                         }
1104                 }
1105         }
1106 }
1107
1108 void copy_object_softbody(Object *obn, Object *ob)
1109 {
1110         if(ob->soft)
1111                 obn->soft= copy_softbody(ob->soft);
1112 }
1113
1114 static void copy_object_pose(Object *obn, Object *ob)
1115 {
1116         bPoseChannel *chan;
1117         
1118         /* note: need to clear obn->pose pointer first, so that copy_pose works (otherwise there's a crash) */
1119         obn->pose= NULL;
1120         copy_pose(&obn->pose, ob->pose, 1);     /* 1 = copy constraints */
1121
1122         for (chan = obn->pose->chanbase.first; chan; chan=chan->next){
1123                 bConstraint *con;
1124                 
1125                 chan->flag &= ~(POSE_LOC|POSE_ROT|POSE_SIZE);
1126                 
1127                 for (con= chan->constraints.first; con; con= con->next) {
1128                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1129                         ListBase targets = {NULL, NULL};
1130                         bConstraintTarget *ct;
1131                         
1132 #if 0 // XXX old animation system
1133                         /* note that we can't change lib linked ipo blocks. for making
1134                          * proxies this still works correct however because the object
1135                          * is changed to object->proxy_from when evaluating the driver. */
1136                         if(con->ipo && !con->ipo->id.lib) {
1137                                 IpoCurve *icu;
1138                                 
1139                                 con->ipo= copy_ipo(con->ipo);
1140                                 
1141                                 for(icu= con->ipo->curve.first; icu; icu= icu->next) {
1142                                         if(icu->driver && icu->driver->ob==ob)
1143                                                 icu->driver->ob= obn;
1144                                 }
1145                         }
1146 #endif // XXX old animation system
1147                         
1148                         if (cti && cti->get_constraint_targets) {
1149                                 cti->get_constraint_targets(con, &targets);
1150                                 
1151                                 for (ct= targets.first; ct; ct= ct->next) {
1152                                         if (ct->tar == ob)
1153                                                 ct->tar = obn;
1154                                 }
1155                                 
1156                                 if (cti->flush_constraint_targets)
1157                                         cti->flush_constraint_targets(con, &targets, 0);
1158                         }
1159                 }
1160         }
1161 }
1162
1163 Object *copy_object(Object *ob)
1164 {
1165         Object *obn;
1166         ModifierData *md;
1167         int a;
1168
1169         obn= copy_libblock(ob);
1170         
1171         if(ob->totcol) {
1172                 obn->mat= MEM_dupallocN(ob->mat);
1173         }
1174         
1175         if(ob->bb) obn->bb= MEM_dupallocN(ob->bb);
1176         obn->path= NULL;
1177         obn->flag &= ~OB_FROMGROUP;
1178         
1179         obn->modifiers.first = obn->modifiers.last= NULL;
1180         
1181         for (md=ob->modifiers.first; md; md=md->next) {
1182                 ModifierData *nmd = modifier_new(md->type);
1183                 modifier_copyData(md, nmd);
1184                 BLI_addtail(&obn->modifiers, nmd);
1185         }
1186 #ifndef DISABLE_PYTHON  
1187         BPY_copy_scriptlink(&ob->scriptlink);
1188 #endif
1189         obn->prop.first = obn->prop.last = NULL;
1190         copy_properties(&obn->prop, &ob->prop);
1191         
1192         copy_sensors(&obn->sensors, &ob->sensors);
1193         copy_controllers(&obn->controllers, &ob->controllers);
1194         copy_actuators(&obn->actuators, &ob->actuators);
1195         
1196         if(ob->pose) {
1197                 copy_object_pose(obn, ob);
1198                 /* backwards compat... non-armatures can get poses in older files? */
1199                 if(ob->type==OB_ARMATURE)
1200                         armature_rebuild_pose(obn, obn->data);
1201         }
1202         copy_defgroups(&obn->defbase, &ob->defbase);
1203         copy_constraints(&obn->constraints, &ob->constraints);
1204
1205         /* increase user numbers */
1206         id_us_plus((ID *)obn->data);
1207         id_us_plus((ID *)obn->dup_group);
1208         // FIXME: add this for animdata too...
1209
1210         for(a=0; a<obn->totcol; a++) id_us_plus((ID *)obn->mat[a]);
1211         
1212         obn->disp.first= obn->disp.last= NULL;
1213         
1214         if(ob->pd){
1215                 obn->pd= MEM_dupallocN(ob->pd);
1216                 if(obn->pd->tex)
1217                         id_us_plus(&(obn->pd->tex->id));
1218         }
1219         obn->soft= copy_softbody(ob->soft);
1220         obn->bsoft = copy_bulletsoftbody(ob->bsoft);
1221
1222         copy_object_particlesystems(obn, ob);
1223         
1224         obn->derivedDeform = NULL;
1225         obn->derivedFinal = NULL;
1226
1227         obn->gpulamp.first = obn->gpulamp.last = NULL;
1228
1229         return obn;
1230 }
1231
1232 void expand_local_object(Object *ob)
1233 {
1234         //bActionStrip *strip;
1235         ParticleSystem *psys;
1236         int a;
1237
1238 #if 0 // XXX old animation system
1239         id_lib_extern((ID *)ob->action);
1240         id_lib_extern((ID *)ob->ipo);
1241 #endif // XXX old animation system
1242         id_lib_extern((ID *)ob->data);
1243         id_lib_extern((ID *)ob->dup_group);
1244         
1245         for(a=0; a<ob->totcol; a++) {
1246                 id_lib_extern((ID *)ob->mat[a]);
1247         }
1248 #if 0 // XXX old animation system
1249         for (strip=ob->nlastrips.first; strip; strip=strip->next) {
1250                 id_lib_extern((ID *)strip->act);
1251         }
1252 #endif // XXX old animation system
1253         for(psys=ob->particlesystem.first; psys; psys=psys->next)
1254                 id_lib_extern((ID *)psys->part);
1255 }
1256
1257 void make_local_object(Object *ob)
1258 {
1259         Object *obn;
1260         Scene *sce;
1261         Base *base;
1262         int local=0, lib=0;
1263
1264         /* - only lib users: do nothing
1265             * - only local users: set flag
1266             * - mixed: make copy
1267             */
1268         
1269         if(ob->id.lib==NULL) return;
1270         
1271         ob->proxy= ob->proxy_from= NULL;
1272         
1273         if(ob->id.us==1) {
1274                 ob->id.lib= NULL;
1275                 ob->id.flag= LIB_LOCAL;
1276                 new_id(0, (ID *)ob, 0);
1277
1278         }
1279         else {
1280                 sce= G.main->scene.first;
1281                 while(sce) {
1282                         base= sce->base.first;
1283                         while(base) {
1284                                 if(base->object==ob) {
1285                                         if(sce->id.lib) lib++;
1286                                         else local++;
1287                                         break;
1288                                 }
1289                                 base= base->next;
1290                         }
1291                         sce= sce->id.next;
1292                 }
1293                 
1294                 if(local && lib==0) {
1295                         ob->id.lib= 0;
1296                         ob->id.flag= LIB_LOCAL;
1297                         new_id(0, (ID *)ob, 0);
1298                 }
1299                 else if(local && lib) {
1300                         obn= copy_object(ob);
1301                         obn->id.us= 0;
1302                         
1303                         sce= G.main->scene.first;
1304                         while(sce) {
1305                                 if(sce->id.lib==0) {
1306                                         base= sce->base.first;
1307                                         while(base) {
1308                                                 if(base->object==ob) {
1309                                                         base->object= obn;
1310                                                         obn->id.us++;
1311                                                         ob->id.us--;
1312                                                 }
1313                                                 base= base->next;
1314                                         }
1315                                 }
1316                                 sce= sce->id.next;
1317                         }
1318                 }
1319         }
1320         
1321         expand_local_object(ob);
1322 }
1323
1324 /* returns true if the Object data is a from an external blend file (libdata) */
1325 int object_data_is_libdata(Object *ob)
1326 {
1327         if(!ob) return 0;
1328         if(ob->proxy) return 0;
1329         if(ob->id.lib) return 1;
1330         if(!ob->data) return 0;
1331         if(((ID *)ob->data)->lib) return 1;
1332
1333         return 0;
1334 }
1335
1336 /* *************** PROXY **************** */
1337
1338 /* when you make proxy, ensure the exposed layers are extern */
1339 void armature_set_id_extern(Object *ob)
1340 {
1341         bArmature *arm= ob->data;
1342         bPoseChannel *pchan;
1343         int lay= arm->layer_protected;
1344         
1345         for (pchan = ob->pose->chanbase.first; pchan; pchan=pchan->next) {
1346                 if(!(pchan->bone->layer & lay))
1347                         id_lib_extern((ID *)pchan->custom);
1348         }
1349                         
1350 }
1351
1352 /* proxy rule: lib_object->proxy_from == the one we borrow from, set temporally while object_update */
1353 /*             local_object->proxy == pointer to library object, saved in files and read */
1354 /*             local_object->proxy_group == pointer to group dupli-object, saved in files and read */
1355
1356 void object_make_proxy(Object *ob, Object *target, Object *gob)
1357 {
1358         /* paranoia checks */
1359         if(ob->id.lib || target->id.lib==NULL) {
1360                 printf("cannot make proxy\n");
1361                 return;
1362         }
1363         
1364         ob->proxy= target;
1365         ob->proxy_group= gob;
1366         id_lib_extern(&target->id);
1367         
1368         ob->recalc= target->recalc= OB_RECALC;
1369         
1370         /* copy transform */
1371         if(gob) {
1372                 VECCOPY(ob->loc, gob->loc);
1373                 VECCOPY(ob->rot, gob->rot);
1374                 VECCOPY(ob->size, gob->size);
1375                 
1376                 group_tag_recalc(gob->dup_group);
1377         }
1378         else {
1379                 VECCOPY(ob->loc, target->loc);
1380                 VECCOPY(ob->rot, target->rot);
1381                 VECCOPY(ob->size, target->size);
1382         }
1383         
1384         ob->parent= target->parent;     /* libdata */
1385         Mat4CpyMat4(ob->parentinv, target->parentinv);
1386 #if 0 // XXX old animation system
1387         ob->ipo= target->ipo;           /* libdata */
1388 #endif // XXX old animation system
1389         
1390         /* skip constraints, constraintchannels, nla? */
1391         
1392         /* set object type and link to data */
1393         ob->type= target->type;
1394         ob->data= target->data;
1395         id_us_plus((ID *)ob->data);             /* ensures lib data becomes LIB_EXTERN */
1396         
1397         /* copy material and index information */
1398         ob->actcol= ob->totcol= 0;
1399         if(ob->mat) MEM_freeN(ob->mat);
1400         ob->mat = NULL;
1401         if ((target->totcol) && (target->mat) && ELEM5(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL)) { //XXX OB_SUPPORT_MATERIAL
1402                 int i;
1403                 ob->colbits = target->colbits;
1404                 
1405                 ob->actcol= target->actcol;
1406                 ob->totcol= target->totcol;
1407                 
1408                 ob->mat = MEM_dupallocN(target->mat);
1409                 for(i=0; i<target->totcol; i++) {
1410                         /* dont need to run test_object_materials since we know this object is new and not used elsewhere */
1411                         id_us_plus((ID *)ob->mat[i]); 
1412                 }
1413         }
1414         
1415         /* type conversions */
1416         if(target->type == OB_ARMATURE) {
1417                 copy_object_pose(ob, target);   /* data copy, object pointers in constraints */
1418                 rest_pose(ob->pose);                    /* clear all transforms in channels */
1419                 armature_rebuild_pose(ob, ob->data);    /* set all internal links */
1420                 
1421                 armature_set_id_extern(ob);
1422         }
1423 }
1424
1425
1426 /* *************** CALC ****************** */
1427
1428 /* there is also a timing calculation in drawobject() */
1429
1430 float bluroffs= 0.0f, fieldoffs= 0.0f;
1431 int no_speed_curve= 0;
1432
1433 /* ugly calls from render */
1434 void set_mblur_offs(float blur)
1435 {
1436         bluroffs= blur;
1437 }
1438
1439 void set_field_offs(float field)
1440 {
1441         fieldoffs= field;
1442 }
1443
1444 void disable_speed_curve(int val)
1445 {
1446         no_speed_curve= val;
1447 }
1448
1449 // XXX THIS CRUFT NEEDS SERIOUS RECODING ASAP!
1450 /* ob can be NULL */
1451 float bsystem_time(struct Scene *scene, Object *ob, float cfra, float ofs)
1452 {
1453         /* returns float ( see frame_to_float in ipo.c) */
1454         
1455         /* bluroffs and fieldoffs are ugly globals that are set by render */
1456         cfra+= bluroffs+fieldoffs;
1457
1458         /* global time */
1459         cfra*= scene->r.framelen;       
1460         
1461 #if 0 // XXX old animation system
1462         if (ob) {
1463                 if (no_speed_curve==0 && ob->ipo)
1464                         cfra= calc_ipo_time(ob->ipo, cfra);
1465                 
1466                 /* ofset frames */
1467                 if ((ob->ipoflag & OB_OFFS_PARENT) && (ob->partype & PARSLOW)==0) 
1468                         cfra-= give_timeoffset(ob);
1469         }
1470 #endif // XXX old animation system
1471         
1472         cfra-= ofs;
1473
1474         return cfra;
1475 }
1476
1477 void object_scale_to_mat3(Object *ob, float mat[][3])
1478 {
1479         float vec[3];
1480         if(ob->ipo) {
1481                 vec[0]= ob->size[0]+ob->dsize[0];
1482                 vec[1]= ob->size[1]+ob->dsize[1];
1483                 vec[2]= ob->size[2]+ob->dsize[2];
1484                 SizeToMat3(vec, mat);
1485         }
1486         else {
1487                 SizeToMat3(ob->size, mat);
1488         }
1489 }
1490
1491 void object_rot_to_mat3(Object *ob, float mat[][3])
1492 {
1493         float vec[3];
1494         if(ob->ipo) {
1495                 vec[0]= ob->rot[0]+ob->drot[0];
1496                 vec[1]= ob->rot[1]+ob->drot[1];
1497                 vec[2]= ob->rot[2]+ob->drot[2];
1498                 EulToMat3(vec, mat);
1499         }
1500         else {
1501                 EulToMat3(ob->rot, mat);
1502         }
1503 }
1504
1505 void object_to_mat3(Object *ob, float mat[][3]) /* no parent */
1506 {
1507         float smat[3][3];
1508         float rmat[3][3];
1509         /*float q1[4];*/
1510         
1511         /* size */
1512         object_scale_to_mat3(ob, smat);
1513
1514         /* rot */
1515         /* Quats arnt used yet */
1516         /*if(ob->transflag & OB_QUAT) {
1517                 if(ob->ipo) {
1518                         QuatMul(q1, ob->quat, ob->dquat);
1519                         QuatToMat3(q1, rmat);
1520                 }
1521                 else {
1522                         QuatToMat3(ob->quat, rmat);
1523                 }
1524         }
1525         else {*/
1526                 object_rot_to_mat3(ob, rmat);
1527         /*}*/
1528         Mat3MulMat3(mat, rmat, smat);
1529 }
1530
1531 void object_to_mat4(Object *ob, float mat[][4])
1532 {
1533         float tmat[3][3];
1534         
1535         object_to_mat3(ob, tmat);
1536         
1537         Mat4CpyMat3(mat, tmat);
1538         
1539         VECCOPY(mat[3], ob->loc);
1540         if(ob->ipo) {
1541                 mat[3][0]+= ob->dloc[0];
1542                 mat[3][1]+= ob->dloc[1];
1543                 mat[3][2]+= ob->dloc[2];
1544         }
1545 }
1546
1547 int enable_cu_speed= 1;
1548
1549 static void ob_parcurve(Scene *scene, Object *ob, Object *par, float mat[][4])
1550 {
1551         Curve *cu;
1552         float q[4], vec[4], dir[3], quat[4], x1, ctime;
1553         float timeoffs = 0.0, sf_orig = 0.0;
1554         
1555         Mat4One(mat);
1556         
1557         cu= par->data;
1558         if(cu->path==NULL || cu->path->data==NULL) /* only happens on reload file, but violates depsgraph still... fix! */
1559                 makeDispListCurveTypes(scene, par, 0);
1560         if(cu->path==NULL) return;
1561         
1562         /* exception, timeoffset is regarded as distance offset */
1563         if(cu->flag & CU_OFFS_PATHDIST) {
1564                 timeoffs = give_timeoffset(ob);
1565                 SWAP(float, sf_orig, ob->sf);
1566         }
1567         
1568         /* catch exceptions: feature for nla stride editing */
1569         if(ob->ipoflag & OB_DISABLE_PATH) {
1570                 ctime= 0.0f;
1571         }
1572         /* catch exceptions: curve paths used as a duplicator */
1573         else if(enable_cu_speed) {
1574                 /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated,
1575                  * but this will only work if it actually is animated... 
1576                  *
1577                  * we firstly calculate the modulus of cu->ctime/cu->pathlen to clamp ctime within the 0.0 to 1.0 times pathlen
1578                  * range, then divide this (the modulus) by pathlen to get a value between 0.0 and 1.0
1579                  */
1580                 ctime= fmod(cu->ctime, cu->pathlen) / cu->pathlen;
1581                 CLAMP(ctime, 0.0, 1.0);
1582         }
1583         else {
1584                 ctime= scene->r.cfra - give_timeoffset(ob);
1585                 ctime /= cu->pathlen;
1586                 
1587                 CLAMP(ctime, 0.0, 1.0);
1588         }
1589         
1590         /* time calculus is correct, now apply distance offset */
1591         if(cu->flag & CU_OFFS_PATHDIST) {
1592                 ctime += timeoffs/cu->path->totdist;
1593
1594                 /* restore */
1595                 SWAP(float, sf_orig, ob->sf);
1596         }
1597         
1598         
1599         /* vec: 4 items! */
1600         if( where_on_path(par, ctime, vec, dir) ) {
1601
1602                 if(cu->flag & CU_FOLLOW) {
1603                         vectoquat(dir, ob->trackflag, ob->upflag, quat);
1604                         
1605                         /* the tilt */
1606                         Normalize(dir);
1607                         q[0]= (float)cos(0.5*vec[3]);
1608                         x1= (float)sin(0.5*vec[3]);
1609                         q[1]= -x1*dir[0];
1610                         q[2]= -x1*dir[1];
1611                         q[3]= -x1*dir[2];
1612                         QuatMul(quat, q, quat);
1613                         
1614                         QuatToMat4(quat, mat);
1615                 }
1616                 
1617                 VECCOPY(mat[3], vec);
1618                 
1619         }
1620 }
1621
1622 static void ob_parbone(Object *ob, Object *par, float mat[][4])
1623 {       
1624         bPoseChannel *pchan;
1625         float vec[3];
1626         
1627         if (par->type!=OB_ARMATURE) {
1628                 Mat4One(mat);
1629                 return;
1630         }
1631         
1632         /* Make sure the bone is still valid */
1633         pchan= get_pose_channel(par->pose, ob->parsubstr);
1634         if (!pchan){
1635                 printf ("Object %s with Bone parent: bone %s doesn't exist\n", ob->id.name+2, ob->parsubstr);
1636                 Mat4One(mat);
1637                 return;
1638         }
1639
1640         /* get bone transform */
1641         Mat4CpyMat4(mat, pchan->pose_mat);
1642
1643         /* but for backwards compatibility, the child has to move to the tail */
1644         VECCOPY(vec, mat[1]);
1645         VecMulf(vec, pchan->bone->length);
1646         VecAddf(mat[3], mat[3], vec);
1647 }
1648
1649 static void give_parvert(Object *par, int nr, float *vec)
1650 {
1651         EditMesh *em;
1652         int a, count;
1653         
1654         vec[0]=vec[1]=vec[2]= 0.0f;
1655         
1656         if(par->type==OB_MESH) {
1657                 Mesh *me= par->data;
1658                 em = BKE_mesh_get_editmesh(me);
1659
1660                 if(em) {
1661                         EditVert *eve;
1662                         
1663                         for(eve= em->verts.first; eve; eve= eve->next) {
1664                                 if(eve->keyindex==nr) {
1665                                         memcpy(vec, eve->co, sizeof(float)*3);
1666                                         break;
1667                                 }
1668                         }
1669                         BKE_mesh_end_editmesh(me, em);
1670                 }
1671                 else {
1672                         DerivedMesh *dm = par->derivedFinal;
1673                         
1674                         if(dm) {
1675                                 int i, count = 0, numVerts = dm->getNumVerts(dm);
1676                                 int *index = (int *)dm->getVertDataArray(dm, CD_ORIGINDEX);
1677                                 float co[3];
1678
1679                                 /* get the average of all verts with (original index == nr) */
1680                                 for(i = 0; i < numVerts; ++i, ++index) {
1681                                         if(*index == nr) {
1682                                                 dm->getVertCo(dm, i, co);
1683                                                 VecAddf(vec, vec, co);
1684                                                 count++;
1685                                         }
1686                                 }
1687
1688                                 if (count==0) {
1689                                         /* keep as 0,0,0 */
1690                                 } else if(count > 0) {
1691                                         VecMulf(vec, 1.0f / count);
1692                                 } else {
1693                                         /* use first index if its out of range */
1694                                         dm->getVertCo(dm, 0, vec);
1695                                 }
1696                         }
1697                 }
1698         }
1699         else if (ELEM(par->type, OB_CURVE, OB_SURF)) {
1700                 Nurb *nu;
1701                 Curve *cu;
1702                 BPoint *bp;
1703                 BezTriple *bezt;
1704                 int found= 0;
1705                 
1706                 cu= par->data;
1707                 if(cu->editnurb)
1708                         nu= cu->editnurb->first;
1709                 else
1710                         nu= cu->nurb.first;
1711                 
1712                 count= 0;
1713                 while(nu && !found) {
1714                         if((nu->type & 7)==CU_BEZIER) {
1715                                 bezt= nu->bezt;
1716                                 a= nu->pntsu;
1717                                 while(a--) {
1718                                         if(count==nr) {
1719                                                 found= 1;
1720                                                 VECCOPY(vec, bezt->vec[1]);
1721                                                 break;
1722                                         }
1723                                         count++;
1724                                         bezt++;
1725                                 }
1726                         }
1727                         else {
1728                                 bp= nu->bp;
1729                                 a= nu->pntsu*nu->pntsv;
1730                                 while(a--) {
1731                                         if(count==nr) {
1732                                                 found= 1;
1733                                                 memcpy(vec, bp->vec, sizeof(float)*3);
1734                                                 break;
1735                                         }
1736                                         count++;
1737                                         bp++;
1738                                 }
1739                         }
1740                         nu= nu->next;
1741                 }
1742
1743         }
1744         else if(par->type==OB_LATTICE) {
1745                 Lattice *latt= par->data;
1746                 BPoint *bp;
1747                 DispList *dl = find_displist(&par->disp, DL_VERTS);
1748                 float *co = dl?dl->verts:NULL;
1749                 
1750                 if(latt->editlatt) latt= latt->editlatt;
1751                 
1752                 a= latt->pntsu*latt->pntsv*latt->pntsw;
1753                 count= 0;
1754                 bp= latt->def;
1755                 while(a--) {
1756                         if(count==nr) {
1757                                 if(co)
1758                                         memcpy(vec, co, 3*sizeof(float));
1759                                 else
1760                                         memcpy(vec, bp->vec, 3*sizeof(float));
1761                                 break;
1762                         }
1763                         count++;
1764                         if(co) co+= 3;
1765                         else bp++;
1766                 }
1767         }
1768 }
1769
1770 static void ob_parvert3(Object *ob, Object *par, float mat[][4])
1771 {
1772         float cmat[3][3], v1[3], v2[3], v3[3], q[4];
1773
1774         /* in local ob space */
1775         Mat4One(mat);
1776         
1777         if (ELEM4(par->type, OB_MESH, OB_SURF, OB_CURVE, OB_LATTICE)) {
1778                 
1779                 give_parvert(par, ob->par1, v1);
1780                 give_parvert(par, ob->par2, v2);
1781                 give_parvert(par, ob->par3, v3);
1782                                 
1783                 triatoquat(v1, v2, v3, q);
1784                 QuatToMat3(q, cmat);
1785                 Mat4CpyMat3(mat, cmat);
1786                 
1787                 if(ob->type==OB_CURVE) {
1788                         VECCOPY(mat[3], v1);
1789                 }
1790                 else {
1791                         VecAddf(mat[3], v1, v2);
1792                         VecAddf(mat[3], mat[3], v3);
1793                         VecMulf(mat[3], 0.3333333f);
1794                 }
1795         }
1796 }
1797
1798 // XXX what the hell is this?
1799 static int no_parent_ipo=0;
1800 void set_no_parent_ipo(int val)
1801 {
1802         no_parent_ipo= val;
1803 }
1804
1805 static int during_script_flag=0;
1806 void disable_where_script(short on)
1807 {
1808         during_script_flag= on;
1809 }
1810
1811 int during_script(void) {
1812         return during_script_flag;
1813 }
1814
1815 static int during_scriptlink_flag=0;
1816 void disable_where_scriptlink(short on)
1817 {
1818         during_scriptlink_flag= on;
1819 }
1820
1821 int during_scriptlink(void) {
1822         return during_scriptlink_flag;
1823 }
1824
1825 void where_is_object_time(Scene *scene, Object *ob, float ctime)
1826 {
1827         float *fp1, *fp2, slowmat[4][4] = MAT4_UNITY;
1828         float stime=ctime, fac1, fac2, vec[3];
1829         int a;
1830         int pop; 
1831         
1832         /* new version: correct parent+vertexparent and track+parent */
1833         /* this one only calculates direct attached parent and track */
1834         /* is faster, but should keep track of timeoffs */
1835         
1836         if(ob==NULL) return;
1837         
1838 #if 0 // XXX old animation system
1839         /* this is needed to be able to grab objects with ipos, otherwise it always freezes them */
1840         stime= bsystem_time(scene, ob, ctime, 0.0);
1841         if(stime != ob->ctime) {
1842                 
1843                 ob->ctime= stime;
1844                 
1845                 if(ob->ipo) {
1846                         calc_ipo(ob->ipo, stime);
1847                         execute_ipo((ID *)ob, ob->ipo);
1848                 }
1849                 else 
1850                         do_all_object_actions(scene, ob);
1851                 
1852                 /* do constraint ipos ..., note it needs stime (0 = all ipos) */
1853                 do_constraint_channels(&ob->constraints, &ob->constraintChannels, stime, 0);
1854         }
1855         else {
1856                 /* but, the drivers have to be done */
1857                 if(ob->ipo) do_ob_ipodrivers(ob, ob->ipo, stime);
1858                 /* do constraint ipos ..., note it needs stime (1 = only drivers ipos) */
1859                 do_constraint_channels(&ob->constraints, &ob->constraintChannels, stime, 1);
1860         }
1861 #endif // XXX old animation system
1862
1863         /* execute drivers only, as animation has already been done */
1864         BKE_animsys_evaluate_animdata(&ob->id, ob->adt, ctime, ADT_RECALC_DRIVERS);
1865         
1866         if(ob->parent) {
1867                 Object *par= ob->parent;
1868                 
1869                 // XXX depreceated - animsys
1870                 if(ob->ipoflag & OB_OFFS_PARENT) ctime-= give_timeoffset(ob);
1871                 
1872                 /* hurms, code below conflicts with depgraph... (ton) */
1873                 /* and even worse, it gives bad effects for NLA stride too (try ctime != par->ctime, with MBlur) */
1874                 pop= 0;
1875                 if(no_parent_ipo==0 && stime != par->ctime) {
1876                         // only for ipo systems? 
1877                         pushdata(par, sizeof(Object));
1878                         pop= 1;
1879                         
1880                         if(par->proxy_from);    // was a copied matrix, no where_is! bad...
1881                         else where_is_object_time(scene, par, ctime);
1882                 }
1883                 
1884                 solve_parenting(scene, ob, par, ob->obmat, slowmat, 0);
1885                 
1886                 if(pop) {
1887                         poplast(par);
1888                 }
1889                 
1890                 if(ob->partype & PARSLOW) {
1891                         // include framerate
1892                         fac1= ( 1.0f / (1.0f + (float)fabs(give_timeoffset(ob))) );
1893                         if(fac1 >= 1.0f) return;
1894                         fac2= 1.0f-fac1;
1895                         
1896                         fp1= ob->obmat[0];
1897                         fp2= slowmat[0];
1898                         for(a=0; a<16; a++, fp1++, fp2++) {
1899                                 fp1[0]= fac1*fp1[0] + fac2*fp2[0];
1900                         }
1901                 }
1902         }
1903         else {
1904                 object_to_mat4(ob, ob->obmat);
1905         }
1906
1907         /* Handle tracking */
1908         if(ob->track) {
1909                 if( ctime != ob->track->ctime) where_is_object_time(scene, ob->track, ctime);
1910                 solve_tracking (ob, ob->track->obmat);
1911         }
1912
1913         /* solve constraints */
1914         if (ob->constraints.first) {
1915                 bConstraintOb *cob;
1916                 
1917                 cob= constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
1918                 
1919                 /* constraints need ctime, not stime. Some call where_is_object_time and bsystem_time */
1920                 solve_constraints (&ob->constraints, cob, ctime);
1921                 
1922                 constraints_clear_evalob(cob);
1923         }
1924 #ifndef DISABLE_PYTHON
1925         if(ob->scriptlink.totscript && !during_script()) {
1926                 if (G.f & G_DOSCRIPTLINKS) BPY_do_pyscript((ID *)ob, SCRIPT_REDRAW);
1927         }
1928 #endif
1929         
1930         /* set negative scale flag in object */
1931         Crossf(vec, ob->obmat[0], ob->obmat[1]);
1932         if( Inpf(vec, ob->obmat[2]) < 0.0 ) ob->transflag |= OB_NEG_SCALE;
1933         else ob->transflag &= ~OB_NEG_SCALE;
1934 }
1935
1936 static void solve_parenting (Scene *scene, Object *ob, Object *par, float obmat[][4], float slowmat[][4], int simul)
1937 {
1938         float totmat[4][4];
1939         float tmat[4][4];
1940         float locmat[4][4];
1941         float vec[3];
1942         int ok;
1943         
1944         object_to_mat4(ob, locmat);
1945         
1946         if(ob->partype & PARSLOW) Mat4CpyMat4(slowmat, obmat);
1947
1948         switch(ob->partype & PARTYPE) {
1949         case PAROBJECT:
1950                 ok= 0;
1951                 if(par->type==OB_CURVE) {
1952                         if( ((Curve *)par->data)->flag & CU_PATH ) {
1953                                 ob_parcurve(scene, ob, par, tmat);
1954                                 ok= 1;
1955                         }
1956                 }
1957                 
1958                 if(ok) Mat4MulSerie(totmat, par->obmat, tmat, 
1959                         NULL, NULL, NULL, NULL, NULL, NULL);
1960                 else Mat4CpyMat4(totmat, par->obmat);
1961                 
1962                 break;
1963         case PARBONE:
1964                 ob_parbone(ob, par, tmat);
1965                 Mat4MulSerie(totmat, par->obmat, tmat,         
1966                         NULL, NULL, NULL, NULL, NULL, NULL);
1967                 break;
1968                 
1969         case PARVERT1:
1970                 Mat4One(totmat);
1971                 if (simul){
1972                         VECCOPY(totmat[3], par->obmat[3]);
1973                 }
1974                 else{
1975                         give_parvert(par, ob->par1, vec);
1976                         VecMat4MulVecfl(totmat[3], par->obmat, vec);
1977                 }
1978                 break;
1979         case PARVERT3:
1980                 ob_parvert3(ob, par, tmat);
1981                 
1982                 Mat4MulSerie(totmat, par->obmat, tmat,         
1983                         NULL, NULL, NULL, NULL, NULL, NULL);
1984                 break;
1985                 
1986         case PARSKEL:
1987                 Mat4CpyMat4(totmat, par->obmat);
1988                 break;
1989         }
1990         
1991         // total 
1992         Mat4MulSerie(tmat, totmat, ob->parentinv,         
1993                 NULL, NULL, NULL, NULL, NULL, NULL);
1994         Mat4MulSerie(obmat, tmat, locmat,         
1995                 NULL, NULL, NULL, NULL, NULL, NULL);
1996         
1997         if (simul) {
1998
1999         }
2000         else{
2001                 // external usable originmat 
2002                 Mat3CpyMat4(originmat, tmat);
2003                 
2004                 // origin, voor help line
2005                 if( (ob->partype & 15)==PARSKEL ) {
2006                         VECCOPY(ob->orig, par->obmat[3]);
2007                 }
2008                 else {
2009                         VECCOPY(ob->orig, totmat[3]);
2010                 }
2011         }
2012
2013 }
2014 void solve_tracking (Object *ob, float targetmat[][4])
2015 {
2016         float quat[4];
2017         float vec[3];
2018         float totmat[3][3];
2019         float tmat[4][4];
2020         
2021         VecSubf(vec, ob->obmat[3], targetmat[3]);
2022         vectoquat(vec, ob->trackflag, ob->upflag, quat);
2023         QuatToMat3(quat, totmat);
2024         
2025         if(ob->parent && (ob->transflag & OB_POWERTRACK)) {
2026                 /* 'temporal' : clear parent info */
2027                 object_to_mat4(ob, tmat);
2028                 tmat[0][3]= ob->obmat[0][3];
2029                 tmat[1][3]= ob->obmat[1][3];
2030                 tmat[2][3]= ob->obmat[2][3];
2031                 tmat[3][0]= ob->obmat[3][0];
2032                 tmat[3][1]= ob->obmat[3][1];
2033                 tmat[3][2]= ob->obmat[3][2];
2034                 tmat[3][3]= ob->obmat[3][3];
2035         }
2036         else Mat4CpyMat4(tmat, ob->obmat);
2037         
2038         Mat4MulMat34(ob->obmat, totmat, tmat);
2039
2040 }
2041
2042 void where_is_object(struct Scene *scene, Object *ob)
2043 {
2044         where_is_object_time(scene, ob, (float)scene->r.cfra);
2045 }
2046
2047
2048 void where_is_object_simul(Scene *scene, Object *ob)
2049 /* was written for the old game engine (until 2.04) */
2050 /* It seems that this function is only called
2051 for a lamp that is the child of another object */
2052 {
2053         Object *par;
2054         //Ipo *ipo;
2055         float *fp1, *fp2;
2056         float slowmat[4][4];
2057         float fac1, fac2;
2058         int a;
2059         
2060         /* NO TIMEOFFS */
2061         
2062         /* no ipo! (because of dloc and realtime-ipos) */
2063                 // XXX old animation system
2064         //ipo= ob->ipo;
2065         //ob->ipo= NULL;
2066
2067         if(ob->parent) {
2068                 par= ob->parent;
2069                 
2070                 solve_parenting(scene, ob, par, ob->obmat, slowmat, 1);
2071
2072                 if(ob->partype & PARSLOW) {
2073
2074                         fac1= (float)(1.0/(1.0+ fabs(give_timeoffset(ob))));
2075                         fac2= 1.0f-fac1;
2076                         fp1= ob->obmat[0];
2077                         fp2= slowmat[0];
2078                         for(a=0; a<16; a++, fp1++, fp2++) {
2079                                 fp1[0]= fac1*fp1[0] + fac2*fp2[0];
2080                         }
2081                 }
2082                 
2083         }
2084         else {
2085                 object_to_mat4(ob, ob->obmat);
2086         }
2087         
2088         if(ob->track) 
2089                 solve_tracking(ob, ob->track->obmat);
2090
2091         /* solve constraints */
2092         if (ob->constraints.first) {
2093                 bConstraintOb *cob;
2094                 
2095                 cob= constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2096                 solve_constraints(&ob->constraints, cob, (float)scene->r.cfra);
2097                 constraints_clear_evalob(cob);
2098         }
2099         
2100         /*  WATCH IT!!! */
2101                 // XXX old animation system
2102         //ob->ipo= ipo;
2103 }
2104
2105 /* for calculation of the inverse parent transform, only used for editor */
2106 void what_does_parent(Scene *scene, Object *ob, Object *workob)
2107 {
2108         clear_workob(workob);
2109         
2110         Mat4One(workob->obmat);
2111         Mat4One(workob->parentinv);
2112         Mat4One(workob->constinv);
2113         workob->parent= ob->parent;
2114         workob->track= ob->track;
2115
2116         workob->trackflag= ob->trackflag;
2117         workob->upflag= ob->upflag;
2118         
2119         workob->partype= ob->partype;
2120         workob->par1= ob->par1;
2121         workob->par2= ob->par2;
2122         workob->par3= ob->par3;
2123
2124         workob->constraints.first = ob->constraints.first;
2125         workob->constraints.last = ob->constraints.last;
2126
2127         strcpy(workob->parsubstr, ob->parsubstr); 
2128
2129         where_is_object(scene, workob);
2130 }
2131
2132 BoundBox *unit_boundbox()
2133 {
2134         BoundBox *bb;
2135         float min[3] = {-1.0f,-1.0f,-1.0f}, max[3] = {-1.0f,-1.0f,-1.0f};
2136
2137         bb= MEM_callocN(sizeof(BoundBox), "bb");
2138         boundbox_set_from_min_max(bb, min, max);
2139         
2140         return bb;
2141 }
2142
2143 void boundbox_set_from_min_max(BoundBox *bb, float min[3], float max[3])
2144 {
2145         bb->vec[0][0]=bb->vec[1][0]=bb->vec[2][0]=bb->vec[3][0]= min[0];
2146         bb->vec[4][0]=bb->vec[5][0]=bb->vec[6][0]=bb->vec[7][0]= max[0];
2147         
2148         bb->vec[0][1]=bb->vec[1][1]=bb->vec[4][1]=bb->vec[5][1]= min[1];
2149         bb->vec[2][1]=bb->vec[3][1]=bb->vec[6][1]=bb->vec[7][1]= max[1];
2150
2151         bb->vec[0][2]=bb->vec[3][2]=bb->vec[4][2]=bb->vec[7][2]= min[2];
2152         bb->vec[1][2]=bb->vec[2][2]=bb->vec[5][2]=bb->vec[6][2]= max[2];
2153 }
2154
2155 BoundBox *object_get_boundbox(Object *ob)
2156 {
2157         BoundBox *bb= NULL;
2158         
2159         if(ob->type==OB_MESH) {
2160                 bb = mesh_get_bb(ob);
2161         }
2162         else if (ELEM3(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2163                 bb= ( (Curve *)ob->data )->bb;
2164         }
2165         else if(ob->type==OB_MBALL) {
2166                 bb= ob->bb;
2167         }
2168         return bb;
2169 }
2170
2171 /* used to temporally disable/enable boundbox */
2172 void object_boundbox_flag(Object *ob, int flag, int set)
2173 {
2174         BoundBox *bb= object_get_boundbox(ob);
2175         if(bb) {
2176                 if(set) bb->flag |= flag;
2177                 else bb->flag &= ~flag;
2178         }
2179 }
2180
2181 void minmax_object(Object *ob, float *min, float *max)
2182 {
2183         BoundBox bb;
2184         Mesh *me;
2185         Curve *cu;
2186         float vec[3];
2187         int a;
2188         
2189         switch(ob->type) {
2190                 
2191         case OB_CURVE:
2192         case OB_FONT:
2193         case OB_SURF:
2194                 cu= ob->data;
2195                 
2196                 if(cu->bb==NULL) tex_space_curve(cu);
2197                 bb= *(cu->bb);
2198                 
2199                 for(a=0; a<8; a++) {
2200                         Mat4MulVecfl(ob->obmat, bb.vec[a]);
2201                         DO_MINMAX(bb.vec[a], min, max);
2202                 }
2203                 break;
2204         case OB_ARMATURE:
2205                 if(ob->pose) {
2206                         bPoseChannel *pchan;
2207                         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2208                                 VECCOPY(vec, pchan->pose_head);
2209                                 Mat4MulVecfl(ob->obmat, vec);
2210                                 DO_MINMAX(vec, min, max);
2211                                 VECCOPY(vec, pchan->pose_tail);
2212                                 Mat4MulVecfl(ob->obmat, vec);
2213                                 DO_MINMAX(vec, min, max);
2214                         }
2215                         break;
2216                 }
2217                 /* no break, get_mesh will give NULL and it passes on to default */
2218         case OB_MESH:
2219                 me= get_mesh(ob);
2220                 
2221                 if(me) {
2222                         bb = *mesh_get_bb(ob);
2223                         
2224                         for(a=0; a<8; a++) {
2225                                 Mat4MulVecfl(ob->obmat, bb.vec[a]);
2226                                 DO_MINMAX(bb.vec[a], min, max);
2227                         }
2228                 }
2229                 if(min[0] < max[0] ) break;
2230                 
2231                 /* else here no break!!!, mesh can be zero sized */
2232                 
2233         default:
2234                 DO_MINMAX(ob->obmat[3], min, max);
2235
2236                 VECCOPY(vec, ob->obmat[3]);
2237                 VecAddf(vec, vec, ob->size);
2238                 DO_MINMAX(vec, min, max);
2239
2240                 VECCOPY(vec, ob->obmat[3]);
2241                 VecSubf(vec, vec, ob->size);
2242                 DO_MINMAX(vec, min, max);
2243                 break;
2244         }
2245 }
2246
2247 /* TODO - use dupli objects bounding boxes */
2248 void minmax_object_duplis(Scene *scene, Object *ob, float *min, float *max)
2249 {
2250         if ((ob->transflag & OB_DUPLI)==0) {
2251                 return;
2252         } else {
2253                 ListBase *lb;
2254                 DupliObject *dob;
2255                 
2256                 lb= object_duplilist(scene, ob);
2257                 for(dob= lb->first; dob; dob= dob->next) {
2258                         if(dob->no_draw);
2259                         else {
2260                                 /* should really use bound box of dup object */
2261                                 DO_MINMAX(dob->mat[3], min, max);
2262                         }
2263                 }
2264                 free_object_duplilist(lb);      /* does restore */
2265         }
2266 }
2267
2268
2269 /* proxy rule: lib_object->proxy_from == the one we borrow from, only set temporal and cleared here */
2270 /*           local_object->proxy      == pointer to library object, saved in files and read */
2271
2272 /* function below is polluted with proxy exceptions, cleanup will follow! */
2273
2274 /* the main object update call, for object matrix, constraints, keys and displist (modifiers) */
2275 /* requires flags to be set! */
2276 void object_handle_update(Scene *scene, Object *ob)
2277 {
2278         if(ob->recalc & OB_RECALC) {
2279                 
2280                 /* XXX new animsys warning: depsgraph tag OB_RECALC_DATA should not skip drivers, 
2281                    which is only in where_is_object now */
2282                 if(ob->recalc & OB_RECALC) {
2283                         
2284                         if (G.f & G_DEBUG)
2285                                 printf("recalcob %s\n", ob->id.name+2);
2286                         
2287                         /* handle proxy copy for target */
2288                         if(ob->id.lib && ob->proxy_from) {
2289                                 // printf("ob proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2290                                 if(ob->proxy_from->proxy_group) {/* transform proxy into group space */
2291                                         Object *obg= ob->proxy_from->proxy_group;
2292                                         Mat4Invert(obg->imat, obg->obmat);
2293                                         Mat4MulMat4(ob->obmat, ob->proxy_from->obmat, obg->imat);
2294                                 }
2295                                 else
2296                                         Mat4CpyMat4(ob->obmat, ob->proxy_from->obmat);
2297                         }
2298                         else
2299                                 where_is_object(scene, ob);
2300 #ifndef DISABLE_PYTHON
2301                         if (G.f & G_DOSCRIPTLINKS) BPY_do_pyscript((ID *)ob, SCRIPT_OBJECTUPDATE);
2302 #endif
2303                 }
2304                 
2305                 if(ob->recalc & OB_RECALC_DATA) {
2306                         
2307                         if (G.f & G_DEBUG)
2308                                 printf("recalcdata %s\n", ob->id.name+2);
2309                         
2310                         /* includes all keys and modifiers */
2311                         if(ob->type==OB_MESH) {
2312                                 EditMesh *em = BKE_mesh_get_editmesh(ob->data);
2313
2314                                         // here was vieweditdatamask? XXX
2315                                 if(ob==scene->obedit) {
2316                                         makeDerivedMesh(scene, ob, em, CD_MASK_BAREMESH);
2317                                         BKE_mesh_end_editmesh(ob->data, em);
2318                                 } else
2319                                         makeDerivedMesh(scene, ob, NULL, CD_MASK_BAREMESH);
2320                         }
2321                         else if(ob->type==OB_MBALL) {
2322                                 makeDispListMBall(scene, ob);
2323                         } 
2324                         else if(ELEM3(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2325                                 makeDispListCurveTypes(scene, ob, 0);
2326                         }
2327                         else if(ELEM(ob->type, OB_CAMERA, OB_LAMP)) {
2328                                 ID *data_id= (ID *)ob->data;
2329                                 AnimData *adt= BKE_animdata_from_id(data_id);
2330                                 float ctime= (float)scene->r.cfra; // XXX this is bad...
2331                                 
2332                                 /* evaluate drivers */
2333                                 BKE_animsys_evaluate_animdata(data_id, adt, ctime, ADT_RECALC_DRIVERS);
2334                         }
2335                         else if(ob->type==OB_LATTICE) {
2336                                 lattice_calc_modifiers(scene, ob);
2337                         }
2338                         else if(ob->type==OB_ARMATURE) {
2339                                 /* this happens for reading old files and to match library armatures with poses */
2340                                 // XXX this won't screw up the pose set already...
2341                                 if(ob->pose==NULL || (ob->pose->flag & POSE_RECALC))
2342                                         armature_rebuild_pose(ob, ob->data);
2343                                 
2344                                 if(ob->id.lib && ob->proxy_from) {
2345                                         copy_pose_result(ob->pose, ob->proxy_from->pose);
2346                                         // printf("pose proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2347                                 }
2348                                 else {
2349                                         where_is_pose(scene, ob);
2350                                 }
2351                         }
2352
2353                         if(ob->particlesystem.first) {
2354                                 ParticleSystem *tpsys, *psys;
2355                                 DerivedMesh *dm;
2356                                 
2357                                 psys= ob->particlesystem.first;
2358                                 while(psys) {
2359                                         if(psys_check_enabled(ob, psys)) {
2360                                                 particle_system_update(scene, ob, psys);
2361                                                 psys= psys->next;
2362                                         }
2363                                         else if(psys->flag & PSYS_DELETE) {
2364                                                 tpsys=psys->next;
2365                                                 BLI_remlink(&ob->particlesystem, psys);
2366                                                 psys_free(ob,psys);
2367                                                 psys= tpsys;
2368                                         }
2369                                         else
2370                                                 psys= psys->next;
2371                                 }
2372
2373                                 if(G.rendering && ob->transflag & OB_DUPLIPARTS) {
2374                                         /* this is to make sure we get render level duplis in groups:
2375                                          * the derivedmesh must be created before init_render_mesh,
2376                                          * since object_duplilist does dupliparticles before that */
2377                                         dm = mesh_create_derived_render(scene, ob, CD_MASK_BAREMESH|CD_MASK_MTFACE|CD_MASK_MCOL);
2378                                         dm->release(dm);
2379
2380                                         for(psys=ob->particlesystem.first; psys; psys=psys->next)
2381                                                 psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated;
2382                                 }
2383                         }
2384 #ifndef DISABLE_PYTHON
2385                         if (G.f & G_DOSCRIPTLINKS) BPY_do_pyscript((ID *)ob, SCRIPT_OBDATAUPDATE);
2386 #endif
2387                 }
2388
2389                 /* the no-group proxy case, we call update */
2390                 if(ob->proxy && ob->proxy_group==NULL) {
2391                         /* set pointer in library proxy target, for copying, but restore it */
2392                         ob->proxy->proxy_from= ob;
2393                         // printf("call update, lib ob %s proxy %s\n", ob->proxy->id.name, ob->id.name);
2394                         object_handle_update(scene, ob->proxy);
2395                 }
2396         
2397                 ob->recalc &= ~OB_RECALC;
2398         }
2399
2400         /* the case when this is a group proxy, object_update is called in group.c */
2401         if(ob->proxy) {
2402                 ob->proxy->proxy_from= ob;
2403                 // printf("set proxy pointer for later group stuff %s\n", ob->id.name);
2404         }
2405 }
2406
2407 float give_timeoffset(Object *ob) {
2408         if ((ob->ipoflag & OB_OFFS_PARENTADD) && ob->parent) {
2409                 return ob->sf + give_timeoffset(ob->parent);
2410         } else {
2411                 return ob->sf;
2412         }
2413 }
2414
2415 int give_obdata_texspace(Object *ob, int **texflag, float **loc, float **size, float **rot) {
2416         
2417         if (ob->data==NULL)
2418                 return 0;
2419         
2420         switch (GS(((ID *)ob->data)->name)) {
2421         case ID_ME:
2422         {
2423                 Mesh *me= ob->data;
2424                 if (texflag)    *texflag = &me->texflag;
2425                 if (loc)                *loc = me->loc;
2426                 if (size)               *size = me->size;
2427                 if (rot)                *rot = me->rot;
2428                 break;
2429         }
2430         case ID_CU:
2431         {
2432                 Curve *cu= ob->data;
2433                 if (texflag)    *texflag = &cu->texflag;
2434                 if (loc)                *loc = cu->loc;
2435                 if (size)               *size = cu->size;
2436                 if (rot)                *rot = cu->rot;
2437                 break;
2438         }
2439         case ID_MB:
2440         {
2441                 MetaBall *mb= ob->data;
2442                 if (texflag)    *texflag = &mb->texflag;
2443                 if (loc)                *loc = mb->loc;
2444                 if (size)               *size = mb->size;
2445                 if (rot)                *rot = mb->rot;
2446                 break;
2447         }
2448         default:
2449                 return 0;
2450         }
2451         return 1;
2452 }
2453
2454 /*
2455  * Test a bounding box for ray intersection
2456  * assumes the ray is already local to the boundbox space
2457  */
2458 int ray_hit_boundbox(struct BoundBox *bb, float ray_start[3], float ray_normal[3])
2459 {
2460         static int triangle_indexes[12][3] = {{0, 1, 2}, {0, 2, 3},
2461                                                                                   {3, 2, 6}, {3, 6, 7},
2462                                                                                   {1, 2, 6}, {1, 6, 5}, 
2463                                                                                   {5, 6, 7}, {4, 5, 7},
2464                                                                                   {0, 3, 7}, {0, 4, 7},
2465                                                                                   {0, 1, 5}, {0, 4, 5}};
2466         int result = 0;
2467         int i;
2468         
2469         for (i = 0; i < 12 && result == 0; i++)
2470         {
2471                 float lambda;
2472                 int v1, v2, v3;
2473                 v1 = triangle_indexes[i][0];
2474                 v2 = triangle_indexes[i][1];
2475                 v3 = triangle_indexes[i][2];
2476                 result = RayIntersectsTriangle(ray_start, ray_normal, bb->vec[v1], bb->vec[v2], bb->vec[v3], &lambda, NULL);
2477         }
2478         
2479         return result;
2480 }