import * as THREE from "three";

function hashNoise(x: number, y: number, z: number) {
  const s = Math.sin(x * 12.9898 + y * 78.233 + z * 37.719) * 43758.5453;
  return s - Math.floor(s);
}

export function makeRockGeometry(seed: number, detail = 1) {
  const geo = new THREE.IcosahedronGeometry(1, detail);
  const pos = geo.attributes.position;
  const v = new THREE.Vector3();
  for (let i = 0; i < pos.count; i++) {
    v.fromBufferAttribute(pos, i);
    const nrm = v.clone().normalize();
    const n = hashNoise(v.x * 1.8 + seed, v.y * 2.1, v.z * 1.6);
    v.copy(nrm).multiplyScalar(0.7 + n * 0.42);
    if (v.y < -0.15) v.y *= 0.62;
    pos.setXYZ(i, v.x, v.y, v.z);
  }
  geo.computeVertexNormals();
  return geo;
}

export function scatterRocks(count: number, seed: number) {
  let n = seed;
  const rand = () => {
    n = (n * 16807) % 2147483647;
    return (n & 0xffff) / 0xffff;
  };
  const items: { position: [number, number, number]; scale: [number, number, number]; rot: number }[] =
    [];
  let guard = 0;
  while (items.length < count && guard < count * 12) {
    guard += 1;
    const x = (rand() - 0.5) * 90;
    const z = (rand() - 0.5) * 90;
    if (Math.abs(x) < 9 && z < 18 && z > -18) continue;
    if (Math.hypot(x, z) < 10) continue;
    const s = 0.25 + rand() * 0.7;
    items.push({
      position: [x, s * 0.35, z],
      scale: [s, s * (0.6 + rand() * 0.7), s],
      rot: rand() * Math.PI * 2,
    });
  }
  return items;
}
