Skip to content

Enhance p5.strands noise() to support noise(x, y) and 4-octave fractal noise #7964

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

Open
wants to merge 2 commits into
base: dev-2.0
Choose a base branch
from
Open
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
14 changes: 13 additions & 1 deletion src/webgl/ShaderGenerator.js
Original file line number Diff line number Diff line change
Expand Up @@ -1641,8 +1641,20 @@ function shadergenerator(p5, fn) {

GLOBAL_SHADER.output.vertexDeclarations.add(noiseGLSL);
GLOBAL_SHADER.output.fragmentDeclarations.add(noiseGLSL);
return fnNodeConstructor('noise', args, { args: ['vec2'], returnType: 'float' });
// Handle noise(x, y) as noise(vec2)
let nodeArgs;
if (args.length === 2) {
nodeArgs = [fn.vec2(args[0], args[1])];
} else {
nodeArgs = args;
}

return fnNodeConstructor('noise', nodeArgs, {
args: ['vec2'],
returnType: 'float'
});
};

}


Expand Down
19 changes: 15 additions & 4 deletions src/webgl/shaders/functions/noiseGLSL.glsl
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,34 @@ vec2 random2(vec2 st) {
return -1.0 + 2.0 * fract(sin(st) * 43758.5453123);
}

float noise(vec2 st) {
float baseNoise(vec2 st) {
vec2 i = floor(st);
vec2 f = fract(st);

// Four corners in 2D of a tile
vec2 a = random2(i);
vec2 b = random2(i + vec2(1.0, 0.0));
vec2 c = random2(i + vec2(0.0, 1.0));
vec2 d = random2(i + vec2(1.0, 1.0));

// Smooth interpolation
vec2 u = f * f * (3.0 - 2.0 * f);

// Mix the results
return mix(mix(dot(a, f - vec2(0.0, 0.0)),
dot(b, f - vec2(1.0, 0.0)), u.x),
mix(dot(c, f - vec2(0.0, 1.0)),
dot(d, f - vec2(1.0, 1.0)), u.x), u.y);
}

// Fractal noise using 4 octaves
float noise(vec2 st) {
float result = 0.0;
float amplitude = 1.0;
float frequency = 1.0;

for (int i = 0; i < 4; i++) {
result += amplitude * baseNoise(st * frequency);
frequency *= 2.0;
amplitude *= 0.5;
}

return result;
}
Loading