import * as three_webgpu from 'three/webgpu'; import { Color, Vector2, Vector4, Vector3, Node, DataTexture, Mesh, Group, Camera, Object3D, DirectionalLight, BufferGeometry } from 'three/webgpu'; import { HeightFn, Terrain } from 'threejs-heightfield'; export { HeightFn, Terrain, bakeHeightfield, createHeightSampler, raycastHeight, slopeAt } from 'threejs-heightfield'; /** Maximum number of simultaneous {@link Interactor}s. Extra ones are ignored. */ declare const MAX_INTERACTORS = 16; /** * Creates the uniform set shared by a Grass field's materials. Grass calls this for you and drives the * values from `Grass.set()`; it is exported so the {@link GrassUniforms} type is documented in full. */ declare function createGrassUniforms(): { /** Blade colour at the root (from `baseColor`). */ baseColor: three_webgpu.UniformNode<"color", Color>; /** Blade colour at the tip (from `tipColor`). */ tipColor: three_webgpu.UniformNode<"color", Color>; /** Per-blade brightness variation, 0..1. */ colorVariation: three_webgpu.UniformNode<"float", number>; /** Field-scale light/dark and dry patches, 0..1. */ patchiness: three_webgpu.UniformNode<"float", number>; /** Back-lit glow strength. */ translucency: three_webgpu.UniformNode<"float", number>; /** Blade height in metres. */ bladeHeight: three_webgpu.UniformNode<"float", number>; /** Blade base width in metres. */ bladeWidth: three_webgpu.UniformNode<"float", number>; /** Natural droop, 0..1. */ curvature: three_webgpu.UniformNode<"float", number>; /** Resistance to wind and interaction (never below 0.05). */ stiffness: three_webgpu.UniformNode<"float", number>; /** Normalised XZ wind direction. */ windDirection: three_webgpu.UniformNode<"vec2", Vector2>; /** How far blades bend in the wind. */ windStrength: three_webgpu.UniformNode<"float", number>; /** Gust noise frequency (1/metres). */ windScale: three_webgpu.UniformNode<"float", number>; /** Gust travel speed. */ windSpeed: three_webgpu.UniformNode<"float", number>; /** The four LOD distances (x, y, z, w = LOD 0..3). */ lodDistances: three_webgpu.UniformNode<"vec4", Vector4>; /** The four LOD density fractions (x, y, z, w = LOD 0..3). */ lodDensities: three_webgpu.UniformNode<"vec4", Vector4>; /** Radius with grass; blades fade over its last 15%. */ maxDistance: three_webgpu.UniformNode<"float", number>; /** 1 tints grass by LOD, 0 = normal shading. */ debugLods: three_webgpu.UniformNode<"float", number>; /** Position LOD/fades are measured from. Set from the Grass camera on the CPU so shadow passes * (which render from the light) see exactly the same blades as the main view. */ viewPosition: three_webgpu.UniformNode<"vec3", Vector3>; /** Direction *towards* the sun. Drives back-lit translucency. */ sunDirection: three_webgpu.UniformNode<"vec3", Vector3>; /** Sun colour × intensity. */ sunColor: three_webgpu.UniformNode<"color", Color>; /** minX, minZ, sizeX, sizeZ of the grass map in world space. */ mapBounds: three_webgpu.UniformNode<"vec4", Vector4>; /** Grass map texture (R = coverage, G = height); a neutral 1×1 texture when there is none. */ map: three_webgpu.TextureNode<"vec4">; /** Global multiplier on interactor push. */ interactionStrength: three_webgpu.UniformNode<"float", number>; /** xyz = world position, w = radius (0 = unused slot). */ interactors: three_webgpu.UniformArrayNode; /** Number of active entries in `interactors`. */ interactorCount: three_webgpu.UniformNode<"int", number>; }; /** Shader uniforms of a Grass field (`grass.uniforms`). Each entry is a TSL uniform/texture node. */ type GrassUniforms = ReturnType; /** TSL nodes returned by `grass.mapNode()`. */ interface GrassMapSample { /** 0 = no grass, 1 = full coverage. 1 outside the map. */ coverage: Node<'float'>; /** Height multiplier, 0..2 (1 = preset height). 1 outside the map. */ height: Node<'float'>; } /** The look of a grass field. Every {@link presets} entry is a complete GrassStyle. */ interface GrassStyle { /** Blades per square metre at full density (LOD 0). */ density: number; /** Blade height in metres. Any height works (lawns ~0.1, meadows ~0.5, tall grass 1–3). */ bladeHeight: number; /** 0..1 random height spread per blade. */ heightVariation: number; /** Blade width at the base in metres. */ bladeWidth: number; /** 0..1 random width spread per blade. */ widthVariation: number; /** 0..1 natural droop of blades when there is no wind. */ curvature: number; /** Higher = less wind/interaction bending. */ stiffness: number; /** 0..1 how strongly blades gather into tufts that splay outwards. */ clumping: number; /** Tuft diameter in metres. */ clumpSize: number; /** Blade colour at the root (any CSS colour). */ baseColor: string; /** Blade colour at the tip (any CSS colour). */ tipColor: string; /** 0..1 per-blade brightness variation. */ colorVariation: number; /** 0..1 field-scale light/dark and dry patches. */ patchiness: number; /** 0..1 how much sunlight shines through blades when back-lit. */ translucency: number; } /** * Twelve ready-made looks: eight inspired by real species and four stylized ones. Pass a name as * `preset`, then override any {@link GrassStyle} field you like. */ declare const presets: { /** Kentucky Bluegrass: dense, fine, blue-green meadow grass. The default. */ kentuckyBluegrass: GrassStyle; /** Perennial Ryegrass: glossy, dark green, slightly taller tufts. */ perennialRyegrass: GrassStyle; /** Tall Fescue: coarse, wide blades in strong clumps, up to knee height. */ tallFescue: GrassStyle; /** Bermuda Grass: very dense, short, fine-bladed turf. */ bermudaGrass: GrassStyle; /** Zoysia Grass: short, stiff, carpet-like lawn grass. */ zoysiaGrass: GrassStyle; /** St. Augustine Grass: broad, flat, deep green blades. */ stAugustineGrass: GrassStyle; /** Buffalo Grass: short, curly, grey-green prairie grass. */ buffaloGrass: GrassStyle; /** Fine Fescue: very thin, floppy, blue-green blades. */ fineFescue: GrassStyle; /** Toon Meadow (stylized): wide, saturated, bright green blades. */ toonMeadow: GrassStyle; /** Golden Savanna (stylized): tall, dry, golden grass. */ goldenSavanna: GrassStyle; /** Autumn Haze (stylized): olive-to-ochre autumn field. */ autumnHaze: GrassStyle; /** Frostbite (stylized): pale, frosted silver-white grass. */ frostbite: GrassStyle; }; /** Name of one of the built-in {@link presets}. */ type PresetName = keyof typeof presets; /** Options for {@link GrassMap}. */ interface GrassMapOptions { /** World XZ centre of the mapped square. Default `[0, 0]`. */ center?: [x: number, z: number]; /** Edge length of the mapped square in metres. Default 256. */ size?: number; /** Texels per side. Default 512. */ resolution?: number; /** Initial coverage 0..1. Default 1 (grass everywhere). */ coverage?: number; /** Initial height multiplier 0..2 (1 = preset height). Default 1. */ height?: number; } /** What a brush stroke does: add/erase coverage, or raise/lower grass height. */ type BrushMode = 'add' | 'erase' | 'raise' | 'lower'; /** A soft round brush used by {@link GrassMap.paint} and {@link TerrainPainter}. */ interface Brush { /** What the stroke does: add/erase coverage or raise/lower height. */ mode: BrushMode; /** World radius in metres. */ radius: number; /** 0..1 amount applied per stroke event at the brush center. */ strength: number; } /** * A world-space control texture covering a square of terrain: where grass grows and how tall. * Channels: R = coverage (0 none … 1 full), G = height (0.5 = 1x … 1 = 2x). Outside its square, * grass grows normally. Edits (paint/fill/load) show up immediately. * * @example * ```ts * const map = new GrassMap({ center: [0, 0], size: 300 }) * map.paint(10, -4, { mode: 'erase', radius: 2, strength: 1 }) // a clearing * grass.set({ grassMap: map }) * ``` */ declare class GrassMap { /** GPU texture sampled by the grass (and by `grass.mapNode()`). */ readonly texture: DataTexture; /** Raw RGBA bytes, row-major, row 0 at `minZ`. Set `texture.needsUpdate = true` after editing directly. */ readonly data: Uint8Array; /** Texels per side. */ readonly resolution: number; /** Edge length of the mapped square in metres. */ readonly size: number; /** World X of the square's west edge. */ readonly minX: number; /** World Z of the square's north (−Z) edge. */ readonly minZ: number; /** Creates a map covering `size × size` metres around `center`, filled with `coverage` and `height`. */ constructor({ center, size, resolution, coverage, height }?: GrassMapOptions); /** * Creates a map from an image (red = coverage, green = height, mid-grey = 1x), read as a top-down * view with its top edge towards −Z. Round-trips with {@link GrassMap.toDataURL}. */ static fromImage(image: CanvasImageSource & { width: number; height: number; }, options?: Omit): GrassMap; /** Replaces the map's contents with an image (scaled to `resolution`). See {@link GrassMap.fromImage}. */ load(image: CanvasImageSource & { width: number; height: number; }): this; /** Sets the whole map to one coverage (0..1) and height multiplier (0..2). `fill(0)` clears all grass. */ fill(coverage?: number, height?: number): void; /** * Applies a soft round brush at world (x, z). * @returns `false` if the brush is entirely outside the map. */ paint(x: number, z: number, { mode, radius, strength }: Brush): boolean; /** Raw map as a canvas (R = coverage, G = height); round-trips through `GrassMap.fromImage`. */ toCanvas(): HTMLCanvasElement; /** PNG data URL of the map, e.g. to save a painted layout. */ toDataURL(): string; /** Frees the GPU texture. */ dispose(): void; } /** * Paint a Grass's `grassMap` directly on the terrain: left-drag to apply the brush; a ring follows * the pointer. Works with mesh and height-function terrain alike. Disable your camera controls * while painting — they listen to the same pointer events. * * @example * ```ts * const painter = new TerrainPainter(grass, renderer.domElement, { mode: 'add', radius: 3 }) * painter.brush.mode = 'erase' // change the brush at any time * painter.enabled = false // pause painting * ``` */ declare class TerrainPainter { readonly grass: Grass; readonly domElement: HTMLElement; /** When false, pointer events are ignored and the cursor is hidden. */ enabled: boolean; /** Current brush. Mutate freely. Defaults: erase, 3 m radius, 0.25 strength. */ brush: Brush; /** Brush outline that follows the terrain under the pointer. */ readonly cursor: Mesh; private painting; private raycaster; private ndc; /** * @param grass Field whose `grassMap` is painted. Must have a grass map. * @param domElement Element receiving pointer events, usually `renderer.domElement`. * @param brush Initial brush settings. * @throws If the grass has no `grassMap`. */ constructor(grass: Grass, domElement: HTMLElement, brush?: Partial); /** Removes listeners and the cursor. */ dispose(): void; private hit; private stroke; private onDown; private onMove; private onUp; private onLeave; } /** * One of the four levels of detail. Density is interpolated linearly between consecutive LODs, so * blades thin out smoothly with distance instead of popping at tile borders. */ interface GrassLOD { /** Distance from the camera (metres, XZ) at which this LOD is fully reached. */ distance: number; /** Fraction (0..1) of the full blade density kept at this distance. */ density: number; /** Vertical segments per blade (or billboard). More = smoother bending, more vertices. */ segments: number; } /** Procedural wind. Gusts are scrolling noise along `direction` plus a travelling ripple. */ interface WindOptions { /** World-space XZ direction the wind blows towards. Normalised internally. */ direction: [x: number, z: number]; /** How far blades bend. 0 = still, ~0.35 = breeze, 1+ = storm. */ strength: number; /** Noise frequency in 1/metres. Smaller = broader gusts. */ scale: number; /** How fast gusts travel across the field. */ speed: number; } /** Something that pushes grass aside: characters, vehicles, balls… */ interface Interactor { /** The object (or a React ref to it). Its world position is read every frame. */ object: Object3D | { /** The referenced object; `null` until mounted. */ current: Object3D | null; }; /** Influence radius in metres. Blades inside are bent away from the object. */ radius: number; } /** Every setting of a {@link Grass} field. All are optional on input; see {@link GrassInput}. */ interface GrassSettings extends GrassStyle { /** Starting look; any {@link GrassStyle} field you pass overrides the preset's value. */ preset: PresetName; /** Detailed geometric blades, or lightweight view-facing billboard tufts. */ type: 'blades' | 'billboards'; /** Edge length of a streaming tile in metres. Tiles are re-centred around the camera. */ tileSize: number; /** Radius (metres) around the camera that has grass. Blades fade out over the last 15%. */ maxDistance: number; /** Exactly four levels of detail, ordered near → far. */ lods: GrassLOD[]; /** Procedural wind; see {@link WindOptions}. */ wind: WindOptions; /** Steepest terrain gradient (rise / run) that still grows grass. `Infinity` disables the check. */ maxSlope: number; /** Coverage/height control texture; see {@link GrassMap}. `null` = grass everywhere. */ grassMap: GrassMap | null; /** Up to 16 objects that push grass aside. */ interactors: Interactor[]; /** Global multiplier on how strongly interactors bend grass. */ interactionStrength: number; /** Whether grass within `shadowDistance` casts shadows (needs a shadow-casting light). */ castShadow: boolean; /** Radius (metres) around the camera in which grass casts shadows. Shadows are costly: keep it small. */ shadowDistance: number; /** Whether grass receives shadows. */ receiveShadow: boolean; /** Light used for back-lit translucency. `null` = first DirectionalLight found in the scene. */ sun: DirectionalLight | null; /** Tints grass by LOD (red, yellow, green, blue) to help tune `lods`. */ debugLods: boolean; /** Milliseconds per frame spent (re)building tiles, nearest first. Spreads work to avoid frame spikes. */ buildBudget: number; } /** Partial settings accepted by {@link Grass.create}, {@link Grass.set} and the `` component. */ type GrassInput = Partial> & { /** Wind settings to change; unspecified fields keep their current value. */ wind?: Partial; }; /** Minimal renderer shape Grass needs. Pass a `WebGPURenderer` from `three/webgpu`. */ interface GrassRenderer { /** `true` on `WebGPURenderer`; anything else is rejected. */ isWebGPURenderer?: boolean; /** Whether `init()` has completed. */ hasInitialized?: () => boolean; /** Initialises the backend (WebGPU, or WebGL2 fallback). */ init?: () => Promise; } /** Live counters of a {@link Grass} field. */ interface GrassStats { /** Tiles currently streamed in around the camera. */ tiles: number; /** Blade (or billboard) instances currently allocated across all tiles. */ instances: number; } /** Options for {@link Grass.create}. */ interface GrassOptions extends GrassInput { /** The camera the field is centred on and whose distance drives LOD. */ camera: Camera; /** If given, grass is added to it and updates itself every frame via `scene.onBeforeRender`. */ scene?: Object3D; /** Must be a WebGPURenderer (`three/webgpu`); it falls back to WebGL2 by itself. Initialised if needed. */ renderer?: GrassRenderer; /** Mesh/group to grow on (baked once into a heightfield), a `(x, z) => y` function, or omit for flat ground. */ terrain?: Terrain; } /** * An infinite, camera-centred grass field. * * The world is divided into square tiles that stream in and out around the camera; each tile holds * instanced blades placed on the terrain, thinned by distance through four LODs. * * @example * ```ts * const grass = await Grass.create({ camera, scene, renderer, terrain, tileSize: 25, maxDistance: 200 }) * // That's it — it updates itself whenever `scene` is rendered. * ``` */ declare class Grass { /** Root of all grass tiles. Added to `scene` for you when one is passed to {@link Grass.create}. */ readonly object: Group; /** Shader uniforms, for advanced tweaks or for reading grass state in your own TSL materials. */ readonly uniforms: GrassUniforms; /** Live counters, refreshed on every {@link Grass.update}. */ readonly stats: GrassStats; /** Camera the field follows. Can be swapped at any time. */ camera: Camera; /** Resolved settings (defaults ← preset ← your input). Read-only: change them with {@link Grass.set}. */ settings: GrassSettings; /** Terrain height at world (x, z); NaN where there is no terrain. Handy for placing objects on the ground. */ sampleHeight: HeightFn; private input; private material; private baseGeometries; private tiles; private layoutKey; private layoutTileSize; private frame; private unhook; /** * Creates a grass field and builds every visible tile so the first frame is complete. * @throws If `renderer` is not a WebGPURenderer. */ static create(options: GrassOptions): Promise; /** Prefer {@link Grass.create}, which also validates/initialises the renderer and pre-builds tiles. */ constructor({ camera, scene, renderer: _renderer, terrain, ...input }: GrassOptions); /** * Changes settings at runtime, merging into what was set before. Visual settings (colours, height, * wind, …) apply instantly through uniforms; layout settings (type, density, tileSize, lods, clumping, * variation, maxSlope) rebuild tiles. `undefined` values are ignored; `wind` merges field by field. * To drop earlier overrides (e.g. go back to a preset's colours), use {@link Grass.reset}. */ set(input: GrassInput): this; /** * Replaces all settings with `input`: anything not given falls back to the preset, then to defaults. * Use it to switch presets cleanly after overriding style fields. `` uses it so props behave * declaratively (removing a prop reverts it). */ reset(input?: GrassInput): this; private apply; /** Swaps the terrain (mesh or height function) and regenerates all tiles. */ setTerrain(terrain?: Terrain): void; /** * Re-centres the tiles on the camera, streams tiles in/out and refreshes interactors and the sun. * Called automatically when a `scene` was given (and by the `` component); otherwise call it once per frame. * @param budget Milliseconds allowed for tile (re)builds this frame. Defaults to `settings.buildBudget`. */ update(budget?: number): void; /** Removes the grass from the scene and frees its GPU resources. */ dispose(): void; /** Fraction (0..1) of full blade density at a distance from the camera — the CPU mirror of the shader's LOD curve. */ densityAt(dist: number): number; /** Tiles are split into ~5 m cells, each holding only as many blades as its own distance needs. * Without this, the tiles around the camera would carry full density across their whole area. */ private get cellsPerSide(); /** Full-density blade candidates per cell. */ private get cellFull(); private needScratch; /** Blade candidates each cell of a tile needs for the current camera position. */ private cellNeeds; private segmentsAt; private createTile; private buildTile; private createCell; /** Continues a cell's blade stream until `upTo` candidates have been drawn. */ private generate; private applyTileSettings; private baseGeometry; /** * TSL nodes reading the grass map at a world XZ position. Use them in your terrain material to show * dirt where grass was erased; they follow map edits and `grassMap` swaps live. * * @example * ```ts * const { coverage } = grass.mapNode(positionWorld.xz) * terrainMaterial.colorNode = mix(dirtColor, grassyGround, coverage) * ``` */ mapNode(worldXZ: Node<'vec2'>): GrassMapSample; private sunSearched; private autoSun; private updateSun; private updateInteractors; private clearTiles; private removeTile; /** * Replaced tile geometries are freed a while later rather than immediately: WebGPU builds render * pipelines asynchronously, and one still in flight may read the old geometry. Freeing it at once * (which detaches the shared blade attributes) made that pipeline fail and the tile blink out. */ private retired; private retire; private flushRetired; } /** * The base blade shape: a tapered, folded strip with x in [-0.5, 0.5] and y in [0, 1]. Each of the * `segments` rows has three vertices (left edge, midrib, right edge) so the shader can fold the * blade along its midrib; a single vertex forms the tip. Exposed for custom instancing setups; * Grass creates these for you. */ declare function createBladeGeometry(segments: number): BufferGeometry; /** The base billboard shape: a unit quad strip with `segments` rows so it bends smoothly in the wind. */ declare function createBillboardGeometry(segments: number): BufferGeometry; export { type Brush, type BrushMode, Grass, type GrassInput, type GrassLOD, GrassMap, type GrassMapOptions, type GrassMapSample, type GrassOptions, type GrassRenderer, type GrassSettings, type GrassStats, type GrassStyle, type GrassUniforms, type Interactor, MAX_INTERACTORS, type PresetName, TerrainPainter, type WindOptions, createBillboardGeometry, createBladeGeometry, createGrassUniforms, presets };