Help us shape the future of Go! Take the 2026 Go Developer Survey

world

package
v0.0.14 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: MIT Imports: 7 Imported by: 0

README

Compiled world contract

world defines the bounded sector document shared by public level compilers and Karty hosts. It owns typed binary encoding and complete document validation. World source owns room, prefab, port and material authoring semantics; public compilers parse and expand that source into this contract. The SDK does not implement runtime rendering or collision.

Versions and encoding

Compiled version Added semantics
1 Convex sectors, coincident reciprocal portals and contents
2 Typed actors, sprites and tags
3 Directed/transformed portal pairs and optional versioned payloads

Versions 1–3 remain supported. Compiled versions, source versions, Go module tags and downloadable SDK/host versions are separate identifiers. A producer must also declare world/sectors@1 and each feature it uses in the cartridge manifest; consumers check these declarations against host support. Validate has no manifest or packaged assets to inspect.

The level resource is @world/main. Encode validates first and emits canonical typed binary. Decode rejects empty or oversized input, unsupported versions, JSON, malformed records and trailing bytes. An allocation-free scan of the complete record bounds typed allocations before decoding; semantic validation then checks the complete document before it can be mounted.

KWR1 is the base binary envelope. Solid-renderer or explicit environment-backdrop extensions select KWR2, retaining the base fields and appending a bounded trailer. Omitting both extensions preserves the base encoding; omitting a backdrop preserves existing solid-only trailer bytes. Exact field order belongs to the generated codec and its handwritten envelope. Regenerate codecs from the owning declarations rather than editing generated output.

Geometry, identity and contents

Bound Limit
Encoded document 8 MiB
Sectors 1–256
Walls 8,192 total; 3–256 per sector
Contents 4,096
Identifier and kind 128 UTF-8 bytes each
Coordinates and plane coefficients Finite, absolute value at most 1,000,000
Edge length and vertical clearance At least 0.000001

Sector order is stable because portals reference sector indexes. Each sector is strictly convex and counterclockwise, with a closed sequence of directed walls. Floor and ceiling planes evaluate z = A*x + B*y + C; every vertex must have positive clearance. Sector IDs and content IDs are unique within their respective lists. SourceRoom, SourceEdge, SourceID and Instance retain provenance after expansion; compiler-generated internal walls may omit SourceEdge.

An opaque wall has Portal = -1 and PortalWall = 0. In v1/v2, a portal requires one coincident reversed edge pointing back from a different sector, with clearance and no crossing floor/ceiling profiles. In v3, Portal is a destination sector index and PortalWall is one plus its destination wall index. The paired edges must have equal lengths; their positions define a rigid destination-to-source transform. Directed and self-sector connections are possible in v3.

Every content position lies within its assigned sector's footprint and elevation bounds. From v2, an optional actor supplies finite yaw/pitch/roll, positive XYZ scale and at most eight strictly sorted, unique UTF-8 tags of at most 64 bytes. An optional sprite references a nonzero asset ID, positive width/height, origins in [0,1], a facing mode (camera-facing, upright, cross, fixed) and an alpha mode (cutout, blend). Compilers and hosts resolve texture/material IDs against packaged assets separately.

See types and validation for the field definitions and precise validation rules.

Lighting, version 1

Optional Lighting requires compiled v3 and world/lighting@1. Ambient, point colors and the optional six-face world-space ambient cube are finite linear RGB values in [0,1]. The cube replaces uniform ambient when supplied. Lights retain authored order and global coordinates. Their IDs are unique and their influence radii range from 0.001 to 1,000,000 world units.

MaxLights = 4096 bounds the complete authored light set, including offline-baked sources. MaxRuntimeLights = 50 separately bounds live direct lights; producers must check the remaining runtime set when packaging a world. An unbaked preview uses that live limit. Optional version-1 light motion moves between Position and Position + Offset and back in 0.1–3,600 seconds; both endpoints remain within coordinate bounds. Moving lights remain runtime sources.

See lighting, emission and the lightmap contract for their separate responsibilities.

Environment and sky openings, version 1

Optional Environment requires compiled v3 and world/environment@1. Its preset is daylight, space, cartoon or fantasy; its optional palette is default, violet or twilight. Palette changes affect appearance independently of illumination. Optional fixed sun angles use azimuth [0,360) from +X toward +Y and elevation [0,90] above the XY plane. Optional TimeOfDay supplies hours [0,24) and cannot coexist with an explicit sun. Optional cloud coverage is [0,1], with omission resolving to 0.35 and explicit zero remaining clear.

