summaryrefslogtreecommitdiff
path: root/tangle/LLBM/sdf.h
blob: 656c109cd2754f3b8e5906bad5ea49ab20e6c20a (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
65
66
67
68
69
70
71
72
73
74
75
#pragma once
#include <vector_types.h>
#include <cuda-samples/Common/helper_math.h>

template <typename SDF, typename V>
__device__ __host__
float approximateDistance(SDF sdf, V origin, V dir, float d0, float d1, float eps=1e-2, unsigned N=128) {
  float distance = d0;
  float delta = (d1-d0) / N;
  for (unsigned i=0; i < N; ++i) {
    float d = sdf(origin + distance*dir);
    if (d < eps) {
      return distance;
    }
    distance += d;
    if (distance > d1) {
      return d1;
    }
  }
  return d1;
}

namespace sdf {

template <typename V>
__device__ __host__ float sphere(V p, float r) {
  return length(p) - r;
}

__device__ __host__ float box(float3 p, float3 b) {
  float3 q = fabs(p) - b;
  return length(fmaxf(q,make_float3(0))) + fmin(fmax(q.x,fmax(q.y,q.z)),0);
}

__device__ __host__ float cylinder(float3 p, float r, float h) {
	return fmax(length(make_float2(p.x,p.y)) - r, fabs(p.z) - 0.5*h);
}

__device__ __host__ float add(float a, float b) {
  return fmin(a, b);
}

__device__ __host__ float intersect(float a, float b) {
  return fmax(a, b);
}

__device__ __host__ float sub(float a, float b) {
  return intersect(-a, b);
}

__device__ __host__ float sadd(float a, float b, float k) {
  float h = clamp(0.5f + 0.5f*(b-a)/k, 0.0f, 1.0f);
  return lerp(b, a, h) - k*h*(1.f-h);
}

__device__ __host__ float ssub(float a, float b, float k) {
  float h = clamp(0.5f - 0.5f*(b+a)/k, 0.f, 1.f);
  return lerp(b, -a, h) + k*h*(1.f-h);
}

__device__ __host__ float sintersect(float a, float b, float k) {
  float h = clamp(0.5f - 0.5f*(b-a)/k, 0.f, 1.f);
  return lerp(b, a, h) + k*h*(1.f-h);
}

}

template <typename SDF>
__device__ float3 sdf_normal(SDF sdf, float3 v, float eps=1e-4) {
  return normalize(make_float3(
    sdf(make_float3(v.x + eps, v.y, v.z)) - sdf(make_float3(v.x - eps, v.y, v.z)),
    sdf(make_float3(v.x, v.y + eps, v.z)) - sdf(make_float3(v.x, v.y - eps, v.z)),
    sdf(make_float3(v.x, v.y, v.z + eps)) - sdf(make_float3(v.x, v.y, v.z - eps))
  ));
}