lightbake

package
v0.4.0-rc.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 22 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package lightbake is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package lightbake is an offline, pure-Go 3D lightmap and light probe baker invoked by `game bake lightmaps <scene.yaml>`.

It unwraps non-overlapping UV2 charts for static meshes lacking TEXCOORD_1, packs charts into lightmap atlases with texel padding, path-traces direct lighting from `bake: static` lights plus multi-bounce indirect lighting, sky light, emissive surfaces, ambient occlusion, and optional directional (L1 SH) lightmaps over a static BVH, applies edge-stopping denoising and texel dilation, bakes a LightProbeGrid for dynamic objects, and emits a versioned YAML sidecar (*.lightmaps.yaml) alongside RGBM PNG or Radiance .hdr atlases and optional glTF-style .bin UV2 buffers.

Game runtimes never import this package; runtime scenes load the baked outputs directly through pkg/render3d and pkg/scenemodel.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func BakeLightProbeGrid

func BakeLightProbeGrid(bvh *BVH, scene *Scene, bounds math3d.AABB, counts [3]int, opts Options) (*render3d.LightProbeGrid, error)

BakeLightProbeGrid path-traces an L2 spherical-harmonic render3d.LightProbeGrid covering bounds with lattice counts [nx, ny, nz] over scene's static geometry, static lights, emissive surfaces, and sky, using deterministic per-probe RNG seeds.

Types

type AtlasData

type AtlasData struct {
	Width  int
	Height int
	// Irradiance stores linear diffuse irradiance / pi (matching render3d.PBRLightmapWGSL) in row-major order.
	Irradiance []math3d.Vec3
	// Direction stores normalized dominant incoming light direction (XYZ in [-1, 1]) when Directional is enabled.
	Direction []math3d.Vec3
	// Directionality stores directional coherence in [0, 1] when Directional is enabled.
	Directionality []float32
	// Valid marks texels covered by static geometry (before dilation).
	Valid []bool
}

AtlasData holds the baked floating-point irradiance and optional L1 SH direction buffers for one atlas.

type AtlasFormat

type AtlasFormat string

AtlasFormat selects the image format written for baked lightmap atlases.

const (
	// AtlasRGBM encodes HDR irradiance into standard 8-bit PNG files using render3d.LightmapRGBM.
	AtlasRGBM AtlasFormat = "rgbm"
	// AtlasHDR encodes linear HDR irradiance into Radiance RGBE (.hdr) files.
	AtlasHDR AtlasFormat = "hdr"
)

type BVH

type BVH struct {
	// contains filtered or unexported fields
}

BVH is a flat binned-SAH bounding volume hierarchy over static world-space triangles.

func (*BVH) Intersect

func (b *BVH) Intersect(ray Ray, tMin, tMax float32) (Hit, bool)

Intersect finds the closest intersection of ray within [tMin, tMax].

func (*BVH) Occluded

func (b *BVH) Occluded(ray Ray, tMin, tMax float32) bool

Occluded reports whether any triangle blocks ray within [tMin, tMax].

type BakeResult

type BakeResult struct {
	// SidecarPath is the slash-separated project path of the written *.lightmaps.yaml sidecar.
	SidecarPath string
	// Sidecar is the validated sidecar document.
	Sidecar *render3d.LightmapSidecarDoc
	// ProbeGrid is the baked light probe grid for dynamic objects, or nil if none was baked.
	ProbeGrid *render3d.LightProbeGrid
	// Files maps every output project-relative slash path (sidecar YAML, atlas PNG/HDR, optional directional PNG, optional UV2 .bin, optional .probes.yaml) to its deterministic byte contents.
	Files map[string][]byte
	// Stats reports counts of baked atlases, objects, triangles, texels, and probes.
	Stats Stats
}

BakeResult holds the encoded files and metadata produced by BakeScene.

func BakeScene

func BakeScene(doc *sceneformat.SceneDoc, resolver scenemodel.ModelResolver, scenePath string, opts Options) (*BakeResult, error)

BakeScene builds doc using resolver, bakes lightmaps for every static object (`lightmap.static: true`) lit by every `bake: static` light plus sky and emissive surfaces, optionally bakes a LightProbeGrid for dynamic objects, and returns the encoded sidecar YAML, atlas images, optional UV2 .bin buffer, and optional probe grid YAML ready to write beside scenePath.

