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