A sector's Sky opens its ceiling visually while retaining finite spatial bounds. A sky wall must be opaque and belong to a sky sector. Sky sectors require an environment. Preset resolution supplies bounded sky, sun and outdoor fill; consumers restrict sun/fill using openings and geometry. See environment validation and resolution.

An explicit backdrop (none, mountains, city) additionally declares world/environment-backdrop@1 and uses the KWR2 trailer after solid renderers (selector bytes 1, 2, 3). A backdrop-only document writes a nil solid-renderer sentinel first. The selector adds no geometry, collision or lighting.

Project-owned sky textures and presentation settings live in the separate world/sky@1 resource; they do not change this environment codec. See source v12 sky authoring for confined PNG paths and partial overrides.

Material mapping, version 1

Optional MaterialMapping requires compiled v3 and world/material-mapping@1. Every sector floor, ceiling and wall then supplies complete SurfaceUV data. Source mode, anchoring, inheritance and prefab transforms are resolved by the compiler; hosts infer none of them.

A surface contains one affine projection or three blended projections, with matching constant weights. Each U/V plane evaluates X*position.X + Y*position.Y + Z*position.Z + Offset in texture repeats. Coefficients are finite and bounded to ±1e12. Weights lie in [0,1] and sum to one within 1e-9. The same projections apply to every material channel. See mapping validation.

Static solids, version 1

Optional StaticSolids requires compiled v3 and world/static-solids@1. At most 1,024 uniquely identified solids are strictly convex counterclockwise extrusions, each with 3–64 footprint vertices and bounded bottom/top planes. Thickness and edge lengths retain the ordinary minimums. Side, top and bottom material IDs are nonzero. Optional mappings require MaterialMapping; SideUV is shared across all sides, rather than per edge.

Solids may overlap sectors or each other and do not alter the sector/portal graph. Collision blocks movement; it never makes the top a walkable floor. Solid validation checks every item before mounting.

Material layers, version 1

Optional MaterialLayers requires compiled v3, world/material-layers@1 and material mapping. Secondary color layers carry a material, strength [0,1] and complete UV projections. Wall bands compile into complete nonoverlapping WallFrameRegion partitions: vertices are counterclockwise in edge-fraction / world-elevation coordinates. Coverage is main, opaque or masked; main regions retain wall mapping, while other regions supply their own mapping.

There are at most 252 regions per wall and 32,768 total. FrameCompiled retains participation when a portal has no exposed solid spans. Frame partitions require a source edge identity. Source band inheritance and texture selection belong to authoring; see compiled layers and partition validation. MaterialIDs provides stable, deduplicated atlas order.

Reusable animations

Optional version-1 Animations requires compiled v3 and world/animations@1. It contains 1–64 uniquely named presets and at most 196 material bindings. Bindings select a preset and nonnegative phase in seconds, bounded to 86,400. Presets cannot recursively animate frame materials or use fields from another kind.

Kind Parameters and bounds
flipbook 2–64 nonzero texture IDs; FPS 0.001–120; optional repeat interval at least one complete frame sequence, at most 86,400 seconds
liquid UV flow components ±10; amplitude [0,1]; frequency (0,100]; speed ±100 radians/second; surface amplitude [0,0.25] metres; opacity [0,1] (default 1); pixel size 0–32 (default 0)
spin Unit axis within 1e-6; bounded actor-local pivot; nonzero speed ±100 radians/second
oscillate Nonzero bounded actor-local offset; period 0.001–86,400 seconds

A flipbook holds frame zero outside an optional repeat burst. Frames are complete textures, resolved and checked by compilers/hosts. Material bindings support flipbook/liquid; displaced liquid requires a horizontal up-facing floor or static solid top. Actor bindings require sprites, reject liquid, and require fixed facing for spin/oscillate. Actor-local motion is applied before scale/orientation. Lighting and collision retain rest geometry. See animation validation.

Material emission, version 1

Optional Emission requires compiled v3 and world/emission@1. At most 196 unique primary surface/band materials carry an eight-bit linear-albedo multiplier, decoded as code*8/255. Secondary modulation and animation-only frames are not emission owners. An optional cosine pulse has depth [0,1], period 0.001–86,400 seconds and phase 0–86,400 seconds. It begins at full brightness.

