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