Pass a resolved *sceneformat.SceneDoc (via sceneformat.Resolve) when doc inherits or instances other scenes.

func (*BakeResult) WriteToRoot

func (r *BakeResult) WriteToRoot(root *os.Root) error

WriteToRoot atomically writes every file in r.Files inside root in sorted path order.

type BakedObject

type BakedObject struct {
	Object       string
	Part         int
	AtlasIndex   int
	Scale        [2]float32
	Offset       [2]float32
	GeneratedUV2 []math3d.Vec2
	PerCorner    bool
	UsedTexCoord bool
	Charts       []UV2Chart
}

BakedObject records the UV2 source and atlas placement produced for one StaticMesh.

type ChartRect

type ChartRect struct {
	X, Y, W, H int
}

ChartRect is the packed integer pixel rectangle of one UV2 chart in an atlas or object UV2 grid.

type DenoiseMode

type DenoiseMode string

DenoiseMode selects the post-trace noise filter applied before texel dilation.

const (
	// DenoiseATrous applies an edge-stopping à-trous wavelet filter guided by chart ID, normal, and world position.
	DenoiseATrous DenoiseMode = "atrous"
	// DenoiseBilateral applies a single-scale edge-stopping bilateral filter guided by chart ID, normal, and world position.
	DenoiseBilateral DenoiseMode = "bilateral"
	// DenoiseNone skips denoising and writes raw path-traced irradiance.
	DenoiseNone DenoiseMode = "none"
)

type Hit

type Hit struct {
	T          float32
	TriIdx     int
	U, V       float32 // barycentric coordinates (w = 1 - u - v)
	Pos        math3d.Vec3
	Normal     math3d.Vec3 // shading normal, oriented against incoming ray for double-sided hits
	FaceNormal math3d.Vec3
	UV0        math3d.Vec2
	MatIdx     int
}

Hit describes the closest intersection of a Ray with static scene geometry.

type LightKind

type LightKind uint8

LightKind selects the kind of static analytical light baked into lightmaps.

const (
	LightDirectional LightKind = iota
	LightPoint
	LightSpot
)

type LowLevelBakeResult

type LowLevelBakeResult struct {
	Atlases []AtlasData
	Objects []BakedObject
	BVH     *BVH
	Stats   Stats
}

LowLevelBakeResult is returned by Bake before encoding into sidecar/atlas files.

func Bake

func Bake(scene *Scene, opts Options) (*LowLevelBakeResult, error)

Bake unwraps missing UV2s, packs all static meshes into lightmap atlas(es), builds a BVH over static geometry, and runs the deterministic multithreaded CPU path tracer, denoiser, and dilation.

Example
package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/math3d"
	"github.com/nsgo-dev/game/pkg/render3d"
	"github.com/nsgo-dev/game/pkg/render3d/lightbake"
)

func main() {
	floor := render3d.Mesh{
		Positions: []math3d.Vec3{
			{X: -1, Y: 0, Z: 1},
			{X: 1, Y: 0, Z: 1},
			{X: 1, Y: 0, Z: -1},
			{X: -1, Y: 0, Z: -1},
		},
		Normals: []math3d.Vec3{
			{Y: 1}, {Y: 1}, {Y: 1}, {Y: 1},
		},
		UVs: []math3d.Vec2{
			{X: 0, Y: 0}, {X: 1, Y: 0}, {X: 1, Y: 1}, {X: 0, Y: 1},
		},
		Indices: []uint32{0, 1, 2, 0, 2, 3},
	}

	scene := &lightbake.Scene{
		Meshes: []lightbake.StaticMesh{{
			Object:   "floor",
			Mesh:     floor,
			World:    math3d.Mat4Identity(),
			Material: lightbake.Material{BaseColor: math3d.Vec3{X: 0.8, Y: 0.8, Z: 0.8}, Roughness: 1},
		}},
		Lights: []lightbake.StaticLight{{
			Kind:      lightbake.LightDirectional,
			Direction: math3d.Vec3{X: 0, Y: -1, Z: 0},
			Color:     math3d.Vec3One(),
			Intensity: 3,
		}},
	}

	opts := lightbake.DefaultOptions()
	opts.Resolution = 32
	opts.Samples = 8
	opts.Bounces = 1
	opts.Denoise = lightbake.DenoiseNone

	res, err := lightbake.Bake(scene, opts)
	if err != nil {
		panic(err)
	}
	fmt.Printf("atlases=%d objects=%d\n", len(res.Atlases), len(res.Objects))
}
Output:
atlases=1 objects=1

