Skip to content

About

2.5D layered intrinsic geometry, discrete phase-field weathering, palette-preserving relighting, and surface-colliding particles for 2D pixel art.

Topics

Resources

Stars

43 stars

Watchers

1 watching

Forks

Repository files navigation

@xprite/phase

npm License: MIT

English | 简体中文

2.5D layered intrinsic geometry, discrete phase-field weathering, palette-preserving relighting, and surface-colliding particles for 2D pixel art. Runs in browsers and Node, with an optional WebGL2 renderer and Godot 4 shaders. Built on @xprite/lighter for the Xprite pixel editor.

Live demo & write-up: Procedural Weather for Pixel Art | Open Xprite Editor | All Xprite projects

Winter Snow Night Rain Ember Dissolve
Winter Snow progression Night Rain progression Ember Dissolve progression

Scene art: Tiny Swords by Pixel Frog (CC0).

  • Discrete pixel-art evolution: crisp step-by-step accumulation (snow, autumn leaves, sand, rain, ash, moss, petrification, ember dissolve) without blurry alpha fades.
  • Oklab palette conservation: chromatic adaptation and 2.5D normal-lit tone quantization keep palette cardinality clean.
  • Scale-invariant 2.5D object deposition: continuous geometric, Oklab photometric, cluster-RAG, and structural-seam fields with zero asset-specific templates or color guessing.
  • Cross-layer 2.5D coupling: automatic wind/canopy shelter raymarching, contact ambient occlusion, directional incident occlusion, and joint inner/outer shoreline Exact EDT without hand-drawn masks.
  • Game-engine export: compact RGBA8 phaseMapTexture per layer for WebGL2 and Godot 4 canvas shaders.

Install

npm install @xprite/phase

Quick Start

Images are { width, height, data: Uint8ClampedArray }, straight-alpha RGBA.

Multi-layer scene

import {
  createScenePhaseBaker,
  evaluateSceneFrame,
  LayerRole,
  PhasePresetId,
} from "@xprite/phase";

// 1. Reconstruct 2.5D layer G-buffers once
const baker = createScenePhaseBaker([
  { id: "ground", role: LayerRole.Ground, zIndex: 0, pixels: groundRgba },
  { id: "water", role: LayerRole.Water, zIndex: 1, pixels: waterRgba },
  { id: "path", role: LayerRole.Path, zIndex: 2, pixels: bridgeRgba },
  { id: "shrine", role: LayerRole.WaterProp, zIndex: 3, pixels: shrineRgba },
  { id: "houses", role: LayerRole.Prop, zIndex: 4, grounded: true, pixels: housesRgba },
  { id: "canopy", role: LayerRole.Canopy, zIndex: 5, pixels: canopyRgba },
]);

// 2. Bake phase-field maps (cached geometry is reused across preset/wind changes)
const baked = baker.bake({
  preset: PhasePresetId.WinterSnow,
  windAngle: 135,
  windStrength: 0.35,
  layeredCoupling: true,
  morphology: true,
  adaptiveRamp: true,
});

// 3. Evaluate any progress/stage and animation timestamp
const frame = evaluateSceneFrame(baked, {
  stage: 3.12,
  frontProgress: 0.78,
  time: 4.5,
  particles: true,
  preservePalette: true,
});

Single sprite or flat image

Pass a single PixelBuffer directly to bakeScenePhase or createScenePhaseBaker. Background-only borders are isolated automatically without hue guessing, and disconnected sprites are analyzed independently.

import { bakeScenePhase, evaluateSceneFrame, PhasePresetId } from "@xprite/phase";

const baked = bakeScenePhase(spriteRgba, {
  preset: PhasePresetId.WinterSnow,
  windAngle: 135,
});
const frame = evaluateSceneFrame(baked, { stage: 3, frontProgress: 0.78, time: 0 });

WebGL2 renderer

For real-time 60 fps playback in browsers, use the @xprite/phase/webgl entry point:

import { createPhaseWebGLRenderer } from "@xprite/phase/webgl";

const renderer = createPhaseWebGLRenderer(canvas);
renderer.uploadBake(baked);
renderer.render({ stage: 3.12, frontProgress: 0.78, time: 4.5, particles: true });

Godot 4 shaders

Prebuilt canvas shaders that consume the baked RGBA8 phaseMapTexture ship in shaders/godot/:

  • phase_surface.gdshader: surface accumulation, seasonal color grading, lifted outlines, extruded caps, and overhang filaments.
  • phase_water.gdshader: shoreline SDF freeze/recession front, rim highlight, and branching fracture filaments.

Presets

All 8 presets run on the same shared 2.5D geometry base and unified RGBA8 phaseMapTexture:

