Skip to content

Commit 815ef71

Browse files
authored
Merge pull request #20 from LykenSol/llXSzX
Ported "Moving Square" (https://www.shadertoy.com/view/llXSzX).
2 parents a0e25d1 + 24e0ed4 commit 815ef71

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

shaders/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ pub mod heart;
1818
pub mod mandelbrot_smooth;
1919
pub mod miracle_snowflakes;
2020
pub mod morphing;
21+
pub mod moving_square;
2122
pub mod phantom_star;
2223
pub mod playing_marble;
2324
pub mod protean_clouds;
@@ -169,6 +170,7 @@ pub fn fs(constants: &ShaderConstants, mut frag_coord: Vec2) -> Vec4 {
169170
mouse,
170171
}
171172
.main_image(&mut color, frag_coord),
173+
19 => moving_square::Inputs { resolution, time }.main_image(&mut color, frag_coord),
172174
_ => {}
173175
}
174176
pow(color.truncate(), 2.2).extend(color.w)

shaders/src/moving_square.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
//! Ported to Rust from <https://www.shadertoy.com/view/llXSzX>
2+
3+
use shared::*;
4+
use spirv_std::glam::{vec3, Mat2, Vec2, Vec3, Vec3Swizzles, Vec4};
5+
6+
// Note: This cfg is incorrect on its surface, it really should be "are we compiling with std", but
7+
// we tie #[no_std] above to the same condition, so it's fine.
8+
#[cfg(target_arch = "spirv")]
9+
use spirv_std::num_traits::Float;
10+
11+
pub struct Inputs {
12+
pub resolution: Vec3,
13+
pub time: f32,
14+
}
15+
16+
fn rect(uv: Vec2, pos: Vec2, r: f32) -> Vec4 {
17+
let re_c: Vec2 = (uv - pos).abs();
18+
let dif1: Vec2 = re_c - Vec2::splat(r / 2.);
19+
let dif2: Vec2 = (re_c - Vec2::splat(r / 2.)).clamp(Vec2::zero(), Vec2::one());
20+
let d1: f32 = (dif1.x + dif1.y).clamp(0.0, 1.0);
21+
let _d2: f32 = (dif2.x + dif2.y).clamp(0.0, 1.0);
22+
23+
Vec4::splat(d1)
24+
}
25+
26+
impl Inputs {
27+
pub fn main_image(&self, frag_color: &mut Vec4, frag_coord: Vec2) {
28+
let mut uv: Vec2 = frag_coord;
29+
let t: f32 = self.time.sin();
30+
31+
let c: Vec2 = self.resolution.xy() * 0.5; // + sin(iTime) * 50.;
32+
33+
uv = Mat2::from_cols_array(&[t.cos(), -t.sin(), t.sin(), t.cos()]) * (uv - c) + c;
34+
35+
*frag_color = rect(uv, c, (self.time * 10.).sin() * 50. + 50.);
36+
*frag_color *= vec3(0.5, 0.2, 1.).extend(1.);
37+
*frag_color += rect(uv, c, self.time.sin() * 50. + 50.);
38+
*frag_color *= vec3(0.5, 0.8, 1.).extend(1.);
39+
}
40+
}

shared/src/lib.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,12 @@ impl Clamp for f32 {
8181
}
8282
}
8383

84+
impl Clamp for Vec2 {
85+
fn clamp(self, min: Self, max: Self) -> Self {
86+
self.max(min).min(max)
87+
}
88+
}
89+
8490
impl Clamp for Vec3 {
8591
fn clamp(self, min: Self, max: Self) -> Self {
8692
self.max(min).min(max)

0 commit comments

Comments
 (0)