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