Optional linked light IDs must exist in Lighting and are unique across all emission records, with at most 50 links in total. Pulse and flipbook/liquid animation are independent effects. See emission validation.

Solid renderer extension

Optional version-1 SolidRenderers requires compiled v3 and world/solid-renderers@1. It retains 1–64 immutable local solid prefabs, at most 1,024 total solid definitions, 65,536 triangles and 4,096 unique actor attachments. It uses KWR2 without changing the base KWR1 fields.

Each attachment references an existing actor and prefab. Renderer actors cannot also carry sprites or actor animation bindings. Renderer solids reuse extrusion validation but reject collision; materials cannot select surface displacement or opacity below one. These definitions contribute material IDs separately from static world geometry. See renderer validation and source prefab authoring.

Separate resources

Render chunks, material atlases, baked lighting, particles and project sky have independent resource versions and bounds. Follow their owning contracts: worldchunk, worldmaterial, worldlightmap, worldparticles and worldsky.

Documentation

Overview

Code generated by internal/codegen/binary; DO NOT EDIT.

Package world defines the bounded compiled sector format shared by level compilers and Karty hosts. It contains data contracts and validation only.

Index

Constants

View Source
const (
	AnimationVersion      = uint32(1)
	FeatureAnimations     = cartridge.FeatureWorldAnimationsV1
	MaxAnimationPresets   = 64
	MaxMaterialAnimations = 196
	MaxAnimationFrames    = 64
	MaxAnimationSeconds   = 86400.0
)
View Source
const (
	FeatureEmission      = cartridge.FeatureWorldEmissionV1
	EmissionVersion      = uint32(1)
	MaxEmissionMaterials = 196
	MaxEmissionIntensity = 8.0
)
View Source
const (
	DefaultEnvironmentTimeOfDay   = 15.0
	DefaultEnvironmentCloudAmount = .35
)
View Source
const (
	MaterialMappingVersion = uint32(1)
	FeatureMaterialMapping = cartridge.FeatureWorldMaterialMappingV1
	MaxUVProjectionValue   = 1e12
	UVWeightTolerance      = 1e-9
)
View Source
const (
	MaterialLayersVersion = uint32(1)
	FeatureMaterialLayers = cartridge.FeatureWorldMaterialLayersV1
	FrameCoverageMain     = "main"
	FrameCoverageOpaque   = "opaque"
	FrameCoverageMasked   = "masked"
	// Each wall has <=7 profile intervals, <=2 solid spans, <=2 band-overlap
	// branches, <=3 vertical columns and <=3 horizontal rows. Every cell is a quad.
	MaxFrameRegionsPerWall = 7 * 2 * 2 * 3 * 3
	MaxFrameRegionVertices = 4
	MaxFrameRegions        = 32768
)
View Source
const (
	SolidRenderersVersion     = uint32(1)
	FeatureSolidRenderers     = "world/solid-renderers@1"
	MaxSolidPrefabs           = 64
	MaxSolidRendererTriangles = 65536
)
View Source
const (
	StaticSolidsVersion = uint32(1)
	FeatureStaticSolids = cartridge.FeatureWorldStaticSolidsV1
	MaxStaticSolids     = 1024
	MaxSolidVertices    = 64
)
View Source
const (
	LegacyVersion      = uint16(1)
	ActorVersion       = uint16(2)
	Version            = uint16(3)
	LightingVersion    = uint32(1)
	EntryName          = "@world/main"
	Feature            = cartridge.FeatureWorldSectorsV1
	FeatureLighting    = cartridge.FeatureWorldLightingV1
	EnvironmentVersion = uint32(1)
	FeatureEnvironment = cartridge.FeatureWorldEnvironmentV1
	MaxEncodedSize     = 8 * 1024 * 1024
	MaxSectors         = 256
	MaxWalls           = 8192
	MaxWallsPerSector  = 256
	MaxContents        = 4096
	// MaxLights bounds authored sources, including lights compiled into an
	// offline lightmap. It does not enlarge the runtime direct-light budget.
	MaxLights          = 4096
	MaxRuntimeLights   = 50
	MinLightRadius     = 0.001
	MaxIdentifierBytes = 128
	MaxKindBytes       = 128
	MaxTags            = 8
	MaxTagBytes        = 64
	MaxCoordinate      = 1_000_000.0
	MinEdgeLength      = 1e-6
	MinClearance       = 1e-6
)
View Source
const BinaryMagic = "KWR1"
View Source
const FeatureEnvironmentBackdrop = cartridge.FeatureWorldEnvironmentBackdropV1
View Source
const SolidBinaryMagic = "KWR2"

