Public
Edited
Mar 14, 2021
4 stars
Insert cell
Insert cell
Insert cell
code = {
let colorValue1 = Math.random()
let rndRot = () => Math.PI/4*Math.random() + ''
let rndTrans = () => Math.random()*.3 + .2 + ''
let rndScale = () => Math.random()*.5 + 1. + ''
let grammar = tracery.createGrammar({
'origin': `
#colors#
float scaleCumulative = 1., scale;
for(int i = 0; i < #iter_val#; i++){
#body#
}
`,
'colors': `vec3 c1=hsv(#color_value1#,.5,1.);vec3 c2=hsv(#color_value2#,1.,1.);vec3 c3=hsv(#color_value3#,.5,1.); `,
'color_value1': colorValue1 + '',
'color_value2': colorValue1+.15 + '',
'color_value3': colorValue1+.3 + '',
'iter_val': ['3', '4'],
'body': [`#body# #op#`, `#body# #op#`, `#body# #op#`, `#mirror# #invert# #trans# #scale#`],
'op': [`#rot#`, `#trans#`, `#mirror#`, `#invert#`],
'rot': `uv *= rot(#rot_val#);`,
'rot_val': [rndRot(), rndRot(), rndRot()],
'scale': `scale = #scale_val#; uv *= scale; scaleCumulative *= scale;`,
'scale_val': [rndScale(), rndScale(), rndScale()],
'trans': `uv-=vec2(#trans_val#, #trans_val#);`,
'trans_val': [rndTrans(), rndTrans(), rndTrans()],
'mirror': `uv = abs(uv);`,
'invert': `uv /= dot(uv,uv);`,
})
let result = grammar.flatten('#origin#')
console.log(result)
return result;
}
Insert cell
fragmentShader = {
const shader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(shader, `
precision highp float;
uniform vec2 u_size;
mat2 rot(float a){float s=sin(a),c=cos(a);return mat2(c,-s,s,c);}
vec3 hsv(float h, float s, float v){
vec4 t = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
vec3 p = abs(fract(vec3(h) + t.xyz) * 6.0 - vec3(t.w));
return v * mix(vec3(t.x), clamp(p - vec3(t.x), 0.0, 1.0), s);
}
void main() {
vec2 uv = (gl_FragCoord.xy * 2. - u_size) / u_size;

${code}

float light;
// light = clamp(uv.x, 0., 1.);
// light = floor(light*2.)/2.;
light = sin(length(uv)*scaleCumulative)*.5+.5;
//gl_FragColor = vec4(vec3(light), 1);

gl_FragColor.rgb = (light<.5) ?
mix(c1, c2, clamp(light*2., 0., 1.)) :
mix(c2, c3, clamp(light*2. - 1., 0., 1.));

gl_FragColor.a = 1.;
}
`);
gl.compileShader(shader);
if (gl.getShaderParameter(shader, gl.COMPILE_STATUS)) return shader;
throw new Error(gl.getShaderInfoLog(shader));
}
Insert cell
Insert cell
Insert cell
{
var image = document.querySelector('canvas.webgl')
.toDataURL("image/png").replace("image/png", "image/octet-stream");
window.location.href=image;
}
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more