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