Variables

View Source
var (
	ErrSize            = errors.New("world payload size is invalid")
	ErrSyntax          = errors.New("world payload syntax is invalid")
	ErrVersion         = errors.New("world payload version is unsupported")
	ErrBounds          = errors.New("world payload exceeds a declared bound")
	ErrIdentity        = errors.New("world identity is invalid")
	ErrGeometry        = errors.New("world geometry is invalid")
	ErrPortal          = errors.New("world portal is invalid")
	ErrContent         = errors.New("world content is invalid")
	ErrMaterialMapping = errors.New("world material mapping is invalid")
	ErrLighting        = errors.New("world lighting is invalid")
	ErrEnvironment     = errors.New("world environment is invalid")
	ErrStaticSolids    = errors.New("world static solids are invalid")
	ErrCanonical       = errors.New("world payload is not canonical")
)

Functions

func Encode

func Encode(document Document) ([]byte, error)

Encode validates and encodes one compiled world as canonical typed binary.

func EncodeEmissionIntensity added in v0.0.11

func EncodeEmissionIntensity(value float64) (uint8, error)

func MaterialIDs added in v0.0.10

func MaterialIDs(d *Document) []uint32

MaterialIDs returns canonical deduplicated atlas order. All legacy primary references retain their original order, followed by secondary references, then non-main frame regions, in sector/floor/ceiling/wall order.

func SolidRendererTriangles added in v0.0.13

func SolidRendererTriangles(renderers *SolidRenderers) int

SolidRendererTriangles counts immutable triangles in validated extrusions: two triangles per side and n-2 triangles on each cap.

func Validate

func Validate(document *Document) error

Validate checks a complete compiled document before a host prepares private indexes or publishes a mounted resource.

func ValidateAnimationPreset added in v0.0.11

func ValidateAnimationPreset(p *AnimationPreset) error

ValidateAnimationPreset checks kind-specific bounds and rejects fields from other kinds. Flipbook holds frame zero outside its optional repeat burst.

func ValidateAnimations added in v0.0.11

func ValidateAnimations(document *Document) error

ValidateAnimations validates presets and bindings together, including complete actor references and nonrecursive frame targets. Texture existence is checked by the level compiler and host against packaged assets.

func ValidateEmission added in v0.0.11

func ValidateEmission(document *Document) error

func ValidateEnvironment added in v0.0.12

func ValidateEnvironment(environment *Environment) error

func ValidateEnvironmentSettings added in v0.0.12

func ValidateEnvironmentSettings(settings EnvironmentSettings) error

func ValidateLighting added in v0.0.8

func ValidateLighting(lighting *Lighting) error

ValidateLighting checks the complete lighting payload without requiring sector geometry. Optional absence is represented by Document.Lighting == nil; passing nil here is invalid. Capability/world consistency is the consumer's responsibility because the payload does not contain a cartridge manifest.

func ValidateSolidRenderers added in v0.0.13

func ValidateSolidRenderers(document *Document) error

func ValidateStaticSolids added in v0.0.8

func ValidateStaticSolids(solids *StaticSolids) (err error)

ValidateStaticSolids validates every item, including the last, before mounting. Solids may overlap each other and sectors; sector validation is unchanged.

func ValidateSurfaceSecondary added in v0.0.10

func ValidateSurfaceSecondary(s *SurfaceSecondary) error

func ValidateSurfaceUV added in v0.0.8

func ValidateSurfaceUV(mapping *SurfaceUV) error

ValidateSurfaceUV validates complete bounded projection and weight lists.

Types

type Actor added in v0.0.6

type Actor struct {
	Yaw       float64
	Pitch     float64
	Roll      float64
	Scale     Vec3
	Sprite    *Sprite
	Tags      []string
	Animation *AnimationBinding
}

Actor is the optional typed ECS payload introduced by compiled-world v2. Position remains on Content so actor and non-rendered gameplay contents share the same stable identity and sector assignment.

