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