summaryrefslogtreecommitdiff
path: root/shaders/polygon.glsl
blob: e33aaf75647fdaaac3c97a90cffd05a7e62c15c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#version 330 core

// --------------------------------------------------------------------------------
// Regular polygon shader
//
// ref: https://thndl.com/square-shaped-shaders.html
// ref: https://thebookofshaders.com/07/
//
// @model quad
// @uniform int   u_n  3 3 12
// @uniform color u_bg 0 0 0 1
// @uniform color u_fg 1 1 1 1
//
// SPDX-License-Identifier: 0BSD
// --------------------------------------------------------------------------------

// --------------------------------------------------------------------------------
// Uniforms
// --------------------------------------------------------------------------------
uniform float u_time;
uniform vec2  u_res;
uniform int   u_n;
uniform vec4  u_bg;
uniform vec4  u_fg;

// --------------------------------------------------------------------------------
// Vertex outputs
// --------------------------------------------------------------------------------
in vec2 v_p;
in vec2 v_t;

// --------------------------------------------------------------------------------
// Fragment outputs
// --------------------------------------------------------------------------------
out vec4 f_c;

// --------------------------------------------------------------------------------
// Entry point
// --------------------------------------------------------------------------------

#define PI 3.14159265359

void main()
{
  // Centered with square aspect ratio
  vec2 st      = gl_FragCoord.xy / u_res.xy;
  float aspect = u_res.x / u_res.y;
  if (aspect > 1.0f) { st.x = (st.x - 0.5f) * aspect + 0.5f; }
  else               { st.y = (st.y - 0.5f) / aspect + 0.5f; }

  // Remap [0, 1] to [-1, 1]
  st = st * 2.0f - 1.0f;

  // Angle of pixel from center + rotation
  float a = atan(st.y, st.x) + u_time * 0.2f;

  // Angle of each sector from center
  float r = (PI * 2.0f) / float(u_n);

  // Polar polygon edge test. cos(theta) = dot product.
  float d = cos(floor(0.5f + a / r) * r - a) * length(st);

  f_c = vec4(vec3(mix(u_bg, u_fg, 1.0f - step(0.5f, d))), 1.0f);
}