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