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