b919b9ffd8fcd4cf36d97b5c8467e353b0dcee4f
[blender.git] / source / blender / blenkernel / intern / depsgraph.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) 2004 Blender Foundation.
19  * All rights reserved.
20  *
21  * Contributor(s): none yet.
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/blenkernel/intern/depsgraph.c
27  *  \ingroup bke
28  */
29
30  
31 #include <stdio.h>
32 #include <string.h>
33 #include <math.h>
34
35 #include "MEM_guardedalloc.h"
36
37 #ifdef WIN32
38 #  include "BLI_winstuff.h"
39 #endif
40
41 #include "BLI_utildefines.h"
42 #include "BLI_listbase.h"
43 #include "BLI_ghash.h"
44
45 #include "DNA_anim_types.h"
46 #include "DNA_camera_types.h"
47 #include "DNA_group_types.h"
48 #include "DNA_lamp_types.h"
49 #include "DNA_lattice_types.h"
50 #include "DNA_key_types.h"
51 #include "DNA_material_types.h"
52 #include "DNA_mesh_types.h"
53 #include "DNA_node_types.h"
54 #include "DNA_scene_types.h"
55 #include "DNA_screen_types.h"
56 #include "DNA_windowmanager_types.h"
57 #include "DNA_movieclip_types.h"
58 #include "DNA_mask_types.h"
59
60 #include "BKE_animsys.h"
61 #include "BKE_action.h"
62 #include "BKE_effect.h"
63 #include "BKE_fcurve.h"
64 #include "BKE_global.h"
65 #include "BKE_group.h"
66 #include "BKE_key.h"
67 #include "BKE_library.h"
68 #include "BKE_main.h"
69 #include "BKE_node.h"
70 #include "BKE_material.h"
71 #include "BKE_mball.h"
72 #include "BKE_modifier.h"
73 #include "BKE_object.h"
74 #include "BKE_particle.h"
75 #include "BKE_pointcache.h"
76 #include "BKE_scene.h"
77 #include "BKE_screen.h"
78 #include "BKE_tracking.h"
79
80 #include "depsgraph_private.h"
81  
82 /* Queue and stack operations for dag traversal 
83  *
84  * the queue store a list of freenodes to avoid successive alloc/dealloc
85  */
86
87 DagNodeQueue *queue_create(int slots)
88 {
89         DagNodeQueue *queue;
90         DagNodeQueueElem *elem;
91         int i;
92         
93         queue = MEM_mallocN(sizeof(DagNodeQueue), "DAG queue");
94         queue->freenodes = MEM_mallocN(sizeof(DagNodeQueue), "DAG queue");
95         queue->count = 0;
96         queue->maxlevel = 0;
97         queue->first = queue->last = NULL;
98         elem = MEM_mallocN(sizeof(DagNodeQueueElem), "DAG queue elem3");
99         elem->node = NULL;
100         elem->next = NULL;
101         queue->freenodes->first = queue->freenodes->last = elem;
102         
103         for (i = 1; i < slots; i++) {
104                 elem = MEM_mallocN(sizeof(DagNodeQueueElem), "DAG queue elem4");
105                 elem->node = NULL;
106                 elem->next = NULL;
107                 queue->freenodes->last->next = elem;
108                 queue->freenodes->last = elem;
109         }
110         queue->freenodes->count = slots;
111         return queue;
112 }
113
114 void queue_raz(DagNodeQueue *queue)
115 {
116         DagNodeQueueElem *elem;
117         
118         elem = queue->first;
119         if (queue->freenodes->last)
120                 queue->freenodes->last->next = elem;
121         else
122                 queue->freenodes->first = queue->freenodes->last = elem;
123         
124         elem->node = NULL;
125         queue->freenodes->count++;
126         while (elem->next) {
127                 elem = elem->next;
128                 elem->node = NULL;
129                 queue->freenodes->count++;
130         }
131         queue->freenodes->last = elem;
132         queue->count = 0;
133 }
134
135 void queue_delete(DagNodeQueue *queue)
136 {
137         DagNodeQueueElem *elem;
138         DagNodeQueueElem *temp;
139         
140         elem = queue->first;
141         while (elem) {
142                 temp = elem;
143                 elem = elem->next;
144                 MEM_freeN(temp);
145         }
146         
147         elem = queue->freenodes->first;
148         while (elem) {
149                 temp = elem;
150                 elem = elem->next;
151                 MEM_freeN(temp);
152         }
153         
154         MEM_freeN(queue->freenodes);
155         MEM_freeN(queue);
156 }
157
158 /* insert in queue, remove in front */
159 void push_queue(DagNodeQueue *queue, DagNode *node)
160 {
161         DagNodeQueueElem *elem;
162         int i;
163
164         if (node == NULL) {
165                 fprintf(stderr, "pushing null node\n");
166                 return;
167         }
168         /*fprintf(stderr, "BFS push : %s %d\n", ((ID *) node->ob)->name, queue->count);*/
169
170         elem = queue->freenodes->first;
171         if (elem != NULL) {
172                 queue->freenodes->first = elem->next;
173                 if (queue->freenodes->last == elem) {
174                         queue->freenodes->last = NULL;
175                         queue->freenodes->first = NULL;
176                 }
177                 queue->freenodes->count--;
178         }
179         else { /* alllocating more */
180                 elem = MEM_mallocN(sizeof(DagNodeQueueElem), "DAG queue elem1");
181                 elem->node = NULL;
182                 elem->next = NULL;
183                 queue->freenodes->first = queue->freenodes->last = elem;
184
185                 for (i = 1; i < DAGQUEUEALLOC; i++) {
186                         elem = MEM_mallocN(sizeof(DagNodeQueueElem), "DAG queue elem2");
187                         elem->node = NULL;
188                         elem->next = NULL;
189                         queue->freenodes->last->next = elem;
190                         queue->freenodes->last = elem;
191                 }
192                 queue->freenodes->count = DAGQUEUEALLOC;
193                         
194                 elem = queue->freenodes->first;
195                 queue->freenodes->first = elem->next;
196         }
197         elem->next = NULL;
198         elem->node = node;
199         if (queue->last != NULL)
200                 queue->last->next = elem;
201         queue->last = elem;
202         if (queue->first == NULL) {
203                 queue->first = elem;
204         }
205         queue->count++;
206 }
207
208
209 /* insert in front, remove in front */
210 void push_stack(DagNodeQueue *queue, DagNode *node)
211 {
212         DagNodeQueueElem *elem;
213         int i;
214
215         elem = queue->freenodes->first;
216         if (elem != NULL) {
217                 queue->freenodes->first = elem->next;
218                 if (queue->freenodes->last == elem) {
219                         queue->freenodes->last = NULL;
220                         queue->freenodes->first = NULL;
221                 }
222                 queue->freenodes->count--;
223         }
224         else { /* alllocating more */
225                 elem = MEM_mallocN(sizeof(DagNodeQueueElem), "DAG queue elem1");
226                 elem->node = NULL;
227                 elem->next = NULL;
228                 queue->freenodes->first = queue->freenodes->last = elem;
229
230                 for (i = 1; i < DAGQUEUEALLOC; i++) {
231                         elem = MEM_mallocN(sizeof(DagNodeQueueElem), "DAG queue elem2");
232                         elem->node = NULL;
233                         elem->next = NULL;
234                         queue->freenodes->last->next = elem;
235                         queue->freenodes->last = elem;
236                 }
237                 queue->freenodes->count = DAGQUEUEALLOC;
238                         
239                 elem = queue->freenodes->first;
240                 queue->freenodes->first = elem->next;
241         }
242         elem->next = queue->first;
243         elem->node = node;
244         queue->first = elem;
245         if (queue->last == NULL)
246                 queue->last = elem;
247         queue->count++;
248 }
249
250
251 DagNode *pop_queue(DagNodeQueue *queue)
252 {
253         DagNodeQueueElem *elem;
254         DagNode *node;
255
256         elem = queue->first;
257         if (elem) {
258                 queue->first = elem->next;
259                 if (queue->last == elem) {
260                         queue->last = NULL;
261                         queue->first = NULL;
262                 }
263                 queue->count--;
264                 if (queue->freenodes->last)
265                         queue->freenodes->last->next = elem;
266                 queue->freenodes->last = elem;
267                 if (queue->freenodes->first == NULL)
268                         queue->freenodes->first = elem;
269                 node = elem->node;
270                 elem->node = NULL;
271                 elem->next = NULL;
272                 queue->freenodes->count++;
273                 return node;
274         }
275         else {
276                 fprintf(stderr, "return null\n");
277                 return NULL;
278         }
279 }
280
281 DagNode *get_top_node_queue(DagNodeQueue *queue)
282 {
283         return queue->first->node;
284 }
285
286 DagForest *dag_init(void)
287 {
288         DagForest *forest;
289         /* use callocN to init all zero */
290         forest = MEM_callocN(sizeof(DagForest), "DAG root");
291         return forest;
292 }
293
294 /* isdata = object data... */
295 /* XXX this needs to be extended to be more flexible (so that not only objects are evaluated via depsgraph)... */
296 static void dag_add_driver_relation(AnimData *adt, DagForest *dag, DagNode *node, int isdata)
297 {
298         FCurve *fcu;
299         DagNode *node1;
300         
301         for (fcu = adt->drivers.first; fcu; fcu = fcu->next) {
302                 ChannelDriver *driver = fcu->driver;
303                 DriverVar *dvar;
304                 int isdata_fcu = (isdata) || (fcu->rna_path && strstr(fcu->rna_path, "modifiers["));
305                 
306                 /* loop over variables to get the target relationships */
307                 for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
308                         /* only used targets */
309                         DRIVER_TARGETS_USED_LOOPER(dvar) 
310                         {
311                                 if (dtar->id) {
312                                         /* FIXME: other data types need to be added here so that they can work! */
313                                         if (GS(dtar->id->name) == ID_OB) {
314                                                 Object *ob = (Object *)dtar->id;
315                                                 
316                                                 /* normal channel-drives-channel */
317                                                 node1 = dag_get_node(dag, dtar->id);
318                                                 
319                                                 /* check if bone... */
320                                                 if ((ob->type == OB_ARMATURE) &&
321                                                     ( ((dtar->rna_path) && strstr(dtar->rna_path, "pose.bones[")) ||
322                                                       ((dtar->flag & DTAR_FLAG_STRUCT_REF) && (dtar->pchan_name[0])) ))
323                                                 {
324                                                         dag_add_relation(dag, node1, node, isdata_fcu ? DAG_RL_DATA_DATA : DAG_RL_DATA_OB, "Driver");
325                                                 }
326                                                 /* check if ob data */
327                                                 else if (dtar->rna_path && strstr(dtar->rna_path, "data."))
328                                                         dag_add_relation(dag, node1, node, isdata_fcu ? DAG_RL_DATA_DATA : DAG_RL_DATA_OB, "Driver");
329                                                 /* normal */
330                                                 else
331                                                         dag_add_relation(dag, node1, node, isdata_fcu ? DAG_RL_OB_DATA : DAG_RL_OB_OB, "Driver");
332                                         }
333                                 }
334                         }
335                         DRIVER_TARGETS_LOOPER_END
336                 }
337         }
338 }
339
340 /* XXX: forward def for material driver handling... */
341 static void dag_add_material_driver_relations(DagForest *dag, DagNode *node, Material *ma);
342
343 /* recursive handling for shader nodetree drivers */
344 static void dag_add_shader_nodetree_driver_relations(DagForest *dag, DagNode *node, bNodeTree *ntree)
345 {
346         bNode *n;
347
348         /* nodetree itself */
349         if (ntree->adt) {
350                 dag_add_driver_relation(ntree->adt, dag, node, 1);
351         }
352         
353         /* nodetree's nodes... */
354         for (n = ntree->nodes.first; n; n = n->next) {
355                 if (n->id) {
356                         if (GS(n->id->name) == ID_MA) {
357                                 dag_add_material_driver_relations(dag, node, (Material *)n->id);
358                         }
359                         else if (n->type == NODE_GROUP) {
360                                 dag_add_shader_nodetree_driver_relations(dag, node, (bNodeTree *)n->id);
361                         }
362                 }
363         }
364 }
365
366 /* recursive handling for material drivers */
367 static void dag_add_material_driver_relations(DagForest *dag, DagNode *node, Material *ma)
368 {
369         /* Prevent infinite recursion by checking (and tagging the material) as having been visited 
370          * already (see build_dag()). This assumes ma->id.flag & LIB_DOIT isn't set by anything else
371          * in the meantime... [#32017]
372          */
373         if (ma->id.flag & LIB_DOIT)
374                 return;
375         else
376                 ma->id.flag |= LIB_DOIT;
377         
378         /* material itself */
379         if (ma->adt)
380                 dag_add_driver_relation(ma->adt, dag, node, 1);
381
382         /* textures */
383         // TODO...
384         //dag_add_texture_driver_relations(DagForest *dag, DagNode *node, ID *id);
385
386         /* material's nodetree */
387         if (ma->nodetree)
388                 dag_add_shader_nodetree_driver_relations(dag, node, ma->nodetree);
389 }
390
391 /* recursive handling for lamp drivers */
392 static void dag_add_lamp_driver_relations(DagForest *dag, DagNode *node, Lamp *la)
393 {
394         /* Prevent infinite recursion by checking (and tagging the lamp) as having been visited 
395          * already (see build_dag()). This assumes la->id.flag & LIB_DOIT isn't set by anything else
396          * in the meantime... [#32017]
397          */
398         if (la->id.flag & LIB_DOIT)
399                 return;
400         else
401                 la->id.flag |= LIB_DOIT;
402         
403         /* lamp itself */
404         if (la->adt)
405                 dag_add_driver_relation(la->adt, dag, node, 1);
406
407         /* textures */
408         // TODO...
409         //dag_add_texture_driver_relations(DagForest *dag, DagNode *node, ID *id);
410
411         /* lamp's nodetree */
412         if (la->nodetree)
413                 dag_add_shader_nodetree_driver_relations(dag, node, la->nodetree);
414 }
415
416 static void dag_add_collision_field_relation(DagForest *dag, Scene *scene, Object *ob, DagNode *node, int skip_forcefield, bool no_collision)
417 {
418         Base *base;
419         DagNode *node2;
420
421         /* would be nice to have a list of colliders here
422          * so for now walk all objects in scene check 'same layer rule' */
423         for (base = scene->base.first; base; base = base->next) {
424                 if ((base->lay & ob->lay) && base->object->pd) {
425                         Object *ob1 = base->object;
426                         if ((ob1->pd->deflect || ob1->pd->forcefield) && (ob1 != ob)) {
427                                 if ((skip_forcefield && ob1->pd->forcefield == skip_forcefield) || (no_collision && ob1->pd->forcefield == 0))
428                                         continue;
429                                 node2 = dag_get_node(dag, ob1);
430                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Field Collision");
431                         }
432                 }
433         }
434 }
435
436 static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, Object *ob, int mask)
437 {
438         bConstraint *con;
439         DagNode *node;
440         DagNode *node2;
441         DagNode *node3;
442         Key *key;
443         ParticleSystem *psys;
444         int addtoroot = 1;
445         
446         node = dag_get_node(dag, ob);
447         
448         if ((ob->data) && (mask & DAG_RL_DATA)) {
449                 node2 = dag_get_node(dag, ob->data);
450                 dag_add_relation(dag, node, node2, DAG_RL_DATA, "Object-Data Relation");
451                 node2->first_ancestor = ob;
452                 node2->ancestor_count += 1;
453         }
454
455         /* also build a custom data mask for dependencies that need certain layers */
456         node->customdata_mask = 0;
457         
458         if (ob->type == OB_ARMATURE) {
459                 if (ob->pose) {
460                         bPoseChannel *pchan;
461                         
462                         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
463                                 for (con = pchan->constraints.first; con; con = con->next) {
464                                         bConstraintTypeInfo *cti = BKE_constraint_get_typeinfo(con);
465                                         ListBase targets = {NULL, NULL};
466                                         bConstraintTarget *ct;
467                                         
468                                         if (cti && cti->get_constraint_targets) {
469                                                 cti->get_constraint_targets(con, &targets);
470                                                 
471                                                 for (ct = targets.first; ct; ct = ct->next) {
472                                                         if (ct->tar && ct->tar != ob) {
473                                                                 // fprintf(stderr, "armature %s target :%s\n", ob->id.name, target->id.name);
474                                                                 node3 = dag_get_node(dag, ct->tar);
475                                                                 
476                                                                 if (ct->subtarget[0]) {
477                                                                         dag_add_relation(dag, node3, node, DAG_RL_OB_DATA | DAG_RL_DATA_DATA, cti->name);
478                                                                         if (ct->tar->type == OB_MESH)
479                                                                                 node3->customdata_mask |= CD_MASK_MDEFORMVERT;
480                                                                 }
481                                                                 else if (ELEM3(con->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO, CONSTRAINT_TYPE_SPLINEIK))
482                                                                         dag_add_relation(dag, node3, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, cti->name);
483                                                                 else
484                                                                         dag_add_relation(dag, node3, node, DAG_RL_OB_DATA, cti->name);
485                                                         }
486                                                 }
487                                                 
488                                                 if (cti->flush_constraint_targets)
489                                                         cti->flush_constraint_targets(con, &targets, 1);
490                                         }
491                                         
492                                 }
493                         }
494                 }
495         }
496         
497         /* driver dependencies, nla modifiers */
498 #if 0 // XXX old animation system
499         if (ob->nlastrips.first) {
500                 bActionStrip *strip;
501                 bActionChannel *chan;
502                 for (strip = ob->nlastrips.first; strip; strip = strip->next) {
503                         if (strip->modifiers.first) {
504                                 bActionModifier *amod;
505                                 for (amod = strip->modifiers.first; amod; amod = amod->next) {
506                                         if (amod->ob) {
507                                                 node2 = dag_get_node(dag, amod->ob);
508                                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "NLA Strip Modifier");
509                                         }
510                                 }
511                         }
512                 }
513         }
514 #endif // XXX old animation system
515         if (ob->adt)
516                 dag_add_driver_relation(ob->adt, dag, node, (ob->type == OB_ARMATURE));  // XXX isdata arg here doesn't give an accurate picture of situation
517                 
518         key = BKE_key_from_object(ob);
519         if (key && key->adt)
520                 dag_add_driver_relation(key->adt, dag, node, 1);
521
522         if (ob->modifiers.first) {
523                 ModifierData *md;
524                 
525                 for (md = ob->modifiers.first; md; md = md->next) {
526                         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
527                         
528                         if (mti->updateDepgraph) mti->updateDepgraph(md, dag, scene, ob, node);
529                 }
530         }
531         if (ob->parent) {
532                 node2 = dag_get_node(dag, ob->parent);
533                 
534                 switch (ob->partype) {
535                         case PARSKEL:
536                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_OB, "Parent");
537                                 break;
538                         case PARVERT1: case PARVERT3:
539                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_OB | DAG_RL_OB_OB, "Vertex Parent");
540                                 node2->customdata_mask |= CD_MASK_ORIGINDEX;
541                                 break;
542                         case PARBONE:
543                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_OB | DAG_RL_OB_OB, "Bone Parent");
544                                 break;
545                         default:
546                                 if (ob->parent->type == OB_LATTICE)
547                                         dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_OB, "Lattice Parent");
548                                 else if (ob->parent->type == OB_CURVE) {
549                                         Curve *cu = ob->parent->data;
550                                         if (cu->flag & CU_PATH) 
551                                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_OB | DAG_RL_OB_OB, "Curve Parent");
552                                         else
553                                                 dag_add_relation(dag, node2, node, DAG_RL_OB_OB, "Curve Parent");
554                                 }
555                                 else
556                                         dag_add_relation(dag, node2, node, DAG_RL_OB_OB, "Parent");
557                 }
558                 /* exception case: parent is duplivert */
559                 if (ob->type == OB_MBALL && (ob->parent->transflag & OB_DUPLIVERTS)) {
560                         dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_OB, "Duplivert");
561                 }
562                 
563                 addtoroot = 0;
564         }
565         if (ob->proxy) {
566                 node2 = dag_get_node(dag, ob->proxy);
567                 dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA | DAG_RL_OB_OB, "Proxy");
568                 /* inverted relation, so addtoroot shouldn't be set to zero */
569         }
570         
571         if (ob->transflag & OB_DUPLI) {
572                 if ((ob->transflag & OB_DUPLIGROUP) && ob->dup_group) {
573                         GroupObject *go;
574                         for (go = ob->dup_group->gobject.first; go; go = go->next) {
575                                 if (go->ob) {
576                                         node2 = dag_get_node(dag, go->ob);
577                                         /* node2 changes node1, this keeps animations updated in groups?? not logical? */
578                                         dag_add_relation(dag, node2, node, DAG_RL_OB_OB, "Dupligroup");
579                                 }
580                         }
581                 }
582         }
583
584         /* softbody collision  */
585         if ((ob->type == OB_MESH) || (ob->type == OB_CURVE) || (ob->type == OB_LATTICE)) {
586                 if (ob->particlesystem.first ||
587                     modifiers_isModifierEnabled(ob, eModifierType_Softbody) ||
588                     modifiers_isModifierEnabled(ob, eModifierType_Cloth) ||
589                     modifiers_isModifierEnabled(ob, eModifierType_DynamicPaint))
590                 {
591                         dag_add_collision_field_relation(dag, scene, ob, node, 0, false);  /* TODO: use effectorweight->group */
592                 }
593                 else if (modifiers_isModifierEnabled(ob, eModifierType_Smoke)) {
594                         dag_add_collision_field_relation(dag, scene, ob, node, PFIELD_SMOKEFLOW, false);
595                 }
596                 else if (ob->rigidbody_object) {
597                         dag_add_collision_field_relation(dag, scene, ob, node, 0, true);
598                 }
599         }
600         
601         /* object data drivers */
602         if (ob->data) {
603                 AnimData *adt = BKE_animdata_from_id((ID *)ob->data);
604                 if (adt)
605                         dag_add_driver_relation(adt, dag, node, 1);
606         }
607         
608         /* object type/data relationships */
609         switch (ob->type) {
610                 case OB_CAMERA:
611                 {
612                         Camera *cam = (Camera *)ob->data;
613                         
614                         if (cam->dof_ob) {
615                                 node2 = dag_get_node(dag, cam->dof_ob);
616                                 dag_add_relation(dag, node2, node, DAG_RL_OB_OB, "Camera DoF");
617                         }
618                 }
619                 break;
620                 case OB_MBALL: 
621                 {
622                         Object *mom = BKE_mball_basis_find(scene, ob);
623                         
624                         if (mom != ob) {
625                                 node2 = dag_get_node(dag, mom);
626                                 dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Metaball");  /* mom depends on children! */
627                         }
628                 }
629                 break;
630                 case OB_CURVE:
631                 case OB_FONT:
632                 {
633                         Curve *cu = ob->data;
634                         
635                         if (cu->bevobj) {
636                                 node2 = dag_get_node(dag, cu->bevobj);
637                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Curve Bevel");
638                         }
639                         if (cu->taperobj) {
640                                 node2 = dag_get_node(dag, cu->taperobj);
641                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Curve Taper");
642                         }
643                         if (ob->type == OB_FONT) {
644                                 if (cu->textoncurve) {
645                                         node2 = dag_get_node(dag, cu->textoncurve);
646                                         dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Texture On Curve");
647                                 }
648                         }
649                 }
650                 break;
651         }
652         
653         /* material drivers */
654         if (ob->totcol) {
655                 int a;
656                 
657                 for (a = 1; a <= ob->totcol; a++) {
658                         Material *ma = give_current_material(ob, a);
659                         
660                         if (ma) {
661                                 /* recursively figure out if there are drivers, and hook these up to this object */
662                                 dag_add_material_driver_relations(dag, node, ma);
663                         }
664                 }
665         }
666         else if (ob->type == OB_LAMP) {
667                 dag_add_lamp_driver_relations(dag, node, ob->data);
668         }
669         
670         /* particles */
671         psys = ob->particlesystem.first;
672         if (psys) {
673                 GroupObject *go;
674
675                 for (; psys; psys = psys->next) {
676                         BoidRule *rule = NULL;
677                         BoidState *state = NULL;
678                         ParticleSettings *part = psys->part;
679                         ListBase *effectors = NULL;
680                         EffectorCache *eff;
681
682                         dag_add_relation(dag, node, node, DAG_RL_OB_DATA, "Particle-Object Relation");
683
684                         if (!psys_check_enabled(ob, psys))
685                                 continue;
686
687                         if (ELEM(part->phystype, PART_PHYS_KEYED, PART_PHYS_BOIDS)) {
688                                 ParticleTarget *pt = psys->targets.first;
689
690                                 for (; pt; pt = pt->next) {
691                                         if (pt->ob && BLI_findlink(&pt->ob->particlesystem, pt->psys - 1)) {
692                                                 node2 = dag_get_node(dag, pt->ob);
693                                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Particle Targets");
694                                         }
695                                 }
696                         }
697
698                         if (part->ren_as == PART_DRAW_OB && part->dup_ob) {
699                                 node2 = dag_get_node(dag, part->dup_ob);
700                                 /* note that this relation actually runs in the wrong direction, the problem
701                                  * is that dupli system all have this (due to parenting), and the render
702                                  * engine instancing assumes particular ordering of objects in list */
703                                 dag_add_relation(dag, node, node2, DAG_RL_OB_OB, "Particle Object Visualization");
704                                 if (part->dup_ob->type == OB_MBALL)
705                                         dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA, "Particle Object Visualization");
706                         }
707
708                         if (part->ren_as == PART_DRAW_GR && part->dup_group) {
709                                 for (go = part->dup_group->gobject.first; go; go = go->next) {
710                                         node2 = dag_get_node(dag, go->ob);
711                                         dag_add_relation(dag, node2, node, DAG_RL_OB_OB, "Particle Group Visualization");
712                                 }
713                         }
714
715                         effectors = pdInitEffectors(scene, ob, psys, part->effector_weights);
716
717                         if (effectors) {
718                                 for (eff = effectors->first; eff; eff = eff->next) {
719                                         if (eff->psys) {
720                                                 node2 = dag_get_node(dag, eff->ob);
721                                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Particle Field");
722                                         }
723                                 }
724                         }
725
726                         pdEndEffectors(&effectors);
727
728                         if (part->boids) {
729                                 for (state = part->boids->states.first; state; state = state->next) {
730                                         for (rule = state->rules.first; rule; rule = rule->next) {
731                                                 Object *ruleob = NULL;
732                                                 if (rule->type == eBoidRuleType_Avoid)
733                                                         ruleob = ((BoidRuleGoalAvoid *)rule)->ob;
734                                                 else if (rule->type == eBoidRuleType_FollowLeader)
735                                                         ruleob = ((BoidRuleFollowLeader *)rule)->ob;
736
737                                                 if (ruleob) {
738                                                         node2 = dag_get_node(dag, ruleob);
739                                                         dag_add_relation(dag, node2, node, DAG_RL_OB_DATA, "Boid Rule");
740                                                 }
741                                         }
742                                 }
743                         }
744                 }
745         }
746         
747         /* object constraints */
748         for (con = ob->constraints.first; con; con = con->next) {
749                 bConstraintTypeInfo *cti = BKE_constraint_get_typeinfo(con);
750                 ListBase targets = {NULL, NULL};
751                 bConstraintTarget *ct;
752                 
753                 if (!cti)
754                         continue;
755
756                 /* special case for camera tracking -- it doesn't use targets to define relations */
757                 if (ELEM3(cti->type, CONSTRAINT_TYPE_FOLLOWTRACK, CONSTRAINT_TYPE_CAMERASOLVER, CONSTRAINT_TYPE_OBJECTSOLVER)) {
758                         int depends_on_camera = 0;
759
760                         if (cti->type == CONSTRAINT_TYPE_FOLLOWTRACK) {
761                                 bFollowTrackConstraint *data = (bFollowTrackConstraint *)con->data;
762
763                                 if ((data->clip || data->flag & FOLLOWTRACK_ACTIVECLIP) && data->track[0])
764                                         depends_on_camera = 1;
765
766                                 if (data->depth_ob) {
767                                         node2 = dag_get_node(dag, data->depth_ob);
768                                         dag_add_relation(dag, node2, node, DAG_RL_DATA_OB | DAG_RL_OB_OB, cti->name);
769                                 }
770                         }
771                         else if (cti->type == CONSTRAINT_TYPE_OBJECTSOLVER)
772                                 depends_on_camera = 1;
773
774                         if (depends_on_camera && scene->camera) {
775                                 node2 = dag_get_node(dag, scene->camera);
776                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_OB | DAG_RL_OB_OB, cti->name);
777                         }
778
779                         dag_add_relation(dag, scenenode, node, DAG_RL_SCENE, "Scene Relation");
780                         addtoroot = 0;
781                 }
782                 else if (cti->get_constraint_targets) {
783                         cti->get_constraint_targets(con, &targets);
784                         
785                         for (ct = targets.first; ct; ct = ct->next) {
786                                 Object *obt;
787                                 
788                                 if (ct->tar)
789                                         obt = ct->tar;
790                                 else
791                                         continue;
792                                 
793                                 node2 = dag_get_node(dag, obt);
794                                 if (ELEM(con->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO))
795                                         dag_add_relation(dag, node2, node, DAG_RL_DATA_OB | DAG_RL_OB_OB, cti->name);
796                                 else {
797                                         if (ELEM3(obt->type, OB_ARMATURE, OB_MESH, OB_LATTICE) && (ct->subtarget[0])) {
798                                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_OB | DAG_RL_OB_OB, cti->name);
799                                                 if (obt->type == OB_MESH)
800                                                         node2->customdata_mask |= CD_MASK_MDEFORMVERT;
801                                         }
802                                         else
803                                                 dag_add_relation(dag, node2, node, DAG_RL_OB_OB, cti->name);
804                                 }
805                                 addtoroot = 0;
806                         }
807                         
808                         if (cti->flush_constraint_targets)
809                                 cti->flush_constraint_targets(con, &targets, 1);
810                 }
811         }
812
813         if (addtoroot == 1)
814                 dag_add_relation(dag, scenenode, node, DAG_RL_SCENE, "Scene Relation");
815 }
816
817 DagForest *build_dag(Main *bmain, Scene *sce, short mask)
818 {
819         Base *base;
820         Object *ob;
821         Group *group;
822         GroupObject *go;
823         DagNode *node;
824         DagNode *scenenode;
825         DagForest *dag;
826         DagAdjList *itA;
827
828         dag = sce->theDag;
829         if (dag)
830                 free_forest(dag);
831         else {
832                 dag = dag_init();
833                 sce->theDag = dag;
834         }
835         
836         /* clear "LIB_DOIT" flag from all materials, to prevent infinite recursion problems later [#32017] */
837         tag_main_idcode(bmain, ID_MA, FALSE);
838         tag_main_idcode(bmain, ID_LA, FALSE);
839         
840         /* add base node for scene. scene is always the first node in DAG */
841         scenenode = dag_add_node(dag, sce);
842         
843         /* add current scene objects */
844         for (base = sce->base.first; base; base = base->next) {
845                 ob = base->object;
846                 
847                 build_dag_object(dag, scenenode, sce, ob, mask);
848                 if (ob->proxy)
849                         build_dag_object(dag, scenenode, sce, ob->proxy, mask);
850                 
851                 /* handled in next loop */
852                 if (ob->dup_group) 
853                         ob->dup_group->id.flag |= LIB_DOIT;
854         }
855         
856         /* add groups used in current scene objects */
857         for (group = bmain->group.first; group; group = group->id.next) {
858                 if (group->id.flag & LIB_DOIT) {
859                         for (go = group->gobject.first; go; go = go->next) {
860                                 build_dag_object(dag, scenenode, sce, go->ob, mask);
861                         }
862                         group->id.flag &= ~LIB_DOIT;
863                 }
864         }
865         
866         /* Now all relations were built, but we need to solve 1 exceptional case;
867          * When objects have multiple "parents" (for example parent + constraint working on same object)
868          * the relation type has to be synced. One of the parents can change, and should give same event to child */
869         
870         /* nodes were callocced, so we can use node->color for temporal storage */
871         for (node = sce->theDag->DagNode.first; node; node = node->next) {
872                 if (node->type == ID_OB) {
873                         for (itA = node->child; itA; itA = itA->next) {
874                                 if (itA->node->type == ID_OB) {
875                                         itA->node->color |= itA->type;
876                                 }
877                         }
878
879                         /* also flush custom data mask */
880                         ((Object *)node->ob)->customdata_mask = node->customdata_mask;
881                 }
882         }
883         /* now set relations equal, so that when only one parent changes, the correct recalcs are found */
884         for (node = sce->theDag->DagNode.first; node; node = node->next) {
885                 if (node->type == ID_OB) {
886                         for (itA = node->child; itA; itA = itA->next) {
887                                 if (itA->node->type == ID_OB) {
888                                         itA->type |= itA->node->color;
889                                 }
890                         }
891                 }
892         }
893         
894         /* cycle detection and solving */
895         // solve_cycles(dag);
896         
897         return dag;
898 }
899
900
901 void free_forest(DagForest *Dag) 
902 {  /* remove all nodes and deps */
903         DagNode *tempN;
904         DagAdjList *tempA;
905         DagAdjList *itA;
906         DagNode *itN = Dag->DagNode.first;
907         
908         while (itN) {
909                 itA = itN->child;
910                 while (itA) {
911                         tempA = itA;
912                         itA = itA->next;
913                         MEM_freeN(tempA);
914                 }
915                 
916                 itA = itN->parent;
917                 while (itA) {
918                         tempA = itA;
919                         itA = itA->next;
920                         MEM_freeN(tempA);
921                 }
922                 
923                 tempN = itN;
924                 itN = itN->next;
925                 MEM_freeN(tempN);
926         }
927
928         BLI_ghash_free(Dag->nodeHash, NULL, NULL);
929         Dag->nodeHash = NULL;
930         Dag->DagNode.first = NULL;
931         Dag->DagNode.last = NULL;
932         Dag->numNodes = 0;
933
934 }
935
936 DagNode *dag_find_node(DagForest *forest, void *fob)
937 {
938         if (forest->nodeHash)
939                 return BLI_ghash_lookup(forest->nodeHash, fob);
940
941         return NULL;
942 }
943
944 static int ugly_hack_sorry = 1;         /* prevent type check */
945 static int dag_print_dependencies = 0;  /* debugging */
946
947 /* no checking of existence, use dag_find_node first or dag_get_node */
948 DagNode *dag_add_node(DagForest *forest, void *fob)
949 {
950         DagNode *node;
951                 
952         node = MEM_callocN(sizeof(DagNode), "DAG node");
953         if (node) {
954                 node->ob = fob;
955                 node->color = DAG_WHITE;
956
957                 if (ugly_hack_sorry) node->type = GS(((ID *) fob)->name);  /* sorry, done for pose sorting */
958                 if (forest->numNodes) {
959                         ((DagNode *) forest->DagNode.last)->next = node;
960                         forest->DagNode.last = node;
961                         forest->numNodes++;
962                 }
963                 else {
964                         forest->DagNode.last = node;
965                         forest->DagNode.first = node;
966                         forest->numNodes = 1;
967                 }
968
969                 if (!forest->nodeHash)
970                         forest->nodeHash = BLI_ghash_ptr_new("dag_add_node gh");
971                 BLI_ghash_insert(forest->nodeHash, fob, node);
972         }
973
974         return node;
975 }
976
977 DagNode *dag_get_node(DagForest *forest, void *fob)
978 {
979         DagNode *node;
980         
981         node = dag_find_node(forest, fob);
982         if (!node) 
983                 node = dag_add_node(forest, fob);
984         return node;
985 }
986
987
988
989 DagNode *dag_get_sub_node(DagForest *forest, void *fob)
990 {
991         DagNode *node;
992         DagAdjList *mainchild, *prev = NULL;
993         
994         mainchild = ((DagNode *) forest->DagNode.first)->child;
995         /* remove from first node (scene) adj list if present */
996         while (mainchild) {
997                 if (mainchild->node == fob) {
998                         if (prev) {
999                                 prev->next = mainchild->next;
1000                                 MEM_freeN(mainchild);
1001                                 break;
1002                         }
1003                         else {
1004                                 ((DagNode *) forest->DagNode.first)->child = mainchild->next;
1005                                 MEM_freeN(mainchild);
1006                                 break;
1007                         }
1008                 }
1009                 prev = mainchild;
1010                 mainchild = mainchild->next;
1011         }
1012         node = dag_find_node(forest, fob);
1013         if (!node) 
1014                 node = dag_add_node(forest, fob);
1015         return node;
1016 }
1017
1018 static void dag_add_parent_relation(DagForest *UNUSED(forest), DagNode *fob1, DagNode *fob2, short rel, const char *name) 
1019 {
1020         DagAdjList *itA = fob2->parent;
1021         
1022         while (itA) { /* search if relation exist already */
1023                 if (itA->node == fob1) {
1024                         itA->type |= rel;
1025                         itA->count += 1;
1026                         return;
1027                 }
1028                 itA = itA->next;
1029         }
1030         /* create new relation and insert at head. MALLOC alert! */
1031         itA = MEM_mallocN(sizeof(DagAdjList), "DAG adj list");
1032         itA->node = fob1;
1033         itA->type = rel;
1034         itA->count = 1;
1035         itA->next = fob2->parent;
1036         itA->name = name;
1037         fob2->parent = itA;
1038 }
1039
1040 void dag_add_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel, const char *name) 
1041 {
1042         DagAdjList *itA = fob1->child;
1043         
1044         /* parent relation is for cycle checking */
1045         dag_add_parent_relation(forest, fob1, fob2, rel, name);
1046
1047         while (itA) { /* search if relation exist already */
1048                 if (itA->node == fob2) {
1049                         itA->type |= rel;
1050                         itA->count += 1;
1051                         return;
1052                 }
1053                 itA = itA->next;
1054         }
1055         /* create new relation and insert at head. MALLOC alert! */
1056         itA = MEM_mallocN(sizeof(DagAdjList), "DAG adj list");
1057         itA->node = fob2;
1058         itA->type = rel;
1059         itA->count = 1;
1060         itA->next = fob1->child;
1061         itA->name = name;
1062         fob1->child = itA;
1063 }
1064
1065 static const char *dag_node_name(DagNode *node)
1066 {
1067         if (node->ob == NULL)
1068                 return "null";
1069         else if (ugly_hack_sorry)
1070                 return ((ID *)(node->ob))->name + 2;
1071         else
1072                 return ((bPoseChannel *)(node->ob))->name;
1073 }
1074
1075 static void dag_node_print_dependencies(DagNode *node)
1076 {
1077         DagAdjList *itA;
1078
1079         printf("%s depends on:\n", dag_node_name(node));
1080
1081         for (itA = node->parent; itA; itA = itA->next)
1082                 printf("  %s through %s\n", dag_node_name(itA->node), itA->name);
1083         printf("\n");
1084 }
1085
1086 static int dag_node_print_dependency_recurs(DagNode *node, DagNode *endnode)
1087 {
1088         DagAdjList *itA;
1089
1090         if (node->color == DAG_BLACK)
1091                 return 0;
1092
1093         node->color = DAG_BLACK;
1094
1095         if (node == endnode)
1096                 return 1;
1097
1098         for (itA = node->parent; itA; itA = itA->next) {
1099                 if (dag_node_print_dependency_recurs(itA->node, endnode)) {
1100                         printf("  %s depends on %s through %s.\n", dag_node_name(node), dag_node_name(itA->node), itA->name);
1101                         return 1;
1102                 }
1103         }
1104
1105         return 0;
1106 }
1107
1108 static void dag_node_print_dependency_cycle(DagForest *dag, DagNode *startnode, DagNode *endnode, const char *name)
1109 {
1110         DagNode *node;
1111
1112         for (node = dag->DagNode.first; node; node = node->next)
1113                 node->color = DAG_WHITE;
1114
1115         printf("  %s depends on %s through %s.\n", dag_node_name(endnode), dag_node_name(startnode), name);
1116         dag_node_print_dependency_recurs(startnode, endnode);
1117         printf("\n");
1118 }
1119
1120 static int dag_node_recurs_level(DagNode *node, int level)
1121 {
1122         DagAdjList *itA;
1123         int newlevel;
1124
1125         node->color = DAG_BLACK; /* done */
1126         newlevel = ++level;
1127         
1128         for (itA = node->parent; itA; itA = itA->next) {
1129                 if (itA->node->color == DAG_WHITE) {
1130                         itA->node->ancestor_count = dag_node_recurs_level(itA->node, level);
1131                         newlevel = MAX2(newlevel, level + itA->node->ancestor_count);
1132                 }
1133                 else
1134                         newlevel = MAX2(newlevel, level + itA->node->ancestor_count);
1135         }
1136         
1137         return newlevel;
1138 }
1139
1140 static void dag_check_cycle(DagForest *dag)
1141 {
1142         DagNode *node;
1143         DagAdjList *itA;
1144
1145         /* debugging print */
1146         if (dag_print_dependencies)
1147                 for (node = dag->DagNode.first; node; node = node->next)
1148                         dag_node_print_dependencies(node);
1149
1150         /* tag nodes unchecked */
1151         for (node = dag->DagNode.first; node; node = node->next)
1152                 node->color = DAG_WHITE;
1153         
1154         for (node = dag->DagNode.first; node; node = node->next) {
1155                 if (node->color == DAG_WHITE) {
1156                         node->ancestor_count = dag_node_recurs_level(node, 0);
1157                 }
1158         }
1159         
1160         /* check relations, and print errors */
1161         for (node = dag->DagNode.first; node; node = node->next) {
1162                 for (itA = node->parent; itA; itA = itA->next) {
1163                         if (itA->node->ancestor_count > node->ancestor_count) {
1164                                 if (node->ob && itA->node->ob) {
1165                                         printf("Dependency cycle detected:\n");
1166                                         dag_node_print_dependency_cycle(dag, itA->node, node, itA->name);
1167                                 }
1168                         }
1169                 }
1170         }
1171
1172         /* parent relations are only needed for cycle checking, so free now */
1173         for (node = dag->DagNode.first; node; node = node->next) {
1174                 while (node->parent) {
1175                         itA = node->parent->next;
1176                         MEM_freeN(node->parent);
1177                         node->parent = itA;
1178                 }
1179         }
1180 }
1181
1182 /* debug test functions */
1183
1184 void graph_print_queue(DagNodeQueue *nqueue)
1185 {       
1186         DagNodeQueueElem *queueElem;
1187         
1188         queueElem = nqueue->first;
1189         while (queueElem) {
1190                 fprintf(stderr, "** %s %i %i-%i ", ((ID *) queueElem->node->ob)->name, queueElem->node->color, queueElem->node->DFS_dvtm, queueElem->node->DFS_fntm);
1191                 queueElem = queueElem->next;
1192         }
1193         fprintf(stderr, "\n");
1194 }
1195
1196 void graph_print_queue_dist(DagNodeQueue *nqueue)
1197 {       
1198         DagNodeQueueElem *queueElem;
1199         int count;
1200         
1201         queueElem = nqueue->first;
1202         count = 0;
1203         while (queueElem) {
1204                 fprintf(stderr, "** %25s %2.2i-%2.2i ", ((ID *) queueElem->node->ob)->name, queueElem->node->DFS_dvtm, queueElem->node->DFS_fntm);
1205                 while (count < queueElem->node->DFS_dvtm - 1) { fputc(' ', stderr); count++; }
1206                 fputc('|', stderr);
1207                 while (count < queueElem->node->DFS_fntm - 2) { fputc('-', stderr); count++; }
1208                 fputc('|', stderr);
1209                 fputc('\n', stderr);
1210                 count = 0;
1211                 queueElem = queueElem->next;
1212         }
1213         fprintf(stderr, "\n");
1214 }
1215
1216 void graph_print_adj_list(DagForest *dag)
1217 {
1218         DagNode *node;
1219         DagAdjList *itA;
1220         
1221         node = dag->DagNode.first;
1222         while (node) {
1223                 fprintf(stderr, "node : %s col: %i", ((ID *) node->ob)->name, node->color);
1224                 itA = node->child;
1225                 while (itA) {
1226                         fprintf(stderr, "-- %s ", ((ID *) itA->node->ob)->name);
1227                         
1228                         itA = itA->next;
1229                 }
1230                 fprintf(stderr, "\n");
1231                 node = node->next;
1232         }
1233 }
1234
1235 /* ************************ API *********************** */
1236
1237 /* mechanism to allow editors to be informed of depsgraph updates,
1238  * to do their own updates based on changes... */
1239 static void (*EditorsUpdateIDCb)(Main *bmain, ID *id) = NULL;
1240 static void (*EditorsUpdateSceneCb)(Main *bmain, Scene *scene, int updated) = NULL;
1241
1242 void DAG_editors_update_cb(void (*id_func)(Main *bmain, ID *id), void (*scene_func)(Main *bmain, Scene *scene, int updated))
1243 {
1244         EditorsUpdateIDCb = id_func;
1245         EditorsUpdateSceneCb = scene_func;
1246 }
1247
1248 static void dag_editors_id_update(Main *bmain, ID *id)
1249 {
1250         if (EditorsUpdateIDCb)
1251                 EditorsUpdateIDCb(bmain, id);
1252 }
1253
1254 static void dag_editors_scene_update(Main *bmain, Scene *scene, int updated)
1255 {
1256         if (EditorsUpdateSceneCb)
1257                 EditorsUpdateSceneCb(bmain, scene, updated);
1258 }
1259
1260 /* groups with objects in this scene need to be put in the right order as well */
1261 static void scene_sort_groups(Main *bmain, Scene *sce)
1262 {
1263         Base *base;
1264         Group *group;
1265         GroupObject *go;
1266         Object *ob;
1267         
1268         /* test; are group objects all in this scene? */
1269         for (ob = bmain->object.first; ob; ob = ob->id.next) {
1270                 ob->id.flag &= ~LIB_DOIT;
1271                 ob->id.newid = NULL; /* newid abuse for GroupObject */
1272         }
1273         for (base = sce->base.first; base; base = base->next)
1274                 base->object->id.flag |= LIB_DOIT;
1275         
1276         for (group = bmain->group.first; group; group = group->id.next) {
1277                 for (go = group->gobject.first; go; go = go->next) {
1278                         if ((go->ob->id.flag & LIB_DOIT) == 0)
1279                                 break;
1280                 }
1281                 /* this group is entirely in this scene */
1282                 if (go == NULL) {
1283                         ListBase listb = {NULL, NULL};
1284                         
1285                         for (go = group->gobject.first; go; go = go->next)
1286                                 go->ob->id.newid = (ID *)go;
1287                         
1288                         /* in order of sorted bases we reinsert group objects */
1289                         for (base = sce->base.first; base; base = base->next) {
1290                                 
1291                                 if (base->object->id.newid) {
1292                                         go = (GroupObject *)base->object->id.newid;
1293                                         base->object->id.newid = NULL;
1294                                         BLI_remlink(&group->gobject, go);
1295                                         BLI_addtail(&listb, go);
1296                                 }
1297                         }
1298                         /* copy the newly sorted listbase */
1299                         group->gobject = listb;
1300                 }
1301         }
1302 }
1303
1304 /* free the depency graph */
1305 static void dag_scene_free(Scene *sce)
1306 {
1307         if (sce->theDag) {
1308                 free_forest(sce->theDag);
1309                 MEM_freeN(sce->theDag);
1310                 sce->theDag = NULL;
1311         }
1312 }
1313
1314 /* sort the base list on dependency order */
1315 static void dag_scene_build(Main *bmain, Scene *sce)
1316 {
1317         DagNode *node, *rootnode;
1318         DagNodeQueue *nqueue;
1319         DagAdjList *itA;
1320         int time;
1321         int skip = 0;
1322         ListBase tempbase;
1323         Base *base;
1324
1325         tempbase.first = tempbase.last = NULL;
1326         
1327         build_dag(bmain, sce, DAG_RL_ALL_BUT_DATA);
1328         
1329         dag_check_cycle(sce->theDag);
1330
1331         nqueue = queue_create(DAGQUEUEALLOC);
1332         
1333         for (node = sce->theDag->DagNode.first; node; node = node->next) {
1334                 node->color = DAG_WHITE;
1335         }
1336         
1337         time = 1;
1338         
1339         rootnode = sce->theDag->DagNode.first;
1340         rootnode->color = DAG_GRAY;
1341         time++;
1342         push_stack(nqueue, rootnode);
1343         
1344         while (nqueue->count) {
1345                 
1346                 skip = 0;
1347                 node = get_top_node_queue(nqueue);
1348                 
1349                 itA = node->child;
1350                 while (itA != NULL) {
1351                         if (itA->node->color == DAG_WHITE) {
1352                                 itA->node->DFS_dvtm = time;
1353                                 itA->node->color = DAG_GRAY;
1354                                 
1355                                 time++;
1356                                 push_stack(nqueue, itA->node);
1357                                 skip = 1;
1358                                 break;
1359                         }
1360                         itA = itA->next;
1361                 }
1362                 
1363                 if (!skip) {
1364                         if (node) {
1365                                 node = pop_queue(nqueue);
1366                                 if (node->ob == sce)  /* we are done */
1367                                         break;
1368                                 node->color = DAG_BLACK;
1369                                 
1370                                 time++;
1371                                 base = sce->base.first;
1372                                 while (base && base->object != node->ob)
1373                                         base = base->next;
1374                                 if (base) {
1375                                         BLI_remlink(&sce->base, base);
1376                                         BLI_addhead(&tempbase, base);
1377                                 }
1378                         }
1379                 }
1380         }
1381         
1382         /* temporal correction for circular dependencies */
1383         base = sce->base.first;
1384         while (base) {
1385                 BLI_remlink(&sce->base, base);
1386                 BLI_addhead(&tempbase, base);
1387                 //if (G.debug & G_DEBUG)
1388                 printf("cyclic %s\n", base->object->id.name);
1389                 base = sce->base.first;
1390         }
1391         
1392         sce->base = tempbase;
1393         queue_delete(nqueue);
1394         
1395         /* all groups with objects in this scene gets resorted too */
1396         scene_sort_groups(bmain, sce);
1397         
1398         if (G.debug & G_DEBUG) {
1399                 printf("\nordered\n");
1400                 for (base = sce->base.first; base; base = base->next) {
1401                         printf(" %s\n", base->object->id.name);
1402                 }
1403         }
1404
1405         /* temporal...? */
1406         sce->recalc |= SCE_PRV_CHANGED; /* test for 3d preview */
1407 }
1408
1409 /* clear all dependency graphs */
1410 void DAG_relations_tag_update(Main *bmain)
1411 {
1412         Scene *sce;
1413
1414         for (sce = bmain->scene.first; sce; sce = sce->id.next)
1415                 dag_scene_free(sce);
1416 }
1417
1418 /* rebuild dependency graph only for a given scene */
1419 void DAG_scene_relations_rebuild(Main *bmain, Scene *sce)
1420 {
1421         dag_scene_free(sce);
1422         DAG_scene_relations_update(bmain, sce);
1423 }
1424
1425 /* create dependency graph if it was cleared or didn't exist yet */
1426 void DAG_scene_relations_update(Main *bmain, Scene *sce)
1427 {
1428         if (!sce->theDag)
1429                 dag_scene_build(bmain, sce);
1430 }
1431
1432 void DAG_scene_free(Scene *sce)
1433 {
1434         if (sce->theDag) {
1435                 free_forest(sce->theDag);
1436                 MEM_freeN(sce->theDag);
1437                 sce->theDag = NULL;
1438         }
1439 }
1440
1441 static void lib_id_recalc_tag(Main *bmain, ID *id)
1442 {
1443         id->flag |= LIB_ID_RECALC;
1444         DAG_id_type_tag(bmain, GS(id->name));
1445 }
1446
1447 static void lib_id_recalc_data_tag(Main *bmain, ID *id)
1448 {
1449         id->flag |= LIB_ID_RECALC_DATA;
1450         DAG_id_type_tag(bmain, GS(id->name));
1451 }
1452
1453 /* node was checked to have lasttime != curtime and is if type ID_OB */
1454 static void flush_update_node(DagNode *node, unsigned int layer, int curtime)
1455 {
1456         Main *bmain = G.main;
1457         DagAdjList *itA;
1458         Object *ob, *obc;
1459         int oldflag, changed = 0;
1460         unsigned int all_layer;
1461         
1462         node->lasttime = curtime;
1463         
1464         ob = node->ob;
1465         if (ob && (ob->recalc & OB_RECALC_ALL)) {
1466                 all_layer = node->scelay;
1467
1468                 /* got an object node that changes, now check relations */
1469                 for (itA = node->child; itA; itA = itA->next) {
1470                         all_layer |= itA->lay;
1471                         /* the relationship is visible */
1472                         if ((itA->lay & layer)) { // XXX || (itA->node->ob == obedit)
1473                                 if (itA->node->type == ID_OB) {
1474                                         obc = itA->node->ob;
1475                                         oldflag = obc->recalc;
1476                                         
1477                                         /* got a ob->obc relation, now check if flag needs flush */
1478                                         if (ob->recalc & OB_RECALC_OB) {
1479                                                 if (itA->type & DAG_RL_OB_OB) {
1480                                                         //printf("ob %s changes ob %s\n", ob->id.name, obc->id.name);
1481                                                         obc->recalc |= OB_RECALC_OB;
1482                                                         lib_id_recalc_tag(bmain, &obc->id);
1483                                                 }
1484                                                 if (itA->type & DAG_RL_OB_DATA) {
1485                                                         //printf("ob %s changes obdata %s\n", ob->id.name, obc->id.name);
1486                                                         obc->recalc |= OB_RECALC_DATA;
1487                                                         lib_id_recalc_data_tag(bmain, &obc->id);
1488                                                 }
1489                                         }
1490                                         if (ob->recalc & OB_RECALC_DATA) {
1491                                                 if (itA->type & DAG_RL_DATA_OB) {
1492                                                         //printf("obdata %s changes ob %s\n", ob->id.name, obc->id.name);
1493                                                         obc->recalc |= OB_RECALC_OB;
1494                                                         lib_id_recalc_tag(bmain, &obc->id);
1495                                                 }
1496                                                 if (itA->type & DAG_RL_DATA_DATA) {
1497                                                         //printf("obdata %s changes obdata %s\n", ob->id.name, obc->id.name);
1498                                                         obc->recalc |= OB_RECALC_DATA;
1499                                                         lib_id_recalc_data_tag(bmain, &obc->id);
1500                                                 }
1501                                         }
1502                                         if (oldflag != obc->recalc) changed = 1;
1503                                 }
1504                         }
1505                 }
1506                 /* even nicer, we can clear recalc flags...  */
1507                 if ((all_layer & layer) == 0) { // XXX && (ob != obedit)) {
1508                         /* but existing displaylists or derivedmesh should be freed */
1509                         if (ob->recalc & OB_RECALC_DATA)
1510                                 BKE_object_free_display(ob);
1511                         
1512                         ob->recalc &= ~OB_RECALC_ALL;
1513                 }
1514         }
1515         
1516         /* check case where child changes and parent forcing obdata to change */
1517         /* should be done regardless if this ob has recalc set */
1518         /* could merge this in with loop above...? (ton) */
1519         for (itA = node->child; itA; itA = itA->next) {
1520                 /* the relationship is visible */
1521                 if ((itA->lay & layer)) {       // XXX  || (itA->node->ob == obedit)
1522                         if (itA->node->type == ID_OB) {
1523                                 obc = itA->node->ob;
1524                                 /* child moves */
1525                                 if ((obc->recalc & OB_RECALC_ALL) == OB_RECALC_OB) {
1526                                         /* parent has deforming info */
1527                                         if (itA->type & (DAG_RL_OB_DATA | DAG_RL_DATA_DATA)) {
1528                                                 // printf("parent %s changes ob %s\n", ob->id.name, obc->id.name);
1529                                                 obc->recalc |= OB_RECALC_DATA;
1530                                                 lib_id_recalc_data_tag(bmain, &obc->id);
1531                                         }
1532                                 }
1533                         }
1534                 }
1535         }
1536         
1537         /* we only go deeper if node not checked or something changed  */
1538         for (itA = node->child; itA; itA = itA->next) {
1539                 if (changed || itA->node->lasttime != curtime)
1540                         flush_update_node(itA->node, layer, curtime);
1541         }
1542         
1543 }
1544
1545 /* node was checked to have lasttime != curtime, and is of type ID_OB */
1546 static unsigned int flush_layer_node(Scene *sce, DagNode *node, int curtime)
1547 {
1548         DagAdjList *itA;
1549         
1550         node->lasttime = curtime;
1551         node->lay = node->scelay;
1552         
1553         for (itA = node->child; itA; itA = itA->next) {
1554                 if (itA->node->type == ID_OB) {
1555                         if (itA->node->lasttime != curtime) {
1556                                 itA->lay = flush_layer_node(sce, itA->node, curtime);  /* lay is only set once for each relation */
1557                         }
1558                         else itA->lay = itA->node->lay;
1559                         
1560                         node->lay |= itA->lay;
1561                 }
1562         }
1563
1564         return node->lay;
1565 }
1566
1567 /* node was checked to have lasttime != curtime, and is of type ID_OB */
1568 static void flush_pointcache_reset(Scene *scene, DagNode *node, int curtime, int reset)
1569 {
1570         Main *bmain = G.main;
1571         DagAdjList *itA;
1572         Object *ob;
1573         
1574         node->lasttime = curtime;
1575         
1576         for (itA = node->child; itA; itA = itA->next) {
1577                 if (itA->node->type == ID_OB) {
1578                         if (itA->node->lasttime != curtime) {
1579                                 ob = (Object *)(itA->node->ob);
1580
1581                                 if (reset || (ob->recalc & OB_RECALC_ALL)) {
1582                                         if (BKE_ptcache_object_reset(scene, ob, PTCACHE_RESET_DEPSGRAPH)) {
1583                                                 ob->recalc |= OB_RECALC_DATA;
1584                                                 lib_id_recalc_data_tag(bmain, &ob->id);
1585                                         }
1586
1587                                         flush_pointcache_reset(scene, itA->node, curtime, 1);
1588                                 }
1589                                 else
1590                                         flush_pointcache_reset(scene, itA->node, curtime, 0);
1591                         }
1592                 }
1593         }
1594 }
1595
1596 /* flush layer flags to dependencies */
1597 static void dag_scene_flush_layers(Scene *sce, int lay)
1598 {
1599         DagNode *node, *firstnode;
1600         DagAdjList *itA;
1601         Base *base;
1602         int lasttime;
1603
1604         firstnode = sce->theDag->DagNode.first;  /* always scene node */
1605
1606         for (itA = firstnode->child; itA; itA = itA->next)
1607                 itA->lay = 0;
1608
1609         sce->theDag->time++;  /* so we know which nodes were accessed */
1610         lasttime = sce->theDag->time;
1611
1612         /* update layer flags in nodes */
1613         for (base = sce->base.first; base; base = base->next) {
1614                 node = dag_get_node(sce->theDag, base->object);
1615                 node->scelay = base->object->lay;
1616         }
1617
1618         /* ensure cameras are set as if they are on a visible layer, because
1619          * they ared still used for rendering or setting the camera view
1620          *
1621          * XXX, this wont work for local view / unlocked camera's */
1622         if (sce->camera) {
1623                 node = dag_get_node(sce->theDag, sce->camera);
1624                 node->scelay |= lay;
1625         }
1626
1627 #ifdef DURIAN_CAMERA_SWITCH
1628         {
1629                 TimeMarker *m;
1630
1631                 for (m = sce->markers.first; m; m = m->next) {
1632                         if (m->camera) {
1633                                 node = dag_get_node(sce->theDag, m->camera);
1634                                 node->scelay |= lay;
1635                         }
1636                 }
1637         }
1638 #endif
1639
1640         /* flush layer nodes to dependencies */
1641         for (itA = firstnode->child; itA; itA = itA->next)
1642                 if (itA->node->lasttime != lasttime && itA->node->type == ID_OB)
1643                         flush_layer_node(sce, itA->node, lasttime);
1644 }
1645
1646 static void dag_tag_renderlayers(Scene *sce, unsigned int lay)
1647 {
1648         if (sce->nodetree) {
1649                 bNode *node;
1650                 Base *base;
1651                 unsigned int lay_changed = 0;
1652                 
1653                 for (base = sce->base.first; base; base = base->next)
1654                         if (base->lay & lay)
1655                                 if (base->object->recalc)
1656                                         lay_changed |= base->lay;
1657                         
1658                 for (node = sce->nodetree->nodes.first; node; node = node->next) {
1659                         if (node->id == (ID *)sce) {
1660                                 SceneRenderLayer *srl = BLI_findlink(&sce->r.layers, node->custom1);
1661                                 if (srl && (srl->lay & lay_changed))
1662                                         nodeUpdate(sce->nodetree, node);
1663                         }
1664                 }
1665         }
1666 }
1667
1668 /* flushes all recalc flags in objects down the dependency tree */
1669 void DAG_scene_flush_update(Main *bmain, Scene *sce, unsigned int lay, const short time)
1670 {
1671         DagNode *firstnode;
1672         DagAdjList *itA;
1673         Object *ob;
1674         int lasttime;
1675         
1676         if (sce->theDag == NULL) {
1677                 printf("DAG zero... not allowed to happen!\n");
1678                 DAG_scene_relations_update(bmain, sce);
1679         }
1680         
1681         firstnode = sce->theDag->DagNode.first;  /* always scene node */
1682
1683         /* first we flush the layer flags */
1684         dag_scene_flush_layers(sce, lay);
1685
1686         /* then we use the relationships + layer info to flush update events */
1687         sce->theDag->time++;  /* so we know which nodes were accessed */
1688         lasttime = sce->theDag->time;
1689         for (itA = firstnode->child; itA; itA = itA->next)
1690                 if (itA->node->lasttime != lasttime && itA->node->type == ID_OB)
1691                         flush_update_node(itA->node, lay, lasttime);
1692
1693         /* if update is not due to time change, do pointcache clears */
1694         if (!time) {
1695                 sce->theDag->time++;  /* so we know which nodes were accessed */
1696                 lasttime = sce->theDag->time;
1697                 for (itA = firstnode->child; itA; itA = itA->next) {
1698                         if (itA->node->lasttime != lasttime && itA->node->type == ID_OB) {
1699                                 ob = (Object *)(itA->node->ob);
1700
1701                                 if (ob->recalc & OB_RECALC_ALL) {
1702                                         if (BKE_ptcache_object_reset(sce, ob, PTCACHE_RESET_DEPSGRAPH)) {
1703                                                 ob->recalc |= OB_RECALC_DATA;
1704                                                 lib_id_recalc_data_tag(bmain, &ob->id);
1705                                         }
1706
1707                                         flush_pointcache_reset(sce, itA->node, lasttime, 1);
1708                                 }
1709                                 else
1710                                         flush_pointcache_reset(sce, itA->node, lasttime, 0);
1711                         }
1712                 }
1713         }
1714         
1715         dag_tag_renderlayers(sce, lay);
1716 }
1717
1718 static int object_modifiers_use_time(Object *ob)
1719 {
1720         ModifierData *md;
1721         
1722         /* check if a modifier in modifier stack needs time input */
1723         for (md = ob->modifiers.first; md; md = md->next)
1724                 if (modifier_dependsOnTime(md))
1725                         return 1;
1726         
1727         /* check whether any modifiers are animated */
1728         if (ob->adt) {
1729                 AnimData *adt = ob->adt;
1730                 FCurve *fcu;
1731                 
1732                 /* action - check for F-Curves with paths containing 'modifiers[' */
1733                 if (adt->action) {
1734                         for (fcu = adt->action->curves.first; fcu; fcu = fcu->next) {
1735                                 if (fcu->rna_path && strstr(fcu->rna_path, "modifiers["))
1736                                         return 1;
1737                         }
1738                 }
1739                 
1740                 /* This here allows modifier properties to get driven and still update properly
1741                  *
1742                  * Workaround to get [#26764] (e.g. subsurf levels not updating when animated/driven)
1743                  * working, without the updating problems ([#28525] [#28690] [#28774] [#28777]) caused
1744                  * by the RNA updates cache introduced in r.38649
1745                  */
1746                 for (fcu = adt->drivers.first; fcu; fcu = fcu->next) {
1747                         if (fcu->rna_path && strstr(fcu->rna_path, "modifiers["))
1748                                 return 1;
1749                 }
1750                 
1751                 /* XXX: also, should check NLA strips, though for now assume that nobody uses
1752                  * that and we can omit that for performance reasons... */
1753         }
1754         
1755         return 0;
1756 }
1757
1758 static short animdata_use_time(AnimData *adt)
1759 {
1760         NlaTrack *nlt;
1761         
1762         if (adt == NULL) return 0;
1763         
1764         /* check action - only if assigned, and it has anim curves */
1765         if (adt->action && adt->action->curves.first)
1766                 return 1;
1767         
1768         /* check NLA tracks + strips */
1769         for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) {
1770                 if (nlt->strips.first)
1771                         return 1;
1772         }
1773         
1774         /* If we have drivers, more likely than not, on a frame change
1775          * they'll need updating because their owner changed
1776          * 
1777          * This is kindof a hack to get around a whole host of problems
1778          * involving drivers using non-object datablock data (which the 
1779          * depsgraph currently has no way of representing let alone correctly
1780          * dependency sort+tagging). By doing this, at least we ensure that 
1781          * some commonly attempted drivers (such as scene -> current frame;
1782          * see "Driver updates fail" thread on Bf-committers dated July 2)
1783          * will work correctly, and that other non-object datablocks will have
1784          * their drivers update at least on frame change.
1785          *
1786          * -- Aligorith, July 4 2011
1787          */
1788         if (adt->drivers.first)
1789                 return 1;
1790         
1791         return 0;
1792 }
1793
1794 static void dag_object_time_update_flags(Scene *scene, Object *ob)
1795 {
1796         if (ob->constraints.first) {
1797                 bConstraint *con;
1798                 for (con = ob->constraints.first; con; con = con->next) {
1799                         bConstraintTypeInfo *cti = BKE_constraint_get_typeinfo(con);
1800                         ListBase targets = {NULL, NULL};
1801                         bConstraintTarget *ct;
1802                         
1803                         if (cti) {
1804                                 /* special case for camera tracking -- it doesn't use targets to define relations */
1805                                 if (ELEM3(cti->type, CONSTRAINT_TYPE_FOLLOWTRACK, CONSTRAINT_TYPE_CAMERASOLVER, CONSTRAINT_TYPE_OBJECTSOLVER)) {
1806                                         ob->recalc |= OB_RECALC_OB;
1807                                 }
1808                                 else if (cti->get_constraint_targets) {
1809                                         cti->get_constraint_targets(con, &targets);
1810                                         
1811                                         for (ct = targets.first; ct; ct = ct->next) {
1812                                                 if (ct->tar) {
1813                                                         ob->recalc |= OB_RECALC_OB;
1814                                                         break;
1815                                                 }
1816                                         }
1817                                         
1818                                         if (cti->flush_constraint_targets)
1819                                                 cti->flush_constraint_targets(con, &targets, 1);
1820                                 }
1821                                 
1822                         }
1823                 }
1824         }
1825         
1826         if (ob->parent) {
1827                 /* motion path or bone child */
1828                 if (ob->parent->type == OB_CURVE || ob->parent->type == OB_ARMATURE) ob->recalc |= OB_RECALC_OB;
1829         }
1830         
1831 #if 0 // XXX old animation system
1832         if (ob->nlastrips.first) {
1833                 if (ob->dup_group) {
1834                         bActionStrip *strip;
1835                         /* this case is for groups with nla, whilst nla target has no action or nla */
1836                         for (strip = ob->nlastrips.first; strip; strip = strip->next) {
1837                                 if (strip->object)
1838                                         strip->object->recalc |= OB_RECALC_ALL;
1839                         }
1840                 }
1841         }
1842 #endif // XXX old animation system
1843         
1844         if (animdata_use_time(ob->adt)) {
1845                 ob->recalc |= OB_RECALC_OB;
1846                 ob->adt->recalc |= ADT_RECALC_ANIM;
1847         }
1848         
1849         if ((ob->adt) && (ob->type == OB_ARMATURE)) ob->recalc |= OB_RECALC_DATA;
1850         
1851         if (object_modifiers_use_time(ob)) ob->recalc |= OB_RECALC_DATA;
1852         if ((ob->pose) && (ob->pose->flag & POSE_CONSTRAINTS_TIMEDEPEND)) ob->recalc |= OB_RECALC_DATA;
1853         
1854         // XXX: scene here may not be the scene that contains the rigidbody world affecting this!
1855         if (ob->rigidbody_object && BKE_scene_check_rigidbody_active(scene))
1856                 ob->recalc |= OB_RECALC_OB;
1857         
1858         {
1859                 AnimData *adt = BKE_animdata_from_id((ID *)ob->data);
1860                 Mesh *me;
1861                 Curve *cu;
1862                 Lattice *lt;
1863                 
1864                 switch (ob->type) {
1865                         case OB_MESH:
1866                                 me = ob->data;
1867                                 if (me->key) {
1868                                         if (!(ob->shapeflag & OB_SHAPE_LOCK)) {
1869                                                 ob->recalc |= OB_RECALC_DATA;
1870                                         }
1871                                 }
1872                                 if (ob->particlesystem.first)
1873                                         ob->recalc |= OB_RECALC_DATA;
1874                                 break;
1875                         case OB_CURVE:
1876                         case OB_SURF:
1877                                 cu = ob->data;
1878                                 if (cu->key) {
1879                                         if (!(ob->shapeflag & OB_SHAPE_LOCK)) {
1880                                                 ob->recalc |= OB_RECALC_DATA;
1881                                         }
1882                                 }
1883                                 break;
1884                         case OB_FONT:
1885                                 cu = ob->data;
1886                                 if (cu->nurb.first == NULL && cu->str && cu->vfont)
1887                                         ob->recalc |= OB_RECALC_DATA;
1888                                 break;
1889                         case OB_LATTICE:
1890                                 lt = ob->data;
1891                                 if (lt->key) {
1892                                         if (!(ob->shapeflag & OB_SHAPE_LOCK)) {
1893                                                 ob->recalc |= OB_RECALC_DATA;
1894                                         }
1895                                 }
1896                                 break;
1897                         case OB_MBALL:
1898                                 if (ob->transflag & OB_DUPLI) ob->recalc |= OB_RECALC_DATA;
1899                                 break;
1900                 }
1901                 
1902                 if (animdata_use_time(adt)) {
1903                         ob->recalc |= OB_RECALC_DATA;
1904                         adt->recalc |= ADT_RECALC_ANIM;
1905                 }
1906
1907                 if (ob->particlesystem.first) {
1908                         ParticleSystem *psys = ob->particlesystem.first;
1909
1910                         for (; psys; psys = psys->next) {
1911                                 if (psys_check_enabled(ob, psys)) {
1912                                         ob->recalc |= OB_RECALC_DATA;
1913                                         break;
1914                                 }
1915                         }
1916                 }
1917         }
1918
1919         if (ob->recalc & OB_RECALC_OB)
1920                 lib_id_recalc_tag(G.main, &ob->id);
1921         if (ob->recalc & OB_RECALC_DATA)
1922                 lib_id_recalc_data_tag(G.main, &ob->id);
1923
1924 }
1925 /* flag all objects that need recalc, for changes in time for example */
1926 /* do_time: make this optional because undo resets objects to their animated locations without this */
1927 void DAG_scene_update_flags(Main *bmain, Scene *scene, unsigned int lay, const short do_time)
1928 {
1929         Base *base;
1930         Object *ob;
1931         Group *group;
1932         GroupObject *go;
1933         Scene *sce_iter;
1934
1935         /* set ob flags where animated systems are */
1936         for (SETLOOPER(scene, sce_iter, base)) {
1937                 ob = base->object;
1938
1939                 if (do_time) {
1940                         /* now if DagNode were part of base, the node->lay could be checked... */
1941                         /* we do all now, since the scene_flush checks layers and clears recalc flags even */
1942                         
1943                         /* NOTE: "sce_iter" not "scene" so that rigidbodies in background scenes work 
1944                          * (i.e. muting + rbw availability can be checked and tagged properly) [#33970] 
1945                          */
1946                         dag_object_time_update_flags(sce_iter, ob);
1947                 }
1948
1949                 /* handled in next loop */
1950                 if (ob->dup_group)
1951                         ob->dup_group->id.flag |= LIB_DOIT;
1952         }
1953
1954         if (do_time) {
1955                 /* we do groups each once */
1956                 for (group = bmain->group.first; group; group = group->id.next) {
1957                         if (group->id.flag & LIB_DOIT) {
1958                                 for (go = group->gobject.first; go; go = go->next) {
1959                                         dag_object_time_update_flags(scene, go->ob);
1960                                 }
1961                         }
1962                 }
1963         }
1964
1965         for (sce_iter = scene; sce_iter; sce_iter = sce_iter->set)
1966                 DAG_scene_flush_update(bmain, sce_iter, lay, 1);
1967         
1968         if (do_time) {
1969                 /* test: set time flag, to disable baked systems to update */
1970                 for (SETLOOPER(scene, sce_iter, base)) {
1971                         ob = base->object;
1972                         if (ob->recalc)
1973                                 ob->recalc |= OB_RECALC_TIME;
1974                 }
1975
1976                 /* hrmf... an exception to look at once, for invisible camera object we do it over */
1977                 if (scene->camera)
1978                         dag_object_time_update_flags(scene, scene->camera);
1979         }
1980
1981         /* and store the info in groupobject */
1982         for (group = bmain->group.first; group; group = group->id.next) {
1983                 if (group->id.flag & LIB_DOIT) {
1984                         for (go = group->gobject.first; go; go = go->next) {
1985                                 go->recalc = go->ob->recalc;
1986                                 // printf("ob %s recalc %d\n", go->ob->id.name, go->recalc);
1987                         }
1988                         group->id.flag &= ~LIB_DOIT;
1989                 }
1990         }
1991         
1992 }
1993
1994 /* struct returned by DagSceneLayer */
1995 typedef struct DagSceneLayer {
1996         struct DagSceneLayer *next, *prev;
1997         Scene *scene;
1998         unsigned int layer;
1999 } DagSceneLayer;
2000
2001 /* returns visible scenes with valid DAG */
2002 static void dag_current_scene_layers(Main *bmain, ListBase *lb)
2003 {
2004         wmWindowManager *wm;
2005         wmWindow *win;
2006         
2007         lb->first = lb->last = NULL;
2008
2009         /* if we have a windowmanager, look into windows */
2010         if ((wm = bmain->wm.first)) {
2011                 
2012                 flag_listbase_ids(&bmain->scene, LIB_DOIT, 1);
2013
2014                 for (win = wm->windows.first; win; win = win->next) {
2015                         if (win->screen && win->screen->scene->theDag) {
2016                                 Scene *scene = win->screen->scene;
2017                                 
2018                                 if (scene->id.flag & LIB_DOIT) {
2019                                         DagSceneLayer *dsl = MEM_mallocN(sizeof(DagSceneLayer), "dag scene layer");
2020                                         
2021                                         BLI_addtail(lb, dsl);
2022                                         
2023                                         dsl->scene = scene;
2024                                         dsl->layer = BKE_screen_visible_layers(win->screen, scene);
2025                                         
2026                                         scene->id.flag &= ~LIB_DOIT;
2027                                 }
2028                         }
2029                 }
2030         }
2031         else {
2032                 /* if not, use the first sce */
2033                 DagSceneLayer *dsl = MEM_mallocN(sizeof(DagSceneLayer), "dag scene layer");
2034                 
2035                 BLI_addtail(lb, dsl);
2036                 
2037                 dsl->scene = bmain->scene.first;
2038                 dsl->layer = dsl->scene->lay;
2039
2040                 /* XXX for background mode, we should get the scene
2041                  * from somewhere, for the -S option, but it's in
2042                  * the context, how to get it here? */
2043         }
2044 }
2045
2046 void DAG_on_visible_update(Main *bmain, const short do_time)
2047 {
2048         ListBase listbase;
2049         DagSceneLayer *dsl;
2050         
2051         /* get list of visible scenes and layers */
2052         dag_current_scene_layers(bmain, &listbase);
2053         
2054         for (dsl = listbase.first; dsl; dsl = dsl->next) {
2055                 Scene *scene = dsl->scene;
2056                 Scene *sce_iter;
2057                 Base *base;
2058                 Object *ob;
2059                 Group *group;
2060                 GroupObject *go;
2061                 DagNode *node;
2062                 unsigned int lay = dsl->layer, oblay;
2063         
2064                 /* derivedmeshes and displists are not saved to file so need to be
2065                  * remade, tag them so they get remade in the scene update loop,
2066                  * note armature poses or object matrices are preserved and do not
2067                  * require updates, so we skip those */
2068                 dag_scene_flush_layers(scene, lay);
2069
2070                 for (SETLOOPER(scene, sce_iter, base)) {
2071                         ob = base->object;
2072                         node = (sce_iter->theDag) ? dag_get_node(sce_iter->theDag, ob) : NULL;
2073                         oblay = (node) ? node->lay : ob->lay;
2074
2075                         if ((oblay & lay) & ~scene->lay_updated) {
2076                                 if (ELEM6(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL, OB_LATTICE))
2077                                         ob->recalc |= OB_RECALC_DATA;
2078                                 if (ob->dup_group) 
2079                                         ob->dup_group->id.flag |= LIB_DOIT;
2080                         }
2081                 }
2082
2083                 for (group = bmain->group.first; group; group = group->id.next) {
2084                         if (group->id.flag & LIB_DOIT) {
2085                                 for (go = group->gobject.first; go; go = go->next) {
2086                                         if (ELEM6(go->ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL, OB_LATTICE))
2087                                                 go->ob->recalc |= OB_RECALC_DATA;
2088                                         if (go->ob->proxy_from)
2089                                                 go->ob->recalc |= OB_RECALC_OB;
2090                                 }
2091                                 
2092                                 group->id.flag &= ~LIB_DOIT;
2093                         }
2094                 }
2095
2096                 /* now tag update flags, to ensure deformers get calculated on redraw */
2097                 DAG_scene_update_flags(bmain, scene, lay, do_time);
2098                 scene->lay_updated |= lay;
2099         }
2100         
2101         BLI_freelistN(&listbase);
2102
2103         /* hack to get objects updating on layer changes */
2104         DAG_id_type_tag(bmain, ID_OB);
2105
2106         /* so masks update on load */
2107         if (bmain->mask.first) {
2108                 Mask *mask;
2109
2110                 for (mask = bmain->mask.first; mask; mask = mask->id.next) {
2111                         DAG_id_tag_update(&mask->id, 0);
2112                 }
2113         }
2114 }
2115
2116 static void dag_id_flush_update__isDependentTexture(void *userData, Object *UNUSED(ob), ID **idpoin)
2117 {
2118         struct { ID *id; int is_dependent; } *data = userData;
2119         
2120         if (*idpoin && GS((*idpoin)->name) == ID_TE) {
2121                 if (data->id == (*idpoin))
2122                         data->is_dependent = 1;
2123         }
2124 }
2125
2126 static void dag_id_flush_update(Scene *sce, ID *id)
2127 {
2128         Main *bmain = G.main;
2129         Object *obt, *ob = NULL;
2130         short idtype;
2131
2132         /* here we flush a few things before actual scene wide flush, mostly
2133          * due to only objects and not other datablocks being in the depsgraph */
2134
2135         /* set flags & pointcache for object */
2136         if (GS(id->name) == ID_OB) {
2137                 ob = (Object *)id;
2138                 BKE_ptcache_object_reset(sce, ob, PTCACHE_RESET_DEPSGRAPH);
2139
2140                 if (ob->recalc & OB_RECALC_DATA) {
2141                         /* all users of this ob->data should be checked */
2142                         id = ob->data;
2143
2144                         /* no point in trying in this cases */
2145                         if (id && id->us <= 1) {
2146                                 dag_editors_id_update(bmain, id);
2147                                 id = NULL;
2148                         }
2149                 }
2150         }
2151
2152         /* set flags & pointcache for object data */
2153         if (id) {
2154                 idtype = GS(id->name);
2155
2156
2157                 if (OB_DATA_SUPPORT_ID(idtype)) {
2158                         for (obt = bmain->object.first; obt; obt = obt->id.next) {
2159                                 if (!(ob && obt == ob) && obt->data == id) {
2160                                         obt->recalc |= OB_RECALC_DATA;
2161                                         lib_id_recalc_data_tag(bmain, &obt->id);
2162                                         BKE_ptcache_object_reset(sce, obt, PTCACHE_RESET_DEPSGRAPH);
2163                                 }
2164                         }
2165                 }
2166                 
2167                 /* set flags based on textures - can influence depgraph via modifiers */
2168                 if (idtype == ID_TE) {
2169                         for (obt = bmain->object.first; obt; obt = obt->id.next) {
2170                                 struct { ID *id; int is_dependent; } data;
2171                                 data.id = id;
2172                                 data.is_dependent = 0;
2173
2174                                 modifiers_foreachIDLink(obt, dag_id_flush_update__isDependentTexture, &data);
2175                                 if (data.is_dependent) {
2176                                         obt->recalc |= OB_RECALC_DATA;
2177                                         lib_id_recalc_data_tag(bmain, &obt->id);
2178                                 }
2179
2180                                 /* particle settings can use the texture as well */
2181                                 if (obt->particlesystem.first) {
2182                                         ParticleSystem *psys = obt->particlesystem.first;
2183                                         MTex **mtexp, *mtex;
2184                                         int a;
2185                                         for (; psys; psys = psys->next) {
2186                                                 mtexp = psys->part->mtex;
2187                                                 for (a = 0; a < MAX_MTEX; a++, mtexp++) {
2188                                                         mtex = *mtexp;
2189                                                         if (mtex && mtex->tex == (Tex *)id) {
2190                                                                 obt->recalc |= OB_RECALC_DATA;
2191                                                                 lib_id_recalc_data_tag(bmain, &obt->id);
2192
2193                                                                 if (mtex->mapto & PAMAP_INIT)
2194                                                                         psys->recalc |= PSYS_RECALC_RESET;
2195                                                                 if (mtex->mapto & PAMAP_CHILD)
2196                                                                         psys->recalc |= PSYS_RECALC_CHILD;
2197
2198                                                                 BKE_ptcache_object_reset(sce, obt, PTCACHE_RESET_DEPSGRAPH);
2199                                                         }
2200                                                 }
2201                                         }
2202                                 }
2203                         }
2204                 }
2205                 
2206                 /* set flags based on ShapeKey */
2207                 if (idtype == ID_KE) {
2208                         for (obt = bmain->object.first; obt; obt = obt->id.next) {
2209                                 Key *key = BKE_key_from_object(obt);
2210                                 if (!(ob && obt == ob) && ((ID *)key == id)) {
2211                                         obt->flag |= (OB_RECALC_OB | OB_RECALC_DATA);
2212                                         lib_id_recalc_tag(bmain, &obt->id);
2213                                         lib_id_recalc_data_tag(bmain, &obt->id);
2214                                         BKE_ptcache_object_reset(sce, obt, PTCACHE_RESET_DEPSGRAPH);
2215                                 }
2216                         }
2217                 }
2218                 
2219                 /* set flags based on particle settings */
2220                 if (idtype == ID_PA) {
2221                         ParticleSystem *psys;
2222                         for (obt = bmain->object.first; obt; obt = obt->id.next)
2223                                 for (psys = obt->particlesystem.first; psys; psys = psys->next)
2224                                         if (&psys->part->id == id)
2225                                                 BKE_ptcache_object_reset(sce, obt, PTCACHE_RESET_DEPSGRAPH);
2226                 }
2227
2228                 if (idtype == ID_MC) {
2229                         MovieClip *clip = (MovieClip *) id;
2230
2231                         BKE_tracking_dopesheet_tag_update(&clip->tracking);
2232
2233                         for (obt = bmain->object.first; obt; obt = obt->id.next) {
2234                                 bConstraint *con;
2235                                 for (con = obt->constraints.first; con; con = con->next) {
2236                                         bConstraintTypeInfo *cti = BKE_constraint_get_typeinfo(con);
2237                                         if (ELEM3(cti->type, CONSTRAINT_TYPE_FOLLOWTRACK, CONSTRAINT_TYPE_CAMERASOLVER,
2238                                                   CONSTRAINT_TYPE_OBJECTSOLVER))
2239                                         {
2240                                                 obt->recalc |= OB_RECALC_OB;
2241                                                 break;
2242                                         }
2243                                 }
2244                         }
2245
2246                         if (sce->nodetree) {
2247                                 bNode *node;
2248
2249                                 for (node = sce->nodetree->nodes.first; node; node = node->next) {
2250                                         if (node->id == id) {
2251                                                 nodeUpdate(sce->nodetree, node);
2252                                         }
2253                                 }
2254                         }
2255                 }
2256
2257                 if (idtype == ID_MSK) {
2258                         if (sce->nodetree) {
2259                                 bNode *node;
2260
2261                                 for (node = sce->nodetree->nodes.first; node; node = node->next) {
2262                                         if (node->id == id) {
2263                                                 nodeUpdate(sce->nodetree, node);
2264                                         }
2265                                 }
2266                         }
2267                 }
2268
2269                 /* camera's matrix is used to orient reconstructed stuff,
2270                  * so it should happen tracking-related constraints recalculation
2271                  * when camera is changing (sergey) */
2272                 if (sce->camera && &sce->camera->id == id) {
2273                         MovieClip *clip = BKE_object_movieclip_get(sce, sce->camera, 1);
2274
2275                         if (clip)
2276                                 dag_id_flush_update(sce, &clip->id);
2277                 }
2278
2279                 /* update editors */
2280                 dag_editors_id_update(bmain, id);
2281         }
2282 }
2283
2284 void DAG_ids_flush_tagged(Main *bmain)
2285 {
2286         ListBase listbase;
2287         DagSceneLayer *dsl;
2288         ListBase *lbarray[MAX_LIBARRAY];
2289         int a, do_flush = FALSE;
2290         
2291         /* get list of visible scenes and layers */
2292         dag_current_scene_layers(bmain, &listbase);
2293
2294         if (listbase.first == NULL)
2295                 return;
2296
2297         /* loop over all ID types */
2298         a  = set_listbasepointers(bmain, lbarray);
2299
2300         while (a--) {
2301                 ListBase *lb = lbarray[a];
2302                 ID *id = lb->first;
2303
2304                 /* we tag based on first ID type character to avoid 
2305                  * looping over all ID's in case there are no tags */
2306                 if (id && bmain->id_tag_update[id->name[0]]) {
2307                         for (; id; id = id->next) {
2308                                 if (id->flag & (LIB_ID_RECALC | LIB_ID_RECALC_DATA)) {
2309                                         
2310                                         for (dsl = listbase.first; dsl; dsl = dsl->next)
2311                                                 dag_id_flush_update(dsl->scene, id);
2312                                         
2313                                         do_flush = TRUE;
2314                                 }
2315                         }
2316                 }
2317         }
2318
2319         /* flush changes to other objects */
2320         if (do_flush) {
2321                 for (dsl = listbase.first; dsl; dsl = dsl->next)
2322                         DAG_scene_flush_update(bmain, dsl->scene, dsl->layer, 0);
2323         }
2324         
2325         BLI_freelistN(&listbase);
2326 }
2327
2328 void DAG_ids_check_recalc(Main *bmain, Scene *scene, int time)
2329 {
2330         ListBase *lbarray[MAX_LIBARRAY];
2331         int a, updated = 0;
2332
2333         /* loop over all ID types */
2334         a  = set_listbasepointers(bmain, lbarray);
2335
2336         while (a--) {
2337                 ListBase *lb = lbarray[a];
2338                 ID *id = lb->first;
2339
2340                 /* we tag based on first ID type character to avoid 
2341                  * looping over all ID's in case there are no tags */
2342                 if (id && bmain->id_tag_update[id->name[0]]) {
2343                         updated = 1;
2344                         break;
2345                 }
2346         }
2347
2348         dag_editors_scene_update(bmain, scene, (updated || time));
2349 }
2350
2351 void DAG_ids_clear_recalc(Main *bmain)
2352 {
2353         ListBase *lbarray[MAX_LIBARRAY];
2354         bNodeTree *ntree;
2355         int a;
2356
2357         /* loop over all ID types */
2358         a  = set_listbasepointers(bmain, lbarray);
2359
2360         while (a--) {
2361                 ListBase *lb = lbarray[a];
2362                 ID *id = lb->first;
2363
2364                 /* we tag based on first ID type character to avoid 
2365                  * looping over all ID's in case there are no tags */
2366                 if (id && bmain->id_tag_update[id->name[0]]) {
2367                         for (; id; id = id->next) {
2368                                 if (id->flag & (LIB_ID_RECALC | LIB_ID_RECALC_DATA))
2369                                         id->flag &= ~(LIB_ID_RECALC | LIB_ID_RECALC_DATA);
2370
2371                                 /* some ID's contain semi-datablock nodetree */
2372                                 ntree = ntreeFromID(id);
2373                                 if (ntree && (ntree->id.flag & (LIB_ID_RECALC | LIB_ID_RECALC_DATA)))
2374                                         ntree->id.flag &= ~(LIB_ID_RECALC | LIB_ID_RECALC_DATA);
2375                         }
2376                 }
2377         }
2378
2379         memset(bmain->id_tag_update, 0, sizeof(bmain->id_tag_update));
2380 }
2381
2382 void DAG_id_tag_update_ex(Main *bmain, ID *id, short flag)
2383 {
2384         if (id == NULL) return;
2385
2386         /* tag ID for update */
2387         if (flag) {
2388                 if (flag & OB_RECALC_OB)
2389                         lib_id_recalc_tag(bmain, id);
2390                 if (flag & (OB_RECALC_DATA | PSYS_RECALC))
2391                         lib_id_recalc_data_tag(bmain, id);
2392         }
2393         else
2394                 lib_id_recalc_tag(bmain, id);
2395
2396         /* flag is for objects and particle systems */
2397         if (flag) {
2398                 Object *ob;
2399                 short idtype = GS(id->name);
2400
2401                 if (idtype == ID_OB) {
2402                         /* only quick tag */
2403                         ob = (Object *)id;
2404                         ob->recalc |= (flag & OB_RECALC_ALL);
2405                 }
2406                 else if (idtype == ID_PA) {
2407                         ParticleSystem *psys;
2408                         /* this is weak still, should be done delayed as well */
2409                         for (ob = bmain->object.first; ob; ob = ob->id.next) {
2410                                 for (psys = ob->particlesystem.first; psys; psys = psys->next) {
2411                                         if (&psys->part->id == id) {
2412                                                 ob->recalc |= (flag & OB_RECALC_ALL);
2413                                                 psys->recalc |= (flag & PSYS_RECALC);
2414                                                 lib_id_recalc_tag(bmain, &ob->id);
2415                                                 lib_id_recalc_data_tag(bmain, &ob->id);
2416                                         }
2417                                 }
2418                         }
2419                 }
2420                 else if (idtype == ID_VF) {
2421                         /* this is weak still, should be done delayed as well */
2422                         for (ob = bmain->object.first; ob; ob = ob->id.next) {
2423                                 if (ob->type == OB_FONT) {
2424                                         Curve *cu = ob->data;
2425
2426                                         if (ELEM4((struct VFont *)id, cu->vfont, cu->vfontb, cu->vfonti, cu->vfontbi)) {
2427                                                 ob->recalc |= (flag & OB_RECALC_ALL);
2428                                         }
2429                                 }
2430                         }
2431                 }
2432                 else {
2433                         /* disable because this is called on various ID types automatically.
2434                          * where printing warning is not useful. for now just ignore */
2435                         /* BLI_assert(!"invalid flag for this 'idtype'"); */
2436                 }
2437         }
2438 }
2439
2440 void DAG_id_tag_update(ID *id, short flag)
2441 {
2442         DAG_id_tag_update_ex(G.main, id, flag);
2443 }
2444
2445 void DAG_id_type_tag(Main *bmain, short idtype)
2446 {
2447         if (idtype == ID_NT) {
2448                 /* stupid workaround so parent datablocks of nested nodetree get looped
2449                  * over when we loop over tagged datablock types */
2450                 DAG_id_type_tag(bmain, ID_MA);
2451                 DAG_id_type_tag(bmain, ID_TE);
2452                 DAG_id_type_tag(bmain, ID_LA);
2453                 DAG_id_type_tag(bmain, ID_WO);
2454                 DAG_id_type_tag(bmain, ID_SCE);
2455         }
2456
2457         bmain->id_tag_update[((char *)&idtype)[0]] = 1;
2458 }
2459
2460 int DAG_id_type_tagged(Main *bmain, short idtype)
2461 {
2462         return bmain->id_tag_update[((char *)&idtype)[0]];
2463 }
2464
2465 #if 0 // UNUSED
2466 /* recursively descends tree, each node only checked once */
2467 /* node is checked to be of type object */
2468 static int parent_check_node(DagNode *node, int curtime)
2469 {
2470         DagAdjList *itA;
2471         
2472         node->lasttime = curtime;
2473         
2474         if (node->color == DAG_GRAY)
2475                 return DAG_GRAY;
2476         
2477         for (itA = node->child; itA; itA = itA->next) {
2478                 if (itA->node->type == ID_OB) {
2479                         
2480                         if (itA->node->color == DAG_GRAY)
2481                                 return DAG_GRAY;
2482
2483                         /* descend if not done */
2484                         if (itA->node->lasttime != curtime) {
2485                                 itA->node->color = parent_check_node(itA->node, curtime);
2486                         
2487                                 if (itA->node->color == DAG_GRAY)
2488                                         return DAG_GRAY;
2489                         }
2490                 }
2491         }
2492         
2493         return DAG_WHITE;
2494 }
2495 #endif
2496
2497 /* ******************* DAG FOR ARMATURE POSE ***************** */
2498
2499 /* we assume its an armature with pose */
2500 void DAG_pose_sort(Object *ob)
2501 {
2502         bPose *pose = ob->pose;
2503         bPoseChannel *pchan;
2504         bConstraint *con;
2505         DagNode *node;
2506         DagNode *node2, *node3;
2507         DagNode *rootnode;
2508         DagForest *dag;
2509         DagNodeQueue *nqueue;
2510         DagAdjList *itA;
2511         ListBase tempbase;
2512         int skip = 0;
2513         
2514         dag = dag_init();
2515         ugly_hack_sorry = 0;  /* no ID structs */
2516
2517         rootnode = dag_add_node(dag, NULL);  /* node->ob becomes NULL */
2518         
2519         /* we add the hierarchy and the constraints */
2520         for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
2521                 int addtoroot = 1;
2522                 
2523                 node = dag_get_node(dag, pchan);
2524                 
2525                 if (pchan->parent) {
2526                         node2 = dag_get_node(dag, pchan->parent);
2527                         dag_add_relation(dag, node2, node, 0, "Parent Relation");
2528                         addtoroot = 0;
2529                 }
2530                 for (con = pchan->constraints.first; con; con = con->next) {
2531                         bConstraintTypeInfo *cti = BKE_constraint_get_typeinfo(con);
2532                         ListBase targets = {NULL, NULL};
2533                         bConstraintTarget *ct;
2534                         
2535                         if (cti && cti->get_constraint_targets) {
2536                                 cti->get_constraint_targets(con, &targets);
2537                                 
2538                                 for (ct = targets.first; ct; ct = ct->next) {
2539                                         if (ct->tar == ob && ct->subtarget[0]) {
2540                                                 bPoseChannel *target = BKE_pose_channel_find_name(ob->pose, ct->subtarget);
2541                                                 if (target) {
2542                                                         node2 = dag_get_node(dag, target);
2543                                                         dag_add_relation(dag, node2, node, 0, "Pose Constraint");
2544                                                         
2545                                                         if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
2546                                                                 bKinematicConstraint *data = (bKinematicConstraint *)con->data;
2547                                                                 bPoseChannel *parchan;
2548                                                                 int segcount = 0;
2549                                                                 
2550                                                                 /* exclude tip from chain? */
2551                                                                 if (!(data->flag & CONSTRAINT_IK_TIP))
2552                                                                         parchan = pchan->parent;
2553                                                                 else
2554                                                                         parchan = pchan;
2555                                                                 
2556                                                                 /* Walk to the chain's root */
2557                                                                 while (parchan) {
2558                                                                         node3 = dag_get_node(dag, parchan);
2559                                                                         dag_add_relation(dag, node2, node3, 0, "IK Constraint");
2560                                                                         
2561                                                                         segcount++;
2562                                                                         if (segcount == data->rootbone || segcount > 255) break;  /* 255 is weak */
2563                                                                         parchan = parchan->parent;
2564                                                                 }
2565                                                         }
2566                                                 }
2567                                         }
2568                                 }
2569                                 
2570                                 if (cti->flush_constraint_targets)
2571                                         cti->flush_constraint_targets(con, &targets, 1);
2572                         }
2573                 }
2574                 if (addtoroot == 1) {
2575                         dag_add_relation(dag, rootnode, node, 0, "Root Bone Relation");
2576                 }
2577         }
2578
2579         dag_check_cycle(dag);
2580         
2581         /* now we try to sort... */
2582         tempbase.first = tempbase.last = NULL;
2583
2584         nqueue = queue_create(DAGQUEUEALLOC);
2585         
2586         /* tag nodes unchecked */
2587         for (node = dag->DagNode.first; node; node = node->next)
2588                 node->color = DAG_WHITE;
2589         
2590         rootnode->color = DAG_GRAY;
2591         push_stack(nqueue, rootnode);  
2592         
2593         while (nqueue->count) {
2594                 
2595                 skip = 0;
2596                 node = get_top_node_queue(nqueue);
2597                 
2598                 itA = node->child;
2599                 while (itA != NULL) {
2600                         if (itA->node->color == DAG_WHITE) {
2601                                 itA->node->color = DAG_GRAY;
2602                                 push_stack(nqueue, itA->node);
2603                                 skip = 1;
2604                                 break;
2605                         }
2606                         itA = itA->next;
2607                 }
2608                 
2609                 if (!skip) {
2610                         if (node) {
2611                                 node = pop_queue(nqueue);
2612                                 if (node->ob == NULL)  /* we are done */
2613                                         break;
2614                                 node->color = DAG_BLACK;
2615                                 
2616                                 /* put node in new list */
2617                                 BLI_remlink(&pose->chanbase, node->ob);
2618                                 BLI_addhead(&tempbase, node->ob);
2619                         }
2620                 }
2621         }
2622         
2623         /* temporal correction for circular dependencies */
2624         while (pose->chanbase.first) {
2625                 pchan = pose->chanbase.first;
2626                 BLI_remlink(&pose->chanbase, pchan);
2627                 BLI_addhead(&tempbase, pchan);
2628
2629                 printf("cyclic %s\n", pchan->name);
2630         }
2631         
2632         pose->chanbase = tempbase;
2633         queue_delete(nqueue);
2634         
2635 //      printf("\nordered\n");
2636 //      for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
2637 //              printf(" %s\n", pchan->name);
2638 //      }
2639         
2640         free_forest(dag);
2641         MEM_freeN(dag);
2642         
2643         ugly_hack_sorry = 1;
2644 }
2645
2646 /* ************************ DAG DEBUGGING ********************* */
2647
2648 void DAG_print_dependencies(Main *bmain, Scene *scene, Object *ob)
2649 {
2650         /* utility for debugging dependencies */
2651         dag_print_dependencies = 1;
2652
2653         if (ob && (ob->mode & OB_MODE_POSE)) {
2654                 printf("\nDEPENDENCY RELATIONS for %s\n\n", ob->id.name + 2);
2655                 DAG_pose_sort(ob);
2656         }
2657         else {
2658                 printf("\nDEPENDENCY RELATIONS for %s\n\n", scene->id.name + 2);
2659                 DAG_scene_relations_rebuild(bmain, scene);
2660         }
2661         
2662         dag_print_dependencies = 0;
2663 }
2664