Merge with -r 22620:23107.
[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->soft) {
1117                 psysn->soft= copy_softbody(psys->soft);
1118                 psysn->soft->particles = psysn;
1119         }
1120
1121         BLI_duplicatelist(&psysn->targets, &psys->targets);
1122         
1123         psysn->pathcache= NULL;
1124         psysn->childcache= NULL;
1125         psysn->edit= NULL;
1126         psysn->effectors.first= psysn->effectors.last= 0;
1127         
1128         psysn->pathcachebufs.first = psysn->pathcachebufs.last = NULL;
1129         psysn->childcachebufs.first = psysn->childcachebufs.last = NULL;
1130         psysn->reactevents.first = psysn->reactevents.last = NULL;
1131         psysn->renderdata = NULL;
1132         
1133         psysn->pointcache= BKE_ptcache_copy_list(&psysn->ptcaches, &psys->ptcaches);
1134
1135         id_us_plus((ID *)psysn->part);
1136
1137         return psysn;
1138 }
1139
1140 void copy_object_particlesystems(Object *obn, Object *ob)
1141 {
1142         ParticleSystemModifierData *psmd;
1143         ParticleSystem *psys, *npsys;
1144         ModifierData *md;
1145
1146         obn->particlesystem.first= obn->particlesystem.last= NULL;
1147         for(psys=ob->particlesystem.first; psys; psys=psys->next) {
1148                 npsys= copy_particlesystem(psys);
1149
1150                 BLI_addtail(&obn->particlesystem, npsys);
1151
1152                 /* need to update particle modifiers too */
1153                 for(md=obn->modifiers.first; md; md=md->next) {
1154                         if(md->type==eModifierType_ParticleSystem) {
1155                                 psmd= (ParticleSystemModifierData*)md;
1156                                 if(psmd->psys==psys)
1157                                         psmd->psys= npsys;
1158                         }
1159                 }
1160         }
1161 }
1162
1163 void copy_object_softbody(Object *obn, Object *ob)
1164 {
1165         if(ob->soft)
1166                 obn->soft= copy_softbody(ob->soft);
1167 }
1168
1169 static void copy_object_pose(Object *obn, Object *ob)
1170 {
1171         bPoseChannel *chan;
1172         
1173         /* note: need to clear obn->pose pointer first, so that copy_pose works (otherwise there's a crash) */
1174         obn->pose= NULL;
1175         copy_pose(&obn->pose, ob->pose, 1);     /* 1 = copy constraints */
1176
1177         for (chan = obn->pose->chanbase.first; chan; chan=chan->next){
1178                 bConstraint *con;
1179                 
1180                 chan->flag &= ~(POSE_LOC|POSE_ROT|POSE_SIZE);
1181                 
1182                 for (con= chan->constraints.first; con; con= con->next) {
1183                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1184                         ListBase targets = {NULL, NULL};
1185                         bConstraintTarget *ct;
1186                         
1187 #if 0 // XXX old animation system
1188                         /* note that we can't change lib linked ipo blocks. for making
1189                          * proxies this still works correct however because the object
1190                          * is changed to object->proxy_from when evaluating the driver. */
1191                         if(con->ipo && !con->ipo->id.lib) {
1192                                 IpoCurve *icu;
1193                                 
1194                                 con->ipo= copy_ipo(con->ipo);
1195                                 
1196                                 for(icu= con->ipo->curve.first; icu; icu= icu->next) {
1197                                         if(icu->driver && icu->driver->ob==ob)
1198                                                 icu->driver->ob= obn;
1199                                 }
1200                         }
1201 #endif // XXX old animation system
1202                         
1203                         if (cti && cti->get_constraint_targets) {
1204                                 cti->get_constraint_targets(con, &targets);
1205                                 
1206                                 for (ct= targets.first; ct; ct= ct->next) {
1207                                         if (ct->tar == ob)
1208                                                 ct->tar = obn;
1209                                 }
1210                                 
1211                                 if (cti->flush_constraint_targets)
1212                                         cti->flush_constraint_targets(con, &targets, 0);
1213                         }
1214                 }
1215         }
1216 }
1217
1218 Object *copy_object(Object *ob)
1219 {
1220         Object *obn;
1221         ModifierData *md;
1222         int a;
1223
1224         obn= copy_libblock(ob);
1225         
1226         if(ob->totcol) {
1227                 obn->mat= MEM_dupallocN(ob->mat);
1228                 obn->matbits= MEM_dupallocN(ob->matbits);
1229         }
1230         
1231         if(ob->bb) obn->bb= MEM_dupallocN(ob->bb);
1232         obn->path= NULL;
1233         obn->flag &= ~OB_FROMGROUP;
1234         
1235         obn->modifiers.first = obn->modifiers.last= NULL;
1236         
1237         for (md=ob->modifiers.first; md; md=md->next) {
1238                 ModifierData *nmd = modifier_new(md->type);
1239                 modifier_copyData(md, nmd);
1240                 BLI_addtail(&obn->modifiers, nmd);
1241         }
1242
1243         obn->prop.first = obn->prop.last = NULL;
1244         copy_properties(&obn->prop, &ob->prop);
1245         
1246         copy_sensors(&obn->sensors, &ob->sensors);
1247         copy_controllers(&obn->controllers, &ob->controllers);
1248         copy_actuators(&obn->actuators, &ob->actuators);
1249         
1250         if(ob->pose) {
1251                 copy_object_pose(obn, ob);
1252                 /* backwards compat... non-armatures can get poses in older files? */
1253                 if(ob->type==OB_ARMATURE)
1254                         armature_rebuild_pose(obn, obn->data);
1255         }
1256         copy_defgroups(&obn->defbase, &ob->defbase);
1257         copy_constraints(&obn->constraints, &ob->constraints);
1258
1259         obn->mode = 0;
1260         obn->sculpt = NULL;
1261
1262         /* increase user numbers */
1263         id_us_plus((ID *)obn->data);
1264         id_us_plus((ID *)obn->dup_group);
1265         // FIXME: add this for animdata too...
1266
1267         for(a=0; a<obn->totcol; a++) id_us_plus((ID *)obn->mat[a]);
1268         
1269         obn->disp.first= obn->disp.last= NULL;
1270         
1271         if(ob->pd){
1272                 obn->pd= MEM_dupallocN(ob->pd);
1273                 if(obn->pd->tex)
1274                         id_us_plus(&(obn->pd->tex->id));
1275         }
1276         obn->soft= copy_softbody(ob->soft);
1277         obn->bsoft = copy_bulletsoftbody(ob->bsoft);
1278
1279         copy_object_particlesystems(obn, ob);
1280         
1281         obn->derivedDeform = NULL;
1282         obn->derivedFinal = NULL;
1283
1284         obn->gpulamp.first = obn->gpulamp.last = NULL;
1285         obn->pc_ids.first = obn->pc_ids.last = NULL;
1286         
1287         return obn;
1288 }
1289
1290 void expand_local_object(Object *ob)
1291 {
1292         //bActionStrip *strip;
1293         ParticleSystem *psys;
1294         int a;
1295
1296 #if 0 // XXX old animation system
1297         id_lib_extern((ID *)ob->action);
1298         id_lib_extern((ID *)ob->ipo);
1299 #endif // XXX old animation system
1300         id_lib_extern((ID *)ob->data);
1301         id_lib_extern((ID *)ob->dup_group);
1302         
1303         for(a=0; a<ob->totcol; a++) {
1304                 id_lib_extern((ID *)ob->mat[a]);
1305         }
1306 #if 0 // XXX old animation system
1307         for (strip=ob->nlastrips.first; strip; strip=strip->next) {
1308                 id_lib_extern((ID *)strip->act);
1309         }
1310 #endif // XXX old animation system
1311         for(psys=ob->particlesystem.first; psys; psys=psys->next)
1312                 id_lib_extern((ID *)psys->part);
1313 }
1314
1315 void make_local_object(Object *ob)
1316 {
1317         Object *obn;
1318         Scene *sce;
1319         Base *base;
1320         int local=0, lib=0;
1321
1322         /* - only lib users: do nothing
1323             * - only local users: set flag
1324             * - mixed: make copy
1325             */
1326         
1327         if(ob->id.lib==NULL) return;
1328         
1329         ob->proxy= ob->proxy_from= NULL;
1330         
1331         if(ob->id.us==1) {
1332                 ob->id.lib= NULL;
1333                 ob->id.flag= LIB_LOCAL;
1334                 new_id(0, (ID *)ob, 0);
1335
1336         }
1337         else {
1338                 sce= G.main->scene.first;
1339                 while(sce) {
1340                         base= sce->base.first;
1341                         while(base) {
1342                                 if(base->object==ob) {
1343                                         if(sce->id.lib) lib++;
1344                                         else local++;
1345                                         break;
1346                                 }
1347                                 base= base->next;
1348                         }
1349                         sce= sce->id.next;
1350                 }
1351                 
1352                 if(local && lib==0) {
1353                         ob->id.lib= 0;
1354                         ob->id.flag= LIB_LOCAL;
1355                         new_id(0, (ID *)ob, 0);
1356                 }
1357                 else if(local && lib) {
1358                         obn= copy_object(ob);
1359                         obn->id.us= 0;
1360                         
1361                         sce= G.main->scene.first;
1362                         while(sce) {
1363                                 if(sce->id.lib==0) {
1364                                         base= sce->base.first;
1365                                         while(base) {
1366                                                 if(base->object==ob) {
1367                                                         base->object= obn;
1368                                                         obn->id.us++;
1369                                                         ob->id.us--;
1370                                                 }
1371                                                 base= base->next;
1372                                         }
1373                                 }
1374                                 sce= sce->id.next;
1375                         }
1376                 }
1377         }
1378         
1379         expand_local_object(ob);
1380 }
1381
1382 /*
1383  * Returns true if the Object is a from an external blend file (libdata)
1384  */
1385 int object_is_libdata(Object *ob)
1386 {
1387         if (!ob) return 0;
1388         if (ob->proxy) return 0;
1389         if (ob->id.lib) return 1;
1390         return 0;
1391 }
1392
1393 /* Returns true if the Object data is a from an external blend file (libdata) */
1394 int object_data_is_libdata(Object *ob)
1395 {
1396         if(!ob) return 0;
1397         if(ob->proxy) return 0;
1398         if(ob->id.lib) return 1;
1399         if(!ob->data) return 0;
1400         if(((ID *)ob->data)->lib) return 1;
1401
1402         return 0;
1403 }
1404
1405 /* *************** PROXY **************** */
1406
1407 /* when you make proxy, ensure the exposed layers are extern */
1408 void armature_set_id_extern(Object *ob)
1409 {
1410         bArmature *arm= ob->data;
1411         bPoseChannel *pchan;
1412         int lay= arm->layer_protected;
1413         
1414         for (pchan = ob->pose->chanbase.first; pchan; pchan=pchan->next) {
1415                 if(!(pchan->bone->layer & lay))
1416                         id_lib_extern((ID *)pchan->custom);
1417         }
1418                         
1419 }
1420
1421 /* proxy rule: lib_object->proxy_from == the one we borrow from, set temporally while object_update */
1422 /*             local_object->proxy == pointer to library object, saved in files and read */
1423 /*             local_object->proxy_group == pointer to group dupli-object, saved in files and read */
1424
1425 void object_make_proxy(Object *ob, Object *target, Object *gob)
1426 {
1427         /* paranoia checks */
1428         if(ob->id.lib || target->id.lib==NULL) {
1429                 printf("cannot make proxy\n");
1430                 return;
1431         }
1432         
1433         ob->proxy= target;
1434         ob->proxy_group= gob;
1435         id_lib_extern(&target->id);
1436         
1437         ob->recalc= target->recalc= OB_RECALC;
1438         
1439         /* copy transform */
1440         if(gob) {
1441                 VECCOPY(ob->loc, gob->loc);
1442                 VECCOPY(ob->rot, gob->rot);
1443                 VECCOPY(ob->size, gob->size);
1444                 
1445                 group_tag_recalc(gob->dup_group);
1446         }
1447         else {
1448                 VECCOPY(ob->loc, target->loc);
1449                 VECCOPY(ob->rot, target->rot);
1450                 VECCOPY(ob->size, target->size);
1451         }
1452         
1453         ob->parent= target->parent;     /* libdata */
1454         Mat4CpyMat4(ob->parentinv, target->parentinv);
1455         
1456         /* copy animdata stuff - drivers only for now... */
1457         if ((target->adt) && (target->adt->drivers.first)) {
1458                 FCurve *fcu;
1459                 
1460                 /* add new animdata block */
1461                 ob->adt= BKE_id_add_animdata(&ob->id);
1462                 
1463                 /* make a copy of all the drivers (for now), then correct any links that need fixing */
1464                 copy_fcurves(&ob->adt->drivers, &target->adt->drivers);
1465                 
1466                 for (fcu= ob->adt->drivers.first; fcu; fcu= fcu->next) {
1467                         ChannelDriver *driver= fcu->driver;
1468                         DriverTarget *dtar;
1469                         
1470                         for (dtar= driver->targets.first; dtar; dtar= dtar->next) {
1471                                 if ((Object *)dtar->id == target)
1472                                         dtar->id= (ID *)ob;
1473                                 else
1474                                         id_lib_extern((ID *)dtar->id);
1475                         }
1476                 }
1477         }
1478         
1479         /* skip constraints? */
1480         // FIXME: this is considered by many as a bug
1481         
1482         /* set object type and link to data */
1483         ob->type= target->type;
1484         ob->data= target->data;
1485         id_us_plus((ID *)ob->data);             /* ensures lib data becomes LIB_EXTERN */
1486         
1487         /* copy material and index information */
1488         ob->actcol= ob->totcol= 0;
1489         if(ob->mat) MEM_freeN(ob->mat);
1490         if(ob->matbits) MEM_freeN(ob->matbits);
1491         ob->mat = NULL;
1492         ob->matbits= NULL;
1493         if ((target->totcol) && (target->mat) && ELEM5(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL)) { //XXX OB_SUPPORT_MATERIAL
1494                 int i;
1495                 ob->colbits = target->colbits;
1496                 
1497                 ob->actcol= target->actcol;
1498                 ob->totcol= target->totcol;
1499                 
1500                 ob->mat = MEM_dupallocN(target->mat);
1501                 ob->matbits = MEM_dupallocN(target->matbits);
1502                 for(i=0; i<target->totcol; i++) {
1503                         /* dont need to run test_object_materials since we know this object is new and not used elsewhere */
1504                         id_us_plus((ID *)ob->mat[i]); 
1505                 }
1506         }
1507         
1508         /* type conversions */
1509         if(target->type == OB_ARMATURE) {
1510                 copy_object_pose(ob, target);   /* data copy, object pointers in constraints */
1511                 rest_pose(ob->pose);                    /* clear all transforms in channels */
1512                 armature_rebuild_pose(ob, ob->data);    /* set all internal links */
1513                 
1514                 armature_set_id_extern(ob);
1515         }
1516         
1517         /* copy drawtype info */
1518         ob->dt= target->dt;
1519 }
1520
1521
1522 /* *************** CALC ****************** */
1523
1524 /* there is also a timing calculation in drawobject() */
1525
1526 float bluroffs= 0.0f, fieldoffs= 0.0f;
1527 int no_speed_curve= 0;
1528
1529 /* ugly calls from render */
1530 void set_mblur_offs(float blur)
1531 {
1532         bluroffs= blur;
1533 }
1534
1535 void set_field_offs(float field)
1536 {
1537         fieldoffs= field;
1538 }
1539
1540 void disable_speed_curve(int val)
1541 {
1542         no_speed_curve= val;
1543 }
1544
1545 // XXX THIS CRUFT NEEDS SERIOUS RECODING ASAP!
1546 /* ob can be NULL */
1547 float bsystem_time(struct Scene *scene, Object *ob, float cfra, float ofs)
1548 {
1549         /* returns float ( see frame_to_float in ipo.c) */
1550         
1551         /* bluroffs and fieldoffs are ugly globals that are set by render */
1552         cfra+= bluroffs+fieldoffs;
1553
1554         /* global time */
1555         cfra*= scene->r.framelen;       
1556         
1557 #if 0 // XXX old animation system
1558         if (ob) {
1559                 if (no_speed_curve==0 && ob->ipo)
1560                         cfra= calc_ipo_time(ob->ipo, cfra);
1561                 
1562                 /* ofset frames */
1563                 if ((ob->ipoflag & OB_OFFS_PARENT) && (ob->partype & PARSLOW)==0) 
1564                         cfra-= give_timeoffset(ob);
1565         }
1566 #endif // XXX old animation system
1567         
1568         cfra-= ofs;
1569
1570         return cfra;
1571 }
1572
1573 void object_scale_to_mat3(Object *ob, float mat[][3])
1574 {
1575         float vec[3];
1576         if(ob->ipo) {
1577                 vec[0]= ob->size[0]+ob->dsize[0];
1578                 vec[1]= ob->size[1]+ob->dsize[1];
1579                 vec[2]= ob->size[2]+ob->dsize[2];
1580                 SizeToMat3(vec, mat);
1581         }
1582         else {
1583                 SizeToMat3(ob->size, mat);
1584         }
1585 }
1586
1587 void object_rot_to_mat3(Object *ob, float mat[][3])
1588 {
1589         float vec[3];
1590         if(ob->ipo) {
1591                 vec[0]= ob->rot[0]+ob->drot[0];
1592                 vec[1]= ob->rot[1]+ob->drot[1];
1593                 vec[2]= ob->rot[2]+ob->drot[2];
1594                 EulToMat3(vec, mat);
1595         }
1596         else {
1597                 EulToMat3(ob->rot, mat);
1598         }
1599 }
1600
1601 void object_to_mat3(Object *ob, float mat[][3]) /* no parent */
1602 {
1603         float smat[3][3];
1604         float rmat[3][3];
1605         /*float q1[4];*/
1606         
1607         /* size */
1608         object_scale_to_mat3(ob, smat);
1609
1610         /* rot */
1611         /* Quats arnt used yet */
1612         /*if(ob->transflag & OB_QUAT) {
1613                 if(ob->ipo) {
1614                         QuatMul(q1, ob->quat, ob->dquat);
1615                         QuatToMat3(q1, rmat);
1616                 }
1617                 else {
1618                         QuatToMat3(ob->quat, rmat);
1619                 }
1620         }
1621         else {*/
1622                 object_rot_to_mat3(ob, rmat);
1623         /*}*/
1624         Mat3MulMat3(mat, rmat, smat);
1625 }
1626
1627 void object_to_mat4(Object *ob, float mat[][4])
1628 {
1629         float tmat[3][3];
1630         
1631         object_to_mat3(ob, tmat);
1632         
1633         Mat4CpyMat3(mat, tmat);
1634         
1635         VECCOPY(mat[3], ob->loc);
1636         if(ob->ipo) {
1637                 mat[3][0]+= ob->dloc[0];
1638                 mat[3][1]+= ob->dloc[1];
1639                 mat[3][2]+= ob->dloc[2];
1640         }
1641 }
1642
1643 int enable_cu_speed= 1;
1644
1645 static void ob_parcurve(Scene *scene, Object *ob, Object *par, float mat[][4])
1646 {
1647         Curve *cu;
1648         float q[4], vec[4], dir[3], quat[4], x1, ctime;
1649         float timeoffs = 0.0, sf_orig = 0.0;
1650         
1651         Mat4One(mat);
1652         
1653         cu= par->data;
1654         if(cu->path==NULL || cu->path->data==NULL) /* only happens on reload file, but violates depsgraph still... fix! */
1655                 makeDispListCurveTypes(scene, par, 0);
1656         if(cu->path==NULL) return;
1657         
1658         /* exception, timeoffset is regarded as distance offset */
1659         if(cu->flag & CU_OFFS_PATHDIST) {
1660                 timeoffs = give_timeoffset(ob);
1661                 SWAP(float, sf_orig, ob->sf);
1662         }
1663         
1664         /* catch exceptions: feature for nla stride editing */
1665         if(ob->ipoflag & OB_DISABLE_PATH) {
1666                 ctime= 0.0f;
1667         }
1668         /* catch exceptions: curve paths used as a duplicator */
1669         else if(enable_cu_speed) {
1670                 /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated,
1671                  * but this will only work if it actually is animated... 
1672                  *
1673                  * we firstly calculate the modulus of cu->ctime/cu->pathlen to clamp ctime within the 0.0 to 1.0 times pathlen
1674                  * range, then divide this (the modulus) by pathlen to get a value between 0.0 and 1.0
1675                  */
1676                 ctime= fmod(cu->ctime, cu->pathlen) / cu->pathlen;
1677                 CLAMP(ctime, 0.0, 1.0);
1678         }
1679         else {
1680                 ctime= scene->r.cfra - give_timeoffset(ob);
1681                 ctime /= cu->pathlen;
1682                 
1683                 CLAMP(ctime, 0.0, 1.0);
1684         }
1685         
1686         /* time calculus is correct, now apply distance offset */
1687         if(cu->flag & CU_OFFS_PATHDIST) {
1688                 ctime += timeoffs/cu->path->totdist;
1689
1690                 /* restore */
1691                 SWAP(float, sf_orig, ob->sf);
1692         }
1693         
1694         
1695         /* vec: 4 items! */
1696         if( where_on_path(par, ctime, vec, dir) ) {
1697
1698                 if(cu->flag & CU_FOLLOW) {
1699                         vectoquat(dir, ob->trackflag, ob->upflag, quat);
1700                         
1701                         /* the tilt */
1702                         Normalize(dir);
1703                         q[0]= (float)cos(0.5*vec[3]);
1704                         x1= (float)sin(0.5*vec[3]);
1705                         q[1]= -x1*dir[0];
1706                         q[2]= -x1*dir[1];
1707                         q[3]= -x1*dir[2];
1708                         QuatMul(quat, q, quat);
1709                         
1710                         QuatToMat4(quat, mat);
1711                 }
1712                 
1713                 VECCOPY(mat[3], vec);
1714                 
1715         }
1716 }
1717
1718 static void ob_parbone(Object *ob, Object *par, float mat[][4])
1719 {       
1720         bPoseChannel *pchan;
1721         float vec[3];
1722         
1723         if (par->type!=OB_ARMATURE) {
1724                 Mat4One(mat);
1725                 return;
1726         }
1727         
1728         /* Make sure the bone is still valid */
1729         pchan= get_pose_channel(par->pose, ob->parsubstr);
1730         if (!pchan){
1731                 printf ("Object %s with Bone parent: bone %s doesn't exist\n", ob->id.name+2, ob->parsubstr);
1732                 Mat4One(mat);
1733                 return;
1734         }
1735
1736         /* get bone transform */
1737         Mat4CpyMat4(mat, pchan->pose_mat);
1738
1739         /* but for backwards compatibility, the child has to move to the tail */
1740         VECCOPY(vec, mat[1]);
1741         VecMulf(vec, pchan->bone->length);
1742         VecAddf(mat[3], mat[3], vec);
1743 }
1744
1745 static void give_parvert(Object *par, int nr, float *vec)
1746 {
1747         EditMesh *em;
1748         int a, count;
1749         
1750         vec[0]=vec[1]=vec[2]= 0.0f;
1751         
1752         if(par->type==OB_MESH) {
1753                 Mesh *me= par->data;
1754                 em = BKE_mesh_get_editmesh(me);
1755
1756                 if(em) {
1757                         EditVert *eve;
1758                         
1759                         for(eve= em->verts.first; eve; eve= eve->next) {
1760                                 if(eve->keyindex==nr) {
1761                                         memcpy(vec, eve->co, sizeof(float)*3);
1762                                         break;
1763                                 }
1764                         }
1765                         BKE_mesh_end_editmesh(me, em);
1766                 }
1767                 else {
1768                         DerivedMesh *dm = par->derivedFinal;
1769                         
1770                         if(dm) {
1771                                 int i, count = 0, numVerts = dm->getNumVerts(dm);
1772                                 int *index = (int *)dm->getVertDataArray(dm, CD_ORIGINDEX);
1773                                 float co[3];
1774
1775                                 /* get the average of all verts with (original index == nr) */
1776                                 for(i = 0; i < numVerts; ++i, ++index) {
1777                                         if(*index == nr) {
1778                                                 dm->getVertCo(dm, i, co);
1779                                                 VecAddf(vec, vec, co);
1780                                                 count++;
1781                                         }
1782                                 }
1783
1784                                 if (count==0) {
1785                                         /* keep as 0,0,0 */
1786                                 } else if(count > 0) {
1787                                         VecMulf(vec, 1.0f / count);
1788                                 } else {
1789                                         /* use first index if its out of range */
1790                                         dm->getVertCo(dm, 0, vec);
1791                                 }
1792                         }
1793                 }
1794         }
1795         else if (ELEM(par->type, OB_CURVE, OB_SURF)) {
1796                 Nurb *nu;
1797                 Curve *cu;
1798                 BPoint *bp;
1799                 BezTriple *bezt;
1800                 int found= 0;
1801                 
1802                 cu= par->data;
1803                 if(cu->editnurb)
1804                         nu= cu->editnurb->first;
1805                 else
1806                         nu= cu->nurb.first;
1807                 
1808                 count= 0;
1809                 while(nu && !found) {
1810                         if(nu->type == CU_BEZIER) {
1811                                 bezt= nu->bezt;
1812                                 a= nu->pntsu;
1813                                 while(a--) {
1814                                         if(count==nr) {
1815                                                 found= 1;
1816                                                 VECCOPY(vec, bezt->vec[1]);
1817                                                 break;
1818                                         }
1819                                         count++;
1820                                         bezt++;
1821                                 }
1822                         }
1823                         else {
1824                                 bp= nu->bp;
1825                                 a= nu->pntsu*nu->pntsv;
1826                                 while(a--) {
1827                                         if(count==nr) {
1828                                                 found= 1;
1829                                                 memcpy(vec, bp->vec, sizeof(float)*3);
1830                                                 break;
1831                                         }
1832                                         count++;
1833                                         bp++;
1834                                 }
1835                         }
1836                         nu= nu->next;
1837                 }
1838
1839         }
1840         else if(par->type==OB_LATTICE) {
1841                 Lattice *latt= par->data;
1842                 BPoint *bp;
1843                 DispList *dl = find_displist(&par->disp, DL_VERTS);
1844                 float *co = dl?dl->verts:NULL;
1845                 
1846                 if(latt->editlatt) latt= latt->editlatt;
1847                 
1848                 a= latt->pntsu*latt->pntsv*latt->pntsw;
1849                 count= 0;
1850                 bp= latt->def;
1851                 while(a--) {
1852                         if(count==nr) {
1853                                 if(co)
1854                                         memcpy(vec, co, 3*sizeof(float));
1855                                 else
1856                                         memcpy(vec, bp->vec, 3*sizeof(float));
1857                                 break;
1858                         }
1859                         count++;
1860                         if(co) co+= 3;
1861                         else bp++;
1862                 }
1863         }
1864 }
1865
1866 static void ob_parvert3(Object *ob, Object *par, float mat[][4])
1867 {
1868         float cmat[3][3], v1[3], v2[3], v3[3], q[4];
1869
1870         /* in local ob space */
1871         Mat4One(mat);
1872         
1873         if (ELEM4(par->type, OB_MESH, OB_SURF, OB_CURVE, OB_LATTICE)) {
1874                 
1875                 give_parvert(par, ob->par1, v1);
1876                 give_parvert(par, ob->par2, v2);
1877                 give_parvert(par, ob->par3, v3);
1878                                 
1879                 triatoquat(v1, v2, v3, q);
1880                 QuatToMat3(q, cmat);
1881                 Mat4CpyMat3(mat, cmat);
1882                 
1883                 if(ob->type==OB_CURVE) {
1884                         VECCOPY(mat[3], v1);
1885                 }
1886                 else {
1887                         VecAddf(mat[3], v1, v2);
1888                         VecAddf(mat[3], mat[3], v3);
1889                         VecMulf(mat[3], 0.3333333f);
1890                 }
1891         }
1892 }
1893
1894 // XXX what the hell is this?
1895 static int no_parent_ipo=0;
1896 void set_no_parent_ipo(int val)
1897 {
1898         no_parent_ipo= val;
1899 }
1900
1901 void where_is_object_time(Scene *scene, Object *ob, float ctime)
1902 {
1903         float *fp1, *fp2, slowmat[4][4] = MAT4_UNITY;
1904         float stime=ctime, fac1, fac2, vec[3];
1905         int a;
1906         int pop; 
1907         
1908         /* new version: correct parent+vertexparent and track+parent */
1909         /* this one only calculates direct attached parent and track */
1910         /* is faster, but should keep track of timeoffs */
1911         
1912         if(ob==NULL) return;
1913         
1914 #if 0 // XXX old animation system
1915         /* this is needed to be able to grab objects with ipos, otherwise it always freezes them */
1916         stime= bsystem_time(scene, ob, ctime, 0.0);
1917         if(stime != ob->ctime) {
1918                 
1919                 ob->ctime= stime;
1920                 
1921                 if(ob->ipo) {
1922                         calc_ipo(ob->ipo, stime);
1923                         execute_ipo((ID *)ob, ob->ipo);
1924                 }
1925                 else 
1926                         do_all_object_actions(scene, ob);
1927                 
1928                 /* do constraint ipos ..., note it needs stime (0 = all ipos) */
1929                 do_constraint_channels(&ob->constraints, &ob->constraintChannels, stime, 0);
1930         }
1931         else {
1932                 /* but, the drivers have to be done */
1933                 if(ob->ipo) do_ob_ipodrivers(ob, ob->ipo, stime);
1934                 /* do constraint ipos ..., note it needs stime (1 = only drivers ipos) */
1935                 do_constraint_channels(&ob->constraints, &ob->constraintChannels, stime, 1);
1936         }
1937 #endif // XXX old animation system
1938
1939         /* execute drivers only, as animation has already been done */
1940         BKE_animsys_evaluate_animdata(&ob->id, ob->adt, ctime, ADT_RECALC_DRIVERS);
1941         
1942         if(ob->parent) {
1943                 Object *par= ob->parent;
1944                 
1945                 // XXX depreceated - animsys
1946                 if(ob->ipoflag & OB_OFFS_PARENT) ctime-= give_timeoffset(ob);
1947                 
1948                 /* hurms, code below conflicts with depgraph... (ton) */
1949                 /* and even worse, it gives bad effects for NLA stride too (try ctime != par->ctime, with MBlur) */
1950                 pop= 0;
1951                 if(no_parent_ipo==0 && stime != par->ctime) {
1952                         // only for ipo systems? 
1953                         pushdata(par, sizeof(Object));
1954                         pop= 1;
1955                         
1956                         if(par->proxy_from);    // was a copied matrix, no where_is! bad...
1957                         else where_is_object_time(scene, par, ctime);
1958                 }
1959                 
1960                 solve_parenting(scene, ob, par, ob->obmat, slowmat, 0);
1961                 
1962                 if(pop) {
1963                         poplast(par);
1964                 }
1965                 
1966                 if(ob->partype & PARSLOW) {
1967                         // include framerate
1968                         fac1= ( 1.0f / (1.0f + (float)fabs(give_timeoffset(ob))) );
1969                         if(fac1 >= 1.0f) return;
1970                         fac2= 1.0f-fac1;
1971                         
1972                         fp1= ob->obmat[0];
1973                         fp2= slowmat[0];
1974                         for(a=0; a<16; a++, fp1++, fp2++) {
1975                                 fp1[0]= fac1*fp1[0] + fac2*fp2[0];
1976                         }
1977                 }
1978         }
1979         else {
1980                 object_to_mat4(ob, ob->obmat);
1981         }
1982
1983         /* Handle tracking */
1984         if(ob->track) {
1985                 if( ctime != ob->track->ctime) where_is_object_time(scene, ob->track, ctime);
1986                 solve_tracking (ob, ob->track->obmat);
1987         }
1988
1989         /* solve constraints */
1990         if (ob->constraints.first) {
1991                 bConstraintOb *cob;
1992                 
1993                 cob= constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
1994                 
1995                 /* constraints need ctime, not stime. Some call where_is_object_time and bsystem_time */
1996                 solve_constraints (&ob->constraints, cob, ctime);
1997                 
1998                 constraints_clear_evalob(cob);
1999         }
2000         
2001         /* set negative scale flag in object */
2002         Crossf(vec, ob->obmat[0], ob->obmat[1]);
2003         if( Inpf(vec, ob->obmat[2]) < 0.0 ) ob->transflag |= OB_NEG_SCALE;
2004         else ob->transflag &= ~OB_NEG_SCALE;
2005 }
2006
2007 static void solve_parenting (Scene *scene, Object *ob, Object *par, float obmat[][4], float slowmat[][4], int simul)
2008 {
2009         float totmat[4][4];
2010         float tmat[4][4];
2011         float locmat[4][4];
2012         float vec[3];
2013         int ok;
2014         
2015         object_to_mat4(ob, locmat);
2016         
2017         if(ob->partype & PARSLOW) Mat4CpyMat4(slowmat, obmat);
2018
2019         switch(ob->partype & PARTYPE) {
2020         case PAROBJECT:
2021                 ok= 0;
2022                 if(par->type==OB_CURVE) {
2023                         if( ((Curve *)par->data)->flag & CU_PATH ) {
2024                                 ob_parcurve(scene, ob, par, tmat);
2025                                 ok= 1;
2026                         }
2027                 }
2028                 
2029                 if(ok) Mat4MulSerie(totmat, par->obmat, tmat, 
2030                         NULL, NULL, NULL, NULL, NULL, NULL);
2031                 else Mat4CpyMat4(totmat, par->obmat);
2032                 
2033                 break;
2034         case PARBONE:
2035                 ob_parbone(ob, par, tmat);
2036                 Mat4MulSerie(totmat, par->obmat, tmat,         
2037                         NULL, NULL, NULL, NULL, NULL, NULL);
2038                 break;
2039                 
2040         case PARVERT1:
2041                 Mat4One(totmat);
2042                 if (simul){
2043                         VECCOPY(totmat[3], par->obmat[3]);
2044                 }
2045                 else{
2046                         give_parvert(par, ob->par1, vec);
2047                         VecMat4MulVecfl(totmat[3], par->obmat, vec);
2048                 }
2049                 break;
2050         case PARVERT3:
2051                 ob_parvert3(ob, par, tmat);
2052                 
2053                 Mat4MulSerie(totmat, par->obmat, tmat,         
2054                         NULL, NULL, NULL, NULL, NULL, NULL);
2055                 break;
2056                 
2057         case PARSKEL:
2058                 Mat4CpyMat4(totmat, par->obmat);
2059                 break;
2060         }
2061         
2062         // total 
2063         Mat4MulSerie(tmat, totmat, ob->parentinv,         
2064                 NULL, NULL, NULL, NULL, NULL, NULL);
2065         Mat4MulSerie(obmat, tmat, locmat,         
2066                 NULL, NULL, NULL, NULL, NULL, NULL);
2067         
2068         if (simul) {
2069
2070         }
2071         else{
2072                 // external usable originmat 
2073                 Mat3CpyMat4(originmat, tmat);
2074                 
2075                 // origin, voor help line
2076                 if( (ob->partype & 15)==PARSKEL ) {
2077                         VECCOPY(ob->orig, par->obmat[3]);
2078                 }
2079                 else {
2080                         VECCOPY(ob->orig, totmat[3]);
2081                 }
2082         }
2083
2084 }
2085 void solve_tracking (Object *ob, float targetmat[][4])
2086 {
2087         float quat[4];
2088         float vec[3];
2089         float totmat[3][3];
2090         float tmat[4][4];
2091         
2092         VecSubf(vec, ob->obmat[3], targetmat[3]);
2093         vectoquat(vec, ob->trackflag, ob->upflag, quat);
2094         QuatToMat3(quat, totmat);
2095         
2096         if(ob->parent && (ob->transflag & OB_POWERTRACK)) {
2097                 /* 'temporal' : clear parent info */
2098                 object_to_mat4(ob, tmat);
2099                 tmat[0][3]= ob->obmat[0][3];
2100                 tmat[1][3]= ob->obmat[1][3];
2101                 tmat[2][3]= ob->obmat[2][3];
2102                 tmat[3][0]= ob->obmat[3][0];
2103                 tmat[3][1]= ob->obmat[3][1];
2104                 tmat[3][2]= ob->obmat[3][2];
2105                 tmat[3][3]= ob->obmat[3][3];
2106         }
2107         else Mat4CpyMat4(tmat, ob->obmat);
2108         
2109         Mat4MulMat34(ob->obmat, totmat, tmat);
2110
2111 }
2112
2113 void where_is_object(struct Scene *scene, Object *ob)
2114 {
2115         where_is_object_time(scene, ob, (float)scene->r.cfra);
2116 }
2117
2118
2119 void where_is_object_simul(Scene *scene, Object *ob)
2120 /* was written for the old game engine (until 2.04) */
2121 /* It seems that this function is only called
2122 for a lamp that is the child of another object */
2123 {
2124         Object *par;
2125         //Ipo *ipo;
2126         float *fp1, *fp2;
2127         float slowmat[4][4];
2128         float fac1, fac2;
2129         int a;
2130         
2131         /* NO TIMEOFFS */
2132         
2133         /* no ipo! (because of dloc and realtime-ipos) */
2134                 // XXX old animation system
2135         //ipo= ob->ipo;
2136         //ob->ipo= NULL;
2137
2138         if(ob->parent) {
2139                 par= ob->parent;
2140                 
2141                 solve_parenting(scene, ob, par, ob->obmat, slowmat, 1);
2142
2143                 if(ob->partype & PARSLOW) {
2144
2145                         fac1= (float)(1.0/(1.0+ fabs(give_timeoffset(ob))));
2146                         fac2= 1.0f-fac1;
2147                         fp1= ob->obmat[0];
2148                         fp2= slowmat[0];
2149                         for(a=0; a<16; a++, fp1++, fp2++) {
2150                                 fp1[0]= fac1*fp1[0] + fac2*fp2[0];
2151                         }
2152                 }
2153                 
2154         }
2155         else {
2156                 object_to_mat4(ob, ob->obmat);
2157         }
2158         
2159         if(ob->track) 
2160                 solve_tracking(ob, ob->track->obmat);
2161
2162         /* solve constraints */
2163         if (ob->constraints.first) {
2164                 bConstraintOb *cob;
2165                 
2166                 cob= constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2167                 solve_constraints(&ob->constraints, cob, (float)scene->r.cfra);
2168                 constraints_clear_evalob(cob);
2169         }
2170         
2171         /*  WATCH IT!!! */
2172                 // XXX old animation system
2173         //ob->ipo= ipo;
2174 }
2175
2176 /* for calculation of the inverse parent transform, only used for editor */
2177 void what_does_parent(Scene *scene, Object *ob, Object *workob)
2178 {
2179         clear_workob(workob);
2180         
2181         Mat4One(workob->obmat);
2182         Mat4One(workob->parentinv);
2183         Mat4One(workob->constinv);
2184         workob->parent= ob->parent;
2185         workob->track= ob->track;
2186
2187         workob->trackflag= ob->trackflag;
2188         workob->upflag= ob->upflag;
2189         
2190         workob->partype= ob->partype;
2191         workob->par1= ob->par1;
2192         workob->par2= ob->par2;
2193         workob->par3= ob->par3;
2194
2195         workob->constraints.first = ob->constraints.first;
2196         workob->constraints.last = ob->constraints.last;
2197
2198         strcpy(workob->parsubstr, ob->parsubstr); 
2199
2200         where_is_object(scene, workob);
2201 }
2202
2203 BoundBox *unit_boundbox()
2204 {
2205         BoundBox *bb;
2206         float min[3] = {-1.0f,-1.0f,-1.0f}, max[3] = {-1.0f,-1.0f,-1.0f};
2207
2208         bb= MEM_callocN(sizeof(BoundBox), "bb");
2209         boundbox_set_from_min_max(bb, min, max);
2210         
2211         return bb;
2212 }
2213
2214 void boundbox_set_from_min_max(BoundBox *bb, float min[3], float max[3])
2215 {
2216         bb->vec[0][0]=bb->vec[1][0]=bb->vec[2][0]=bb->vec[3][0]= min[0];
2217         bb->vec[4][0]=bb->vec[5][0]=bb->vec[6][0]=bb->vec[7][0]= max[0];
2218         
2219         bb->vec[0][1]=bb->vec[1][1]=bb->vec[4][1]=bb->vec[5][1]= min[1];
2220         bb->vec[2][1]=bb->vec[3][1]=bb->vec[6][1]=bb->vec[7][1]= max[1];
2221
2222         bb->vec[0][2]=bb->vec[3][2]=bb->vec[4][2]=bb->vec[7][2]= min[2];
2223         bb->vec[1][2]=bb->vec[2][2]=bb->vec[5][2]=bb->vec[6][2]= max[2];
2224 }
2225
2226 BoundBox *object_get_boundbox(Object *ob)
2227 {
2228         BoundBox *bb= NULL;
2229         
2230         if(ob->type==OB_MESH) {
2231                 bb = mesh_get_bb(ob);
2232         }
2233         else if (ELEM3(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2234                 bb= ( (Curve *)ob->data )->bb;
2235         }
2236         else if(ob->type==OB_MBALL) {
2237                 bb= ob->bb;
2238         }
2239         return bb;
2240 }
2241
2242 /* used to temporally disable/enable boundbox */
2243 void object_boundbox_flag(Object *ob, int flag, int set)
2244 {
2245         BoundBox *bb= object_get_boundbox(ob);
2246         if(bb) {
2247                 if(set) bb->flag |= flag;
2248                 else bb->flag &= ~flag;
2249         }
2250 }
2251
2252 void minmax_object(Object *ob, float *min, float *max)
2253 {
2254         BoundBox bb;
2255         Mesh *me;
2256         Curve *cu;
2257         float vec[3];
2258         int a;
2259         
2260         switch(ob->type) {
2261                 
2262         case OB_CURVE:
2263         case OB_FONT:
2264         case OB_SURF:
2265                 cu= ob->data;
2266                 
2267                 if(cu->bb==NULL) tex_space_curve(cu);
2268                 bb= *(cu->bb);
2269                 
2270                 for(a=0; a<8; a++) {
2271                         Mat4MulVecfl(ob->obmat, bb.vec[a]);
2272                         DO_MINMAX(bb.vec[a], min, max);
2273                 }
2274                 break;
2275         case OB_ARMATURE:
2276                 if(ob->pose) {
2277                         bPoseChannel *pchan;
2278                         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2279                                 VECCOPY(vec, pchan->pose_head);
2280                                 Mat4MulVecfl(ob->obmat, vec);
2281                                 DO_MINMAX(vec, min, max);
2282                                 VECCOPY(vec, pchan->pose_tail);
2283                                 Mat4MulVecfl(ob->obmat, vec);
2284                                 DO_MINMAX(vec, min, max);
2285                         }
2286                         break;
2287                 }
2288                 /* no break, get_mesh will give NULL and it passes on to default */
2289         case OB_MESH:
2290                 me= get_mesh(ob);
2291                 
2292                 if(me) {
2293                         bb = *mesh_get_bb(ob);
2294                         
2295                         for(a=0; a<8; a++) {
2296                                 Mat4MulVecfl(ob->obmat, bb.vec[a]);
2297                                 DO_MINMAX(bb.vec[a], min, max);
2298                         }
2299                 }
2300                 if(min[0] < max[0] ) break;
2301                 
2302                 /* else here no break!!!, mesh can be zero sized */
2303                 
2304         default:
2305                 DO_MINMAX(ob->obmat[3], min, max);
2306
2307                 VECCOPY(vec, ob->obmat[3]);
2308                 VecAddf(vec, vec, ob->size);
2309                 DO_MINMAX(vec, min, max);
2310
2311                 VECCOPY(vec, ob->obmat[3]);
2312                 VecSubf(vec, vec, ob->size);
2313                 DO_MINMAX(vec, min, max);
2314                 break;
2315         }
2316 }
2317
2318 /* TODO - use dupli objects bounding boxes */
2319 void minmax_object_duplis(Scene *scene, Object *ob, float *min, float *max)
2320 {
2321         if ((ob->transflag & OB_DUPLI)==0) {
2322                 return;
2323         } else {
2324                 ListBase *lb;
2325                 DupliObject *dob;
2326                 
2327                 lb= object_duplilist(scene, ob);
2328                 for(dob= lb->first; dob; dob= dob->next) {
2329                         if(dob->no_draw);
2330                         else {
2331                                 /* should really use bound box of dup object */
2332                                 DO_MINMAX(dob->mat[3], min, max);
2333                         }
2334                 }
2335                 free_object_duplilist(lb);      /* does restore */
2336         }
2337 }
2338
2339
2340 /* proxy rule: lib_object->proxy_from == the one we borrow from, only set temporal and cleared here */
2341 /*           local_object->proxy      == pointer to library object, saved in files and read */
2342
2343 /* function below is polluted with proxy exceptions, cleanup will follow! */
2344
2345 /* the main object update call, for object matrix, constraints, keys and displist (modifiers) */
2346 /* requires flags to be set! */
2347 void object_handle_update(Scene *scene, Object *ob)
2348 {
2349         if(ob->recalc & OB_RECALC) {
2350                 
2351                 /* XXX new animsys warning: depsgraph tag OB_RECALC_DATA should not skip drivers, 
2352                    which is only in where_is_object now */
2353                 if(ob->recalc & OB_RECALC) {
2354                         
2355                         if (G.f & G_DEBUG)
2356                                 printf("recalcob %s\n", ob->id.name+2);
2357                         
2358                         /* handle proxy copy for target */
2359                         if(ob->id.lib && ob->proxy_from) {
2360                                 // printf("ob proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2361                                 if(ob->proxy_from->proxy_group) {/* transform proxy into group space */
2362                                         Object *obg= ob->proxy_from->proxy_group;
2363                                         Mat4Invert(obg->imat, obg->obmat);
2364                                         Mat4MulMat4(ob->obmat, ob->proxy_from->obmat, obg->imat);
2365                                 }
2366                                 else
2367                                         Mat4CpyMat4(ob->obmat, ob->proxy_from->obmat);
2368                         }
2369                         else
2370                                 where_is_object(scene, ob);
2371                 }
2372                 
2373                 if(ob->recalc & OB_RECALC_DATA) {
2374                         
2375                         if (G.f & G_DEBUG)
2376                                 printf("recalcdata %s\n", ob->id.name+2);
2377                         
2378                         /* includes all keys and modifiers */
2379                         if(ob->type==OB_MESH) {
2380                                 EditMesh *em = BKE_mesh_get_editmesh(ob->data);
2381
2382                                         // here was vieweditdatamask? XXX
2383                                 if(ob==scene->obedit) {
2384                                         makeDerivedMesh(scene, ob, em, CD_MASK_BAREMESH);
2385                                         BKE_mesh_end_editmesh(ob->data, em);
2386                                 } else
2387                                         makeDerivedMesh(scene, ob, NULL, CD_MASK_BAREMESH);
2388                         }
2389                         else if(ob->type==OB_MBALL) {
2390                                 makeDispListMBall(scene, ob);
2391                         } 
2392                         else if(ELEM3(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2393                                 makeDispListCurveTypes(scene, ob, 0);
2394                         }
2395                         else if(ELEM(ob->type, OB_CAMERA, OB_LAMP)) {
2396                                 ID *data_id= (ID *)ob->data;
2397                                 AnimData *adt= BKE_animdata_from_id(data_id);
2398                                 float ctime= (float)scene->r.cfra; // XXX this is bad...
2399                                 
2400                                 /* evaluate drivers */
2401                                 BKE_animsys_evaluate_animdata(data_id, adt, ctime, ADT_RECALC_DRIVERS);
2402                         }
2403                         else if(ob->type==OB_LATTICE) {
2404                                 lattice_calc_modifiers(scene, ob);
2405                         }
2406                         else if(ob->type==OB_ARMATURE) {
2407                                 /* this happens for reading old files and to match library armatures with poses */
2408                                 // XXX this won't screw up the pose set already...
2409                                 if(ob->pose==NULL || (ob->pose->flag & POSE_RECALC))
2410                                         armature_rebuild_pose(ob, ob->data);
2411                                 
2412                                 if(ob->id.lib && ob->proxy_from) {
2413                                         copy_pose_result(ob->pose, ob->proxy_from->pose);
2414                                         // printf("pose proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2415                                 }
2416                                 else {
2417                                         where_is_pose(scene, ob);
2418                                 }
2419                         }
2420
2421                         if(ob->particlesystem.first) {
2422                                 ParticleSystem *tpsys, *psys;
2423                                 DerivedMesh *dm;
2424                                 ob->transflag &= ~OB_DUPLIPARTS;
2425                                 
2426                                 psys= ob->particlesystem.first;
2427                                 while(psys) {
2428                                         if(psys_check_enabled(ob, psys)) {
2429                                                 /* check use of dupli objects here */
2430                                                 if(psys->part && psys->part->draw_as == PART_DRAW_REND &&
2431                                                         ((psys->part->ren_as == PART_DRAW_OB && psys->part->dup_ob)
2432                                                         || (psys->part->ren_as == PART_DRAW_GR && psys->part->dup_group)))
2433                                                         ob->transflag |= OB_DUPLIPARTS;
2434
2435                                                 particle_system_update(scene, ob, psys);
2436                                                 psys= psys->next;
2437                                         }
2438                                         else if(psys->flag & PSYS_DELETE) {
2439                                                 tpsys=psys->next;
2440                                                 BLI_remlink(&ob->particlesystem, psys);
2441                                                 psys_free(ob,psys);
2442                                                 psys= tpsys;
2443                                         }
2444                                         else
2445                                                 psys= psys->next;
2446                                 }
2447
2448                                 if(G.rendering && ob->transflag & OB_DUPLIPARTS) {
2449                                         /* this is to make sure we get render level duplis in groups:
2450                                          * the derivedmesh must be created before init_render_mesh,
2451                                          * since object_duplilist does dupliparticles before that */
2452                                         dm = mesh_create_derived_render(scene, ob, CD_MASK_BAREMESH|CD_MASK_MTFACE|CD_MASK_MCOL);
2453                                         dm->release(dm);
2454
2455                                         for(psys=ob->particlesystem.first; psys; psys=psys->next)
2456                                                 psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated;
2457                                 }
2458                         }
2459                 }
2460
2461                 /* the no-group proxy case, we call update */
2462                 if(ob->proxy && ob->proxy_group==NULL) {
2463                         /* set pointer in library proxy target, for copying, but restore it */
2464                         ob->proxy->proxy_from= ob;
2465                         // printf("call update, lib ob %s proxy %s\n", ob->proxy->id.name, ob->id.name);
2466                         object_handle_update(scene, ob->proxy);
2467                 }
2468         
2469                 ob->recalc &= ~OB_RECALC;
2470         }
2471
2472         /* the case when this is a group proxy, object_update is called in group.c */
2473         if(ob->proxy) {
2474                 ob->proxy->proxy_from= ob;
2475                 // printf("set proxy pointer for later group stuff %s\n", ob->id.name);
2476         }
2477 }
2478
2479 float give_timeoffset(Object *ob) {
2480         if ((ob->ipoflag & OB_OFFS_PARENTADD) && ob->parent) {
2481                 return ob->sf + give_timeoffset(ob->parent);
2482         } else {
2483                 return ob->sf;
2484         }
2485 }
2486
2487 int give_obdata_texspace(Object *ob, int **texflag, float **loc, float **size, float **rot) {
2488         
2489         if (ob->data==NULL)
2490                 return 0;
2491         
2492         switch (GS(((ID *)ob->data)->name)) {
2493         case ID_ME:
2494         {
2495                 Mesh *me= ob->data;
2496                 if (texflag)    *texflag = &me->texflag;
2497                 if (loc)                *loc = me->loc;
2498                 if (size)               *size = me->size;
2499                 if (rot)                *rot = me->rot;
2500                 break;
2501         }
2502         case ID_CU:
2503         {
2504                 Curve *cu= ob->data;
2505                 if (texflag)    *texflag = &cu->texflag;
2506                 if (loc)                *loc = cu->loc;
2507                 if (size)               *size = cu->size;
2508                 if (rot)                *rot = cu->rot;
2509                 break;
2510         }
2511         case ID_MB:
2512         {
2513                 MetaBall *mb= ob->data;
2514                 if (texflag)    *texflag = &mb->texflag;
2515                 if (loc)                *loc = mb->loc;
2516                 if (size)               *size = mb->size;
2517                 if (rot)                *rot = mb->rot;
2518                 break;
2519         }
2520         default:
2521                 return 0;
2522         }
2523         return 1;
2524 }
2525
2526 /*
2527  * Test a bounding box for ray intersection
2528  * assumes the ray is already local to the boundbox space
2529  */
2530 int ray_hit_boundbox(struct BoundBox *bb, float ray_start[3], float ray_normal[3])
2531 {
2532         static int triangle_indexes[12][3] = {{0, 1, 2}, {0, 2, 3},
2533                                                                                   {3, 2, 6}, {3, 6, 7},
2534                                                                                   {1, 2, 6}, {1, 6, 5}, 
2535                                                                                   {5, 6, 7}, {4, 5, 7},
2536                                                                                   {0, 3, 7}, {0, 4, 7},
2537                                                                                   {0, 1, 5}, {0, 4, 5}};
2538         int result = 0;
2539         int i;
2540         
2541         for (i = 0; i < 12 && result == 0; i++)
2542         {
2543                 float lambda;
2544                 int v1, v2, v3;
2545                 v1 = triangle_indexes[i][0];
2546                 v2 = triangle_indexes[i][1];
2547                 v3 = triangle_indexes[i][2];
2548                 result = RayIntersectsTriangle(ray_start, ray_normal, bb->vec[v1], bb->vec[v2], bb->vec[v3], &lambda, NULL);
2549         }
2550         
2551         return result;
2552 }
2553
2554 static int pc_cmp(void *a, void *b)
2555 {
2556         LinkData *ad = a, *bd = b;
2557         if((int)ad->data > (int)bd->data)
2558                 return 1;
2559         else return 0;
2560 }
2561
2562 int object_insert_ptcache(Object *ob) 
2563 {
2564         LinkData *link = NULL;
2565         int i = 0;
2566
2567         BLI_sortlist(&ob->pc_ids, pc_cmp);
2568
2569         for(link=ob->pc_ids.first, i = 0; link; link=link->next, i++) 
2570         {
2571                 int index =(int)link->data;
2572
2573                 if(i < index)
2574                         break;
2575         }
2576
2577         link = MEM_callocN(sizeof(LinkData), "PCLink");
2578         link->data = (void *)i;
2579         BLI_addtail(&ob->pc_ids, link);
2580
2581         return i;
2582 }
2583
2584 #if 0
2585 static int pc_findindex(ListBase *listbase, int index)
2586 {
2587         LinkData *link= NULL;
2588         int number= 0;
2589         
2590         if (listbase == NULL) return -1;
2591         
2592         link= listbase->first;
2593         while (link) {
2594                 if ((int)link->data == index)
2595                         return number;
2596                 
2597                 number++;
2598                 link= link->next;
2599         }
2600         
2601         return -1;
2602 }
2603
2604 void object_delete_ptcache(Object *ob, int index) 
2605 {
2606         int list_index = pc_findindex(&ob->pc_ids, index);
2607         LinkData *link = BLI_findlink(&ob->pc_ids, list_index);
2608         BLI_freelinkN(&ob->pc_ids, link);
2609 }
2610 #endif