yum-archive/Tooner

A toon shader for Unity's BIRP.

git clone https://git.yummers.dev/yum-archive/Tooner

yumFix smooth_min3b0aba1

master
1.8 KiB66 linesraw
1#include "tone_iq.cginc"
2
3#ifndef __TONE_INC
4#define __TONE_INC
5
6// This library contains a bunch of useful tonemapping curves.
7
8// https://knarkowicz.wordpress.com/2016/01/06/aces-filmic-tone-mapping-curve/
9// cc0
10float3 aces_filmic(float3 x) {
11  float a = 2.51f;
12  float b = 0.03f;
13  float c = 2.43f;
14  float d = 0.59f;
15  float e = 0.14f;
16  return saturate((x*(a*x+b))/(x*(c*x+d)+e));
17}
18
19// Clamp x to [0, k].
20// Assumes that x is already on [0, 1].
21// Nice properties:
22//  1. At x=0, the derivative is 1.
23//  2. No transcendental ops, and branchless.
24
25// This original attempt at a smooth minimum function has a problem:
26//   f(x, k) = k * x / (x + k)
27// As k -> inf, f(x, k) -> 1. We want f(x, k) -> k.
28// Claude suggests this:
29//  f(x, a, j) = j * (1 + a) * x / (1 + ax)
30// At x=1:
31//  f(1, a, j) = j * (1 + a) / (1 + a)
32//             = j
33// At infinity, we know that:
34//  b * x / (x + b) -> 1
35// So:
36// f(x, a, j) = j * (1 + a) * x / (1 + ax)
37//            = (j + ja) * x / (1 + ax)
38//            = (jx + jax) / (1 + ax)
39//            = jx / (1 + ax) + jax / (1 + ax)
40//            = j (x / (1 + ax) + ax / (1 + ax))
41// At infinity, this becomes:
42//              j (1/a + 1)
43// So if we want the limit to be k:
44//  k       = j (1/a + 1)
45//  k/j     = 1/a + 1
46//  k/j - 1 = 1/a
47//  a       = 1 / (k/j - 1)
48
49// Smooth, analytic min function.
50// Guarantees that x <= k for all positive x. At x=1, returns j.
51// Caller must ensure that j < k.
52float smooth_min(float x, float j, float k) {
53  float a = 1 / (k / j - 1);
54  return j * (1 + a) * x / (1 + a * x);
55}
56float3 smooth_min(float3 x, float j, float k) {
57  float a = 1 / (k / j - 1);
58  return j * (1 + a) * x / (1 + a * x);
59}
60
61float smooth_clamp(float x, float lo, float hi) {
62  return smooth_max(smooth_min(x, (lo + (hi - lo)/2), hi), lo);
63}
64
65#endif  // __TONE_INC
66