map/random.js
2026-05-20 17:15:09 +09:00

51 lines
1.2 KiB
JavaScript

import { clamp } from "./grid.js";
export function hash2(x, y, seed) {
let h = Math.imul((x | 0) ^ (seed | 0), 374761393) + Math.imul((y | 0) ^ ((seed >>> 1) | 0), 668265263);
h = (h ^ (h >>> 13)) >>> 0;
h = Math.imul(h, 1274126177) >>> 0;
return ((h ^ (h >>> 16)) >>> 0) / 4294967295;
}
export function rand(seed, n) {
return hash2(n * 7919 + 17, n * 104729 + 31, seed);
}
export function smoothstep(t) {
t = clamp(t);
return t * t * (3 - 2 * t);
}
export function lerp(a, b, t) {
return a + (b - a) * t;
}
export function valueNoise(x, y, seed, scale) {
const sx = x / scale;
const sy = y / scale;
const x0 = Math.floor(sx);
const y0 = Math.floor(sy);
const tx = smoothstep(sx - x0);
const ty = smoothstep(sy - y0);
const a = hash2(x0, y0, seed);
const b = hash2(x0 + 1, y0, seed);
const c = hash2(x0, y0 + 1, seed);
const d = hash2(x0 + 1, y0 + 1, seed);
return lerp(lerp(a, b, tx), lerp(c, d, tx), ty);
}
export function fbm(x, y, seed) {
let amp = 1;
let scale = 54;
let sum = 0;
let norm = 0;
for (let i = 0; i < 5; i++) {
sum += valueNoise(x, y, seed + i * 101, scale) * amp;
norm += amp;
amp *= 0.5;
scale *= 0.5;
}
return sum / norm;
}