Initial commit: @medieval-kit registry and viewer
A lowpoly medieval procedural model library for Vibe3D, plus the model inspector used to build it. Registry (@medieval-kit, published as @medieval-kit/registry): - core: deterministic mulberry32 RNG, slot-based vertex-coloured materials, a geometry vocabulary (box, prism, stave, band, head, flip), and the stable-anchor part slots the Vibe3D protocol requires - wooden-barrel: 806 tris, 13 separate staves, iron hoops, recessed heads - wooden-crate: 360 tris, plank rows on corner posts, forged straps - iron-brazier: 423 tris, typed actions, per-frame flame flicker, own light The kit declares no renderer capabilities, so it runs on WebGLRenderer as well as WebGPURenderer. Colour variation lives in vertex attributes rather than in materials, so each model keeps one draw call per material. Verification (bun run verify) covers 64 checks without a browser: geometry validity, winding by two measures (radial alignment for bodies of revolution, signed volume for closed solids), coplanar-face detection for z-fighting, stable root and anchor identity across configure(), deterministic seeding, material ownership, and idempotent disposal.
This commit is contained in:
commit
98cfbab180
53 changed files with 10097 additions and 0 deletions
101
src/lib/vibe3d/scifi-kit/generator/batching.ts
Normal file
101
src/lib/vibe3d/scifi-kit/generator/batching.ts
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import {
|
||||
Float32BufferAttribute,
|
||||
Matrix4,
|
||||
Mesh,
|
||||
type BufferGeometry,
|
||||
type Group,
|
||||
type Material,
|
||||
} from 'three/webgpu'
|
||||
import { mergeGeometries, mergeVertices } from 'three/addons/utils/BufferGeometryUtils.js'
|
||||
|
||||
export interface StaticBatchOptions {
|
||||
/** Maps a source material to the material used by its merged batch. */
|
||||
readonly resolveMaterial?: (source: Material) => Material
|
||||
/** Extra vertex attributes to retain for a resolved material. */
|
||||
readonly retainedAttributes?: (
|
||||
resolved: Material,
|
||||
source: Material,
|
||||
) => readonly string[]
|
||||
/** Names the merged mesh created for a material batch. */
|
||||
readonly meshName?: (material: Material) => string
|
||||
}
|
||||
|
||||
/**
|
||||
* Collapses the static meshes below `root` into one mesh per resolved material.
|
||||
* Transforms are baked relative to `root`, so the resulting group remains safe
|
||||
* to animate as one assembly. Source geometries are disposed after the merge.
|
||||
*/
|
||||
export function mergeStaticByMaterial(
|
||||
root: Group,
|
||||
options: StaticBatchOptions = {},
|
||||
): BufferGeometry[] {
|
||||
root.updateMatrixWorld(true)
|
||||
const rootInverse = new Matrix4().copy(root.matrixWorld).invert()
|
||||
const batches = new Map<Material, BufferGeometry[]>()
|
||||
const sourceGeometries = new Set<BufferGeometry>()
|
||||
|
||||
root.traverse((object) => {
|
||||
if (!(object instanceof Mesh) || Array.isArray(object.material)) return
|
||||
const source = object.geometry as BufferGeometry
|
||||
const sourceMaterial = object.material as Material
|
||||
const material = options.resolveMaterial?.(sourceMaterial) ?? sourceMaterial
|
||||
const retained = new Set([
|
||||
'position',
|
||||
'normal',
|
||||
'uv',
|
||||
...(options.retainedAttributes?.(material, sourceMaterial) ?? []),
|
||||
])
|
||||
|
||||
sourceGeometries.add(source)
|
||||
const geometry = source.index ? source.toNonIndexed() : source.clone()
|
||||
geometry.applyMatrix4(object.matrixWorld).applyMatrix4(rootInverse)
|
||||
if (!geometry.getAttribute('normal')) geometry.computeVertexNormals()
|
||||
if (!geometry.getAttribute('uv')) addPlanarUv(geometry)
|
||||
for (const name of Object.keys(geometry.attributes)) {
|
||||
if (!retained.has(name)) geometry.deleteAttribute(name)
|
||||
}
|
||||
|
||||
const geometries = batches.get(material) ?? []
|
||||
geometries.push(geometry)
|
||||
batches.set(material, geometries)
|
||||
})
|
||||
|
||||
root.clear()
|
||||
const mergedGeometries: BufferGeometry[] = []
|
||||
for (const [material, geometries] of batches) {
|
||||
const merged = mergeGeometries(geometries, false)
|
||||
for (const geometry of geometries) geometry.dispose()
|
||||
if (!merged) throw new Error(`Failed to merge static batch for material ${material.name || '(unnamed)'}`)
|
||||
// Sources are expanded before merging so independently-authored meshes can
|
||||
// carry different attribute sets safely. Re-index the finished batch once
|
||||
// those attributes have been normalized: mergeVertices hashes every
|
||||
// retained attribute (normal, UV, wear data, etc.), so only vertices that
|
||||
// are visually identical are shared. This removes the 3-vertices-per-
|
||||
// triangle expansion without smoothing hard edges or changing shaders.
|
||||
const indexed = mergeVertices(merged, 1e-6)
|
||||
merged.dispose()
|
||||
indexed.computeBoundingSphere()
|
||||
const mesh = new Mesh(indexed, material)
|
||||
mesh.name = options.meshName?.(material) ?? material.name
|
||||
root.add(mesh)
|
||||
mergedGeometries.push(indexed)
|
||||
}
|
||||
for (const geometry of sourceGeometries) geometry.dispose()
|
||||
return mergedGeometries
|
||||
}
|
||||
|
||||
function addPlanarUv(geometry: BufferGeometry): void {
|
||||
geometry.computeBoundingBox()
|
||||
const bounds = geometry.boundingBox!
|
||||
const sizeX = Math.max(bounds.max.x - bounds.min.x, 0.001)
|
||||
const sizeY = Math.max(bounds.max.y - bounds.min.y, 0.001)
|
||||
const positions = geometry.getAttribute('position')
|
||||
const uvs: number[] = []
|
||||
for (let index = 0; index < positions.count; index += 1) {
|
||||
uvs.push(
|
||||
(positions.getX(index) - bounds.min.x) / sizeX,
|
||||
(positions.getY(index) - bounds.min.y) / sizeY,
|
||||
)
|
||||
}
|
||||
geometry.setAttribute('uv', new Float32BufferAttribute(uvs, 2))
|
||||
}
|
||||
129
src/lib/vibe3d/scifi-kit/generator/effects.ts
Normal file
129
src/lib/vibe3d/scifi-kit/generator/effects.ts
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
import {
|
||||
DataTexture,
|
||||
LinearFilter,
|
||||
LinearMipmapLinearFilter,
|
||||
RepeatWrapping,
|
||||
RGBAFormat,
|
||||
SRGBColorSpace,
|
||||
UnsignedByteType,
|
||||
} from 'three/webgpu'
|
||||
|
||||
const DEFAULT_SMOKE_TEXTURE_SIZE = 48
|
||||
|
||||
function smokeSmoothstep(edge0: number, edge1: number, value: number): number {
|
||||
const t = Math.min(1, Math.max(0, (value - edge0) / (edge1 - edge0)))
|
||||
return t * t * (3 - 2 * t)
|
||||
}
|
||||
|
||||
function smokeEllipse(
|
||||
px: number,
|
||||
py: number,
|
||||
centreX: number,
|
||||
centreY: number,
|
||||
radiusX: number,
|
||||
radiusY: number,
|
||||
): number {
|
||||
const distance = Math.hypot((px - centreX) / radiusX, (py - centreY) / radiusY)
|
||||
return 1 - smokeSmoothstep(0.52, 1.05, distance)
|
||||
}
|
||||
|
||||
function smokeWisp(
|
||||
px: number,
|
||||
py: number,
|
||||
phase: number,
|
||||
amplitude: number,
|
||||
width: number,
|
||||
): number {
|
||||
const lift = (py + 1) * 0.5
|
||||
const centreX = Math.sin((py + phase) * 5.2) * amplitude
|
||||
+ Math.sin((py + phase) * 10.7) * 0.045
|
||||
const taper = width * (0.72 + lift * 0.55)
|
||||
const lateral = 1 - smokeSmoothstep(0.38, 1.0, Math.abs(px - centreX) / taper)
|
||||
const ends = 1 - smokeSmoothstep(0.84, 1.03, Math.abs(py))
|
||||
return lateral * ends
|
||||
}
|
||||
|
||||
function smokeHash(x: number, y: number): number {
|
||||
const value = Math.sin(x * 127.1 + y * 311.7) * 43758.5453
|
||||
return value - Math.floor(value)
|
||||
}
|
||||
|
||||
function smokeValueNoise(u: number, v: number, frequency: number): number {
|
||||
const x = u * frequency
|
||||
const y = v * frequency
|
||||
const x0 = Math.floor(x)
|
||||
const y0 = Math.floor(y)
|
||||
const x1 = (x0 + 1) % frequency
|
||||
const y1 = (y0 + 1) % frequency
|
||||
const tx = x - x0
|
||||
const ty = y - y0
|
||||
const sx = tx * tx * (3 - 2 * tx)
|
||||
const sy = ty * ty * (3 - 2 * ty)
|
||||
const low = smokeHash(x0, y0) * (1 - sx) + smokeHash(x1, y0) * sx
|
||||
const high = smokeHash(x0, y1) * (1 - sx) + smokeHash(x1, y1) * sx
|
||||
return low * (1 - sy) + high * sy
|
||||
}
|
||||
|
||||
function tileableFbm(u: number, v: number): number {
|
||||
let total = 0
|
||||
let amplitude = 0.5
|
||||
let weight = 0
|
||||
for (const frequency of [3, 6, 12, 24]) {
|
||||
total += smokeValueNoise(u, v, frequency) * amplitude
|
||||
weight += amplitude
|
||||
amplitude *= 0.5
|
||||
}
|
||||
return total / weight
|
||||
}
|
||||
|
||||
export interface SmokeTextureOptions {
|
||||
/** Square texture resolution. Defaults to 48 pixels. */
|
||||
readonly size?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* CPU-baked once per model, then sampled by every smoke card. DataTexture keeps
|
||||
* this usable by the headless asset renderer as well as the browser preview;
|
||||
* there is no DOM canvas dependency and no per-frame texture work.
|
||||
*/
|
||||
export function createSmokeTexture(options: SmokeTextureOptions = {}): DataTexture {
|
||||
const size = Math.max(2, Math.round(options.size ?? DEFAULT_SMOKE_TEXTURE_SIZE))
|
||||
const data = new Uint8Array(size * size * 4)
|
||||
const centre = (size - 1) * 0.5
|
||||
for (let y = 0; y < size; y += 1) {
|
||||
for (let x = 0; x < size; x += 1) {
|
||||
const u = x / size
|
||||
const v = y / size
|
||||
const px = (x - centre) / centre
|
||||
const py = (y - centre) / centre
|
||||
const noise = tileableFbm(u, v)
|
||||
const fineWisp = smokeWisp(px, py, 0.08, 0.2, 0.24)
|
||||
const splitWisp = smokeWisp(px, py, 0.41, -0.16, 0.18) * 0.72
|
||||
const highWisp = smokeWisp(px, py, 0.73, 0.12, 0.15) * 0.62
|
||||
const billow = Math.max(
|
||||
smokeEllipse(px, py, -0.14, -0.18, 0.42, 0.55) * 0.34,
|
||||
smokeEllipse(px, py, 0.13, 0.28, 0.36, 0.48) * 0.28,
|
||||
)
|
||||
const envelope = Math.max(fineWisp, splitWisp, highWisp, billow)
|
||||
const density = Math.min(1, Math.max(0, envelope * (0.3 + noise * 0.95) - 0.08))
|
||||
const alpha = Math.floor(255 * density ** 1.12)
|
||||
const lift = Math.min(1, Math.max(0, 0.52 - px * 0.24 + py * 0.34))
|
||||
const shade = Math.floor(150 + (240 - 150) * lift * (1 - density * 0.4))
|
||||
const index = (y * size + x) * 4
|
||||
data[index] = shade
|
||||
data[index + 1] = shade
|
||||
data[index + 2] = shade
|
||||
data[index + 3] = alpha
|
||||
}
|
||||
}
|
||||
|
||||
const textureMap = new DataTexture(data, size, size, RGBAFormat, UnsignedByteType)
|
||||
textureMap.colorSpace = SRGBColorSpace
|
||||
textureMap.wrapS = RepeatWrapping
|
||||
textureMap.wrapT = RepeatWrapping
|
||||
textureMap.magFilter = LinearFilter
|
||||
textureMap.minFilter = LinearMipmapLinearFilter
|
||||
textureMap.generateMipmaps = true
|
||||
textureMap.needsUpdate = true
|
||||
return textureMap
|
||||
}
|
||||
211
src/lib/vibe3d/scifi-kit/generator/generator.test.ts
Normal file
211
src/lib/vibe3d/scifi-kit/generator/generator.test.ts
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { describe, test } from 'node:test'
|
||||
import {
|
||||
Float32BufferAttribute,
|
||||
Group,
|
||||
InstancedMesh,
|
||||
Matrix4,
|
||||
Mesh,
|
||||
MeshPhysicalMaterial,
|
||||
SphereGeometry,
|
||||
} from 'three/webgpu'
|
||||
import {
|
||||
createWearMaterial,
|
||||
createSmokeTexture,
|
||||
createStaticGlbSnapshot,
|
||||
bakeSurfaceAttributes,
|
||||
filletRing,
|
||||
flatPlate,
|
||||
mergeStaticByMaterial,
|
||||
MaterialLibrary,
|
||||
mountMaterialSource,
|
||||
prism,
|
||||
tuneMaterial,
|
||||
type MaterialHandle,
|
||||
} from './index.ts'
|
||||
|
||||
describe('generator primitives', () => {
|
||||
test('prism authors the geometry and wear attributes expected by the shared helpers', () => {
|
||||
const material = new MeshPhysicalMaterial()
|
||||
const mesh = prism(material, [2, 1, 0.5], [1, 2, 3], {
|
||||
chamfer: [0.2, 0.1, 0.05, 0],
|
||||
fillet: 0.04,
|
||||
bevel: 0.03,
|
||||
})
|
||||
|
||||
assert.deepEqual(mesh.position.toArray(), [1, 2, 3])
|
||||
assert.ok(mesh.geometry.getAttribute('position').count > 0)
|
||||
assert.equal(mesh.geometry.getAttribute('normal').count,
|
||||
mesh.geometry.getAttribute('position').count,
|
||||
)
|
||||
assert.equal(mesh.geometry.getAttribute('aEdge').itemSize, 1)
|
||||
assert.equal(mesh.geometry.getAttribute('aPlane').itemSize, 2)
|
||||
|
||||
mesh.geometry.dispose()
|
||||
material.dispose()
|
||||
})
|
||||
|
||||
test('filletRing and flatPlate expose reusable authoring metadata', () => {
|
||||
const ring = filletRing([[1, 1], [-1, 1], [-1, -1], [1, -1]], 0.1, 2)
|
||||
assert.equal(ring.length, 12)
|
||||
assert.ok(ring.every((point) => Number.isFinite(point.nx + point.ny)))
|
||||
|
||||
const material = new MeshPhysicalMaterial()
|
||||
const engraved = flatPlate(material, [2, 0.25], [0, 0, 0])
|
||||
const painted = flatPlate(material, [2, 0.25], [0, 0, 0], [0, 0, 0], false)
|
||||
assert.equal(engraved.userData.grooveCross, 'y')
|
||||
assert.equal(painted.userData.grooveCross, undefined)
|
||||
engraved.geometry.dispose()
|
||||
painted.geometry.dispose()
|
||||
material.dispose()
|
||||
})
|
||||
})
|
||||
|
||||
describe('generator assembly helpers', () => {
|
||||
test('static GLB snapshots bake wear and omit explicitly excluded effects', () => {
|
||||
const root = new Group()
|
||||
const sourceMaterial = new MeshPhysicalMaterial({ color: 0x8b9294, roughness: 0.5, metalness: 0.3 })
|
||||
const worn = prism(sourceMaterial, [2, 1, 0.5], [0, 0, 0])
|
||||
const smoke = new Group()
|
||||
smoke.name = 'preview smoke'
|
||||
smoke.userData.excludeFromExport = true
|
||||
const orbGeometry = new SphereGeometry(0.1, 8, 6)
|
||||
const orbMaterial = new MeshPhysicalMaterial({ color: 0x55ffff })
|
||||
const orbs = new InstancedMesh(orbGeometry, orbMaterial, 2)
|
||||
const instanceMatrix = new Matrix4()
|
||||
orbs.setMatrixAt(0, instanceMatrix.makeTranslation(-0.2, 0, 0))
|
||||
orbs.setMatrixAt(1, instanceMatrix.makeTranslation(0.2, 0, 0))
|
||||
root.add(worn, smoke, orbs)
|
||||
const wornUv = worn.geometry.getAttribute('uv')
|
||||
wornUv.setXY(0, 0.5, 0.5)
|
||||
wornUv.setXY(1, 0.5, 0.5)
|
||||
wornUv.setXY(2, 0.5, 0.5)
|
||||
bakeSurfaceAttributes(root, new Map([
|
||||
[sourceMaterial, { rub: 1, grime: 0.8, scratch: 0.9 }],
|
||||
]))
|
||||
|
||||
const snapshot = createStaticGlbSnapshot(root, { textureSize: 32 })
|
||||
assert.equal(snapshot.root.getObjectByName('preview smoke'), undefined)
|
||||
assert.equal(snapshot.root.getObjectByProperty('isInstancedMesh', true), undefined)
|
||||
let bakedMeshes = 0
|
||||
let bakedSurface: Mesh | undefined
|
||||
snapshot.root.traverse((object) => {
|
||||
if (!(object instanceof Mesh)) return
|
||||
bakedMeshes += 1
|
||||
if (object.name.includes('baked surface')) bakedSurface = object
|
||||
assert.ok(object.material instanceof MeshPhysicalMaterial)
|
||||
const material = object.material as MeshPhysicalMaterial
|
||||
assert.equal(object.geometry.getAttribute('aMask'), undefined)
|
||||
if (material.normalMap) {
|
||||
const tangent = object.geometry.getAttribute('tangent')
|
||||
assert.ok(tangent)
|
||||
for (let index = 0; index < tangent.count; index += 1) {
|
||||
const length = Math.hypot(tangent.getX(index), tangent.getY(index), tangent.getZ(index))
|
||||
assert.ok(Math.abs(length - 1) < 1e-5, `tangent ${index} has length ${length}`)
|
||||
assert.equal(Math.abs(tangent.getW(index)), 1)
|
||||
}
|
||||
}
|
||||
if (!material.map && !material.normalMap && !material.roughnessMap && !material.metalnessMap) {
|
||||
assert.equal(object.geometry.getAttribute('uv'), undefined)
|
||||
}
|
||||
})
|
||||
assert.ok(bakedMeshes >= 3)
|
||||
const bakedMaterial = bakedSurface?.material as MeshPhysicalMaterial | undefined
|
||||
assert.ok(bakedSurface?.geometry.getAttribute('color'))
|
||||
assert.ok(bakedMaterial?.map)
|
||||
assert.ok(bakedMaterial?.normalMap)
|
||||
assert.ok(bakedMaterial?.roughnessMap)
|
||||
assert.ok(worn.geometry.getAttribute('aMask'), 'the live model must remain unchanged')
|
||||
|
||||
snapshot.dispose()
|
||||
worn.geometry.dispose()
|
||||
sourceMaterial.dispose()
|
||||
orbGeometry.dispose()
|
||||
orbMaterial.dispose()
|
||||
})
|
||||
|
||||
test('smoke textures are deterministic and do not require a DOM canvas', () => {
|
||||
const first = createSmokeTexture({ size: 16 })
|
||||
const second = createSmokeTexture({ size: 16 })
|
||||
assert.equal(first.image.width, 16)
|
||||
assert.equal(first.image.height, 16)
|
||||
assert.deepEqual(first.image.data, second.image.data)
|
||||
assert.ok((first.image.data as Uint8Array).some((value, index) => index % 4 === 3 && value > 0))
|
||||
first.dispose()
|
||||
second.dispose()
|
||||
})
|
||||
|
||||
test('mergeStaticByMaterial remaps batches and retains requested attributes', () => {
|
||||
const root = new Group()
|
||||
const sourceA = new MeshPhysicalMaterial({ name: 'source-a' })
|
||||
const sourceB = new MeshPhysicalMaterial({ name: 'source-b' })
|
||||
const resolved = new MeshPhysicalMaterial({ name: 'resolved' })
|
||||
const first = prism(sourceA, [1, 1, 1], [-1, 0, 0])
|
||||
const second = prism(sourceB, [1, 1, 1], [1, 0, 0])
|
||||
const tag = (mesh: Mesh) => {
|
||||
const count = mesh.geometry.getAttribute('position').count
|
||||
mesh.geometry.setAttribute('batchTag', new Float32BufferAttribute(new Float32Array(count), 1))
|
||||
}
|
||||
tag(first)
|
||||
tag(second)
|
||||
root.add(first, second)
|
||||
|
||||
const geometries = mergeStaticByMaterial(root, {
|
||||
resolveMaterial: () => resolved,
|
||||
retainedAttributes: () => ['aEdge', 'aPlane', 'batchTag'],
|
||||
meshName: () => 'merged-test-batch',
|
||||
})
|
||||
|
||||
assert.equal(geometries.length, 1)
|
||||
assert.equal(root.children.length, 1)
|
||||
const merged = root.children[0] as Mesh
|
||||
assert.equal(merged.material, resolved)
|
||||
assert.equal(merged.name, 'merged-test-batch')
|
||||
assert.ok(merged.geometry.getAttribute('batchTag'))
|
||||
assert.ok(merged.geometry.index, 'merged batches should be re-indexed after attribute normalization')
|
||||
assert.ok(
|
||||
merged.geometry.getAttribute('position').count < (merged.geometry.index?.count ?? 0),
|
||||
're-indexing should share visually identical triangle vertices',
|
||||
)
|
||||
merged.geometry.computeBoundingBox()
|
||||
assert.ok((merged.geometry.boundingBox?.min.x ?? 0) < -1.4)
|
||||
assert.ok((merged.geometry.boundingBox?.max.x ?? 0) > 1.4)
|
||||
|
||||
merged.geometry.dispose()
|
||||
sourceA.dispose()
|
||||
sourceB.dispose()
|
||||
resolved.dispose()
|
||||
})
|
||||
|
||||
test('material helpers are configurable without asset-specific names', () => {
|
||||
const material = new MeshPhysicalMaterial()
|
||||
const handle: MaterialHandle = { key: 'test', material, release: () => undefined }
|
||||
tuneMaterial(handle, 0x123456, 0.7, 0.4, { clearcoat: 0.2, emissive: 1.5 })
|
||||
assert.equal(material.color.getHex(), 0x123456)
|
||||
assert.equal(material.roughness, 0.7)
|
||||
assert.equal(material.metalness, 0.4)
|
||||
assert.equal(material.emissiveIntensity, 1.5)
|
||||
|
||||
const wear = createWearMaterial({ name: 'generator-test / wear', clearcoat: 0.1 })
|
||||
assert.equal(wear.name, 'generator-test / wear')
|
||||
assert.equal(wear.clearcoat, 0.1)
|
||||
wear.dispose()
|
||||
material.dispose()
|
||||
})
|
||||
|
||||
test('material sources can be mounted and restored', () => {
|
||||
const material = new MeshPhysicalMaterial()
|
||||
let acquired = 0
|
||||
const restore = mountMaterialSource({
|
||||
acquire(_options, key) {
|
||||
acquired += 1
|
||||
return { key, material, release: () => undefined }
|
||||
},
|
||||
})
|
||||
const handle = new MaterialLibrary().acquire({ recipeId: 'paint', palette: 'blue' })
|
||||
assert.equal(handle.material, material)
|
||||
assert.equal(acquired, 1)
|
||||
restore()
|
||||
material.dispose()
|
||||
})
|
||||
})
|
||||
913
src/lib/vibe3d/scifi-kit/generator/glb.ts
Normal file
913
src/lib/vibe3d/scifi-kit/generator/glb.ts
Normal file
|
|
@ -0,0 +1,913 @@
|
|||
import {
|
||||
BufferGeometry,
|
||||
Color,
|
||||
DataTexture,
|
||||
Float32BufferAttribute,
|
||||
Group,
|
||||
InstancedMesh,
|
||||
LinearFilter,
|
||||
LinearMipmapLinearFilter,
|
||||
Matrix4,
|
||||
Mesh,
|
||||
MeshPhysicalMaterial,
|
||||
RepeatWrapping,
|
||||
RGBAFormat,
|
||||
SRGBColorSpace,
|
||||
Texture,
|
||||
UnsignedByteType,
|
||||
type BufferAttribute,
|
||||
type InterleavedBufferAttribute,
|
||||
type Object3D,
|
||||
} from 'three/webgpu'
|
||||
import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js'
|
||||
|
||||
export interface StaticGlbOptions {
|
||||
/** Resolution of each embedded baked wear texture. */
|
||||
readonly textureSize?: number
|
||||
/** Additional objects to omit from the static snapshot. */
|
||||
readonly exclude?: (object: Object3D) => boolean
|
||||
}
|
||||
|
||||
export interface StaticGlbSnapshot {
|
||||
readonly root: Object3D
|
||||
dispose(): void
|
||||
}
|
||||
|
||||
interface SurfaceProfile {
|
||||
readonly colour: readonly [number, number, number]
|
||||
readonly roughness: number
|
||||
readonly metalness: number
|
||||
readonly rub: number
|
||||
readonly grime: number
|
||||
readonly scratch: number
|
||||
}
|
||||
|
||||
interface GeometryBucket {
|
||||
readonly profile: SurfaceProfile
|
||||
readonly positions: number[]
|
||||
readonly normals: number[]
|
||||
readonly uvs: number[]
|
||||
readonly colours: number[]
|
||||
}
|
||||
|
||||
interface BakeContext {
|
||||
readonly textureSize: number
|
||||
readonly materials: Map<string, MeshPhysicalMaterial>
|
||||
readonly standardMaterials: Map<MeshPhysicalMaterial, MeshPhysicalMaterial>
|
||||
readonly ownedGeometries: Set<BufferGeometry>
|
||||
readonly ownedMaterials: Set<MeshPhysicalMaterial>
|
||||
readonly ownedTextures: Set<Texture>
|
||||
readonly geometryVariants: Map<BufferGeometry, Map<string, BufferGeometry>>
|
||||
readonly preparedNormalMaterials: Set<MeshPhysicalMaterial>
|
||||
}
|
||||
|
||||
type ReadableAttribute = BufferAttribute | InterleavedBufferAttribute
|
||||
|
||||
const WEAR_ATTRIBUTE_NAMES = ['aMask', 'aColor', 'aSurface', 'aWearDir'] as const
|
||||
|
||||
/**
|
||||
* Clones a model into a static, glTF-safe hierarchy. Preview-only node
|
||||
* materials are replaced without mutating the live model.
|
||||
*/
|
||||
export function createStaticGlbSnapshot(
|
||||
source: Object3D,
|
||||
options: StaticGlbOptions = {},
|
||||
): StaticGlbSnapshot {
|
||||
const root = source.clone(true)
|
||||
root.name = source.name || 'static-model'
|
||||
root.userData = {
|
||||
...root.userData,
|
||||
staticGlb: true,
|
||||
animations: 'omitted',
|
||||
proceduralWear: 'baked to vertex colors and PBR textures',
|
||||
}
|
||||
|
||||
const context: BakeContext = {
|
||||
textureSize: Math.max(32, Math.round(options.textureSize ?? 512)),
|
||||
materials: new Map(),
|
||||
standardMaterials: new Map(),
|
||||
ownedGeometries: new Set(),
|
||||
ownedMaterials: new Set(),
|
||||
ownedTextures: new Set(),
|
||||
geometryVariants: new Map(),
|
||||
preparedNormalMaterials: new Set(),
|
||||
}
|
||||
|
||||
const excluded: Object3D[] = []
|
||||
const wornMeshes: Mesh[] = []
|
||||
root.traverse((object) => {
|
||||
if (object !== root && (object.userData.excludeFromExport === true || options.exclude?.(object))) {
|
||||
excluded.push(object)
|
||||
return
|
||||
}
|
||||
if (object instanceof Mesh && hasWearAttributes(object.geometry)) wornMeshes.push(object)
|
||||
})
|
||||
for (const object of excluded) object.removeFromParent()
|
||||
expandInstancedMeshes(root)
|
||||
|
||||
for (const mesh of wornMeshes) {
|
||||
if (!mesh.parent) continue
|
||||
const replacement = bakeWearMesh(mesh, context)
|
||||
mesh.parent.add(replacement)
|
||||
mesh.removeFromParent()
|
||||
}
|
||||
prepareStandardMaterials(root, context)
|
||||
prepareGeometryForExport(root, context)
|
||||
|
||||
return {
|
||||
root,
|
||||
dispose: () => {
|
||||
for (const geometry of context.ownedGeometries) geometry.dispose()
|
||||
for (const material of context.ownedMaterials) material.dispose()
|
||||
for (const texture of context.ownedTextures) texture.dispose()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function prepareStandardMaterials(root: Object3D, context: BakeContext): void {
|
||||
root.traverse((object) => {
|
||||
if (!(object instanceof Mesh)) return
|
||||
const sources = Array.isArray(object.material) ? object.material : [object.material]
|
||||
const materials = sources.map((source) => {
|
||||
if (!(source instanceof MeshPhysicalMaterial) || context.ownedMaterials.has(source)) return source
|
||||
const existing = context.standardMaterials.get(source)
|
||||
if (existing) return existing
|
||||
const material = source.clone()
|
||||
packDataTextureOrm(material, context)
|
||||
context.standardMaterials.set(source, material)
|
||||
context.ownedMaterials.add(material)
|
||||
return material
|
||||
})
|
||||
object.material = Array.isArray(object.material) ? materials : materials[0]!
|
||||
})
|
||||
}
|
||||
|
||||
function expandInstancedMeshes(root: Object3D): void {
|
||||
const instances: InstancedMesh[] = []
|
||||
root.traverse((object) => {
|
||||
if (object instanceof InstancedMesh) instances.push(object)
|
||||
})
|
||||
const matrix = new Matrix4()
|
||||
for (const source of instances) {
|
||||
if (!source.parent) continue
|
||||
const group = new Group()
|
||||
group.name = source.name
|
||||
group.position.copy(source.position)
|
||||
group.quaternion.copy(source.quaternion)
|
||||
group.scale.copy(source.scale)
|
||||
group.visible = source.visible
|
||||
group.userData = { ...source.userData, gpuInstances: 'expanded for portable glTF' }
|
||||
for (let index = 0; index < source.count; index += 1) {
|
||||
source.getMatrixAt(index, matrix)
|
||||
const mesh = new Mesh(source.geometry, source.material)
|
||||
mesh.name = `${source.name} / instance ${String(index + 1).padStart(2, '0')}`
|
||||
matrix.decompose(mesh.position, mesh.quaternion, mesh.scale)
|
||||
mesh.castShadow = source.castShadow
|
||||
mesh.receiveShadow = source.receiveShadow
|
||||
group.add(mesh)
|
||||
}
|
||||
source.parent.add(group)
|
||||
source.removeFromParent()
|
||||
}
|
||||
}
|
||||
|
||||
function prepareGeometryForExport(root: Object3D, context: BakeContext): void {
|
||||
root.traverse((object) => {
|
||||
if (!(object instanceof Mesh)) return
|
||||
const materials = Array.isArray(object.material) ? object.material : [object.material]
|
||||
const usesUv = materials.some(materialUsesUv)
|
||||
const usesNormalMap = materials.some((material) => (
|
||||
material instanceof MeshPhysicalMaterial && material.normalMap !== null
|
||||
))
|
||||
const variantKey = `${usesUv ? 'uv' : 'no-uv'}/${usesNormalMap ? 'tangent' : 'no-tangent'}`
|
||||
object.geometry = geometryVariant(object.geometry, variantKey, context, (geometry) => {
|
||||
stripNonGltfAttributes(geometry)
|
||||
if (!usesUv) geometry.deleteAttribute('uv')
|
||||
if (usesNormalMap) {
|
||||
if (!geometry.getAttribute('uv')) {
|
||||
throw new Error(`Cannot export normal-mapped mesh without UVs: ${object.name}`)
|
||||
}
|
||||
computePortableTangents(geometry)
|
||||
} else {
|
||||
geometry.deleteAttribute('tangent')
|
||||
}
|
||||
geometry.computeBoundingSphere()
|
||||
})
|
||||
for (const material of materials) {
|
||||
if (!(material instanceof MeshPhysicalMaterial) || context.preparedNormalMaterials.has(material)) continue
|
||||
prepareDataTextureNormal(material, usesNormalMap, context)
|
||||
context.preparedNormalMaterials.add(material)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes explicit glTF tangent frames and supplies a normalized fallback
|
||||
* when a triangle's UVs collapse to a point or line. Three's built-in tangent
|
||||
* builder leaves those vertices at (0, 0, 0), which glTF correctly rejects.
|
||||
*/
|
||||
function computePortableTangents(geometry: BufferGeometry): void {
|
||||
const position = geometry.getAttribute('position')
|
||||
const normal = geometry.getAttribute('normal')
|
||||
const uv = geometry.getAttribute('uv')
|
||||
const index = geometry.index
|
||||
const tangentSum = new Float64Array(position.count * 3)
|
||||
const bitangentSum = new Float64Array(position.count * 3)
|
||||
const triangleIndices = index?.count ?? position.count
|
||||
|
||||
for (let offset = 0; offset < triangleIndices; offset += 3) {
|
||||
const ia = index?.getX(offset) ?? offset
|
||||
const ib = index?.getX(offset + 1) ?? offset + 1
|
||||
const ic = index?.getX(offset + 2) ?? offset + 2
|
||||
const edge1: [number, number, number] = [
|
||||
position.getX(ib) - position.getX(ia),
|
||||
position.getY(ib) - position.getY(ia),
|
||||
position.getZ(ib) - position.getZ(ia),
|
||||
]
|
||||
const edge2: [number, number, number] = [
|
||||
position.getX(ic) - position.getX(ia),
|
||||
position.getY(ic) - position.getY(ia),
|
||||
position.getZ(ic) - position.getZ(ia),
|
||||
]
|
||||
const du1 = uv.getX(ib) - uv.getX(ia)
|
||||
const dv1 = uv.getY(ib) - uv.getY(ia)
|
||||
const du2 = uv.getX(ic) - uv.getX(ia)
|
||||
const dv2 = uv.getY(ic) - uv.getY(ia)
|
||||
const determinant = du1 * dv2 - du2 * dv1
|
||||
let tangent: [number, number, number]
|
||||
let bitangent: [number, number, number]
|
||||
|
||||
if (Number.isFinite(determinant) && Math.abs(determinant) > 1e-10) {
|
||||
const inverse = 1 / determinant
|
||||
tangent = [
|
||||
(edge1[0] * dv2 - edge2[0] * dv1) * inverse,
|
||||
(edge1[1] * dv2 - edge2[1] * dv1) * inverse,
|
||||
(edge1[2] * dv2 - edge2[2] * dv1) * inverse,
|
||||
]
|
||||
bitangent = [
|
||||
(edge2[0] * du1 - edge1[0] * du2) * inverse,
|
||||
(edge2[1] * du1 - edge1[1] * du2) * inverse,
|
||||
(edge2[2] * du1 - edge1[2] * du2) * inverse,
|
||||
]
|
||||
} else {
|
||||
tangent = squaredLength(edge1) >= squaredLength(edge2) ? edge1 : edge2
|
||||
const averageNormal = normalize3([
|
||||
normal.getX(ia) + normal.getX(ib) + normal.getX(ic),
|
||||
normal.getY(ia) + normal.getY(ib) + normal.getY(ic),
|
||||
normal.getZ(ia) + normal.getZ(ib) + normal.getZ(ic),
|
||||
], [0, 1, 0])
|
||||
tangent = orthogonalize(tangent, averageNormal)
|
||||
if (squaredLength(tangent) < 1e-20) tangent = fallbackTangent(averageNormal)
|
||||
bitangent = cross3(averageNormal, tangent)
|
||||
}
|
||||
|
||||
for (const vertex of [ia, ib, ic]) {
|
||||
const target = vertex * 3
|
||||
tangentSum[target] += tangent[0]
|
||||
tangentSum[target + 1] += tangent[1]
|
||||
tangentSum[target + 2] += tangent[2]
|
||||
bitangentSum[target] += bitangent[0]
|
||||
bitangentSum[target + 1] += bitangent[1]
|
||||
bitangentSum[target + 2] += bitangent[2]
|
||||
}
|
||||
}
|
||||
|
||||
const tangents = new Float32Array(position.count * 4)
|
||||
for (let vertex = 0; vertex < position.count; vertex += 1) {
|
||||
const source = vertex * 3
|
||||
const target = vertex * 4
|
||||
const n = normalize3([
|
||||
normal.getX(vertex),
|
||||
normal.getY(vertex),
|
||||
normal.getZ(vertex),
|
||||
], [0, 1, 0])
|
||||
let tangent = orthogonalize([
|
||||
tangentSum[source],
|
||||
tangentSum[source + 1],
|
||||
tangentSum[source + 2],
|
||||
], n)
|
||||
tangent = normalize3(tangent, fallbackTangent(n))
|
||||
const bitangent: [number, number, number] = [
|
||||
bitangentSum[source],
|
||||
bitangentSum[source + 1],
|
||||
bitangentSum[source + 2],
|
||||
]
|
||||
const handedness = dot3(cross3(n, tangent), bitangent) < 0 ? -1 : 1
|
||||
tangents[target] = tangent[0]
|
||||
tangents[target + 1] = tangent[1]
|
||||
tangents[target + 2] = tangent[2]
|
||||
tangents[target + 3] = handedness
|
||||
}
|
||||
geometry.setAttribute('tangent', new Float32BufferAttribute(tangents, 4))
|
||||
}
|
||||
|
||||
function orthogonalize(
|
||||
vector: [number, number, number],
|
||||
normal: [number, number, number],
|
||||
): [number, number, number] {
|
||||
const projection = dot3(vector, normal)
|
||||
return [
|
||||
vector[0] - normal[0] * projection,
|
||||
vector[1] - normal[1] * projection,
|
||||
vector[2] - normal[2] * projection,
|
||||
]
|
||||
}
|
||||
|
||||
function fallbackTangent(normal: [number, number, number]): [number, number, number] {
|
||||
const absolute = normal.map(Math.abs)
|
||||
const helper: [number, number, number] = absolute[0] <= absolute[1] && absolute[0] <= absolute[2]
|
||||
? [1, 0, 0]
|
||||
: absolute[1] <= absolute[2]
|
||||
? [0, 1, 0]
|
||||
: [0, 0, 1]
|
||||
return normalize3(cross3(helper, normal), [1, 0, 0])
|
||||
}
|
||||
|
||||
function normalize3(
|
||||
vector: [number, number, number],
|
||||
fallback: [number, number, number],
|
||||
): [number, number, number] {
|
||||
const length = Math.sqrt(squaredLength(vector))
|
||||
return Number.isFinite(length) && length > 1e-10
|
||||
? [vector[0] / length, vector[1] / length, vector[2] / length]
|
||||
: fallback
|
||||
}
|
||||
|
||||
function cross3(
|
||||
left: [number, number, number],
|
||||
right: [number, number, number],
|
||||
): [number, number, number] {
|
||||
return [
|
||||
left[1] * right[2] - left[2] * right[1],
|
||||
left[2] * right[0] - left[0] * right[2],
|
||||
left[0] * right[1] - left[1] * right[0],
|
||||
]
|
||||
}
|
||||
|
||||
function dot3(left: [number, number, number], right: [number, number, number]): number {
|
||||
return left[0] * right[0] + left[1] * right[1] + left[2] * right[2]
|
||||
}
|
||||
|
||||
function squaredLength(vector: [number, number, number]): number {
|
||||
return dot3(vector, vector)
|
||||
}
|
||||
|
||||
function geometryVariant(
|
||||
source: BufferGeometry,
|
||||
key: string,
|
||||
context: BakeContext,
|
||||
prepare: (geometry: BufferGeometry) => void,
|
||||
): BufferGeometry {
|
||||
if (context.ownedGeometries.has(source)) {
|
||||
prepare(source)
|
||||
return source
|
||||
}
|
||||
const variants = context.geometryVariants.get(source) ?? new Map<string, BufferGeometry>()
|
||||
const existing = variants.get(key)
|
||||
if (existing) return existing
|
||||
const geometry = source.clone()
|
||||
prepare(geometry)
|
||||
variants.set(key, geometry)
|
||||
context.geometryVariants.set(source, variants)
|
||||
context.ownedGeometries.add(geometry)
|
||||
return geometry
|
||||
}
|
||||
|
||||
const GLTF_ATTRIBUTES = new Set([
|
||||
'position',
|
||||
'normal',
|
||||
'tangent',
|
||||
'uv',
|
||||
'uv1',
|
||||
'color',
|
||||
'skinIndex',
|
||||
'skinWeight',
|
||||
])
|
||||
|
||||
function stripNonGltfAttributes(geometry: BufferGeometry): void {
|
||||
for (const name of Object.keys(geometry.attributes)) {
|
||||
if (!GLTF_ATTRIBUTES.has(name)) geometry.deleteAttribute(name)
|
||||
}
|
||||
}
|
||||
|
||||
const UV_TEXTURE_PROPERTIES = [
|
||||
'map',
|
||||
'normalMap',
|
||||
'roughnessMap',
|
||||
'metalnessMap',
|
||||
'aoMap',
|
||||
'emissiveMap',
|
||||
'alphaMap',
|
||||
'lightMap',
|
||||
'bumpMap',
|
||||
'displacementMap',
|
||||
'clearcoatMap',
|
||||
'clearcoatNormalMap',
|
||||
'clearcoatRoughnessMap',
|
||||
'sheenColorMap',
|
||||
'sheenRoughnessMap',
|
||||
'transmissionMap',
|
||||
'thicknessMap',
|
||||
] as const
|
||||
|
||||
function materialUsesUv(material: unknown): boolean {
|
||||
if (typeof material !== 'object' || material === null) return false
|
||||
const values = material as Record<string, unknown>
|
||||
return UV_TEXTURE_PROPERTIES.some((property) => values[property] instanceof Texture)
|
||||
}
|
||||
|
||||
function prepareDataTextureNormal(
|
||||
material: MeshPhysicalMaterial,
|
||||
hasTangents: boolean,
|
||||
context: BakeContext,
|
||||
): void {
|
||||
const normal = material.normalMap
|
||||
if (!isDataTexture(normal)) return
|
||||
const flipX = material.normalScale.x < 0
|
||||
const flipY = hasTangents ? material.normalScale.y < 0 : material.normalScale.y > 0
|
||||
if (flipX || flipY) {
|
||||
const width = normal.image.width
|
||||
const height = normal.image.height
|
||||
const output = new Uint8Array(width * height * 4)
|
||||
for (let y = 0; y < height; y += 1) {
|
||||
for (let x = 0; x < width; x += 1) {
|
||||
const offset = (y * width + x) * 4
|
||||
const red = sampleTextureChannel(normal, x, y, width, height, 0, 128)
|
||||
const green = sampleTextureChannel(normal, x, y, width, height, 1, 128)
|
||||
output[offset] = flipX ? 255 - red : red
|
||||
output[offset + 1] = flipY ? 255 - green : green
|
||||
output[offset + 2] = sampleTextureChannel(normal, x, y, width, height, 2, 255)
|
||||
output[offset + 3] = sampleTextureChannel(normal, x, y, width, height, 3, 255)
|
||||
}
|
||||
}
|
||||
const prepared = dataTexture(output, width, height, false, `${material.name} / gltf normal`)
|
||||
material.normalMap = prepared
|
||||
context.ownedTextures.add(prepared)
|
||||
}
|
||||
material.normalScale.set(Math.abs(material.normalScale.x), hasTangents
|
||||
? Math.abs(material.normalScale.y)
|
||||
: -Math.abs(material.normalScale.y))
|
||||
}
|
||||
|
||||
function packDataTextureOrm(material: MeshPhysicalMaterial, context: BakeContext): void {
|
||||
if (material.metalnessMap === material.roughnessMap) return
|
||||
const metalness = material.metalnessMap
|
||||
const roughness = material.roughnessMap
|
||||
if (!isDataTexture(metalness) && !isDataTexture(roughness)) return
|
||||
const width = Math.max(textureWidth(metalness), textureWidth(roughness), 1)
|
||||
const height = Math.max(textureHeight(metalness), textureHeight(roughness), 1)
|
||||
const packed = new Uint8Array(width * height * 4)
|
||||
for (let y = 0; y < height; y += 1) {
|
||||
for (let x = 0; x < width; x += 1) {
|
||||
const offset = (y * width + x) * 4
|
||||
packed[offset] = 255
|
||||
packed[offset + 1] = sampleTextureChannel(roughness, x, y, width, height, 1, 255)
|
||||
packed[offset + 2] = sampleTextureChannel(metalness, x, y, width, height, 2, 255)
|
||||
packed[offset + 3] = 255
|
||||
}
|
||||
}
|
||||
const orm = dataTexture(packed, width, height, false, `${material.name} / packed orm`)
|
||||
material.roughnessMap = orm
|
||||
material.metalnessMap = orm
|
||||
context.ownedTextures.add(orm)
|
||||
}
|
||||
|
||||
function isDataTexture(texture: Texture | null): texture is DataTexture {
|
||||
return texture instanceof DataTexture && texture.image?.data !== undefined
|
||||
}
|
||||
|
||||
function textureWidth(texture: Texture | null): number {
|
||||
return isDataTexture(texture) ? texture.image.width : 0
|
||||
}
|
||||
|
||||
function textureHeight(texture: Texture | null): number {
|
||||
return isDataTexture(texture) ? texture.image.height : 0
|
||||
}
|
||||
|
||||
function sampleTextureChannel(
|
||||
texture: Texture | null,
|
||||
x: number,
|
||||
y: number,
|
||||
width: number,
|
||||
height: number,
|
||||
channel: number,
|
||||
fallback: number,
|
||||
): number {
|
||||
if (!isDataTexture(texture)) return fallback
|
||||
const sourceX = Math.min(texture.image.width - 1, Math.floor(x * texture.image.width / width))
|
||||
const sourceY = Math.min(texture.image.height - 1, Math.floor(y * texture.image.height / height))
|
||||
const source = texture.image.data as ArrayLike<number>
|
||||
const channels = Math.max(1, Math.round(source.length / (texture.image.width * texture.image.height)))
|
||||
return source[(sourceY * texture.image.width + sourceX) * channels + Math.min(channel, channels - 1)] ?? fallback
|
||||
}
|
||||
|
||||
/** Exports one binary, animation-free GLB with all textures embedded. */
|
||||
export async function exportStaticGlb(
|
||||
source: Object3D,
|
||||
options: StaticGlbOptions = {},
|
||||
): Promise<Blob> {
|
||||
const snapshot = createStaticGlbSnapshot(source, options)
|
||||
try {
|
||||
const output = await new GLTFExporter().parseAsync(snapshot.root, {
|
||||
binary: true,
|
||||
animations: [],
|
||||
onlyVisible: false,
|
||||
includeCustomExtensions: true,
|
||||
maxTextureSize: options.textureSize ?? 512,
|
||||
})
|
||||
if (!(output instanceof ArrayBuffer)) throw new Error('GLTFExporter did not return binary GLB data')
|
||||
assertPortableGlb(output)
|
||||
return new Blob([output], { type: 'model/gltf-binary' })
|
||||
} finally {
|
||||
snapshot.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
interface GltfJson {
|
||||
readonly accessors?: readonly {
|
||||
readonly bufferView?: number
|
||||
readonly byteOffset?: number
|
||||
readonly componentType?: number
|
||||
readonly count?: number
|
||||
readonly type?: string
|
||||
}[]
|
||||
readonly animations?: readonly unknown[]
|
||||
readonly bufferViews?: readonly {
|
||||
readonly byteOffset?: number
|
||||
readonly byteStride?: number
|
||||
}[]
|
||||
readonly extensionsUsed?: readonly string[]
|
||||
readonly materials?: readonly Record<string, unknown>[]
|
||||
readonly meshes?: readonly {
|
||||
readonly primitives?: readonly {
|
||||
readonly attributes?: Readonly<Record<string, number>>
|
||||
readonly indices?: number
|
||||
readonly material?: number
|
||||
}[]
|
||||
}[]
|
||||
}
|
||||
|
||||
function assertPortableGlb(buffer: ArrayBuffer): void {
|
||||
const view = new DataView(buffer)
|
||||
if (view.getUint32(0, true) !== 0x46546c67 || view.getUint32(4, true) !== 2) {
|
||||
throw new Error('GLTFExporter returned an invalid GLB header')
|
||||
}
|
||||
const jsonLength = view.getUint32(12, true)
|
||||
const jsonType = view.getUint32(16, true)
|
||||
if (jsonType !== 0x4e4f534a) throw new Error('GLB does not begin with a JSON chunk')
|
||||
const json = JSON.parse(
|
||||
new TextDecoder().decode(new Uint8Array(buffer, 20, jsonLength)).trim(),
|
||||
) as GltfJson
|
||||
const binaryChunkHeader = 20 + jsonLength
|
||||
const binaryType = view.getUint32(binaryChunkHeader + 4, true)
|
||||
if (binaryType !== 0x004e4942) throw new Error('GLB does not contain a BIN chunk after JSON')
|
||||
const binaryDataOffset = binaryChunkHeader + 8
|
||||
if (json.extensionsUsed?.includes('EXT_mesh_gpu_instancing')) {
|
||||
throw new Error('Portable GLB unexpectedly contains EXT_mesh_gpu_instancing')
|
||||
}
|
||||
if ((json.animations?.length ?? 0) > 0) {
|
||||
throw new Error('Static GLB unexpectedly contains animations')
|
||||
}
|
||||
|
||||
const usedAccessors = new Set<number>()
|
||||
for (const [meshIndex, mesh] of (json.meshes ?? []).entries()) {
|
||||
for (const [primitiveIndex, primitive] of (mesh.primitives ?? []).entries()) {
|
||||
const material = primitive.material === undefined ? undefined : json.materials?.[primitive.material]
|
||||
const attributes = primitive.attributes ?? {}
|
||||
if (material?.normalTexture !== undefined && attributes.TANGENT === undefined) {
|
||||
throw new Error(`Normal-mapped primitive ${meshIndex}/${primitiveIndex} has no tangent attribute`)
|
||||
}
|
||||
if (attributes.TANGENT !== undefined) {
|
||||
assertUnitTangents(view, binaryDataOffset, json, attributes.TANGENT, meshIndex, primitiveIndex)
|
||||
}
|
||||
if (!jsonValueUsesTexture(material) && attributes.TEXCOORD_0 !== undefined) {
|
||||
throw new Error(`Untextured primitive ${meshIndex}/${primitiveIndex} contains an unused TEXCOORD_0`)
|
||||
}
|
||||
for (const accessor of Object.values(attributes)) usedAccessors.add(accessor)
|
||||
if (primitive.indices !== undefined) usedAccessors.add(primitive.indices)
|
||||
}
|
||||
}
|
||||
for (let accessor = 0; accessor < (json.accessors?.length ?? 0); accessor += 1) {
|
||||
if (!usedAccessors.has(accessor)) throw new Error(`GLB contains unused accessor ${accessor}`)
|
||||
}
|
||||
}
|
||||
|
||||
function assertUnitTangents(
|
||||
view: DataView,
|
||||
binaryDataOffset: number,
|
||||
json: GltfJson,
|
||||
accessorIndex: number,
|
||||
meshIndex: number,
|
||||
primitiveIndex: number,
|
||||
): void {
|
||||
const accessor = json.accessors?.[accessorIndex]
|
||||
const bufferView = accessor?.bufferView === undefined ? undefined : json.bufferViews?.[accessor.bufferView]
|
||||
if (!accessor || !bufferView || accessor.componentType !== 5126 || accessor.type !== 'VEC4') {
|
||||
throw new Error(`Tangent accessor ${accessorIndex} is not a float VEC4`)
|
||||
}
|
||||
const stride = bufferView.byteStride ?? 16
|
||||
const start = binaryDataOffset + (bufferView.byteOffset ?? 0) + (accessor.byteOffset ?? 0)
|
||||
for (let index = 0; index < (accessor.count ?? 0); index += 1) {
|
||||
const offset = start + index * stride
|
||||
const x = view.getFloat32(offset, true)
|
||||
const y = view.getFloat32(offset + 4, true)
|
||||
const z = view.getFloat32(offset + 8, true)
|
||||
const w = view.getFloat32(offset + 12, true)
|
||||
const length = Math.hypot(x, y, z)
|
||||
if (!Number.isFinite(length) || Math.abs(length - 1) > 1e-4 || Math.abs(Math.abs(w) - 1) > 1e-4) {
|
||||
throw new Error(
|
||||
`Primitive ${meshIndex}/${primitiveIndex} has invalid tangent ${index}: `
|
||||
+ `[${x}, ${y}, ${z}, ${w}]`,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function jsonValueUsesTexture(value: unknown, key = ''): boolean {
|
||||
if (value === null || typeof value !== 'object') return false
|
||||
if (key.toLowerCase().endsWith('texture')) return true
|
||||
return Object.entries(value).some(([childKey, child]) => jsonValueUsesTexture(child, childKey))
|
||||
}
|
||||
|
||||
function hasWearAttributes(geometry: BufferGeometry): boolean {
|
||||
return WEAR_ATTRIBUTE_NAMES.every((name) => geometry.getAttribute(name) !== undefined)
|
||||
}
|
||||
|
||||
function bakeWearMesh(source: Mesh, context: BakeContext): Group {
|
||||
const geometry = source.geometry.index ? source.geometry.toNonIndexed() : source.geometry
|
||||
const position = geometry.getAttribute('position')
|
||||
const normal = geometry.getAttribute('normal')
|
||||
const uv = geometry.getAttribute('uv')
|
||||
const mask = geometry.getAttribute('aMask')
|
||||
const colour = geometry.getAttribute('aColor')
|
||||
const surface = geometry.getAttribute('aSurface')
|
||||
const wearDirection = geometry.getAttribute('aWearDir')
|
||||
const buckets = new Map<string, GeometryBucket>()
|
||||
|
||||
for (let triangle = 0; triangle < position.count; triangle += 3) {
|
||||
const profile = readProfile(colour, surface, wearDirection, triangle)
|
||||
const key = profileKey(profile)
|
||||
const bucket = buckets.get(key) ?? {
|
||||
profile,
|
||||
positions: [],
|
||||
normals: [],
|
||||
uvs: [],
|
||||
colours: [],
|
||||
}
|
||||
buckets.set(key, bucket)
|
||||
|
||||
for (let corner = 0; corner < 3; corner += 1) {
|
||||
const index = triangle + corner
|
||||
bucket.positions.push(position.getX(index), position.getY(index), position.getZ(index))
|
||||
bucket.normals.push(normal.getX(index), normal.getY(index), normal.getZ(index))
|
||||
bucket.uvs.push(uv?.getX(index) ?? 0, uv?.getY(index) ?? 0)
|
||||
bucket.colours.push(...bakeVertexColour(position, normal, mask, profile, index))
|
||||
}
|
||||
}
|
||||
if (geometry !== source.geometry) geometry.dispose()
|
||||
|
||||
const group = new Group()
|
||||
group.name = source.name
|
||||
group.position.copy(source.position)
|
||||
group.quaternion.copy(source.quaternion)
|
||||
group.scale.copy(source.scale)
|
||||
group.visible = source.visible
|
||||
group.renderOrder = source.renderOrder
|
||||
group.userData = { ...source.userData, surfaceBake: 'standard-pbr' }
|
||||
|
||||
let part = 0
|
||||
for (const [key, bucket] of buckets) {
|
||||
const bakedGeometry = new BufferGeometry()
|
||||
bakedGeometry.setAttribute('position', new Float32BufferAttribute(bucket.positions, 3))
|
||||
bakedGeometry.setAttribute('normal', new Float32BufferAttribute(bucket.normals, 3))
|
||||
bakedGeometry.setAttribute('uv', new Float32BufferAttribute(bucket.uvs, 2))
|
||||
bakedGeometry.setAttribute('color', new Float32BufferAttribute(bucket.colours, 3))
|
||||
bakedGeometry.computeBoundingSphere()
|
||||
context.ownedGeometries.add(bakedGeometry)
|
||||
|
||||
const baked = new Mesh(bakedGeometry, materialForProfile(key, bucket.profile, context))
|
||||
baked.name = `${source.name} / baked surface ${String(part + 1).padStart(2, '0')}`
|
||||
baked.castShadow = source.castShadow
|
||||
baked.receiveShadow = source.receiveShadow
|
||||
group.add(baked)
|
||||
part += 1
|
||||
}
|
||||
return group
|
||||
}
|
||||
|
||||
function readProfile(
|
||||
colour: ReadableAttribute,
|
||||
surface: ReadableAttribute,
|
||||
wearDirection: ReadableAttribute,
|
||||
index: number,
|
||||
): SurfaceProfile {
|
||||
return {
|
||||
colour: [colour.getX(index), colour.getY(index), colour.getZ(index)],
|
||||
roughness: surface.getX(index),
|
||||
metalness: surface.getY(index),
|
||||
rub: surface.getZ(index),
|
||||
grime: surface.getW(index),
|
||||
scratch: wearDirection.getX(index),
|
||||
}
|
||||
}
|
||||
|
||||
function profileKey(profile: SurfaceProfile): string {
|
||||
return [
|
||||
...profile.colour,
|
||||
profile.roughness,
|
||||
profile.metalness,
|
||||
profile.rub,
|
||||
profile.grime,
|
||||
profile.scratch,
|
||||
].map((value) => value.toFixed(4)).join('/')
|
||||
}
|
||||
|
||||
function bakeVertexColour(
|
||||
position: ReadableAttribute,
|
||||
normal: ReadableAttribute,
|
||||
mask: ReadableAttribute,
|
||||
profile: SurfaceProfile,
|
||||
index: number,
|
||||
): [number, number, number] {
|
||||
const px = position.getX(index)
|
||||
const py = position.getY(index)
|
||||
const pz = position.getZ(index)
|
||||
const edge = mask.getX(index)
|
||||
const occlusion = mask.getY(index)
|
||||
const flakeScale = mask.getW(index)
|
||||
const flake = smoothstep(0.52, 0.36, valueNoise3(px * flakeScale * 22, py * flakeScale * 22, pz * flakeScale * 22))
|
||||
const cluster = smoothstep(0.36, 0.56, valueNoise3(px * flakeScale * 3.4, py * flakeScale * 3.4, pz * flakeScale * 3.4))
|
||||
const rub = clamp01(edge ** 3 * flake * cluster * (1 - occlusion * 0.85) * profile.rub)
|
||||
const down = clamp01(-normal.getY(index))
|
||||
const up = clamp01(normal.getY(index))
|
||||
const splash = smoothstep(1.05, 0.12, py)
|
||||
const streak = valueNoise3(px * 9, py * 0.9, pz * 9)
|
||||
const grime = clamp01(occlusion * 1.15 + down * 0.24 + splash * 0.3)
|
||||
* (streak * 0.4 + 0.7) * profile.grime
|
||||
const dust = up * 0.26 * (streak * 0.5 + 0.5) * (1 - rub) * profile.grime
|
||||
|
||||
const base = new Color(...profile.colour)
|
||||
base.lerp(new Color(0.16, 0.15, 0.13), clamp01(grime * 0.6))
|
||||
base.lerp(new Color(0.47, 0.46, 0.42), clamp01(dust * 0.28))
|
||||
base.lerp(new Color(0.56, 0.575, 0.59), clamp01(rub * 0.55))
|
||||
return [base.r, base.g, base.b]
|
||||
}
|
||||
|
||||
function materialForProfile(
|
||||
key: string,
|
||||
profile: SurfaceProfile,
|
||||
context: BakeContext,
|
||||
): MeshPhysicalMaterial {
|
||||
const existing = context.materials.get(key)
|
||||
if (existing) return existing
|
||||
const { albedo, orm, normal } = createWearTextureSet(profile, context.textureSize)
|
||||
const material = new MeshPhysicalMaterial({
|
||||
name: `baked worn surface / ${context.materials.size + 1}`,
|
||||
color: 0xffffff,
|
||||
vertexColors: true,
|
||||
roughness: 1,
|
||||
metalness: 1,
|
||||
clearcoat: 0.3,
|
||||
clearcoatRoughness: 0.3,
|
||||
map: albedo,
|
||||
roughnessMap: orm,
|
||||
metalnessMap: orm,
|
||||
normalMap: normal,
|
||||
})
|
||||
material.normalScale.set(0.42, 0.42)
|
||||
material.userData = {
|
||||
surfaceBake: 'toolbox-wear-v1',
|
||||
baseRoughness: profile.roughness,
|
||||
baseMetalness: profile.metalness,
|
||||
}
|
||||
context.materials.set(key, material)
|
||||
context.ownedMaterials.add(material)
|
||||
context.ownedTextures.add(albedo)
|
||||
context.ownedTextures.add(orm)
|
||||
context.ownedTextures.add(normal)
|
||||
return material
|
||||
}
|
||||
|
||||
function createWearTextureSet(
|
||||
profile: SurfaceProfile,
|
||||
size: number,
|
||||
): { albedo: DataTexture; orm: DataTexture; normal: DataTexture } {
|
||||
const albedoData = new Uint8Array(size * size * 4)
|
||||
const ormData = new Uint8Array(size * size * 4)
|
||||
const normalData = new Uint8Array(size * size * 4)
|
||||
for (let y = 0; y < size; y += 1) {
|
||||
for (let x = 0; x < size; x += 1) {
|
||||
const u = x / size
|
||||
const v = y / size
|
||||
const grain = valueNoise2(u * 18, v * 96)
|
||||
const broad = valueNoise2(u * 7, v * 7)
|
||||
const primaryPhase = u * 11 + v * 3
|
||||
const crossPhase = u * 4 - v * 13
|
||||
const primaryDistance = Math.abs(Math.sin(Math.PI * primaryPhase))
|
||||
const crossDistance = Math.abs(Math.sin(Math.PI * crossPhase))
|
||||
const broken = smoothstep(0.72, 0.94, Math.sin((u * 5 + v * 7) * Math.PI * 2) * 0.5 + 0.5)
|
||||
const scratch = clamp01(
|
||||
smoothstep(0.09, 0.015, primaryDistance) * broken
|
||||
+ smoothstep(0.055, 0.012, crossDistance) * (1 - broken) * 0.55,
|
||||
) * profile.scratch
|
||||
const chips = smoothstep(0.7, 0.84, broad) * profile.rub
|
||||
const dirt = smoothstep(0.38, 0.7, valueNoise2(u * 5 + 2.7, v * 5 - 1.3)) * profile.grime
|
||||
const multiplier = clamp01(0.98 + (grain - 0.5) * 0.08 - dirt * 0.16 - scratch * 0.3)
|
||||
const roughness = clamp01(profile.roughness + dirt * 0.2 - scratch * 0.34 - chips * 0.12)
|
||||
const metalness = clamp01(profile.metalness + (scratch * 0.7 + chips * 0.45) * (1 - profile.metalness))
|
||||
const wall = Math.sign(Math.sin(Math.PI * primaryPhase)) * scratch * 0.34
|
||||
const wallCross = Math.sign(Math.sin(Math.PI * crossPhase)) * scratch * 0.18
|
||||
const nx = -wall * 0.96 - wallCross * 0.3
|
||||
const ny = -wall * 0.26 + wallCross * 0.95
|
||||
const nz = Math.sqrt(Math.max(0, 1 - nx * nx - ny * ny))
|
||||
const offset = (y * size + x) * 4
|
||||
const albedo = Math.round(multiplier * 255)
|
||||
albedoData.set([albedo, albedo, albedo, 255], offset)
|
||||
ormData.set([255, Math.round(roughness * 255), Math.round(metalness * 255), 255], offset)
|
||||
normalData.set([
|
||||
Math.round((nx * 0.5 + 0.5) * 255),
|
||||
Math.round((ny * 0.5 + 0.5) * 255),
|
||||
Math.round((nz * 0.5 + 0.5) * 255),
|
||||
255,
|
||||
], offset)
|
||||
}
|
||||
}
|
||||
return {
|
||||
albedo: dataTexture(albedoData, size, true, 'baked wear / albedo'),
|
||||
orm: dataTexture(ormData, size, false, 'baked wear / orm'),
|
||||
normal: dataTexture(normalData, size, false, 'baked wear / normal'),
|
||||
}
|
||||
}
|
||||
|
||||
function dataTexture(data: Uint8Array, size: number, srgb: boolean, name: string): DataTexture
|
||||
function dataTexture(data: Uint8Array, width: number, height: number, srgb: boolean, name: string): DataTexture
|
||||
function dataTexture(
|
||||
data: Uint8Array,
|
||||
width: number,
|
||||
heightOrSrgb: number | boolean,
|
||||
srgbOrName: boolean | string,
|
||||
maybeName?: string,
|
||||
): DataTexture {
|
||||
const height = typeof heightOrSrgb === 'number' ? heightOrSrgb : width
|
||||
const srgb = typeof heightOrSrgb === 'boolean' ? heightOrSrgb : srgbOrName as boolean
|
||||
const name = typeof heightOrSrgb === 'boolean' ? srgbOrName as string : maybeName!
|
||||
const texture = new DataTexture(data, width, height, RGBAFormat, UnsignedByteType)
|
||||
texture.name = name
|
||||
texture.wrapS = RepeatWrapping
|
||||
texture.wrapT = RepeatWrapping
|
||||
texture.magFilter = LinearFilter
|
||||
texture.minFilter = LinearMipmapLinearFilter
|
||||
texture.generateMipmaps = true
|
||||
if (srgb) texture.colorSpace = SRGBColorSpace
|
||||
texture.needsUpdate = true
|
||||
return texture
|
||||
}
|
||||
|
||||
function valueNoise2(x: number, y: number): number {
|
||||
const ix = Math.floor(x)
|
||||
const iy = Math.floor(y)
|
||||
const fx = x - ix
|
||||
const fy = y - iy
|
||||
const ux = fx * fx * (3 - 2 * fx)
|
||||
const uy = fy * fy * (3 - 2 * fy)
|
||||
return mix(mix(hash2(ix, iy), hash2(ix + 1, iy), ux), mix(hash2(ix, iy + 1), hash2(ix + 1, iy + 1), ux), uy)
|
||||
}
|
||||
|
||||
function valueNoise3(x: number, y: number, z: number): number {
|
||||
const ix = Math.floor(x)
|
||||
const iy = Math.floor(y)
|
||||
const iz = Math.floor(z)
|
||||
const fx = x - ix
|
||||
const fy = y - iy
|
||||
const fz = z - iz
|
||||
const ux = fx * fx * (3 - 2 * fx)
|
||||
const uy = fy * fy * (3 - 2 * fy)
|
||||
const uz = fz * fz * (3 - 2 * fz)
|
||||
const corner = (dx: number, dy: number, dz: number) => hash2(
|
||||
ix + dx * 37 + (iz + dz) * 17,
|
||||
iy + dy * 53 + (iz + dz) * 29,
|
||||
)
|
||||
return mix(
|
||||
mix(mix(corner(0, 0, 0), corner(1, 0, 0), ux), mix(corner(0, 1, 0), corner(1, 1, 0), ux), uy),
|
||||
mix(mix(corner(0, 0, 1), corner(1, 0, 1), ux), mix(corner(0, 1, 1), corner(1, 1, 1), ux), uy),
|
||||
uz,
|
||||
)
|
||||
}
|
||||
|
||||
function hash2(x: number, y: number): number {
|
||||
const value = Math.sin(x * 127.1 + y * 311.7) * 43758.5453
|
||||
return value - Math.floor(value)
|
||||
}
|
||||
|
||||
function smoothstep(edge0: number, edge1: number, value: number): number {
|
||||
const t = clamp01((value - edge0) / (edge1 - edge0))
|
||||
return t * t * (3 - 2 * t)
|
||||
}
|
||||
|
||||
function mix(a: number, b: number, amount: number): number {
|
||||
return a * (1 - amount) + b * amount
|
||||
}
|
||||
|
||||
function clamp01(value: number): number {
|
||||
return Math.min(1, Math.max(0, value))
|
||||
}
|
||||
50
src/lib/vibe3d/scifi-kit/generator/index.ts
Normal file
50
src/lib/vibe3d/scifi-kit/generator/index.ts
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
export { mergeStaticByMaterial } from './batching.ts'
|
||||
export type { StaticBatchOptions } from './batching.ts'
|
||||
export { createSmokeTexture } from './effects.ts'
|
||||
export type { SmokeTextureOptions } from './effects.ts'
|
||||
export { createStaticGlbSnapshot, exportStaticGlb } from './glb.ts'
|
||||
export type { StaticGlbOptions, StaticGlbSnapshot } from './glb.ts'
|
||||
export { MaterialLibrary, mountMaterialSource, tuneMaterial } from './materials.ts'
|
||||
export type {
|
||||
MaterialHandle,
|
||||
MaterialSource,
|
||||
MaterialSourceOptions,
|
||||
PhysicalMaterialTuning,
|
||||
} from './materials.ts'
|
||||
export { mirrorProfile, octagon, offsetProfile, rect, stepEdge } from './profile.ts'
|
||||
export type { Side } from './profile.ts'
|
||||
export {
|
||||
WEAR_BAND,
|
||||
WEAR_FLOOR,
|
||||
cylinder,
|
||||
downTriangle,
|
||||
extrudeProfile,
|
||||
filletRing,
|
||||
flatPlate,
|
||||
groove,
|
||||
orientRing,
|
||||
prism,
|
||||
signedArea,
|
||||
} from './primitives.ts'
|
||||
export type {
|
||||
CapChamfer,
|
||||
Corners,
|
||||
PrismOptions,
|
||||
ProfileOptions,
|
||||
RingPoint,
|
||||
Vec2,
|
||||
Vec3,
|
||||
} from './primitives.ts'
|
||||
export {
|
||||
WEAR_ATTRIBUTES,
|
||||
bakeOcclusion,
|
||||
bakeSurfaceAttributes,
|
||||
createWearMaterial,
|
||||
wearOutputs,
|
||||
} from './wear.ts'
|
||||
export type {
|
||||
OcclusionBakeOptions,
|
||||
WearMaterialOptions,
|
||||
WearOutputs,
|
||||
WearProfile,
|
||||
} from './wear.ts'
|
||||
97
src/lib/vibe3d/scifi-kit/generator/materials.ts
Normal file
97
src/lib/vibe3d/scifi-kit/generator/materials.ts
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
import { MeshPhysicalMaterial } from 'three/webgpu'
|
||||
|
||||
export interface MaterialSourceOptions {
|
||||
readonly recipeId?: string
|
||||
readonly palette?: string
|
||||
readonly condition?: string
|
||||
readonly wear?: number
|
||||
readonly dirt?: number
|
||||
readonly seed?: number
|
||||
readonly uvScale?: readonly [number, number]
|
||||
}
|
||||
|
||||
export interface MaterialHandle {
|
||||
readonly key: string
|
||||
readonly material: MeshPhysicalMaterial
|
||||
release(): void
|
||||
}
|
||||
|
||||
export interface MaterialSource {
|
||||
acquire(options: MaterialSourceOptions, key: string): MaterialHandle
|
||||
}
|
||||
|
||||
let mountedMaterialSource: MaterialSource | undefined
|
||||
|
||||
/**
|
||||
* Sets the application-level material source used by subsequently-created
|
||||
* libraries. The returned function restores the previous source, which makes
|
||||
* kit mounting safe across previews, tests, and hot reloads.
|
||||
*/
|
||||
export function mountMaterialSource(source: MaterialSource): () => void {
|
||||
const previous = mountedMaterialSource
|
||||
mountedMaterialSource = source
|
||||
return () => {
|
||||
if (mountedMaterialSource === source) mountedMaterialSource = previous
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tiny ownership helper for model-local PBR materials. It deliberately has no
|
||||
* registry, schema, hashing, or compiler dependency; generators can create and
|
||||
* release materials without adopting a production pipeline.
|
||||
*/
|
||||
export class MaterialLibrary {
|
||||
readonly #source: MaterialSource | undefined
|
||||
|
||||
constructor(source: MaterialSource | undefined = mountedMaterialSource) {
|
||||
this.#source = source
|
||||
}
|
||||
|
||||
acquire(options: MaterialSourceOptions = {}): MaterialHandle {
|
||||
const key = [options.recipeId, options.palette, options.seed].filter(Boolean).join('/') || 'material'
|
||||
if (this.#source) return this.#source.acquire(options, key)
|
||||
const material = new MeshPhysicalMaterial({ name: key })
|
||||
material.userData.source = { ...options }
|
||||
let released = false
|
||||
return {
|
||||
key,
|
||||
material,
|
||||
release() {
|
||||
if (released) return
|
||||
released = true
|
||||
material.dispose()
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface PhysicalMaterialTuning {
|
||||
readonly clearcoat?: number
|
||||
readonly clearcoatRoughness?: number
|
||||
readonly emissive?: number
|
||||
}
|
||||
|
||||
/** Applies generator-local art direction to an owned material handle. */
|
||||
export function tuneMaterial(
|
||||
handle: MaterialHandle,
|
||||
hex: number,
|
||||
roughness: number,
|
||||
metalness: number,
|
||||
tuning: PhysicalMaterialTuning = {},
|
||||
): MeshPhysicalMaterial {
|
||||
const material = handle.material as MeshPhysicalMaterial
|
||||
material.color.setHex(hex)
|
||||
material.roughness = roughness
|
||||
material.metalness = metalness
|
||||
material.clearcoat = tuning.clearcoat ?? 0
|
||||
material.clearcoatRoughness = tuning.clearcoatRoughness ?? 0.3
|
||||
if (tuning.emissive !== undefined) {
|
||||
material.emissive.setHex(hex)
|
||||
material.emissiveIntensity = tuning.emissive
|
||||
material.toneMapped = false
|
||||
} else {
|
||||
material.emissive.setHex(0x000000)
|
||||
material.emissiveIntensity = 0
|
||||
}
|
||||
return material
|
||||
}
|
||||
867
src/lib/vibe3d/scifi-kit/generator/primitives.ts
Normal file
867
src/lib/vibe3d/scifi-kit/generator/primitives.ts
Normal file
|
|
@ -0,0 +1,867 @@
|
|||
import {
|
||||
BufferGeometry,
|
||||
CylinderGeometry,
|
||||
Float32BufferAttribute,
|
||||
Mesh,
|
||||
ShapeUtils,
|
||||
Vector2,
|
||||
type MeshPhysicalMaterial,
|
||||
} from 'three/webgpu'
|
||||
|
||||
export const WEAR_BAND = 0.075
|
||||
/** Edge value on clean interior surface, so nothing is ever perfectly pristine. */
|
||||
export const WEAR_FLOOR = 0.08
|
||||
|
||||
export type Vec3 = [number, number, number]
|
||||
export type Vec2 = [number, number]
|
||||
/** Corner clip sizes in ring order: top-right, top-left, bottom-left, bottom-right. */
|
||||
export type Corners = [number, number, number, number]
|
||||
|
||||
export interface RingPoint {
|
||||
x: number
|
||||
y: number
|
||||
nx: number
|
||||
ny: number
|
||||
}
|
||||
|
||||
/** Twice the enclosed area; positive when the ring is wound counter-clockwise. */
|
||||
export function signedArea(polygon: Vec2[]): number {
|
||||
let total = 0
|
||||
for (let i = 0; i < polygon.length; i += 1) {
|
||||
const [ax, ay] = polygon[i]
|
||||
const [bx, by] = polygon[(i + 1) % polygon.length]
|
||||
total += ax * by - bx * ay
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
/** Returns the ring wound the requested way, copying only when it has to flip. */
|
||||
export function orientRing(polygon: Vec2[], counterClockwise: boolean): Vec2[] {
|
||||
const isCounterClockwise = signedArea(polygon) > 0
|
||||
return isCounterClockwise === counterClockwise ? polygon : [...polygon].reverse()
|
||||
}
|
||||
|
||||
/**
|
||||
* Rounds every corner of an XY polygon into a tangent arc. The tangent points
|
||||
* inherit the arc normal, which is identical to the adjacent edge normal, so
|
||||
* straight runs stay perfectly flat while corners shade smoothly.
|
||||
*
|
||||
* Reflex corners are filleted too. The arc centre already lands on the correct
|
||||
* side for them - it is only the outward normal that inverts, because the
|
||||
* material is on the far side of the bisector. Concave silhouettes (an L-shaped
|
||||
* upright, a notched bracket, a recessed shoulder) therefore round exactly like
|
||||
* convex ones, which is what lets a whole part be one ring instead of a stack.
|
||||
*/
|
||||
export function filletRing(polygon: Vec2[], fillet: number, arcSegments: number): RingPoint[] {
|
||||
const count = polygon.length
|
||||
const points: RingPoint[] = []
|
||||
const winding = signedArea(polygon) > 0 ? 1 : -1
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
const previous = polygon[(i - 1 + count) % count]
|
||||
const vertex = polygon[i]
|
||||
const next = polygon[(i + 1) % count]
|
||||
|
||||
const toPrevious: Vec2 = [previous[0] - vertex[0], previous[1] - vertex[1]]
|
||||
const toNext: Vec2 = [next[0] - vertex[0], next[1] - vertex[1]]
|
||||
const previousLength = Math.hypot(...toPrevious)
|
||||
const nextLength = Math.hypot(...toNext)
|
||||
const u1: Vec2 = [toPrevious[0] / previousLength, toPrevious[1] / previousLength]
|
||||
const u2: Vec2 = [toNext[0] / nextLength, toNext[1] / nextLength]
|
||||
|
||||
const interior = Math.acos(Math.min(1, Math.max(-1, u1[0] * u2[0] + u1[1] * u2[1])))
|
||||
const half = interior * 0.5
|
||||
// A degenerate corner (collinear edges) contributes a single flat point.
|
||||
if (!Number.isFinite(half) || half < 1e-3 || Math.abs(Math.PI - interior) < 1e-3) {
|
||||
const nx = u2[1] * winding
|
||||
const ny = -u2[0] * winding
|
||||
points.push({ x: vertex[0], y: vertex[1], nx, ny })
|
||||
continue
|
||||
}
|
||||
|
||||
// The bisector points into the corner's narrow side. On a convex vertex that
|
||||
// is the material, so the surface normal runs from the arc centre outward;
|
||||
// on a reflex vertex it is the void, and the normal inverts.
|
||||
const convex = (u1[0] * u2[1] - u1[1] * u2[0]) * winding < 0
|
||||
const facing = convex ? 1 : -1
|
||||
|
||||
const radius = Math.min(fillet, previousLength * 0.49 * Math.tan(half), nextLength * 0.49 * Math.tan(half))
|
||||
const tangent = radius / Math.tan(half)
|
||||
const bisector: Vec2 = [u1[0] + u2[0], u1[1] + u2[1]]
|
||||
const bisectorLength = Math.hypot(...bisector) || 1
|
||||
const centre: Vec2 = [
|
||||
vertex[0] + (bisector[0] / bisectorLength) * (radius / Math.sin(half)),
|
||||
vertex[1] + (bisector[1] / bisectorLength) * (radius / Math.sin(half)),
|
||||
]
|
||||
|
||||
const start: Vec2 = [vertex[0] + u1[0] * tangent, vertex[1] + u1[1] * tangent]
|
||||
const end: Vec2 = [vertex[0] + u2[0] * tangent, vertex[1] + u2[1] * tangent]
|
||||
const startAngle = Math.atan2(start[1] - centre[1], start[0] - centre[0])
|
||||
const endAngle = Math.atan2(end[1] - centre[1], end[0] - centre[0])
|
||||
let sweep = endAngle - startAngle
|
||||
while (sweep > Math.PI) sweep -= Math.PI * 2
|
||||
while (sweep < -Math.PI) sweep += Math.PI * 2
|
||||
|
||||
for (let s = 0; s <= arcSegments; s += 1) {
|
||||
const angle = startAngle + (sweep * s) / arcSegments
|
||||
const nx = Math.cos(angle)
|
||||
const ny = Math.sin(angle)
|
||||
points.push({
|
||||
x: centre[0] + nx * radius,
|
||||
y: centre[1] + ny * radius,
|
||||
nx: nx * facing,
|
||||
ny: ny * facing,
|
||||
})
|
||||
}
|
||||
}
|
||||
return points
|
||||
}
|
||||
|
||||
/**
|
||||
* Depth-axis corner cut, the counterpart to the profile-plane `chamfer`.
|
||||
*
|
||||
* A number cuts both ends; a pair cuts the front and back independently. Give a
|
||||
* part both a `chamfer` and a `capChamfer` and every one of its twelve edges is
|
||||
* a real 45-degree facet - which is the difference between a machined block and
|
||||
* an extruded slab whose ends were left square.
|
||||
*/
|
||||
export type CapChamfer = number | [number, number]
|
||||
|
||||
export interface PrismOptions {
|
||||
/** Large 45-degree corner cuts. A single number applies to all four corners. */
|
||||
chamfer?: number | Corners
|
||||
/** Large 45-degree cuts on the depth axis: `number` or `[front, back]`. */
|
||||
capChamfer?: CapChamfer
|
||||
/** Small radius softening every ring corner, including the chamfer's own. */
|
||||
fillet?: number
|
||||
/** Radius rolling the front and back face edges into the side walls. */
|
||||
bevel?: number
|
||||
/** Inner rings cut clean through the part. Real openings, not floated quads. */
|
||||
holes?: Vec2[][]
|
||||
rotation?: Vec3
|
||||
arcSegments?: number
|
||||
bevelSegments?: number
|
||||
}
|
||||
|
||||
export interface ProfileOptions {
|
||||
/** Small radius softening every polygon corner. */
|
||||
fillet?: number
|
||||
/** Radius rolling the front and back face edges into the side walls. On a
|
||||
* profile extrusion this band is the part's corner facet in the extruded
|
||||
* plane, so hero masses want it large rather than hairline. */
|
||||
bevel?: number
|
||||
/** Large 45-degree cuts on the depth axis: `number` or `[front, back]`. */
|
||||
capChamfer?: CapChamfer
|
||||
/**
|
||||
* Inner rings cut clean through the extrusion. Each hole gets its own filleted
|
||||
* rim, its own bevel roll, and walls that face into the opening, so a screen
|
||||
* well, a vent mouth, or a cable pass-through is subtracted from the part
|
||||
* rather than faked with a dark quad floated on top of it.
|
||||
*/
|
||||
holes?: Vec2[][]
|
||||
rotation?: Vec3
|
||||
arcSegments?: number
|
||||
bevelSegments?: number
|
||||
}
|
||||
|
||||
/** One ring of the depth cross-section: where it sits, and which way it faces. */
|
||||
interface Band {
|
||||
z: number
|
||||
inset: number
|
||||
nz: number
|
||||
nScale: number
|
||||
edge: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the depth cross-section as a closed polygon in (inset, z) and fillets
|
||||
* it with the very same routine that rounds the profile plane.
|
||||
*
|
||||
* That symmetry is the point. The old cross-section was hard-coded to a single
|
||||
* quarter-round, so the depth axis could only ever receive a hairline roll no
|
||||
* matter what the caller asked for - a part could be chamfered across its face
|
||||
* and never through its thickness. Expressing depth as a profile means a cap
|
||||
* chamfer is just another corner, its own creases get the same bevel, and the
|
||||
* two axes finally have equal expressive power.
|
||||
*/
|
||||
function depthBands(
|
||||
halfDepth: number,
|
||||
front: number,
|
||||
back: number,
|
||||
bevel: number,
|
||||
bevelSegments: number,
|
||||
): Band[] {
|
||||
// The section is closed off far inside the part; those corners are discarded
|
||||
// after filleting, so their only job is to make the ring a valid polygon.
|
||||
const far = halfDepth * 4 + Math.max(front, back) + bevel * 4 + 1
|
||||
const section: Vec2[] = [[far, halfDepth]]
|
||||
if (front > 0) section.push([front, halfDepth], [0, halfDepth - front])
|
||||
else section.push([0, halfDepth])
|
||||
if (back > 0) section.push([0, -(halfDepth - back)], [back, -halfDepth])
|
||||
else section.push([0, -halfDepth])
|
||||
section.push([far, -halfDepth])
|
||||
|
||||
const bands: Band[] = []
|
||||
for (const point of filletRing(section, bevel, bevelSegments)) {
|
||||
if (point.x > far * 0.5) continue
|
||||
// Section +x runs into the part, so its normal component is the ring normal
|
||||
// inverted; section +y is world z.
|
||||
bands.push({ z: point.y, inset: point.x, nz: point.ny, nScale: -point.nx, edge: 1 })
|
||||
}
|
||||
|
||||
// A deep side wall gets two interior rings so its middle can read as clean
|
||||
// metal. Without them the wear band would stretch across the whole wall.
|
||||
const wall = bands.findIndex((band, index) =>
|
||||
index + 1 < bands.length
|
||||
&& Math.abs(band.inset) < 1e-6 && Math.abs(band.nz) < 1e-6
|
||||
&& Math.abs(bands[index + 1].inset) < 1e-6 && Math.abs(bands[index + 1].nz) < 1e-6)
|
||||
if (wall >= 0 && bands[wall].z - bands[wall + 1].z > WEAR_BAND * 3) {
|
||||
bands.splice(wall + 1, 0,
|
||||
{ z: bands[wall].z - WEAR_BAND, inset: 0, nz: 0, nScale: 1, edge: WEAR_FLOOR },
|
||||
{ z: bands[wall + 1].z + WEAR_BAND, inset: 0, nz: 0, nScale: 1, edge: WEAR_FLOOR })
|
||||
}
|
||||
return bands
|
||||
}
|
||||
|
||||
function resolveCapChamfer(value: CapChamfer | undefined, limit: number): [number, number] {
|
||||
const pair: [number, number] = typeof value === 'number' ? [value, value] : value ?? [0, 0]
|
||||
return [
|
||||
Math.max(0, Math.min(pair[0], limit)),
|
||||
Math.max(0, Math.min(pair[1], limit)),
|
||||
]
|
||||
}
|
||||
|
||||
/**
|
||||
* The tightest arc `filletRing` will actually produce on a convex corner of this
|
||||
* polygon, which is the hard ceiling on how far the ring can be inset.
|
||||
*
|
||||
* A cap chamfer is built by drawing the ring inset from itself, and pushing a
|
||||
* rounded corner inward by more than its own radius turns it inside out. Reflex
|
||||
* corners only ever open up under the same inset, so they impose no limit.
|
||||
*/
|
||||
function minConvexRadius(polygon: Vec2[], fillet: number): number {
|
||||
const count = polygon.length
|
||||
const winding = signedArea(polygon) > 0 ? 1 : -1
|
||||
let smallest = Infinity
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
const previous = polygon[(i - 1 + count) % count]
|
||||
const vertex = polygon[i]
|
||||
const next = polygon[(i + 1) % count]
|
||||
const toPrevious: Vec2 = [previous[0] - vertex[0], previous[1] - vertex[1]]
|
||||
const toNext: Vec2 = [next[0] - vertex[0], next[1] - vertex[1]]
|
||||
const previousLength = Math.hypot(...toPrevious)
|
||||
const nextLength = Math.hypot(...toNext)
|
||||
const u1: Vec2 = [toPrevious[0] / previousLength, toPrevious[1] / previousLength]
|
||||
const u2: Vec2 = [toNext[0] / nextLength, toNext[1] / nextLength]
|
||||
const interior = Math.acos(Math.min(1, Math.max(-1, u1[0] * u2[0] + u1[1] * u2[1])))
|
||||
const half = interior * 0.5
|
||||
if (!Number.isFinite(half) || half < 1e-3 || Math.abs(Math.PI - interior) < 1e-3) continue
|
||||
if ((u1[0] * u2[1] - u1[1] * u2[0]) * winding >= 0) continue
|
||||
smallest = Math.min(
|
||||
smallest,
|
||||
fillet,
|
||||
previousLength * 0.49 * Math.tan(half),
|
||||
nextLength * 0.49 * Math.tan(half),
|
||||
)
|
||||
}
|
||||
return smallest
|
||||
}
|
||||
|
||||
/**
|
||||
* The single building block for the whole case. Corners and face edges carry a
|
||||
* real bevel, but at the segment count a hand modeller would actually use: one
|
||||
* facet, with the normals shared across it so it reads as a soft highlight
|
||||
* rather than a razor edge. Only the hero masses opt into a second segment.
|
||||
*/
|
||||
export function prism(
|
||||
material: MeshPhysicalMaterial,
|
||||
size: Vec3,
|
||||
position: Vec3,
|
||||
options: PrismOptions = {},
|
||||
): Mesh {
|
||||
const [width, height, depth] = size
|
||||
const hx = width * 0.5
|
||||
const hy = height * 0.5
|
||||
|
||||
const raw = options.chamfer ?? 0
|
||||
const clips: Corners = typeof raw === 'number' ? [raw, raw, raw, raw] : raw
|
||||
// Leave real straight edge between clips. At 0.85 a thin prism's side collapses
|
||||
// to a few thou, and filleting both ends of that produces zero-area slivers.
|
||||
const [ctr, ctl, cbl, cbr] = clips.map((clip) => Math.min(clip, hx * 0.6, hy * 0.6)) as Corners
|
||||
|
||||
// Counter-clockwise ring beginning at the top-right corner.
|
||||
const polygon: Vec2[] = []
|
||||
if (ctr > 0) polygon.push([hx, hy - ctr], [hx - ctr, hy])
|
||||
else polygon.push([hx, hy])
|
||||
if (ctl > 0) polygon.push([-hx + ctl, hy], [-hx, hy - ctl])
|
||||
else polygon.push([-hx, hy])
|
||||
if (cbl > 0) polygon.push([-hx, -hy + cbl], [-hx + cbl, -hy])
|
||||
else polygon.push([-hx, -hy])
|
||||
if (cbr > 0) polygon.push([hx - cbr, -hy], [hx, -hy + cbr])
|
||||
else polygon.push([hx, -hy])
|
||||
|
||||
return extrudeProfile(material, polygon, depth, position, options)
|
||||
}
|
||||
|
||||
/** Rings are authored counter-clockwise; a hole's wall faces into the opening. */
|
||||
function ringOf(polygon: Vec2[], fillet: number, arcSegments: number, hole: boolean): RingPoint[] {
|
||||
const ring = filletRing(orientRing(polygon, true), fillet, arcSegments)
|
||||
if (!hole) return ring
|
||||
return ring.map((point) => ({ ...point, nx: -point.nx, ny: -point.ny }))
|
||||
}
|
||||
|
||||
/**
|
||||
* Ear-clips a cap, honouring concave outlines and any number of openings.
|
||||
*
|
||||
* The triangulator wants a counter-clockwise contour and clockwise holes, but
|
||||
* the caller has already emitted its vertices in ring order, so any ring flipped
|
||||
* on the way in has its indices flipped back on the way out.
|
||||
*/
|
||||
function capIndices(outer: Vec2[], holes: Vec2[][]): number[] {
|
||||
const toVectors = (ring: Vec2[], counterClockwise: boolean) => {
|
||||
const flipped = signedArea(ring) > 0 !== counterClockwise
|
||||
const ordered = flipped ? [...ring].reverse() : ring
|
||||
return { points: ordered.map(([x, y]) => new Vector2(x, y)), flipped }
|
||||
}
|
||||
|
||||
const contour = toVectors(outer, true)
|
||||
const rings = holes.map((hole) => toVectors(hole, false))
|
||||
|
||||
// Offsets into the concatenated [outer, ...holes] list the triangulator indexes.
|
||||
const spans = [{ start: 0, count: outer.length, flipped: contour.flipped }]
|
||||
for (const [index, hole] of holes.entries()) {
|
||||
const previous = spans[spans.length - 1]
|
||||
spans.push({ start: previous.start + previous.count, count: hole.length, flipped: rings[index].flipped })
|
||||
}
|
||||
const restore = (index: number): number => {
|
||||
const span = spans.findLast((candidate) => index >= candidate.start)!
|
||||
const local = index - span.start
|
||||
return span.start + (span.flipped ? span.count - 1 - local : local)
|
||||
}
|
||||
|
||||
const faces = ShapeUtils.triangulateShape(contour.points, rings.map((ring) => ring.points))
|
||||
|
||||
// An ear-clipper handed a hole it cannot bridge drops it and returns a cap
|
||||
// with no opening - geometry that still renders, still passes a volume check
|
||||
// on its walls, and reads as a solid face. A dropped hole contributes no
|
||||
// vertices at all, which is exact; comparing triangle counts instead would
|
||||
// cry wolf every time a collinear corner collapsed.
|
||||
const used = new Set<number>()
|
||||
for (const triangle of faces) used.add(triangle[0]).add(triangle[1]).add(triangle[2])
|
||||
for (let hole = 1; hole < spans.length; hole += 1) {
|
||||
const { start, count } = spans[hole]
|
||||
let reached = false
|
||||
for (let i = start; i < start + count && !reached; i += 1) reached = used.has(i)
|
||||
if (!reached) {
|
||||
console.warn(
|
||||
`extrudeProfile: cap triangulation dropped hole ${hole} - it is too close to the `
|
||||
+ 'outline or to another hole to bridge, and the face will render solid.',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const indices: number[] = []
|
||||
for (const triangle of faces) {
|
||||
indices.push(restore(triangle[0]), restore(triangle[1]), restore(triangle[2]))
|
||||
}
|
||||
return indices
|
||||
}
|
||||
|
||||
/**
|
||||
* Extrudes an arbitrary profile along z with the same bevel, normal, and
|
||||
* wear-attribute treatment `prism` gets. The outline may be concave, and
|
||||
* `options.holes` cuts real openings clean through it.
|
||||
*
|
||||
* Reach for this whenever the silhouette is not a clipped rectangle. Stacking
|
||||
* boxes to approximate a stepped or tapering mass leaves coincident interior
|
||||
* faces, a bevel that restarts at every joint, and a hard seam wherever two
|
||||
* blocks meet - the profile has to be one ring for the outline to be one edge.
|
||||
*/
|
||||
export function extrudeProfile(
|
||||
material: MeshPhysicalMaterial,
|
||||
profile: Vec2[],
|
||||
depth: number,
|
||||
position: Vec3,
|
||||
options: ProfileOptions = {},
|
||||
): Mesh {
|
||||
const hz = depth * 0.5
|
||||
const arcSegments = options.arcSegments ?? 1
|
||||
const bevelSegments = options.bevelSegments ?? 1
|
||||
|
||||
let minX = Infinity
|
||||
let maxX = -Infinity
|
||||
let minY = Infinity
|
||||
let maxY = -Infinity
|
||||
for (const [x, y] of profile) {
|
||||
minX = Math.min(minX, x)
|
||||
maxX = Math.max(maxX, x)
|
||||
minY = Math.min(minY, y)
|
||||
maxY = Math.max(maxY, y)
|
||||
}
|
||||
const width = maxX - minX
|
||||
const height = maxY - minY
|
||||
const hx = width * 0.5
|
||||
const hy = height * 0.5
|
||||
|
||||
// Callers author profiles and holes in one shared coordinate system, and
|
||||
// `position` is an offset applied on top of the profile's own centre; mesh
|
||||
// rotation then pivots about that centre, which is what an angled return
|
||||
// plate wants.
|
||||
const centreX = (minX + maxX) * 0.5
|
||||
const centreY = (minY + maxY) * 0.5
|
||||
const recentre = (ring: Vec2[]): Vec2[] =>
|
||||
centreX === 0 && centreY === 0
|
||||
? ring
|
||||
: ring.map(([x, y]): Vec2 => [x - centreX, y - centreY])
|
||||
const polygon = recentre(profile)
|
||||
const holePolygons = (options.holes ?? []).map(recentre)
|
||||
minX -= centreX
|
||||
maxX -= centreX
|
||||
minY -= centreY
|
||||
maxY -= centreY
|
||||
|
||||
const capLimit = Math.min(hz * 0.9, Math.min(hx, hy) * 0.9)
|
||||
const requested = resolveCapChamfer(options.capChamfer, capLimit)
|
||||
const chamfered = requested[0] > 0 || requested[1] > 0
|
||||
|
||||
// A cap chamfer needs a corner round enough to carry it, so when the caller
|
||||
// has not pinned the profile fillet it opens up to match. That is what a hand
|
||||
// modeller does too: a deep 45 on the ends implies the vertical edges are not
|
||||
// razor sharp either.
|
||||
const autoFillet = Math.max(Math.min(hx, hy) * 0.18, chamfered ? Math.max(...requested) * 1.25 : 0)
|
||||
const fillet = Math.max(1e-4, Math.min(options.fillet ?? autoFillet, hx * 0.9, hy * 0.9))
|
||||
|
||||
// Without a cap chamfer the depth axis only carries the legacy hairline roll,
|
||||
// whose radius stays tied to the profile fillet. A part that asked for a real
|
||||
// depth chamfer has creases of its own to soften, and `filletRing` already
|
||||
// clamps a radius that will not fit, so that tie is dropped.
|
||||
const rings = [
|
||||
ringOf(polygon, fillet, arcSegments, false),
|
||||
...holePolygons.map((hole) => {
|
||||
let holeSpan = Infinity
|
||||
for (const [ax, ay] of hole) {
|
||||
for (const [bx, by] of hole) holeSpan = Math.min(holeSpan, Math.hypot(ax - bx, ay - by) || Infinity)
|
||||
}
|
||||
const holeFillet = Math.max(1e-4, Math.min(options.fillet ?? holeSpan * 0.24, holeSpan * 0.32))
|
||||
return ringOf(hole, holeFillet, arcSegments, true)
|
||||
}),
|
||||
]
|
||||
|
||||
// Everything that draws the cap ring inward shares one budget. Overrun it and
|
||||
// a corner arc turns inside out, or a hole's mouth opens wider than the
|
||||
// outline enclosing it - and an ear-clipper handed either one gives up and
|
||||
// returns a cap with no hole in it at all.
|
||||
const clearance = ringClearance(rings)
|
||||
const insetLimit = Math.min(minConvexRadius(polygon, fillet) * 0.85, clearance * 0.42)
|
||||
|
||||
const defaultBevel = Math.min(0.028, hz * 0.6)
|
||||
const bevel = Math.max(1e-4, Math.min(
|
||||
options.bevel ?? defaultBevel,
|
||||
hz * 0.9,
|
||||
insetLimit,
|
||||
// Without a cap chamfer the roll is the whole depth-axis treatment, and its
|
||||
// radius has always been tied to the profile fillet.
|
||||
chamfered ? Infinity : fillet * 1.6,
|
||||
))
|
||||
const insetCeiling = Math.max(0, insetLimit - bevel * 0.4143)
|
||||
const [frontChamfer, backChamfer] = [
|
||||
Math.min(requested[0], insetCeiling),
|
||||
Math.min(requested[1], insetCeiling),
|
||||
]
|
||||
|
||||
const bands = depthBands(hz, frontChamfer, backChamfer, bevel, bevelSegments)
|
||||
|
||||
const positions: number[] = []
|
||||
const normals: number[] = []
|
||||
const uvs: number[] = []
|
||||
const edges: number[] = []
|
||||
const planes: number[] = []
|
||||
const indices: number[] = []
|
||||
|
||||
const pushVertex = (
|
||||
x: number, y: number, z: number,
|
||||
nx: number, ny: number, nz: number,
|
||||
edge: number, planeU: number, planeV: number,
|
||||
): void => {
|
||||
positions.push(x, y, z)
|
||||
normals.push(nx, ny, nz)
|
||||
uvs.push((x - minX) / width, (y - minY) / height)
|
||||
edges.push(edge)
|
||||
planes.push(planeU, planeV)
|
||||
}
|
||||
|
||||
// Side walls, one strip per ring. Cumulative arc length is the surface
|
||||
// parameter the wear is evaluated in: projecting world position onto an axis
|
||||
// plane instead smears the pattern into stripes wherever the surface turns
|
||||
// edge-on to the projection, which is exactly what a bevel does.
|
||||
for (const [ringIndex, ring] of rings.entries()) {
|
||||
const ringCount = ring.length
|
||||
const arc: number[] = []
|
||||
let travelled = 0
|
||||
for (let i = 0; i < ringCount; i += 1) {
|
||||
arc.push(travelled)
|
||||
const next = ring[(i + 1) % ringCount]
|
||||
travelled += Math.hypot(next.x - ring[i].x, next.y - ring[i].y)
|
||||
}
|
||||
|
||||
const base = positions.length / 3
|
||||
for (const band of bands) {
|
||||
for (const [i, point] of ring.entries()) {
|
||||
pushVertex(
|
||||
point.x - point.nx * band.inset, point.y - point.ny * band.inset, band.z,
|
||||
point.nx * band.nScale, point.ny * band.nScale, band.nz,
|
||||
band.edge, arc[i], band.z,
|
||||
)
|
||||
}
|
||||
}
|
||||
for (let s = 0; s < bands.length - 1; s += 1) {
|
||||
const a = base + s * ringCount
|
||||
const b = base + (s + 1) * ringCount
|
||||
for (let i = 0; i < ringCount; i += 1) {
|
||||
const j = (i + 1) % ringCount
|
||||
// A hole's wall faces the opening, so its strip winds the other way.
|
||||
if (ringIndex === 0) indices.push(a + i, b + i, b + j, a + i, b + j, a + j)
|
||||
else indices.push(a + i, b + j, b + i, a + i, a + j, b + j)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Caps. A face broad enough to have a clean middle gets an inset rim ring, so
|
||||
// the rub band stays a constant width instead of scaling with the panel. A
|
||||
// small greeble has no clean middle and stays worn all over. Offsetting a ring
|
||||
// inward is only safe while it stays convex, so a concave outline skips the
|
||||
// rim band rather than risk folding its own cap inside out.
|
||||
const halfMin = Math.min(hx, hy)
|
||||
const convex = rings.every((ring, index) => index === 0 ? isConvexRing(ring) : true)
|
||||
// Each ring's rub band eats WEAR_BAND of face on its way inward, so two rings
|
||||
// separated by less than two bands would offset straight through each other
|
||||
// and hand the triangulator a hole wider than its own contour.
|
||||
const broad = halfMin > WEAR_BAND * 3.2 && convex
|
||||
&& clearance > WEAR_BAND * 2.4
|
||||
&& rings.every((ring) => ringSpan(ring) > WEAR_BAND * 3.2)
|
||||
|
||||
for (const [index, band] of [bands[0], bands[bands.length - 1]].entries()) {
|
||||
// Each cap gets its own copy of the rim ring. It has to be parameterised in
|
||||
// the face plane, and the wall's copy is parameterised as arc length for the
|
||||
// bevel - one vertex cannot carry both. The seam lands on the hard edge,
|
||||
// which is where an unwrap would put it anyway.
|
||||
const capBase = positions.length / 3
|
||||
const offsetRing = (ring: RingPoint[], inset: number): Vec2[] =>
|
||||
ring.map((point): Vec2 => [point.x - point.nx * inset, point.y - point.ny * inset])
|
||||
const rims = rings.map((ring) => offsetRing(ring, band.inset))
|
||||
|
||||
// The rub band is measured from the profile itself, not from the rim, so a
|
||||
// hairline bevel does not eat into it. A cap chamfer can push the rim past
|
||||
// that, in which case the band follows the rim inward instead.
|
||||
const wearInset = Math.max(WEAR_BAND, band.inset + WEAR_BAND * 0.5)
|
||||
const wears = rings.map((ring) => offsetRing(ring, wearInset))
|
||||
// Offsetting a ring inward by more than a corner's fillet radius turns that
|
||||
// corner inside out. Reversed segments are the exact symptom, and a cap that
|
||||
// cannot hold a clean band is better off without one than folded.
|
||||
const safe = wears.every((wear, index) => wear.every((point, i) => {
|
||||
const next = wear[(i + 1) % wear.length]
|
||||
const ring = rings[index]
|
||||
const source = ring[i]
|
||||
const sourceNext = ring[(i + 1) % ring.length]
|
||||
const dot = (next[0] - point[0]) * (sourceNext.x - source.x)
|
||||
+ (next[1] - point[1]) * (sourceNext.y - source.y)
|
||||
return dot >= 0
|
||||
}))
|
||||
|
||||
let fanRings = rims
|
||||
if (broad && safe) {
|
||||
for (const rim of rims) {
|
||||
for (const [x, y] of rim) pushVertex(x, y, band.z, 0, 0, band.nz, 1, x, y)
|
||||
}
|
||||
const wearBase = positions.length / 3
|
||||
for (const wear of wears) {
|
||||
for (const [x, y] of wear) pushVertex(x, y, band.z, 0, 0, band.nz, WEAR_FLOOR, x, y)
|
||||
}
|
||||
let cursor = 0
|
||||
for (const [ringIndex, ring] of rings.entries()) {
|
||||
const count = ring.length
|
||||
const rimStart = capBase + cursor
|
||||
const wearStart = wearBase + cursor
|
||||
cursor += count
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
const j = (i + 1) % count
|
||||
// The inset ring runs inward from the rim, reversing the winding
|
||||
// relative to the outward-facing wall bands; a hole reverses again.
|
||||
const flip = (index === 0) === (ringIndex === 0)
|
||||
if (flip) {
|
||||
indices.push(rimStart + i, wearStart + j, wearStart + i, rimStart + i, rimStart + j, wearStart + j)
|
||||
} else {
|
||||
indices.push(rimStart + j, wearStart + i, wearStart + j, rimStart + j, rimStart + i, wearStart + i)
|
||||
}
|
||||
}
|
||||
}
|
||||
fanRings = wears
|
||||
} else {
|
||||
const edge = halfMin > WEAR_BAND * 3.2 ? WEAR_FLOOR : Math.max(0, 1 - halfMin / (WEAR_BAND * 2.2))
|
||||
for (const rim of rims) {
|
||||
for (const [x, y] of rim) pushVertex(x, y, band.z, 0, 0, band.nz, edge, x, y)
|
||||
}
|
||||
}
|
||||
|
||||
const fanBase = fanRings === rims
|
||||
? capBase
|
||||
: positions.length / 3 - fanRings.reduce((total, ring) => total + ring.length, 0)
|
||||
const face = capIndices(fanRings[0], fanRings.slice(1))
|
||||
for (let t = 0; t < face.length; t += 3) {
|
||||
// Triangulation is authored for a counter-clockwise contour seen from +z.
|
||||
if (index === 0) indices.push(fanBase + face[t], fanBase + face[t + 1], fanBase + face[t + 2])
|
||||
else indices.push(fanBase + face[t + 2], fanBase + face[t + 1], fanBase + face[t])
|
||||
}
|
||||
}
|
||||
|
||||
const geometry = new BufferGeometry()
|
||||
geometry.setAttribute('position', new Float32BufferAttribute(positions, 3))
|
||||
geometry.setAttribute('normal', new Float32BufferAttribute(normals, 3))
|
||||
geometry.setAttribute('uv', new Float32BufferAttribute(uvs, 2))
|
||||
geometry.setAttribute('aEdge', new Float32BufferAttribute(edges, 1))
|
||||
geometry.setAttribute('aPlane', new Float32BufferAttribute(planes, 2))
|
||||
geometry.setIndex(indices)
|
||||
|
||||
const mesh = new Mesh(geometry, material)
|
||||
mesh.position.set(position[0] + centreX, position[1] + centreY, position[2])
|
||||
if (options.rotation) mesh.rotation.set(...options.rotation)
|
||||
return mesh
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrowest web of material between any two rings of the profile - the outer
|
||||
* outline and each opening. Infinite when the part has no holes at all.
|
||||
*
|
||||
* Measured point-to-edge in both directions, never corner-to-corner: two
|
||||
* concentric rectangles a tenth apart have corners a seventh apart, and trusting
|
||||
* that larger figure lets a chamfer open a hole wider than the outline it is
|
||||
* supposed to sit inside.
|
||||
*
|
||||
* It runs on the filleted rings rather than the polygons they came from, because
|
||||
* those rings are what actually gets offset - rounding two facing corners pulls
|
||||
* them closer than the straight edges ever were, and measuring the input would
|
||||
* miss it.
|
||||
*/
|
||||
function ringClearance(rings: RingPoint[][]): number {
|
||||
if (rings.length < 2) return Infinity
|
||||
let smallest = Infinity
|
||||
for (let a = 0; a < rings.length; a += 1) {
|
||||
for (let b = 0; b < rings.length; b += 1) {
|
||||
if (a === b) continue
|
||||
for (const { x: px, y: py } of rings[a]) {
|
||||
const ring = rings[b]
|
||||
for (let i = 0; i < ring.length; i += 1) {
|
||||
const { x: ax, y: ay } = ring[i]
|
||||
const { x: bx, y: by } = ring[(i + 1) % ring.length]
|
||||
const dx = bx - ax
|
||||
const dy = by - ay
|
||||
const lengthSquared = dx * dx + dy * dy
|
||||
const t = lengthSquared > 0
|
||||
? Math.min(1, Math.max(0, ((px - ax) * dx + (py - ay) * dy) / lengthSquared))
|
||||
: 0
|
||||
smallest = Math.min(smallest, Math.hypot(px - (ax + dx * t), py - (ay + dy * t)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return smallest
|
||||
}
|
||||
|
||||
/** Smallest width of a ring's bounding box - its room for a constant wear band. */
|
||||
function ringSpan(ring: RingPoint[]): number {
|
||||
let minX = Infinity
|
||||
let maxX = -Infinity
|
||||
let minY = Infinity
|
||||
let maxY = -Infinity
|
||||
for (const point of ring) {
|
||||
minX = Math.min(minX, point.x)
|
||||
maxX = Math.max(maxX, point.x)
|
||||
minY = Math.min(minY, point.y)
|
||||
maxY = Math.max(maxY, point.y)
|
||||
}
|
||||
return Math.min(maxX - minX, maxY - minY)
|
||||
}
|
||||
|
||||
function isConvexRing(ring: RingPoint[]): boolean {
|
||||
const count = ring.length
|
||||
let sign = 0
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
const a = ring[i]
|
||||
const b = ring[(i + 1) % count]
|
||||
const c = ring[(i + 2) % count]
|
||||
const cross = (b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x)
|
||||
if (Math.abs(cross) < 1e-9) continue
|
||||
const current = Math.sign(cross)
|
||||
if (sign === 0) sign = current
|
||||
else if (current !== sign) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* A single quad. Engraved marks, dashes, and slot cuts on a flat armor face are
|
||||
* two triangles apiece, the way they would be modelled or floated by hand -
|
||||
* they never justify a beveled solid.
|
||||
*/
|
||||
export function flatPlate(
|
||||
material: MeshPhysicalMaterial,
|
||||
size: Vec2,
|
||||
position: Vec3,
|
||||
rotation: Vec3 = [0, 0, 0],
|
||||
engraved = true,
|
||||
): Mesh {
|
||||
const hx = size[0] * 0.5
|
||||
const hy = size[1] * 0.5
|
||||
const geometry = new BufferGeometry()
|
||||
geometry.setAttribute(
|
||||
'position',
|
||||
new Float32BufferAttribute([-hx, -hy, 0, hx, -hy, 0, hx, hy, 0, -hx, hy, 0], 3),
|
||||
)
|
||||
geometry.setAttribute('normal', new Float32BufferAttribute([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], 3))
|
||||
geometry.setAttribute('uv', new Float32BufferAttribute([0, 0, 1, 0, 1, 1, 0, 1], 2))
|
||||
// Engraved marks sit in a cut, so they read as worn along their whole length.
|
||||
geometry.setAttribute('aEdge', new Float32BufferAttribute([0.7, 0.7, 0.7, 0.7], 1))
|
||||
geometry.setAttribute(
|
||||
'aPlane',
|
||||
new Float32BufferAttribute([-hx, -hy, hx, -hy, hx, hy, -hx, hy], 2),
|
||||
)
|
||||
geometry.setIndex([0, 1, 2, 0, 2, 3])
|
||||
const mesh = new Mesh(geometry, material)
|
||||
mesh.position.set(...position)
|
||||
mesh.rotation.set(...rotation)
|
||||
// A cut runs along the mark's long axis, so its profile is read across the
|
||||
// short one. Painted markers are not cuts and opt out.
|
||||
if (engraved) mesh.userData.grooveCross = size[0] >= size[1] ? 'y' : 'x'
|
||||
return mesh
|
||||
}
|
||||
|
||||
/**
|
||||
* A real cut: a narrow channel with two side walls and a floor, extruded along
|
||||
* its length.
|
||||
*
|
||||
* A dark quad floated on a face shares that face's normal, so it lights
|
||||
* identically to the surface around it and reads as paint no matter how black it
|
||||
* is. What makes a panel line read as engraved is that its two walls face
|
||||
* opposite directions - one catches the key and one falls into shadow - which
|
||||
* only exists if the walls are geometry. Six triangles buys that.
|
||||
*
|
||||
* The channel is cut into the plane z = 0 with the face normal along +z; rotate
|
||||
* the mesh to place it on any other face.
|
||||
*/
|
||||
export function groove(
|
||||
material: MeshPhysicalMaterial,
|
||||
length: number,
|
||||
width: number,
|
||||
depth: number,
|
||||
position: Vec3,
|
||||
rotation: Vec3 = [0, 0, 0],
|
||||
): Mesh {
|
||||
const hw = width * 0.5
|
||||
const hl = length * 0.5
|
||||
// Wall draft. A dead-vertical wall gives the two sides the same shading under
|
||||
// a frontal key, so the cut needs a real opening angle to separate them.
|
||||
const wall = Math.min(hw * 0.55, depth * 0.9)
|
||||
|
||||
// Cross-section across the width, from one rim down to the floor and back.
|
||||
const section: Vec2[] = [
|
||||
[-hw, 0],
|
||||
[-hw + wall, -depth],
|
||||
[hw - wall, -depth],
|
||||
[hw, 0],
|
||||
]
|
||||
|
||||
const positions: number[] = []
|
||||
const normals: number[] = []
|
||||
const uvs: number[] = []
|
||||
const edges: number[] = []
|
||||
const planes: number[] = []
|
||||
const indices: number[] = []
|
||||
|
||||
for (let i = 0; i < section.length - 1; i += 1) {
|
||||
const [ax, az] = section[i]
|
||||
const [bx, bz] = section[i + 1]
|
||||
// Outward normal of this facet: perpendicular to the section edge, pointing
|
||||
// up out of the cut.
|
||||
const dx = bx - ax
|
||||
const dz = bz - az
|
||||
const nl = Math.hypot(dx, dz) || 1
|
||||
const nx = -dz / nl
|
||||
const nz = dx / nl
|
||||
const base = positions.length / 3
|
||||
for (const [x, z] of [[ax, az], [bx, bz]] as const) {
|
||||
for (const y of [-hl, hl]) {
|
||||
positions.push(x, y, z)
|
||||
normals.push(nx, 0, nz)
|
||||
uvs.push((x + hw) / width, (y + hl) / length)
|
||||
// A cut is worn along its whole length; nothing in here is pristine.
|
||||
edges.push(0.85)
|
||||
planes.push(y, x)
|
||||
}
|
||||
}
|
||||
indices.push(base, base + 2, base + 3, base, base + 3, base + 1)
|
||||
}
|
||||
|
||||
const geometry = new BufferGeometry()
|
||||
geometry.setAttribute('position', new Float32BufferAttribute(positions, 3))
|
||||
geometry.setAttribute('normal', new Float32BufferAttribute(normals, 3))
|
||||
geometry.setAttribute('uv', new Float32BufferAttribute(uvs, 2))
|
||||
geometry.setAttribute('aEdge', new Float32BufferAttribute(edges, 1))
|
||||
geometry.setAttribute('aPlane', new Float32BufferAttribute(planes, 2))
|
||||
geometry.setIndex(indices)
|
||||
|
||||
const mesh = new Mesh(geometry, material)
|
||||
mesh.position.set(...position)
|
||||
mesh.rotation.set(...rotation)
|
||||
mesh.userData.grooveCross = 'x'
|
||||
return mesh
|
||||
}
|
||||
|
||||
export function cylinder(
|
||||
material: MeshPhysicalMaterial,
|
||||
radius: number,
|
||||
depth: number,
|
||||
position: Vec3,
|
||||
rotation: Vec3 = [0, 0, 0],
|
||||
segments = 8,
|
||||
): Mesh {
|
||||
const geometry = new CylinderGeometry(radius, radius, depth, segments)
|
||||
// Bolt heads and pivot bosses are small proud hardware: worn across the cap.
|
||||
const count = geometry.getAttribute('position').count
|
||||
geometry.setAttribute('aEdge', new Float32BufferAttribute(new Float32Array(count).fill(0.75), 1))
|
||||
const mesh = new Mesh(geometry, material)
|
||||
mesh.position.set(...position)
|
||||
mesh.rotation.set(...rotation)
|
||||
return mesh
|
||||
}
|
||||
|
||||
/** Flat down-pointing triangle, so the latch arrow is deterministic. */
|
||||
export function downTriangle(material: MeshPhysicalMaterial, width: number, height: number, position: Vec3): Mesh {
|
||||
const hx = width * 0.5
|
||||
const hy = height * 0.5
|
||||
const hz = 0.01
|
||||
const face: Vec2[] = [
|
||||
[-hx, hy],
|
||||
[hx, hy],
|
||||
[0, -hy],
|
||||
]
|
||||
const positions: number[] = []
|
||||
const normals: number[] = []
|
||||
const uvs: number[] = []
|
||||
for (const z of [-hz, hz]) {
|
||||
for (const [x, y] of face) {
|
||||
positions.push(x, y, z)
|
||||
normals.push(0, 0, Math.sign(z))
|
||||
uvs.push(0.5, 0.5)
|
||||
}
|
||||
}
|
||||
const indices = [0, 2, 1, 3, 4, 5, 0, 1, 4, 0, 4, 3, 1, 2, 5, 1, 5, 4, 2, 0, 3, 2, 3, 5]
|
||||
const geometry = new BufferGeometry()
|
||||
geometry.setAttribute('position', new Float32BufferAttribute(positions, 3))
|
||||
geometry.setAttribute('normal', new Float32BufferAttribute(normals, 3))
|
||||
geometry.setAttribute('uv', new Float32BufferAttribute(uvs, 2))
|
||||
geometry.setAttribute('aEdge', new Float32BufferAttribute(new Float32Array(6).fill(0.6), 1))
|
||||
geometry.setIndex(indices)
|
||||
const mesh = new Mesh(geometry, material)
|
||||
mesh.position.set(...position)
|
||||
return mesh
|
||||
}
|
||||
|
||||
158
src/lib/vibe3d/scifi-kit/generator/profile.ts
Normal file
158
src/lib/vibe3d/scifi-kit/generator/profile.ts
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
import { orientRing, signedArea, type Vec2 } from './primitives.ts'
|
||||
|
||||
/**
|
||||
* Shape algebra for extrusion profiles.
|
||||
*
|
||||
* `extrudeProfile` has always accepted any polygon, so a notched frame or an
|
||||
* interlocking pair was never beyond the geometry - it was beyond the *notation*.
|
||||
* Absolute coordinate lists can only be typed out, and two parts that must fit
|
||||
* each other can only be typed out twice and kept in sync by hand, which never
|
||||
* survives the first edit.
|
||||
*
|
||||
* These are the operations hard-surface forms are actually conceived in: take an
|
||||
* outline, step one of its edges, offset the whole ring to get the part that
|
||||
* mates with it. A profile built this way stays correct when its source moves,
|
||||
* which is the only reason a fit ever holds.
|
||||
*/
|
||||
|
||||
const EPSILON = 1e-6
|
||||
|
||||
function unit(x: number, y: number): Vec2 {
|
||||
const length = Math.hypot(x, y) || 1
|
||||
return [x / length, y / length]
|
||||
}
|
||||
|
||||
/** Axis-aligned rectangle, counter-clockwise from the top-right. */
|
||||
export function rect(halfWidth: number, halfHeight: number): Vec2[] {
|
||||
return [
|
||||
[halfWidth, halfHeight],
|
||||
[-halfWidth, halfHeight],
|
||||
[-halfWidth, -halfHeight],
|
||||
[halfWidth, -halfHeight],
|
||||
]
|
||||
}
|
||||
|
||||
/** Rectangle with all four corners clipped at 45 degrees - the kit's octagon. */
|
||||
export function octagon(halfWidth: number, halfHeight: number, clip: number): Vec2[] {
|
||||
return [
|
||||
[halfWidth, halfHeight - clip], [halfWidth - clip, halfHeight],
|
||||
[-halfWidth + clip, halfHeight], [-halfWidth, halfHeight - clip],
|
||||
[-halfWidth, -halfHeight + clip], [-halfWidth + clip, -halfHeight],
|
||||
[halfWidth - clip, -halfHeight], [halfWidth, -halfHeight + clip],
|
||||
]
|
||||
}
|
||||
|
||||
/** Mirrors a right-hand outline into a closed symmetric ring. */
|
||||
export function mirrorProfile(right: Vec2[]): Vec2[] {
|
||||
return [...right, ...[...right].reverse().map(([x, y]): Vec2 => [-x, y])]
|
||||
}
|
||||
|
||||
export type Side = 'top' | 'bottom' | 'left' | 'right'
|
||||
|
||||
/**
|
||||
* Steps a centred span of one side in or out, joined by 45-degree runs.
|
||||
*
|
||||
* This is the notch that shows up on nearly every hard-surface frame and stand,
|
||||
* and the reason it is worth a named operation is that writing it by hand means
|
||||
* inventing six coordinates that have to stay symmetric about the centre and
|
||||
* stay put when the outline around them changes.
|
||||
*
|
||||
* A positive `rise` pushes the span outward; a negative one sinks it, which
|
||||
* makes two reflex corners - filleted and extruded exactly like convex ones.
|
||||
*/
|
||||
export function stepEdge(
|
||||
profile: Vec2[],
|
||||
side: Side,
|
||||
halfSpan: number,
|
||||
rise: number,
|
||||
run = Math.abs(rise),
|
||||
): Vec2[] {
|
||||
const ring = orientRing(profile, true)
|
||||
const horizontal = side === 'top' || side === 'bottom'
|
||||
const outward = side === 'top' || side === 'right' ? 1 : -1
|
||||
|
||||
// Along-axis coordinate of the side, and the ring's extreme in that direction.
|
||||
const axis = (point: Vec2): number => (horizontal ? point[1] : point[0])
|
||||
const across = (point: Vec2): number => (horizontal ? point[0] : point[1])
|
||||
let extreme = -Infinity
|
||||
for (const point of ring) extreme = Math.max(extreme, axis(point) * outward)
|
||||
extreme *= outward
|
||||
|
||||
const make = (alongCentre: number, acrossValue: number): Vec2 =>
|
||||
horizontal ? [acrossValue, alongCentre] : [alongCentre, acrossValue]
|
||||
|
||||
const stepped = extreme + rise * outward
|
||||
const result: Vec2[] = []
|
||||
let inserted = false
|
||||
|
||||
for (let i = 0; i < ring.length; i += 1) {
|
||||
const current = ring[i]
|
||||
const next = ring[(i + 1) % ring.length]
|
||||
result.push(current)
|
||||
if (inserted) continue
|
||||
// The edge lying on the side being stepped, long enough to hold the span.
|
||||
if (Math.abs(axis(current) - extreme) > EPSILON) continue
|
||||
if (Math.abs(axis(next) - extreme) > EPSILON) continue
|
||||
const from = across(current)
|
||||
const to = across(next)
|
||||
if (Math.min(from, to) > -halfSpan - run || Math.max(from, to) < halfSpan + run) continue
|
||||
|
||||
// Insert in traversal order so the ring stays wound the way it arrived.
|
||||
const descending = to < from
|
||||
const outer = halfSpan + run
|
||||
const spans: Array<[number, number]> = descending
|
||||
? [[outer, extreme], [halfSpan, stepped], [-halfSpan, stepped], [-outer, extreme]]
|
||||
: [[-outer, extreme], [-halfSpan, stepped], [halfSpan, stepped], [outer, extreme]]
|
||||
for (const [acrossValue, alongValue] of spans) result.push(make(alongValue, acrossValue))
|
||||
inserted = true
|
||||
}
|
||||
|
||||
if (!inserted) {
|
||||
throw new Error(`stepEdge: no ${side} edge wide enough for a ${halfSpan * 2} span`)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Offsets every edge of a ring by a constant distance, mitring the corners.
|
||||
*
|
||||
* Positive grows the shape, negative shrinks it. This is what makes two parts
|
||||
* fit by construction: author the inner part once, and derive whatever wraps it
|
||||
* as `offsetProfile(inner, gap)`. Edit the inner outline afterwards - add a
|
||||
* notch to it, move a corner - and the mating part follows, because it was never
|
||||
* a second copy of the numbers in the first place.
|
||||
*/
|
||||
export function offsetProfile(profile: Vec2[], distance: number, miterLimit = 4): Vec2[] {
|
||||
const ring = orientRing(profile, true)
|
||||
const count = ring.length
|
||||
const winding = signedArea(ring) > 0 ? 1 : -1
|
||||
const result: Vec2[] = []
|
||||
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
const previous = ring[(i - 1 + count) % count]
|
||||
const vertex = ring[i]
|
||||
const next = ring[(i + 1) % count]
|
||||
|
||||
const incoming = unit(vertex[0] - previous[0], vertex[1] - previous[1])
|
||||
const outgoing = unit(next[0] - vertex[0], next[1] - vertex[1])
|
||||
// Outward edge normal of a counter-clockwise ring is the direction turned
|
||||
// right; `winding` keeps that true if a caller hands in a reversed loop.
|
||||
const firstNormal: Vec2 = [incoming[1] * winding, -incoming[0] * winding]
|
||||
const secondNormal: Vec2 = [outgoing[1] * winding, -outgoing[0] * winding]
|
||||
|
||||
const bisector = unit(firstNormal[0] + secondNormal[0], firstNormal[1] + secondNormal[1])
|
||||
const cosine = bisector[0] * firstNormal[0] + bisector[1] * firstNormal[1]
|
||||
if (!Number.isFinite(cosine) || cosine < EPSILON) {
|
||||
result.push([vertex[0] + firstNormal[0] * distance, vertex[1] + firstNormal[1] * distance])
|
||||
continue
|
||||
}
|
||||
// A sharp corner's mitre runs away to infinity, so it is capped rather than
|
||||
// allowed to throw a spike out of the silhouette.
|
||||
const reach = Math.min(1 / cosine, miterLimit)
|
||||
result.push([
|
||||
vertex[0] + bisector[0] * distance * reach,
|
||||
vertex[1] + bisector[1] * distance * reach,
|
||||
])
|
||||
}
|
||||
return result
|
||||
}
|
||||
524
src/lib/vibe3d/scifi-kit/generator/wear.ts
Normal file
524
src/lib/vibe3d/scifi-kit/generator/wear.ts
Normal file
|
|
@ -0,0 +1,524 @@
|
|||
import {
|
||||
Box3,
|
||||
Float32BufferAttribute,
|
||||
Mesh,
|
||||
MeshPhysicalMaterial,
|
||||
Vector3,
|
||||
type BufferGeometry,
|
||||
type Group,
|
||||
} from 'three/webgpu'
|
||||
import {
|
||||
abs,
|
||||
attribute,
|
||||
clamp,
|
||||
cos,
|
||||
float,
|
||||
floor,
|
||||
fract,
|
||||
hash,
|
||||
mix,
|
||||
normalWorld,
|
||||
oneMinus,
|
||||
positionLocal,
|
||||
positionWorld,
|
||||
pow,
|
||||
sin,
|
||||
normalize,
|
||||
max,
|
||||
sqrt,
|
||||
cross,
|
||||
smoothstep,
|
||||
step,
|
||||
transformNormalToView,
|
||||
uv,
|
||||
vec3,
|
||||
vec4,
|
||||
} from 'three/tsl'
|
||||
|
||||
/**
|
||||
* Wear is placed by the form, never sprayed over it.
|
||||
*
|
||||
* Two attributes baked into the mesh at build time do all the placing: `aEdge`
|
||||
* marks the convex bevels and corner arcs the prism generator already knows
|
||||
* about, and `aOcc` is a short-ray occlusion bake against the other parts, so
|
||||
* grime lands in the seams and under the overhangs that actually exist. Noise
|
||||
* only breaks those masks up - a perfectly even rub outline is the tell that
|
||||
* nobody authored it by hand.
|
||||
*/
|
||||
|
||||
const OCCLUSION_REACH = 0.34
|
||||
const OCCLUSION_RAYS: Array<[number, number, number]> = [
|
||||
[0, 0, 1],
|
||||
[0.62, 0, 0.78],
|
||||
[-0.62, 0, 0.78],
|
||||
[0, 0.62, 0.78],
|
||||
[0, -0.62, 0.78],
|
||||
]
|
||||
|
||||
/** Slab test: distance along `direction` at which the ray first enters `box`, or Infinity. */
|
||||
function rayBoxEntry(origin: Vector3, direction: Vector3, box: Box3, limit: number): number {
|
||||
let near = 0
|
||||
let far = limit
|
||||
for (const axis of ['x', 'y', 'z'] as const) {
|
||||
const d = direction[axis]
|
||||
if (Math.abs(d) < 1e-6) {
|
||||
if (origin[axis] < box.min[axis] || origin[axis] > box.max[axis]) return Infinity
|
||||
continue
|
||||
}
|
||||
let t0 = (box.min[axis] - origin[axis]) / d
|
||||
let t1 = (box.max[axis] - origin[axis]) / d
|
||||
if (t0 > t1) [t0, t1] = [t1, t0]
|
||||
if (t0 > near) near = t0
|
||||
if (t1 < far) far = t1
|
||||
if (near > far) return Infinity
|
||||
}
|
||||
return near
|
||||
}
|
||||
|
||||
/** An orthonormal basis around `normal`, so the ray cone spreads across the surface. */
|
||||
function basisFor(normal: Vector3, tangent: Vector3, bitangent: Vector3): void {
|
||||
const helper = Math.abs(normal.y) > 0.9 ? new Vector3(1, 0, 0) : new Vector3(0, 1, 0)
|
||||
tangent.crossVectors(helper, normal).normalize()
|
||||
bitangent.crossVectors(normal, tangent).normalize()
|
||||
}
|
||||
|
||||
/**
|
||||
* Bakes `aOcc` per vertex by marching a small cone of rays against every other
|
||||
* part's world bounds. A vertex on an exposed panel face sees nothing and stays
|
||||
* clean; one down a channel or under the lid overhang is hit from several
|
||||
* directions and collects grime.
|
||||
*/
|
||||
export interface OcclusionBakeOptions {
|
||||
/** Maximum world-space distance at which another part can occlude a vertex. */
|
||||
readonly reach?: number
|
||||
}
|
||||
|
||||
export function bakeOcclusion(root: Group, options: OcclusionBakeOptions = {}): void {
|
||||
const reach = options.reach ?? OCCLUSION_REACH
|
||||
root.updateMatrixWorld(true)
|
||||
|
||||
const meshes: Mesh[] = []
|
||||
root.traverse((object) => {
|
||||
if (object instanceof Mesh) meshes.push(object)
|
||||
})
|
||||
|
||||
const bounds = meshes.map((mesh) => {
|
||||
const box = new Box3().setFromObject(mesh)
|
||||
return {
|
||||
box,
|
||||
centre: box.getCenter(new Vector3()),
|
||||
radius: box.getSize(new Vector3()).length() * 0.5,
|
||||
}
|
||||
})
|
||||
|
||||
const position = new Vector3()
|
||||
const normal = new Vector3()
|
||||
const tangent = new Vector3()
|
||||
const bitangent = new Vector3()
|
||||
const origin = new Vector3()
|
||||
const direction = new Vector3()
|
||||
|
||||
for (const [index, mesh] of meshes.entries()) {
|
||||
const geometry = mesh.geometry as BufferGeometry
|
||||
const positions = geometry.getAttribute('position')
|
||||
const normals = geometry.getAttribute('normal')
|
||||
if (!positions || !normals) continue
|
||||
const occlusion = new Float32Array(positions.count)
|
||||
|
||||
for (let v = 0; v < positions.count; v += 1) {
|
||||
position.fromBufferAttribute(positions, v).applyMatrix4(mesh.matrixWorld)
|
||||
normal.fromBufferAttribute(normals, v).transformDirection(mesh.matrixWorld).normalize()
|
||||
basisFor(normal, tangent, bitangent)
|
||||
// Lift off the surface so a part never occludes itself at its own skin.
|
||||
origin.copy(position).addScaledVector(normal, 0.014)
|
||||
|
||||
let hits = 0
|
||||
for (const [tx, ty, tz] of OCCLUSION_RAYS) {
|
||||
direction
|
||||
.copy(normal)
|
||||
.multiplyScalar(tz)
|
||||
.addScaledVector(tangent, tx)
|
||||
.addScaledVector(bitangent, ty)
|
||||
.normalize()
|
||||
|
||||
let nearest = Infinity
|
||||
for (const [other, bound] of bounds.entries()) {
|
||||
if (other === index) continue
|
||||
if (origin.distanceTo(bound.centre) - bound.radius > reach) continue
|
||||
const entry = rayBoxEntry(origin, direction, bound.box, reach)
|
||||
if (entry < nearest) nearest = entry
|
||||
}
|
||||
if (nearest < reach) hits += 1 - nearest / reach
|
||||
}
|
||||
occlusion[v] = Math.min(1, hits / (OCCLUSION_RAYS.length * 0.7))
|
||||
}
|
||||
|
||||
geometry.setAttribute('aOcc', new Float32BufferAttribute(occlusion, 1))
|
||||
}
|
||||
}
|
||||
|
||||
export interface WearProfile {
|
||||
/** How readily this surface rubs through to bare metal on its edges. */
|
||||
readonly rub: number
|
||||
/** How much grime this surface collects in its occluded areas. */
|
||||
readonly grime: number
|
||||
/** Scratch visibility. Rubber and lenses take almost none. */
|
||||
readonly scratch: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Bakes each part's surface identity into vertex attributes: base colour,
|
||||
* roughness/metalness, and its wear character.
|
||||
*
|
||||
* This exists because the whole case is deliberately one material. Giving each
|
||||
* part its own node material instead would make several materials compile to
|
||||
* structurally identical graphs, and they then share a program and bindings -
|
||||
* every surface ends up wearing the colour of whichever material compiled last.
|
||||
* Baking to attributes also collapses the prop to a handful of draw calls,
|
||||
* which is what a real hand-authored asset would ship as anyway.
|
||||
*/
|
||||
export function bakeSurfaceAttributes(
|
||||
root: Group,
|
||||
profiles: ReadonlyMap<MeshPhysicalMaterial, WearProfile>,
|
||||
): void {
|
||||
root.traverse((object) => {
|
||||
if (!(object instanceof Mesh) || Array.isArray(object.material)) return
|
||||
const material = object.material as MeshPhysicalMaterial
|
||||
const profile = profiles.get(material)
|
||||
if (!profile) return
|
||||
const geometry = object.geometry as BufferGeometry
|
||||
const positions = geometry.getAttribute('position')
|
||||
const normals = geometry.getAttribute('normal')
|
||||
const count = positions.count
|
||||
|
||||
// An engraved mark needs its cut direction in world space so the shader can
|
||||
// tilt the two walls apart. The local cross axis is known at authoring time;
|
||||
// the world matrix is still available here, before the merge flattens it.
|
||||
const cross = object.userData.grooveCross as 'x' | 'y' | undefined
|
||||
const direction = new Vector3(cross === 'x' ? 1 : 0, cross === 'y' ? 1 : 0, 0)
|
||||
if (cross) direction.transformDirection(object.matrixWorld).normalize()
|
||||
|
||||
const edge = geometry.getAttribute('aEdge')
|
||||
const occlusion = geometry.getAttribute('aOcc')
|
||||
|
||||
// WebGPU allows eight vertex buffers and position/normal/uv take three, so
|
||||
// everything the wear shader needs is packed into four.
|
||||
const mask = new Float32Array(count * 4)
|
||||
const plane = new Float32Array(count * 2)
|
||||
const vertex = new Vector3()
|
||||
const faceNormal = new Vector3()
|
||||
const source = geometry.getAttribute('aPlane')
|
||||
// Flake frequency relative to the part. One world frequency makes a bolt
|
||||
// and a lid wear at the same absolute grain, so small parts read as camo.
|
||||
geometry.computeBoundingBox()
|
||||
const extent = geometry.boundingBox!.getSize(new Vector3())
|
||||
const span = Math.max(0.06, (extent.x + extent.y + extent.z) / 3)
|
||||
const flakeScale = Math.min(2.6, Math.max(0.55, 0.9 / span))
|
||||
const origin = new Vector3().setFromMatrixPosition(object.matrixWorld)
|
||||
const offsetU = origin.x * 3.17 + origin.y * 1.41 + origin.z * 0.83
|
||||
const offsetV = origin.z * 2.71 + origin.y * 0.97 - origin.x * 1.13
|
||||
const colour = new Float32Array(count * 3)
|
||||
const surface = new Float32Array(count * 4)
|
||||
const wearDir = new Float32Array(count * 4)
|
||||
for (let v = 0; v < count; v += 1) {
|
||||
mask[v * 4] = edge ? edge.getX(v) : 0
|
||||
mask[v * 4 + 1] = occlusion ? occlusion.getX(v) : 0
|
||||
// Groove state packed into one slot: 0 none, 1 cut across X, 2 across Y.
|
||||
mask[v * 4 + 2] = cross ? (cross === 'y' ? 2 : 1) : 0
|
||||
|
||||
// Prisms and flat marks bake a real surface parameter in the generator.
|
||||
// Offset it per part, or two identical parts wear identically - and that
|
||||
// repeat is far more obvious than any noise pattern.
|
||||
vertex.fromBufferAttribute(positions, v).applyMatrix4(object.matrixWorld)
|
||||
if (source) {
|
||||
plane[v * 2] = source.getX(v) + offsetU
|
||||
plane[v * 2 + 1] = source.getY(v) + offsetV
|
||||
} else {
|
||||
// Lathe primitives have no unwrap; project them, they are small enough
|
||||
// that the stretch never reads.
|
||||
faceNormal.fromBufferAttribute(normals, v).transformDirection(object.matrixWorld)
|
||||
const ax = Math.abs(faceNormal.x)
|
||||
const ay = Math.abs(faceNormal.y)
|
||||
const az = Math.abs(faceNormal.z)
|
||||
const dominant = ax >= ay && ax >= az ? 0 : ay >= az ? 1 : 2
|
||||
plane[v * 2] = dominant === 0 ? vertex.z : vertex.x
|
||||
plane[v * 2 + 1] = dominant === 1 ? vertex.z : vertex.y
|
||||
}
|
||||
mask[v * 4 + 3] = flakeScale
|
||||
|
||||
colour[v * 3] = material.color.r
|
||||
colour[v * 3 + 1] = material.color.g
|
||||
colour[v * 3 + 2] = material.color.b
|
||||
surface[v * 4] = material.roughness
|
||||
surface[v * 4 + 1] = material.metalness
|
||||
surface[v * 4 + 2] = profile.rub
|
||||
surface[v * 4 + 3] = profile.grime
|
||||
wearDir[v * 4] = profile.scratch
|
||||
wearDir[v * 4 + 1] = direction.x
|
||||
wearDir[v * 4 + 2] = direction.y
|
||||
wearDir[v * 4 + 3] = direction.z
|
||||
}
|
||||
geometry.setAttribute('aMask', new Float32BufferAttribute(mask, 4))
|
||||
geometry.setAttribute('aPlane', new Float32BufferAttribute(plane, 2))
|
||||
geometry.setAttribute('aSurface', new Float32BufferAttribute(surface, 4))
|
||||
geometry.setAttribute('aWearDir', new Float32BufferAttribute(wearDir, 4))
|
||||
geometry.deleteAttribute('aEdge')
|
||||
geometry.deleteAttribute('aOcc')
|
||||
geometry.setAttribute('aColor', new Float32BufferAttribute(colour, 3))
|
||||
})
|
||||
}
|
||||
|
||||
export const WEAR_ATTRIBUTES = ['aMask', 'aColor', 'aSurface', 'aWearDir', 'aPlane'] as const
|
||||
|
||||
/**
|
||||
* The single wear material.
|
||||
*
|
||||
* Deliberately no fractal noise in any placement term. Fractal noise is
|
||||
* isotropic, so it produces soft clouds, and clouds read as fog rather than as
|
||||
* damage. Real wear is structured and hard-edged: paint chips off in discrete
|
||||
* flakes with crisp boundaries, scratches are thin straight cuts, and grime is
|
||||
* placed by cavities and gravity with noise only varying its density.
|
||||
*/
|
||||
export interface WearMaterialOptions {
|
||||
readonly name?: string
|
||||
readonly clearcoat?: number
|
||||
readonly clearcoatRoughness?: number
|
||||
}
|
||||
|
||||
export function createWearMaterial(options: WearMaterialOptions = {}): MeshPhysicalMaterial {
|
||||
const material = new MeshPhysicalMaterial({ name: options.name ?? 'asset-forge / worn surface' })
|
||||
material.clearcoat = options.clearcoat ?? 0.3
|
||||
material.clearcoatRoughness = options.clearcoatRoughness ?? 0.3
|
||||
// One graph, shared across all four outputs. Calling wearOutputs() per output
|
||||
// builds the whole noise stack once per channel and costs four times as much.
|
||||
const outputs = wearOutputs()
|
||||
material.colorNode = outputs.colour
|
||||
material.roughnessNode = outputs.roughness
|
||||
material.metalnessNode = outputs.metalness
|
||||
material.normalNode = outputs.normal
|
||||
return material
|
||||
}
|
||||
|
||||
export interface WearOutputs {
|
||||
colour: typeof positionWorld
|
||||
roughness: typeof positionWorld.x
|
||||
metalness: typeof positionWorld.x
|
||||
normal: typeof positionWorld
|
||||
worldNormal: typeof positionWorld
|
||||
}
|
||||
|
||||
/**
|
||||
* The whole wear stack as node expressions.
|
||||
*
|
||||
* Everything is evaluated in the surface's own plane rather than in 3D. Slicing
|
||||
* a 3D noise field with a surface is both the reason the cracks read as flat
|
||||
* polygonal cells and the reason this was costing three 27-cell worley lookups
|
||||
* per pixel per output. Cracks and chips are surface phenomena, so 2D is both
|
||||
* cheaper and correct. All noise here is a four-tap value noise.
|
||||
*/
|
||||
export function wearOutputs(): WearOutputs {
|
||||
/** A plain float-valued node; the concrete TSL node classes vary by helper. */
|
||||
type Scalar = typeof positionLocal.x
|
||||
|
||||
const mask = attribute('aMask', 'vec4') as unknown as ReturnType<typeof vec4>
|
||||
const packed = attribute('aSurface', 'vec4') as unknown as ReturnType<typeof vec4>
|
||||
const wearDir = attribute('aWearDir', 'vec4') as unknown as ReturnType<typeof vec4>
|
||||
const baseColour = attribute('aColor', 'vec3') as unknown as ReturnType<typeof vec3>
|
||||
|
||||
const edge = mask.x
|
||||
const occ = mask.y
|
||||
const grooveOn = step(float(0.5), mask.z)
|
||||
const grooveCross = step(float(1.5), mask.z)
|
||||
const surface = packed
|
||||
const character = vec3(packed.z, packed.w, wearDir.x)
|
||||
const grooveDir = vec3(wearDir.y, wearDir.z, wearDir.w)
|
||||
|
||||
const metalColour = vec3(0.56, 0.575, 0.59)
|
||||
const grimeColour = vec3(0.16, 0.15, 0.13)
|
||||
const dustColour = vec3(0.47, 0.46, 0.42)
|
||||
|
||||
// Object-local coordinates keep the procedural surface attached to an
|
||||
// animated assembly. The geometry is merged into root/lid local space before
|
||||
// rendering, so this costs the same as positionWorld while following the
|
||||
// lid's hinge transform instead of swimming through it in world space.
|
||||
const p = positionLocal
|
||||
|
||||
// Surface-plane coordinates and the axis they came from, both baked per vertex
|
||||
// so they are stable no matter how the shading normal wobbles.
|
||||
const planeCoord = attribute('aPlane', 'vec2') as unknown as ReturnType<typeof vec4>
|
||||
const planeU = planeCoord.x.toVar()
|
||||
const planeV = planeCoord.y.toVar()
|
||||
// A surface basis from the normal, so nothing here depends on world axes.
|
||||
const helper = mix(vec3(0, 1, 0), vec3(1, 0, 0), step(float(0.9), abs(normalWorld.y)))
|
||||
const tangentU = normalize(cross(helper, normalWorld))
|
||||
const tangentV = cross(normalWorld, tangentU)
|
||||
|
||||
const lattice = (x: Scalar, y: Scalar) => hash(x.mul(127.1).add(y.mul(311.7)))
|
||||
/** Four-tap 2D value noise, for the surface-space grain only. */
|
||||
const noise = (x: Scalar, y: Scalar) => {
|
||||
const ix = floor(x)
|
||||
const iy = floor(y)
|
||||
const fx = fract(x)
|
||||
const fy = fract(y)
|
||||
const ux = fx.mul(fx).mul(fx.mul(-2).add(3))
|
||||
const uy = fy.mul(fy).mul(fy.mul(-2).add(3))
|
||||
return mix(
|
||||
mix(lattice(ix, iy), lattice(ix.add(1), iy), ux),
|
||||
mix(lattice(ix, iy.add(1)), lattice(ix.add(1), iy.add(1)), ux),
|
||||
uy,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Eight-tap 3D value noise.
|
||||
*
|
||||
* Everything that should read as belonging to the object rather than to one
|
||||
* panel is evaluated in object-local space with this. A 2D surface parameter cannot
|
||||
* be continuous across a part boundary, or across the seam between a face and
|
||||
* its own bevel, so patterns built on one always die at those edges - which is
|
||||
* exactly the "bound to a single face" break. 3D has no seams and no
|
||||
* projection stretch. It costs eight hashes; the worley field this replaces
|
||||
* cost twenty-seven.
|
||||
*/
|
||||
const noise3 = (q: typeof positionWorld) => {
|
||||
const i = floor(q)
|
||||
const f = fract(q)
|
||||
const u = f.mul(f).mul(f.mul(-2).add(3))
|
||||
const corner = (dx: number, dy: number, dz: number) =>
|
||||
hash(i.x.add(dx).mul(127.1).add(i.y.add(dy).mul(311.7)).add(i.z.add(dz).mul(74.7)))
|
||||
return mix(
|
||||
mix(
|
||||
mix(corner(0, 0, 0), corner(1, 0, 0), u.x),
|
||||
mix(corner(0, 1, 0), corner(1, 1, 0), u.x),
|
||||
u.y,
|
||||
),
|
||||
mix(
|
||||
mix(corner(0, 0, 1), corner(1, 0, 1), u.x),
|
||||
mix(corner(0, 1, 1), corner(1, 1, 1), u.x),
|
||||
u.y,
|
||||
),
|
||||
u.z,
|
||||
)
|
||||
}
|
||||
|
||||
// Paint chips. Frequency is scaled per part, so a bolt gets flakes sized to a
|
||||
// bolt rather than the one world frequency that made small parts read as
|
||||
// camouflage. Chipping is an edge phenomenon, so the mask is tied hard to the
|
||||
// edge attribute and blended in rather than stepped, which stops it shouting.
|
||||
const flakeScale = mask.w
|
||||
const flakeField = noise3(p.mul(flakeScale.mul(22)))
|
||||
const cluster = smoothstep(float(0.36), float(0.56), noise3(p.mul(flakeScale.mul(3.4))))
|
||||
const flake = smoothstep(float(0.52), float(0.36), flakeField)
|
||||
const rub = pow(edge, float(3))
|
||||
.mul(flake)
|
||||
.mul(cluster)
|
||||
.mul(oneMinus(occ.mul(0.85)))
|
||||
.mul(character.x)
|
||||
.toVar()
|
||||
|
||||
// Scratches as 3D slabs. A drag event picks a direction in object-local space
|
||||
// and lays parallel planes along it; wherever a surface cuts those planes it
|
||||
// gets straight parallel cuts that carry on across bevels and onto the next part.
|
||||
const region = floor(p.mul(0.4))
|
||||
const seed = region.x.mul(37.3).add(region.y.mul(91.7)).add(region.z.mul(53.1))
|
||||
const azimuth = hash(seed).mul(6.2831853)
|
||||
const height = hash(seed.add(3.7)).mul(2).sub(1)
|
||||
const ring = sqrt(clamp(oneMinus(height.mul(height)), 0, 1))
|
||||
const slab = vec3(cos(azimuth).mul(ring), height, sin(azimuth).mul(ring))
|
||||
const pitch = hash(seed.add(5.1)).mul(24).add(26)
|
||||
const band = p.dot(slab).mul(pitch).add(hash(seed.add(11.3)).mul(20))
|
||||
const cell = floor(band)
|
||||
const offset = fract(band).sub(0.5)
|
||||
const across = abs(offset).mul(2)
|
||||
const halfWidth = hash(cell.mul(7.7).add(seed)).mul(0.13).add(0.05)
|
||||
const line = step(across, halfWidth)
|
||||
const picked = step(float(0.78), hash(cell.mul(13.1).add(seed.mul(3.3))))
|
||||
const alongDir = normalize(cross(slab, vec3(0.31, 0.79, 0.53)))
|
||||
const run = step(float(0.36), hash(floor(p.dot(alongDir).mul(1.7)).mul(19.7).add(cell.mul(3.1))))
|
||||
// A slab lying nearly parallel to the surface would smear into a wide wash,
|
||||
// so fade the cut out as the two approach alignment.
|
||||
const bite = oneMinus(abs(slab.dot(normalWorld)))
|
||||
const exposure = oneMinus(occ).mul(smoothstep(float(-0.2), float(0.5), normalWorld.y.add(0.25)))
|
||||
const cut = line.mul(picked).mul(run).mul(exposure).mul(smoothstep(float(0.15), float(0.5), bite)).toVar()
|
||||
const scratch = cut.mul(character.z)
|
||||
const trough = oneMinus(clamp(across.div(halfWidth), 0, 1)).mul(scratch).toVar()
|
||||
const lip = clamp(across.div(halfWidth), 0, 1).mul(scratch).toVar()
|
||||
|
||||
// Brushed finish. Deliberately carried by roughness rather than by the normal:
|
||||
// the grain's fast axis is the baked surface parameter, but the direction it
|
||||
// can be tilted along comes from a cross-product basis that has no relation to
|
||||
// it, so where the two disagree a normal-driven grain visibly stretches and
|
||||
// thins from face to face. Roughness has no direction to get wrong, and a
|
||||
// brushed surface reads through the specular anyway.
|
||||
const grain = noise(planeU.mul(3.1), planeV.mul(68)).sub(0.5).toVar()
|
||||
const grainFine = noise(planeU.mul(9), planeV.mul(165)).sub(0.5)
|
||||
const finish = grain.mul(0.68).add(grainFine.mul(0.32)).mul(surface.y.add(0.4)).toVar()
|
||||
|
||||
// Engraved marks are flat geometry, so their depth comes from a V profile
|
||||
// read across the mark's own UVs.
|
||||
const grooveCoord = mix(uv().x, uv().y, grooveCross)
|
||||
const grooveFloor = oneMinus(abs(grooveCoord.sub(0.5)).mul(2)).mul(grooveOn).toVar()
|
||||
const grooveWall = clamp(grooveCoord.sub(0.5).mul(2), -1, 1).mul(grooveOn)
|
||||
|
||||
// Grime. Occlusion and gravity place all of it; noise only varies density.
|
||||
const down = clamp(normalWorld.y.negate(), 0, 1)
|
||||
const up = clamp(normalWorld.y, 0, 1)
|
||||
const splash = smoothstep(float(1.05), float(0.12), p.y)
|
||||
const streak = noise3(p.mul(vec3(9, 0.9, 9)))
|
||||
const grime = clamp(occ.mul(1.15).add(down.mul(0.24)).add(splash.mul(0.3)), 0, 1)
|
||||
.mul(streak.mul(0.4).add(0.7))
|
||||
.mul(character.y)
|
||||
.toVar()
|
||||
const dust = up.mul(0.26).mul(streak.mul(0.5).add(0.5)).mul(oneMinus(rub)).mul(character.y)
|
||||
|
||||
let colour = mix(baseColour, grimeColour, grime.mul(0.6))
|
||||
colour = mix(colour, dustColour, dust.mul(0.28))
|
||||
colour = mix(colour, metalColour, rub.mul(0.55))
|
||||
colour = mix(colour, grimeColour, trough.mul(0.85))
|
||||
colour = mix(colour, metalColour, lip.mul(0.6))
|
||||
colour = colour.mul(oneMinus(grooveFloor.mul(0.35)))
|
||||
|
||||
const roughness = clamp(
|
||||
surface.x
|
||||
.add(grime.mul(0.3))
|
||||
.add(trough.mul(0.38))
|
||||
.add(grooveFloor.mul(0.2))
|
||||
.sub(rub.mul(0.2))
|
||||
.sub(lip.mul(0.18))
|
||||
.add(finish.mul(0.1)),
|
||||
0.04,
|
||||
1,
|
||||
)
|
||||
const metalness = clamp(
|
||||
surface.y.add(rub.mul(0.35)).add(lip.mul(0.25)).sub(grime.mul(0.22)),
|
||||
0,
|
||||
1,
|
||||
)
|
||||
|
||||
// Normals. The scratch walls tilt across the cut, the crack walls tilt along
|
||||
// the gradient of the ridge field - which is what gives a crack actual depth
|
||||
// rather than leaving it a grey line - and engraved marks use their baked axis.
|
||||
// A cut leans its walls toward its own centre: on the +across side the normal
|
||||
// tilts to -across. Adding +across instead builds a raised welt, which is why
|
||||
// every scratch read as sticking out of the surface rather than into it.
|
||||
// A cut leans its walls toward its own centre: on the +across side the normal
|
||||
// tilts to -across. Adding +across instead builds a raised welt, which is why
|
||||
// every scratch read as sticking out of the surface rather than into it.
|
||||
const wall = clamp(offset.div(halfWidth), -1, 1).mul(cut).mul(character.z).mul(1.9)
|
||||
const inPlane = slab.sub(normalWorld.mul(slab.dot(normalWorld)))
|
||||
const acrossCut = inPlane.div(max(inPlane.length(), float(1e-4)))
|
||||
|
||||
const perturbed = normalWorld
|
||||
.sub(acrossCut.mul(wall))
|
||||
.sub(grooveDir.mul(grooveWall.mul(0.85)))
|
||||
.add(tangentV.mul(finish.mul(0.055)))
|
||||
.normalize()
|
||||
|
||||
return {
|
||||
colour,
|
||||
roughness,
|
||||
metalness,
|
||||
normal: transformNormalToView(perturbed),
|
||||
worldNormal: perturbed,
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue