Skip to content

Latest commit

 

History

History
142 lines (111 loc) · 2.85 KB

distancefields.org

File metadata and controls

142 lines (111 loc) · 2.85 KB

Contents

Shape primitives

Plane

float sdPlane(vec3 p, vec3 n, float w) {
  return dot(n, p) + w;
}

float sdPlane(vec3 p, vec3 pp, vec3 n) {
  return dot(n, p) - dot(n, pp);
}

Sphere

float sdSphere(vec3 p, float radius) {
  return length(p) - radius;
}

AABB

float sdAABB(vec3 p, vec3 b) {
  vec3 d = abs(p) - b;
  return min(max(d.x, max(d.y, d.z)), 0.0) + length(max(d, 0.0));
}

Torus

float sdTorus(vec3 p, float r1, float r2) {
  return length(vec2(length(p.xz) - r2, p.y)) - r1;
}

Cylinder

float sdCylinder(vec3 p, float h, float r) {
  vec2 d = abs(vec2(length(p.xz), p.y)) - vec2(h, r);
  return min(max(d.x, d.y), 0.0) + length(max(d, 0.0));
}

Capsule

float sdCapsule(vec3 p, vec3 a, vec3 b, float r) {
  vec3 pa = p - a, ba = b - a;
  float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);
  return length(pa - ba * h) - r;
}

Shape operations

Subtraction

float sdOpSub(float d1, float d2) {
  return max(-d2, d1);
}

Union

float sdOpUnion(float d1, float d2) {
  return min(d1, d2);
}

Blending

float sdOpBlend(float a, float b, float f) {
  float h = clamp(0.5 + 0.5 * (b - a) / f, 0.0, 1.0);
  return mix(b, a, h) - f * h * (1.0 - h);
}

Complete namespace definition

(ns thi.ng.glsl.distancefields
  (:require
   [thi.ng.glsl.core :as glsl :include-macros true]))

(glsl/defglsl sd-plane
  nil "
  <<plane>>")

(glsl/defglsl sd-sphere
  nil "
  <<sphere>>")

(glsl/defglsl sd-aabb
  nil "
  <<aabb>>")

(glsl/defglsl sd-torus
  nil "
  <<torus>>")

(glsl/defglsl sd-cylinder
  nil "
  <<cylinder>>")

(glsl/defglsl sd-capsule
  nil "
  <<capsule>>")

(glsl/defglsl sd-op-sub
  nil "
  <<op-sub>>")

(glsl/defglsl sd-op-union
  nil "
  <<op-union>>")

(glsl/defglsl sd-op-blend
  nil "
  <<op-blend>>")