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