type AmbientCube added in v0.0.8

type AmbientCube struct {
	PositiveX Vec3
	NegativeX Vec3
	PositiveY Vec3
	NegativeY Vec3
	PositiveZ Vec3
	NegativeZ Vec3
}

AmbientCube supplies six world-space directional ambient colors. It replaces Ambient when present; squared unit-normal components weight each selected face. Colors are finite linear RGB intensities in [0,1].

type AnimationBinding added in v0.0.11

type AnimationBinding struct {
	Preset       string
	PhaseSeconds float64
}

AnimationBinding selects a named preset and a nonnegative clock offset.

type AnimationPreset added in v0.0.11

type AnimationPreset struct {
	Name             string
	Kind             string
	Frames           []uint32
	FPS              float64
	IntervalSeconds  float64
	Flow             Vec2
	Amplitude        float64
	SurfaceAmplitude float64
	Opacity          *float64
	PixelSize        uint32
	Frequency        float64
	Speed            float64
	Axis             Vec3
	Pivot            Vec3
	Offset           Vec3
	PeriodSeconds    float64
}

AnimationPreset contains exactly the fields relevant to Kind. Speeds are radians/second for spin and liquid; liquid flow and amplitude use UV units. SurfaceAmplitude is visual displacement in world metres on horizontal up-facing surfaces. Opacity defaults to 1; PixelSize defaults to 0 (continuous sampling). Axis, Pivot and Offset are actor-local, before actor scale and orientation.

type Animations added in v0.0.11

type Animations struct {
	Version   uint32
	Presets   []AnimationPreset
	Materials []MaterialAnimation
}

Animations is the optional world/animations@1 payload in compiled world v3.

type Content

type Content struct {
	ID       string
	SourceID string
	Instance string
	Kind     string
	Sector   uint32
	Position Vec3
	Actor    *Actor
}

Content retains both its compiled identity and authored/prefab provenance. The component payload is deliberately deferred to its own versioned format.

type Document

type Document struct {
	Version  uint16
	Sectors  []Sector
	Contents []Content
	// Lighting is opt-in in compiled v3 and requires FeatureLighting in addition
	// to Feature. Nil preserves the legacy wire encoding and runtime behavior.
	Lighting        *Lighting
	MaterialMapping *MaterialMapping
	StaticSolids    *StaticSolids
	MaterialLayers  *MaterialLayers
	Animations      *Animations
	Emission        *Emission
	Environment     *Environment
	SolidRenderers  *SolidRenderers
}

Document is one completely compiled world. Sector order is stable because portal references use sector indexes.

func Decode

func Decode(encoded []byte) (Document, error)

Decode rejects JSON, unsupported binary versions, trailing bytes and malformed records. A complete allocation-free scan bounds all typed allocations first.

type Emission added in v0.0.11

type Emission struct {
	Version   uint32
	Materials []MaterialEmission
}

Emission is an optional world/emission@1 payload. Intensity is an eight-bit linear-albedo multiplier, decoded as code*8/255. Pulse is independent of the material's optional flipbook/liquid animation; these are two bounded effects.

type EmissionPulse added in v0.0.11

type EmissionPulse struct {
	Depth         float64
	PeriodSeconds float64
	PhaseSeconds  float64
}

EmissionPulse has depth is the fraction of intensity removed at the dimmest point. A cosine pulse begins at full brightness and reaches its minimum after half a period.

func (EmissionPulse) Validate added in v0.0.11

func (p EmissionPulse) Validate() error

type Environment added in v0.0.12

type Environment struct {
	Version     uint32
	Preset      EnvironmentPreset
	Palette     EnvironmentPalette
	Sun         *EnvironmentSun
	TimeOfDay   *float64
	CloudAmount *float64
	Backdrop    EnvironmentBackdrop
}

Environment is the optional world/environment@1 payload, available in compiled-world v3. Preset defaults are fixed by this payload version. Palette affects sky appearance only, independently of surface illumination.

type EnvironmentBackdrop added in v0.0.14

type EnvironmentBackdrop string

EnvironmentBackdrop selects a decorative horizon layer. Empty selects the preset default; explicit none suppresses the layer. It adds no geometry/light.

