Fix #30496: Bugs and crashes about "make links modifers" function.
[blender.git] / source / blender / blenkernel / intern / object.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/object.c
29  *  \ingroup bke
30  */
31
32
33 #include <string.h>
34 #include <math.h>
35 #include <stdio.h>                      
36
37 #include "MEM_guardedalloc.h"
38
39 #include "DNA_anim_types.h"
40 #include "DNA_armature_types.h"
41 #include "DNA_camera_types.h"
42 #include "DNA_constraint_types.h"
43 #include "DNA_group_types.h"
44 #include "DNA_key_types.h"
45 #include "DNA_lattice_types.h"
46 #include "DNA_material_types.h"
47 #include "DNA_meta_types.h"
48 #include "DNA_mesh_types.h"
49 #include "DNA_meshdata_types.h"
50 #include "DNA_movieclip_types.h"
51 #include "DNA_scene_types.h"
52 #include "DNA_screen_types.h"
53 #include "DNA_sequence_types.h"
54 #include "DNA_smoke_types.h"
55 #include "DNA_sound_types.h"
56 #include "DNA_space_types.h"
57 #include "DNA_view3d_types.h"
58 #include "DNA_world_types.h"
59
60 #include "BLI_blenlib.h"
61 #include "BLI_bpath.h"
62 #include "BLI_math.h"
63 #include "BLI_pbvh.h"
64 #include "BLI_utildefines.h"
65
66 #include "BKE_main.h"
67 #include "BKE_global.h"
68 #include "BKE_idprop.h"
69 #include "BKE_armature.h"
70 #include "BKE_action.h"
71 #include "BKE_bullet.h"
72 #include "BKE_colortools.h"
73 #include "BKE_deform.h"
74 #include "BKE_DerivedMesh.h"
75 #include "BKE_animsys.h"
76 #include "BKE_anim.h"
77 #include "BKE_constraint.h"
78 #include "BKE_curve.h"
79 #include "BKE_displist.h"
80 #include "BKE_effect.h"
81 #include "BKE_fcurve.h"
82 #include "BKE_group.h"
83 #include "BKE_icons.h"
84 #include "BKE_key.h"
85 #include "BKE_lamp.h"
86 #include "BKE_lattice.h"
87 #include "BKE_library.h"
88 #include "BKE_mesh.h"
89 #include "BKE_tessmesh.h"
90 #include "BKE_mball.h"
91 #include "BKE_modifier.h"
92 #include "BKE_node.h"
93 #include "BKE_object.h"
94 #include "BKE_paint.h"
95 #include "BKE_particle.h"
96 #include "BKE_pointcache.h"
97 #include "BKE_property.h"
98 #include "BKE_sca.h"
99 #include "BKE_scene.h"
100 #include "BKE_sequencer.h"
101 #include "BKE_speaker.h"
102 #include "BKE_softbody.h"
103 #include "BKE_material.h"
104 #include "BKE_camera.h"
105
106 #include "LBM_fluidsim.h"
107
108 #ifdef WITH_PYTHON
109 #include "BPY_extern.h"
110 #endif
111
112 #include "GPU_material.h"
113
114 /* Local function protos */
115 static void solve_parenting (Scene *scene, Object *ob, Object *par, float obmat[][4], float slowmat[][4], int simul);
116
117 float originmat[3][3];  /* after where_is_object(), can be used in other functions (bad!) */
118
119 void clear_workob(Object *workob)
120 {
121         memset(workob, 0, sizeof(Object));
122         
123         workob->size[0]= workob->size[1]= workob->size[2]= 1.0f;
124         workob->dscale[0]= workob->dscale[1]= workob->dscale[2]= 1.0f;
125         workob->rotmode= ROT_MODE_EUL;
126 }
127
128 void copy_baseflags(struct Scene *scene)
129 {
130         Base *base= scene->base.first;
131         
132         while (base) {
133                 base->object->flag= base->flag;
134                 base= base->next;
135         }
136 }
137
138 void copy_objectflags(struct Scene *scene)
139 {
140         Base *base= scene->base.first;
141         
142         while (base) {
143                 base->flag= base->object->flag;
144                 base= base->next;
145         }
146 }
147
148 void update_base_layer(struct Scene *scene, Object *ob)
149 {
150         Base *base= scene->base.first;
151
152         while (base) {
153                 if (base->object == ob) base->lay= ob->lay;
154                 base= base->next;
155         }
156 }
157
158 void object_free_particlesystems(Object *ob)
159 {
160         while (ob->particlesystem.first) {
161                 ParticleSystem *psys = ob->particlesystem.first;
162                 
163                 BLI_remlink(&ob->particlesystem,psys);
164                 
165                 psys_free(ob,psys);
166         }
167 }
168
169 void object_free_softbody(Object *ob)
170 {
171         if (ob->soft) {
172                 sbFree(ob->soft);
173                 ob->soft= NULL;
174         }
175 }
176
177 void object_free_bulletsoftbody(Object *ob)
178 {
179         if (ob->bsoft) {
180                 bsbFree(ob->bsoft);
181                 ob->bsoft= NULL;
182         }
183 }
184
185 void object_free_modifiers(Object *ob)
186 {
187         while (ob->modifiers.first) {
188                 ModifierData *md = ob->modifiers.first;
189                 
190                 BLI_remlink(&ob->modifiers, md);
191                 
192                 modifier_free(md);
193         }
194
195         /* particle modifiers were freed, so free the particlesystems as well */
196         object_free_particlesystems(ob);
197
198         /* same for softbody */
199         object_free_softbody(ob);
200 }
201
202 int object_support_modifier_type(Object *ob, int modifier_type)
203 {
204         ModifierTypeInfo *mti;
205
206         mti = modifierType_getInfo(modifier_type);
207
208         if (!((mti->flags & eModifierTypeFlag_AcceptsCVs) ||
209              (ob->type==OB_MESH && (mti->flags & eModifierTypeFlag_AcceptsMesh))))
210         {
211                         return FALSE;
212         }
213
214         return TRUE;
215 }
216
217 void object_link_modifiers(struct Object *ob, struct Object *from)
218 {
219         ModifierData *md;
220         object_free_modifiers(ob);
221
222         if (!ELEM5(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_LATTICE)) {
223                 /* only objects listed above can have modifiers and linking them to objects
224                  * which doesn't have modifiers stack is quite silly */
225                 return;
226         }
227
228         for (md=from->modifiers.first; md; md=md->next) {
229                 ModifierData *nmd = NULL;
230
231                 if (ELEM4(md->type, eModifierType_Hook, eModifierType_Softbody, eModifierType_ParticleInstance, eModifierType_Collision)) continue;
232
233                 if (!object_support_modifier_type(ob, md->type))
234                         continue;
235
236                 nmd = modifier_new(md->type);
237                 modifier_copyData(md, nmd);
238                 BLI_addtail(&ob->modifiers, nmd);
239         }
240
241         copy_object_particlesystems(ob, from);
242         copy_object_softbody(ob, from);
243
244         // TODO: smoke?, cloth?
245 }
246
247 /* here we will collect all local displist stuff */
248 /* also (ab)used in depsgraph */
249 void object_free_display(Object *ob)
250 {
251         if (ob->derivedDeform) {
252                 ob->derivedDeform->needsFree = 1;
253                 ob->derivedDeform->release(ob->derivedDeform);
254                 ob->derivedDeform= NULL;
255         }
256         if (ob->derivedFinal) {
257                 ob->derivedFinal->needsFree = 1;
258                 ob->derivedFinal->release(ob->derivedFinal);
259                 ob->derivedFinal= NULL;
260         }
261         
262         freedisplist(&ob->disp);
263 }
264
265 void free_sculptsession_deformMats(SculptSession *ss)
266 {
267         if (ss->orig_cos) MEM_freeN(ss->orig_cos);
268         if (ss->deform_cos) MEM_freeN(ss->deform_cos);
269         if (ss->deform_imats) MEM_freeN(ss->deform_imats);
270
271         ss->orig_cos = NULL;
272         ss->deform_cos = NULL;
273         ss->deform_imats = NULL;
274 }
275
276 void free_sculptsession(Object *ob)
277 {
278         if (ob && ob->sculpt) {
279                 SculptSession *ss = ob->sculpt;
280                 DerivedMesh *dm= ob->derivedFinal;
281
282                 if (ss->pbvh)
283                         BLI_pbvh_free(ss->pbvh);
284                 if (dm && dm->getPBVH)
285                         dm->getPBVH(NULL, dm); /* signal to clear */
286
287                 if (ss->texcache)
288                         MEM_freeN(ss->texcache);
289
290                 if (ss->layer_co)
291                         MEM_freeN(ss->layer_co);
292
293                 if (ss->orig_cos)
294                         MEM_freeN(ss->orig_cos);
295                 if (ss->deform_cos)
296                         MEM_freeN(ss->deform_cos);
297                 if (ss->deform_imats)
298                         MEM_freeN(ss->deform_imats);
299
300                 MEM_freeN(ss);
301
302                 ob->sculpt = NULL;
303         }
304 }
305
306
307 /* do not free object itself */
308 void free_object(Object *ob)
309 {
310         int a;
311         
312         object_free_display(ob);
313         
314         /* disconnect specific data */
315         if (ob->data) {
316                 ID *id= ob->data;
317                 id->us--;
318                 if (id->us==0) {
319                         if (ob->type==OB_MESH) unlink_mesh(ob->data);
320                         else if (ob->type==OB_CURVE) unlink_curve(ob->data);
321                         else if (ob->type==OB_MBALL) unlink_mball(ob->data);
322                 }
323                 ob->data= NULL;
324         }
325         
326         for (a=0; a<ob->totcol; a++) {
327                 if (ob->mat[a]) ob->mat[a]->id.us--;
328         }
329         if (ob->mat) MEM_freeN(ob->mat);
330         if (ob->matbits) MEM_freeN(ob->matbits);
331         ob->mat= NULL;
332         ob->matbits= NULL;
333         if (ob->bb) MEM_freeN(ob->bb); 
334         ob->bb= NULL;
335         if (ob->adt) BKE_free_animdata((ID *)ob);
336         if (ob->poselib) ob->poselib->id.us--;
337         if (ob->gpd) ((ID *)ob->gpd)->us--;
338         if (ob->defbase.first)
339                 BLI_freelistN(&ob->defbase);
340         if (ob->pose)
341                 free_pose(ob->pose);
342         if (ob->mpath)
343                 animviz_free_motionpath(ob->mpath);
344         free_properties(&ob->prop);
345         object_free_modifiers(ob);
346         
347         free_sensors(&ob->sensors);
348         free_controllers(&ob->controllers);
349         free_actuators(&ob->actuators);
350         
351         free_constraints(&ob->constraints);
352         
353         free_partdeflect(ob->pd);
354
355         if (ob->soft) sbFree(ob->soft);
356         if (ob->bsoft) bsbFree(ob->bsoft);
357         if (ob->gpulamp.first) GPU_lamp_free(ob);
358
359         free_sculptsession(ob);
360
361         if (ob->pc_ids.first) BLI_freelistN(&ob->pc_ids);
362 }
363
364 static void unlink_object__unlinkModifierLinks(void *userData, Object *ob, Object **obpoin)
365 {
366         Object *unlinkOb = userData;
367
368         if (*obpoin==unlinkOb) {
369                 *obpoin = NULL;
370                 ob->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME; // XXX: should this just be OB_RECALC_DATA?
371         }
372 }
373
374 void unlink_object(Object *ob)
375 {
376         Main *bmain= G.main;
377         Object *obt;
378         Material *mat;
379         World *wrld;
380         bScreen *sc;
381         Scene *sce;
382         Curve *cu;
383         Tex *tex;
384         Group *group;
385         Camera *camera;
386         bConstraint *con;
387         //bActionStrip *strip; // XXX animsys 
388         ModifierData *md;
389         ARegion *ar;
390         RegionView3D *rv3d;
391         int a, found;
392         
393         unlink_controllers(&ob->controllers);
394         unlink_actuators(&ob->actuators);
395         
396         /* check all objects: parents en bevels and fields, also from libraries */
397         // FIXME: need to check all animation blocks (drivers)
398         obt= bmain->object.first;
399         while (obt) {
400                 if (obt->proxy==ob)
401                         obt->proxy= NULL;
402                 if (obt->proxy_from==ob) {
403                         obt->proxy_from= NULL;
404                         obt->recalc |= OB_RECALC_OB;
405                 }
406                 if (obt->proxy_group==ob)
407                         obt->proxy_group= NULL;
408                 
409                 if (obt->parent==ob) {
410                         obt->parent= NULL;
411                         obt->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
412                 }
413                 
414                 modifiers_foreachObjectLink(obt, unlink_object__unlinkModifierLinks, ob);
415                 
416                 if ELEM(obt->type, OB_CURVE, OB_FONT) {
417                         cu= obt->data;
418
419                         if (cu->bevobj==ob) {
420                                 cu->bevobj= NULL;
421                                 obt->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
422                         }
423                         if (cu->taperobj==ob) {
424                                 cu->taperobj= NULL;
425                                 obt->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
426                         }
427                         if (cu->textoncurve==ob) {
428                                 cu->textoncurve= NULL;
429                                 obt->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
430                         }
431                 }
432                 else if (obt->type==OB_ARMATURE && obt->pose) {
433                         bPoseChannel *pchan;
434                         for (pchan= obt->pose->chanbase.first; pchan; pchan= pchan->next) {
435                                 for (con = pchan->constraints.first; con; con=con->next) {
436                                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
437                                         ListBase targets = {NULL, NULL};
438                                         bConstraintTarget *ct;
439                                         
440                                         if (cti && cti->get_constraint_targets) {
441                                                 cti->get_constraint_targets(con, &targets);
442                                                 
443                                                 for (ct= targets.first; ct; ct= ct->next) {
444                                                         if (ct->tar == ob) {
445                                                                 ct->tar = NULL;
446                                                                 ct->subtarget[0]= '\0';
447                                                                 obt->recalc |= OB_RECALC_DATA;
448                                                         }
449                                                 }
450                                                 
451                                                 if (cti->flush_constraint_targets)
452                                                         cti->flush_constraint_targets(con, &targets, 0);
453                                         }
454                                 }
455                                 if (pchan->custom==ob)
456                                         pchan->custom= NULL;
457                         }
458                 } 
459                 else if (ELEM(OB_MBALL, ob->type, obt->type)) {
460                         if (is_mball_basis_for (obt, ob))
461                                 obt->recalc|= OB_RECALC_DATA;
462                 }
463                 
464                 sca_remove_ob_poin(obt, ob);
465                 
466                 for (con = obt->constraints.first; con; con=con->next) {
467                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
468                         ListBase targets = {NULL, NULL};
469                         bConstraintTarget *ct;
470                         
471                         if (cti && cti->get_constraint_targets) {
472                                 cti->get_constraint_targets(con, &targets);
473                                 
474                                 for (ct= targets.first; ct; ct= ct->next) {
475                                         if (ct->tar == ob) {
476                                                 ct->tar = NULL;
477                                                 ct->subtarget[0]= '\0';
478                                                 obt->recalc |= OB_RECALC_DATA;
479                                         }
480                                 }
481                                 
482                                 if (cti->flush_constraint_targets)
483                                         cti->flush_constraint_targets(con, &targets, 0);
484                         }
485                 }
486                 
487                 /* object is deflector or field */
488                 if (ob->pd) {
489                         if (obt->soft)
490                                 obt->recalc |= OB_RECALC_DATA;
491
492                         /* cloth */
493                         for (md=obt->modifiers.first; md; md=md->next)
494                                 if (md->type == eModifierType_Cloth)
495                                         obt->recalc |= OB_RECALC_DATA;
496                 }
497                 
498                 /* strips */
499 #if 0 // XXX old animation system
500                 for (strip= obt->nlastrips.first; strip; strip= strip->next) {
501                         if (strip->object==ob)
502                                 strip->object= NULL;
503                         
504                         if (strip->modifiers.first) {
505                                 bActionModifier *amod;
506                                 for (amod= strip->modifiers.first; amod; amod= amod->next)
507                                         if (amod->ob==ob)
508                                                 amod->ob= NULL;
509                         }
510                 }
511 #endif // XXX old animation system
512
513                 /* particle systems */
514                 if (obt->particlesystem.first) {
515                         ParticleSystem *tpsys= obt->particlesystem.first;
516                         for (; tpsys; tpsys=tpsys->next) {
517                                 BoidState *state = NULL;
518                                 BoidRule *rule = NULL;
519
520                                 ParticleTarget *pt = tpsys->targets.first;
521                                 for (; pt; pt=pt->next) {
522                                         if (pt->ob==ob) {
523                                                 pt->ob = NULL;
524                                                 obt->recalc |= OB_RECALC_DATA;
525                                                 break;
526                                         }
527                                 }
528
529                                 if (tpsys->target_ob==ob) {
530                                         tpsys->target_ob= NULL;
531                                         obt->recalc |= OB_RECALC_DATA;
532                                 }
533
534                                 if (tpsys->part->dup_ob==ob)
535                                         tpsys->part->dup_ob= NULL;
536
537                                 if (tpsys->part->phystype==PART_PHYS_BOIDS) {
538                                         ParticleData *pa;
539                                         BoidParticle *bpa;
540                                         int p;
541
542                                         for (p=0,pa=tpsys->particles; p<tpsys->totpart; p++,pa++) {
543                                                 bpa = pa->boid;
544                                                 if (bpa->ground == ob)
545                                                         bpa->ground = NULL;
546                                         }
547                                 }
548                                 if (tpsys->part->boids) {
549                                         for (state = tpsys->part->boids->states.first; state; state=state->next) {
550                                                 for (rule = state->rules.first; rule; rule=rule->next) {
551                                                         if (rule->type==eBoidRuleType_Avoid) {
552                                                                 BoidRuleGoalAvoid *gabr = (BoidRuleGoalAvoid*)rule;
553                                                                 if (gabr->ob==ob)
554                                                                         gabr->ob= NULL;
555                                                         }
556                                                         else if (rule->type==eBoidRuleType_FollowLeader) {
557                                                                 BoidRuleFollowLeader *flbr = (BoidRuleFollowLeader*)rule;
558                                                                 if (flbr->ob==ob)
559                                                                         flbr->ob= NULL;
560                                                         }
561                                                 }
562                                         }
563                                 }
564                         }
565                         if (ob->pd)
566                                 obt->recalc |= OB_RECALC_DATA;
567                 }
568
569                 obt= obt->id.next;
570         }
571         
572         /* materials */
573         mat= bmain->mat.first;
574         while (mat) {
575         
576                 for (a=0; a<MAX_MTEX; a++) {
577                         if (mat->mtex[a] && ob==mat->mtex[a]->object) {
578                                 /* actually, test for lib here... to do */
579                                 mat->mtex[a]->object= NULL;
580                         }
581                 }
582
583                 mat= mat->id.next;
584         }
585         
586         /* textures */
587         for (tex= bmain->tex.first; tex; tex= tex->id.next) {
588                 if (tex->env && (ob==tex->env->object)) tex->env->object= NULL;
589                 if (tex->pd  && (ob==tex->pd->object))  tex->pd->object= NULL;
590                 if (tex->vd  && (ob==tex->vd->object))  tex->vd->object= NULL;
591         }
592
593         /* worlds */
594         wrld= bmain->world.first;
595         while (wrld) {
596                 if (wrld->id.lib==NULL) {
597                         for (a=0; a<MAX_MTEX; a++) {
598                                 if (wrld->mtex[a] && ob==wrld->mtex[a]->object)
599                                         wrld->mtex[a]->object= NULL;
600                         }
601                 }
602                 
603                 wrld= wrld->id.next;
604         }
605                 
606         /* scenes */
607         sce= bmain->scene.first;
608         while (sce) {
609                 if (sce->id.lib==NULL) {
610                         if (sce->camera==ob) sce->camera= NULL;
611                         if (sce->toolsettings->skgen_template==ob) sce->toolsettings->skgen_template = NULL;
612                         if (sce->toolsettings->particle.object==ob) sce->toolsettings->particle.object= NULL;
613
614 #ifdef DURIAN_CAMERA_SWITCH
615                         {
616                                 TimeMarker *m;
617
618                                 for (m= sce->markers.first; m; m= m->next) {
619                                         if (m->camera==ob)
620                                                 m->camera= NULL;
621                                 }
622                         }
623 #endif
624                         if (sce->ed) {
625                                 Sequence *seq;
626                                 SEQ_BEGIN(sce->ed, seq)
627                                         if (seq->scene_camera==ob) {
628                                                 seq->scene_camera= NULL;
629                                         }
630                                 SEQ_END
631                         }
632                 }
633
634                 sce= sce->id.next;
635         }
636         
637         /* screens */
638         sc= bmain->screen.first;
639         while (sc) {
640                 ScrArea *sa= sc->areabase.first;
641                 while (sa) {
642                         SpaceLink *sl;
643
644                         for (sl= sa->spacedata.first; sl; sl= sl->next) {
645                                 if (sl->spacetype==SPACE_VIEW3D) {
646                                         View3D *v3d= (View3D*) sl;
647
648                                         found= 0;
649                                         if (v3d->camera==ob) {
650                                                 v3d->camera= NULL;
651                                                 found= 1;
652                                         }
653                                         if (v3d->localvd && v3d->localvd->camera==ob ) {
654                                                 v3d->localvd->camera= NULL;
655                                                 found += 2;
656                                         }
657
658                                         if (found) {
659                                                 if (sa->spacetype == SPACE_VIEW3D) {
660                                                         for (ar= sa->regionbase.first; ar; ar= ar->next) {
661                                                                 if (ar->regiontype==RGN_TYPE_WINDOW) {
662                                                                         rv3d= (RegionView3D *)ar->regiondata;
663                                                                         if (found == 1 || found == 3) {
664                                                                                 if (rv3d->persp == RV3D_CAMOB)
665                                                                                         rv3d->persp= RV3D_PERSP;
666                                                                         }
667                                                                         if (found == 2 || found == 3) {
668                                                                                 if (rv3d->localvd && rv3d->localvd->persp == RV3D_CAMOB)
669                                                                                         rv3d->localvd->persp= RV3D_PERSP;
670                                                                         }
671                                                                 }
672                                                         }
673                                                 }
674                                         }
675                                 }
676                                 else if (sl->spacetype==SPACE_OUTLINER) {
677                                         SpaceOops *so= (SpaceOops *)sl;
678
679                                         if (so->treestore) {
680                                                 TreeStoreElem *tselem= so->treestore->data;
681                                                 int a;
682                                                 for (a=0; a<so->treestore->usedelem; a++, tselem++) {
683                                                         if (tselem->id==(ID *)ob) tselem->id= NULL;
684                                                 }
685                                         }
686                                 }
687                                 else if (sl->spacetype==SPACE_BUTS) {
688                                         SpaceButs *sbuts= (SpaceButs *)sl;
689
690                                         if (sbuts->pinid==(ID *)ob) {
691                                                 sbuts->flag&= ~SB_PIN_CONTEXT;
692                                                 sbuts->pinid= NULL;
693                                         }
694                                 }
695                         }
696
697                         sa= sa->next;
698                 }
699                 sc= sc->id.next;
700         }
701
702         /* groups */
703         group= bmain->group.first;
704         while (group) {
705                 rem_from_group(group, ob, NULL, NULL);
706                 group= group->id.next;
707         }
708         
709         /* cameras */
710         camera= bmain->camera.first;
711         while (camera) {
712                 if (camera->dof_ob==ob) {
713                         camera->dof_ob = NULL;
714                 }
715                 camera= camera->id.next;
716         }
717 }
718
719 int exist_object(Object *obtest)
720 {
721         Object *ob;
722         
723         if (obtest==NULL) return 0;
724         
725         ob= G.main->object.first;
726         while (ob) {
727                 if (ob==obtest) return 1;
728                 ob= ob->id.next;
729         }
730         return 0;
731 }
732
733 /* *************************************************** */
734
735 static void *add_obdata_from_type(int type)
736 {
737         switch (type) {
738         case OB_MESH: return add_mesh("Mesh");
739         case OB_CURVE: return add_curve("Curve", OB_CURVE);
740         case OB_SURF: return add_curve("Surf", OB_SURF);
741         case OB_FONT: return add_curve("Text", OB_FONT);
742         case OB_MBALL: return add_mball("Meta");
743         case OB_CAMERA: return add_camera("Camera");
744         case OB_LAMP: return add_lamp("Lamp");
745         case OB_LATTICE: return add_lattice("Lattice");
746         case OB_ARMATURE: return add_armature("Armature");
747         case OB_SPEAKER: return add_speaker("Speaker");
748         case OB_EMPTY: return NULL;
749         default:
750                 printf("add_obdata_from_type: Internal error, bad type: %d\n", type);
751                 return NULL;
752         }
753 }
754
755 static const char *get_obdata_defname(int type)
756 {
757         switch (type) {
758         case OB_MESH: return "Mesh";
759         case OB_CURVE: return "Curve";
760         case OB_SURF: return "Surf";
761         case OB_FONT: return "Text";
762         case OB_MBALL: return "Mball";
763         case OB_CAMERA: return "Camera";
764         case OB_LAMP: return "Lamp";
765         case OB_LATTICE: return "Lattice";
766         case OB_ARMATURE: return "Armature";
767         case OB_SPEAKER: return "Speaker";
768         case OB_EMPTY: return "Empty";
769         default:
770                 printf("get_obdata_defname: Internal error, bad type: %d\n", type);
771                 return "Empty";
772         }
773 }
774
775 /* more general add: creates minimum required data, but without vertices etc. */
776 Object *add_only_object(int type, const char *name)
777 {
778         Object *ob;
779
780         ob= alloc_libblock(&G.main->object, ID_OB, name);
781
782         /* default object vars */
783         ob->type= type;
784         
785         ob->col[0]= ob->col[1]= ob->col[2]= 1.0;
786         ob->col[3]= 1.0;
787         
788         ob->size[0]= ob->size[1]= ob->size[2]= 1.0;
789         ob->dscale[0]= ob->dscale[1]= ob->dscale[2]= 1.0;
790         
791         /* objects should default to having Euler XYZ rotations, 
792          * but rotations default to quaternions 
793          */
794         ob->rotmode= ROT_MODE_EUL;
795
796         unit_axis_angle(ob->rotAxis, &ob->rotAngle);
797         unit_axis_angle(ob->drotAxis, &ob->drotAngle);
798
799         unit_qt(ob->quat);
800         unit_qt(ob->dquat);
801
802         /* rotation locks should be 4D for 4 component rotations by default... */
803         ob->protectflag = OB_LOCK_ROT4D;
804         
805         unit_m4(ob->constinv);
806         unit_m4(ob->parentinv);
807         unit_m4(ob->obmat);
808         ob->dt= OB_TEXTURE;
809         ob->empty_drawtype= OB_PLAINAXES;
810         ob->empty_drawsize= 1.0;
811
812         if (type==OB_CAMERA || type==OB_LAMP || type==OB_SPEAKER) {
813                 ob->trackflag= OB_NEGZ;
814                 ob->upflag= OB_POSY;
815         }
816         else {
817                 ob->trackflag= OB_POSY;
818                 ob->upflag= OB_POSZ;
819         }
820         
821         ob->dupon= 1; ob->dupoff= 0;
822         ob->dupsta= 1; ob->dupend= 100;
823         ob->dupfacesca = 1.0;
824
825         /* Game engine defaults*/
826         ob->mass= ob->inertia= 1.0f;
827         ob->formfactor= 0.4f;
828         ob->damping= 0.04f;
829         ob->rdamping= 0.1f;
830         ob->anisotropicFriction[0] = 1.0f;
831         ob->anisotropicFriction[1] = 1.0f;
832         ob->anisotropicFriction[2] = 1.0f;
833         ob->gameflag= OB_PROP|OB_COLLISION;
834         ob->margin = 0.0;
835         ob->init_state=1;
836         ob->state=1;
837         /* ob->pad3 == Contact Processing Threshold */
838         ob->m_contactProcessingThreshold = 1.;
839         ob->obstacleRad = 1.;
840         
841         /* NT fluid sim defaults */
842         ob->fluidsimSettings = NULL;
843
844         ob->pc_ids.first = ob->pc_ids.last = NULL;
845         
846         /* Animation Visualisation defaults */
847         animviz_settings_init(&ob->avs);
848
849         return ob;
850 }
851
852 /* general add: to scene, with layer from area and default name */
853 /* creates minimum required data, but without vertices etc. */
854 Object *add_object(struct Scene *scene, int type)
855 {
856         Object *ob;
857         Base *base;
858         char name[MAX_ID_NAME];
859
860         BLI_strncpy(name, get_obdata_defname(type), sizeof(name));
861         ob = add_only_object(type, name);
862
863         ob->data= add_obdata_from_type(type);
864
865         ob->lay= scene->lay;
866         
867         base= scene_add_base(scene, ob);
868         scene_select_base(scene, base);
869         ob->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
870
871         return ob;
872 }
873
874 SoftBody *copy_softbody(SoftBody *sb)
875 {
876         SoftBody *sbn;
877         
878         if (sb==NULL) return(NULL);
879         
880         sbn= MEM_dupallocN(sb);
881         sbn->totspring= sbn->totpoint= 0;
882         sbn->bpoint= NULL;
883         sbn->bspring= NULL;
884         
885         sbn->keys= NULL;
886         sbn->totkey= sbn->totpointkey= 0;
887         
888         sbn->scratch= NULL;
889
890         sbn->pointcache= BKE_ptcache_copy_list(&sbn->ptcaches, &sb->ptcaches);
891
892         if (sb->effector_weights)
893                 sbn->effector_weights = MEM_dupallocN(sb->effector_weights);
894
895         return sbn;
896 }
897
898 BulletSoftBody *copy_bulletsoftbody(BulletSoftBody *bsb)
899 {
900         BulletSoftBody *bsbn;
901
902         if (bsb == NULL)
903                 return NULL;
904         bsbn = MEM_dupallocN(bsb);
905         /* no pointer in this structure yet */
906         return bsbn;
907 }
908
909 static ParticleSystem *copy_particlesystem(ParticleSystem *psys)
910 {
911         ParticleSystem *psysn;
912         ParticleData *pa;
913         int p;
914
915         psysn= MEM_dupallocN(psys);
916         psysn->particles= MEM_dupallocN(psys->particles);
917         psysn->child= MEM_dupallocN(psys->child);
918
919         if (psys->part->type == PART_HAIR) {
920                 for (p=0, pa=psysn->particles; p<psysn->totpart; p++, pa++)
921                         pa->hair = MEM_dupallocN(pa->hair);
922         }
923
924         if (psysn->particles && (psysn->particles->keys || psysn->particles->boid)) {
925                 ParticleKey *key = psysn->particles->keys;
926                 BoidParticle *boid = psysn->particles->boid;
927
928                 if (key)
929                         key = MEM_dupallocN(key);
930                 
931                 if (boid)
932                         boid = MEM_dupallocN(boid);
933                 
934                 for (p=0, pa=psysn->particles; p<psysn->totpart; p++, pa++) {
935                         if (boid)
936                                 pa->boid = boid++;
937                         if (key) {
938                                 pa->keys = key;
939                                 key += pa->totkey;
940                         }
941                 }
942         }
943
944         if (psys->clmd) {
945                 psysn->clmd = (ClothModifierData *)modifier_new(eModifierType_Cloth);
946                 modifier_copyData((ModifierData*)psys->clmd, (ModifierData*)psysn->clmd);
947                 psys->hair_in_dm = psys->hair_out_dm = NULL;
948         }
949
950         BLI_duplicatelist(&psysn->targets, &psys->targets);
951
952         psysn->pathcache= NULL;
953         psysn->childcache= NULL;
954         psysn->edit= NULL;
955         psysn->frand= NULL;
956         psysn->pdd= NULL;
957         psysn->effectors= NULL;
958         
959         psysn->pathcachebufs.first = psysn->pathcachebufs.last = NULL;
960         psysn->childcachebufs.first = psysn->childcachebufs.last = NULL;
961         psysn->renderdata = NULL;
962         
963         psysn->pointcache= BKE_ptcache_copy_list(&psysn->ptcaches, &psys->ptcaches);
964
965         /* XXX - from reading existing code this seems correct but intended usage of
966          * pointcache should /w cloth should be added in 'ParticleSystem' - campbell */
967         if (psysn->clmd) {
968                 psysn->clmd->point_cache= psysn->pointcache;
969         }
970
971         id_us_plus((ID *)psysn->part);
972
973         return psysn;
974 }
975
976 void copy_object_particlesystems(Object *obn, Object *ob)
977 {
978         ParticleSystem *psys, *npsys;
979         ModifierData *md;
980
981         if (obn->type != OB_MESH) {
982                 /* currently only mesh objects can have soft body */
983                 return;
984         }
985
986         obn->particlesystem.first= obn->particlesystem.last= NULL;
987         for (psys=ob->particlesystem.first; psys; psys=psys->next) {
988                 npsys= copy_particlesystem(psys);
989
990                 BLI_addtail(&obn->particlesystem, npsys);
991
992                 /* need to update particle modifiers too */
993                 for (md=obn->modifiers.first; md; md=md->next) {
994                         if (md->type==eModifierType_ParticleSystem) {
995                                 ParticleSystemModifierData *psmd= (ParticleSystemModifierData*)md;
996                                 if (psmd->psys==psys)
997                                         psmd->psys= npsys;
998                         }
999                         else if (md->type==eModifierType_DynamicPaint) {
1000                                 DynamicPaintModifierData *pmd= (DynamicPaintModifierData*)md;
1001                                 if (pmd->brush) {
1002                                         if (pmd->brush->psys==psys) {
1003                                                 pmd->brush->psys= npsys;
1004                                         }
1005                                 }
1006                         }
1007                         else if (md->type==eModifierType_Smoke) {
1008                                 SmokeModifierData *smd = (SmokeModifierData*) md;
1009                                 
1010                                 if (smd->type==MOD_SMOKE_TYPE_FLOW) {
1011                                         if (smd->flow) {
1012                                                 if (smd->flow->psys == psys)
1013                                                         smd->flow->psys= npsys;
1014                                         }
1015                                 }
1016                         }
1017                 }
1018         }
1019 }
1020
1021 void copy_object_softbody(Object *obn, Object *ob)
1022 {
1023         if (ob->soft)
1024                 obn->soft= copy_softbody(ob->soft);
1025 }
1026
1027 static void copy_object_pose(Object *obn, Object *ob)
1028 {
1029         bPoseChannel *chan;
1030         
1031         /* note: need to clear obn->pose pointer first, so that copy_pose works (otherwise there's a crash) */
1032         obn->pose= NULL;
1033         copy_pose(&obn->pose, ob->pose, 1);     /* 1 = copy constraints */
1034
1035         for (chan = obn->pose->chanbase.first; chan; chan=chan->next) {
1036                 bConstraint *con;
1037                 
1038                 chan->flag &= ~(POSE_LOC|POSE_ROT|POSE_SIZE);
1039                 
1040                 for (con= chan->constraints.first; con; con= con->next) {
1041                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1042                         ListBase targets = {NULL, NULL};
1043                         bConstraintTarget *ct;
1044                         
1045                         if (cti && cti->get_constraint_targets) {
1046                                 cti->get_constraint_targets(con, &targets);
1047                                 
1048                                 for (ct= targets.first; ct; ct= ct->next) {
1049                                         if (ct->tar == ob)
1050                                                 ct->tar = obn;
1051                                 }
1052                                 
1053                                 if (cti->flush_constraint_targets)
1054                                         cti->flush_constraint_targets(con, &targets, 0);
1055                         }
1056                 }
1057         }
1058 }
1059
1060 static int object_pose_context(Object *ob)
1061 {
1062         if (    (ob) &&
1063                 (ob->type == OB_ARMATURE) &&
1064                 (ob->pose) &&
1065                 (ob->mode & OB_MODE_POSE)
1066         ) {
1067                 return 1;
1068         }
1069         else {
1070                 return 0;
1071         }
1072 }
1073
1074 Object *object_pose_armature_get(Object *ob)
1075 {
1076         if (ob==NULL)
1077                 return NULL;
1078
1079         if (object_pose_context(ob))
1080                 return ob;
1081
1082         ob= modifiers_isDeformedByArmature(ob);
1083
1084         if (object_pose_context(ob))
1085                 return ob;
1086
1087         return NULL;
1088 }
1089
1090 static void copy_object_transform(Object *ob_tar, Object *ob_src)
1091 {
1092         copy_v3_v3(ob_tar->loc, ob_src->loc);
1093         copy_v3_v3(ob_tar->rot, ob_src->rot);
1094         copy_v3_v3(ob_tar->quat, ob_src->quat);
1095         copy_v3_v3(ob_tar->rotAxis, ob_src->rotAxis);
1096         ob_tar->rotAngle= ob_src->rotAngle;
1097         ob_tar->rotmode= ob_src->rotmode;
1098         copy_v3_v3(ob_tar->size, ob_src->size);
1099 }
1100
1101 Object *copy_object(Object *ob)
1102 {
1103         Object *obn;
1104         ModifierData *md;
1105         int a;
1106
1107         obn= copy_libblock(&ob->id);
1108         
1109         if (ob->totcol) {
1110                 obn->mat= MEM_dupallocN(ob->mat);
1111                 obn->matbits= MEM_dupallocN(ob->matbits);
1112                 obn->totcol= ob->totcol;
1113         }
1114         
1115         if (ob->bb) obn->bb= MEM_dupallocN(ob->bb);
1116         obn->flag &= ~OB_FROMGROUP;
1117         
1118         obn->modifiers.first = obn->modifiers.last= NULL;
1119         
1120         for (md=ob->modifiers.first; md; md=md->next) {
1121                 ModifierData *nmd = modifier_new(md->type);
1122                 BLI_strncpy(nmd->name, md->name, sizeof(nmd->name));
1123                 modifier_copyData(md, nmd);
1124                 BLI_addtail(&obn->modifiers, nmd);
1125         }
1126
1127         obn->prop.first = obn->prop.last = NULL;
1128         copy_properties(&obn->prop, &ob->prop);
1129         
1130         copy_sensors(&obn->sensors, &ob->sensors);
1131         copy_controllers(&obn->controllers, &ob->controllers);
1132         copy_actuators(&obn->actuators, &ob->actuators);
1133         
1134         if (ob->pose) {
1135                 copy_object_pose(obn, ob);
1136                 /* backwards compat... non-armatures can get poses in older files? */
1137                 if (ob->type==OB_ARMATURE)
1138                         armature_rebuild_pose(obn, obn->data);
1139         }
1140         defgroup_copy_list(&obn->defbase, &ob->defbase);
1141         copy_constraints(&obn->constraints, &ob->constraints, TRUE);
1142
1143         obn->mode = 0;
1144         obn->sculpt = NULL;
1145
1146         /* increase user numbers */
1147         id_us_plus((ID *)obn->data);
1148         id_us_plus((ID *)obn->gpd);
1149         id_lib_extern((ID *)obn->dup_group);
1150
1151         for (a=0; a<obn->totcol; a++) id_us_plus((ID *)obn->mat[a]);
1152         
1153         obn->disp.first= obn->disp.last= NULL;
1154         
1155         if (ob->pd) {
1156                 obn->pd= MEM_dupallocN(ob->pd);
1157                 if (obn->pd->tex)
1158                         id_us_plus(&(obn->pd->tex->id));
1159                 if (obn->pd->rng)
1160                         obn->pd->rng = MEM_dupallocN(ob->pd->rng);
1161         }
1162         obn->soft= copy_softbody(ob->soft);
1163         obn->bsoft = copy_bulletsoftbody(ob->bsoft);
1164
1165         copy_object_particlesystems(obn, ob);
1166         
1167         obn->derivedDeform = NULL;
1168         obn->derivedFinal = NULL;
1169
1170         obn->gpulamp.first = obn->gpulamp.last = NULL;
1171         obn->pc_ids.first = obn->pc_ids.last = NULL;
1172
1173         obn->mpath= NULL;
1174         
1175         return obn;
1176 }
1177
1178 static void extern_local_object(Object *ob)
1179 {
1180         ParticleSystem *psys;
1181
1182         id_lib_extern((ID *)ob->data);
1183         id_lib_extern((ID *)ob->dup_group);
1184         id_lib_extern((ID *)ob->poselib);
1185         id_lib_extern((ID *)ob->gpd);
1186
1187         extern_local_matarar(ob->mat, ob->totcol);
1188
1189         for (psys=ob->particlesystem.first; psys; psys=psys->next)
1190                 id_lib_extern((ID *)psys->part);
1191 }
1192
1193 void make_local_object(Object *ob)
1194 {
1195         Main *bmain= G.main;
1196         Scene *sce;
1197         Base *base;
1198         int is_local= FALSE, is_lib= FALSE;
1199
1200         /* - only lib users: do nothing
1201          * - only local users: set flag
1202          * - mixed: make copy
1203          */
1204
1205         if (ob->id.lib==NULL) return;
1206         
1207         ob->proxy= ob->proxy_from= NULL;
1208         
1209         if (ob->id.us==1) {
1210                 id_clear_lib_data(bmain, &ob->id);
1211                 extern_local_object(ob);
1212         }
1213         else {
1214                 for (sce= bmain->scene.first; sce && ELEM(0, is_lib, is_local); sce= sce->id.next) {
1215                         if (object_in_scene(ob, sce)) {
1216                                 if (sce->id.lib) is_lib= TRUE;
1217                                 else is_local= TRUE;
1218                         }
1219                 }
1220
1221                 if (is_local && is_lib == FALSE) {
1222                         id_clear_lib_data(bmain, &ob->id);
1223                         extern_local_object(ob);
1224                 }
1225                 else if (is_local && is_lib) {
1226                         Object *ob_new= copy_object(ob);
1227
1228                         ob_new->id.us= 0;
1229                         
1230                         /* Remap paths of new ID using old library as base. */
1231                         BKE_id_lib_local_paths(bmain, ob->id.lib, &ob_new->id);
1232
1233                         sce= bmain->scene.first;
1234                         while (sce) {
1235                                 if (sce->id.lib==NULL) {
1236                                         base= sce->base.first;
1237                                         while (base) {
1238                                                 if (base->object==ob) {
1239                                                         base->object= ob_new;
1240                                                         ob_new->id.us++;
1241                                                         ob->id.us--;
1242                                                 }
1243                                                 base= base->next;
1244                                         }
1245                                 }
1246                                 sce= sce->id.next;
1247                         }
1248                 }
1249         }
1250 }
1251
1252 /*
1253  * Returns true if the Object is a from an external blend file (libdata)
1254  */
1255 int object_is_libdata(Object *ob)
1256 {
1257         if (!ob) return 0;
1258         if (ob->proxy) return 0;
1259         if (ob->id.lib) return 1;
1260         return 0;
1261 }
1262
1263 /* Returns true if the Object data is a from an external blend file (libdata) */
1264 int object_data_is_libdata(Object *ob)
1265 {
1266         if (!ob) return 0;
1267         if (ob->proxy && (ob->data==NULL || ((ID *)ob->data)->lib==NULL)) return 0;
1268         if (ob->id.lib) return 1;
1269         if (ob->data==NULL) return 0;
1270         if (((ID *)ob->data)->lib) return 1;
1271
1272         return 0;
1273 }
1274
1275 /* *************** PROXY **************** */
1276
1277 /* when you make proxy, ensure the exposed layers are extern */
1278 static void armature_set_id_extern(Object *ob)
1279 {
1280         bArmature *arm= ob->data;
1281         bPoseChannel *pchan;
1282         unsigned int lay= arm->layer_protected;
1283         
1284         for (pchan = ob->pose->chanbase.first; pchan; pchan=pchan->next) {
1285                 if (!(pchan->bone->layer & lay))
1286                         id_lib_extern((ID *)pchan->custom);
1287         }
1288                         
1289 }
1290
1291 void object_copy_proxy_drivers(Object *ob, Object *target)
1292 {
1293         if ((target->adt) && (target->adt->drivers.first)) {
1294                 FCurve *fcu;
1295                 
1296                 /* add new animdata block */
1297                 if (!ob->adt)
1298                         ob->adt= BKE_id_add_animdata(&ob->id);
1299                 
1300                 /* make a copy of all the drivers (for now), then correct any links that need fixing */
1301                 free_fcurves(&ob->adt->drivers);
1302                 copy_fcurves(&ob->adt->drivers, &target->adt->drivers);
1303                 
1304                 for (fcu= ob->adt->drivers.first; fcu; fcu= fcu->next) {
1305                         ChannelDriver *driver= fcu->driver;
1306                         DriverVar *dvar;
1307                         
1308                         for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
1309                                 /* all drivers */
1310                                 DRIVER_TARGETS_LOOPER(dvar) 
1311                                 {
1312                                         if (dtar->id) {
1313                                                 if ((Object *)dtar->id == target)
1314                                                         dtar->id= (ID *)ob;
1315                                                 else {
1316                                                         /* only on local objects because this causes indirect links a -> b -> c,blend to point directly to a.blend
1317                                                          * when a.blend has a proxy thats linked into c.blend  */
1318                                                         if (ob->id.lib==NULL)
1319                                                                 id_lib_extern((ID *)dtar->id);
1320                                                 }
1321                                         }
1322                                 }
1323                                 DRIVER_TARGETS_LOOPER_END
1324                         }
1325                 }
1326         }
1327 }
1328
1329 /* proxy rule: lib_object->proxy_from == the one we borrow from, set temporally while object_update */
1330 /*             local_object->proxy == pointer to library object, saved in files and read */
1331 /*             local_object->proxy_group == pointer to group dupli-object, saved in files and read */
1332
1333 void object_make_proxy(Object *ob, Object *target, Object *gob)
1334 {
1335         /* paranoia checks */
1336         if (ob->id.lib || target->id.lib==NULL) {
1337                 printf("cannot make proxy\n");
1338                 return;
1339         }
1340         
1341         ob->proxy= target;
1342         ob->proxy_group= gob;
1343         id_lib_extern(&target->id);
1344         
1345         ob->recalc= target->recalc= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
1346         
1347         /* copy transform
1348          * - gob means this proxy comes from a group, just apply the matrix
1349          *   so the object wont move from its dupli-transform.
1350          *
1351          * - no gob means this is being made from a linked object,
1352          *   this is closer to making a copy of the object - in-place. */
1353         if (gob) {
1354                 ob->rotmode= target->rotmode;
1355                 mult_m4_m4m4(ob->obmat, gob->obmat, target->obmat);
1356                 if (gob->dup_group) { /* should always be true */
1357                         float tvec[3];
1358                         copy_v3_v3(tvec, gob->dup_group->dupli_ofs);
1359                         mul_mat3_m4_v3(ob->obmat, tvec);
1360                         sub_v3_v3(ob->obmat[3], tvec);
1361                 }
1362                 object_apply_mat4(ob, ob->obmat, FALSE, TRUE);
1363         }
1364         else {
1365                 copy_object_transform(ob, target);
1366                 ob->parent= target->parent;     /* libdata */
1367                 copy_m4_m4(ob->parentinv, target->parentinv);
1368         }
1369         
1370         /* copy animdata stuff - drivers only for now... */
1371         object_copy_proxy_drivers(ob, target);
1372
1373         /* skip constraints? */
1374         // FIXME: this is considered by many as a bug
1375         
1376         /* set object type and link to data */
1377         ob->type= target->type;
1378         ob->data= target->data;
1379         id_us_plus((ID *)ob->data);             /* ensures lib data becomes LIB_EXTERN */
1380         
1381         /* copy material and index information */
1382         ob->actcol= ob->totcol= 0;
1383         if (ob->mat) MEM_freeN(ob->mat);
1384         if (ob->matbits) MEM_freeN(ob->matbits);
1385         ob->mat = NULL;
1386         ob->matbits= NULL;
1387         if ((target->totcol) && (target->mat) && OB_TYPE_SUPPORT_MATERIAL(ob->type)) {
1388                 int i;
1389                 
1390                 ob->actcol= target->actcol;
1391                 ob->totcol= target->totcol;
1392                 
1393                 ob->mat = MEM_dupallocN(target->mat);
1394                 ob->matbits = MEM_dupallocN(target->matbits);
1395                 for (i=0; i<target->totcol; i++) {
1396                         /* dont need to run test_object_materials since we know this object is new and not used elsewhere */
1397                         id_us_plus((ID *)ob->mat[i]); 
1398                 }
1399         }
1400         
1401         /* type conversions */
1402         if (target->type == OB_ARMATURE) {
1403                 copy_object_pose(ob, target);   /* data copy, object pointers in constraints */
1404                 rest_pose(ob->pose);                    /* clear all transforms in channels */
1405                 armature_rebuild_pose(ob, ob->data);    /* set all internal links */
1406                 
1407                 armature_set_id_extern(ob);
1408         }
1409         else if (target->type == OB_EMPTY) {
1410                 ob->empty_drawtype = target->empty_drawtype;
1411                 ob->empty_drawsize = target->empty_drawsize;
1412         }
1413
1414         /* copy IDProperties */
1415         if (ob->id.properties) {
1416                 IDP_FreeProperty(ob->id.properties);
1417                 MEM_freeN(ob->id.properties);
1418                 ob->id.properties= NULL;
1419         }
1420         if (target->id.properties) {
1421                 ob->id.properties= IDP_CopyProperty(target->id.properties);
1422         }
1423
1424         /* copy drawtype info */
1425         ob->dt= target->dt;
1426 }
1427
1428
1429 /* *************** CALC ****************** */
1430
1431 void object_scale_to_mat3(Object *ob, float mat[][3])
1432 {
1433         float vec[3];
1434         mul_v3_v3v3(vec, ob->size, ob->dscale);
1435         size_to_mat3( mat,vec);
1436 }
1437
1438 void object_rot_to_mat3(Object *ob, float mat[][3])
1439 {
1440         float rmat[3][3], dmat[3][3];
1441         
1442         /* 'dmat' is the delta-rotation matrix, which will get (pre)multiplied
1443          * with the rotation matrix to yield the appropriate rotation
1444          */
1445
1446         /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
1447         if (ob->rotmode > 0) {
1448                 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
1449                 eulO_to_mat3(rmat, ob->rot, ob->rotmode);
1450                 eulO_to_mat3(dmat, ob->drot, ob->rotmode);
1451         }
1452         else if (ob->rotmode == ROT_MODE_AXISANGLE) {
1453                 /* axis-angle -  not really that great for 3D-changing orientations */
1454                 axis_angle_to_mat3(rmat, ob->rotAxis, ob->rotAngle);
1455                 axis_angle_to_mat3(dmat, ob->drotAxis, ob->drotAngle);
1456         }
1457         else {
1458                 /* quats are normalised before use to eliminate scaling issues */
1459                 float tquat[4];
1460                 
1461                 normalize_qt_qt(tquat, ob->quat);
1462                 quat_to_mat3(rmat, tquat);
1463                 
1464                 normalize_qt_qt(tquat, ob->dquat);
1465                 quat_to_mat3(dmat, tquat);
1466         }
1467         
1468         /* combine these rotations */
1469         mul_m3_m3m3(mat, dmat, rmat);
1470 }
1471
1472 void object_mat3_to_rot(Object *ob, float mat[][3], short use_compat)
1473 {
1474         switch(ob->rotmode) {
1475         case ROT_MODE_QUAT:
1476                 {
1477                         float dquat[4];
1478                         mat3_to_quat(ob->quat, mat);
1479                         normalize_qt_qt(dquat, ob->dquat);
1480                         invert_qt(dquat);
1481                         mul_qt_qtqt(ob->quat, dquat, ob->quat);
1482                 }
1483                 break;
1484         case ROT_MODE_AXISANGLE:
1485                 mat3_to_axis_angle(ob->rotAxis, &ob->rotAngle, mat);
1486                 sub_v3_v3(ob->rotAxis, ob->drotAxis);
1487                 ob->rotAngle -= ob->drotAngle;
1488                 break;
1489         default: /* euler */
1490                 {
1491                         float quat[4];
1492                         float dquat[4];
1493                         float tmat[3][3];
1494
1495                         /* without drot we could apply 'mat' directly */
1496                         mat3_to_quat(quat, mat);
1497                         eulO_to_quat(dquat, ob->drot, ob->rotmode);
1498                         invert_qt(dquat);
1499                         mul_qt_qtqt(quat, dquat, quat);
1500                         quat_to_mat3(tmat, quat);
1501                         /* end drot correction */
1502
1503                         if (use_compat) mat3_to_compatible_eulO(ob->rot, ob->rot, ob->rotmode, tmat);
1504                         else                    mat3_to_eulO(ob->rot, ob->rotmode, tmat);
1505                 }
1506         }
1507 }
1508
1509 void object_tfm_protected_backup(const Object *ob,
1510                                  ObjectTfmProtectedChannels *obtfm)
1511 {
1512
1513 #define TFMCPY(   _v) (obtfm->_v = ob->_v)
1514 #define TFMCPY3D( _v) copy_v3_v3(obtfm->_v, ob->_v)
1515 #define TFMCPY4D( _v) copy_v4_v4(obtfm->_v, ob->_v)
1516
1517         TFMCPY3D(loc);
1518         TFMCPY3D(dloc);
1519         TFMCPY3D(size);
1520         TFMCPY3D(dscale);
1521         TFMCPY3D(rot);
1522         TFMCPY3D(drot);
1523         TFMCPY4D(quat);
1524         TFMCPY4D(dquat);
1525         TFMCPY3D(rotAxis);
1526         TFMCPY3D(drotAxis);
1527         TFMCPY(rotAngle);
1528         TFMCPY(drotAngle);
1529
1530 #undef TFMCPY
1531 #undef TFMCPY3D
1532 #undef TFMCPY4D
1533
1534 }
1535
1536 void object_tfm_protected_restore(Object *ob,
1537                                   const ObjectTfmProtectedChannels *obtfm,
1538                                   const short protectflag)
1539 {
1540         unsigned int i;
1541
1542         for (i= 0; i < 3; i++) {
1543                 if (protectflag & (OB_LOCK_LOCX<<i)) {
1544                         ob->loc[i]=  obtfm->loc[i];
1545                         ob->dloc[i]= obtfm->dloc[i];
1546                 }
1547
1548                 if (protectflag & (OB_LOCK_SCALEX<<i)) {
1549                         ob->size[i]=  obtfm->size[i];
1550                         ob->dscale[i]= obtfm->dscale[i];
1551                 }
1552
1553                 if (protectflag & (OB_LOCK_ROTX<<i)) {
1554                         ob->rot[i]=  obtfm->rot[i];
1555                         ob->drot[i]= obtfm->drot[i];
1556
1557                         ob->quat[i + 1]=  obtfm->quat[i + 1];
1558                         ob->dquat[i + 1]= obtfm->dquat[i + 1];
1559
1560                         ob->rotAxis[i]=  obtfm->rotAxis[i];
1561                         ob->drotAxis[i]= obtfm->drotAxis[i];
1562                 }
1563         }
1564
1565         if ((protectflag & OB_LOCK_ROT4D) && (protectflag & OB_LOCK_ROTW)) {
1566                 ob->quat[0]=  obtfm->quat[0];
1567                 ob->dquat[0]= obtfm->dquat[0];
1568
1569                 ob->rotAngle=  obtfm->rotAngle;
1570                 ob->drotAngle= obtfm->drotAngle;
1571         }
1572 }
1573
1574 /* see pchan_apply_mat4() for the equivalent 'pchan' function */
1575 void object_apply_mat4(Object *ob, float mat[][4], const short use_compat, const short use_parent)
1576 {
1577         float rot[3][3];
1578
1579         if (use_parent && ob->parent) {
1580                 float rmat[4][4], diff_mat[4][4], imat[4][4];
1581                 mult_m4_m4m4(diff_mat, ob->parent->obmat, ob->parentinv);
1582                 invert_m4_m4(imat, diff_mat);
1583                 mult_m4_m4m4(rmat, imat, mat); /* get the parent relative matrix */
1584                 object_apply_mat4(ob, rmat, use_compat, FALSE);
1585                 
1586                 /* same as below, use rmat rather than mat */
1587                 mat4_to_loc_rot_size(ob->loc, rot, ob->size, rmat);
1588                 object_mat3_to_rot(ob, rot, use_compat);
1589         }
1590         else {
1591                 mat4_to_loc_rot_size(ob->loc, rot, ob->size, mat);
1592                 object_mat3_to_rot(ob, rot, use_compat);
1593         }
1594         
1595         sub_v3_v3(ob->loc, ob->dloc);
1596
1597         if (ob->dscale[0] != 0.0f) ob->size[0] /= ob->dscale[0];
1598         if (ob->dscale[1] != 0.0f) ob->size[1] /= ob->dscale[1];
1599         if (ob->dscale[2] != 0.0f) ob->size[2] /= ob->dscale[2];
1600
1601         /* object_mat3_to_rot handles delta rotations */
1602 }
1603
1604 void object_to_mat3(Object *ob, float mat[][3]) /* no parent */
1605 {
1606         float smat[3][3];
1607         float rmat[3][3];
1608         /*float q1[4];*/
1609         
1610         /* size */
1611         object_scale_to_mat3(ob, smat);
1612
1613         /* rot */
1614         object_rot_to_mat3(ob, rmat);
1615         mul_m3_m3m3(mat, rmat, smat);
1616 }
1617
1618 void object_to_mat4(Object *ob, float mat[][4])
1619 {
1620         float tmat[3][3];
1621         
1622         object_to_mat3(ob, tmat);
1623         
1624         copy_m4_m3(mat, tmat);
1625
1626         add_v3_v3v3(mat[3], ob->loc, ob->dloc);
1627 }
1628
1629 /* extern */
1630 int enable_cu_speed= 1;
1631
1632 static void ob_parcurve(Scene *scene, Object *ob, Object *par, float mat[][4])
1633 {
1634         Curve *cu;
1635         float vec[4], dir[3], quat[4], radius, ctime;
1636         float timeoffs = 0.0, sf_orig = 0.0;
1637         
1638         unit_m4(mat);
1639         
1640         cu= par->data;
1641         if (cu->path==NULL || cu->path->data==NULL) /* only happens on reload file, but violates depsgraph still... fix! */
1642                 makeDispListCurveTypes(scene, par, 0);
1643         if (cu->path==NULL) return;
1644         
1645         /* catch exceptions: feature for nla stride editing */
1646         if (ob->ipoflag & OB_DISABLE_PATH) {
1647                 ctime= 0.0f;
1648         }
1649         /* catch exceptions: curve paths used as a duplicator */
1650         else if (enable_cu_speed) {
1651                 /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated,
1652                  * but this will only work if it actually is animated... 
1653                  *
1654                  * we divide the curvetime calculated in the previous step by the length of the path, to get a time
1655                  * factor, which then gets clamped to lie within 0.0 - 1.0 range
1656                  */
1657                 if (IS_EQF(cu->pathlen, 0.0f) == 0)
1658                         ctime= cu->ctime / cu->pathlen;
1659                 else
1660                         ctime= cu->ctime;
1661
1662                 CLAMP(ctime, 0.0f, 1.0f);
1663         }
1664         else {
1665                 ctime= scene->r.cfra;
1666                 if (IS_EQF(cu->pathlen, 0.0f) == 0)
1667                         ctime /= cu->pathlen;
1668                 
1669                 CLAMP(ctime, 0.0f, 1.0f);
1670         }
1671         
1672         /* time calculus is correct, now apply distance offset */
1673         if (cu->flag & CU_OFFS_PATHDIST) {
1674                 ctime += timeoffs/cu->path->totdist;
1675
1676                 /* restore */
1677                 SWAP(float, sf_orig, ob->sf);
1678         }
1679         
1680         
1681         /* vec: 4 items! */
1682         if ( where_on_path(par, ctime, vec, dir, cu->flag & CU_FOLLOW ? quat:NULL, &radius, NULL) ) {
1683
1684                 if (cu->flag & CU_FOLLOW) {
1685 #if 0
1686                         float x1, q[4];
1687                         vec_to_quat( quat,dir, ob->trackflag, ob->upflag);
1688                         
1689                         /* the tilt */
1690                         normalize_v3(dir);
1691                         q[0]= (float)cos(0.5*vec[3]);
1692                         x1= (float)sin(0.5*vec[3]);
1693                         q[1]= -x1*dir[0];
1694                         q[2]= -x1*dir[1];
1695                         q[3]= -x1*dir[2];
1696                         mul_qt_qtqt(quat, q, quat);
1697 #else
1698                         quat_apply_track(quat, ob->trackflag, ob->upflag);
1699 #endif
1700                         normalize_qt(quat);
1701                         quat_to_mat4(mat, quat);
1702                 }
1703                 
1704                 if (cu->flag & CU_PATH_RADIUS) {
1705                         float tmat[4][4], rmat[4][4];
1706                         scale_m4_fl(tmat, radius);
1707                         mult_m4_m4m4(rmat, tmat, mat);
1708                         copy_m4_m4(mat, rmat);
1709                 }
1710
1711                 copy_v3_v3(mat[3], vec);
1712                 
1713         }
1714 }
1715
1716 static void ob_parbone(Object *ob, Object *par, float mat[][4])
1717 {       
1718         bPoseChannel *pchan;
1719         float vec[3];
1720         
1721         if (par->type!=OB_ARMATURE) {
1722                 unit_m4(mat);
1723                 return;
1724         }
1725         
1726         /* Make sure the bone is still valid */
1727         pchan= get_pose_channel(par->pose, ob->parsubstr);
1728         if (!pchan) {
1729                 printf ("Object %s with Bone parent: bone %s doesn't exist\n", ob->id.name+2, ob->parsubstr);
1730                 unit_m4(mat);
1731                 return;
1732         }
1733
1734         /* get bone transform */
1735         copy_m4_m4(mat, pchan->pose_mat);
1736
1737         /* but for backwards compatibility, the child has to move to the tail */
1738         copy_v3_v3(vec, mat[1]);
1739         mul_v3_fl(vec, pchan->bone->length);
1740         add_v3_v3(mat[3], vec);
1741 }
1742
1743 static void give_parvert(Object *par, int nr, float vec[3])
1744 {
1745         BMEditMesh *em;
1746         int a, count;
1747         
1748         vec[0]=vec[1]=vec[2]= 0.0f;
1749         
1750         if (par->type==OB_MESH) {
1751                 Mesh *me= par->data;
1752                 DerivedMesh *dm;
1753
1754                 em = me->edit_btmesh;
1755
1756 #if 0   /* this was bmesh only, better, evaluate why this was needed - campbell*/
1757                 if (em) {
1758                         BMVert *eve;
1759                         BMIter iter;
1760
1761                         BM_ITER(eve, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
1762                                 int *keyindex = CustomData_bmesh_get(&em->bm->vdata, eve->head.data, CD_SHAPE_KEYINDEX);
1763                                 
1764                                 if (keyindex && *keyindex==nr) {
1765                                         copy_v3_v3(vec, eve->co);
1766                                         break;
1767                                 }
1768                         }
1769                 }
1770 #endif
1771
1772                 dm = (em)? em->derivedFinal: par->derivedFinal;
1773                         
1774                 if (dm) {
1775                         MVert *mvert= dm->getVertArray(dm);
1776                         int *index = (int *)dm->getVertDataArray(dm, CD_ORIGINDEX);
1777                         int i, vindex, numVerts = dm->getNumVerts(dm);
1778
1779                         /* get the average of all verts with (original index == nr) */
1780                         count= 0;
1781                         for (i = 0; i < numVerts; i++) {
1782                                 vindex= (index)? index[i]: i;
1783
1784                                 if (vindex == nr) {
1785                                         add_v3_v3(vec, mvert[i].co);
1786                                         count++;
1787                                 }
1788                         }
1789
1790                         if (count==0) {
1791                                 /* keep as 0,0,0 */
1792                         } else if (count > 0) {
1793                                 mul_v3_fl(vec, 1.0f / count);
1794                         } else {
1795                                 /* use first index if its out of range */
1796                                 dm->getVertCo(dm, 0, vec);
1797                         }
1798                 }
1799                 else fprintf(stderr, "%s: DerivedMesh is needed to solve parenting, object position can be wrong now\n", __func__);
1800         }
1801         else if (ELEM(par->type, OB_CURVE, OB_SURF)) {
1802                 Nurb *nu;
1803                 Curve *cu;
1804                 BPoint *bp;
1805                 BezTriple *bezt;
1806                 int found= 0;
1807                 ListBase *nurbs;
1808
1809                 cu= par->data;
1810                 nurbs= BKE_curve_nurbs(cu);
1811                 nu= nurbs->first;
1812
1813                 count= 0;
1814                 while (nu && !found) {
1815                         if (nu->type == CU_BEZIER) {
1816                                 bezt= nu->bezt;
1817                                 a= nu->pntsu;
1818                                 while (a--) {
1819                                         if (count==nr) {
1820                                                 found= 1;
1821                                                 copy_v3_v3(vec, bezt->vec[1]);
1822                                                 break;
1823                                         }
1824                                         count++;
1825                                         bezt++;
1826                                 }
1827                         }
1828                         else {
1829                                 bp= nu->bp;
1830                                 a= nu->pntsu*nu->pntsv;
1831                                 while (a--) {
1832                                         if (count==nr) {
1833                                                 found= 1;
1834                                                 memcpy(vec, bp->vec, sizeof(float)*3);
1835                                                 break;
1836                                         }
1837                                         count++;
1838                                         bp++;
1839                                 }
1840                         }
1841                         nu= nu->next;
1842                 }
1843
1844         }
1845         else if (par->type==OB_LATTICE) {
1846                 Lattice *latt= par->data;
1847                 BPoint *bp;
1848                 DispList *dl = find_displist(&par->disp, DL_VERTS);
1849                 float *co = dl?dl->verts:NULL;
1850                 
1851                 if (latt->editlatt) latt= latt->editlatt->latt;
1852                 
1853                 a= latt->pntsu*latt->pntsv*latt->pntsw;
1854                 count= 0;
1855                 bp= latt->def;
1856                 while (a--) {
1857                         if (count==nr) {
1858                                 if (co)
1859                                         memcpy(vec, co, 3*sizeof(float));
1860                                 else
1861                                         memcpy(vec, bp->vec, 3*sizeof(float));
1862                                 break;
1863                         }
1864                         count++;
1865                         if (co) co+= 3;
1866                         else bp++;
1867                 }
1868         }
1869 }
1870
1871 static void ob_parvert3(Object *ob, Object *par, float mat[][4])
1872 {
1873         float cmat[3][3], v1[3], v2[3], v3[3], q[4];
1874
1875         /* in local ob space */
1876         unit_m4(mat);
1877         
1878         if (ELEM4(par->type, OB_MESH, OB_SURF, OB_CURVE, OB_LATTICE)) {
1879                 
1880                 give_parvert(par, ob->par1, v1);
1881                 give_parvert(par, ob->par2, v2);
1882                 give_parvert(par, ob->par3, v3);
1883                                 
1884                 tri_to_quat( q,v1, v2, v3);
1885                 quat_to_mat3( cmat,q);
1886                 copy_m4_m3(mat, cmat);
1887                 
1888                 if (ob->type==OB_CURVE) {
1889                         copy_v3_v3(mat[3], v1);
1890                 }
1891                 else {
1892                         add_v3_v3v3(mat[3], v1, v2);
1893                         add_v3_v3(mat[3], v3);
1894                         mul_v3_fl(mat[3], 0.3333333f);
1895                 }
1896         }
1897 }
1898
1899 static int where_is_object_parslow(Object *ob, float obmat[4][4], float slowmat[4][4])
1900 {
1901         float *fp1, *fp2;
1902         float fac1, fac2;
1903         int a;
1904
1905         // include framerate
1906         fac1= ( 1.0f / (1.0f + fabsf(ob->sf)) );
1907         if (fac1 >= 1.0f) return 0;
1908         fac2= 1.0f-fac1;
1909
1910         fp1= obmat[0];
1911         fp2= slowmat[0];
1912         for (a=0; a<16; a++, fp1++, fp2++) {
1913                 fp1[0]= fac1*fp1[0] + fac2*fp2[0];
1914         }
1915
1916         return 1;
1917 }
1918
1919 void where_is_object_time(Scene *scene, Object *ob, float ctime)
1920 {
1921         float slowmat[4][4] = MAT4_UNITY;
1922         float stime=ctime;
1923         
1924         /* new version: correct parent+vertexparent and track+parent */
1925         /* this one only calculates direct attached parent and track */
1926         /* is faster, but should keep track of timeoffs */
1927         
1928         if (ob==NULL) return;
1929         
1930         /* execute drivers only, as animation has already been done */
1931         BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, ctime, ADT_RECALC_DRIVERS);
1932         
1933         if (ob->parent) {
1934                 Object *par= ob->parent;
1935                 
1936                 /* hurms, code below conflicts with depgraph... (ton) */
1937                 /* and even worse, it gives bad effects for NLA stride too (try ctime != par->ctime, with MBlur) */
1938                 if (stime != par->ctime) {
1939                         // only for ipo systems? 
1940                         Object tmp= *par;
1941                         
1942                         if (par->proxy_from);   // was a copied matrix, no where_is! bad...
1943                         else where_is_object_time(scene, par, ctime);
1944                         
1945                         solve_parenting(scene, ob, par, ob->obmat, slowmat, 0);
1946                         
1947                         *par= tmp;
1948                 }
1949                 else
1950                         solve_parenting(scene, ob, par, ob->obmat, slowmat, 0);
1951                 
1952                 /* "slow parent" is definitely not threadsafe, and may also give bad results jumping around 
1953                  * An old-fashioned hack which probably doesn't really cut it anymore
1954                  */
1955                 if (ob->partype & PARSLOW) {
1956                         if (!where_is_object_parslow(ob, ob->obmat, slowmat))
1957                                 return;
1958                 }
1959         }
1960         else {
1961                 object_to_mat4(ob, ob->obmat);
1962         }
1963
1964         /* solve constraints */
1965         if (ob->constraints.first && !(ob->transflag & OB_NO_CONSTRAINTS)) {
1966                 bConstraintOb *cob;
1967                 
1968                 cob= constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
1969                 
1970                 /* constraints need ctime, not stime. Some call where_is_object_time and bsystem_time */
1971                 solve_constraints (&ob->constraints, cob, ctime);
1972                 
1973                 constraints_clear_evalob(cob);
1974         }
1975         
1976         /* set negative scale flag in object */
1977         if (is_negative_m4(ob->obmat))  ob->transflag |= OB_NEG_SCALE;
1978         else                                                    ob->transflag &= ~OB_NEG_SCALE;
1979 }
1980
1981 /* get object transformation matrix without recalculating dependencies and
1982  * constraints -- assume dependencies are already solved by depsgraph.
1983  * no changes to object and it's parent would be done.
1984  * used for bundles orientation in 3d space relative to parented blender camera */
1985 void where_is_object_mat(Scene *scene, Object *ob, float obmat[4][4])
1986 {
1987         float slowmat[4][4] = MAT4_UNITY;
1988
1989         if (ob->parent) {
1990                 Object *par= ob->parent;
1991
1992                 solve_parenting(scene, ob, par, obmat, slowmat, 1);
1993
1994                 if (ob->partype & PARSLOW)
1995                         where_is_object_parslow(ob, obmat, slowmat);
1996         }
1997         else {
1998                 object_to_mat4(ob, obmat);
1999         }
2000 }
2001
2002 static void solve_parenting (Scene *scene, Object *ob, Object *par, float obmat[][4], float slowmat[][4], int simul)
2003 {
2004         float totmat[4][4];
2005         float tmat[4][4];
2006         float locmat[4][4];
2007         float vec[3];
2008         int ok;
2009         
2010         object_to_mat4(ob, locmat);
2011         
2012         if (ob->partype & PARSLOW) copy_m4_m4(slowmat, obmat);
2013
2014         switch(ob->partype & PARTYPE) {
2015         case PAROBJECT:
2016                 ok= 0;
2017                 if (par->type==OB_CURVE) {
2018                         if ( ((Curve *)par->data)->flag & CU_PATH ) {
2019                                 ob_parcurve(scene, ob, par, tmat);
2020                                 ok= 1;
2021                         }
2022                 }
2023                 
2024                 if (ok) mul_serie_m4(totmat, par->obmat, tmat, 
2025                         NULL, NULL, NULL, NULL, NULL, NULL);
2026                 else copy_m4_m4(totmat, par->obmat);
2027                 
2028                 break;
2029         case PARBONE:
2030                 ob_parbone(ob, par, tmat);
2031                 mul_serie_m4(totmat, par->obmat, tmat,         
2032                         NULL, NULL, NULL, NULL, NULL, NULL);
2033                 break;
2034                 
2035         case PARVERT1:
2036                 unit_m4(totmat);
2037                 if (simul) {
2038                         copy_v3_v3(totmat[3], par->obmat[3]);
2039                 }
2040                 else{
2041                         give_parvert(par, ob->par1, vec);
2042                         mul_v3_m4v3(totmat[3], par->obmat, vec);
2043                 }
2044                 break;
2045         case PARVERT3:
2046                 ob_parvert3(ob, par, tmat);
2047                 
2048                 mul_serie_m4(totmat, par->obmat, tmat,         
2049                         NULL, NULL, NULL, NULL, NULL, NULL);
2050                 break;
2051                 
2052         case PARSKEL:
2053                 copy_m4_m4(totmat, par->obmat);
2054                 break;
2055         }
2056         
2057         // total 
2058         mul_serie_m4(tmat, totmat, ob->parentinv,         
2059                 NULL, NULL, NULL, NULL, NULL, NULL);
2060         mul_serie_m4(obmat, tmat, locmat,         
2061                 NULL, NULL, NULL, NULL, NULL, NULL);
2062         
2063         if (simul) {
2064
2065         }
2066         else{
2067                 // external usable originmat 
2068                 copy_m3_m4(originmat, tmat);
2069                 
2070                 // origin, voor help line
2071                 if ( (ob->partype & PARTYPE)==PARSKEL ) {
2072                         copy_v3_v3(ob->orig, par->obmat[3]);
2073                 }
2074                 else {
2075                         copy_v3_v3(ob->orig, totmat[3]);
2076                 }
2077         }
2078
2079 }
2080
2081 void where_is_object(struct Scene *scene, Object *ob)
2082 {
2083         where_is_object_time(scene, ob, (float)scene->r.cfra);
2084 }
2085
2086
2087 void where_is_object_simul(Scene *scene, Object *ob)
2088 /* was written for the old game engine (until 2.04) */
2089 /* It seems that this function is only called
2090  * for a lamp that is the child of another object */
2091 {
2092         Object *par;
2093         float *fp1, *fp2;
2094         float slowmat[4][4];
2095         float fac1, fac2;
2096         int a;
2097         
2098         /* NO TIMEOFFS */
2099         if (ob->parent) {
2100                 par= ob->parent;
2101                 
2102                 solve_parenting(scene, ob, par, ob->obmat, slowmat, 1);
2103                 
2104                 if (ob->partype & PARSLOW) {
2105                         fac1= (float)(1.0/(1.0+ fabs(ob->sf)));
2106                         fac2= 1.0f-fac1;
2107                         fp1= ob->obmat[0];
2108                         fp2= slowmat[0];
2109                         for (a=0; a<16; a++, fp1++, fp2++) {
2110                                 fp1[0]= fac1*fp1[0] + fac2*fp2[0];
2111                         }
2112                 }
2113         }
2114         else {
2115                 object_to_mat4(ob, ob->obmat);
2116         }
2117         
2118         /* solve constraints */
2119         if (ob->constraints.first) {
2120                 bConstraintOb *cob;
2121                 
2122                 cob= constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2123                 solve_constraints(&ob->constraints, cob, (float)scene->r.cfra);
2124                 constraints_clear_evalob(cob);
2125         }
2126 }
2127
2128 /* for calculation of the inverse parent transform, only used for editor */
2129 void what_does_parent(Scene *scene, Object *ob, Object *workob)
2130 {
2131         clear_workob(workob);
2132         
2133         unit_m4(workob->obmat);
2134         unit_m4(workob->parentinv);
2135         unit_m4(workob->constinv);
2136         workob->parent= ob->parent;
2137
2138         workob->trackflag= ob->trackflag;
2139         workob->upflag= ob->upflag;
2140         
2141         workob->partype= ob->partype;
2142         workob->par1= ob->par1;
2143         workob->par2= ob->par2;
2144         workob->par3= ob->par3;
2145
2146         workob->constraints.first = ob->constraints.first;
2147         workob->constraints.last = ob->constraints.last;
2148
2149         BLI_strncpy(workob->parsubstr, ob->parsubstr, sizeof(workob->parsubstr));
2150
2151         where_is_object(scene, workob);
2152 }
2153
2154 BoundBox *unit_boundbox(void)
2155 {
2156         BoundBox *bb;
2157         float min[3] = {-1.0f,-1.0f,-1.0f}, max[3] = {-1.0f,-1.0f,-1.0f};
2158
2159         bb= MEM_callocN(sizeof(BoundBox), "OB-BoundBox");
2160         boundbox_set_from_min_max(bb, min, max);
2161         
2162         return bb;
2163 }
2164
2165 void boundbox_set_from_min_max(BoundBox *bb, float min[3], float max[3])
2166 {
2167         bb->vec[0][0]=bb->vec[1][0]=bb->vec[2][0]=bb->vec[3][0]= min[0];
2168         bb->vec[4][0]=bb->vec[5][0]=bb->vec[6][0]=bb->vec[7][0]= max[0];
2169         
2170         bb->vec[0][1]=bb->vec[1][1]=bb->vec[4][1]=bb->vec[5][1]= min[1];
2171         bb->vec[2][1]=bb->vec[3][1]=bb->vec[6][1]=bb->vec[7][1]= max[1];
2172
2173         bb->vec[0][2]=bb->vec[3][2]=bb->vec[4][2]=bb->vec[7][2]= min[2];
2174         bb->vec[1][2]=bb->vec[2][2]=bb->vec[5][2]=bb->vec[6][2]= max[2];
2175 }
2176
2177 BoundBox *object_get_boundbox(Object *ob)
2178 {
2179         BoundBox *bb= NULL;
2180         
2181         if (ob->type==OB_MESH) {
2182                 bb = mesh_get_bb(ob);
2183         }
2184         else if (ELEM3(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2185                 bb= ob->bb ? ob->bb : ( (Curve *)ob->data )->bb;
2186         }
2187         else if (ob->type==OB_MBALL) {
2188                 bb= ob->bb;
2189         }
2190         return bb;
2191 }
2192
2193 /* used to temporally disable/enable boundbox */
2194 void object_boundbox_flag(Object *ob, int flag, int set)
2195 {
2196         BoundBox *bb= object_get_boundbox(ob);
2197         if (bb) {
2198                 if (set) bb->flag |= flag;
2199                 else bb->flag &= ~flag;
2200         }
2201 }
2202
2203 void object_get_dimensions(Object *ob, float vec[3])
2204 {
2205         BoundBox *bb = NULL;
2206         
2207         bb= object_get_boundbox(ob);
2208         if (bb) {
2209                 float scale[3];
2210                 
2211                 mat4_to_size( scale,ob->obmat);
2212                 
2213                 vec[0] = fabsf(scale[0]) * (bb->vec[4][0] - bb->vec[0][0]);
2214                 vec[1] = fabsf(scale[1]) * (bb->vec[2][1] - bb->vec[0][1]);
2215                 vec[2] = fabsf(scale[2]) * (bb->vec[1][2] - bb->vec[0][2]);
2216         } else {
2217                 vec[0] = vec[1] = vec[2] = 0.f;
2218         }
2219 }
2220
2221 void object_set_dimensions(Object *ob, const float *value)
2222 {
2223         BoundBox *bb = NULL;
2224         
2225         bb= object_get_boundbox(ob);
2226         if (bb) {
2227                 float scale[3], len[3];
2228                 
2229                 mat4_to_size( scale,ob->obmat);
2230                 
2231                 len[0] = bb->vec[4][0] - bb->vec[0][0];
2232                 len[1] = bb->vec[2][1] - bb->vec[0][1];
2233                 len[2] = bb->vec[1][2] - bb->vec[0][2];
2234                 
2235                 if (len[0] > 0.f) ob->size[0] = value[0] / len[0];
2236                 if (len[1] > 0.f) ob->size[1] = value[1] / len[1];
2237                 if (len[2] > 0.f) ob->size[2] = value[2] / len[2];
2238         }
2239 }
2240
2241 void minmax_object(Object *ob, float min[3], float max[3])
2242 {
2243         BoundBox bb;
2244         float vec[3];
2245         int a;
2246         short change= FALSE;
2247         
2248         switch(ob->type) {
2249         case OB_CURVE:
2250         case OB_FONT:
2251         case OB_SURF:
2252                 {
2253                         Curve *cu= ob->data;
2254
2255                         if (cu->bb==NULL) tex_space_curve(cu);
2256                         bb= *(cu->bb);
2257
2258                         for (a=0; a<8; a++) {
2259                                 mul_m4_v3(ob->obmat, bb.vec[a]);
2260                                 DO_MINMAX(bb.vec[a], min, max);
2261                         }
2262                         change= TRUE;
2263                 }
2264                 break;
2265         case OB_LATTICE:
2266                 {
2267                         Lattice *lt= ob->data;
2268                         BPoint *bp= lt->def;
2269                         int u, v, w;
2270
2271                         for (w=0; w<lt->pntsw; w++) {
2272                                 for (v=0; v<lt->pntsv; v++) {
2273                                         for (u=0; u<lt->pntsu; u++, bp++) {
2274                                                 mul_v3_m4v3(vec, ob->obmat, bp->vec);
2275                                                 DO_MINMAX(vec, min, max);
2276                                         }
2277                                 }
2278                         }
2279                         change= TRUE;
2280                 }
2281                 break;
2282         case OB_ARMATURE:
2283                 if (ob->pose) {
2284                         bPoseChannel *pchan;
2285                         for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2286                                 mul_v3_m4v3(vec, ob->obmat, pchan->pose_head);
2287                                 DO_MINMAX(vec, min, max);
2288                                 mul_v3_m4v3(vec, ob->obmat, pchan->pose_tail);
2289                                 DO_MINMAX(vec, min, max);
2290                         }
2291                         change= TRUE;
2292                 }
2293                 break;
2294         case OB_MESH:
2295                 {
2296                         Mesh *me= get_mesh(ob);
2297
2298                         if (me) {
2299                                 bb = *mesh_get_bb(ob);
2300
2301                                 for (a=0; a<8; a++) {
2302                                         mul_m4_v3(ob->obmat, bb.vec[a]);
2303                                         DO_MINMAX(bb.vec[a], min, max);
2304                                 }
2305                                 change= TRUE;
2306                         }
2307                 }
2308                 break;
2309         }
2310
2311         if (change == FALSE) {
2312                 DO_MINMAX(ob->obmat[3], min, max);
2313
2314                 copy_v3_v3(vec, ob->obmat[3]);
2315                 add_v3_v3(vec, ob->size);
2316                 DO_MINMAX(vec, min, max);
2317
2318                 copy_v3_v3(vec, ob->obmat[3]);
2319                 sub_v3_v3(vec, ob->size);
2320                 DO_MINMAX(vec, min, max);
2321         }
2322 }
2323
2324 int minmax_object_duplis(Scene *scene, Object *ob, float min[3], float max[3])
2325 {
2326         int ok= 0;
2327         if ((ob->transflag & OB_DUPLI)==0) {
2328                 return ok;
2329         } else {
2330                 ListBase *lb;
2331                 DupliObject *dob;
2332                 
2333                 lb= object_duplilist(scene, ob);
2334                 for (dob= lb->first; dob; dob= dob->next) {
2335                         if (dob->no_draw == 0) {
2336                                 BoundBox *bb= object_get_boundbox(dob->ob);
2337
2338                                 if (bb) {
2339                                         int i;
2340                                         for (i=0; i<8; i++) {
2341                                                 float vec[3];
2342                                                 mul_v3_m4v3(vec, dob->mat, bb->vec[i]);
2343                                                 DO_MINMAX(vec, min, max);
2344                                         }
2345
2346                                         ok= 1;
2347                                 }
2348                         }
2349                 }
2350                 free_object_duplilist(lb);      /* does restore */
2351         }
2352
2353         return ok;
2354 }
2355
2356 void BKE_object_foreach_display_point(
2357         Object *ob, float obmat[4][4],
2358         void (*func_cb)(const float[3], void *), void *user_data)
2359 {
2360         float co[3];
2361
2362         if (ob->derivedFinal) {
2363                 DerivedMesh *dm= ob->derivedFinal;
2364                 MVert *mv= dm->getVertArray(dm);
2365                 int totvert= dm->getNumVerts(dm);
2366                 int i;
2367
2368                 for (i= 0; i < totvert; i++, mv++) {
2369                         mul_v3_m4v3(co, obmat, mv->co);
2370                         func_cb(co, user_data);
2371                 }
2372         }
2373         else if (ob->disp.first) {
2374                 DispList *dl;
2375
2376                 for (dl=ob->disp.first; dl; dl=dl->next) {
2377                         float *v3= dl->verts;
2378                         int totvert= dl->nr;
2379                         int i;
2380
2381                         for (i= 0; i < totvert; i++, v3+=3) {
2382                                 mul_v3_m4v3(co, obmat, v3);
2383                                 func_cb(co, user_data);
2384                         }
2385                 }
2386         }
2387 }
2388
2389 void BKE_scene_foreach_display_point(
2390         Scene *scene, View3D *v3d, const short flag,
2391         void (*func_cb)(const float[3], void *), void *user_data)
2392 {
2393         Base *base;
2394         Object *ob;
2395
2396         for (base= FIRSTBASE; base; base = base->next) {
2397                 if (BASE_VISIBLE(v3d, base) && (base->flag & flag) == flag) {
2398                         ob= base->object;
2399
2400                         if ((ob->transflag & OB_DUPLI)==0) {
2401                                 BKE_object_foreach_display_point(ob, ob->obmat, func_cb, user_data);
2402                         }
2403                         else {
2404                                 ListBase *lb;
2405                                 DupliObject *dob;
2406
2407                                 lb= object_duplilist(scene, ob);
2408                                 for (dob= lb->first; dob; dob= dob->next) {
2409                                         if (dob->no_draw == 0) {
2410                                                 BKE_object_foreach_display_point(dob->ob, dob->mat, func_cb, user_data);
2411                                         }
2412                                 }
2413                                 free_object_duplilist(lb);      /* does restore */
2414                         }
2415                 }
2416         }
2417 }
2418
2419 /* copied from DNA_object_types.h */
2420 typedef struct ObTfmBack {
2421         float loc[3], dloc[3], orig[3];
2422         float size[3], dscale[3];       /* scale and delta scale */
2423         float rot[3], drot[3];          /* euler rotation */
2424         float quat[4], dquat[4];        /* quaternion rotation */
2425         float rotAxis[3], drotAxis[3];  /* axis angle rotation - axis part */
2426         float rotAngle, drotAngle;      /* axis angle rotation - angle part */
2427         float obmat[4][4];              /* final worldspace matrix with constraints & animsys applied */
2428         float parentinv[4][4]; /* inverse result of parent, so that object doesn't 'stick' to parent */
2429         float constinv[4][4]; /* inverse result of constraints. doesn't include effect of parent or object local transform */
2430         float imat[4][4];       /* inverse matrix of 'obmat' for during render, old game engine, temporally: ipokeys of transform  */
2431 } ObTfmBack;
2432
2433 void *object_tfm_backup(Object *ob)
2434 {
2435         ObTfmBack *obtfm= MEM_mallocN(sizeof(ObTfmBack), "ObTfmBack");
2436         copy_v3_v3(obtfm->loc, ob->loc);
2437         copy_v3_v3(obtfm->dloc, ob->dloc);
2438         copy_v3_v3(obtfm->orig, ob->orig);
2439         copy_v3_v3(obtfm->size, ob->size);
2440         copy_v3_v3(obtfm->dscale, ob->dscale);
2441         copy_v3_v3(obtfm->rot, ob->rot);
2442         copy_v3_v3(obtfm->drot, ob->drot);
2443         copy_qt_qt(obtfm->quat, ob->quat);
2444         copy_qt_qt(obtfm->dquat, ob->dquat);
2445         copy_v3_v3(obtfm->rotAxis, ob->rotAxis);
2446         copy_v3_v3(obtfm->drotAxis, ob->drotAxis);
2447         obtfm->rotAngle= ob->rotAngle;
2448         obtfm->drotAngle= ob->drotAngle;
2449         copy_m4_m4(obtfm->obmat, ob->obmat);
2450         copy_m4_m4(obtfm->parentinv, ob->parentinv);
2451         copy_m4_m4(obtfm->constinv, ob->constinv);
2452         copy_m4_m4(obtfm->imat, ob->imat);
2453
2454         return (void *)obtfm;
2455 }
2456
2457 void object_tfm_restore(Object *ob, void *obtfm_pt)
2458 {
2459         ObTfmBack *obtfm= (ObTfmBack *)obtfm_pt;
2460         copy_v3_v3(ob->loc, obtfm->loc);
2461         copy_v3_v3(ob->dloc, obtfm->dloc);
2462         copy_v3_v3(ob->orig, obtfm->orig);
2463         copy_v3_v3(ob->size, obtfm->size);
2464         copy_v3_v3(ob->dscale, obtfm->dscale);
2465         copy_v3_v3(ob->rot, obtfm->rot);
2466         copy_v3_v3(ob->drot, obtfm->drot);
2467         copy_qt_qt(ob->quat, obtfm->quat);
2468         copy_qt_qt(ob->dquat, obtfm->dquat);
2469         copy_v3_v3(ob->rotAxis, obtfm->rotAxis);
2470         copy_v3_v3(ob->drotAxis, obtfm->drotAxis);
2471         ob->rotAngle= obtfm->rotAngle;
2472         ob->drotAngle= obtfm->drotAngle;
2473         copy_m4_m4(ob->obmat, obtfm->obmat);
2474         copy_m4_m4(ob->parentinv, obtfm->parentinv);
2475         copy_m4_m4(ob->constinv, obtfm->constinv);
2476         copy_m4_m4(ob->imat, obtfm->imat);
2477 }
2478
2479 int BKE_object_parent_loop_check(const Object *par, const Object *ob)
2480 {
2481         /* test if 'ob' is a parent somewhere in par's parents */
2482         if (par == NULL) return 0;
2483         if (ob == par) return 1;
2484         return BKE_object_parent_loop_check(par->parent, ob);
2485 }
2486
2487 /* proxy rule: lib_object->proxy_from == the one we borrow from, only set temporal and cleared here */
2488 /*           local_object->proxy      == pointer to library object, saved in files and read */
2489
2490 /* function below is polluted with proxy exceptions, cleanup will follow! */
2491
2492 /* the main object update call, for object matrix, constraints, keys and displist (modifiers) */
2493 /* requires flags to be set! */
2494 void object_handle_update(Scene *scene, Object *ob)
2495 {
2496         if (ob->recalc & OB_RECALC_ALL) {
2497                 /* speed optimization for animation lookups */
2498                 if (ob->pose)
2499                         make_pose_channels_hash(ob->pose);
2500
2501                 if (ob->recalc & OB_RECALC_DATA) {
2502                         if (ob->type==OB_ARMATURE) {
2503                                 /* this happens for reading old files and to match library armatures
2504                                  * with poses we do it ahead of where_is_object to ensure animation
2505                                  * is evaluated on the rebuilt pose, otherwise we get incorrect poses
2506                                  * on file load */
2507                                 if (ob->pose==NULL || (ob->pose->flag & POSE_RECALC))
2508                                         armature_rebuild_pose(ob, ob->data);
2509                         }
2510                 }
2511
2512                 /* XXX new animsys warning: depsgraph tag OB_RECALC_DATA should not skip drivers, 
2513                  * which is only in where_is_object now */
2514                 // XXX: should this case be OB_RECALC_OB instead?
2515                 if (ob->recalc & OB_RECALC_ALL) {
2516                         
2517                         if (G.f & G_DEBUG)
2518                                 printf("recalcob %s\n", ob->id.name+2);
2519                         
2520                         /* handle proxy copy for target */
2521                         if (ob->id.lib && ob->proxy_from) {
2522                                 // printf("ob proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2523                                 if (ob->proxy_from->proxy_group) {/* transform proxy into group space */
2524                                         Object *obg= ob->proxy_from->proxy_group;
2525                                         invert_m4_m4(obg->imat, obg->obmat);
2526                                         mult_m4_m4m4(ob->obmat, obg->imat, ob->proxy_from->obmat);
2527                                         if (obg->dup_group) { /* should always be true */
2528                                                 add_v3_v3(ob->obmat[3], obg->dup_group->dupli_ofs);
2529                                         }
2530                                 }
2531                                 else
2532                                         copy_m4_m4(ob->obmat, ob->proxy_from->obmat);
2533                         }
2534                         else
2535                                 where_is_object(scene, ob);
2536                 }
2537                 
2538                 if (ob->recalc & OB_RECALC_DATA) {
2539                         ID *data_id= (ID *)ob->data;
2540                         AnimData *adt= BKE_animdata_from_id(data_id);
2541                         float ctime= (float)scene->r.cfra; // XXX this is bad...
2542                         ListBase pidlist;
2543                         PTCacheID *pid;
2544                         
2545                         if (G.f & G_DEBUG)
2546                                 printf("recalcdata %s\n", ob->id.name+2);
2547
2548                         if (adt) {
2549                                 /* evaluate drivers */
2550                                 // XXX: for mesh types, should we push this to derivedmesh instead?
2551                                 BKE_animsys_evaluate_animdata(scene, data_id, adt, ctime, ADT_RECALC_DRIVERS);
2552                         }
2553
2554                         /* includes all keys and modifiers */
2555                         switch(ob->type) {
2556                         case OB_MESH:
2557                                 {
2558 #if 0                           // XXX, comment for 2.56a release, background wont set 'scene->customdata_mask'
2559                                         BMEditMesh *em = (ob == scene->obedit) ? BMEdit_FromObject(ob) : NULL;
2560                                         BLI_assert((scene->customdata_mask & CD_MASK_BAREMESH) == CD_MASK_BAREMESH);
2561                                         if (em) {
2562                                                 makeDerivedMesh(scene, ob, em,  scene->customdata_mask, 0); /* was CD_MASK_BAREMESH */
2563                                         }
2564                                         else {
2565                                                 makeDerivedMesh(scene, ob, NULL, scene->customdata_mask, 0);
2566                                         }
2567
2568 #else                           /* ensure CD_MASK_BAREMESH for now */
2569                                         BMEditMesh *em = (ob == scene->obedit) ? BMEdit_FromObject(ob) : NULL;
2570                                         uint64_t data_mask= scene->customdata_mask | ob->customdata_mask | CD_MASK_BAREMESH;
2571                                         if (em) {
2572                                                 makeDerivedMesh(scene, ob, em,  data_mask, 0); /* was CD_MASK_BAREMESH */
2573                                         }
2574                                         else {
2575                                                 makeDerivedMesh(scene, ob, NULL, data_mask, 0);
2576                                         }
2577 #endif
2578
2579                                 }
2580                                 break;
2581
2582                         case OB_ARMATURE:
2583                                 if (ob->id.lib && ob->proxy_from) {
2584                                         // printf("pose proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2585                                         copy_pose_result(ob->pose, ob->proxy_from->pose);
2586                                 }
2587                                 else {
2588                                         where_is_pose(scene, ob);
2589                                 }
2590                                 break;
2591
2592                         case OB_MBALL:
2593                                 makeDispListMBall(scene, ob);
2594                                 break;
2595
2596                         case OB_CURVE:
2597                         case OB_SURF:
2598                         case OB_FONT:
2599                                 makeDispListCurveTypes(scene, ob, 0);
2600                                 break;
2601                                 
2602                         case OB_LATTICE:
2603                                 lattice_calc_modifiers(scene, ob);
2604                                 break;
2605                         }
2606
2607
2608                         if (ob->particlesystem.first) {
2609                                 ParticleSystem *tpsys, *psys;
2610                                 DerivedMesh *dm;
2611                                 ob->transflag &= ~OB_DUPLIPARTS;
2612                                 
2613                                 psys= ob->particlesystem.first;
2614                                 while (psys) {
2615                                         if (psys_check_enabled(ob, psys)) {
2616                                                 /* check use of dupli objects here */
2617                                                 if (psys->part && (psys->part->draw_as == PART_DRAW_REND || G.rendering) &&
2618                                                         ((psys->part->ren_as == PART_DRAW_OB && psys->part->dup_ob)
2619                                                         || (psys->part->ren_as == PART_DRAW_GR && psys->part->dup_group)))
2620                                                         ob->transflag |= OB_DUPLIPARTS;
2621
2622                                                 particle_system_update(scene, ob, psys);
2623                                                 psys= psys->next;
2624                                         }
2625                                         else if (psys->flag & PSYS_DELETE) {
2626                                                 tpsys=psys->next;
2627                                                 BLI_remlink(&ob->particlesystem, psys);
2628                                                 psys_free(ob,psys);
2629                                                 psys= tpsys;
2630                                         }
2631                                         else
2632                                                 psys= psys->next;
2633                                 }
2634
2635                                 if (G.rendering && ob->transflag & OB_DUPLIPARTS) {
2636                                         /* this is to make sure we get render level duplis in groups:
2637                                          * the derivedmesh must be created before init_render_mesh,
2638                                          * since object_duplilist does dupliparticles before that */
2639                                         dm = mesh_create_derived_render(scene, ob, CD_MASK_BAREMESH|CD_MASK_MTFACE|CD_MASK_MCOL);
2640                                         dm->release(dm);
2641
2642                                         for (psys=ob->particlesystem.first; psys; psys=psys->next)
2643                                                 psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated;
2644                                 }
2645                         }
2646
2647                         /* check if quick cache is needed */
2648                         BKE_ptcache_ids_from_object(&pidlist, ob, scene, MAX_DUPLI_RECUR);
2649
2650                         for (pid=pidlist.first; pid; pid=pid->next) {
2651                                 if ((pid->cache->flag & PTCACHE_BAKED)
2652                                         || (pid->cache->flag & PTCACHE_QUICK_CACHE)==0)
2653                                         continue;
2654
2655                                 if (pid->cache->flag & PTCACHE_OUTDATED || (pid->cache->flag & PTCACHE_SIMULATION_VALID)==0) {
2656                                         scene->physics_settings.quick_cache_step =
2657                                                 scene->physics_settings.quick_cache_step ?
2658                                                 MIN2(scene->physics_settings.quick_cache_step, pid->cache->step) :
2659                                                 pid->cache->step;
2660                                 }
2661                         }
2662
2663                         BLI_freelistN(&pidlist);
2664                 }
2665
2666                 /* the no-group proxy case, we call update */
2667                 if (ob->proxy && ob->proxy_group==NULL) {
2668                         /* set pointer in library proxy target, for copying, but restore it */
2669                         ob->proxy->proxy_from= ob;
2670                         // printf("call update, lib ob %s proxy %s\n", ob->proxy->id.name, ob->id.name);
2671                         object_handle_update(scene, ob->proxy);
2672                 }
2673         
2674                 ob->recalc &= ~OB_RECALC_ALL;
2675         }
2676
2677         /* the case when this is a group proxy, object_update is called in group.c */
2678         if (ob->proxy) {
2679                 ob->proxy->proxy_from= ob;
2680                 // printf("set proxy pointer for later group stuff %s\n", ob->id.name);
2681         }
2682 }
2683
2684 void object_sculpt_modifiers_changed(Object *ob)
2685 {
2686         SculptSession *ss= ob->sculpt;
2687
2688         if (!ss->cache) {
2689                 /* we free pbvh on changes, except during sculpt since it can't deal with
2690                  * changing PVBH node organization, we hope topology does not change in
2691                  * the meantime .. weak */
2692                 if (ss->pbvh) {
2693                                 BLI_pbvh_free(ss->pbvh);
2694                                 ss->pbvh= NULL;
2695                 }
2696
2697                 free_sculptsession_deformMats(ob->sculpt);
2698         } else {
2699                 PBVHNode **nodes;
2700                 int n, totnode;
2701
2702                 BLI_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode);
2703
2704                 for (n = 0; n < totnode; n++)
2705                         BLI_pbvh_node_mark_update(nodes[n]);
2706
2707                 MEM_freeN(nodes);
2708         }
2709 }
2710
2711 int give_obdata_texspace(Object *ob, short **texflag, float **loc, float **size, float **rot)
2712 {
2713         
2714         if (ob->data==NULL)
2715                 return 0;
2716         
2717         switch (GS(((ID *)ob->data)->name)) {
2718         case ID_ME:
2719         {
2720                 Mesh *me= ob->data;
2721                 if (texflag)    *texflag = &me->texflag;
2722                 if (loc)                *loc = me->loc;
2723                 if (size)               *size = me->size;
2724                 if (rot)                *rot = me->rot;
2725                 break;
2726         }
2727         case ID_CU:
2728         {
2729                 Curve *cu= ob->data;
2730                 if (texflag)    *texflag = &cu->texflag;
2731                 if (loc)                *loc = cu->loc;
2732                 if (size)               *size = cu->size;
2733                 if (rot)                *rot = cu->rot;
2734                 break;
2735         }
2736         case ID_MB:
2737         {
2738                 MetaBall *mb= ob->data;
2739                 if (texflag)    *texflag = &mb->texflag;
2740                 if (loc)                *loc = mb->loc;
2741                 if (size)               *size = mb->size;
2742                 if (rot)                *rot = mb->rot;
2743                 break;
2744         }
2745         default:
2746                 return 0;
2747         }
2748         return 1;
2749 }
2750
2751 /*
2752  * Test a bounding box for ray intersection
2753  * assumes the ray is already local to the boundbox space
2754  */
2755 int ray_hit_boundbox(struct BoundBox *bb, float ray_start[3], float ray_normal[3])
2756 {
2757         static int triangle_indexes[12][3] = {{0, 1, 2}, {0, 2, 3},
2758                                                                                   {3, 2, 6}, {3, 6, 7},
2759                                                                                   {1, 2, 6}, {1, 6, 5}, 
2760                                                                                   {5, 6, 7}, {4, 5, 7},
2761                                                                                   {0, 3, 7}, {0, 4, 7},
2762                                                                                   {0, 1, 5}, {0, 4, 5}};
2763         int result = 0;
2764         int i;
2765         
2766         for (i = 0; i < 12 && result == 0; i++)
2767         {
2768                 float lambda;
2769                 int v1, v2, v3;
2770                 v1 = triangle_indexes[i][0];
2771                 v2 = triangle_indexes[i][1];
2772                 v3 = triangle_indexes[i][2];
2773                 result = isect_ray_tri_v3(ray_start, ray_normal, bb->vec[v1], bb->vec[v2], bb->vec[v3], &lambda, NULL);
2774         }
2775         
2776         return result;
2777 }
2778
2779 static int pc_cmp(void *a, void *b)
2780 {
2781         LinkData *ad = a, *bd = b;
2782         if (GET_INT_FROM_POINTER(ad->data) > GET_INT_FROM_POINTER(bd->data))
2783                 return 1;
2784         else return 0;
2785 }
2786
2787 int object_insert_ptcache(Object *ob) 
2788 {
2789         LinkData *link = NULL;
2790         int i = 0;
2791
2792         BLI_sortlist(&ob->pc_ids, pc_cmp);
2793
2794         for (link=ob->pc_ids.first, i = 0; link; link=link->next, i++) 
2795         {
2796                 int index = GET_INT_FROM_POINTER(link->data);
2797
2798                 if (i < index)
2799                         break;
2800         }
2801
2802         link = MEM_callocN(sizeof(LinkData), "PCLink");
2803         link->data = SET_INT_IN_POINTER(i);
2804         BLI_addtail(&ob->pc_ids, link);
2805
2806         return i;
2807 }
2808
2809 #if 0
2810 static int pc_findindex(ListBase *listbase, int index)
2811 {
2812         LinkData *link= NULL;
2813         int number= 0;
2814         
2815         if (listbase == NULL) return -1;
2816         
2817         link= listbase->first;
2818         while (link) {
2819                 if ((int)link->data == index)
2820                         return number;
2821                 
2822                 number++;
2823                 link= link->next;
2824         }
2825         
2826         return -1;
2827 }
2828
2829 void object_delete_ptcache(Object *ob, int index) 
2830 {
2831         int list_index = pc_findindex(&ob->pc_ids, index);
2832         LinkData *link = BLI_findlink(&ob->pc_ids, list_index);
2833         BLI_freelinkN(&ob->pc_ids, link);
2834 }
2835 #endif
2836
2837 /* shape key utility function */
2838
2839 /************************* Mesh ************************/
2840 static KeyBlock *insert_meshkey(Scene *scene, Object *ob, const char *name, int from_mix)
2841 {
2842         Mesh *me= ob->data;
2843         Key *key= me->key;
2844         KeyBlock *kb;
2845         int newkey= 0;
2846
2847         if (key == NULL) {
2848                 key= me->key= add_key((ID *)me);
2849                 key->type= KEY_RELATIVE;
2850                 newkey= 1;
2851         }
2852
2853         if (newkey || from_mix==FALSE) {
2854                 /* create from mesh */
2855                 kb= add_keyblock(key, name);
2856                 mesh_to_key(me, kb);
2857         }
2858         else {
2859                 /* copy from current values */
2860                 float *data= do_ob_key(scene, ob);
2861
2862                 /* create new block with prepared data */
2863                 kb= add_keyblock(key, name);
2864                 kb->data= data;
2865                 kb->totelem= me->totvert;
2866         }
2867
2868         return kb;
2869 }
2870 /************************* Lattice ************************/
2871 static KeyBlock *insert_lattkey(Scene *scene, Object *ob, const char *name, int from_mix)
2872 {
2873         Lattice *lt= ob->data;
2874         Key *key= lt->key;
2875         KeyBlock *kb;
2876         int newkey= 0;
2877
2878         if (key==NULL) {
2879                 key= lt->key= add_key( (ID *)lt);
2880                 key->type= KEY_RELATIVE;
2881                 newkey= 1;
2882         }
2883
2884         if (newkey || from_mix==FALSE) {
2885                 kb= add_keyblock(key, name);
2886                 if (!newkey) {
2887                         KeyBlock *basekb= (KeyBlock *)key->block.first;
2888                         kb->data= MEM_dupallocN(basekb->data);
2889                         kb->totelem= basekb->totelem;
2890                 }
2891                 else {
2892                         latt_to_key(lt, kb);
2893                 }
2894         }
2895         else {
2896                 /* copy from current values */
2897                 float *data= do_ob_key(scene, ob);
2898
2899                 /* create new block with prepared data */
2900                 kb= add_keyblock(key, name);
2901                 kb->totelem= lt->pntsu*lt->pntsv*lt->pntsw;
2902                 kb->data= data;
2903         }
2904
2905         return kb;
2906 }
2907 /************************* Curve ************************/
2908 static KeyBlock *insert_curvekey(Scene *scene, Object *ob, const char *name, int from_mix)
2909 {
2910         Curve *cu= ob->data;
2911         Key *key= cu->key;
2912         KeyBlock *kb;
2913         ListBase *lb= BKE_curve_nurbs(cu);
2914         int newkey= 0;
2915
2916         if (key==NULL) {
2917                 key= cu->key= add_key( (ID *)cu);
2918                 key->type = KEY_RELATIVE;
2919                 newkey= 1;
2920         }
2921
2922         if (newkey || from_mix==FALSE) {
2923                 /* create from curve */
2924                 kb= add_keyblock(key, name);
2925                 if (!newkey) {
2926                         KeyBlock *basekb= (KeyBlock *)key->block.first;
2927                         kb->data= MEM_dupallocN(basekb->data);
2928                         kb->totelem= basekb->totelem;
2929                 }
2930                 else {
2931                         curve_to_key(cu, kb, lb);
2932                 }
2933         }
2934         else {
2935                 /* copy from current values */
2936                 float *data= do_ob_key(scene, ob);
2937
2938                 /* create new block with prepared data */
2939                 kb= add_keyblock(key, name);
2940                 kb->totelem= count_curveverts(lb);
2941                 kb->data= data;
2942         }
2943
2944         return kb;
2945 }
2946
2947 KeyBlock *object_insert_shape_key(Scene *scene, Object *ob, const char *name, int from_mix)
2948 {
2949         if (ob->type==OB_MESH)                                   return insert_meshkey(scene, ob, name, from_mix);
2950         else if ELEM(ob->type, OB_CURVE, OB_SURF)return insert_curvekey(scene, ob, name, from_mix);
2951         else if (ob->type==OB_LATTICE)                   return insert_lattkey(scene, ob, name, from_mix);
2952         else                                                                     return NULL;
2953 }
2954
2955 /* most important if this is modified it should _always_ return True, in certain
2956  * cases false positives are hard to avoid (shape keys for eg)
2957  */
2958 int object_is_modified(Scene *scene, Object *ob)
2959 {
2960         int flag= 0;
2961
2962         if (ob_get_key(ob)) {
2963                 flag |= eModifierMode_Render;
2964         }
2965         else {
2966                 ModifierData *md;
2967                 /* cloth */
2968                 for (md=modifiers_getVirtualModifierList(ob);
2969                      md && (flag != (eModifierMode_Render | eModifierMode_Realtime));
2970                      md=md->next)
2971                 {
2972                         if ((flag & eModifierMode_Render) == 0  && modifier_isEnabled(scene, md, eModifierMode_Render)) {
2973                                 flag |= eModifierMode_Render;
2974                         }
2975
2976                         if ((flag & eModifierMode_Realtime) == 0        && modifier_isEnabled(scene, md, eModifierMode_Realtime)) {
2977                                 flag |= eModifierMode_Realtime;
2978                         }
2979                 }
2980         }
2981
2982         return flag;
2983 }
2984
2985 static void copy_object__forwardModifierLinks(void *UNUSED(userData), Object *UNUSED(ob), ID **idpoin)
2986 {
2987         /* this is copied from ID_NEW; it might be better to have a macro */
2988         if (*idpoin && (*idpoin)->newid) *idpoin = (*idpoin)->newid;
2989 }
2990
2991 void object_relink(Object *ob)
2992 {
2993         if (ob->id.lib)
2994                 return;
2995
2996         relink_constraints(&ob->constraints);
2997         if (ob->pose) {
2998                 bPoseChannel *chan;
2999                 for (chan = ob->pose->chanbase.first; chan; chan=chan->next) {
3000                         relink_constraints(&chan->constraints);
3001                 }
3002         }
3003         modifiers_foreachIDLink(ob, copy_object__forwardModifierLinks, NULL);
3004
3005         if (ob->adt)
3006                 BKE_relink_animdata(ob->adt);
3007
3008         ID_NEW(ob->parent);
3009
3010         ID_NEW(ob->proxy);
3011         ID_NEW(ob->proxy_group);
3012 }
3013
3014 MovieClip *object_get_movieclip(Scene *scene, Object *ob, int use_default)
3015 {
3016         MovieClip *clip= use_default ? scene->clip : NULL;
3017         bConstraint *con= ob->constraints.first, *scon= NULL;
3018
3019         while (con) {
3020                 if (con->type==CONSTRAINT_TYPE_CAMERASOLVER) {
3021                         if (scon==NULL || (scon->flag&CONSTRAINT_OFF))
3022                                 scon= con;
3023                 }
3024
3025                 con= con->next;
3026         }
3027
3028         if (scon) {
3029                 bCameraSolverConstraint *solver= scon->data;
3030                 if ((solver->flag&CAMERASOLVER_ACTIVECLIP)==0)
3031                         clip= solver->clip;
3032                 else
3033                         clip= scene->clip;
3034         }
3035
3036         return clip;
3037 }