type Material

type Material struct {
	// BaseColor is the linear RGB base color multiplier.
	BaseColor math3d.Vec3
	// Metallic is the surface metalness in [0, 1]; diffuse albedo is (1 - Metallic) * BaseColor.
	Metallic float32
	// Roughness is the perceptual roughness in [0, 1].
	Roughness float32
	// Emissive is the linear RGB emitted radiance of the surface.
	Emissive math3d.Vec3
	// BaseColorTexture is an optional sRGB albedo image sampled at UV0.
	BaseColorTexture image.Image
	// DoubleSided allows rays to intersect both sides of triangles with this material.
	DoubleSided bool
}

Material describes the surface reflectance and emission of a static mesh during baking.

type ObjectAtlasPlacement

type ObjectAtlasPlacement struct {
	AtlasIndex int
	Rect       ChartRect
	Scale      [2]float32
	Offset     [2]float32
}

ObjectAtlasPlacement records where one object's UV2 block landed inside a shared lightmap atlas.

type Options

type Options struct {
	// Resolution is the width and height in texels of each baked lightmap atlas (default 512).
	Resolution int
	// TexelsPerUnit sets the baseline lightmap texel density per world unit, multiplied by each object's texelScale (default 8).
	TexelsPerUnit float32
	// Padding is the minimum empty texel gutter preserved between UV2 charts and atlas borders (default 2).
	Padding int
	// Samples is the number of Monte Carlo path-tracing samples per covered texel (default 64).
	Samples int
	// Bounces is the number of indirect light bounces (N >= 1; default 2). Set DirectOnly to skip indirect bounces.
	Bounces int
	// DirectOnly skips indirect bounces when true, baking direct static light only.
	DirectOnly bool
	// AORadius is the ray distance for optional extra ambient occlusion darkening; 0 disables extra AO modulation.
	AORadius float32
	// AOStrength blends extra ambient occlusion into indirect lighting in [0, 1].
	AOStrength float32
	// AOSamples is the number of hemisphere AO rays per texel when AORadius > 0 and AOStrength > 0 (default 16).
	AOSamples int
	// Directional bakes companion L1 SH dominant-direction PNG atlases alongside irradiance atlases.
	Directional bool
	// Format selects AtlasRGBM (default, .png) or AtlasHDR (.hdr).
	Format AtlasFormat
	// RGBMMaxRange sets the HDR peak scale for AtlasRGBM (default render3d.DefaultRGBMMaxRange = 8).
	RGBMMaxRange float32
	// Denoise selects DenoiseATrous (default), DenoiseBilateral, or DenoiseNone.
	Denoise DenoiseMode
	// DenoiseIterations sets the number of à-trous wavelet passes (default 3).
	DenoiseIterations int
	// Dilation sets the number of 8-neighbor texel dilation passes across chart seams (default 4).
	Dilation int
	// Seed is the deterministic per-texel RNG seed (default 1).
	Seed uint64
	// Workers sets the parallel worker goroutine count; <= 0 uses runtime.GOMAXPROCS(0).
	Workers int
	// ForceUnwrap regenerates UV2 charts even for meshes that already carry TEXCOORD_1.
	ForceUnwrap bool
	// GenerateProbeGrid bakes a LightProbeGrid covering static scene bounds for dynamic objects when true (default true in DefaultOptions).
	GenerateProbeGrid bool
	// ProbeCounts sets the [nx, ny, nz] lattice dimensions of an auto-generated LightProbeGrid (default [4, 2, 4]).
	ProbeCounts [3]int
	// ProbeSamples sets the number of rays integrated per light probe (default 128).
	ProbeSamples int
	// SidecarPath overrides the default output path (<scene>.lightmaps.yaml) for BakeScene.
	SidecarPath string
}