const (
	EnvironmentBackdropNone      EnvironmentBackdrop = "none"
	EnvironmentBackdropMountains EnvironmentBackdrop = "mountains"
	EnvironmentBackdropCity      EnvironmentBackdrop = "city"
)

type EnvironmentPalette added in v0.0.12

type EnvironmentPalette string
const (
	EnvironmentPaletteDefault  EnvironmentPalette = "default"
	EnvironmentPaletteViolet   EnvironmentPalette = "violet"
	EnvironmentPaletteTwilight EnvironmentPalette = "twilight"
)

type EnvironmentPreset added in v0.0.12

type EnvironmentPreset string
const (
	EnvironmentDaylight EnvironmentPreset = "daylight"
	EnvironmentSpace    EnvironmentPreset = "space"
	EnvironmentCartoon  EnvironmentPreset = "cartoon"
	EnvironmentFantasy  EnvironmentPreset = "fantasy"
)

type EnvironmentSettings added in v0.0.12

type EnvironmentSettings struct {
	TimeOfDay   float64
	CloudAmount float64
}

EnvironmentSettings is a complete live override of the clock and cloud coverage. TimeOfDay is hours in [0,24); CloudAmount is in [0,1]. A live clock overrides the authored fixed sun. Preset and palette remain authored.

type EnvironmentSun added in v0.0.12

type EnvironmentSun struct {
	Azimuth   float64 `yaml:"azimuth"`
	Elevation float64 `yaml:"elevation"`
}

EnvironmentSun supplies a fixed global sun direction in degrees. Azimuth is [0,360), measured from +X toward +Y. Elevation is [0,90] above the XY plane. If present both angles are explicit; omission selects the preset defaults.

type FrameHorizontal added in v0.0.10

type FrameHorizontal struct {
	Height, Repeat float64
	Offset         Vec2
	Piece          FramePiece
}

type FramePiece added in v0.0.10

type FramePiece struct {
	Material uint32
	Coverage string
}

FramePiece is an already resolved sheet region and its tile coverage class.

type FrameVertical added in v0.0.10

type FrameVertical struct {
	Width, Repeat, Phase float64
	Offset               Vec2
	Piece                FramePiece
}

type LightMotion added in v0.0.8

type LightMotion struct {
	Version       uint32
	Offset        Vec3
	PeriodSeconds float64
}

LightMotion version 1 moves a light smoothly from Position to Position+Offset and back once per PeriodSeconds. It is runtime direct lighting, never baked. The complete segment must stay within the ordinary light coordinate bounds.

type Lighting added in v0.0.8

type Lighting struct {
	Version     uint32
	Ambient     Vec3
	Lights      []PointLight
	AmbientCube *AmbientCube
	Actors      bool
}

Lighting is the independently versioned world/lighting@1 payload. Ambient and point colors are linear RGB intensities in [0,1]. Lights retain authored order and global world coordinates, without sector assignment, prefab transforms, shadows, portal transport or PBR parameters.

type MaterialAnimation added in v0.0.11

type MaterialAnimation struct {
	Material     uint32
	Preset       string
	PhaseSeconds float64
}

type MaterialEmission added in v0.0.11

type MaterialEmission struct {
	Material  uint32
	Intensity uint8
	Pulse     *EmissionPulse
	Lights    []string
}

type MaterialLayers added in v0.0.10

type MaterialLayers struct {
	Version uint32
}

type MaterialMapping added in v0.0.8

type MaterialMapping struct {
	Version uint32
}

MaterialMapping opts a compiled v3 world into world/material-mapping@1. Every floor, ceiling and wall must then supply complete baked projections. Projection setup, authoring modes and anchors belong to the compiler.

type Plane

type Plane struct {
	A float64
	B float64
	C float64
}

Plane describes elevation z=A*x+B*y+C.

type PointLight added in v0.0.8

type PointLight struct {
	ID       string
	Position Vec3
	Color    Vec3
	Radius   float64
	Motion   *LightMotion
}

PointLight is one bounded global light. ID is unique within Lighting; Radius is an influence radius in world units in [MinLightRadius, MaxCoordinate].

type ResolvedEnvironment added in v0.0.12

