video / src /jiangnan /engine /rng.ts
Ethscriptions's picture
暮归江南 · 步骤2-3:渲染引擎、村落与道具
2b0432b verified
Raw History Blame Contribute Delete
2.57 kB
// Deterministic random numbers and noise. Everything in the film is a pure
// function of time + fixed seeds, so preview, export, covers and live photos
// always show identical frames.
export function mulberry32(seed: number) {
let a = seed >>> 0
return () => {
a = (a + 0x6d2b79f5) >>> 0
let t = a
t = Math.imul(t ^ (t >>> 15), t | 1)
t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}
}
export type Rng = ReturnType<typeof mulberry32>
export const rrange = (r: Rng, a: number, b: number) => a + (b - a) * r()
export const rpick = <T,>(r: Rng, arr: readonly T[]): T => arr[Math.floor(r() * arr.length) % arr.length]
export function hash2(x: number, y: number, seed = 0) {
let h = Math.imul(x | 0, 374761393) + Math.imul(y | 0, 668265263) + Math.imul(seed | 0, 2246822519)
h = Math.imul(h ^ (h >>> 13), 1274126177)
h ^= h >>> 16
return (h >>> 0) / 4294967296
}
export function hash1(x: number, seed = 0) {
return hash2(x, 917, seed)
}
const fade = (t: number) => t * t * (3 - 2 * t)
export function valueNoise2(x: number, y: number, seed = 0) {
const xi = Math.floor(x), yi = Math.floor(y)
const xf = x - xi, yf = y - yi
const a = hash2(xi, yi, seed), b = hash2(xi + 1, yi, seed)
const c = hash2(xi, yi + 1, seed), d = hash2(xi + 1, yi + 1, seed)
const u = fade(xf), v = fade(yf)
return (a + (b - a) * u) * (1 - v) + (c + (d - c) * u) * v
}
export function fbm2(x: number, y: number, oct = 5, seed = 0, lac = 2.03, gain = 0.5) {
let amp = 0.5, f = 1, sum = 0, norm = 0
for (let i = 0; i < oct; i++) {
sum += amp * valueNoise2(x * f, y * f, seed + i * 31)
norm += amp
amp *= gain
f *= lac
}
return sum / norm
}
export function ridged2(x: number, y: number, oct = 6, seed = 0) {
let amp = 0.5, f = 1, sum = 0, norm = 0, prev = 1
for (let i = 0; i < oct; i++) {
let n = 1 - Math.abs(valueNoise2(x * f, y * f, seed + i * 17) * 2 - 1)
n = n * n
sum += amp * n * prev
prev = n
norm += amp
amp *= 0.5
f *= 2.07
}
return sum / norm
}
export const clamp = (v: number, a = 0, b = 1) => (v < a ? a : v > b ? b : v)
export const lerp = (a: number, b: number, t: number) => a + (b - a) * t
export const smoothstep = (a: number, b: number, v: number) => {
const t = clamp((v - a) / (b - a))
return t * t * (3 - 2 * t)
}
export const easeInOut = (t: number) => {
t = clamp(t)
return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2
}
export const easeSine = (t: number) => 0.5 - 0.5 * Math.cos(Math.PI * clamp(t))