Options configures lightmap UV2 unwrapping, path tracing, post-processing, and light probe baking.

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns balanced defaults for baking a scene's lightmaps and probes.

type Ray

type Ray struct {
	Origin math3d.Vec3
	Dir    math3d.Vec3
}

Ray is a world-space ray used by the lightmap path tracer.

type Scene

type Scene struct {
	Meshes []StaticMesh
	Lights []StaticLight
	Sky    Sky
}

Scene holds the static geometry, static lights, and sky baked by Bake.

type Sky

type Sky struct {
	// Enabled activates sky evaluation on escaped rays.
	Enabled bool
	// SolidColor is used when Gradient is false and Cubemap is nil.
	SolidColor math3d.Vec3
	// Gradient blends Zenith, Horizon, and Ground by direction Y.
	Gradient bool
	Zenith   math3d.Vec3
	Horizon  math3d.Vec3
	Ground   math3d.Vec3
	// Cubemap samples a linear HDR sky cubemap when non-nil.
	Cubemap *render3d.HDRCubemap
	// Intensity scales sky radiance (0 defaults to 1 when Enabled is true).
	Intensity float32
	// Ambient is a uniform fallback ambient irradiance (linear RGB) added when no sky is active or scaled alongside sky.
	Ambient math3d.Vec3
}

Sky evaluates directional background sky radiance for rays that escape static scene geometry.

type StaticLight

type StaticLight struct {
	Kind           LightKind
	Position       math3d.Vec3
	Direction      math3d.Vec3 // direction light travels (normalized)
	Color          math3d.Vec3 // linear RGB
	Intensity      float32
	Range          float32 // 0 = unbounded inverse square
	InnerConeAngle float32 // radians (spot only)
	OuterConeAngle float32 // radians (spot only)
}

StaticLight is a light marked `bake: static` evaluated during lightmap and probe baking.

type StaticMesh

type StaticMesh struct {
	Object     string
	Part       int
	Mesh       render3d.Mesh
	World      math3d.Mat4
	Material   Material
	TexelScale float32
	// HasUV2 indicates Mesh.UV2s already holds authored non-overlapping UV2 coordinates (e.g. glTF TEXCOORD_1).
	HasUV2 bool
}

StaticMesh is one static object part participating in lightmap baking.

type Stats

type Stats struct {
	Atlases         int
	Objects         int
	StaticTriangles int
	CoveredTexels   int
	Probes          int
}

Stats summarizes the work performed by one lightmap bake.

type UV2Chart

type UV2Chart struct {
	// Triangles holds the 0-based triangle indices belonging to this chart.
	Triangles []int
	// Rect is the packed pixel rectangle inside the object's unwrapped UV2 grid (Width x Height).
	Rect ChartRect
	// Normal is the area-weighted average world-space normal of the chart.
	Normal math3d.Vec3
}

UV2Chart describes one planar-projected, non-overlapping chart produced by UnwrapMesh.

type UnwrapResult

type UnwrapResult struct {
	// UV2 holds the normalized [0, 1] UV2 coordinates. When PerCorner is false, len(UV2) == len(mesh.Positions);
	// when PerCorner is true (chart seams split shared indexed vertices), len(UV2) == triCount*3.
	UV2 []math3d.Vec2
	// PerCorner reports whether UV2 is stored per triangle corner rather than per original mesh vertex.
	PerCorner bool
	// Charts lists every non-overlapping chart with its packed pixel rectangle.
	Charts []UV2Chart
	// Width and Height are the pixel dimensions of the object's packed UV2 grid.
	Width, Height int
}

UnwrapResult holds the generated UV2 coordinates and packed chart layout for one mesh.

func UnwrapMesh

func UnwrapMesh(m render3d.Mesh, world math3d.Mat4, texelsPerUnit float32, padding int, maxSize int) (UnwrapResult, error)

UnwrapMesh segments m into non-overlapping planar-projected UV2 charts (in world scale using world) and packs them deterministically with at least padding empty texels between every pair of charts and around the grid borders, fitting within maxSize x maxSize texels.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL