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

world

package
v0.0.12 Latest Latest
Warning

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

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

README

Compiled world contract

Compiled worlds use the world/sectors@1 cartridge capability and the @world/main level entry. format/world accepts only its canonical encoding and validates all sectors, planes, reciprocal portals, identities, provenance, and content placement before a host prepares runtime indexes. Format version 2 adds optional typed actor transforms, sprite modes, alpha policy and bounded exact tags while readers retain version 1 compatibility.

See authoring semantics for compiler inputs.

Candidate binary wire, version 1

The unreleased SDK candidate replaces compiled runtime JSON with KWR1 typed binary. The 16-byte little-endian header contains magic (4 bytes), binary version 1 (uint16), zero flags (uint16), payload length (uint32) and zero reserved (uint32). The exact payload follows public Go declaration order; semantic world versions 1–3 retain their separate feature gates. JSON and older runtime payloads are rejected, without a compatibility fallback.

Integers use fixed widths (int is signed int32), floats are finite IEEE values, and negative zero has one canonical positive-zero encoding. Booleans and pointer presence are bytes 0/1. Strings have uint32 byte lengths and valid UTF-8; slices use uint32 length+1, reserving zero for nil and preserving an explicit empty slice. Fixed arrays have no counts. Generated readers scan every record before allocating typed arrays, enforcing field counts, the 8 MiB payload bound and a 32 MiB conservative allocation ceiling. Truncation, bad counts, unsupported versions, noncanonical primitives and trailing bytes fail before publication.

The handwritten generator owns the typed codecs. Run mise exec -- go generate ./format/world after contract edits; regeneration coverage prevents stale generated files. Binary digests and compiled artifacts must be rebuilt for this candidate; historical released JSON bytes are not the current wire contract. Authoring remains TOML/YAML.

Environment and sky openings, version 1

The next candidate SDK adds optional world/environment@1 alongside world/sectors@1, using compiled world v3 and source v9. The typed environment record has version 1 and preset daylight, optionally adding palette, a sun with azimuth 135/elevation 40, time_of_day and cloud_amount. The engine candidate supplies a mount-owned live clock/cloud setter; cartridge manifest capability gating is independent of the candidate binary envelope. Compiled v1–2 reject the feature; absent controls retain their prior semantics.

Presets are daylight, space, cartoon, fantasy. Palette is omitted, default, violet or twilight; it affects only sky colors, independently of illumination. A supplied sun has two finite angles in degrees: azimuth [0,360) from +X toward +Y and elevation [0,90] above XY. The fixed global sun direction points toward the light, so incoming rays travel in the opposite direction. Each preset fixes the default angles, light color/intensity, sky palette and outdoor ambient cube for this capability version. ResolveEnvironment exposes the bounded linear RGB defaults without heap allocations; consumers resolve them at preparation time. Changing these defaults requires a versioned decision.

Optional time_of_day is finite hours in [0,24); cloud_amount is finite coverage in [0,1]. Pointer presence preserves explicit zero. Omitted time retains the fixed preset or explicit sun; authored time and sun together are rejected. Omitted clouds default to 0.35. ResolveEnvironmentSettings accepts a complete live clock/cloud override without allocation; 15 reproduces preset sun defaults, 0 is midnight, 6 sunrise, 12 noon and 18 sunset. The clock coordinates direction, direct intensity, sky/fill brightness and low-sun warmth; night sun intensity/disk are zero. Palette selection remains independent of illumination. Clouds change visual coverage and do not shadow geometry.

Preset Default azimuth/elevation Sun intensity Outdoor fill
daylight 135° / 40° 0.72 Cool blue
space 135° / 25° 0.85 Restrained dark blue
cartoon 135° / 50° 0.58 Bright neutral blue
fantasy 135° / 32° 0.68 Muted violet

Sector sky: true is a finite ceiling mask revealing the environment rather than a physical roof. Opaque wall sky: true is a finite horizon mask, valid only in a sky sector with portal: -1. Every sky marker requires a root environment. Sky masks preserve navigation bounds, collision confinement, portal topology and semantic surface bindings. Adjacent sky sectors show the same environment in their exposed upper wall strips even when finite ceiling heights differ. Sky ceilings, horizon masks and these upper strips are excluded from physical shadow casters and lightmap receivers. Floors, roofs and ordinary walls still occlude lighting. Decorative clouds, stars and celestial bodies do not introduce additional lights.

Outdoor fill must be restricted to sky-connected geometry and sun visibility must respect physical occluders; the resolver's ambient cube is not a global interior light. Renderer quality and shadow budgets are host choices. The first version supports a live clock and static casters; moving casters, terrain generation, vegetation and baked sun/sky transport remain separate features. Existing point-light bake recipes remain usable with open sky geometry and never select the directional sun. See lightmap treatment.

Complete validation rejects unknown presets/palettes, bad versions and angles, sky without an environment, horizon walls on portals and horizon walls in indoor sectors. Binary decoding rejects malformed presence tags, incomplete records and noncanonical primitives. Older hosts reject the new capability before publishing resources.

Authored lighting, version 1

The world/lighting@1 contract adds optional authored lighting to compiled world version 3 and authoring source version 4. The cartridge declares both world/sectors@1 and world/lighting@1. Compiled versions 1–2 and source versions 1–3 reject lighting. Absent lighting preserves legacy rendering on every supported semantic world version; source v4 also accepts absence. This independently versioned capability does not change the level envelope or cartridge manifest version.

The typed record contains version 1, ambient linear RGB and a light list. Each point light has id, position, color and radius fields. Ambient and point colors are finite linear RGB intensities in [0,1], represented by x, y, z; they are not sRGB color bytes. Positions are finite global world coordinates, bounded inclusively to ±1,000,000 per component, and need not fall inside a sector. The unreleased SDK 0.0.11 candidate permits 0–4,096 authored sources in authored order, with unique nonempty UTF-8 IDs of at most 128 bytes. An empty list permits ambient-only lighting. Lighting belongs to the root document, never a room, prefab or instance, and receives no prefab transform or sector assignment. The contract supplies no shadows, portal transport, guest lighting controls or PBR parameters.

MaxLights bounds authored sources; MaxRuntimeLights = 50 separately bounds live direct lighting. Completed prebakes collapse any selected steady sources into three coefficient tiles and remove them from runtime direct-light slots. An unbaked world or partial bake must still fit its remaining direct sources within 50; raising the authored bound does not raise GPU or guest light limits. The typed binary field layout stays unchanged, while its generated source-count preflight bound becomes 4,096. Small light lists retain allocation-free identity validation; larger lists use a bounded identity index rather than quadratic comparisons. This candidate producer/bounds change belongs to SDK 0.0.11; released manifests and the runtime command protocol remain unchanged.

The version-1 decision bounds radius inclusively to [0.001, 1,000,000] world units (world.MinLightRadius and world.MaxCoordinate). The lower bound keeps the host's float32 distance/attenuation calculation representable; arbitrary positive float64 radii are not valid. Both source and compiled validators enforce the same complete lighting bounds, identities and finite values. Compiled world decoding additionally requires complete canonical binary records. A nil lights slice and an explicit empty slice have distinct encodings and the same ambient-only semantics. Source TOML/YAML presence and unknown-field checks belong to the public compiler: worldsource.Validate validates typed values and does not parse author text. Future semantic changes require a new lighting capability/version.

The SDK 0.0.8 authored-lighting path uses squared Half-Lambert diffuse and bounded point-light falloff. When a material atlas is present, tangent normals affect diffuse shading, and AO scales ambient light only, once in linear RGB. Direct light remains unoccluded. Lit albedo diagnostics retain unoccluded albedo; normal and depth diagnostics keep their meanings. Material height never replaces geometric camera depth or changes silhouettes.

Material height represents positive raised relief; zero preserves the original UVs. The authored path uses two fixed-point parallax shifts with bilinear height samples, bounded to 0.025 of a texture repeat per UV component and faded at grazing angles. Albedo, normal, height and AO share the shifted UVs. A restrained stylized rim has coefficient 0.08, height/AO masks, a fourth-power view Fresnel term and actual front-facing direct-light contributions; it supplies no ambient glow or PBR/specular parameters. Legacy worlds without authored lighting retain AO-baked unlit output and ignore height. These rendering semantics introduce no new payload fields, material-atlas schema or SDK manifest version.

Ambient cube and actor lighting

The SDK 0.0.8 world/lighting@1 contract accepts optional ambient_cube with six finite linear RGB [0,1] fields: positive_x, negative_x, positive_y, negative_y, positive_z, negative_z. When present it replaces ambient: select axis colors by the unit world normal's signs and weight them by squared normal components, then apply material AO once. Identical six colors match uniform ambient. This world-global artistic cube provides no spatial probes or portal light transport. Optional actors: true lights world sprites in full camera output using geometry normals; omitted/false keeps sprites unlit. Their absence retains the existing lighting behavior.

Point-light motion, version 1

The SDK 0.0.8 lighting contract accepts point-light motion: {version: 1, offset: {x: 12, y: 0, z: 0.8}, period_seconds: 12}. The offset and both segment endpoints obey the ordinary finite coordinate bounds; period is finite in [0.1, 3600] seconds. Runtime position follows position + offset*(1-cos(2*pi*(t mod period)/period))/2. All cameras share a mounted-level simulation clock, reset on replacement/remount. Full surfaces and opted-in actors receive this unshadowed direct light; diagnostic views stay unchanged. A moving light cannot be selected in a static lightmap bake. Omission retains static-light semantics. The motion record is version 1; the guest wire contract is unchanged.

Material mapping, version 1

Compiled world v3 retains an optional material_mapping: {version: 1} marker. When present, every sector floor_uv, ceiling_uv and wall uv is required, including internal decomposition and portal edges. A mapping without the marker is invalid. Compiled v1–2 reject both the marker and surface mappings. The game cartridge declares world/material-mapping@1 alongside world/sectors@1; older hosts reject unsupported capabilities before readiness. No new guest command or level envelope version is involved.

Each SurfaceUV has projections of length one or three and equally many weights. A projection contains u and v, each an affine plane with x, y, z, offset; the host evaluates x*X+y*Y+z*Z+offset at authored geometry positions before clipping. Every coefficient and offset is finite and bounded to ±1,000,000,000,000. Weights are finite in [0,1] and sum to one within 1e-9. Three projections blend using constant surface weights derived by the compiler from geometric normals; all material channels use the same projections and weights. The runtime does not infer projection setup or authoring modes. Compiled decoding requires complete canonical binary records before publishing a world. The mapping capability is available in SDK 0.0.8; absent mappings retain legacy projection semantics.

Static solids, version 1

Compiled world v3 optionally carries static_solids: {version: 1, items: [...]} with the world/static-solids@1 capability, available in SDK 0.0.8. Solids are independent of room sectors and portal connectivity. Omission retains worlds without static solids.

Each compiled Solid contains id, a strictly convex CCW footprint (3–64 vertices), bottom/top elevation planes, nonzero side_material, top_material and bottom_material IDs, optional side_uv/top_uv/bottom_uv, and omitted-false collision. There are at most 1,024 solids; IDs are unique UTF-8 of 1–128 bytes. Coordinates, plane coefficients and evaluated elevations obey ±1,000,000 bounds; edges and thickness are at least 1e-6. Overlapping solids do not relax any room or portal validation. Collision is a blocking volume, not a walkable top. Complete validation and canonical binary rules apply before mounting.

Mapped solids require the material-mapping marker and capability. There are no new guest commands or level-envelope versions. Incompatible contract changes require a versioned decision.

Compiled material layers, version 1

Compiled world v3 may declare material_layers: {"version":1} together with material_mapping and the world/material-layers@1 cartridge capability. Absent fields retain existing v1–v3 material behavior. Secondary descriptors on sector floors/ceilings and walls contain material, strength in [0,1], and a complete independent uv projection. Atlas tiles used as primary or secondary materials remain opaque.

An authored wall may carry frame_compiled: true and frame_regions: the entire partition of its visible solid spans, including main-only regions. Each convex region contains 3–4 counterclockwise vertices in edge-fraction/elevation coordinates (x is the fraction from directed start to end, y is world Z), a resolved material, and coverage (main, opaque, or masked). Main regions use the original wall material/mapping and omit region uv and repeat controls. Frame regions supply one UV projection and optional repeat_u/repeat_v; their material IDs select ordinary level textures, including direct top/bottom band images. Opaque regions use one full material; masked regions blend over the wall main using atlas alpha. A completely open portal retains frame_compiled: true even with no region records, so the host can reject edits that would create uncompiled framed wall spans. Marked empty regions are valid only when the wall has no visible solid area. Nonempty regions implicitly mark frame participation. Coverage never opens holes in the wall or alters collision, geometric depth or lightmap receiver identity.

CompileWallFrame is the shared build-time partitioner. Its non-serialized recipe contains resolved strip dimensions, repeats, phases, offsets and piece IDs. ProfileForWall resolves affine solid spans, including transformed portal endpoints. Horizontal strips preserve PNG row direction: top V=(top−z)/height and bottom V=(bottom+height−z)/height, before offsets. They follow slopes, and overlapping envelopes crop proportionally. The source-v7 builder supplies horizontal bands only; compiled regions also retain their existing general strip/patch representation. No authored texture selection or placement inference is required at runtime. There are at most 252 regions per wall (7 profile intervals × 2 exposed spans × 2 overlap branches × 3 columns × 3 rows), 4 vertices per region and 32768 regions per world. Existing 8 MiB encoded-world and world geometry limits still apply.

Complete validation rejects nonconvex regions, invalid mappings, missing markers, regions on decomposition edges, escaped or portal-aperture polygons, overlapping partitions and uncovered solid area. The host must preserve the original authored edge/receiver identity during triangulation and must not reuse static records after a wall-height edit changes their geometry.

MaterialIDs defines shared atlas traversal: legacy primary references first (sector floor, ceiling, walls, then solid side/top/bottom), followed by secondary references in surface order and selected non-main frame regions in emitted order, deduplicated by material ID. Builders and hosts must use this same order and validate every referenced slot before readiness.

Reusable animations

Compiled v3 optionally carries animations version 1 and requires world/animations@1 alongside world/sectors@1. Source version 8 introduces this feature without changing compiled geometry or absent-animation behavior. The level-wide library contains at most 64 unique named presets and 196 material bindings. Actors can select a named preset with animation; material bindings select a texture/material ID with material. phase_seconds offsets the shared simulation clock by a finite nonnegative value up to 86400 seconds.

Kind Parameters and behavior
flipbook frames (2–64 texture IDs), fps (0.001–120), optional interval_seconds. Zero interval loops continuously. A positive interval must contain the full frame sequence; after playing it, frame zero is held until the next interval.
liquid flow (UV/second, each component −10 to 10), amplitude (UV units, 0–1), frequency (waves/UV unit, greater than 0 up to 100), speed (radians/second, −100 to 100). Smooth analytic UV distortion on world materials. Optional surface_amplitude (world metres, 0–0.25) adds visual waves on horizontal up-facing floors and solid tops; optional opacity (0–1, defaults to 1) uses ordered screen-space coverage so deeper geometry remains visible; optional pixel_size (integer 0–32, defaults to 0) quantizes sampling to multiples of base texture texels. Collision remains static.
spin Unit axis, optional pivot, speed (nonzero radians/second, −100 to 100). Fixed sprites rotate around their local pivot.
oscillate Nonzero offset, period_seconds (0.001–86400). Fixed sprites smoothly move from their authored rest position to rest plus offset and back, using (1-cos(2*pi*t/period))/2.

Axis, pivot and offset are actor-local before scale and orientation. Motion is visual only: authored positions, sector ownership, collision and gameplay queries remain unchanged. Explicit sprite flipbook bindings support all facing modes; material flipbooks also affect sprites that use that texture. liquid bindings apply to world materials; fixed sprites support spin and oscillate. Kind-specific validation rejects parameters belonging to other kinds and unsupported targets.

All frames must reference packaged textures, including animation-only frames. Material flipbook frame targets cannot select another animation, except for the binding's own material (normally frame zero). MaterialIDs appends these frames in material-binding and frame order after all existing surface references, with stable deduplication. Actor-only frames stay in the ordinary sprite texture table and do not consume world material slots. Baking remains static: animation does uses the authored rest geometry and does not emit light. Horizontal surface displacement is GPU-only; other faces sharing the material remain rigid. A displacement binding needs at least one horizontal floor or solid top. opacity: 0 is fully transparent; omitting it means opaque. Explicit null values are invalid in authored YAML. Texture pixel quantization does not reduce viewport resolution.

Material emission

Candidate world/emission@1 adds the optional compiled v3 Emission payload. Up to 196 used primary environment/band material IDs have an eight-bit intensity, decoded as code * 8 / 255, and an optional bounded cosine pulse. Depth is [0,1], period [0.001,86400] seconds and phase [0,86400] seconds. Duplicate IDs, frame-only/secondary-only materials, invalid versions and invalid pulse values reject. The pulse composes independently with the existing single surface animation. Emission uses final linear albedo and bypasses lighting/shadow/AO attenuation; it does not supply bloom, sprite emission or automatic light transport. Explicit colored point lights provide nearby illumination. Omitted payloads retain legacy emission behavior. The feature requires world/sectors@1.

Optional material lights entries link existing point-light IDs to that material's pulse envelope. Their authored colors are the peak contribution; the same simulation phase drives surface emission and environment/actor light colors. At most 50 unique lights may be linked, each to one material. Unknown, duplicate or multiply owned IDs reject. A linked light with nonzero pulse depth cannot be included in static world-lightmap bake recipes.

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 (
	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"

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 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 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
}

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
}

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 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
	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 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