Depsgraph: Comb code to a better state all over
[blender.git] / source / blender / depsgraph / intern / builder / deg_builder_relations.cc
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) 2013 Blender Foundation.
19  * All rights reserved.
20  *
21  * Original Author: Joshua Leung
22  * Contributor(s): Based on original depsgraph.c code - Blender Foundation (2005-2013)
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/depsgraph/intern/builder/deg_builder_relations.cc
28  *  \ingroup depsgraph
29  *
30  * Methods for constructing depsgraph
31  */
32
33 #include "intern/builder/deg_builder_relations.h"
34
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <cstring>  /* required for STREQ later on. */
38
39 #include "MEM_guardedalloc.h"
40
41 #include "BLI_utildefines.h"
42 #include "BLI_blenlib.h"
43
44 extern "C" {
45 #include "DNA_action_types.h"
46 #include "DNA_anim_types.h"
47 #include "DNA_armature_types.h"
48 #include "DNA_camera_types.h"
49 #include "DNA_cachefile_types.h"
50 #include "DNA_collection_types.h"
51 #include "DNA_constraint_types.h"
52 #include "DNA_curve_types.h"
53 #include "DNA_effect_types.h"
54 #include "DNA_gpencil_types.h"
55 #include "DNA_key_types.h"
56 #include "DNA_lamp_types.h"
57 #include "DNA_material_types.h"
58 #include "DNA_mask_types.h"
59 #include "DNA_mesh_types.h"
60 #include "DNA_meta_types.h"
61 #include "DNA_movieclip_types.h"
62 #include "DNA_node_types.h"
63 #include "DNA_particle_types.h"
64 #include "DNA_lightprobe_types.h"
65 #include "DNA_object_types.h"
66 #include "DNA_rigidbody_types.h"
67 #include "DNA_scene_types.h"
68 #include "DNA_speaker_types.h"
69 #include "DNA_texture_types.h"
70 #include "DNA_world_types.h"
71 #include "DNA_object_force_types.h"
72
73 #include "BKE_action.h"
74 #include "BKE_armature.h"
75 #include "BKE_animsys.h"
76 #include "BKE_collection.h"
77 #include "BKE_constraint.h"
78 #include "BKE_curve.h"
79 #include "BKE_effect.h"
80 #include "BKE_collision.h"
81 #include "BKE_fcurve.h"
82 #include "BKE_key.h"
83 #include "BKE_material.h"
84 #include "BKE_mball.h"
85 #include "BKE_modifier.h"
86 #include "BKE_gpencil_modifier.h"
87 #include "BKE_node.h"
88 #include "BKE_object.h"
89 #include "BKE_particle.h"
90 #include "BKE_pointcache.h"
91 #include "BKE_rigidbody.h"
92 #include "BKE_shader_fx.h"
93 #include "BKE_shrinkwrap.h"
94 #include "BKE_sound.h"
95 #include "BKE_tracking.h"
96 #include "BKE_world.h"
97
98 #include "RNA_access.h"
99 #include "RNA_types.h"
100 } /* extern "C" */
101
102 #include "DEG_depsgraph.h"
103 #include "DEG_depsgraph_build.h"
104
105 #include "intern/builder/deg_builder.h"
106 #include "intern/builder/deg_builder_pchanmap.h"
107 #include "intern/debug/deg_debug.h"
108 #include "intern/depsgraph_tag.h"
109 #include "intern/depsgraph_physics.h"
110 #include "intern/eval/deg_eval_copy_on_write.h"
111
112 #include "intern/node/deg_node.h"
113 #include "intern/node/deg_node_component.h"
114 #include "intern/node/deg_node_id.h"
115 #include "intern/node/deg_node_operation.h"
116 #include "intern/node/deg_node_time.h"
117
118 #include "intern/depsgraph_type.h"
119
120 namespace DEG {
121
122 /* ***************** */
123 /* Relations Builder */
124
125 /* TODO(sergey): This is somewhat weak, but we don't want neither false-positive
126  * time dependencies nor special exceptions in the depsgraph evaluation.
127  */
128 static bool python_driver_depends_on_time(ChannelDriver *driver)
129 {
130         if (driver->expression[0] == '\0') {
131                 /* Empty expression depends on nothing. */
132                 return false;
133         }
134         if (strchr(driver->expression, '(') != NULL) {
135                 /* Function calls are considered dependent on a time. */
136                 return true;
137         }
138         if (strstr(driver->expression, "frame") != NULL) {
139                 /* Variable `frame` depends on time. */
140                 /* TODO(sergey): This is a bit weak, but not sure about better way of
141                  * handling this. */
142                 return true;
143         }
144         /* Possible indirect time relation s should be handled via variable
145          * targets. */
146         return false;
147 }
148
149 static bool particle_system_depends_on_time(ParticleSystem *psys)
150 {
151         ParticleSettings *part = psys->part;
152         /* Non-hair particles we always consider dependent on time. */
153         if (part->type != PART_HAIR) {
154                 return true;
155         }
156         /* Dynamics always depends on time. */
157         if (psys->flag & PSYS_HAIR_DYNAMICS) {
158                 return true;
159         }
160         /* TODO(sergey): Check what else makes hair dependent on time. */
161         return false;
162 }
163
164 static bool object_particles_depends_on_time(Object *object)
165 {
166         if (object->type != OB_MESH) {
167                 return false;
168         }
169         LISTBASE_FOREACH (ParticleSystem *, psys, &object->particlesystem) {
170                 if (particle_system_depends_on_time(psys)) {
171                         return true;
172                 }
173         }
174         return false;
175 }
176
177 static bool check_id_has_anim_component(ID *id)
178 {
179         AnimData *adt = BKE_animdata_from_id(id);
180         if (adt == NULL) {
181                 return false;
182         }
183         return (adt->action != NULL) ||
184                (!BLI_listbase_is_empty(&adt->nla_tracks));
185 }
186
187 static OperationCode bone_target_opcode(ID *target,
188                                               const char *subtarget,
189                                               ID *id,
190                                               const char *component_subdata,
191                                               RootPChanMap *root_map)
192 {
193         /* Same armature.  */
194         if (target == id) {
195                 /* Using "done" here breaks in-chain deps, while using
196                  * "ready" here breaks most production rigs instead.
197                  * So, we do a compromise here, and only do this when an
198                  * IK chain conflict may occur. */
199                 if (root_map->has_common_root(component_subdata, subtarget)) {
200                         return OperationCode::BONE_READY;
201                 }
202         }
203         return OperationCode::BONE_DONE;
204 }
205
206 static bool bone_has_segments(Object *object, const char *bone_name)
207 {
208         /* Proxies don't have BONE_SEGMENTS */
209         if (ID_IS_LINKED(object) && object->proxy_from != NULL) {
210                 return false;
211         }
212         /* Only B-Bones have segments. */
213         bPoseChannel *pchan = BKE_pose_channel_find_name(object->pose, bone_name);
214         return pchan && pchan->bone && pchan->bone->segments > 1;
215 }
216
217 /* **** General purpose functions ****  */
218
219 DepsgraphRelationBuilder::DepsgraphRelationBuilder(Main *bmain,
220                                                    Depsgraph *graph)
221     : bmain_(bmain),
222       graph_(graph),
223       scene_(NULL)
224 {
225 }
226
227 TimeSourceNode *DepsgraphRelationBuilder::get_node(
228         const TimeSourceKey &key) const
229 {
230         if (key.id) {
231                 /* XXX TODO */
232                 return NULL;
233         }
234         else {
235                 return graph_->time_source;
236         }
237 }
238
239 ComponentNode *DepsgraphRelationBuilder::get_node(
240         const ComponentKey &key) const
241 {
242         IDNode *id_node = graph_->find_id_node(key.id);
243         if (!id_node) {
244                 fprintf(stderr, "find_node component: Could not find ID %s\n",
245                         (key.id != NULL) ? key.id->name : "<null>");
246                 return NULL;
247         }
248
249         ComponentNode *node = id_node->find_component(key.type, key.name);
250         return node;
251 }
252
253 OperationNode *DepsgraphRelationBuilder::get_node(
254         const OperationKey &key) const
255 {
256         OperationNode *op_node = find_node(key);
257         if (op_node == NULL) {
258                 fprintf(stderr, "find_node_operation: Failed for (%s, '%s')\n",
259                         operationCodeAsString(key.opcode), key.name);
260         }
261         return op_node;
262 }
263
264 Node *DepsgraphRelationBuilder::get_node(const RNAPathKey &key) const
265 {
266         return graph_->find_node_from_pointer(&key.ptr, key.prop, key.source);
267 }
268
269 OperationNode *DepsgraphRelationBuilder::find_node(
270         const OperationKey &key) const
271 {
272         IDNode *id_node = graph_->find_id_node(key.id);
273         if (!id_node) {
274                 return NULL;
275         }
276         ComponentNode *comp_node = id_node->find_component(key.component_type,
277                                                                key.component_name);
278         if (!comp_node) {
279                 return NULL;
280         }
281         return comp_node->find_operation(key.opcode, key.name, key.name_tag);
282 }
283
284 bool DepsgraphRelationBuilder::has_node(const OperationKey &key) const
285 {
286         return find_node(key) != NULL;
287 }
288
289 void DepsgraphRelationBuilder::add_customdata_mask(Object *object, uint64_t mask)
290 {
291         if (mask != 0 && object != NULL && object->type == OB_MESH) {
292                 DEG::IDNode *id_node = graph_->find_id_node(&object->id);
293
294                 if (id_node == NULL) {
295                         BLI_assert(!"ID should always be valid");
296                 }
297                 else {
298                         id_node->customdata_mask |= mask;
299                 }
300         }
301 }
302
303 void DepsgraphRelationBuilder::add_special_eval_flag(ID *id, uint32_t flag)
304 {
305         DEG::IDNode *id_node = graph_->find_id_node(id);
306         if (id_node == NULL) {
307                 BLI_assert(!"ID should always be valid");
308         }
309         else {
310                 id_node->eval_flags |= flag;
311         }
312 }
313
314 Relation *DepsgraphRelationBuilder::add_time_relation(
315         TimeSourceNode *timesrc,
316         Node *node_to,
317         const char *description,
318         int flags)
319 {
320         if (timesrc && node_to) {
321                 return graph_->add_new_relation(
322                         timesrc, node_to, description, flags);
323         }
324         else {
325                 DEG_DEBUG_PRINTF((::Depsgraph *)graph_,
326                                  BUILD, "add_time_relation(%p = %s, %p = %s, %s) Failed\n",
327                                  timesrc,   (timesrc) ? timesrc->identifier().c_str() : "<None>",
328                                  node_to,   (node_to) ? node_to->identifier().c_str() : "<None>",
329                                  description);
330         }
331         return NULL;
332 }
333
334 Relation *DepsgraphRelationBuilder::add_operation_relation(
335         OperationNode *node_from,
336         OperationNode *node_to,
337         const char *description,
338         int flags)
339 {
340         if (node_from && node_to) {
341                 return graph_->add_new_relation(node_from,
342                                                 node_to,
343                                                 description,
344                                                 flags);
345         }
346         else {
347                 DEG_DEBUG_PRINTF((::Depsgraph *)graph_,
348                                  BUILD, "add_operation_relation(%p = %s, %p = %s, %s) Failed\n",
349                                  node_from, (node_from) ? node_from->identifier().c_str() : "<None>",
350                                  node_to,   (node_to)   ? node_to->identifier().c_str() : "<None>",
351                                  description);
352         }
353         return NULL;
354 }
355
356 void DepsgraphRelationBuilder::add_particle_collision_relations(
357         const OperationKey &key,
358         Object *object,
359         Collection *collection,
360         const char *name)
361 {
362         ListBase *relations = build_collision_relations(graph_, collection, eModifierType_Collision);
363
364         LISTBASE_FOREACH (CollisionRelation *, relation, relations) {
365                 if (relation->ob != object) {
366                         ComponentKey trf_key(&relation->ob->id, NodeType::TRANSFORM);
367                         add_relation(trf_key, key, name);
368
369                         ComponentKey coll_key(&relation->ob->id, NodeType::GEOMETRY);
370                         add_relation(coll_key, key, name);
371                 }
372         }
373 }
374
375 void DepsgraphRelationBuilder::add_particle_forcefield_relations(
376         const OperationKey &key,
377         Object *object,
378         ParticleSystem *psys,
379         EffectorWeights *eff,
380         bool add_absorption,
381         const char *name)
382 {
383         ListBase *relations = build_effector_relations(graph_, eff->group);
384
385         LISTBASE_FOREACH (EffectorRelation *, relation, relations) {
386                 if (relation->ob != object) {
387                         /* Relation to forcefield object, optionally including geometry. */
388                         ComponentKey eff_key(&relation->ob->id, NodeType::TRANSFORM);
389                         add_relation(eff_key, key, name);
390
391                         if (ELEM(relation->pd->shape, PFIELD_SHAPE_SURFACE, PFIELD_SHAPE_POINTS) ||
392                             relation->pd->forcefield == PFIELD_GUIDE)
393                         {
394                                 ComponentKey mod_key(&relation->ob->id, NodeType::GEOMETRY);
395                                 add_relation(mod_key, key, name);
396                         }
397
398                         /* Smoke flow relations. */
399                         if (relation->pd->forcefield == PFIELD_SMOKEFLOW && relation->pd->f_source) {
400                                 ComponentKey trf_key(&relation->pd->f_source->id,
401                                                      NodeType::TRANSFORM);
402                                 add_relation(trf_key, key, "Smoke Force Domain");
403                                 ComponentKey eff_key(&relation->pd->f_source->id,
404                                                      NodeType::GEOMETRY);
405                                 add_relation(eff_key, key, "Smoke Force Domain");
406                         }
407
408                         /* Absorption forces need collision relation. */
409                         if (add_absorption && (relation->pd->flag & PFIELD_VISIBILITY)) {
410                                 add_particle_collision_relations(key,
411                                                                  object,
412                                                                  NULL,
413                                                                  "Force Absorption");
414                         }
415                 }
416
417                 if (relation->psys) {
418                         if (relation->ob != object) {
419                                 ComponentKey eff_key(&relation->ob->id,
420                                                      NodeType::PARTICLE_SYSTEM);
421                                 add_relation(eff_key, key, name);
422                                 /* TODO: remove this when/if EVAL_PARTICLES is sufficient
423                                  * for up to date particles. */
424                                 ComponentKey mod_key(&relation->ob->id, NodeType::GEOMETRY);
425                                 add_relation(mod_key, key, name);
426                         }
427                         else if (relation->psys != psys) {
428                                 OperationKey eff_key(&relation->ob->id,
429                                                      NodeType::PARTICLE_SYSTEM,
430                                                      OperationCode::PARTICLE_SYSTEM_EVAL,
431                                                      relation->psys->name);
432                                 add_relation(eff_key, key, name);
433                         }
434                 }
435         }
436 }
437
438 Depsgraph *DepsgraphRelationBuilder::getGraph()
439 {
440         return graph_;
441 }
442
443 /* **** Functions to build relations between entities  **** */
444
445 void DepsgraphRelationBuilder::begin_build()
446 {
447 }
448
449 void DepsgraphRelationBuilder::build_id(ID *id)
450 {
451         if (id == NULL) {
452                 return;
453         }
454         switch (GS(id->name)) {
455                 case ID_AC:
456                         build_action((bAction *)id);
457                         break;
458                 case ID_AR:
459                         build_armature((bArmature *)id);
460                         break;
461                 case ID_CA:
462                         build_camera((Camera *)id);
463                         break;
464                 case ID_GR:
465                         build_collection(NULL, NULL, (Collection *)id);
466                         break;
467                 case ID_OB:
468                         build_object(NULL, (Object *)id);
469                         break;
470                 case ID_KE:
471                         build_shapekeys((Key *)id);
472                         break;
473                 case ID_LA:
474                         build_lamp((Lamp *)id);
475                         break;
476                 case ID_LP:
477                         build_lightprobe((LightProbe *)id);
478                         break;
479                 case ID_NT:
480                         build_nodetree((bNodeTree *)id);
481                         break;
482                 case ID_MA:
483                         build_material((Material *)id);
484                         break;
485                 case ID_TE:
486                         build_texture((Tex *)id);
487                         break;
488                 case ID_WO:
489                         build_world((World *)id);
490                         break;
491                 case ID_MSK:
492                         build_mask((Mask *)id);
493                         break;
494                 case ID_MC:
495                         build_movieclip((MovieClip *)id);
496                         break;
497                 case ID_ME:
498                 case ID_CU:
499                 case ID_MB:
500                 case ID_LT:
501                         build_object_data_geometry_datablock(id);
502                         break;
503                 case ID_SPK:
504                         build_speaker((Speaker *)id);
505                         break;
506                 case ID_TXT:
507                         /* Not a part of dependency graph. */
508                         break;
509                 case ID_CF:
510                         build_cachefile((CacheFile *)id);
511                         break;
512                 default:
513                         fprintf(stderr, "Unhandled ID %s\n", id->name);
514                         BLI_assert(!"Should never happen");
515                         break;
516         }
517 }
518
519 void DepsgraphRelationBuilder::build_collection(
520         LayerCollection *from_layer_collection,
521         Object *object,
522         Collection *collection)
523 {
524         if (from_layer_collection != NULL) {
525                 /* If we came from layer collection we don't go deeper, view layer
526                  * builder takes care of going deeper.
527                  *
528                  * NOTE: Do early output before tagging build as done, so possbile
529                  * subsequent builds from outside of the layer collection properly
530                  * recurses into all the nested objects and collections. */
531                 return;
532         }
533         const bool group_done = built_map_.checkIsBuiltAndTag(collection);
534         OperationKey object_transform_final_key(object != NULL ? &object->id : NULL,
535                                                 NodeType::TRANSFORM,
536                                                 OperationCode::TRANSFORM_FINAL);
537         ComponentKey duplicator_key(object != NULL ? &object->id : NULL,
538                                     NodeType::DUPLI);
539         if (!group_done) {
540                 LISTBASE_FOREACH (CollectionObject *, cob, &collection->gobject) {
541                         build_object(NULL, cob->ob);
542                 }
543                 LISTBASE_FOREACH (CollectionChild *, child, &collection->children) {
544                         build_collection(NULL, NULL, child->collection);
545                 }
546         }
547         if (object != NULL) {
548                 FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_BEGIN(collection, ob, graph_->mode)
549                 {
550                         ComponentKey dupli_transform_key(&ob->id, NodeType::TRANSFORM);
551                         add_relation(dupli_transform_key,
552                                      object_transform_final_key,
553                                      "Dupligroup");
554                         /* Hook to special component, to ensure proper visibility/evaluation
555                          * optimizations. */
556                         add_relation(dupli_transform_key, duplicator_key, "Dupligroup");
557                         const NodeType dupli_geometry_component_type =
558                                 geometry_tag_to_component(&ob->id);
559                         if (dupli_geometry_component_type != NodeType::UNDEFINED) {
560                                 ComponentKey dupli_geometry_component_key(
561                                         &ob->id, dupli_geometry_component_type);
562                                 add_relation(dupli_geometry_component_key,
563                                              duplicator_key,
564                                              "Dupligroup");
565                         }
566                 }
567                 FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_END;
568         }
569 }
570
571 void DepsgraphRelationBuilder::build_object(Base *base, Object *object)
572 {
573         if (built_map_.checkIsBuiltAndTag(object)) {
574                 if (base != NULL) {
575                         build_object_flags(base, object);
576                 }
577                 return;
578         }
579         /* Object Transforms */
580         OperationCode base_op = (object->parent) ? OperationCode::TRANSFORM_PARENT
581                                                        : OperationCode::TRANSFORM_LOCAL;
582         OperationKey base_op_key(&object->id, NodeType::TRANSFORM, base_op);
583         OperationKey local_transform_key(&object->id,
584                                          NodeType::TRANSFORM,
585                                          OperationCode::TRANSFORM_LOCAL);
586         OperationKey parent_transform_key(&object->id,
587                                           NodeType::TRANSFORM,
588                                           OperationCode::TRANSFORM_PARENT);
589         OperationKey final_transform_key(&object->id,
590                                          NodeType::TRANSFORM,
591                                          OperationCode::TRANSFORM_FINAL);
592         OperationKey ob_ubereval_key(&object->id,
593                                      NodeType::TRANSFORM,
594                                      OperationCode::TRANSFORM_OBJECT_UBEREVAL);
595         /* Various flags, flushing from bases/collections. */
596         build_object_flags(base, object);
597         /* Parenting. */
598         if (object->parent != NULL) {
599                 /* Make sure parent object's relations are built. */
600                 build_object(NULL, object->parent);
601                 /* Parent relationship. */
602                 build_object_parent(object);
603                 /* Local -> parent. */
604                 add_relation(local_transform_key,
605                              parent_transform_key,
606                              "ObLocal -> ObParent");
607         }
608         /* Modifiers. */
609         if (object->modifiers.first != NULL) {
610                 BuilderWalkUserData data;
611                 data.builder = this;
612                 modifiers_foreachIDLink(object, modifier_walk, &data);
613         }
614         /* Grease Pencil Modifiers. */
615         if (object->greasepencil_modifiers.first != NULL) {
616                 BuilderWalkUserData data;
617                 data.builder = this;
618                 BKE_gpencil_modifiers_foreachIDLink(object, modifier_walk, &data);
619         }
620         /* Shader FX. */
621         if (object->shader_fx.first != NULL) {
622                 BuilderWalkUserData data;
623                 data.builder = this;
624                 BKE_shaderfx_foreachIDLink(object, modifier_walk, &data);
625         }
626         /* Constraints. */
627         if (object->constraints.first != NULL) {
628                 BuilderWalkUserData data;
629                 data.builder = this;
630                 BKE_constraints_id_loop(&object->constraints, constraint_walk, &data);
631         }
632         /* Object constraints. */
633         if (object->constraints.first != NULL) {
634                 OperationKey constraint_key(&object->id,
635                                             NodeType::TRANSFORM,
636                                             OperationCode::TRANSFORM_CONSTRAINTS);
637                 /* Constraint relations. */
638                 build_constraints(&object->id,
639                                   NodeType::TRANSFORM,
640                                   "",
641                                   &object->constraints,
642                                   NULL);
643                 /* operation order */
644                 add_relation(base_op_key, constraint_key, "ObBase-> Constraint Stack");
645                 add_relation(constraint_key, final_transform_key, "ObConstraints -> Done");
646                 // XXX
647                 add_relation(constraint_key, ob_ubereval_key, "Temp Ubereval");
648                 add_relation(ob_ubereval_key, final_transform_key, "Temp Ubereval");
649         }
650         else {
651                 /* NOTE: Keep an eye here, we skip some relations here to "streamline"
652                  * dependencies and avoid transitive relations which causes overhead.
653                  * But once we get rid of uber eval node this will need reconsideration. */
654                 if (object->rigidbody_object == NULL) {
655                         /* Rigid body will hook up another node inbetween, so skip
656                          * relation here to avoid transitive relation. */
657                         add_relation(base_op_key, ob_ubereval_key, "Temp Ubereval");
658                 }
659                 add_relation(ob_ubereval_key, final_transform_key, "Temp Ubereval");
660         }
661         /* Animation data */
662         build_animdata(&object->id);
663         /* Object data. */
664         build_object_data(object);
665         /* Particle systems. */
666         if (object->particlesystem.first != NULL) {
667                 build_particle_systems(object);
668         }
669         /* Proxy object to copy from. */
670         if (object->proxy_from != NULL) {
671                 build_object(NULL, object->proxy_from);
672                 ComponentKey ob_transform_key(&object->proxy_from->id, NodeType::TRANSFORM);
673                 ComponentKey proxy_transform_key(&object->id, NodeType::TRANSFORM);
674                 add_relation(ob_transform_key, proxy_transform_key, "Proxy Transform");
675         }
676         if (object->proxy_group != NULL) {
677                 build_object(NULL, object->proxy_group);
678                 OperationKey proxy_group_ubereval_key(&object->proxy_group->id,
679                                                       NodeType::TRANSFORM,
680                                                       OperationCode::TRANSFORM_OBJECT_UBEREVAL);
681                 add_relation(proxy_group_ubereval_key, final_transform_key, "Proxy Group Transform");
682         }
683         /* Object dupligroup. */
684         if (object->dup_group != NULL) {
685                 build_collection(NULL, object, object->dup_group);
686         }
687         /* Point caches. */
688         build_object_pointcache(object);
689         /* Syncronization back to original object. */
690         OperationKey synchronize_key(&object->id,
691                                      NodeType::SYNCHRONIZE,
692                                      OperationCode::SYNCHRONIZE_TO_ORIGINAL);
693         add_relation(
694                 final_transform_key, synchronize_key, "Synchronize to Original");
695 }
696
697 void DepsgraphRelationBuilder::build_object_flags(Base *base, Object *object)
698 {
699         if (base == NULL) {
700                 return;
701         }
702         OperationKey view_layer_done_key(&scene_->id,
703                                          NodeType::LAYER_COLLECTIONS,
704                                          OperationCode::VIEW_LAYER_EVAL);
705         OperationKey object_flags_key(&object->id,
706                                       NodeType::OBJECT_FROM_LAYER,
707                                       OperationCode::OBJECT_BASE_FLAGS);
708         add_relation(view_layer_done_key, object_flags_key, "Base flags flush");
709         /* Syncronization back to original object. */
710         OperationKey synchronize_key(&object->id,
711                                      NodeType::SYNCHRONIZE,
712                                      OperationCode::SYNCHRONIZE_TO_ORIGINAL);
713         add_relation(
714                 object_flags_key, synchronize_key, "Synchronize to Original");
715 }
716
717 void DepsgraphRelationBuilder::build_object_data(Object *object)
718 {
719         if (object->data == NULL) {
720                 return;
721         }
722         ID *obdata_id = (ID *)object->data;
723         /* Object data animation. */
724         if (!built_map_.checkIsBuilt(obdata_id)) {
725                 build_animdata(obdata_id);
726         }
727         /* type-specific data. */
728         switch (object->type) {
729                 case OB_MESH:
730                 case OB_CURVE:
731                 case OB_FONT:
732                 case OB_SURF:
733                 case OB_MBALL:
734                 case OB_LATTICE:
735                 case OB_GPENCIL:
736                 {
737                         build_object_data_geometry(object);
738                         /* TODO(sergey): Only for until we support granular
739                          * update of curves. */
740                         if (object->type == OB_FONT) {
741                                 Curve *curve = (Curve *)object->data;
742                                 if (curve->textoncurve) {
743                                         add_special_eval_flag(&curve->textoncurve->id, DAG_EVAL_NEED_CURVE_PATH);
744                                 }
745                         }
746                         break;
747                 }
748                 case OB_ARMATURE:
749                         if (ID_IS_LINKED(object) && object->proxy_from != NULL) {
750                                 build_proxy_rig(object);
751                         }
752                         else {
753                                  build_rig(object);
754                         }
755                         break;
756                 case OB_LAMP:
757                         build_object_data_lamp(object);
758                         break;
759                 case OB_CAMERA:
760                         build_object_data_camera(object);
761                         break;
762                 case OB_LIGHTPROBE:
763                         build_object_data_lightprobe(object);
764                         break;
765                 case OB_SPEAKER:
766                         build_object_data_speaker(object);
767                         break;
768         }
769         Key *key = BKE_key_from_object(object);
770         if (key != NULL) {
771                 ComponentKey geometry_key((ID *)object->data, NodeType::GEOMETRY);
772                 ComponentKey key_key(&key->id, NodeType::GEOMETRY);
773                 add_relation(key_key, geometry_key, "Shapekeys");
774                 build_nested_shapekey(&object->id, key);
775         }
776 }
777
778 void DepsgraphRelationBuilder::build_object_data_camera(Object *object)
779 {
780         Camera *camera = (Camera *)object->data;
781         build_camera(camera);
782         ComponentKey object_parameters_key(&object->id, NodeType::PARAMETERS);
783         ComponentKey camera_parameters_key(&camera->id, NodeType::PARAMETERS);
784         add_relation(camera_parameters_key, object_parameters_key, "Camera -> Object");
785 }
786
787 void DepsgraphRelationBuilder::build_object_data_lamp(Object *object)
788 {
789         Lamp *lamp = (Lamp *)object->data;
790         build_lamp(lamp);
791         ComponentKey object_parameters_key(&object->id, NodeType::PARAMETERS);
792         ComponentKey lamp_parameters_key(&lamp->id, NodeType::PARAMETERS);
793         add_relation(lamp_parameters_key, object_parameters_key, "Light -> Object");
794 }
795
796 void DepsgraphRelationBuilder::build_object_data_lightprobe(Object *object)
797 {
798         LightProbe *probe = (LightProbe *)object->data;
799         build_lightprobe(probe);
800         OperationKey probe_key(&probe->id,
801                                NodeType::PARAMETERS,
802                                OperationCode::LIGHT_PROBE_EVAL);
803         OperationKey object_key(&object->id,
804                                 NodeType::PARAMETERS,
805                                 OperationCode::LIGHT_PROBE_EVAL);
806         add_relation(probe_key, object_key, "LightProbe Update");
807 }
808
809 void DepsgraphRelationBuilder::build_object_data_speaker(Object *object)
810 {
811         Speaker *speaker = (Speaker *)object->data;
812         build_speaker(speaker);
813         OperationKey probe_key(&speaker->id,
814                                NodeType::PARAMETERS,
815                                OperationCode::SPEAKER_EVAL);
816         OperationKey object_key(&object->id,
817                                 NodeType::PARAMETERS,
818                                 OperationCode::SPEAKER_EVAL);
819         add_relation(probe_key, object_key, "Speaker Update");
820 }
821
822 void DepsgraphRelationBuilder::build_object_parent(Object *object)
823 {
824         /* XXX: for now, need to use the component key (not just direct to the parent op),
825          * or else the matrix doesn't get reset. */
826         // XXX: @sergey - it would be good if we got that backwards flushing working
827         // when tagging for updates.
828         //OperationKey ob_key(&object->id, NodeType::TRANSFORM, OperationCode::TRANSFORM_PARENT);
829         ComponentKey ob_key(&object->id, NodeType::TRANSFORM);
830
831         /* type-specific links */
832         switch (object->partype) {
833                 case PARSKEL:  /* Armature Deform (Virtual Modifier) */
834                 {
835                         ComponentKey parent_key(&object->parent->id, NodeType::TRANSFORM);
836                         add_relation(parent_key, ob_key, "Armature Deform Parent");
837                         break;
838                 }
839
840                 case PARVERT1: /* Vertex Parent */
841                 case PARVERT3:
842                 {
843                         ComponentKey parent_key(&object->parent->id, NodeType::GEOMETRY);
844                         add_relation(parent_key, ob_key, "Vertex Parent");
845
846                         /* XXX not sure what this is for or how you could be done properly - lukas */
847                         add_customdata_mask(object->parent, CD_MASK_ORIGINDEX);
848
849                         ComponentKey transform_key(&object->parent->id, NodeType::TRANSFORM);
850                         add_relation(transform_key, ob_key, "Vertex Parent TFM");
851                         break;
852                 }
853
854                 case PARBONE: /* Bone Parent */
855                 {
856                         ComponentKey parent_bone_key(&object->parent->id,
857                                                      NodeType::BONE,
858                                                      object->parsubstr);
859                         OperationKey parent_transform_key(&object->parent->id,
860                                                           NodeType::TRANSFORM,
861                                                           OperationCode::TRANSFORM_FINAL);
862                         add_relation(parent_bone_key, ob_key, "Bone Parent");
863                         add_relation(parent_transform_key, ob_key, "Armature Parent");
864                         break;
865                 }
866
867                 default:
868                 {
869                         if (object->parent->type == OB_LATTICE) {
870                                 /* Lattice Deform Parent - Virtual Modifier */
871                                 // XXX: no virtual modifiers should be left!
872                                 ComponentKey parent_key(&object->parent->id, NodeType::TRANSFORM);
873                                 ComponentKey geom_key(&object->parent->id, NodeType::GEOMETRY);
874
875                                 add_relation(parent_key, ob_key, "Lattice Deform Parent");
876                                 add_relation(geom_key, ob_key, "Lattice Deform Parent Geom");
877                         }
878                         else if (object->parent->type == OB_CURVE) {
879                                 Curve *cu = (Curve *)object->parent->data;
880
881                                 if (cu->flag & CU_PATH) {
882                                         /* Follow Path */
883                                         ComponentKey parent_key(&object->parent->id, NodeType::GEOMETRY);
884                                         add_relation(parent_key, ob_key, "Curve Follow Parent");
885
886                                         ComponentKey transform_key(&object->parent->id, NodeType::TRANSFORM);
887                                         add_relation(transform_key, ob_key, "Curve Follow TFM");
888                                 }
889                                 else {
890                                         /* Standard Parent */
891                                         ComponentKey parent_key(&object->parent->id, NodeType::TRANSFORM);
892                                         add_relation(parent_key, ob_key, "Curve Parent");
893                                 }
894                         }
895                         else {
896                                 /* Standard Parent */
897                                 ComponentKey parent_key(&object->parent->id, NodeType::TRANSFORM);
898                                 add_relation(parent_key, ob_key, "Parent");
899                         }
900                         break;
901                 }
902         }
903 }
904
905 void DepsgraphRelationBuilder::build_object_pointcache(Object *object)
906 {
907         ComponentKey point_cache_key(&object->id, NodeType::POINT_CACHE);
908         /* Different point caches are affecting different aspects of life of the
909          * object. We keep track of those aspects and avoid duplicate relations. */
910         enum {
911                 FLAG_TRANSFORM = (1 << 0),
912                 FLAG_GEOMETRY = (1 << 1),
913                 FLAG_ALL = (FLAG_TRANSFORM | FLAG_GEOMETRY),
914         };
915         ListBase ptcache_id_list;
916         BKE_ptcache_ids_from_object(&ptcache_id_list, object, scene_, 0);
917         int handled_components = 0;
918         LISTBASE_FOREACH (PTCacheID *, ptcache_id, &ptcache_id_list) {
919                 /* Check which components needs the point cache. */
920                 int flag;
921                 if (ptcache_id->type == PTCACHE_TYPE_RIGIDBODY) {
922                         flag = FLAG_TRANSFORM;
923                         ComponentKey transform_key(&object->id,
924                                                    NodeType::TRANSFORM);
925                         add_relation(point_cache_key,
926                                      transform_key,
927                                      "Point Cache -> Rigid Body");
928                 }
929                 else {
930                         flag = FLAG_GEOMETRY;
931                         ComponentKey geometry_key(&object->id,
932                                                    NodeType::GEOMETRY);
933                         add_relation(point_cache_key,
934                                      geometry_key,
935                                      "Point Cache -> Geometry");
936                 }
937                 /* Tag that we did handle that component. */
938                 handled_components |= flag;
939                 if (handled_components == FLAG_ALL) {
940                         break;
941                 }
942         }
943         BLI_freelistN(&ptcache_id_list);
944 }
945
946 void DepsgraphRelationBuilder::build_constraints(ID *id,
947                                                  NodeType component_type,
948                                                  const char *component_subdata,
949                                                  ListBase *constraints,
950                                                  RootPChanMap *root_map)
951 {
952         OperationKey constraint_op_key(
953                 id,
954                 component_type,
955                 component_subdata,
956                 (component_type == NodeType::BONE)
957                         ? OperationCode::BONE_CONSTRAINTS
958                         : OperationCode::TRANSFORM_CONSTRAINTS);
959         /* Add dependencies for each constraint in turn. */
960         for (bConstraint *con = (bConstraint *)constraints->first; con; con = con->next) {
961                 const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
962                 /* Invalid constraint type. */
963                 if (cti == NULL) {
964                         continue;
965                 }
966                 /* Special case for camera tracking -- it doesn't use targets to
967                  * define relations. */
968                 /* TODO: we can now represent dependencies in a much richer manner,
969                  * so review how this is done.  */
970                 if (ELEM(cti->type,
971                          CONSTRAINT_TYPE_FOLLOWTRACK,
972                          CONSTRAINT_TYPE_CAMERASOLVER,
973                          CONSTRAINT_TYPE_OBJECTSOLVER))
974                 {
975                         bool depends_on_camera = false;
976                         if (cti->type == CONSTRAINT_TYPE_FOLLOWTRACK) {
977                                 bFollowTrackConstraint *data = (bFollowTrackConstraint *)con->data;
978                                 if (((data->clip) ||
979                                      (data->flag & FOLLOWTRACK_ACTIVECLIP)) && data->track[0])
980                                 {
981                                         depends_on_camera = true;
982                                 }
983                                 if (data->depth_ob) {
984                                         ComponentKey depth_transform_key(&data->depth_ob->id,
985                                                                          NodeType::TRANSFORM);
986                                         ComponentKey depth_geometry_key(&data->depth_ob->id,
987                                                                         NodeType::GEOMETRY);
988                                         add_relation(depth_transform_key, constraint_op_key, cti->name);
989                                         add_relation(depth_geometry_key, constraint_op_key, cti->name);
990                                 }
991                         }
992                         else if (cti->type == CONSTRAINT_TYPE_OBJECTSOLVER) {
993                                 depends_on_camera = true;
994                         }
995                         if (depends_on_camera && scene_->camera != NULL) {
996                                 ComponentKey camera_key(&scene_->camera->id, NodeType::TRANSFORM);
997                                 add_relation(camera_key, constraint_op_key, cti->name);
998                         }
999                         /* TODO(sergey): This is more a TimeSource -> MovieClip ->
1000                          * Constraint dependency chain. */
1001                         TimeSourceKey time_src_key;
1002                         add_relation(time_src_key, constraint_op_key, "TimeSrc -> Animation");
1003                 }
1004                 else if (cti->type == CONSTRAINT_TYPE_TRANSFORM_CACHE) {
1005                         /* TODO(kevin): This is more a TimeSource -> CacheFile -> Constraint
1006                          * dependency chain. */
1007                         TimeSourceKey time_src_key;
1008                         add_relation(time_src_key, constraint_op_key, "TimeSrc -> Animation");
1009                         bTransformCacheConstraint *data = (bTransformCacheConstraint *)con->data;
1010                         if (data->cache_file) {
1011                                 ComponentKey cache_key(&data->cache_file->id, NodeType::CACHE);
1012                                 add_relation(cache_key, constraint_op_key, cti->name);
1013                         }
1014                 }
1015                 else if (cti->get_constraint_targets) {
1016                         ListBase targets = {NULL, NULL};
1017                         cti->get_constraint_targets(con, &targets);
1018                         LISTBASE_FOREACH (bConstraintTarget *, ct, &targets) {
1019                                 if (ct->tar == NULL) {
1020                                         continue;
1021                                 }
1022                                 if (ELEM(con->type,
1023                                          CONSTRAINT_TYPE_KINEMATIC,
1024                                          CONSTRAINT_TYPE_SPLINEIK))
1025                                 {
1026                                         /* Ignore IK constraints - these are handled separately
1027                                          * (on pose level). */
1028                                 }
1029                                 else if (ELEM(con->type,
1030                                               CONSTRAINT_TYPE_FOLLOWPATH,
1031                                               CONSTRAINT_TYPE_CLAMPTO))
1032                                 {
1033                                         /* These constraints require path geometry data. */
1034                                         ComponentKey target_key(&ct->tar->id, NodeType::GEOMETRY);
1035                                         add_relation(target_key, constraint_op_key, cti->name);
1036                                         ComponentKey target_transform_key(&ct->tar->id,
1037                                                                           NodeType::TRANSFORM);
1038                                         add_relation(target_transform_key, constraint_op_key, cti->name);
1039                                 }
1040                                 else if ((ct->tar->type == OB_ARMATURE) && (ct->subtarget[0])) {
1041                                         OperationCode opcode;
1042                                         /* relation to bone */
1043                                         opcode = bone_target_opcode(&ct->tar->id, ct->subtarget,
1044                                                                     id, component_subdata, root_map);
1045                                         /* Armature constraint always wants the final position and chan_mat. */
1046                                         if (ELEM(con->type, CONSTRAINT_TYPE_ARMATURE)) {
1047                                                 opcode = OperationCode::BONE_DONE;
1048                                         }
1049                                         /* if needs bbone shape, reference the segment computation */
1050                                         if (BKE_constraint_target_uses_bbone(con, ct) &&
1051                                             bone_has_segments(ct->tar, ct->subtarget))
1052                                         {
1053                                                 opcode = OperationCode::BONE_SEGMENTS;
1054                                         }
1055                                         OperationKey target_key(&ct->tar->id,
1056                                                                 NodeType::BONE,
1057                                                                 ct->subtarget,
1058                                                                 opcode);
1059                                         add_relation(target_key, constraint_op_key, cti->name);
1060                                 }
1061                                 else if (ELEM(ct->tar->type, OB_MESH, OB_LATTICE) &&
1062                                          (ct->subtarget[0]))
1063                                 {
1064                                         /* Vertex group. */
1065                                         /* NOTE: for now, we don't need to represent vertex groups
1066                                          * separately. */
1067                                         ComponentKey target_key(&ct->tar->id, NodeType::GEOMETRY);
1068                                         add_relation(target_key, constraint_op_key, cti->name);
1069                                         add_customdata_mask(ct->tar, CD_MASK_MDEFORMVERT);
1070                                 }
1071                                 else if (con->type == CONSTRAINT_TYPE_SHRINKWRAP) {
1072                                         bShrinkwrapConstraint *scon = (bShrinkwrapConstraint *) con->data;
1073
1074                                         /* Constraints which requires the target object surface. */
1075                                         ComponentKey target_key(&ct->tar->id, NodeType::GEOMETRY);
1076                                         add_relation(target_key, constraint_op_key, cti->name);
1077
1078                                         /* Add dependency on normal layers if necessary. */
1079                                         if (ct->tar->type == OB_MESH && scon->shrinkType != MOD_SHRINKWRAP_NEAREST_VERTEX) {
1080                                                 bool track = (scon->flag & CON_SHRINKWRAP_TRACK_NORMAL) != 0;
1081                                                 if (track || BKE_shrinkwrap_needs_normals(scon->shrinkType, scon->shrinkMode)) {
1082                                                         add_customdata_mask(ct->tar, CD_MASK_NORMAL | CD_MASK_CUSTOMLOOPNORMAL);
1083                                                 }
1084                                                 if (scon->shrinkType == MOD_SHRINKWRAP_TARGET_PROJECT) {
1085                                                         add_special_eval_flag(&ct->tar->id, DAG_EVAL_NEED_SHRINKWRAP_BOUNDARY);
1086                                                 }
1087                                         }
1088
1089                                         /* NOTE: obdata eval now doesn't necessarily depend on the
1090                                          * object's transform. */
1091                                         ComponentKey target_transform_key(&ct->tar->id,
1092                                                                           NodeType::TRANSFORM);
1093                                         add_relation(target_transform_key, constraint_op_key, cti->name);
1094                                 }
1095                                 else {
1096                                         /* Standard object relation. */
1097                                         // TODO: loc vs rot vs scale?
1098                                         if (&ct->tar->id == id) {
1099                                                 /* Constraint targeting own object:
1100                                                  * - This case is fine IFF we're dealing with a bone
1101                                                  *   constraint pointing to its own armature. In that
1102                                                  *   case, it's just transform -> bone.
1103                                                  * - If however it is a real self targeting case, just
1104                                                  *   make it depend on the previous constraint (or the
1105                                                  *   pre-constraint state). */
1106                                                 if ((ct->tar->type == OB_ARMATURE) &&
1107                                                     (component_type == NodeType::BONE))
1108                                                 {
1109                                                         OperationKey target_key(&ct->tar->id,
1110                                                                                 NodeType::TRANSFORM,
1111                                                                                 OperationCode::TRANSFORM_FINAL);
1112                                                         add_relation(target_key, constraint_op_key, cti->name);
1113                                                 }
1114                                                 else {
1115                                                         OperationKey target_key(&ct->tar->id,
1116                                                                                 NodeType::TRANSFORM,
1117                                                                                 OperationCode::TRANSFORM_LOCAL);
1118                                                         add_relation(target_key, constraint_op_key, cti->name);
1119                                                 }
1120                                         }
1121                                         else {
1122                                                 /* Normal object dependency. */
1123                                                 OperationKey target_key(&ct->tar->id,
1124                                                                         NodeType::TRANSFORM,
1125                                                                         OperationCode::TRANSFORM_FINAL);
1126                                                 add_relation(target_key, constraint_op_key, cti->name);
1127                                         }
1128                                 }
1129                                 /* Constraints which needs world's matrix for transform.
1130                                  * TODO(sergey): More constraints here? */
1131                                 if (ELEM(con->type,
1132                                          CONSTRAINT_TYPE_ROTLIKE,
1133                                          CONSTRAINT_TYPE_SIZELIKE,
1134                                          CONSTRAINT_TYPE_LOCLIKE,
1135                                          CONSTRAINT_TYPE_TRANSLIKE))
1136                                 {
1137                                         /* TODO(sergey): Add used space check. */
1138                                         ComponentKey target_transform_key(&ct->tar->id,
1139                                                                           NodeType::TRANSFORM);
1140                                         add_relation(target_transform_key, constraint_op_key, cti->name);
1141                                 }
1142                         }
1143                         if (cti->flush_constraint_targets) {
1144                                 cti->flush_constraint_targets(con, &targets, 1);
1145                         }
1146                 }
1147         }
1148 }
1149
1150 void DepsgraphRelationBuilder::build_animdata(ID *id)
1151 {
1152         /* Animation curves and NLA. */
1153         build_animdata_curves(id);
1154         /* Drivers. */
1155         build_animdata_drivers(id);
1156 }
1157
1158 void DepsgraphRelationBuilder::build_animdata_curves(ID *id)
1159 {
1160         AnimData *adt = BKE_animdata_from_id(id);
1161         if (adt == NULL) {
1162                 return;
1163         }
1164         if (adt->action != NULL) {
1165                 build_action(adt->action);
1166         }
1167         if (adt->action == NULL && adt->nla_tracks.first == NULL) {
1168                 return;
1169         }
1170         /* Wire up dependency to time source. */
1171         ComponentKey adt_key(id, NodeType::ANIMATION);
1172         /* Relation from action itself. */
1173         if (adt->action != NULL) {
1174                 ComponentKey action_key(&adt->action->id, NodeType::ANIMATION);
1175                 add_relation(action_key, adt_key, "Action -> Animation");
1176         }
1177         /* Get source operations. */
1178         Node *node_from = get_node(adt_key);
1179         BLI_assert(node_from != NULL);
1180         if (node_from == NULL) {
1181                 return;
1182         }
1183         OperationNode *operation_from = node_from->get_exit_operation();
1184         BLI_assert(operation_from != NULL);
1185         /* Build relations from animation operation to properties it changes. */
1186         if (adt->action != NULL) {
1187                 build_animdata_curves_targets(id, adt_key,
1188                                       operation_from,
1189                                       &adt->action->curves);
1190         }
1191         LISTBASE_FOREACH(NlaTrack *, nlt, &adt->nla_tracks) {
1192                 build_animdata_nlastrip_targets(id, adt_key,
1193                                                 operation_from,
1194                                                 &nlt->strips);
1195         }
1196 }
1197
1198 void DepsgraphRelationBuilder::build_animdata_curves_targets(
1199         ID *id, ComponentKey &adt_key,
1200         OperationNode *operation_from,
1201         ListBase *curves)
1202 {
1203         /* Iterate over all curves and build relations. */
1204         PointerRNA id_ptr;
1205         RNA_id_pointer_create(id, &id_ptr);
1206         LISTBASE_FOREACH(FCurve *, fcu, curves) {
1207                 PointerRNA ptr;
1208                 PropertyRNA *prop;
1209                 int index;
1210                 if (!RNA_path_resolve_full(&id_ptr, fcu->rna_path,
1211                                            &ptr, &prop, &index))
1212                 {
1213                         continue;
1214                 }
1215                 Node *node_to = graph_->find_node_from_pointer(
1216                         &ptr, prop, RNAPointerSource::ENTRY);
1217                 if (node_to == NULL) {
1218                         continue;
1219                 }
1220                 OperationNode *operation_to = node_to->get_entry_operation();
1221                 /* NOTE: Special case for bones, avoid relation from animation to
1222                  * each of the bones. Bone evaluation could only start from pose
1223                  * init anyway. */
1224                 if (operation_to->opcode == OperationCode::BONE_LOCAL) {
1225                         OperationKey pose_init_key(id,
1226                                                    NodeType::EVAL_POSE,
1227                                                    OperationCode::POSE_INIT);
1228                         add_relation(adt_key,
1229                                      pose_init_key,
1230                                      "Animation -> Prop",
1231                                      RELATION_CHECK_BEFORE_ADD);
1232                         continue;
1233                 }
1234                 graph_->add_new_relation(operation_from, operation_to,
1235                                          "Animation -> Prop",
1236                                          RELATION_CHECK_BEFORE_ADD);
1237                 /* It is possible that animation is writing to a nested ID datablock,
1238                  * need to make sure animation is evaluated after target ID is copied. */
1239                 const IDNode *id_node_from = operation_from->owner->owner;
1240                 const IDNode *id_node_to = operation_to->owner->owner;
1241                 if (id_node_from != id_node_to) {
1242                         ComponentKey cow_key(id_node_to->id_orig,
1243                                              NodeType::COPY_ON_WRITE);
1244                         add_relation(cow_key,
1245                                      adt_key,
1246                                      "Animated CoW -> Animation",
1247                                      RELATION_CHECK_BEFORE_ADD);
1248                 }
1249         }
1250 }
1251
1252 void DepsgraphRelationBuilder::build_animdata_nlastrip_targets(
1253         ID *id, ComponentKey &adt_key,
1254         OperationNode *operation_from,
1255         ListBase *strips)
1256 {
1257         LISTBASE_FOREACH(NlaStrip *, strip, strips) {
1258                 if (strip->act != NULL) {
1259                         build_action(strip->act);
1260
1261                         ComponentKey action_key(&strip->act->id, NodeType::ANIMATION);
1262                         add_relation(action_key, adt_key, "Action -> Animation");
1263
1264                         build_animdata_curves_targets(id, adt_key,
1265                                                       operation_from,
1266                                                       &strip->act->curves);
1267                 }
1268                 else if (strip->strips.first != NULL) {
1269                         build_animdata_nlastrip_targets(id, adt_key,
1270                                                         operation_from,
1271                                                         &strip->strips);
1272                 }
1273         }
1274 }
1275
1276 void DepsgraphRelationBuilder::build_animdata_drivers(ID *id)
1277 {
1278         AnimData *adt = BKE_animdata_from_id(id);
1279         if (adt == NULL) {
1280                 return;
1281         }
1282         ComponentKey adt_key(id, NodeType::ANIMATION);
1283         LISTBASE_FOREACH (FCurve *, fcu, &adt->drivers) {
1284                 OperationKey driver_key(id,
1285                                         NodeType::PARAMETERS,
1286                                         OperationCode::DRIVER,
1287                                         fcu->rna_path ? fcu->rna_path : "",
1288                                         fcu->array_index);
1289
1290                 /* create the driver's relations to targets */
1291                 build_driver(id, fcu);
1292                 /* Special case for array drivers: we can not multithread them because
1293                  * of the way how they work internally: animation system will write the
1294                  * whole array back to RNA even when changing individual array value.
1295                  *
1296                  * Some tricky things here:
1297                  * - array_index is -1 for single channel drivers, meaning we only have
1298                  *   to do some magic when array_index is not -1.
1299                  * - We do relation from next array index to a previous one, so we don't
1300                  *   have to deal with array index 0.
1301                  *
1302                  * TODO(sergey): Avoid liner lookup somehow. */
1303                 if (fcu->array_index > 0) {
1304                         FCurve *fcu_prev = NULL;
1305                         LISTBASE_FOREACH (FCurve *, fcu_candidate, &adt->drivers) {
1306                                 /* Writing to different RNA paths is  */
1307                                 const char *rna_path = fcu->rna_path ? fcu->rna_path : "";
1308                                 if (!STREQ(fcu_candidate->rna_path, rna_path)) {
1309                                         continue;
1310                                 }
1311                                 /* We only do relation from previous fcurve to previous one. */
1312                                 if (fcu_candidate->array_index >= fcu->array_index) {
1313                                         continue;
1314                                 }
1315                                 /* Choose fcurve with highest possible array index. */
1316                                 if (fcu_prev == NULL ||
1317                                     fcu_candidate->array_index > fcu_prev->array_index)
1318                                 {
1319                                         fcu_prev = fcu_candidate;
1320                                 }
1321                         }
1322                         if (fcu_prev != NULL) {
1323                                 OperationKey prev_driver_key(id,
1324                                                              NodeType::PARAMETERS,
1325                                                              OperationCode::DRIVER,
1326                                                              fcu_prev->rna_path ? fcu_prev->rna_path : "",
1327                                                              fcu_prev->array_index);
1328                                 OperationKey driver_key(id,
1329                                                         NodeType::PARAMETERS,
1330                                                         OperationCode::DRIVER,
1331                                                         fcu->rna_path ? fcu->rna_path : "",
1332                                                         fcu->array_index);
1333                                 add_relation(prev_driver_key, driver_key, "Driver Order");
1334                         }
1335                 }
1336
1337                 /* prevent driver from occurring before own animation... */
1338                 if (adt->action || adt->nla_tracks.first) {
1339                         add_relation(adt_key, driver_key, "AnimData Before Drivers");
1340                 }
1341         }
1342 }
1343
1344 void DepsgraphRelationBuilder::build_action(bAction *action)
1345 {
1346         if (built_map_.checkIsBuiltAndTag(action)) {
1347                 return;
1348         }
1349         TimeSourceKey time_src_key;
1350         ComponentKey animation_key(&action->id, NodeType::ANIMATION);
1351         add_relation(time_src_key, animation_key, "TimeSrc -> Animation");
1352 }
1353
1354 void DepsgraphRelationBuilder::build_driver(ID *id, FCurve *fcu)
1355 {
1356         ChannelDriver *driver = fcu->driver;
1357         OperationKey driver_key(id,
1358                                 NodeType::PARAMETERS,
1359                                 OperationCode::DRIVER,
1360                                 fcu->rna_path ? fcu->rna_path : "",
1361                                 fcu->array_index);
1362         /* Driver -> data components (for interleaved evaluation
1363          * bones/constraints/modifiers). */
1364         build_driver_data(id, fcu);
1365         /* Loop over variables to get the target relationships. */
1366         build_driver_variables(id, fcu);
1367         /* It's quite tricky to detect if the driver actually depends on time or
1368          * not, so for now we'll be quite conservative here about optimization and
1369          * consider all python drivers to be depending on time. */
1370         if ((driver->type == DRIVER_TYPE_PYTHON) &&
1371             python_driver_depends_on_time(driver))
1372         {
1373                 TimeSourceKey time_src_key;
1374                 add_relation(time_src_key, driver_key, "TimeSrc -> Driver");
1375         }
1376 }
1377
1378 void DepsgraphRelationBuilder::build_driver_data(ID *id, FCurve *fcu)
1379 {
1380         OperationKey driver_key(id,
1381                                 NodeType::PARAMETERS,
1382                                 OperationCode::DRIVER,
1383                                 fcu->rna_path ? fcu->rna_path : "",
1384                                 fcu->array_index);
1385         const char *rna_path = fcu->rna_path ? fcu->rna_path : "";
1386         if (GS(id->name) == ID_AR && strstr(rna_path, "bones[")) {
1387                 /* Drivers on armature-level bone settings (i.e. bbone stuff),
1388                  * which will affect the evaluation of corresponding pose bones. */
1389                 IDNode *arm_node = graph_->find_id_node(id);
1390                 char *bone_name = BLI_str_quoted_substrN(rna_path, "bones[");
1391                 if (arm_node != NULL && bone_name != NULL) {
1392                         /* Find objects which use this, and make their eval callbacks
1393                          * depend on this. */
1394                         for (Relation *rel : arm_node->outlinks) {
1395                                 IDNode *to_node = (IDNode *)rel->to;
1396                                 /* We only care about objects with pose data which use this. */
1397                                 if (GS(to_node->id_orig->name) == ID_OB) {
1398                                         Object *object = (Object *)to_node->id_orig;
1399                                         // NOTE: object->pose may be NULL
1400                                         bPoseChannel *pchan = BKE_pose_channel_find_name(object->pose,
1401                                                                                          bone_name);
1402                                         if (pchan != NULL) {
1403                                                 OperationKey bone_key(&object->id,
1404                                                                       NodeType::BONE,
1405                                                                       pchan->name,
1406                                                                       OperationCode::BONE_LOCAL);
1407                                                 add_relation(driver_key,
1408                                                              bone_key,
1409                                                              "Arm Bone -> Driver -> Bone");
1410                                         }
1411                                 }
1412                         }
1413                         /* Free temp data. */
1414                         MEM_freeN(bone_name);
1415                         bone_name = NULL;
1416                 }
1417                 else {
1418                         fprintf(stderr,
1419                                 "Couldn't find armature bone name for driver path - '%s'\n",
1420                                 rna_path);
1421                 }
1422         }
1423         else if (rna_path != NULL && rna_path[0] != '\0') {
1424                 RNAPathKey property_entry_key(id, rna_path, RNAPointerSource::ENTRY);
1425                 if (RNA_pointer_is_null(&property_entry_key.ptr)) {
1426                         /* TODO(sergey): This would only mean that driver is broken.
1427                          * so we can't create relation anyway. However, we need to avoid
1428                          * adding drivers which are known to be buggy to a dependency
1429                          * graph, in order to save computational power. */
1430                         return;
1431                 }
1432                 add_relation(
1433                         driver_key, property_entry_key, "Driver -> Driven Property");
1434                 /* Similar to the case with f-curves, driver might drive a nested
1435                  * datablock, which means driver execution should wait for that
1436                  * datablock to be copied. */
1437                 {
1438                         PointerRNA id_ptr;
1439                         PointerRNA ptr;
1440                         RNA_id_pointer_create(id, &id_ptr);
1441                         if (RNA_path_resolve_full(&id_ptr, fcu->rna_path, &ptr, NULL, NULL)) {
1442                                 if (id_ptr.id.data != ptr.id.data) {
1443                                         ComponentKey cow_key((ID *)ptr.id.data,
1444                                                              NodeType::COPY_ON_WRITE);
1445                                         add_relation(cow_key,
1446                                                      driver_key,
1447                                                      "Driven CoW -> Driver",
1448                                                      RELATION_CHECK_BEFORE_ADD);
1449                                 }
1450                         }
1451                 }
1452                 if (property_entry_key.prop != NULL &&
1453                     RNA_property_is_idprop(property_entry_key.prop))
1454                 {
1455                         RNAPathKey property_exit_key(id, rna_path, RNAPointerSource::EXIT);
1456                         OperationKey parameters_key(id,
1457                                                     NodeType::PARAMETERS,
1458                                                     OperationCode::PARAMETERS_EVAL);
1459                         add_relation(property_exit_key,
1460                                      parameters_key,
1461                                      "Driven Property -> Properties");
1462                 }
1463         }
1464 }
1465
1466 void DepsgraphRelationBuilder::build_driver_variables(ID *id, FCurve *fcu)
1467 {
1468         ChannelDriver *driver = fcu->driver;
1469         OperationKey driver_key(id,
1470                                 NodeType::PARAMETERS,
1471                                 OperationCode::DRIVER,
1472                                 fcu->rna_path ? fcu->rna_path : "",
1473                                 fcu->array_index);
1474         const char *rna_path = fcu->rna_path ? fcu->rna_path : "";
1475         const RNAPathKey self_key(id, rna_path, RNAPointerSource::ENTRY);
1476         LISTBASE_FOREACH (DriverVar *, dvar, &driver->variables) {
1477                 /* Only used targets. */
1478                 DRIVER_TARGETS_USED_LOOPER_BEGIN(dvar)
1479                 {
1480                         if (dtar->id == NULL) {
1481                                 continue;
1482                         }
1483                         build_id(dtar->id);
1484                         /* Initialize relations coming to proxy_from. */
1485                         Object *proxy_from = NULL;
1486                         if ((GS(dtar->id->name) == ID_OB) &&
1487                             (((Object *)dtar->id)->proxy_from != NULL))
1488                         {
1489                                 proxy_from = ((Object *)dtar->id)->proxy_from;
1490                                 build_id(&proxy_from->id);
1491                         }
1492                         /* Special handling for directly-named bones. */
1493                         if ((dtar->flag & DTAR_FLAG_STRUCT_REF) &&
1494                             (((Object *)dtar->id)->type == OB_ARMATURE) &&
1495                             (dtar->pchan_name[0]))
1496                         {
1497                                 Object *object = (Object *)dtar->id;
1498                                 bPoseChannel *target_pchan =
1499                                         BKE_pose_channel_find_name(object->pose,
1500                                                                    dtar->pchan_name);
1501                                 if (target_pchan == NULL) {
1502                                         continue;
1503                                 }
1504                                 OperationKey variable_key(dtar->id,
1505                                                           NodeType::BONE,
1506                                                           target_pchan->name,
1507                                                           OperationCode::BONE_DONE);
1508                                 if (is_same_bone_dependency(variable_key, self_key)) {
1509                                         continue;
1510                                 }
1511                                 add_relation(variable_key, driver_key, "Bone Target -> Driver");
1512                         }
1513                         else if (dtar->flag & DTAR_FLAG_STRUCT_REF) {
1514                                 /* Get node associated with the object's transforms. */
1515                                 if (dtar->id == id) {
1516                                         /* Ignore input dependency if we're driving properties of
1517                                          * the same ID, otherwise we'll be ending up in a cyclic
1518                                          * dependency here. */
1519                                         continue;
1520                                 }
1521                                 OperationKey target_key(dtar->id,
1522                                                         NodeType::TRANSFORM,
1523                                                         OperationCode::TRANSFORM_FINAL);
1524                                 add_relation(target_key, driver_key, "Target -> Driver");
1525                         }
1526                         else if (dtar->rna_path != NULL && dtar->rna_path[0] != '\0') {
1527                                 RNAPathKey variable_exit_key(
1528                                         dtar->id, dtar->rna_path, RNAPointerSource::EXIT);
1529                                 if (RNA_pointer_is_null(&variable_exit_key.ptr)) {
1530                                         continue;
1531                                 }
1532                                 if (is_same_bone_dependency(variable_exit_key, self_key) ||
1533                                     is_same_nodetree_node_dependency(variable_exit_key, self_key))
1534                                 {
1535                                         continue;
1536                                 }
1537                                 add_relation(variable_exit_key,
1538                                              driver_key,
1539                                              "RNA Target -> Driver");
1540                                 if (proxy_from != NULL) {
1541                                         RNAPathKey proxy_from_variable_key(&proxy_from->id,
1542                                                                            dtar->rna_path,
1543                                                                            RNAPointerSource::EXIT);
1544                                         RNAPathKey variable_entry_key(
1545                                                 dtar->id, dtar->rna_path, RNAPointerSource::ENTRY);
1546                                         add_relation(proxy_from_variable_key,
1547                                                      variable_entry_key,
1548                                                      "Proxy From -> Variable");
1549                                 }
1550                         }
1551                         else {
1552                                 /* If rna_path is NULL, and DTAR_FLAG_STRUCT_REF isn't set, this
1553                                  * is an incomplete target reference, so nothing to do here. */
1554                         }
1555                 }
1556                 DRIVER_TARGETS_LOOPER_END;
1557         }
1558 }
1559
1560 void DepsgraphRelationBuilder::build_world(World *world)
1561 {
1562         if (built_map_.checkIsBuiltAndTag(world)) {
1563                 return;
1564         }
1565         /* animation */
1566         build_animdata(&world->id);
1567         /* world's nodetree */
1568         if (world->nodetree != NULL) {
1569                 build_nodetree(world->nodetree);
1570                 OperationKey ntree_key(&world->nodetree->id,
1571                                        NodeType::SHADING,
1572                                        OperationCode::MATERIAL_UPDATE);
1573                 OperationKey world_key(&world->id,
1574                                           NodeType::SHADING,
1575                                           OperationCode::WORLD_UPDATE);
1576                 add_relation(ntree_key, world_key, "World's NTree");
1577                 build_nested_nodetree(&world->id, world->nodetree);
1578         }
1579 }
1580
1581 void DepsgraphRelationBuilder::build_rigidbody(Scene *scene)
1582 {
1583         RigidBodyWorld *rbw = scene->rigidbody_world;
1584
1585         OperationKey init_key(&scene->id, NodeType::TRANSFORM, OperationCode::RIGIDBODY_REBUILD);
1586         OperationKey sim_key(&scene->id, NodeType::TRANSFORM, OperationCode::RIGIDBODY_SIM);
1587
1588         /* rel between the two sim-nodes */
1589         add_relation(init_key, sim_key, "Rigidbody [Init -> SimStep]");
1590
1591         /* set up dependencies between these operations and other builtin nodes --------------- */
1592
1593         /* effectors */
1594         ListBase *relations = build_effector_relations(graph_, rbw->effector_weights->group);
1595         LISTBASE_FOREACH (EffectorRelation *, relation, relations) {
1596                 ComponentKey eff_key(&relation->ob->id, NodeType::TRANSFORM);
1597                 add_relation(eff_key, init_key, "RigidBody Field");
1598                 // FIXME add relations so pointache is marked as outdated when effectors are modified
1599         }
1600
1601         /* time dependency */
1602         TimeSourceKey time_src_key;
1603         add_relation(time_src_key, init_key, "TimeSrc -> Rigidbody Reset/Rebuild (Optional)");
1604
1605         /* objects - simulation participants */
1606         if (rbw->group != NULL) {
1607                 build_collection(NULL, NULL, rbw->group);
1608
1609                 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, object)
1610                 {
1611                         if (object->type != OB_MESH) {
1612                                 continue;
1613                         }
1614
1615                         /* hook up evaluation order...
1616                          * 1) flushing rigidbody results follows base transforms being applied
1617                          * 2) rigidbody flushing can only be performed after simulation has been run
1618                          *
1619                          * 3) simulation needs to know base transforms to figure out what to do
1620                          *    XXX: there's probably a difference between passive and active
1621                          *         - passive don't change, so may need to know full transform... */
1622                         OperationKey rbo_key(&object->id, NodeType::TRANSFORM, OperationCode::RIGIDBODY_TRANSFORM_COPY);
1623
1624                         OperationCode trans_opcode = object->parent ? OperationCode::TRANSFORM_PARENT : OperationCode::TRANSFORM_LOCAL;
1625                         OperationKey trans_op(&object->id, NodeType::TRANSFORM, trans_opcode);
1626
1627                         add_relation(sim_key, rbo_key, "Rigidbody Sim Eval -> RBO Sync");
1628
1629                         /* Geometry must be known to create the rigid body. RBO_MESH_BASE uses the non-evaluated
1630                          * mesh, so then the evaluation is unnecessary. */
1631                         if (object->rigidbody_object != NULL && object->rigidbody_object->mesh_source != RBO_MESH_BASE) {
1632                                 ComponentKey geom_key(&object->id, NodeType::GEOMETRY);
1633                                 add_relation(geom_key, init_key, "Object Geom Eval -> Rigidbody Rebuild");
1634                         }
1635
1636                         /* if constraints exist, those depend on the result of the rigidbody sim
1637                          * - This allows constraints to modify the result of the sim (i.e. clamping)
1638                          *   while still allowing the sim to depend on some changes to the objects.
1639                          *   Also, since constraints are hooked up to the final nodes, this link
1640                          *   means that we can also fit in there too...
1641                          * - Later, it might be good to include a constraint in the stack allowing us
1642                          *   to control whether rigidbody eval gets interleaved into the constraint stack */
1643                         if (object->constraints.first) {
1644                                 OperationKey constraint_key(&object->id,
1645                                                             NodeType::TRANSFORM,
1646                                                             OperationCode::TRANSFORM_CONSTRAINTS);
1647                                 add_relation(rbo_key, constraint_key, "RBO Sync -> Ob Constraints");
1648                         }
1649                         else {
1650                                 /* Final object transform depends on rigidbody.
1651                                  *
1652                                  * NOTE: Currently we consider final here an ubereval node.
1653                                  * If it is gone we'll need to reconsider relation here. */
1654                                 OperationKey uber_key(&object->id,
1655                                                       NodeType::TRANSFORM,
1656                                                       OperationCode::TRANSFORM_OBJECT_UBEREVAL);
1657                                 add_relation(rbo_key, uber_key, "RBO Sync -> Uber (Temp)");
1658                         }
1659
1660                         /* Needed to get correct base values. */
1661                         add_relation(trans_op, sim_key, "Base Ob Transform -> Rigidbody Sim Eval");
1662                 }
1663                 FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
1664         }
1665         /* Constraints. */
1666         if (rbw->constraints != NULL) {
1667                 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->constraints, object)
1668                 {
1669                         RigidBodyCon *rbc = object->rigidbody_constraint;
1670                         if (rbc == NULL || rbc->ob1 == NULL || rbc->ob2 == NULL) {
1671                                 /* When either ob1 or ob2 is NULL, the constraint doesn't work. */
1672                                 continue;
1673                         }
1674                         /* Make sure indirectly linked objects are fully built. */
1675                         build_object(NULL, object);
1676                         build_object(NULL, rbc->ob1);
1677                         build_object(NULL, rbc->ob2);
1678                         /* final result of the constraint object's transform controls how
1679                          * the constraint affects the physics sim for these objects. */
1680                         ComponentKey trans_key(&object->id, NodeType::TRANSFORM);
1681                         OperationKey ob1_key(&rbc->ob1->id, NodeType::TRANSFORM, OperationCode::RIGIDBODY_TRANSFORM_COPY);
1682                         OperationKey ob2_key(&rbc->ob2->id, NodeType::TRANSFORM, OperationCode::RIGIDBODY_TRANSFORM_COPY);
1683                         /* Constrained-objects sync depends on the constraint-holder. */
1684                         add_relation(trans_key, ob1_key, "RigidBodyConstraint -> RBC.Object_1");
1685                         add_relation(trans_key, ob2_key, "RigidBodyConstraint -> RBC.Object_2");
1686                         /* Ensure that sim depends on this constraint's transform. */
1687                         add_relation(trans_key, sim_key, "RigidBodyConstraint Transform -> RB Simulation");
1688                 }
1689                 FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
1690         }
1691 }
1692
1693 void DepsgraphRelationBuilder::build_particle_systems(Object *object)
1694 {
1695         TimeSourceKey time_src_key;
1696         OperationKey obdata_ubereval_key(&object->id,
1697                                          NodeType::GEOMETRY,
1698                                          OperationCode::GEOMETRY_UBEREVAL);
1699         OperationKey eval_init_key(&object->id,
1700                                    NodeType::PARTICLE_SYSTEM,
1701                                    OperationCode::PARTICLE_SYSTEM_INIT);
1702         OperationKey eval_done_key(&object->id,
1703                                    NodeType::PARTICLE_SYSTEM,
1704                                    OperationCode::PARTICLE_SYSTEM_DONE);
1705         ComponentKey eval_key(&object->id, NodeType::PARTICLE_SYSTEM);
1706         if (BKE_ptcache_object_has(scene_, object, 0)) {
1707                 ComponentKey point_cache_key(&object->id, NodeType::POINT_CACHE);
1708                 add_relation(eval_key, point_cache_key, "Particle Point Cache");
1709         }
1710         /* Particle systems. */
1711         LISTBASE_FOREACH (ParticleSystem *, psys, &object->particlesystem) {
1712                 ParticleSettings *part = psys->part;
1713                 /* Build particle settings relations.
1714                  * NOTE: The call itself ensures settings are only build once. */
1715                 build_particle_settings(part);
1716                 /* This particle system. */
1717                 OperationKey psys_key(&object->id,
1718                                       NodeType::PARTICLE_SYSTEM,
1719                                       OperationCode::PARTICLE_SYSTEM_EVAL,
1720                                       psys->name);
1721                 /* Update particle system when settings changes. */
1722                 OperationKey particle_settings_key(&part->id,
1723                                                    NodeType::PARTICLE_SETTINGS,
1724                                                    OperationCode::PARTICLE_SETTINGS_EVAL);
1725                 add_relation(particle_settings_key,
1726                              eval_init_key,
1727                              "Particle Settings Change");
1728                 add_relation(eval_init_key, psys_key, "Init -> PSys");
1729                 add_relation(psys_key, eval_done_key, "PSys -> Done");
1730                 /* TODO(sergey): Currently particle update is just a placeholder,
1731                  * hook it to the ubereval node so particle system is getting updated
1732                  * on playback. */
1733                 add_relation(psys_key, obdata_ubereval_key, "PSys -> UberEval");
1734                 /* Collisions. */
1735                 if (part->type != PART_HAIR) {
1736                         add_particle_collision_relations(psys_key,
1737                                                          object,
1738                                                          part->collision_group,
1739                                                          "Particle Collision");
1740                 }
1741                 else if ((psys->flag & PSYS_HAIR_DYNAMICS) &&
1742                           psys->clmd != NULL &&
1743                           psys->clmd->coll_parms != NULL)
1744                 {
1745                         add_particle_collision_relations(psys_key,
1746                                                          object,
1747                                                          psys->clmd->coll_parms->group,
1748                                                          "Hair Collision");
1749                 }
1750                 /* Effectors. */
1751                 add_particle_forcefield_relations(psys_key,
1752                                                   object,
1753                                                   psys,
1754                                                   part->effector_weights,
1755                                                   part->type == PART_HAIR,
1756                                                   "Particle Field");
1757                 /* Boids .*/
1758                 if (part->boids != NULL) {
1759                         LISTBASE_FOREACH (BoidState *, state, &part->boids->states) {
1760                                 LISTBASE_FOREACH (BoidRule *, rule, &state->rules) {
1761                                         Object *ruleob = NULL;
1762                                         if (rule->type == eBoidRuleType_Avoid) {
1763                                                 ruleob = ((BoidRuleGoalAvoid *)rule)->ob;
1764                                         }
1765                                         else if (rule->type == eBoidRuleType_FollowLeader) {
1766                                                 ruleob = ((BoidRuleFollowLeader *)rule)->ob;
1767                                         }
1768                                         if (ruleob != NULL) {
1769                                                 ComponentKey ruleob_key(&ruleob->id,
1770                                                                         NodeType::TRANSFORM);
1771                                                 add_relation(ruleob_key, psys_key, "Boid Rule");
1772                                         }
1773                                 }
1774                         }
1775                 }
1776                 /* Keyed particle targets. */
1777                 if (part->phystype == PART_PHYS_KEYED) {
1778                         LISTBASE_FOREACH (ParticleTarget *, particle_target, &psys->targets) {
1779                                 if (particle_target->ob == NULL ||
1780                                     particle_target->ob == object)
1781                                 {
1782                                         continue;
1783                                 }
1784                                 /* Make sure target object is pulled into the graph. */
1785                                 build_object(NULL, particle_target->ob);
1786                                 /* Use geometry component, since that's where particles are
1787                                  * actually evaluated. */
1788                                 ComponentKey target_key(&particle_target->ob->id,
1789                                                         NodeType::GEOMETRY);
1790                                 add_relation(target_key, psys_key, "Keyed Target");
1791                         }
1792                 }
1793                 /* Visualization. */
1794                 switch (part->ren_as) {
1795                         case PART_DRAW_OB:
1796                                 if (part->dup_ob != NULL) {
1797                                         /* Make sure object's relations are all built.  */
1798                                         build_object(NULL, part->dup_ob);
1799                                         /* Build relation for the particle visualization. */
1800                                         build_particle_system_visualization_object(
1801                                                 object,  psys, part->dup_ob);
1802                                 }
1803                                 break;
1804                         case PART_DRAW_GR:
1805                                 if (part->dup_group != NULL) {
1806                                         build_collection(NULL, NULL, part->dup_group);
1807                                         LISTBASE_FOREACH (CollectionObject *, go, &part->dup_group->gobject) {
1808                                                 build_particle_system_visualization_object(
1809                                                         object, psys, go->ob);
1810                                         }
1811                                 }
1812                                 break;
1813                 }
1814         }
1815         /* Particle depends on the object transform, so that channel is to be ready
1816          * first.
1817          *
1818          * TODO(sergey): This relation should be altered once real granular update
1819          * is implemented. */
1820         ComponentKey transform_key(&object->id, NodeType::TRANSFORM);
1821         add_relation(transform_key, obdata_ubereval_key, "Particle Eval");
1822 }
1823
1824 void DepsgraphRelationBuilder::build_particle_settings(ParticleSettings *part)
1825 {
1826         if (built_map_.checkIsBuiltAndTag(part)) {
1827                 return;
1828         }
1829         /* Animation data relations. */
1830         build_animdata(&part->id);
1831         OperationKey particle_settings_init_key(&part->id,
1832                                                 NodeType::PARTICLE_SETTINGS,
1833                                                 OperationCode::PARTICLE_SETTINGS_INIT);
1834         OperationKey particle_settings_eval_key(&part->id,
1835                                                 NodeType::PARTICLE_SETTINGS,
1836                                                 OperationCode::PARTICLE_SETTINGS_EVAL);
1837         OperationKey particle_settings_reset_key(
1838                 &part->id,
1839                 NodeType::PARTICLE_SETTINGS,
1840                 OperationCode::PARTICLE_SETTINGS_RESET);
1841         add_relation(particle_settings_init_key,
1842                      particle_settings_eval_key,
1843                      "Particle Settings Init Order");
1844         add_relation(particle_settings_reset_key,
1845                      particle_settings_eval_key,
1846                      "Particle Settings Reset");
1847         /* Texture slots. */
1848         for (int mtex_index = 0; mtex_index < MAX_MTEX; ++mtex_index) {
1849                 MTex *mtex = part->mtex[mtex_index];
1850                 if (mtex == NULL || mtex->tex == NULL) {
1851                         continue;
1852                 }
1853                 build_texture(mtex->tex);
1854                 ComponentKey texture_key(&mtex->tex->id,
1855                                          NodeType::GENERIC_DATABLOCK);
1856                 add_relation(texture_key,
1857                              particle_settings_reset_key,
1858                              "Particle Texture",
1859                              RELATION_FLAG_FLUSH_USER_EDIT_ONLY);
1860                 /* TODO(sergey): Consider moving texture space handling to an own
1861                  * function. */
1862                 if (mtex->texco == TEXCO_OBJECT && mtex->object != NULL) {
1863                         ComponentKey object_key(&mtex->object->id, NodeType::TRANSFORM);
1864                         add_relation(object_key,
1865                                      particle_settings_eval_key,
1866                                      "Particle Texture Space");
1867                 }
1868         }
1869         if (check_id_has_anim_component(&part->id)) {
1870                 ComponentKey animation_key(&part->id, NodeType::ANIMATION);
1871                 add_relation(animation_key,
1872                              particle_settings_eval_key,
1873                              "Particle Settings Animation");
1874         }
1875 }
1876
1877 void DepsgraphRelationBuilder::build_particle_system_visualization_object(
1878         Object *object,
1879         ParticleSystem *psys,
1880         Object *draw_object)
1881 {
1882         OperationKey psys_key(&object->id,
1883                               NodeType::PARTICLE_SYSTEM,
1884                               OperationCode::PARTICLE_SYSTEM_EVAL,
1885                               psys->name);
1886         OperationKey obdata_ubereval_key(&object->id,
1887                                          NodeType::GEOMETRY,
1888                                          OperationCode::GEOMETRY_UBEREVAL);
1889         ComponentKey dup_ob_key(&draw_object->id, NodeType::TRANSFORM);
1890         add_relation(dup_ob_key, psys_key, "Particle Object Visualization");
1891         if (draw_object->type == OB_MBALL) {
1892                 ComponentKey dup_geometry_key(&draw_object->id, NodeType::GEOMETRY);
1893                 add_relation(obdata_ubereval_key,
1894                              dup_geometry_key,
1895                              "Particle MBall Visualization");
1896         }
1897 }
1898
1899 /* Shapekeys */
1900 void DepsgraphRelationBuilder::build_shapekeys(Key *key)
1901 {
1902         if (built_map_.checkIsBuiltAndTag(key)) {
1903                 return;
1904         }
1905         /* Attach animdata to geometry. */
1906         build_animdata(&key->id);
1907         /* Connect all blocks properties to the final result evaluation. */
1908         ComponentKey geometry_key(&key->id, NodeType::GEOMETRY);
1909         LISTBASE_FOREACH (KeyBlock *, key_block, &key->block) {
1910                 OperationKey key_block_key(&key->id,
1911                                            NodeType::PARAMETERS,
1912                                            OperationCode::PARAMETERS_EVAL,
1913                                            key_block->name);
1914                 add_relation(key_block_key, geometry_key, "Key Block Properties");
1915         }
1916 }
1917
1918 /**
1919  * ObData Geometry Evaluation
1920  * ==========================
1921  *
1922  * The evaluation of geometry on objects is as follows:
1923  * - The actual evaluated of the derived geometry (e.g. Mesh, DispList)
1924  *   occurs in the Geometry component of the object which references this.
1925  *   This includes modifiers, and the temporary "ubereval" for geometry.
1926  *   Therefore, each user of a piece of shared geometry data ends up evaluating
1927  *   its own version of the stuff, complete with whatever modifiers it may use.
1928  *
1929  * - The datablocks for the geometry data - "obdata" (e.g. ID_ME, ID_CU, ID_LT.)
1930  *   are used for
1931  *     1) calculating the bounding boxes of the geometry data,
1932  *     2) aggregating inward links from other objects (e.g. for text on curve)
1933  *        and also for the links coming from the shapekey datablocks
1934  * - Animation/Drivers affecting the parameters of the geometry are made to
1935  *   trigger updates on the obdata geometry component, which then trigger
1936  *   downstream re-evaluation of the individual instances of this geometry.
1937  */
1938 void DepsgraphRelationBuilder::build_object_data_geometry(Object *object)
1939 {
1940         ID *obdata = (ID *)object->data;
1941         /* Init operation of object-level geometry evaluation. */
1942         OperationKey geom_init_key(&object->id,
1943                                    NodeType::GEOMETRY,
1944                                    OperationCode::PLACEHOLDER,
1945                                    "Eval Init");
1946         /* Get nodes for result of obdata's evaluation, and geometry evaluation
1947          * on object. */
1948         ComponentKey obdata_geom_key(obdata, NodeType::GEOMETRY);
1949         ComponentKey geom_key(&object->id, NodeType::GEOMETRY);
1950         /* Link components to each other. */
1951         add_relation(obdata_geom_key, geom_key, "Object Geometry Base Data");
1952         OperationKey obdata_ubereval_key(&object->id,
1953                                          NodeType::GEOMETRY,
1954                                          OperationCode::GEOMETRY_UBEREVAL);
1955         /* Special case: modifiers evaluation queries scene for various things like
1956          * data mask to be used. We add relation here to ensure object is never
1957          * evaluated prior to Scene's CoW is ready. */
1958         OperationKey scene_key(&scene_->id,
1959                                NodeType::LAYER_COLLECTIONS,
1960                                OperationCode::VIEW_LAYER_EVAL);
1961         Relation *rel = add_relation(scene_key, obdata_ubereval_key, "CoW Relation");
1962         rel->flag |= RELATION_FLAG_NO_FLUSH;
1963         /* Modifiers */
1964         if (object->modifiers.first != NULL) {
1965                 ModifierUpdateDepsgraphContext ctx = {};
1966                 ctx.scene = scene_;
1967                 ctx.object = object;
1968                 LISTBASE_FOREACH (ModifierData *, md, &object->modifiers) {
1969                         const ModifierTypeInfo *mti = modifierType_getInfo((ModifierType)md->type);
1970                         if (mti->updateDepsgraph) {
1971                                 DepsNodeHandle handle = create_node_handle(obdata_ubereval_key);
1972                                 ctx.node = reinterpret_cast< ::DepsNodeHandle* >(&handle);
1973                                 mti->updateDepsgraph(md, &ctx);
1974                         }
1975                         if (BKE_object_modifier_use_time(object, md)) {
1976                                 TimeSourceKey time_src_key;
1977                                 add_relation(time_src_key, obdata_ubereval_key, "Time Source");
1978                         }
1979                 }
1980         }
1981         /* Grease Pencil Modifiers */
1982         if (object->greasepencil_modifiers.first != NULL) {
1983                 ModifierUpdateDepsgraphContext ctx = {};
1984                 ctx.scene = scene_;
1985                 ctx.object = object;
1986                 LISTBASE_FOREACH(GpencilModifierData *, md, &object->greasepencil_modifiers) {
1987                         const GpencilModifierTypeInfo *mti = BKE_gpencil_modifierType_getInfo((GpencilModifierType)md->type);
1988                         if (mti->updateDepsgraph) {
1989                                 DepsNodeHandle handle = create_node_handle(obdata_ubereval_key);
1990                                 ctx.node = reinterpret_cast< ::DepsNodeHandle* >(&handle);
1991                                 mti->updateDepsgraph(md, &ctx);
1992                         }
1993                         if (BKE_object_modifier_gpencil_use_time(object, md)) {
1994                                 TimeSourceKey time_src_key;
1995                                 add_relation(time_src_key, obdata_ubereval_key, "Time Source");
1996                         }
1997                 }
1998         }
1999         /* Shader FX */
2000         if (object->shader_fx.first != NULL) {
2001                 ModifierUpdateDepsgraphContext ctx = {};
2002                 ctx.scene = scene_;
2003                 ctx.object = object;
2004                 LISTBASE_FOREACH(ShaderFxData *, fx, &object->shader_fx) {
2005                         const ShaderFxTypeInfo *fxi = BKE_shaderfxType_getInfo((ShaderFxType)fx->type);
2006                         if (fxi->updateDepsgraph) {
2007                                 DepsNodeHandle handle = create_node_handle(obdata_ubereval_key);
2008                                 ctx.node = reinterpret_cast< ::DepsNodeHandle* >(&handle);
2009                                 fxi->updateDepsgraph(fx, &ctx);
2010                         }
2011                         if (BKE_object_shaderfx_use_time(object, fx)) {
2012                                 TimeSourceKey time_src_key;
2013                                 add_relation(time_src_key, obdata_ubereval_key, "Time Source");
2014                         }
2015                 }
2016         }
2017         /* Materials. */
2018         if (object->totcol) {
2019                 for (int a = 1; a <= object->totcol; a++) {
2020                         Material *ma = give_current_material(object, a);
2021                         if (ma != NULL) {
2022                                 build_material(ma);
2023
2024                                 if (object->type == OB_MESH) {
2025                                         OperationKey material_key(&ma->id,
2026                                                                   NodeType::SHADING,
2027                                                                   OperationCode::MATERIAL_UPDATE);
2028                                         OperationKey shading_key(&object->id,
2029                                                                  NodeType::SHADING,
2030                                                                  OperationCode::SHADING);
2031                                         add_relation(material_key, shading_key, "Material Update");
2032                                 }
2033                         }
2034                 }
2035         }
2036         /* Geometry collision. */
2037         if (ELEM(object->type, OB_MESH, OB_CURVE, OB_LATTICE)) {
2038                 // add geometry collider relations
2039         }
2040         /* Make sure uber update is the last in the dependencies.
2041          *
2042          * TODO(sergey): Get rid of this node. */
2043         if (object->type != OB_ARMATURE) {
2044                 /* Armatures does no longer require uber node. */
2045                 OperationKey obdata_ubereval_key(&object->id,
2046                                                  NodeType::GEOMETRY,
2047                                                  OperationCode::GEOMETRY_UBEREVAL);
2048                 add_relation(geom_init_key,
2049                              obdata_ubereval_key,
2050                              "Object Geometry UberEval");
2051                 if (object->totcol != 0 && object->type == OB_MESH) {
2052                         ComponentKey object_shading_key(&object->id, NodeType::SHADING);
2053                         Relation *rel = add_relation(obdata_ubereval_key,
2054                                                      object_shading_key,
2055                                                      "Object Geometry batch Update");
2056                         rel->flag |= RELATION_FLAG_NO_FLUSH;
2057                 }
2058         }
2059         if (object->type == OB_MBALL) {
2060                 Object *mom = BKE_mball_basis_find(scene_, object);
2061                 ComponentKey mom_geom_key(&mom->id, NodeType::GEOMETRY);
2062                 /* motherball - mom depends on children! */
2063                 if (mom == object) {
2064                         ComponentKey mom_transform_key(&mom->id,
2065                                                        NodeType::TRANSFORM);
2066                         add_relation(mom_transform_key,
2067                                      mom_geom_key,
2068                                      "Metaball Motherball Transform -> Geometry");
2069                 }
2070                 else {
2071                         ComponentKey transform_key(&object->id, NodeType::TRANSFORM);
2072                         add_relation(geom_key, mom_geom_key, "Metaball Motherball");
2073                         add_relation(transform_key, mom_geom_key, "Metaball Motherball");
2074                 }
2075         }
2076         /* NOTE: This is compatibility code to support particle systems
2077          *
2078          * for viewport being properly rendered in final render mode.
2079          * This relation is similar to what dag_object_time_update_flags()
2080          * was doing for mesh objects with particle system.
2081          *
2082          * Ideally we need to get rid of this relation. */
2083         if (object_particles_depends_on_time(object)) {
2084                 TimeSourceKey time_key;
2085                 OperationKey obdata_ubereval_key(&object->id,
2086                                                  NodeType::GEOMETRY,
2087                                                  OperationCode::GEOMETRY_UBEREVAL);
2088                 add_relation(time_key, obdata_ubereval_key, "Legacy particle time");
2089         }
2090         /* Object data datablock. */
2091         build_object_data_geometry_datablock((ID *)object->data);
2092         Key *key = BKE_key_from_object(object);
2093         if (key != NULL) {
2094                 if (key->adt != NULL) {
2095                         if (key->adt->action || key->adt->nla_tracks.first) {
2096                                 ComponentKey obdata_key((ID *)object->data,
2097                                                         NodeType::GEOMETRY);
2098                                 ComponentKey adt_key(&key->id, NodeType::ANIMATION);
2099                                 add_relation(adt_key, obdata_key, "Animation");
2100                         }
2101                 }
2102         }
2103         /* Syncronization back to original object. */
2104         ComponentKey final_geometry_jey(&object->id, NodeType::GEOMETRY);
2105         OperationKey synchronize_key(&object->id,
2106                                      NodeType::SYNCHRONIZE,
2107                                      OperationCode::SYNCHRONIZE_TO_ORIGINAL);
2108         add_relation(
2109                 final_geometry_jey, synchronize_key, "Synchronize to Original");
2110 }
2111
2112 void DepsgraphRelationBuilder::build_object_data_geometry_datablock(ID *obdata)
2113 {
2114         if (built_map_.checkIsBuiltAndTag(obdata)) {
2115                 return;
2116         }
2117         /* Animation. */
2118         build_animdata(obdata);
2119         /* ShapeKeys. */
2120         Key *key = BKE_key_from_id(obdata);
2121         if (key != NULL) {
2122                 build_shapekeys(key);
2123         }
2124         /* Link object data evaluation node to exit operation. */
2125         OperationKey obdata_geom_eval_key(obdata,
2126                 NodeType::GEOMETRY,
2127                 OperationCode::PLACEHOLDER,
2128                 "Geometry Eval");
2129         OperationKey obdata_geom_done_key(obdata,
2130                 NodeType::GEOMETRY,
2131                 OperationCode::PLACEHOLDER,
2132                 "Eval Done");
2133         add_relation(obdata_geom_eval_key,
2134                      obdata_geom_done_key,
2135                      "ObData Geom Eval Done");
2136         /* Type-specific links. */
2137         const ID_Type id_type = GS(obdata->name);
2138         switch (id_type) {
2139                 case ID_ME:
2140                         break;
2141                 case ID_MB:
2142                         break;
2143                 case ID_CU:
2144                 {
2145                         Curve *cu = (Curve *)obdata;
2146                         if (cu->bevobj != NULL) {
2147                                 ComponentKey bevob_geom_key(&cu->bevobj->id,
2148                                         NodeType::GEOMETRY);
2149                                 add_relation(bevob_geom_key,
2150                                         obdata_geom_eval_key,
2151                                         "Curve Bevel Geometry");
2152                                 ComponentKey bevob_key(&cu->bevobj->id,
2153                                         NodeType::TRANSFORM);
2154                                 add_relation(bevob_key,
2155                                         obdata_geom_eval_key,
2156                                         "Curve Bevel Transform");
2157                                 build_object(NULL, cu->bevobj);
2158                         }
2159                         if (cu->taperobj != NULL) {
2160                                 ComponentKey taperob_key(&cu->taperobj->id,
2161                                         NodeType::GEOMETRY);
2162                                 add_relation(taperob_key, obdata_geom_eval_key, "Curve Taper");
2163                                 build_object(NULL, cu->taperobj);
2164                         }
2165                         if (cu->textoncurve != NULL) {
2166                                 ComponentKey textoncurve_key(&cu->textoncurve->id,
2167                                         NodeType::GEOMETRY);
2168                                 add_relation(textoncurve_key,
2169                                         obdata_geom_eval_key,
2170                                         "Text on Curve");
2171                                 build_object(NULL, cu->textoncurve);
2172                         }
2173                         break;
2174                 }
2175                 case ID_LT:
2176                         break;
2177                 case ID_GD: /* Grease Pencil */
2178                 {
2179                         bGPdata *gpd = (bGPdata *)obdata;
2180
2181                         /* Geometry cache needs to be recalculated on frame change
2182                          * (e.g. to fix crashes after scrubbing the timeline when
2183                          * onion skinning is enabled, since the ghosts need to be
2184                          * re-added to the cache once scrubbing ends). */
2185                         TimeSourceKey time_key;
2186                         ComponentKey geometry_key(obdata, NodeType::GEOMETRY);
2187                         add_relation(time_key,
2188                                      geometry_key,
2189                                      "GP Frame Change");
2190
2191                         /* Geometry cache also needs to be recalculated when Material
2192                          * settings change (e.g. when fill.opacity changes on/off,
2193                          * we need to rebuild the bGPDstroke->triangles caches). */
2194                         for (int i = 0; i < gpd->totcol; i++) {
2195                                 Material *ma = gpd->mat[i];
2196                                 if ((ma != NULL) && (ma->gp_style != NULL)) {
2197                                         OperationKey material_key(&ma->id,
2198                                                                   NodeType::SHADING,
2199                                                                   OperationCode::MATERIAL_UPDATE);
2200                                         add_relation(material_key,
2201                                                      geometry_key,
2202                                                      "Material -> GP Data");
2203                                 }
2204                         }
2205                         break;
2206                 }
2207                 default:
2208                         BLI_assert(!"Should not happen");
2209                         break;
2210         }
2211 }
2212
2213 void DepsgraphRelationBuilder::build_armature(bArmature *armature)
2214 {
2215         if (built_map_.checkIsBuiltAndTag(armature)) {
2216                 return;
2217         }
2218         build_animdata(&armature->id);
2219 }
2220
2221 void DepsgraphRelationBuilder::build_camera(Camera *camera)
2222 {
2223         if (built_map_.checkIsBuiltAndTag(camera)) {
2224                 return;
2225         }
2226         if (camera->dof_ob != NULL) {
2227                 ComponentKey camera_parameters_key(&camera->id, NodeType::PARAMETERS);
2228                 ComponentKey dof_ob_key(&camera->dof_ob->id, NodeType::TRANSFORM);
2229                 add_relation(dof_ob_key, camera_parameters_key, "Camera DOF");
2230         }
2231 }
2232
2233 /* Lamps */
2234 void DepsgraphRelationBuilder::build_lamp(Lamp *lamp)
2235 {
2236         if (built_map_.checkIsBuiltAndTag(lamp)) {
2237                 return;
2238         }
2239         /* lamp's nodetree */
2240         if (lamp->nodetree != NULL) {
2241                 build_nodetree(lamp->nodetree);
2242                 ComponentKey lamp_parameters_key(&lamp->id, NodeType::PARAMETERS);
2243                 ComponentKey nodetree_key(&lamp->nodetree->id, NodeType::SHADING);
2244                 add_relation(nodetree_key, lamp_parameters_key, "NTree->Light Parameters");
2245                 build_nested_nodetree(&lamp->id, lamp->nodetree);
2246         }
2247 }
2248
2249 void DepsgraphRelationBuilder::build_nodetree(bNodeTree *ntree)
2250 {
2251         if (ntree == NULL) {
2252                 return;
2253         }
2254         if (built_map_.checkIsBuiltAndTag(ntree)) {
2255                 return;
2256         }
2257         build_animdata(&ntree->id);
2258         ComponentKey shading_key(&ntree->id, NodeType::SHADING);
2259         /* nodetree's nodes... */
2260         LISTBASE_FOREACH (bNode *, bnode, &ntree->nodes) {
2261                 ID *id = bnode->id;
2262                 if (id == NULL) {
2263                         continue;
2264                 }
2265                 ID_Type id_type = GS(id->name);
2266                 if (id_type == ID_MA) {
2267                         build_material((Material *)bnode->id);
2268                 }
2269                 else if (id_type == ID_TE) {
2270                         build_texture((Tex *)bnode->id);
2271                 }
2272                 else if (id_type == ID_IM) {
2273                         /* nothing for now. */
2274                 }
2275                 else if (id_type == ID_OB) {
2276                         build_object(NULL, (Object *)id);
2277                 }
2278                 else if (id_type == ID_SCE) {
2279                         /* Scenes are used by compositor trees, and handled by render
2280                          * pipeline. No need to build dependencies for them here. */
2281                 }
2282                 else if (id_type == ID_TXT) {
2283                         /* Ignore script nodes. */
2284                 }
2285                 else if (id_type == ID_MSK) {
2286                         build_mask((Mask *)id);
2287                 }
2288                 else if (id_type == ID_MC) {
2289                         build_movieclip((MovieClip *)id);
2290                 }
2291                 else if (bnode->type == NODE_GROUP) {
2292                         bNodeTree *group_ntree = (bNodeTree *)id;
2293                         build_nodetree(group_ntree);
2294                         ComponentKey group_shading_key(&group_ntree->id,
2295                                                        NodeType::SHADING);
2296                         add_relation(group_shading_key, shading_key, "Group Node");
2297                 }
2298                 else {
2299                         BLI_assert(!"Unknown ID type used for node");
2300                 }
2301         }
2302
2303         OperationKey shading_update_key(&ntree->id,
2304                                         NodeType::SHADING,
2305                                         OperationCode::MATERIAL_UPDATE);
2306         OperationKey shading_parameters_key(&ntree->id,
2307                                             NodeType::SHADING_PARAMETERS,
2308                                             OperationCode::MATERIAL_UPDATE);
2309         add_relation(shading_parameters_key, shading_update_key, "NTree Shading Parameters");
2310
2311         if (check_id_has_anim_component(&ntree->id)) {
2312                 ComponentKey animation_key(&ntree->id, NodeType::ANIMATION);
2313                 add_relation(animation_key, shading_parameters_key, "NTree Shading Parameters");
2314         }
2315 }
2316
2317 /* Recursively build graph for material */
2318 void DepsgraphRelationBuilder::build_material(Material *material)
2319 {
2320         if (built_map_.checkIsBuiltAndTag(material)) {
2321                 return;
2322         }
2323         /* animation */
2324         build_animdata(&material->id);
2325         /* material's nodetree */
2326         if (material->nodetree != NULL) {
2327                 build_nodetree(material->nodetree);
2328                 OperationKey ntree_key(&material->nodetree->id,
2329                                        NodeType::SHADING,
2330                                        OperationCode::MATERIAL_UPDATE);
2331                 OperationKey material_key(&material->id,
2332                                           NodeType::SHADING,
2333                                           OperationCode::MATERIAL_UPDATE);
2334                 add_relation(ntree_key, material_key, "Material's NTree");
2335                 build_nested_nodetree(&material->id, material->nodetree);
2336         }
2337 }
2338
2339 /* Recursively build graph for texture */
2340 void DepsgraphRelationBuilder::build_texture(Tex *texture)
2341 {
2342         if (built_map_.checkIsBuiltAndTag(texture)) {
2343                 return;
2344         }
2345         /* texture itself */
2346         build_animdata(&texture->id);
2347         /* texture's nodetree */
2348         build_nodetree(texture->nodetree);
2349         build_nested_nodetree(&texture->id, texture->nodetree);
2350         if (check_id_has_anim_component(&texture->id)) {
2351                 ComponentKey animation_key(&texture->id, NodeType::ANIMATION);
2352                 ComponentKey datablock_key(&texture->id,
2353                                            NodeType::GENERIC_DATABLOCK);
2354                 add_relation(animation_key, datablock_key, "Datablock Animation");
2355         }
2356 }
2357
2358 void DepsgraphRelationBuilder::build_compositor(Scene *scene)
2359 {
2360         /* For now, just a plain wrapper? */
2361         build_nodetree(scene->nodetree);
2362 }
2363
2364 void DepsgraphRelationBuilder::build_gpencil(bGPdata *gpd)
2365 {
2366         if (built_map_.checkIsBuiltAndTag(gpd)) {
2367                 return;
2368         }
2369         /* animation */
2370         build_animdata(&gpd->id);
2371
2372         // TODO: parent object (when that feature is implemented)
2373 }
2374
2375 void DepsgraphRelationBuilder::build_cachefile(CacheFile *cache_file)
2376 {
2377         if (built_map_.checkIsBuiltAndTag(cache_file)) {
2378                 return;
2379         }
2380         /* Animation. */
2381         build_animdata(&cache_file->id);
2382 }
2383
2384 void DepsgraphRelationBuilder::build_mask(Mask *mask)
2385 {
2386         if (built_map_.checkIsBuiltAndTag(mask)) {
2387                 return;
2388         }
2389         ID *mask_id = &mask->id;
2390         /* F-Curve animation. */
2391         build_animdata(mask_id);
2392         /* Own mask animation. */
2393         OperationKey mask_animation_key(mask_id,
2394                                         NodeType::ANIMATION,
2395                                         OperationCode::MASK_ANIMATION);
2396         TimeSourceKey time_src_key;
2397         add_relation(time_src_key, mask_animation_key, "TimeSrc -> Mask Animation");
2398         /* Final mask evaluation. */
2399         ComponentKey parameters_key(mask_id, NodeType::PARAMETERS);
2400         add_relation(mask_animation_key, parameters_key, "Mask Animation -> Mask Eval");
2401 }
2402
2403 void DepsgraphRelationBuilder::build_movieclip(MovieClip *clip)
2404 {
2405         if (built_map_.checkIsBuiltAndTag(clip)) {
2406                 return;
2407         }
2408         /* Animation. */
2409         build_animdata(&clip->id);
2410 }
2411
2412 void DepsgraphRelationBuilder::build_lightprobe(LightProbe *probe)
2413 {
2414         if (built_map_.checkIsBuiltAndTag(probe)) {
2415                 return;
2416         }
2417         build_animdata(&probe->id);
2418 }
2419
2420 void DepsgraphRelationBuilder::build_speaker(Speaker *speaker)
2421 {
2422         if (built_map_.checkIsBuiltAndTag(speaker)) {
2423                 return;
2424         }
2425         build_animdata(&speaker->id);
2426 }
2427
2428 void DepsgraphRelationBuilder::build_copy_on_write_relations()
2429 {
2430         for (IDNode *id_node : graph_->id_nodes) {
2431                 build_copy_on_write_relations(id_node);
2432         }
2433 }
2434
2435 /* Nested datablocks (node trees, shape keys) requires special relation to
2436  * ensure owner's datablock remapping happens after node tree itself is ready.
2437  *
2438  * This is similar to what happens in ntree_hack_remap_pointers().
2439  */
2440 void DepsgraphRelationBuilder::build_nested_datablock(ID *owner, ID *id)
2441 {
2442         OperationKey owner_copy_on_write_key(owner,
2443                                              NodeType::COPY_ON_WRITE,
2444                                              OperationCode::COPY_ON_WRITE);
2445         OperationKey id_copy_on_write_key(id,
2446                                           NodeType::COPY_ON_WRITE,
2447                                           OperationCode::COPY_ON_WRITE);
2448         add_relation(id_copy_on_write_key,
2449                      owner_copy_on_write_key,
2450                      "Eval Order");
2451 }
2452
2453 void DepsgraphRelationBuilder::build_nested_nodetree(ID *owner,
2454                                                      bNodeTree *ntree)
2455 {
2456         if (ntree == NULL) {
2457                 return;
2458         }
2459         build_nested_datablock(owner, &ntree->id);
2460 }
2461
2462 void DepsgraphRelationBuilder::build_nested_shapekey(ID *owner, Key *key)
2463 {
2464         if (key == NULL) {
2465                 return;
2466         }
2467         build_nested_datablock(owner, &key->id);
2468 }
2469
2470 void DepsgraphRelationBuilder::build_copy_on_write_relations(IDNode *id_node)
2471 {
2472         ID *id_orig = id_node->id_orig;
2473         const ID_Type id_type = GS(id_orig->name);
2474         TimeSourceKey time_source_key;
2475         OperationKey copy_on_write_key(id_orig,
2476                                        NodeType::COPY_ON_WRITE,
2477                                        OperationCode::COPY_ON_WRITE);
2478         /* XXX: This is a quick hack to make Alt-A to work. */
2479         // add_relation(time_source_key, copy_on_write_key, "Fluxgate capacitor hack");
2480         /* Resat of code is using rather low level trickery, so need to get some
2481          * explicit pointers. */
2482         Node *node_cow = find_node(copy_on_write_key);
2483         OperationNode *op_cow = node_cow->get_exit_operation();
2484         /* Plug any other components to this one. */
2485         GHASH_FOREACH_BEGIN(ComponentNode *, comp_node, id_node->components)
2486         {
2487                 if (comp_node->type == NodeType::COPY_ON_WRITE) {
2488                         /* Copy-on-write component never depends on itself. */
2489                         continue;
2490                 }
2491                 if (!comp_node->depends_on_cow()) {
2492                         /* Component explicitly requests to not add relation. */
2493                         continue;
2494                 }
2495                 int rel_flag = (RELATION_FLAG_NO_FLUSH | RELATION_FLAG_GODMODE);
2496                 if (id_type == ID_ME && comp_node->type == NodeType::GEOMETRY) {
2497                         rel_flag &= ~RELATION_FLAG_NO_FLUSH;
2498                 }
2499                 /* materials need update grease pencil objects */
2500                 if (id_type == ID_MA) {
2501                         rel_flag &= ~RELATION_FLAG_NO_FLUSH;
2502                 }
2503                 /* Notes on exceptions:
2504                  * - Parameters component is where drivers are living. Changing any
2505                  *   of the (custom) properties in the original datablock (even the
2506                  *   ones which do not imply other component update) need to make
2507                  *   sure drivers are properly updated.
2508                  *   This way, for example, changing ID property will properly poke
2509                  *   all drivers to be updated.
2510                  *
2511                  * - View layers have cached array of bases in them, which is not
2512                  *   copied by copy-on-write, and not preserved. PROBABLY it is better
2513                  *   to preserve that cache in copy-on-write, but for the time being
2514                  *   we allow flush to layer collections component which will ensure
2515                  *   that cached array fo bases exists and is up-to-date.
2516                  *
2517                  * - Action is allowed to flush as well, this way it's possible to
2518                  *   keep current tagging in animation editors (which tags action for
2519                  *   CoW update when it's changed) but yet guarantee evaluation order
2520                  *   with objects which are using that action. */
2521                 if (comp_node->type == NodeType::PARAMETERS ||
2522                     comp_node->type == NodeType::LAYER_COLLECTIONS ||
2523                     (comp_node->type == NodeType::ANIMATION && id_type == ID_AC))
2524                 {
2525                         rel_flag &= ~RELATION_FLAG_NO_FLUSH;
2526                 }
2527                 /* All entry operations of each component should wait for a proper
2528                  * copy of ID. */
2529                 OperationNode *op_entry = comp_node->get_entry_operation();
2530                 if (op_entry != NULL) {
2531                         Relation *rel = graph_->add_new_relation(
2532                                 op_cow, op_entry, "CoW Dependency");
2533                         rel->flag |= rel_flag;
2534                 }
2535                 /* All dangling operations should also be executed after copy-on-write. */
2536                 GHASH_FOREACH_BEGIN(OperationNode *, op_node, comp_node->operations_map)
2537                 {
2538                         if (op_node == op_entry) {
2539                                 continue;
2540                         }
2541                         if (op_node->inlinks.size() == 0) {
2542                                 Relation *rel = graph_->add_new_relation(
2543                                         op_cow, op_node, "CoW Dependency");
2544                                 rel->flag |= rel_flag;
2545                         }
2546                         else {
2547                                 bool has_same_comp_dependency = false;
2548                                 for (Relation *rel_current : op_node->inlinks) {
2549                                         if (rel_current->from->type != NodeType::OPERATION) {
2550                                                 continue;
2551                                         }
2552                                         OperationNode *op_node_from =
2553                                                 (OperationNode *)rel_current->from;
2554                                         if (op_node_from->owner == op_node->owner) {
2555                                                 has_same_comp_dependency = true;
2556                                                 break;
2557                                         }
2558                                 }
2559                                 if (!has_same_comp_dependency) {
2560                                         Relation *rel = graph_->add_new_relation(
2561                                                 op_cow, op_node, "CoW Dependency");
2562                                         rel->flag |= rel_flag;
2563                                 }
2564                         }
2565                 }
2566                 GHASH_FOREACH_END();
2567                 /* NOTE: We currently ignore implicit relations to an external
2568                  * datablocks for copy-on-write operations. This means, for example,
2569                  * copy-on-write component of Object will not wait for copy-on-write
2570                  * component of it's Mesh. This is because pointers are all known
2571                  * already so remapping will happen all correct. And then If some object
2572                  * evaluation step needs geometry, it will have transitive dependency
2573                  * to Mesh copy-on-write already. */
2574         }
2575         GHASH_FOREACH_END();
2576         /* TODO(sergey): This solves crash for now, but causes too many
2577          * updates potentially. */
2578         if (GS(id_orig->name) == ID_OB) {
2579                 Object *object = (Object *)id_orig;
2580                 ID *object_data_id = (ID *)object->data;
2581                 if (object_data_id != NULL) {
2582                         if (deg_copy_on_write_is_needed(object_data_id)) {
2583                                 OperationKey data_copy_on_write_key(object_data_id,
2584                                                                     NodeType::COPY_ON_WRITE,
2585                                                                     OperationCode::COPY_ON_WRITE);
2586                                 add_relation(data_copy_on_write_key,
2587                                              copy_on_write_key,
2588                                              "Eval Order",
2589                                              RELATION_FLAG_GODMODE);
2590                         }
2591                 }
2592                 else {
2593                         BLI_assert(object->type == OB_EMPTY);
2594                 }
2595         }
2596 }
2597
2598 /* **** ID traversal callbacks functions **** */
2599
2600 void DepsgraphRelationBuilder::modifier_walk(void *user_data,
2601                                              struct Object * /*object*/,
2602                                              struct ID **idpoin,
2603                                              int /*cb_flag*/)
2604 {
2605         BuilderWalkUserData *data = (BuilderWalkUserData *)user_data;
2606         ID *id = *idpoin;
2607         if (id == NULL) {
2608                 return;
2609         }
2610         data->builder->build_id(id);
2611 }
2612
2613 void DepsgraphRelationBuilder::constraint_walk(bConstraint * /*con*/,
2614                                                ID **idpoin,
2615                                                bool /*is_reference*/,
2616                                                void *user_data)
2617 {
2618         BuilderWalkUserData *data = (BuilderWalkUserData *)user_data;
2619         ID *id = *idpoin;
2620         if (id == NULL) {
2621                 return;
2622         }
2623         data->builder->build_id(id);
2624 }
2625
2626 }  // namespace DEG