type ResolvedEnvironment struct {
	Preset       EnvironmentPreset
	Backdrop     EnvironmentBackdrop
	SkyZenith    Vec3
	SkyHorizon   Vec3
	SkyNadir     Vec3
	CloudColor   Vec3
	SunDiskColor Vec3
	SunDirection Vec3
	SunColor     Vec3
	SunIntensity float64
	Ambient      Vec3
	AmbientCube  AmbientCube
	TimeOfDay    float64
	CloudAmount  float64
}

ResolvedEnvironment supplies bounded linear RGB defaults to consumers without runtime allocation. SunDirection points toward the light; incoming rays travel in the opposite direction. AmbientCube is outdoor fill, not global indoor illumination. Consumers must restrict fill and sun visibility using sky openings and geometry. Decorative sky elements add no additional lights.

func ResolveEnvironment added in v0.0.12

func ResolveEnvironment(environment *Environment) (ResolvedEnvironment, error)

ResolveEnvironment validates and resolves the versioned preset. Palette overrides never modify the sun or ambient light defaults. Calling this at world preparation keeps preset work outside the render loop.

func ResolveEnvironmentSettings added in v0.0.12

func ResolveEnvironmentSettings(environment *Environment, settings EnvironmentSettings) (ResolvedEnvironment, error)

ResolveEnvironmentSettings applies a validated live clock to the authored style. It allocates no memory and never changes the authored payload.

type Sector

type Sector struct {
	ID               string
	SourceRoom       string
	Instance         string
	Walls            []Wall
	Floor            Plane
	Ceiling          Plane
	FloorMaterial    uint32
	CeilingMaterial  uint32
	FloorUV          *SurfaceUV
	CeilingUV        *SurfaceUV
	FloorSecondary   *SurfaceSecondary
	CeilingSecondary *SurfaceSecondary
	// Sky opens the ceiling visually and to environment lighting. The finite
	// ceiling plane still bounds navigation, portals and spatial queries.
	Sky bool
}

Sector is a strictly convex CCW cell. SourceRoom and Instance retain the authoring identity after prefab expansion and decomposition.

type Solid added in v0.0.8

type Solid struct {
	ID             string
	Footprint      []Vec2
	Bottom         Plane
	Top            Plane
	SideMaterial   uint32
	TopMaterial    uint32
	BottomMaterial uint32
	SideUV         *SurfaceUV
	TopUV          *SurfaceUV
	BottomUV       *SurfaceUV
	Collision      bool
}

Solid is a strictly convex CCW extrusion between two elevation planes. Collision blocks movement but never makes Top a walkable floor. Optional mappings are shared by the indicated surface group; SideUV is not per-edge.

type SolidAttachment added in v0.0.13

type SolidAttachment struct {
	Actor  string
	Prefab string
}

type SolidPrefab added in v0.0.13

type SolidPrefab struct {
	ID     string
	Solids []Solid
}

type SolidRenderers added in v0.0.13

type SolidRenderers struct {
	Version uint32
	Prefabs []SolidPrefab
	Actors  []SolidAttachment
}

SolidRenderers retains reusable local solid geometry separately from static world geometry. Actors bind existing content identities to prefab identities.

type Sprite added in v0.0.6

type Sprite struct {
	AssetID uint32
	Facing  SpriteFacing
	Alpha   SpriteAlpha
	Width   float64
	Height  float64
	OriginX float64
	OriginY float64
}

type SpriteAlpha added in v0.0.6

type SpriteAlpha string
const (
	SpriteCutout SpriteAlpha = "cutout"
	SpriteBlend  SpriteAlpha = "blend"
)

type SpriteFacing added in v0.0.6

type SpriteFacing string
const (
	SpriteCameraFacing SpriteFacing = "camera-facing"
	SpriteUpright      SpriteFacing = "upright"
	SpriteCross        SpriteFacing = "cross"
	SpriteFixed        SpriteFacing = "fixed"
)

type StaticSolids added in v0.0.8

type StaticSolids struct {
	Version uint32
	Items   []Solid
}

StaticSolids contains independently placed opaque volumes. They never alter the sector/portal graph. Hosts must advertise FeatureStaticSolids.

type SurfaceSecondary added in v0.0.10

type SurfaceSecondary struct {
	Material uint32
	Strength float64
	UV       *SurfaceUV
}

type SurfaceUV added in v0.0.8

type SurfaceUV struct {
	Projections []UVProjection
	Weights     []float64
}

SurfaceUV contains one planar/wrapped projection or three blended projections. Weights are constant per surface, finite, nonnegative and normalized to one within UVWeightTolerance. They apply to all material channels, not just color.

