1//! Particle graph traversal, bitmap source discovery, and deterministic subgraph hashing.
2
3use std::collections::hash_map::DefaultHasher;
4use std::collections::{HashMap, HashSet};
5use std::hash::{Hash, Hasher};
6
7use model::{BezierSpline, Comp, Gradient, InputBinding, Node, NodeId, ParamValue};
8
9use super::stable_name_hash;
10
11/// Returns true if `kind` is a Fusion particle stream operator.
12pub(super) fn is_particle_node_kind(kind: &str) -> bool {
13 matches!(
14 kind,
15 "pRender"
16 | "pEmitter"
17 | "pPointForce"
18 | "pDirectionalForce"
19 | "pTurbulence"
20 | "pDrag"
21 | "pFriction"
22 | "pKill"
23 | "pMerge"
24 | "pBounce"
25 | "pVortex"
26 | "pFlock"
27 | "pAvoid"
28 | "pSpawn"
29 | "pChangeStyle"
30 | "pCustom"
31 | "pCustomForce"
32 | "pGradientForce"
33 | "pImageEmitter"
34 ) || (kind.starts_with('p')
35 && kind
36 .as_bytes()
37 .get(1)
38 .is_some_and(|b| b.is_ascii_uppercase()))
39}
40
41/// Returns the particle stream input node IDs of `node` in deterministic order.
42pub(super) fn particle_stream_inputs(comp: &Comp, node: &Node) -> Vec<NodeId> {
43 let mut ports: Vec<&str> = Vec::new();
44 for key in node.inputs.keys() {
45 if key == "Input"
46 || key
47 .strip_prefix("Input")
48 .is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit()))
49 {
50 ports.push(key.as_str());
51 }
52 }
53 ports.sort_unstable();
54
55 let mut out = Vec::with_capacity(ports.len());
56 for port in ports {
57 if let Some(src_name) = node.connected_node(port) {
58 if let Some(&src_id) = comp.node_by_name.get(src_name) {
59 out.push(src_id);
60 }
61 }
62 }
63 out
64}
65
66/// Walks upstream from `render_node` through particle operators and returns every
67/// `(emitter_node_id, sprite_source_node_id)` pair for `pEmitter` nodes whose
68/// `ParticleStyleBitmap.DropToolsHere` input is connected.
69pub fn collect_bitmap_sources(comp: &Comp, render_node: NodeId) -> Vec<(NodeId, NodeId)> {
70 let mut visited = HashSet::new();
71 let mut out = Vec::new();
72 collect_bitmap_sources_dfs(comp, render_node, &mut visited, &mut out);
73 out
74}
75
76fn collect_bitmap_sources_dfs(
77 comp: &Comp,
78 node_id: NodeId,
79 visited: &mut HashSet<NodeId>,
80 out: &mut Vec<(NodeId, NodeId)>,
81) {
82 if !visited.insert(node_id) {
83 return;
84 }
85 let Some(node) = comp.nodes.get(node_id.0) else {
86 return;
87 };
88 if !is_particle_node_kind(&node.kind) {
89 return;
90 }
91
92 if matches!(node.kind.as_str(), "pEmitter" | "pSpawn" | "pChangeStyle") {
93 if let Some(src_name) = node.connected_node("ParticleStyleBitmap.DropToolsHere") {
94 if let Some(&src_id) = comp.node_by_name.get(src_name) {
95 out.push((node_id, src_id));
96 }
97 }
98 } else if node.kind == "pImageEmitter" {
99 if let Some(src_name) = node.connected_node("Input") {
100 if let Some(&src_id) = comp.node_by_name.get(src_name) {
101 out.push((node_id, src_id));
102 }
103 }
104 } else if matches!(node.kind.as_str(), "pCustom" | "pCustomForce") {
105 for port in ["Image1", "Image", "Bitmap", "BitmapInput"] {
106 if let Some(src_name) = node.connected_node(port) {
107 if let Some(&src_id) = comp.node_by_name.get(src_name) {
108 out.push((node_id, src_id));
109 break;
110 }
111 }
112 }
113 } else if node.kind == "pGradientForce" {
114 for port in ["Image", "Bitmap", "BitmapInput", "GradientImage"] {
115 if let Some(src_name) = node.connected_node(port) {
116 if let Some(&src_id) = comp.node_by_name.get(src_name) {
117 out.push((node_id, src_id));
118 break;
119 }
120 }
121 }
122 }
123
124 if node.kind != "pImageEmitter" {
125 for up_id in particle_stream_inputs(comp, node) {
126 collect_bitmap_sources_dfs(comp, up_id, visited, out);
127 }
128 }
129}
130
131/// Flattened, topologically-ordered particle graph upstream of a `pRender` node.
132pub(super) struct ParticlePlan {
133 pub(super) emitters: Vec<(NodeId, u64)>,
134 /// Forces/modifiers in topological order along with the set of upstream
135 /// emitter name hashes whose particles flow through each modifier.
136 pub(super) modifiers: Vec<(NodeId, HashSet<u64>)>,
137 pub(super) emitter_nodes: HashMap<u64, NodeId>,
138}
139
140pub(super) fn build_particle_plan(comp: &Comp, render_node: NodeId) -> ParticlePlan {
141 let mut visited = HashSet::new();
142 let mut emitters = Vec::new();
143 let mut modifiers = Vec::new();
144 let mut upstream_emitters: HashMap<NodeId, HashSet<u64>> = HashMap::new();
145 let mut emitter_nodes = HashMap::new();
146
147 build_plan_dfs(
148 comp,
149 render_node,
150 &mut visited,
151 &mut emitters,
152 &mut modifiers,
153 &mut upstream_emitters,
154 &mut emitter_nodes,
155 );
156
157 ParticlePlan {
158 emitters,
159 modifiers,
160 emitter_nodes,
161 }
162}
163
164fn build_plan_dfs(
165 comp: &Comp,
166 node_id: NodeId,
167 visited: &mut HashSet<NodeId>,
168 emitters: &mut Vec<(NodeId, u64)>,
169 modifiers: &mut Vec<(NodeId, HashSet<u64>)>,
170 upstream_emitters: &mut HashMap<NodeId, HashSet<u64>>,
171 emitter_nodes: &mut HashMap<u64, NodeId>,
172) -> HashSet<u64> {
173 if let Some(cached) = upstream_emitters.get(&node_id) {
174 return cached.clone();
175 }
176 if !visited.insert(node_id) {
177 return HashSet::new();
178 }
179
180 let Some(node) = comp.nodes.get(node_id.0) else {
181 return HashSet::new();
182 };
183 if !is_particle_node_kind(&node.kind) {
184 return HashSet::new();
185 }
186
187 let mut scope = HashSet::new();
188 for up_id in particle_stream_inputs(comp, node) {
189 let up_set = build_plan_dfs(
190 comp,
191 up_id,
192 visited,
193 emitters,
194 modifiers,
195 upstream_emitters,
196 emitter_nodes,
197 );
198 scope.extend(up_set);
199 }
200
201 if matches!(node.kind.as_str(), "pEmitter" | "pImageEmitter") {
202 if !node.bypassed {
203 let emitter_hash = stable_name_hash(&node.name);
204 emitters.push((node_id, emitter_hash));
205 emitter_nodes.insert(emitter_hash, node_id);
206 scope.insert(emitter_hash);
207 }
208 } else if !node.bypassed && node.kind == "pSpawn" {
209 // `pSpawn` reads only upstream particle scopes (preventing self-spawning loops),
210 // then adds its own hash so downstream forces and `pRender` include its children.
211 modifiers.push((node_id, scope.clone()));
212 let spawn_hash = stable_name_hash(&node.name);
213 emitter_nodes.insert(spawn_hash, node_id);
214 scope.insert(spawn_hash);
215 } else if !node.bypassed
216 && matches!(
217 node.kind.as_str(),
218 "pPointForce"
219 | "pDirectionalForce"
220 | "pTurbulence"
221 | "pDrag"
222 | "pFriction"
223 | "pKill"
224 | "pBounce"
225 | "pVortex"
226 | "pFlock"
227 | "pAvoid"
228 | "pFollow"
229 | "pTangentForce"
230 | "pCustom"
231 | "pCustomForce"
232 | "pChangeStyle"
233 | "pGradientForce"
234 )
235 {
236 if node.kind == "pChangeStyle" && node.connected_node("ParticleStyleBitmap.DropToolsHere").is_some() {
237 emitter_nodes.insert(stable_name_hash(&node.name), node_id);
238 }
239 modifiers.push((node_id, scope.clone()));
240 }
241
242 upstream_emitters.insert(node_id, scope.clone());
243 scope
244}
245
246fn hash_spline(spline: &BezierSpline, h: &mut DefaultHasher) {
247 spline.name.hash(h);
248 spline.keyframes.len().hash(h);
249 for kf in &spline.keyframes {
250 kf.time.to_bits().hash(h);
251 kf.value.to_bits().hash(h);
252 if let Some([lx, ly]) = kf.lh {
253 1u8.hash(h);
254 lx.to_bits().hash(h);
255 ly.to_bits().hash(h);
256 } else {
257 0u8.hash(h);
258 }
259 if let Some([rx, ry]) = kf.rh {
260 1u8.hash(h);
261 rx.to_bits().hash(h);
262 ry.to_bits().hash(h);
263 } else {
264 0u8.hash(h);
265 }
266 [
267 kf.flags.linear,
268 kf.flags.step_in,
269 kf.flags.step_out,
270 kf.flags.loop_after,
271 kf.flags.loop_rel,
272 kf.flags.ping_pong,
273 kf.flags.locked_y,
274 ]
275 .hash(h);
276 (kf.handle_mode as u8).hash(h);
277 }
278}
279
280fn hash_gradient(grad: &Gradient, h: &mut DefaultHasher) {
281 grad.stops.len().hash(h);
282 for stop in &grad.stops {
283 stop.pos.to_bits().hash(h);
284 for c in stop.rgba {
285 c.to_bits().hash(h);
286 }
287 }
288}
289
290fn hash_input_binding(
291 comp: &Comp,
292 binding: &InputBinding,
293 visited_mods: &mut HashSet<String>,
294 h: &mut DefaultHasher,
295) {
296 binding.source_output.hash(h);
297 binding.expression.hash(h);
298 match &binding.value {
299 None => 0u8.hash(h),
300 Some(ParamValue::Number(v)) => {
301 1u8.hash(h);
302 v.to_bits().hash(h);
303 }
304 Some(ParamValue::Point([x, y])) => {
305 2u8.hash(h);
306 x.to_bits().hash(h);
307 y.to_bits().hash(h);
308 }
309 Some(ParamValue::Text(s)) => {
310 3u8.hash(h);
311 s.hash(h);
312 }
313 Some(ParamValue::FuId(s)) => {
314 4u8.hash(h);
315 s.hash(h);
316 }
317 Some(ParamValue::Gradient(g)) => {
318 5u8.hash(h);
319 hash_gradient(g, h);
320 }
321 Some(ParamValue::Raw(raw)) => {
322 6u8.hash(h);
323 format!("{raw:?}").hash(h);
324 }
325 }
326 binding.source_op.hash(h);
327 if let Some(op) = &binding.source_op {
328 if let Some(sp) = comp.splines.get(op) {
329 hash_spline(sp, h);
330 }
331 if let Some(pp) = comp.poly_paths.get(op) {
332 pp.name.hash(h);
333 pp.displacement_op.hash(h);
334 pp.displacement_value.to_bits().hash(h);
335 pp.closed.hash(h);
336 pp.points.len().hash(h);
337 for pt in &pp.points {
338 pt.x.to_bits().hash(h);
339 pt.y.to_bits().hash(h);
340 pt.lx.to_bits().hash(h);
341 pt.ly.to_bits().hash(h);
342 pt.rx.to_bits().hash(h);
343 pt.ry.to_bits().hash(h);
344 pt.linear.hash(h);
345 }
346 if let Some(disp_op) = &pp.displacement_op {
347 if let Some(sp) = comp.splines.get(disp_op) {
348 hash_spline(sp, h);
349 }
350 }
351 }
352 if let Some(sh) = comp.shakes.get(op) {
353 if visited_mods.insert(op.clone()) {
354 hash_sorted_inputs(comp, &sh.inputs, visited_mods, h);
355 visited_mods.remove(op);
356 } else {
357 0xC1C1_u16.hash(h);
358 op.hash(h);
359 }
360 }
361 if let Some(ex) = comp.expression_modifiers.get(op) {
362 if visited_mods.insert(op.clone()) {
363 hash_sorted_inputs(comp, &ex.inputs, visited_mods, h);
364 visited_mods.remove(op);
365 } else {
366 0xC1C2_u16.hash(h);
367 op.hash(h);
368 }
369 }
370 if let Some(gm) = comp.gradient_modifiers.get(op) {
371 gm.len().hash(h);
372 for (t, g) in gm {
373 t.to_bits().hash(h);
374 hash_gradient(g, h);
375 }
376 }
377 }
378}
379
380fn hash_sorted_inputs(
381 comp: &Comp,
382 inputs: &HashMap<String, InputBinding>,
383 visited_mods: &mut HashSet<String>,
384 h: &mut DefaultHasher,
385) {
386 let mut keys: Vec<&String> = inputs.keys().collect();
387 keys.sort_unstable();
388 keys.len().hash(h);
389 for k in keys {
390 k.hash(h);
391 hash_input_binding(comp, &inputs[k], visited_mods, h);
392 }
393}
394
395/// Content hash of the particle simulation subgraph upstream of `render_node`.
396/// Unrelated edits outside the particle branch leave this hash unchanged.
397pub(super) fn particle_subgraph_hash(comp: &Comp, render_node: NodeId, base_start: i64) -> u64 {
398 fn dfs(
399 comp: &Comp,
400 node_id: NodeId,
401 is_root: bool,
402 visited: &mut HashSet<NodeId>,
403 visited_mods: &mut HashSet<String>,
404 h: &mut DefaultHasher,
405 ) {
406 if !visited.insert(node_id) {
407 return;
408 }
409 let Some(node) = comp.nodes.get(node_id.0) else {
410 return;
411 };
412 if !is_particle_node_kind(&node.kind) {
413 return;
414 }
415 node.name.hash(h);
416 node.kind.hash(h);
417 node.bypassed.hash(h);
418
419 let mut keys: Vec<&String> = node.inputs.keys().collect();
420 keys.sort_unstable();
421 for k in keys {
422 // `pRender.Width` and bitmap drop target only affect rasterization, not simulation state.
423 if (is_root && k == "Width") || k == "ParticleStyleBitmap.DropToolsHere" {
424 continue;
425 }
426 k.hash(h);
427 hash_input_binding(comp, &node.inputs[k], visited_mods, h);
428 }
429 for up_id in particle_stream_inputs(comp, node) {
430 dfs(comp, up_id, false, visited, visited_mods, h);
431 }
432 }
433
434 let mut h = DefaultHasher::new();
435 base_start.hash(&mut h);
436 let mut visited = HashSet::new();
437 let mut visited_mods = HashSet::new();
438 dfs(comp, render_node, true, &mut visited, &mut visited_mods, &mut h);
439 h.finish()
440}