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