type UVPlane added in v0.0.8

type UVPlane struct {
	X      float64
	Y      float64
	Z      float64
	Offset float64
}

UVPlane evaluates X*position.X+Y*position.Y+Z*position.Z+Offset. All coefficients and Offset are finite with absolute value at most 1e12.

type UVProjection added in v0.0.8

type UVProjection struct {
	U UVPlane
	V UVPlane
}

UVProjection is an authored-position affine mapping to texture repeats. Hosts evaluate these planes before clipping; no projection setup is inferred.

type Vec2

type Vec2 struct {
	X float64
	Y float64
}

type Vec3

type Vec3 struct {
	X float64
	Y float64
	Z float64
}

type Wall

type Wall struct {
	Start        Vec2
	End          Vec2
	Portal       int32
	PortalWall   uint16
	Material     uint32
	SourceEdge   string
	UV           *SurfaceUV
	Secondary    *SurfaceSecondary
	FrameRegions []WallFrameRegion
	// FrameCompiled preserves static-frame participation when a portal has no
	// exposed solid spans and thus no region records.
	FrameCompiled bool
	// Sky is an opaque boundary rendered as the environment. It is valid only
	// in a sky sector and cannot participate in a portal. Confinement remains.
	Sky bool
}

Wall is one directed sector boundary. Portal is the adjacent sector index, or -1 for an opaque wall. PortalWall is one plus the reciprocal wall index in compiled-world v3; zero is reserved for v1/v2 coincident portals and opaque walls. The paired directed edges define a rigid destination-to-source portal transform. SourceEdge is empty only for compiler-generated internal decomposition edges.

type WallFrameConfig added in v0.0.10

type WallFrameConfig struct {
	Top, Bottom     FrameHorizontal
	Start, End      FrameVertical
	Patches         [4]FramePiece
	PerimeterOffset float64
}

WallFrameConfig is a build-time recipe; it is never serialized to the host. Patches are top/start, top/end, bottom/start, bottom/end in that order.

type WallFrameRegion added in v0.0.10

type WallFrameRegion struct {
	Vertices []Vec2
	Material uint32
	UV       *SurfaceUV
	Coverage string
	RepeatU  bool
	RepeatV  bool
}

WallFrameRegion is one complete, nonoverlapping wall partition, already selected by the builder. Vertices use X=edge fraction and Y=world elevation, ordered counterclockwise in this two-dimensional coordinate system. Main regions retain the wall's mapping and have no region UV. Opaque regions sample their sole material; masked regions blend over the wall's main material.

func CompileWallFrame added in v0.0.10

func CompileWallFrame(w Wall, p WallProfile, f WallFrameConfig) ([]WallFrameRegion, error)

CompileWallFrame partitions visible solid spans into at most 252 convex regions. Bands follow affine floor/ceiling profiles; opposing envelopes crop proportionally when a face is shorter than their combined requested sizes. Original authored corners and texture IDs have already been resolved by the builder. The output contains every main and frame region with no overlap.

type WallProfile added in v0.0.8

type WallProfile struct {
	Heights [4][2]float64
	Cuts    [8]float64
	Count   int
}

WallProfile divides a wall where any of its four linear elevation functions cross. Heights 0/1 are source floor/ceiling; 2/3 are destination elevations already transformed into the source coordinate frame. It contains no mesh or renderer state and can be used by public builders and private hosts alike.

func NewWallProfile added in v0.0.8

func NewWallProfile(heights [4][2]float64, tolerance float64) (WallProfile, error)

NewWallProfile requires finite endpoint heights and a finite positive tolerance. The four pairs have at most six interior crossings.

func ProfileForWall added in v0.0.10

func ProfileForWall(d *Document, sector, index int) (WallProfile, error)

ProfileForWall resolves destination endpoints and elevation translation using the compiled portal pair. Callers validate the world before invoking it.

func (WallProfile) Controls added in v0.0.8

func (p WallProfile) Controls(t float64) (int, int)

Controls returns the maximum floor and minimum ceiling at an edge fraction.

func (WallProfile) Height added in v0.0.8

func (p WallProfile) Height(kind int, t float64) float64

Height evaluates one linear elevation at an edge fraction.

Jump to

Keyboard shortcuts

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