Winter Snow Autumn Leaves Desert Sand Night Rain
Winter Snow Autumn Leaves Desert Sand Night Rain
Volcanic Ash Forest Moss Stone Petrify Ember Dissolve
Volcanic Ash Forest Moss Stone Petrify Ember Dissolve
Preset Category Surface behavior
PhasePresetId.WinterSnow Weather 2.5D gravity blankets, windward clinging, shoreline ice & cracks, colliding snowflakes
PhasePresetId.AutumnLeaves Weather Full-crown botanical senescence, wind-drifted ground/water litter, drifting leaves
PhasePresetId.DesertSand Weather Aeolian windward sand drifts, receding dry water shoreline, blowing dust
PhasePresetId.NightRain Weather Porous wet film darkening, upward Fresnel wet sheen, rain ripples & splashing drops
PhasePresetId.VolcanicAsh Transformation Tephra caldera deposition, magma crust veins over water, rising embers
PhasePresetId.ForestMoss Transformation Cavity-driven epiphytic moss, bryophyte ground carpet, shoreline mat, fireflies
PhasePresetId.StonePetrify Transformation Synchronized geodesic wavefront petrification across terrain, objects, and water
PhasePresetId.EmberDissolve Transformation Synchronized pyrolysis wavefront with optional final-stage erosion

Options Reference

SceneLayerInput

Field Description
id Unique layer identifier.
role Backdrop, Ground, Water, Path, WaterProp, Prop, Canopy, or Auto (default).
zIndex Explicit stacking order (arbitrary numbers supported).
visible Skip layer when false.
grounded Mark a Prop layer as resting on terrain for subtle ground-contact basal transitions.
phaseMask Optional per-pixel PhaseMaskHint (Exclude, Include, Catch) override.
paintedLightAngle / paintedLightInfluence Optional per-layer painted-light ground truth override.

PhaseBakeOptions

Option Description
preset Preset ID (PhasePresetId) or custom PhasePresetConfig.
windAngle Incoming wind direction in degrees (default 135).
windStrength Wind strength in [0, 1]. 0 guarantees strict angle invariance.
projection SceneProjection.Auto (default), TopDown, or SideView.
layeredCoupling Enable cross-layer shelter, contact AO, inner shorelines, and incident occlusion (default true).
morphology Enable exterior outline lift, extruded caps, overhang filaments, and surface tufts (default true).
adaptiveRamp Adapt overlay ramp lightness/chroma to the scene's Oklab palette (default false).
surface Fine-tune roofSlopeDepth, gableArchSlope, tierSensitivity, celBandContrast, sideCling, cliffDrape, microReliefWeight, roadClearance.

Architecture

[SceneLayerInput[] or Single PixelBuffer]
        │
        ▼
1. Intrinsic 2.5D Layer G-Buffer (src/intrinsic/, powered by @xprite/lighter)
   ├── Perceptual 4-connected clusters, Oklab buffers, & thin dark outline mask
   ├── O(N) Meijster Exact Euclidean Distance Transform (silhouette SDF)
   ├── Dual 2.5D normals (faceted + continuous) & height field
   ├── Curvature, cavity occlusion, painted-light signal, & collision ledges
   └── Scale-adaptive cap depth
        │
        ▼
2. Cross-Layer 2.5D Spatial Coupling (src/coupling/)
   ├── Ground-plane projected wind/canopy shelter & vertical contact AO
   ├── Projection-aware O(L * W * H) directional incident occlusion
   └── Joint inner & outer shoreline Exact EDT (Water + WaterProps + elevated Paths)
        │
        ▼
3. Unified Phase-Field Solver & Morphology (src/phase/)
   ├── Shared operators (src/phase/shared/): affinity, wavefront, fracture filaments, exterior morphology
   ├── Terrain pipeline (src/phase/terrain/): ground/path intrinsics, ground operators, water phase
   └── 2.5D Object pipeline (src/phase/object/{topology,surface,deposition,operators}/):
       Cluster RAG, continuous 2.5D surface fields, geodesic sky/wind transport, & polymorphic operators
        │
        ▼
4. Frame Evaluation, GPU Renderer & Particles (src/palette/, src/evaluate/, src/gpu/, src/dynamics/)
   ├── Oklab palette-preserving LUT & modular CPU compositor
   ├── WebGL2 renderer (@xprite/phase/webgl) & Godot 4 shaders (shaders/godot/)
   └── Stateless analytical 2.5D particles colliding with 2.5D ledges

Demo & Benchmark

  • pnpm run build && pnpm run demo: serves the interactive browser demo at http://localhost:8735/demo/ with a procedural 6-layer scene and drag-and-drop PNG/WebP upload.
  • pnpm run bench: benchmarks 2.5D initialization, interactive rebake, and CPU frame evaluation on a 6-layer 352×256 scene (540,672 pixels). Typical results on Apple Silicon (Node 24): init25D ≈ 270 ms, interactiveBake ≈ 85–100 ms, evaluateFrame ≈ 14 ms.
  • pnpm test: runs the 67-case unit and counterfactual test suite (scale invariance, palette conservation, cross-layer occlusion, calm wind invariance, and bounded surface deposition).

Xprite Ecosystem

Project Description Links
Xprite Browser-based pixel art & animation editor Open Editor
@xprite/pixelate Recover pixel grids from AI/upscaled art and pixelate images npm, Demo & Write-up (Pixelation)
@xprite/lighter Generate normal maps, light masks, and relighted renders for pixel art npm, Demo & Write-up
@xprite/phase (this repo) 2.5D layered geometry, phase-field weathering, and particles for pixel art npm, Demo & Write-up

License

MIT. See LICENSE.

About

2.5D layered intrinsic geometry, discrete phase-field weathering, palette-preserving relighting, and surface-colliding particles for 2D pixel art.

Topics

Resources

Stars

43 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages