1use wgpu::util::DeviceExt;
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
26pub enum TransitionKind {
27 Circle = 0,
29 Plasma = 1,
31 SimpleBlend = 2,
33 Sweep = 3,
35 Warp = 4,
37 ZoomBlur = 5,
39}
40
41impl TransitionKind {
42 pub const ALL: [TransitionKind; 6] = [
44 TransitionKind::Circle,
45 TransitionKind::Plasma,
46 TransitionKind::SimpleBlend,
47 TransitionKind::Sweep,
48 TransitionKind::Warp,
49 TransitionKind::ZoomBlur,
50 ];
51
52 pub fn index(self) -> usize {
54 self as usize
55 }
56
57 pub fn from_index(i: u32) -> Self {
59 Self::ALL[i as usize % Self::ALL.len()]
60 }
61
62 pub fn name(self) -> &'static str {
64 match self {
65 TransitionKind::Circle => "circle",
66 TransitionKind::Plasma => "plasma",
67 TransitionKind::SimpleBlend => "simple_blend",
68 TransitionKind::Sweep => "sweep",
69 TransitionKind::Warp => "warp",
70 TransitionKind::ZoomBlur => "zoom_blur",
71 }
72 }
73}
74
75#[derive(Clone, Copy, Debug, PartialEq)]
77pub struct TransitionParams {
78 pub kind: TransitionKind,
80 pub linear: f64,
82 pub cosine: f64,
84 pub bicubic: f64,
86 pub duration: f64,
88 pub time: f64,
90 pub time_delta: f64,
92 pub rand_static: [i32; 4],
94}
95
96impl TransitionParams {
97 pub fn new(
100 kind: TransitionKind,
101 rand_static: [i32; 4],
102 duration: f64,
103 seconds_since_start: f64,
104 time_delta: f64,
105 ) -> Self {
106 let (linear, cosine, bicubic) = if duration > 0.0 {
107 let l = seconds_since_start / duration;
108 let c = (-(l * std::f64::consts::PI).cos() + 1.0) * 0.5;
109 let b = if l < 0.5 {
110 4.0 * l * l * l
111 } else {
112 1.0 - (-2.0 * l + 2.0).powf(3.0) / 2.0
113 };
114 (l, c, b)
115 } else {
116 (1.0, 1.0, 1.0)
117 };
118 Self {
119 kind,
120 linear,
121 cosine,
122 bicubic,
123 duration,
124 time: seconds_since_start,
125 time_delta,
126 rand_static,
127 }
128 }
129}
130
131#[repr(C)]
132#[derive(Clone, Copy, Debug, Default, bytemuck::Pod, bytemuck::Zeroable)]
133struct TransitionUniforms {
134 resolution: [f32; 4],
136 duration_params: [f32; 4],
138 time_params: [f32; 4],
140 rand_static: [i32; 4],
142}
143
144const HEADER: &str = concat!(
145 crate::shaders::fullscreen_tri_fn!(),
146 r#"
147struct TP {
148 resolution: vec4<f32>,
149 duration_params: vec4<f32>,
150 time_params: vec4<f32>,
151 rand_static: vec4<i32>,
152};
153@group(0) @binding(0) var<uniform> tp: TP;
154@group(0) @binding(1) var tex_old: texture_2d<f32>;
155@group(0) @binding(2) var tex_new: texture_2d<f32>;
156@group(0) @binding(3) var samp: sampler;
157
158@vertex
159fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {
160 // z = 0.5: gl_FragCoord.z of projectM's z = 0 quad under the default [-1, 1] -> [0, 1] depth range
161 return vec4<f32>(fullscreen_tri(vi), 0.5, 1.0);
162}
163
164fn glsl_mod(x: f32, y: f32) -> f32 {
165 return x - y * floor(x / y);
166}
167
168fn glsl_smoothstep(e0: f32, e1: f32, x: f32) -> f32 {
169 let t = clamp((x - e0) / (e1 - e0), 0.0, 1.0);
170 return t * t * (3.0 - 2.0 * t);
171}
172
173fn srgb_to_linear(c: vec3<f32>) -> vec3<f32> {
174 let lo = c / 12.92;
175 let hi = pow((c + vec3<f32>(0.055)) / 1.055, vec3<f32>(2.4));
176 return select(hi, lo, c <= vec3<f32>(0.04045));
177}
178
179// texture(iChannel0, p) / texture(iChannel1, p): GLSL v runs bottom-up, our images top-down.
180fn old_at(p: vec2<f32>) -> vec3<f32> {
181 return textureSampleLevel(tex_old, samp, vec2<f32>(p.x, 1.0 - p.y), 0.0).xyz;
182}
183fn new_at(p: vec2<f32>) -> vec3<f32> {
184 return textureSampleLevel(tex_new, samp, vec2<f32>(p.x, 1.0 - p.y), 0.0).xyz;
185}
186
187fn i_progress_linear() -> f32 { return tp.duration_params.x; }
188fn i_progress_cosine() -> f32 { return tp.duration_params.y; }
189fn i_progress_bicubic() -> f32 { return tp.duration_params.z; }
190
191@fragment
192fn fs_main(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
193 // gl_FragCoord: y up
194 let frag = vec4<f32>(pos.x, tp.resolution.y - pos.y, pos.z, 1.0);
195 var rgb = main_image(frag, frag.xy).xyz;
196 if (tp.resolution.w > 0.5) {
197 rgb = srgb_to_linear(rgb);
198 }
199 return vec4<f32>(rgb, 1.0);
200}
201"#
202);
203
204const CIRCLE: &str = r#"
205fn main_image(frag: vec4<f32>, frag_coord: vec2<f32>) -> vec4<f32> {
206 let uv = frag_coord / tp.resolution.xy;
207 let aspect = tp.resolution.y / tp.resolution.x;
208
209 let in_or_out = glsl_mod(f32(tp.rand_static.x) * 0.01, 2.0);
210
211 var progress: f32;
212 var img_inner: vec3<f32>;
213 var img_outer: vec3<f32>;
214 if (in_or_out < 1.0) {
215 img_inner = old_at(uv);
216 img_outer = new_at(uv);
217 progress = i_progress_cosine();
218 } else {
219 img_outer = old_at(uv);
220 img_inner = new_at(uv);
221 progress = 1.0 - i_progress_cosine();
222 }
223 let blend_width = glsl_mod(f32(tp.rand_static.y) * 0.001, 0.1) + 0.05;
224 progress = progress * (1.0 + blend_width) - blend_width;
225
226 let center = vec2<f32>(0.5);
227 let rad = sqrt(center.x / aspect * center.x / aspect + center.y * center.y) * progress;
228 let rad2 = rad + blend_width;
229 let r1 = sqrt((uv.x - center.x) / aspect * (uv.x - center.x) / aspect + (uv.y - center.y) * (uv.y - center.y));
230
231 var col: vec3<f32>;
232 if (r1 > rad2) {
233 col = img_inner;
234 } else if (r1 > rad) {
235 let v1 = (r1 - rad) / (rad2 - rad);
236 let v2 = 1.0 - v1;
237 col = v1 * img_inner + v2 * img_outer;
238 } else {
239 col = img_outer;
240 }
241 return vec4<f32>(col, 1.0);
242}
243"#;
244
245const PLASMA: &str = r#"
246fn sin_noise(uv: vec2<f32>) -> f32 {
247 return fract(abs(sin(uv.x * 0.018 + uv.y * 0.3077) * (f32(tp.rand_static.x) * 0.001)));
248}
249
250fn value_noise(uv: vec2<f32>, scale: f32) -> f32 {
251 let luv = fract(uv * scale);
252 let luvs = vec2<f32>(glsl_smoothstep(0.0, 1.0, fract(uv * scale).x), glsl_smoothstep(0.0, 1.0, fract(uv * scale).y));
253 let id = floor(uv * scale);
254 let tl = sin_noise(id + vec2<f32>(0.0, 1.0));
255 let tr = sin_noise(id + vec2<f32>(1.0, 1.0));
256 let t = mix(tl, tr, luvs.x);
257
258 let bl = sin_noise(id + vec2<f32>(0.0, 0.0));
259 let br = sin_noise(id + vec2<f32>(1.0, 0.0));
260 let b = mix(bl, br, luvs.x);
261
262 return mix(b, t, luvs.y) * 2.0 - 1.0;
263}
264
265fn main_image(frag: vec4<f32>, frag_coord: vec2<f32>) -> vec4<f32> {
266 var uv = frag_coord / tp.resolution.xy;
267
268 let img_old = old_at(uv);
269 let img_new = new_at(uv);
270
271 uv.y = uv.y / (tp.resolution.x / tp.resolution.y);
272
273 let scale = glsl_mod(f32(tp.rand_static.y) * 0.01, 7.0) * 4.0 + 4.0;
274
275 var fract_value = 0.0;
276 var amp = 1.0;
277 for (var i = 0; i < 16; i = i + 1) {
278 fract_value = fract_value + value_noise(uv, f32(i + 1) * scale) * amp;
279 amp = amp * 0.5;
280 }
281
282 fract_value = fract_value * 0.25;
283 fract_value = fract_value + 0.5;
284
285 let cutoff = glsl_smoothstep(i_progress_cosine() + 0.1, i_progress_cosine() - 0.1, fract_value);
286 let col = mix(img_old, img_new, cutoff);
287 return vec4<f32>(col, 1.0);
288}
289"#;
290
291const SIMPLE_BLEND: &str = r#"
292fn main_image(frag: vec4<f32>, frag_coord: vec2<f32>) -> vec4<f32> {
293 let uv = frag_coord / tp.resolution.xy;
294 return vec4<f32>(mix(old_at(uv), new_at(uv), i_progress_cosine()), 1.0);
295}
296"#;
297
298const SWEEP: &str = r#"
299fn atan_y_over_x(y: f32, x: f32) -> f32 {
300 if (x > 0.0) {
301 return atan(y / x);
302 } else if (x < 0.0 && y >= 0.0) {
303 return atan(y / x) + 3.14159265;
304 } else if (x < 0.0 && y < 0.0) {
305 return atan(y / x) - 3.14159265;
306 }
307 return 1.57079632 * sign(y);
308}
309
310fn main_image(frag: vec4<f32>, frag_coord: vec2<f32>) -> vec4<f32> {
311 var uv = frag_coord / tp.resolution.xy;
312 let img_old = old_at(uv);
313 let img_new = new_at(uv);
314
315 let current_angle = glsl_mod(f32(tp.rand_static.x), 360.0);
316 let blend_width = glsl_mod(f32(tp.rand_static.y) * 0.001, 0.3) + 0.1;
317
318 uv = uv - 0.5;
319 let angle = 90.0 * 0.017453292 - current_angle * 0.017453292 + atan_y_over_x(uv.y, uv.x);
320
321 let len = length(uv) / sqrt(2.0);
322 uv = vec2<f32>(cos(angle) * len, sin(angle) * len) + 0.5;
323
324 let col = mix(img_new, img_old, glsl_smoothstep(i_progress_cosine(), i_progress_cosine() + blend_width, (uv.x / (1.0 + 2.0 * blend_width)) + blend_width));
325 return vec4<f32>(col, 1.0);
326}
327"#;
328
329const WARP: &str = r#"
330fn main_image(frag: vec4<f32>, frag_coord: vec2<f32>) -> vec4<f32> {
331 let uv = frag_coord / tp.resolution.xy;
332
333 let direction = glsl_mod(f32(tp.rand_static.x) * 0.01, 4.0);
334 var coord: f32;
335 if (direction < 1.0) {
336 coord = uv.x;
337 } else if (direction < 2.0) {
338 coord = 1.0 - uv.x;
339 } else if (direction < 3.0) {
340 coord = uv.y;
341 } else {
342 coord = 1.0 - uv.y;
343 }
344
345 let x = glsl_smoothstep(0.0, 1.0, (i_progress_cosine() * 2.0 + coord - 1.0));
346 let a = old_at((uv - 0.5) * (1.0 - x) + 0.5);
347 let b = new_at((uv - 0.5) * x + 0.5);
348 return vec4<f32>(mix(a, b, x), 1.0);
349}
350"#;
351
352const ZOOM_BLUR: &str = r#"
353const STRENGTH: f32 = 0.3;
354const PI: f32 = 3.141592653589793;
355
356fn linear_ease(begin: f32, change: f32, duration: f32, time: f32) -> f32 {
357 return change * time / duration + begin;
358}
359
360fn exponential_ease_in_out(begin: f32, change: f32, duration: f32, time_in: f32) -> f32 {
361 var time = time_in;
362 if (time == 0.0) {
363 return begin;
364 } else if (time == duration) {
365 return begin + change;
366 }
367 time = time / (duration / 2.0);
368 if (time < 1.0) {
369 return change / 2.0 * pow(2.0, 10.0 * (time - 1.0)) + begin;
370 }
371 return change / 2.0 * (-pow(2.0, -10.0 * (time - 1.0)) + 2.0) + begin;
372}
373
374fn sinusoidal_ease_in_out(begin: f32, change: f32, duration: f32, time: f32) -> f32 {
375 return -change / 2.0 * (cos(PI * time / duration) - 1.0) + begin;
376}
377
378fn random3(scale: vec3<f32>, seed: f32, frag: vec3<f32>) -> f32 {
379 return fract(sin(dot(frag + seed, scale)) * 43758.5453 + seed);
380}
381
382fn cross_fade(uv: vec2<f32>, dissolve: f32) -> vec3<f32> {
383 return mix(old_at(uv), new_at(uv), dissolve);
384}
385
386fn main_image(frag: vec4<f32>, frag_coord: vec2<f32>) -> vec4<f32> {
387 let tex_coord = frag_coord / tp.resolution.xy;
388 let progress = i_progress_cosine();
389 let center = vec2<f32>(linear_ease(0.5, 0.0, 1.0, progress), 0.5);
390 let dissolve = exponential_ease_in_out(0.0, 1.0, 1.0, progress);
391
392 let strength = sinusoidal_ease_in_out(0.0, STRENGTH, 0.5, progress);
393
394 var color = vec3<f32>(0.0);
395 var total = 0.0;
396 let to_center = center - tex_coord;
397
398 let offset = random3(vec3<f32>(12.9898, 78.233, 151.7182), 0.0, frag.xyz) * 0.5;
399
400 for (var t = 0.0; t <= 20.0; t = t + 1.0) {
401 let percent = (t + offset) / 20.0;
402 let weight = 1.0 * (percent - percent * percent);
403 color = color + cross_fade(tex_coord + to_center * percent * strength, dissolve) * weight;
404 total = total + weight;
405 }
406
407 return vec4<f32>(color / total, 1.0);
408}
409"#;
410
411fn body(kind: TransitionKind) -> &'static str {
412 match kind {
413 TransitionKind::Circle => CIRCLE,
414 TransitionKind::Plasma => PLASMA,
415 TransitionKind::SimpleBlend => SIMPLE_BLEND,
416 TransitionKind::Sweep => SWEEP,
417 TransitionKind::Warp => WARP,
418 TransitionKind::ZoomBlur => ZOOM_BLUR,
419 }
420}
421
422pub struct TransitionBlender {
424 device: wgpu::Device,
425 bgl: wgpu::BindGroupLayout,
426 sampler: wgpu::Sampler,
427 pipelines: Vec<wgpu::RenderPipeline>,
428 srgb_target: bool,
429}
430
431impl TransitionBlender {
432 pub fn new(device: &wgpu::Device, output_format: wgpu::TextureFormat) -> Self {
434 let tex_entry = |binding| wgpu::BindGroupLayoutEntry {
435 binding,
436 visibility: wgpu::ShaderStages::FRAGMENT,
437 ty: wgpu::BindingType::Texture {
438 sample_type: wgpu::TextureSampleType::Float { filterable: true },
439 view_dimension: wgpu::TextureViewDimension::D2,
440 multisampled: false,
441 },
442 count: None,
443 };
444 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
445 label: Some("transition"),
446 entries: &[
447 wgpu::BindGroupLayoutEntry {
448 binding: 0,
449 visibility: wgpu::ShaderStages::FRAGMENT,
450 ty: wgpu::BindingType::Buffer {
451 ty: wgpu::BufferBindingType::Uniform,
452 has_dynamic_offset: false,
453 min_binding_size: None,
454 },
455 count: None,
456 },
457 tex_entry(1),
458 tex_entry(2),
459 wgpu::BindGroupLayoutEntry {
460 binding: 3,
461 visibility: wgpu::ShaderStages::FRAGMENT,
462 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
463 count: None,
464 },
465 ],
466 });
467 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
468 label: Some("transition"),
469 bind_group_layouts: &[Some(&bgl)],
470 immediate_size: 0,
471 });
472 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
473 label: Some("transition"),
474 address_mode_u: wgpu::AddressMode::ClampToEdge,
475 address_mode_v: wgpu::AddressMode::ClampToEdge,
476 address_mode_w: wgpu::AddressMode::ClampToEdge,
477 mag_filter: wgpu::FilterMode::Linear,
478 min_filter: wgpu::FilterMode::Linear,
479 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
480 ..Default::default()
481 });
482 let pipelines = TransitionKind::ALL
483 .iter()
484 .map(|&kind| {
485 let src = format!("{HEADER}\n{}", body(kind));
486 let sm = device.create_shader_module(wgpu::ShaderModuleDescriptor {
487 label: Some(kind.name()),
488 source: wgpu::ShaderSource::Wgsl(src.into()),
489 });
490 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
491 label: Some(kind.name()),
492 layout: Some(&layout),
493 vertex: wgpu::VertexState {
494 module: &sm,
495 entry_point: Some("vs_main"),
496 compilation_options: Default::default(),
497 buffers: &[],
498 },
499 fragment: Some(wgpu::FragmentState {
500 module: &sm,
501 entry_point: Some("fs_main"),
502 compilation_options: Default::default(),
503 targets: &[Some(wgpu::ColorTargetState {
504 format: output_format,
505 blend: None,
506 write_mask: wgpu::ColorWrites::ALL,
507 })],
508 }),
509 primitive: wgpu::PrimitiveState::default(),
510 depth_stencil: None,
511 multisample: wgpu::MultisampleState::default(),
512 multiview_mask: None,
513 cache: None,
514 })
515 })
516 .collect();
517 Self {
518 device: device.clone(),
519 bgl,
520 sampler,
521 pipelines,
522 srgb_target: output_format.is_srgb(),
523 }
524 }
525
526 pub fn draw(
529 &self,
530 encoder: &mut wgpu::CommandEncoder,
531 old: &wgpu::TextureView,
532 new: &wgpu::TextureView,
533 target: &wgpu::TextureView,
534 size: (u32, u32),
535 p: &TransitionParams,
536 ) {
537 let u = TransitionUniforms {
538 resolution: [
539 size.0 as f32,
540 size.1 as f32,
541 0.0,
542 if self.srgb_target { 1.0 } else { 0.0 },
543 ],
544 duration_params: [
545 p.linear as f32,
546 p.cosine as f32,
547 p.bicubic as f32,
548 p.duration as f32,
549 ],
550 time_params: [p.time as f32, p.time_delta as f32, 0.0, 0.0],
551 rand_static: p.rand_static,
552 };
553 let buf = self
554 .device
555 .create_buffer_init(&wgpu::util::BufferInitDescriptor {
556 label: Some("transition uniforms"),
557 contents: bytemuck::bytes_of(&u),
558 usage: wgpu::BufferUsages::UNIFORM,
559 });
560 let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
561 label: Some("transition"),
562 layout: &self.bgl,
563 entries: &[
564 wgpu::BindGroupEntry {
565 binding: 0,
566 resource: buf.as_entire_binding(),
567 },
568 wgpu::BindGroupEntry {
569 binding: 1,
570 resource: wgpu::BindingResource::TextureView(old),
571 },
572 wgpu::BindGroupEntry {
573 binding: 2,
574 resource: wgpu::BindingResource::TextureView(new),
575 },
576 wgpu::BindGroupEntry {
577 binding: 3,
578 resource: wgpu::BindingResource::Sampler(&self.sampler),
579 },
580 ],
581 });
582 let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
583 label: Some("transition"),
584 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
585 view: target,
586 depth_slice: None,
587 resolve_target: None,
588 ops: wgpu::Operations {
589 load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
590 store: wgpu::StoreOp::Store,
591 },
592 })],
593 ..Default::default()
594 });
595 rp.set_pipeline(&self.pipelines[p.kind.index()]);
596 rp.set_bind_group(0, &bg, &[]);
597 rp.draw(0..3, 0..1);
598 }
599}
600
601#[cfg(test)]
602mod tests {
603 use super::*;
604
605 #[test]
606 fn progress_curves_follow_projectm() {
607 let p = TransitionParams::new(TransitionKind::SimpleBlend, [0; 4], 3.0, 0.0, 0.0);
608 assert_eq!((p.linear, p.cosine, p.bicubic), (0.0, 0.0, 0.0));
609 let p = TransitionParams::new(TransitionKind::SimpleBlend, [0; 4], 3.0, 1.5, 0.0);
610 assert!((p.cosine - 0.5).abs() < 1e-15);
611 assert!((p.bicubic - 0.5).abs() < 1e-15);
612 let p = TransitionParams::new(TransitionKind::SimpleBlend, [0; 4], 3.0, 3.0, 0.0);
613 assert_eq!(p.linear, 1.0);
614 assert!((p.cosine - 1.0).abs() < 1e-15 && (p.bicubic - 1.0).abs() < 1e-15);
615 let p = TransitionParams::new(TransitionKind::SimpleBlend, [0; 4], 4.0, 1.0, 0.0);
617 assert!((p.bicubic - 4.0 * 0.25f64.powi(3)).abs() < 1e-15);
618 let p = TransitionParams::new(TransitionKind::SimpleBlend, [0; 4], 0.0, 0.0, 0.0);
620 assert_eq!((p.linear, p.cosine, p.bicubic), (1.0, 1.0, 1.0));
621 }
622
623 #[test]
624 fn kind_order_matches_projectm() {
625 let names: Vec<_> = TransitionKind::ALL.iter().map(|k| k.name()).collect();
626 assert_eq!(
627 names,
628 [
629 "circle",
630 "plasma",
631 "simple_blend",
632 "sweep",
633 "warp",
634 "zoom_blur"
635 ]
636 );
637 assert_eq!(TransitionKind::from_index(8), TransitionKind::SimpleBlend);
638 }
639}