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