Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix star sdf function #24

Merged
merged 1 commit into from
Apr 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions assets/gallery/star_4.wgsl
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#import bevy_smud::shapes

fn sdf(p: vec2<f32>) -> f32 {
return sd_star(p * 0.5, 10., 4, 3.0);
}
9 changes: 8 additions & 1 deletion assets/shapes.wgsl
Original file line number Diff line number Diff line change
Expand Up @@ -189,14 +189,21 @@ fn sd_star_5(p: vec2<f32>, r: f32, rf: f32) -> f32 {
return length(p - ba * h) * sign(p.y * ba.x - p.x * ba.y);
}

// wgsl made the cowardly choice of keeping an incorrectly named modf,
// function and doesn't currently have a glsl mod equivalent :(
// see: https://github.com/gpuweb/gpuweb/issues/3987
fn modulo(x: f32, y: f32) -> f32 {
return x - y * floor(x / y);
}

fn sd_star(p: vec2<f32>, r: f32, n: i32, m: f32) -> f32 {
// next 4 lines can be precomputed for a given shape
let an = 3.141593 / f32(n);
let en = 3.141593 / m; // m is between 2 and n
let acs = vec2<f32>(cos(an), sin(an));
let ecs = vec2<f32>(cos(en), sin(en)); // ecs=vec2(0, 1) for regular polygon

let bn = atan2(p.x, p.y) % (2. * an) - an;
let bn = modulo(atan2(p.x, p.y), (2. * an)) - an;
var p = length(p) * vec2<f32>(cos(bn), abs(sin(bn)));
p = p - r * acs;
p = p + ecs * clamp(-dot(p, ecs), 0., r * acs.y / ecs.y);
Expand Down
1 change: 1 addition & 0 deletions examples/gallery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ fn setup(
asset_server.load("gallery/rounded_x.wgsl"),
asset_server.load("gallery/ellipse.wgsl"),
asset_server.load("gallery/star_5.wgsl"),
asset_server.load("gallery/star_4.wgsl"),
asset_server.load("gallery/horseshoe.wgsl"),
asset_server.load("gallery/blobby_cross.wgsl"),
asset_server.load("gallery/hexagon.wgsl"),
Expand Down