Skip to content

Commit

Permalink
Merge pull request #24 from johanhelsing/fix-incorrect-star-sdf
Browse files Browse the repository at this point in the history
Fix star sdf function
  • Loading branch information
johanhelsing authored Apr 8, 2023
2 parents 829cdd4 + 6128a62 commit bddaa89
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
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

0 comments on commit bddaa89

Please sign in to comment.