Documentation
¶
Overview ¶
Package scene3d provides a 3D scene graph, named socket attachments, a dynamic AABB Bounding Volume Hierarchy (BVH), BVH-accelerated spatial queries, perspective and orthographic cameras, camera controllers (orbit, first-person, third-person follow), screen-space picking, and box-projected 3D decals (Decal, DecalPool, GPUDecalRenderer) built on math3d.
Conventions ¶
All transforms, projections, frustums, and rays follow package math3d's conventions:
- Right-handed, Y-up coordinate system (+X right, +Y up, -Z forward).
- Column-major matrices with TRS composition (T * R * S) and clip-space transform P * V * M.
- Zero-to-one [0, 1] NDC depth (WebGPU / Metal / Vulkan).
- Screen coordinates place (0, 0) at the top-left of the viewport and (viewW, viewH) at the bottom-right.
Construct nodes with NewNode and scenes with NewScene so default transforms, visibility, layers, and empty bounding volumes are initialized cleanly.
Index ¶
- Constants
- Variables
- func AttachmentAs[T any](n *Node, key string) (T, bool)
- func DecalVertexLayout() gpu.VertexBufferLayout
- func ProjectDecal(scene *Scene, d Decal, dst *DecalGeometry) int
- func ProjectDecalOntoReceiver(d Decal, receiver DecalReceiver, worldMat math3d.Mat4, dst *DecalGeometry) int
- func SceneObstructionCheck(scene *Scene, layerMask uint32, ignore ...*Node) func(from, to math3d.Vec3) (float32, bool)
- type BVH
- func (b *BVH) Bounds(h BVHHandle) (math3d.AABB, bool)
- func (b *BVH) Contains(h BVHHandle) bool
- func (b *BVH) Height() int
- func (b *BVH) ID(h BVHHandle) (uint64, bool)
- func (b *BVH) Insert(id uint64, bounds math3d.AABB, userData any) BVHHandle
- func (b *BVH) LastQueryVisited() int
- func (b *BVH) Len() int
- func (b *BVH) QueryAABB(region math3d.AABB, out []BVHHandle) []BVHHandle
- func (b *BVH) QueryFrustum(frustum math3d.Frustum, out []BVHHandle) []BVHHandle
- func (b *BVH) QuerySphere(center math3d.Vec3, radius float32, out []BVHHandle) []BVHHandle
- func (b *BVH) Raycast(ray math3d.Ray, maxDist float32, ...)
- func (b *BVH) RaycastAll(ray math3d.Ray, maxDist float32, out []BVHRayHit) []BVHRayHit
- func (b *BVH) Rebuild()
- func (b *BVH) Remove(h BVHHandle)
- func (b *BVH) Update(h BVHHandle, newBounds math3d.AABB) bool
- func (b *BVH) UserData(h BVHHandle) (any, bool)
- type BVHHandle
- type BVHRayHit
- type Camera
- func (c *Camera) Eye() math3d.Vec4
- func (c *Camera) Forward() math3d.Vec3
- func (c *Camera) Frustum() math3d.Frustum
- func (c *Camera) Lerp(b *Camera, t float32) Camera
- func (c *Camera) LookAt(target, up math3d.Vec3)
- func (c *Camera) ProjMatrix() math3d.Mat4
- func (c *Camera) Right() math3d.Vec3
- func (c *Camera) ScreenRay(screenX, screenY, viewW, viewH float32) math3d.Ray
- func (c *Camera) SetViewport(width, height float32)
- func (c *Camera) SyncFromNode(node *Node)
- func (c *Camera) Up() math3d.Vec3
- func (c *Camera) ViewMatrix() math3d.Mat4
- func (c *Camera) ViewProj() math3d.Mat4
- func (c *Camera) WorldToScreen(worldPos math3d.Vec3, viewW, viewH float32) (screen math3d.Vec2, depth float32, visible bool)
- type Collider
- type Decal
- type DecalBatch
- type DecalGeometry
- func (g *DecalGeometry) AppendIndexData(dst []byte) []byte
- func (g *DecalGeometry) AppendVertexData(dst []byte) []byte
- func (g *DecalGeometry) Bounds() math3d.AABB
- func (g *DecalGeometry) IndexCount() int
- func (g *DecalGeometry) IndexDataSize() int
- func (g *DecalGeometry) IndexFormat() gpu.IndexFormat
- func (g *DecalGeometry) Reset()
- func (g *DecalGeometry) TriangleCount() int
- func (g *DecalGeometry) VertexCount() int
- func (g *DecalGeometry) VertexDataSize() int
- type DecalHandle
- type DecalPool
- func (p *DecalPool) Active() []Decal
- func (p *DecalPool) ActiveInto(dst []Decal) []Decal
- func (p *DecalPool) BuildGeometry(scene *Scene, dst *DecalGeometry) int
- func (p *DecalPool) BuildReceiverGeometry(receiver DecalReceiver, worldMat math3d.Mat4, layer uint32, dst *DecalGeometry) int
- func (p *DecalPool) Cap() int
- func (p *DecalPool) Clear()
- func (p *DecalPool) Contains(h DecalHandle) bool
- func (p *DecalPool) ForEach(fn func(DecalHandle, *Decal) bool)
- func (p *DecalPool) Get(h DecalHandle) (*Decal, bool)
- func (p *DecalPool) Len() int
- func (p *DecalPool) Remove(h DecalHandle) bool
- func (p *DecalPool) Spawn(d Decal) DecalHandle
- func (p *DecalPool) Step(dt time.Duration) int
- type DecalReceiver
- type DecalReceiverMesh
- type DecalVertex
- type FPSController
- func (c *FPSController) Apply(cam *Camera)
- func (c *FPSController) Forward() math3d.Vec3
- func (c *FPSController) Look(deltaYaw, deltaPitch float32)
- func (c *FPSController) Move(forward, right, up float32, dt time.Duration)
- func (c *FPSController) Right() math3d.Vec3
- func (c *FPSController) Rotation() math3d.Quat
- func (c *FPSController) Up() math3d.Vec3
- type GPUDecalOptions
- type GPUDecalRenderer
- func (r *GPUDecalRenderer) CameraLayout() *gpu.BindGroupLayout
- func (r *GPUDecalRenderer) Close() error
- func (r *GPUDecalRenderer) Draw(pass *gpu.RenderPass)
- func (r *GPUDecalRenderer) DrawWithCamera(pass *gpu.RenderPass, cameraGroup *gpu.BindGroup)
- func (r *GPUDecalRenderer) IndexCount() uint32
- func (r *GPUDecalRenderer) Pipeline() *gpu.Pipeline
- func (r *GPUDecalRenderer) SetTexture(id uint32, tex *gpu.Texture) error
- func (r *GPUDecalRenderer) TextureLayout() *gpu.BindGroupLayout
- func (r *GPUDecalRenderer) Upload(geom *DecalGeometry) error
- func (r *GPUDecalRenderer) UploadTextureRGBA(id uint32, width, height uint32, rgba []byte) error
- func (r *GPUDecalRenderer) WriteCamera(cam *Camera)
- func (r *GPUDecalRenderer) WriteCameraMatrices(view, proj math3d.Mat4, eye math3d.Vec4)
- type MeshCollider
- type Node
- func (n *Node) AddChild(child *Node) error
- func (n *Node) AddTag(tag string)
- func (n *Node) Attach(socket string, child *Node) error
- func (n *Node) Attached(socket string) []*Node
- func (n *Node) Attachment(key string) (any, bool)
- func (n *Node) Children() []*Node
- func (n *Node) DecalReceiver() DecalReceiver
- func (n *Node) DefineSocket(name string, local math3d.Transform) *Node
- func (n *Node) Detach(keepWorld bool) bool
- func (n *Node) DirtyUpdates() uint64
- func (n *Node) EffectiveEnabled() bool
- func (n *Node) EffectiveVisible() bool
- func (n *Node) FindByName(name string) *Node
- func (n *Node) FindByTag(tag string) []*Node
- func (n *Node) FitBoundsToCollider()
- func (n *Node) HasTag(tag string) bool
- func (n *Node) HierarchyBounds() math3d.AABB
- func (n *Node) IsDescendantOf(ancestor *Node) bool
- func (n *Node) IsDirty() bool
- func (n *Node) MarkDirty()
- func (n *Node) Parent() *Node
- func (n *Node) RemoveAttachment(key string)
- func (n *Node) RemoveChild(child *Node) bool
- func (n *Node) RemoveTag(tag string)
- func (n *Node) Reparent(newParent *Node) error
- func (n *Node) ReparentKeepWorld(newParent *Node) error
- func (n *Node) SetAttachment(key string, value any)
- func (n *Node) SetCollider(c Collider)
- func (n *Node) SetDecalReceiver(r DecalReceiver)
- func (n *Node) SetEnabled(enabled bool)
- func (n *Node) SetLocal(t math3d.Transform)
- func (n *Node) SetLocalBounds(bounds math3d.AABB)
- func (n *Node) SetParent(newParent *Node, keepWorld bool) error
- func (n *Node) SetPosition(pos math3d.Vec3)
- func (n *Node) SetRotation(rot math3d.Quat)
- func (n *Node) SetScale(scale math3d.Vec3)
- func (n *Node) SetVisible(visible bool)
- func (n *Node) Socket(name string) *Node
- func (n *Node) Walk(fn func(*Node) bool)
- func (n *Node) WorldBounds() math3d.AABB
- func (n *Node) WorldMatrix() math3d.Mat4
- func (n *Node) WorldTransform() math3d.Transform
- type OrbitController
- func (c *OrbitController) Apply(cam *Camera)
- func (c *OrbitController) Orbit(deltaYaw, deltaPitch float32)
- func (c *OrbitController) Pan(deltaRight, deltaUp float32)
- func (c *OrbitController) SetAngles(yaw, pitch float32)
- func (c *OrbitController) SetDistance(distance float32)
- func (c *OrbitController) SetTarget(target math3d.Vec3)
- func (c *OrbitController) Snap()
- func (c *OrbitController) Step(dt time.Duration)
- func (c *OrbitController) Update(cam *Camera, dt time.Duration)
- func (c *OrbitController) Zoom(delta float32)
- type Projection
- type ProjectionKind
- type RayHit
- type Scene
- func (s *Scene) Add(node *Node) error
- func (s *Scene) BVH() *BVH
- func (s *Scene) CullFrustum(frustum math3d.Frustum) []*Node
- func (s *Scene) CullFrustumInto(frustum math3d.Frustum, out []*Node) []*Node
- func (s *Scene) DirtyUpdates() int
- func (s *Scene) FindByName(name string) *Node
- func (s *Scene) QueryAABB(box math3d.AABB) []*Node
- func (s *Scene) QueryFrustum(vp math3d.Mat4) []*Node
- func (s *Scene) QueryFrustumVolume(f math3d.Frustum) []*Node
- func (s *Scene) QuerySphere(sphere math3d.Sphere) []*Node
- func (s *Scene) Raycast(ray math3d.Ray, layerMask uint32) []RayHit
- func (s *Scene) RaycastFirst(ray math3d.Ray, layerMask uint32) (RayHit, bool)
- func (s *Scene) RebuildBVH()
- func (s *Scene) Remove(node *Node) bool
- func (s *Scene) Root() *Node
- func (s *Scene) SyncBVH()
- func (s *Scene) UpdateTransforms() int
- func (s *Scene) Walk(fn func(*Node) bool)
- type SphereCollider
- type ThirdPersonController
- func (c *ThirdPersonController) Apply(cam *Camera)
- func (c *ThirdPersonController) Snap(targetPos, targetForward math3d.Vec3)
- func (c *ThirdPersonController) Step(targetPos, targetForward math3d.Vec3, dt time.Duration)
- func (c *ThirdPersonController) Update(cam *Camera, targetPos, targetForward math3d.Vec3, dt time.Duration)
Examples ¶
Constants ¶
const ( // DefaultDecalAngleFadeStart is the angle (in radians) between a surface // normal and the decal's opposite projection direction (+Z) where angle fade // begins. DefaultDecalAngleFadeStart float32 = 60 * (math.Pi / 180) // DefaultDecalAngleFadeEnd is the angle (in radians) at and beyond which a // surface receives zero decal opacity and is clipped away. DefaultDecalAngleFadeEnd float32 = 85 * (math.Pi / 180) // DefaultDecalDepthFade is the fraction of box half-depth at both ends of // the projection box over which opacity fades smoothly to zero. DefaultDecalDepthFade float32 = 0.1 // DefaultDecalBias is the default world-space offset applied along receiver // surface normals to prevent z-fighting on the forward rendering path. DefaultDecalBias float32 = 0.002 )
Default decal projection parameters applied by NewDecal and NewDecalOnSurface.
const ( // DecalVertexStride is the byte size of one interleaved decal vertex: // position (12 B) + normal (12 B) + UV (8 B) + RGBA color (16 B). DecalVertexStride = 48 DecalPositionOffset = 0 DecalNormalOffset = 12 DecalUVOffset = 24 DecalColorOffset = 32 DecalPositionLocation = 0 DecalNormalLocation = 1 DecalUVLocation = 2 DecalColorLocation = 3 )
DecalVertexLayout constants describe the interleaved byte layout written by DecalGeometry.AppendVertexData and consumed by DecalWGSL.
const ( // LayerDefault is the default layer assigned to nodes created by NewNode. LayerDefault uint32 = 1 << 0 // LayerAll matches every non-zero layer bit. LayerAll uint32 = ^uint32(0) )
Layer bitmask constants for node filtering in raycasts and picking.
const DecalCameraUniformSize = 3*64 + 16
DecalCameraUniformSize is the byte size of the camera uniform block declared in DecalWGSL (three column-major mat4x4 matrices plus a vec4 eye point), matching render3d.CameraUniformSize byte-for-byte.
const DecalReceiverAttachment = "decal_receiver"
DecalReceiverAttachment is the Node.Attachments key checked by Node.DecalReceiver and ProjectDecal before falling back to Node.Collider.
const DecalWGSL = `` /* 930-byte string literal not displayed */
DecalWGSL is the mobile-compatible forward-rendering WGSL shader for box-projected decals (#385). It uses only standard vertex/fragment stages, a camera uniform at @group(0) @binding(0) (layout-compatible with render3d.CameraWGSL), and an albedo texture + sampler at @group(1). No compute shaders, storage buffers, or depth-buffer readback are required, so it runs identically on WebGPU, Metal, Vulkan, OpenGL ES 3.0, WebGL 2, and NSGo's software renderer.
Variables ¶
var ( // ErrNilNode is returned when a nil node is passed to AddChild or Attach. ErrNilNode = errors.New("scene3d: nil node") // ErrCycle is returned when parenting a node would introduce a cycle. ErrCycle = errors.New("scene3d: hierarchy cycle detected") // ErrNotDecomposable is returned by a keep-world reparent whose new parent is singular or whose exact local transform needs shear, which a Transform cannot hold. ErrNotDecomposable = errors.New("scene3d: local transform is not decomposable to TRS") )
Hierarchy errors returned by Node tree mutations.
Functions ¶
func AttachmentAs ¶
AttachmentAs retrieves the named attachment from n and asserts it to type T.
func DecalVertexLayout ¶
func DecalVertexLayout() gpu.VertexBufferLayout
DecalVertexLayout returns the vertex buffer layout matching DecalGeometry.AppendVertexData and DecalWGSL. Each call returns a fresh Attributes slice.
func ProjectDecal ¶
func ProjectDecal(scene *Scene, d Decal, dst *DecalGeometry) int
ProjectDecal clips and projects d onto all visible, enabled nodes in scene whose world bounds overlap d's projection box and whose Node.Layer matches d.LayerMask. Projected triangles are appended to dst; the number of triangles added is returned.
func ProjectDecalOntoReceiver ¶
func ProjectDecalOntoReceiver(d Decal, receiver DecalReceiver, worldMat math3d.Mat4, dst *DecalGeometry) int
ProjectDecalOntoReceiver clips and projects d onto a single DecalReceiver transformed by worldMat, appending triangles to dst and returning the number of triangles added.
func SceneObstructionCheck ¶
func SceneObstructionCheck(scene *Scene, layerMask uint32, ignore ...*Node) func(from, to math3d.Vec3) (float32, bool)
SceneObstructionCheck returns a ThirdPersonController ObstructionCheck callback backed by BVH-accelerated scene raycasts against visible, enabled nodes matching layerMask. Any node listed in ignore (such as the followed player character) is skipped.
Types ¶
type BVH ¶
type BVH struct {
// contains filtered or unexported fields
}
BVH is a dynamic 3D AABB Bounding Volume Hierarchy.
It maintains a balanced fat-AABB tree with O(log N) incremental Insert, Update, and Remove operations, an optional top-down binned SAH Rebuild for optimal cache-ordered query performance, and zero-allocation slice-reusing frustum, AABB, sphere, and raycast queries.
Every leaf stores both a fattened AABB (for O(1) small-motion updates and subtree pruning) and its exact tight AABB (tested at leaves so queries return the exact same hit set as a brute-force linear scan).
func NewBVH ¶
func NewBVH() *BVH
NewBVH returns an empty dynamic BVH ready for insertions and queries.
func (*BVH) Insert ¶
Insert adds an entry with the given id, tight bounds, and arbitrary userData into b and returns its handle. If bounds is empty, Insert returns an invalid zero BVHHandle without modifying b.
func (*BVH) LastQueryVisited ¶
LastQueryVisited returns the number of BVH tree nodes visited during the most recent query (QueryFrustum, QueryAABB, QuerySphere, Raycast, or RaycastAll).
func (*BVH) QueryAABB ¶
QueryAABB appends handles of all entries whose tight AABB overlaps or touches region to out and returns the resulting slice.
Pass a reused slice (e.g. buf[:0]) for zero-allocation queries.
func (*BVH) QueryFrustum ¶
QueryFrustum appends handles of all entries whose tight AABB intersects frustum to out and returns the resulting slice. Subtrees completely outside frustum are pruned immediately, and subtrees completely inside frustum are collected without redundant per-leaf plane tests.
Pass a reused slice (e.g. buf[:0]) for zero-allocation queries.
func (*BVH) QuerySphere ¶
QuerySphere appends handles of all entries whose tight AABB overlaps or touches the sphere (center, radius) to out and returns the resulting slice.
Pass a reused slice (e.g. buf[:0]) for zero-allocation queries.
func (*BVH) Raycast ¶
func (b *BVH) Raycast(ray math3d.Ray, maxDist float32, visit func(h BVHHandle, hitDist float32) (continueSearch bool))
Raycast traverses the BVH in near-to-far child order using slab AABB intersection tests and invokes visit for each leaf whose tight AABB is hit at parameter hitDist in [0, maxDist]. Traversal stops immediately if visit returns false.
func (*BVH) RaycastAll ¶
RaycastAll finds all entries whose tight AABB intersects ray within [0, maxDist], appends them to out sorted by ascending Distance, and returns the resulting slice.
Pass a reused slice (e.g. buf[:0]) for zero-allocation queries.
func (*BVH) Rebuild ¶
func (b *BVH) Rebuild()
Rebuild reconstructs the BVH top-down using a 12-bucket Surface Area Heuristic (SAH) across all three axes, laying nodes out in cache-friendly depth-first pre-order. All existing BVHHandles remain valid.
func (*BVH) Remove ¶
Remove deletes the entry identified by h from b. Removing an invalid or already-removed handle is a safe no-op.
func (*BVH) Update ¶
Update updates the tight bounds for handle h. If newBounds still fits inside the leaf's existing fat AABB (and is not excessively shrunk), Update completes in O(1) without modifying the tree structure; otherwise the leaf is reinserted with motion-predicted fat bounds in O(log N).
Returns true if h was valid and updated, or false if h is invalid/removed or newBounds is empty.
type BVHHandle ¶
type BVHHandle struct {
// contains filtered or unexported fields
}
BVHHandle uniquely identifies an active leaf entry in a BVH. The zero value is invalid.
type BVHRayHit ¶
type BVHRayHit struct {
Handle BVHHandle
ID uint64
UserData any
Distance float32 // Ray parameter t in [0, maxDist] such that hitPoint == ray.At(Distance)
}
BVHRayHit describes a ray intersection with a BVH leaf's tight AABB.
type Camera ¶
type Camera struct {
Pos math3d.Vec3
Rot math3d.Quat
Projection Projection
}
Camera defines a 3D viewpoint and projection.
In right-handed Y-up space, an identity Rot looks down -Z with +X right and +Y up.
func NewOrthographicCamera ¶
NewOrthographicCamera creates an orthographic Camera looking down -Z.
func NewPerspectiveCamera ¶
NewPerspectiveCamera creates a perspective Camera looking down -Z.
func (*Camera) Eye ¶
Eye returns the camera's eye point in homogeneous world coordinates: (Pos, 1) for a perspective camera, and the direction toward the viewer (-Forward, 0) for an orthographic one, whose eye lies at infinity.
A shader finds the unit vector from a world point p toward the viewer as normalize(eye.xyz - p*eye.w) under either projection.
func (*Camera) Forward ¶
Forward returns the camera's unit world-space forward direction (-Z in local space).
func (*Camera) Lerp ¶
Lerp returns the camera between c (t=0) and b (t=1): Pos blends linearly, Rot by shortest-path spherical interpolation, and the projection by Projection.Lerp.
A game driven by game.Loop keeps the camera from the previous update and draws prev.Lerp(cam, alpha) in Draw, so the view moves smoothly between fixed steps at any display rate.
func (*Camera) LookAt ¶
LookAt orients the camera at its current Pos toward target with world up vector up.
func (*Camera) ProjMatrix ¶
ProjMatrix returns the camera's projection matrix.
func (*Camera) Right ¶
Right returns the camera's unit world-space right direction (+X in local space).
func (*Camera) ScreenRay ¶
ScreenRay unprojects pixel coordinates (screenX, screenY) in a viewport of size (viewW, viewH) through the inverse ViewProj matrix into a world-space Ray with unit direction.
Screen coordinates use (0, 0) at top-left and (viewW, viewH) at bottom-right. Works identically for both perspective and orthographic cameras.
func (*Camera) SetViewport ¶
SetViewport sets Projection.Aspect to width / height, so the projection follows the drawable it renders into (call it from a GPU view's resize callback). It leaves the camera unchanged unless both sizes are positive and finite, so a NaN or infinite size never reaches the projection.
func (*Camera) SyncFromNode ¶
SyncFromNode copies world position and rotation from node into c.
func (*Camera) ViewMatrix ¶
ViewMatrix returns the right-handed view matrix transforming world space into camera view space (inverse of the camera's rigid world transform).
func (*Camera) WorldToScreen ¶
func (c *Camera) WorldToScreen(worldPos math3d.Vec3, viewW, viewH float32) (screen math3d.Vec2, depth float32, visible bool)
WorldToScreen projects a world-space point into viewport pixel coordinates (top-left origin), returning NDC depth in [0, 1] and whether the point lies within the camera frustum.
type Collider ¶
type Collider interface {
// LocalBounds returns the local-space AABB enclosing this collider.
LocalBounds() math3d.AABB
// IntersectRay tests a world-space ray against this collider transformed by
// worldMat. On a hit, it returns ray parameter t >= 0 (with worldRay.At(t)
// equal to the world hit point), unit world-space normal, triangle index
// (-1 if not applicable), and true.
IntersectRay(worldRay math3d.Ray, worldMat math3d.Mat4) (t float32, normal math3d.Vec3, triIndex int, hit bool)
}
Collider provides optional narrow-phase ray intersection for a Node after broad-phase world AABB testing succeeds.
type Decal ¶
type Decal struct {
// Transform positions, orients, and optionally scales the projection box.
Transform math3d.Transform
// HalfExtents sets the local half-size of the projection box before
// Transform.Scale. Zero defaults to (0.5, 0.5, 0.5) (a unit 1x1x1 box).
HalfExtents math3d.Vec3
// Albedo tints the decal (0xRRGGBBAA). Zero defaults to opaque white
// (core.RGB(0xffffff)). Its alpha channel multiplies Opacity.
Albedo core.Color
// TextureID is an optional caller-defined texture or atlas identifier used
// to group draw batches and select textures in [GPUDecalRenderer].
TextureID uint32
// Opacity scales overall visibility in [0, 1].
Opacity float32
// Age is the elapsed lifetime of the decal, advanced by [DecalPool.Step].
Age time.Duration
// Lifetime is the total duration before automatic expiration. Zero or
// negative means the decal does not expire from age (though a full
// [DecalPool] may still evict it).
Lifetime time.Duration
// FadeIn ramps opacity from 0 to 1 over the first FadeIn of Age.
FadeIn time.Duration
// FadeOut ramps opacity from 1 to 0 over the final FadeOut of Lifetime.
FadeOut time.Duration
// AngleFadeStart and AngleFadeEnd are angles in radians from the opposite
// projection axis (+Z). Surfaces within AngleFadeStart get full opacity;
// surfaces at or past AngleFadeEnd (and all back-facing surfaces) fade to 0
// and are rejected. When both are zero, [DefaultDecalAngleFadeStart] and
// [DefaultDecalAngleFadeEnd] are used.
AngleFadeStart float32
AngleFadeEnd float32
// DepthFade in [0, 1] fades opacity smoothly to zero near the front and back
// ends (|local.z| -> 0.5) of the projection box. Zero disables depth fade.
DepthFade float32
// LayerMask selects which [Node.Layer] bitmasks receive this decal. Zero
// matches no nodes; [LayerAll] matches every non-zero layer.
LayerMask uint32
// SortOrder controls both draw ordering (ascending) and pool eviction
// priority (lowest SortOrder is evicted first when a [DecalPool] is full).
SortOrder int32
// Bias offsets projected vertices along receiver surface normals (in world
// units) to prevent z-fighting on forward rendering paths.
Bias float32
}
Decal describes a box-projected 3D decal in world space (#385).
Its projection volume is an oriented box centered at Transform.Pos, rotated by Transform.Rot (identity when zero), with half-extents along local X, Y, Z equal to HalfExtents * Transform.Scale (defaulting to (0.5, 0.5, 0.5) when HalfExtents is zero and (1, 1, 1) when Transform.Scale is zero).
Following math3d conventions, the decal projects along its local forward direction (-Z) onto receiver surfaces whose outward normal faces local +Z. Local box coordinates in [-0.5, 0.5]^3 map to texture coordinates u = local.x + 0.5 and v = 0.5 - local.y (top-left origin for WebGPU/GLES).
func NewDecal ¶
func NewDecal() Decal
NewDecal returns a Decal initialized with sensible defaults: identity transform, unit 1x1x1 box, opaque white albedo, full opacity, LayerAll, 60°–85° normal-angle fade, 0.1 depth fade, and 0.002 normal bias.
func NewDecalOnSurface ¶
NewDecalOnSurface creates a Decal centered at pos, projecting along -normal onto a surface whose outward normal is normal, with local +Y aligned toward up and box half-extents halfExtents.
func (Decal) AngleFade ¶
AngleFade evaluates d's normal-angle attenuation in [0, 1] for a world-space receiver surface normal. Back-facing and perpendicular normals return 0.
func (Decal) EffectiveOpacity ¶
EffectiveOpacity returns d's combined scalar opacity in [0, 1] after applying Opacity, Albedo alpha, and age-based FadeIn / FadeOut.
func (Decal) Forward ¶
Forward returns the decal's unit world-space projection direction (local -Z).
func (Decal) WorldBounds ¶
WorldBounds returns the tight world-space AABB enclosing d's oriented projection box, or math3d.AABBEmpty if d has non-finite or non-positive dimensions.
type DecalBatch ¶
type DecalBatch struct {
DecalID uint64
TextureID uint32
SortOrder int32
FirstIndex uint32
IndexCount uint32
}
DecalBatch describes a contiguous range of indices in a DecalGeometry produced by one decal.
type DecalGeometry ¶
type DecalGeometry struct {
Vertices []DecalVertex
Indices []uint32
Batches []DecalBatch
}
DecalGeometry holds forward-path clipped decal triangles ready for CPU inspection or upload through GPUDecalRenderer. Call Reset to reuse backing storage across frames without allocating.
func (*DecalGeometry) AppendIndexData ¶
func (g *DecalGeometry) AppendIndexData(dst []byte) []byte
AppendIndexData appends g's indices to dst at DecalGeometry.IndexFormat width, little-endian and zero-padded to a 4-byte multiple.
func (*DecalGeometry) AppendVertexData ¶
func (g *DecalGeometry) AppendVertexData(dst []byte) []byte
AppendVertexData appends g's interleaved vertices to dst in the little-endian layout of DecalVertexLayout. It allocates only when dst lacks capacity.
func (*DecalGeometry) Bounds ¶
func (g *DecalGeometry) Bounds() math3d.AABB
Bounds returns the world-space AABB enclosing all vertices in g, or math3d.AABBEmpty when g is empty.
func (*DecalGeometry) IndexCount ¶
func (g *DecalGeometry) IndexCount() int
IndexCount returns the number of triangle indices in g.
func (*DecalGeometry) IndexDataSize ¶
func (g *DecalGeometry) IndexDataSize() int
IndexDataSize returns the byte length DecalGeometry.AppendIndexData writes, padded to a 4-byte multiple as WebGPU requires.
func (*DecalGeometry) IndexFormat ¶
func (g *DecalGeometry) IndexFormat() gpu.IndexFormat
IndexFormat returns gpu.IndexUint16 when every vertex fits below 0xFFFF (leaving WebGL 2's primitive restart sentinel free), otherwise gpu.IndexUint32.
func (*DecalGeometry) Reset ¶
func (g *DecalGeometry) Reset()
Reset clears g's slices while preserving their allocated capacity.
func (*DecalGeometry) TriangleCount ¶
func (g *DecalGeometry) TriangleCount() int
TriangleCount returns the number of projected triangles in g.
func (*DecalGeometry) VertexCount ¶
func (g *DecalGeometry) VertexCount() int
VertexCount returns the number of projected vertices in g.
func (*DecalGeometry) VertexDataSize ¶
func (g *DecalGeometry) VertexDataSize() int
VertexDataSize returns the byte length DecalGeometry.AppendVertexData writes.
type DecalHandle ¶
type DecalHandle struct {
// contains filtered or unexported fields
}
DecalHandle uniquely identifies a live decal stored in a DecalPool. The zero value is invalid.
func (DecalHandle) Valid ¶
func (h DecalHandle) Valid() bool
Valid reports whether h is a non-zero handle.
type DecalPool ¶
type DecalPool struct {
// contains filtered or unexported fields
}
DecalPool is a fixed-capacity pool of live 3D decals (#385).
When the pool reaches capacity, DecalPool.Spawn deterministically evicts the live decal with the lowest Decal.SortOrder, breaking ties by oldest spawn order (FIFO ring behavior when priorities are equal). DecalPool.Step ages live decals and expires those whose Age >= Lifetime. All steady-state operations (Spawn, Remove, Step, BuildGeometry) perform zero heap allocations.
func NewDecalPool ¶
NewDecalPool returns a fixed-capacity DecalPool holding at most maxDecals live decals. A non-positive maxDecals produces a zero-capacity pool.
func (*DecalPool) Active ¶
Active returns a newly allocated slice of all live decals in deterministic draw order (ascending SortOrder, then oldest-to-newest). Use DecalPool.ActiveInto or DecalPool.ForEach to avoid allocating per frame.
func (*DecalPool) ActiveInto ¶
ActiveInto appends all live decals in deterministic draw order to dst and returns the extended slice. Pass dst[:0] for zero-allocation reuse.
func (*DecalPool) BuildGeometry ¶
func (p *DecalPool) BuildGeometry(scene *Scene, dst *DecalGeometry) int
BuildGeometry resets dst and projects every live decal in p onto scene in deterministic draw order (ascending SortOrder, then oldest-to-newest). It returns the total number of projected triangles. After initial slice warmup, BuildGeometry performs zero heap allocations.
func (*DecalPool) BuildReceiverGeometry ¶
func (p *DecalPool) BuildReceiverGeometry(receiver DecalReceiver, worldMat math3d.Mat4, layer uint32, dst *DecalGeometry) int
BuildReceiverGeometry resets dst and projects every live decal in p whose LayerMask matches layer onto receiver transformed by worldMat. It returns the total number of projected triangles.
func (*DecalPool) Clear ¶
func (p *DecalPool) Clear()
Clear removes every live decal from p and invalidates all outstanding handles.
func (*DecalPool) Contains ¶
func (p *DecalPool) Contains(h DecalHandle) bool
Contains reports whether h refers to a currently live decal in p.
func (*DecalPool) ForEach ¶
func (p *DecalPool) ForEach(fn func(DecalHandle, *Decal) bool)
ForEach invokes fn for every live decal in deterministic draw order (ascending SortOrder, then oldest-to-newest). Return false to stop early.
func (*DecalPool) Get ¶
func (p *DecalPool) Get(h DecalHandle) (*Decal, bool)
Get returns a pointer to the live decal identified by h, or (nil, false) if h is invalid, expired, removed, or evicted.
func (*DecalPool) Remove ¶
func (p *DecalPool) Remove(h DecalHandle) bool
Remove deletes the live decal identified by h and returns true if it was present.
func (*DecalPool) Spawn ¶
func (p *DecalPool) Spawn(d Decal) DecalHandle
Spawn inserts d into p and returns its handle. If p is at capacity, the live decal with the lowest SortOrder (and oldest spawn sequence among ties) is evicted deterministically. If p has zero capacity or d is already expired, Spawn returns an invalid zero DecalHandle.
type DecalReceiver ¶
type DecalReceiver interface {
// DecalTriangles invokes emit for each local-space triangle (p0, p1, p2)
// and its local-space vertex normals (n0, n1, n2). Passing zero normals
// tells the projector to derive the flat geometric face normal from
// (p1 - p0) x (p2 - p0). Returning false stops iteration early.
DecalTriangles(emit func(p0, p1, p2, n0, n1, n2 math3d.Vec3) bool)
}
DecalReceiver supplies local-space triangles for box-projected decals. *MeshCollider and *DecalReceiverMesh implement DecalReceiver.
type DecalReceiverMesh ¶
DecalReceiverMesh is indexed or non-indexed local-space triangle geometry that implements DecalReceiver. Positions is required; Normals and Indices are optional.
func (*DecalReceiverMesh) DecalTriangles ¶
func (m *DecalReceiverMesh) DecalTriangles(emit func(p0, p1, p2, n0, n1, n2 math3d.Vec3) bool)
DecalTriangles implements DecalReceiver for DecalReceiverMesh.
func (*DecalReceiverMesh) LocalBounds ¶
func (m *DecalReceiverMesh) LocalBounds() math3d.AABB
LocalBounds returns the tight local-space AABB enclosing m.Positions.
type DecalVertex ¶
type DecalVertex struct {
// Pos is the world-space position offset along Normal by Decal.Bias.
Pos math3d.Vec3
// Normal is the unit world-space surface normal.
Normal math3d.Vec3
// UV is the projected texture coordinate in [0, 1] with top-left origin.
UV math3d.Vec2
// Color holds the linear RGBA tint (R, G, B in [0, 1]) with opacity,
// age fade, normal-angle fade, and depth fade folded into W (alpha).
Color math3d.Vec4
}
DecalVertex is one clipped, biased vertex produced by decal projection.
type FPSController ¶
type FPSController struct {
Pos math3d.Vec3
Yaw float32 // Radians around +Y (0 faces -Z)
Pitch float32 // Radians around local +X (positive looks up)
MinPitch float32 // Defaults to -89° when MinPitch == MaxPitch == 0
MaxPitch float32 // Defaults to +89° when MinPitch == MaxPitch == 0
MoveSpeed float32 // Speed multiplier in units/second (defaults to 1 when <= 0)
Grounded bool // When true, forward/right move on the horizontal XZ plane and up moves along +Y
}
FPSController implements a first-person camera controller with yaw/pitch orientation, clamped pitch, and local forward/right/up movement.
Example ¶
An FPSController moves and turns a first-person camera; Grounded keeps movement on the floor when looking up or down.
package main
import (
"fmt"
"strconv"
"time"
"github.com/nsgo-dev/game/packages/game/math3d"
"github.com/nsgo-dev/game/packages/game/scene3d"
)
// v3 prints v to one decimal, writing a rounded negative zero as 0.
func v3(v math3d.Vec3) string {
num := func(f float32) string {
s := strconv.FormatFloat(float64(f), 'f', 1, 32)
if s == "-0.0" {
s = "0.0"
}
return s
}
return "(" + num(v.X) + ", " + num(v.Y) + ", " + num(v.Z) + ")"
}
func main() {
fps := scene3d.NewFPSController(math3d.Vec3{Y: 1.7})
fps.Grounded = true
fps.MoveSpeed = 4
fps.Look(0, math3d.DegToRad(30))
for range 30 {
fps.Move(1, 0, 0, time.Second/60) // half a second forward in all
}
fmt.Println(v3(fps.Pos))
}
Output: (0.0, 1.7, -2.0)
func NewFPSController ¶
func NewFPSController(pos math3d.Vec3) *FPSController
NewFPSController creates an FPSController at pos with pitch clamped to [-89°, +89°].
func (*FPSController) Apply ¶
func (c *FPSController) Apply(cam *Camera)
Apply writes the controller's current Pos and Rotation into cam.
func (*FPSController) Forward ¶
func (c *FPSController) Forward() math3d.Vec3
Forward returns the controller's local unit forward vector.
func (*FPSController) Look ¶
func (c *FPSController) Look(deltaYaw, deltaPitch float32)
Look adjusts Yaw and Pitch by (deltaYaw, deltaPitch) radians, clamping Pitch to [MinPitch, MaxPitch].
func (*FPSController) Move ¶
func (c *FPSController) Move(forward, right, up float32, dt time.Duration)
Move translates Pos along the controller's local forward, right, and up axes scaled by MoveSpeed and dt.
func (*FPSController) Right ¶
func (c *FPSController) Right() math3d.Vec3
Right returns the controller's local unit right vector.
func (*FPSController) Rotation ¶
func (c *FPSController) Rotation() math3d.Quat
Rotation returns the unit orientation quaternion for (Yaw, Pitch).
func (*FPSController) Up ¶
func (c *FPSController) Up() math3d.Vec3
Up returns the controller's local unit up vector.
type GPUDecalOptions ¶
type GPUDecalOptions struct {
// Label prefixes GPU resource labels in capture tools.
Label string
// DepthFormat is the depth attachment format of the forward render pass, or
// gpu.FormatUndefined when drawing without a depth buffer.
DepthFormat gpu.TextureFormat
// CameraLayout is an optional bind group layout for @group(0) matching
// [DecalWGSL] (such as render3d.CameraBuffer.Layout()). When nil, the
// renderer owns its own camera uniform buffer updated via
// [GPUDecalRenderer.WriteCamera].
CameraLayout *gpu.BindGroupLayout
// Retained opts owned GPU buffers, sampler, and textures into automatic
// recreation across GPU device loss.
Retained bool
// DepthBias and DepthBiasSlopeScale push decal fragments slightly closer in
// the depth buffer in addition to Decal.Bias along the surface normal. When
// both are zero and DepthFormat is set, defaults of -1 and -1.0 are used.
DepthBias int32
DepthBiasSlopeScale float32
// DoubleSided disables back-face culling (gpu.CullNone) when true; the
// default false uses gpu.CullBack.
DoubleSided bool
}
GPUDecalOptions configures NewGPUDecalRenderer.
type GPUDecalRenderer ¶
type GPUDecalRenderer struct {
// contains filtered or unexported fields
}
GPUDecalRenderer draws DecalGeometry on the forward rendering path with alpha blending, depth testing without depth writes, and optional per-TextureID albedo textures (#385).
Create it once when the GPU device is ready (in gpu.View OnReady or on a software device), upload projected decals with GPUDecalRenderer.Upload, and call GPUDecalRenderer.Draw (or GPUDecalRenderer.DrawWithCamera when sharing a render3d.CameraBuffer) inside the opaque/forward render pass after drawing scene geometry.
func NewGPUDecalRenderer ¶
func NewGPUDecalRenderer(cx *core.Scope, dev *gpu.Device, opts GPUDecalOptions) (*GPUDecalRenderer, error)
NewGPUDecalRenderer compiles DecalWGSL and creates the forward decal pipeline, default white albedo texture, sampler, and (when opts.CameraLayout is nil) an internal camera uniform buffer on dev, scoped to cx.
func (*GPUDecalRenderer) CameraLayout ¶
func (r *GPUDecalRenderer) CameraLayout() *gpu.BindGroupLayout
CameraLayout returns the bind group layout used at @group(0).
func (*GPUDecalRenderer) Close ¶
func (r *GPUDecalRenderer) Close() error
Close releases all GPU resources owned by r. It is safe to call more than once.
func (*GPUDecalRenderer) Draw ¶
func (r *GPUDecalRenderer) Draw(pass *gpu.RenderPass)
Draw records the uploaded decal draws into pass using the renderer's internal camera bind group (updated via GPUDecalRenderer.WriteCamera). It is a no-op if no decals are uploaded or if the renderer was configured with an external CameraLayout (use GPUDecalRenderer.DrawWithCamera instead).
func (*GPUDecalRenderer) DrawWithCamera ¶
func (r *GPUDecalRenderer) DrawWithCamera(pass *gpu.RenderPass, cameraGroup *gpu.BindGroup)
DrawWithCamera records the uploaded decal draws into pass using cameraGroup at @group(0) (for example, render3d.CameraBuffer.BindGroup()). Consecutive batches that share the same TextureID are merged into a single DrawIndexed call.
func (*GPUDecalRenderer) IndexCount ¶
func (r *GPUDecalRenderer) IndexCount() uint32
IndexCount returns the number of decal triangle indices currently uploaded.
func (*GPUDecalRenderer) Pipeline ¶
func (r *GPUDecalRenderer) Pipeline() *gpu.Pipeline
Pipeline returns the renderer's forward decal pipeline.
func (*GPUDecalRenderer) SetTexture ¶
func (r *GPUDecalRenderer) SetTexture(id uint32, tex *gpu.Texture) error
SetTexture associates a caller-managed GPU texture with id so decals with Decal.TextureID == id sample tex. Passing nil removes the binding and reverts id to the default 1x1 white texture.
func (*GPUDecalRenderer) TextureLayout ¶
func (r *GPUDecalRenderer) TextureLayout() *gpu.BindGroupLayout
TextureLayout returns the bind group layout used at @group(1).
func (*GPUDecalRenderer) Upload ¶
func (r *GPUDecalRenderer) Upload(geom *DecalGeometry) error
Upload copies geom's vertices, indices, and batch ranges to GPU buffers, reusing previously allocated buffers whenever they are large enough.
func (*GPUDecalRenderer) UploadTextureRGBA ¶
func (r *GPUDecalRenderer) UploadTextureRGBA(id uint32, width, height uint32, rgba []byte) error
UploadTextureRGBA creates a FormatRGBA8Unorm texture of dimensions width x height, uploads rgba (4 bytes per pixel, tightly packed), and binds it to id. The renderer owns and closes the created texture on replacement or Close.
func (*GPUDecalRenderer) WriteCamera ¶
func (r *GPUDecalRenderer) WriteCamera(cam *Camera)
WriteCamera uploads cam's view, projection, view-projection, and eye point to the renderer's internal camera uniform buffer. It is a no-op if the renderer was constructed with an external CameraLayout or if cam is nil.
func (*GPUDecalRenderer) WriteCameraMatrices ¶
func (r *GPUDecalRenderer) WriteCameraMatrices(view, proj math3d.Mat4, eye math3d.Vec4)
WriteCameraMatrices uploads explicit view, projection, and homogeneous eye values to the renderer's internal camera uniform buffer.
type MeshCollider ¶
MeshCollider performs exact double-sided ray-triangle intersection against a triangle soup stored in node-local space. Every 3 consecutive vertices in Triangles form one triangle (v0, v1, v2).
LocalBounds is cached: replacing or resizing Triangles is detected automatically, but after editing vertices of the same slice in place call MarkDirty. Either way the owning node's world bounds and BVH entry refresh only when the node is marked dirty, so call the node's MarkDirty (or SetCollider) after changing Triangles, or BVH-driven raycasts and picks keep testing the old bounds.
func (*MeshCollider) DecalTriangles ¶
func (m *MeshCollider) DecalTriangles(emit func(p0, p1, p2, n0, n1, n2 math3d.Vec3) bool)
DecalTriangles implements DecalReceiver for MeshCollider, emitting every complete triangle in m.Triangles with flat geometric face normals.
func (*MeshCollider) IntersectRay ¶
func (m *MeshCollider) IntersectRay(worldRay math3d.Ray, worldMat math3d.Mat4) (float32, math3d.Vec3, int, bool)
IntersectRay tests worldRay against every triangle in m using Ray.IntersectTriangle, returning the closest hit with t >= 0.
func (*MeshCollider) LocalBounds ¶
func (m *MeshCollider) LocalBounds() math3d.AABB
LocalBounds returns the tight local-space AABB containing all complete triangles in m.Triangles. The result is cached until Triangles is replaced or resized or MarkDirty is called, so node syncs and picks do not rescan every triangle (#546).
func (*MeshCollider) MarkDirty ¶
func (m *MeshCollider) MarkDirty()
MarkDirty drops the cached LocalBounds after vertices in Triangles were edited in place. Call the owning node's MarkDirty too so its world bounds and BVH entry refresh.
type Node ¶
type Node struct {
Name string
Local math3d.Transform
Visible bool
Enabled bool
Layer uint32
LocalBounds math3d.AABB
Tags []string
UserData any
Attachments map[string]any
Collider Collider
// contains filtered or unexported fields
}
Node is a transformable element in a 3D scene hierarchy.
Always construct nodes with NewNode so Local defaults to TransformIdentity, Visible and Enabled default to true, Layer defaults to LayerDefault, and LocalBounds defaults to AABBEmpty.
World transforms, matrices, and bounds are cached and recomputed lazily when dirty. Prefer the setter methods (SetLocal, SetPosition, SetRotation, SetScale, SetLocalBounds) or call MarkDirty after mutating Local directly so dirty flags propagate immediately to descendants.
Example ¶
Nodes form a hierarchy in a Scene: a child's world transform follows its parent's, and sockets mark points to attach things to, such as a hand holding a sword.
package main
import (
"fmt"
"strconv"
"github.com/nsgo-dev/game/packages/game/math3d"
"github.com/nsgo-dev/game/packages/game/scene3d"
)
// v3 prints v to one decimal, writing a rounded negative zero as 0.
func v3(v math3d.Vec3) string {
num := func(f float32) string {
s := strconv.FormatFloat(float64(f), 'f', 1, 32)
if s == "-0.0" {
s = "0.0"
}
return s
}
return "(" + num(v.X) + ", " + num(v.Y) + ", " + num(v.Z) + ")"
}
func main() {
s := scene3d.NewScene()
knight := scene3d.NewNode("knight")
knight.SetPosition(math3d.Vec3{X: 5})
knight.DefineSocket("hand", math3d.Transform{Pos: math3d.Vec3{X: 0.5, Y: 1.2}, Rot: math3d.QuatIdentity(), Scale: math3d.Vec3One()})
s.Add(knight)
sword := scene3d.NewNode("sword")
sword.AddTag("weapon")
if err := knight.Attach("hand", sword); err != nil {
fmt.Println(err)
return
}
s.UpdateTransforms()
fmt.Println(v3(sword.WorldTransform().Pos))
fmt.Println(len(s.Root().FindByTag("weapon")), s.FindByName("sword").IsDescendantOf(knight))
}
Output: (5.5, 1.2, 0.0) 1 true
func NewNode ¶
NewNode returns a new visible, enabled Node with an identity local transform, LayerDefault, and an empty local bounding box.
func (*Node) AddChild ¶
AddChild attaches child as a direct child of n, detaching it from any previous parent. It returns ErrNilNode if child is nil and ErrCycle if child is n or an ancestor of n.
func (*Node) Attach ¶
Attach mounts child onto the named socket point of n.
If socket is empty, child is added directly to n. Otherwise, Attach resolves an existing defined socket or descendant node with that name, or creates a new identity socket node under n if none exists yet. Cycle checks run before creating any implicit socket so failed calls leave n unmodified.
func (*Node) Attached ¶
Attached returns a shallow copy of the nodes currently attached to the named socket on n, or nil if the socket does not exist.
func (*Node) Attachment ¶
Attachment retrieves the named attachment value from n.
func (*Node) DecalReceiver ¶
func (n *Node) DecalReceiver() DecalReceiver
DecalReceiver returns n's DecalReceiver attachment if present, or n.Collider if it implements DecalReceiver, or nil otherwise.
func (*Node) DefineSocket ¶
DefineSocket creates or updates a named socket attachment point on n with the given local transform relative to n and returns the socket node.
Children attached via Attach(name, child) become children of this socket node and follow n's transforms automatically.
func (*Node) Detach ¶
Detach removes n from its current parent. When keepWorld is true, n.Local is updated to n's prior world transform so its world pose is preserved exactly. Returns true if n had a parent and was detached.
func (*Node) DirtyUpdates ¶
DirtyUpdates returns the cumulative number of times n's cached world transform and matrix have been recomputed.
func (*Node) EffectiveEnabled ¶
EffectiveEnabled reports whether n and every ancestor up to the root have Enabled == true.
func (*Node) EffectiveVisible ¶
EffectiveVisible reports whether n and every ancestor up to the root have Visible == true.
func (*Node) FindByName ¶
FindByName searches n and its descendants in pre-order for the first node whose Name equals name, or nil if none matches.
func (*Node) FitBoundsToCollider ¶
func (n *Node) FitBoundsToCollider()
FitBoundsToCollider copies n.Collider.LocalBounds() into n.LocalBounds when n.Collider is non-nil.
func (*Node) HierarchyBounds ¶
HierarchyBounds returns the union of WorldBounds for n and all visible, enabled descendants in its subtree.
func (*Node) IsDescendantOf ¶
IsDescendantOf reports whether ancestor is an ancestor of n in the hierarchy.
func (*Node) MarkDirty ¶
func (n *Node) MarkDirty()
MarkDirty invalidates cached world transforms and bounds for n and every descendant in its subtree.
func (*Node) RemoveAttachment ¶
RemoveAttachment deletes the named attachment key from n.
func (*Node) RemoveChild ¶
RemoveChild detaches child from n and returns true if child was a direct child of n.
func (*Node) Reparent ¶
Reparent moves n under newParent while keeping n's Local transform unchanged. Passing nil detaches n from its current parent. It returns ErrCycle if newParent is n or a descendant of n.
func (*Node) ReparentKeepWorld ¶
ReparentKeepWorld moves n under newParent while adjusting n.Local so n remains at its current world matrix. Passing nil detaches n to root.
It returns ErrNotDecomposable and changes nothing when newParent's world matrix is singular or the exact local transform needs shear, which a Transform cannot hold (a rotated child under a non-uniformly scaled parent).
func (*Node) SetAttachment ¶
SetAttachment stores an arbitrary named attachment value (such as a mesh, light, audio emitter, or gameplay component) on n.
func (*Node) SetCollider ¶
SetCollider assigns a narrow-phase Collider to n and invalidates cached world bounds.
func (*Node) SetDecalReceiver ¶
func (n *Node) SetDecalReceiver(r DecalReceiver)
SetDecalReceiver attaches r to n under DecalReceiverAttachment. If n has empty LocalBounds and r implements LocalBounds() math3d.AABB, n's LocalBounds is populated so the scene BVH indexes n automatically. Passing nil removes the attachment.
func (*Node) SetLocalBounds ¶
SetLocalBounds updates n.LocalBounds and invalidates n's cached world bounds.
func (*Node) SetParent ¶
SetParent moves n under newParent (or detaches it to root when newParent is nil). When keepWorld is true, n.Local is adjusted so n preserves its current world transform; when false, n.Local is left unchanged.
func (*Node) SetPosition ¶
SetPosition updates n.Local.Pos and marks n and all descendants dirty.
func (*Node) SetRotation ¶
SetRotation updates n.Local.Rot and marks n and all descendants dirty.
func (*Node) Socket ¶
Socket returns the node for a named socket on n, checking sockets defined on n first and then searching n's descendants by name (for example, skeleton bone nodes). Returns nil if no matching socket exists.
func (*Node) Walk ¶
Walk traverses n and its descendants in pre-order depth-first order, calling fn on each node. If fn returns false, traversal stops immediately.
func (*Node) WorldBounds ¶
WorldBounds returns the tight world-space AABB enclosing both n's LocalBounds and its Collider's local bounds, recomputing lazily when dirty. A collider that extends past the visual mesh must stay queryable by BVH and raycasts. Returns AABBEmpty if n has no bounds.
func (*Node) WorldMatrix ¶
WorldMatrix returns n's composed world-space 4x4 transformation matrix, recomputing lazily if n or any ancestor is dirty.
func (*Node) WorldTransform ¶
WorldTransform returns n's composed world-space TRS transform, recomputing lazily if n or any ancestor is dirty.
type OrbitController ¶
type OrbitController struct {
Target math3d.Vec3
Yaw float32 // Radians around +Y (0 places camera at +Z looking down -Z)
Pitch float32 // Radians elevation above Target (clamped to [MinPitch, MaxPitch])
Distance float32 // Distance from Target (clamped to [MinDistance, MaxDistance])
MinPitch float32 // Defaults to -89° when MinPitch == MaxPitch == 0
MaxPitch float32 // Defaults to +89° when MinPitch == MaxPitch == 0
MinDistance float32 // Minimum zoom distance (clamped >= 0.001)
MaxDistance float32 // Maximum zoom distance (<= 0 means unbounded)
Damping float32 // Exponential damping rate in 1/s (<= 0 disables damping)
// contains filtered or unexported fields
}
OrbitController orbits a Camera around Target using spherical coordinates (Yaw, Pitch, Distance) with clamped pitch, zoom limits, screen-plane panning, and optional exponential per-step damping.
Example ¶
An OrbitController turns a camera around a target, as an editor's or a strategy game's camera does.
package main
import (
"fmt"
"strconv"
"github.com/nsgo-dev/game/packages/game/math3d"
"github.com/nsgo-dev/game/packages/game/scene3d"
)
// v3 prints v to one decimal, writing a rounded negative zero as 0.
func v3(v math3d.Vec3) string {
num := func(f float32) string {
s := strconv.FormatFloat(float64(f), 'f', 1, 32)
if s == "-0.0" {
s = "0.0"
}
return s
}
return "(" + num(v.X) + ", " + num(v.Y) + ", " + num(v.Z) + ")"
}
func main() {
orbit := scene3d.NewOrbitController(math3d.Vec3Zero(), 10)
orbit.SetAngles(math3d.DegToRad(90), 0)
cam := scene3d.NewPerspectiveCamera(math3d.Vec3Zero(), math3d.DegToRad(60), 1, 0.1, 100)
orbit.Apply(cam)
fmt.Println(v3(cam.Pos), v3(cam.Forward()))
}
Output: (10.0, 0.0, 0.0) (-1.0, 0.0, 0.0)
func NewOrbitController ¶
func NewOrbitController(target math3d.Vec3, distance float32) *OrbitController
NewOrbitController creates an OrbitController orbiting target at distance with default pitch limits [-89°, +89°] and zoom limits [0.1, 1000].
func (*OrbitController) Apply ¶
func (c *OrbitController) Apply(cam *Camera)
Apply writes the controller's current pose into cam.
func (*OrbitController) Orbit ¶
func (c *OrbitController) Orbit(deltaYaw, deltaPitch float32)
Orbit adjusts the desired yaw and pitch by (deltaYaw, deltaPitch) radians, clamping pitch to [MinPitch, MaxPitch]. When Damping <= 0, current angles update immediately.
func (*OrbitController) Pan ¶
func (c *OrbitController) Pan(deltaRight, deltaUp float32)
Pan shifts the orbit target within the camera's local right/up plane.
func (*OrbitController) SetAngles ¶
func (c *OrbitController) SetAngles(yaw, pitch float32)
SetAngles sets the desired yaw and pitch in radians, clamping pitch.
func (*OrbitController) SetDistance ¶
func (c *OrbitController) SetDistance(distance float32)
SetDistance sets the desired orbit distance, clamped to [MinDistance, MaxDistance].
func (*OrbitController) SetTarget ¶
func (c *OrbitController) SetTarget(target math3d.Vec3)
SetTarget updates the desired orbit target.
func (*OrbitController) Snap ¶
func (c *OrbitController) Snap()
Snap immediately sets current Target, Yaw, Pitch, and Distance to their desired values with no damping lag.
func (*OrbitController) Step ¶
func (c *OrbitController) Step(dt time.Duration)
Step advances orbit damping by dt. Call this inside game.Loop.Update.
func (*OrbitController) Update ¶
func (c *OrbitController) Update(cam *Camera, dt time.Duration)
Update advances damping by dt and applies the resulting pose to cam.
func (*OrbitController) Zoom ¶
func (c *OrbitController) Zoom(delta float32)
Zoom adjusts the desired orbit distance by delta (positive zooms out, negative zooms in), clamped to [MinDistance, MaxDistance].
type Projection ¶
type Projection struct {
Kind ProjectionKind
FOVY float32 // Vertical field of view in radians (ProjectionPerspective)
OrthoHeight float32 // Full vertical world height (ProjectionOrthographic)
Aspect float32 // Viewport width / height
Near float32 // Near clip plane distance
Far float32 // Far clip plane distance
}
Projection configures a Camera's projection matrix.
func OrthographicProjection ¶
func OrthographicProjection(orthoHeight, aspect, near, far float32) Projection
OrthographicProjection returns an orthographic Projection configuration.
func PerspectiveProjection ¶
func PerspectiveProjection(fovY, aspect, near, far float32) Projection
PerspectiveProjection returns a perspective Projection configuration.
func (Projection) Lerp ¶
func (p Projection) Lerp(b Projection, t float32) Projection
Lerp interpolates from p (t=0) to b (t=1). When both projections share a Kind, FOVY, OrthoHeight, Aspect, Near and Far blend linearly between the values Matrix uses, so a field left at zero blends from its default rather than from zero; when the Kinds differ there is nothing between them to blend, so Lerp returns p for t < 1 and b from t = 1 on.
func (Projection) Matrix ¶
func (p Projection) Matrix() math3d.Mat4
Matrix builds the column-major projection matrix for p using [0, 1] NDC depth. Fields left at zero or otherwise out of range take defaults: Aspect 1; FOVY 60 degrees and Near 0.1 for a perspective projection; OrthoHeight 2, and Near, Far 0.1, 1000 when both are zero, for an orthographic one; and Far Near+1000 when it is not beyond Near.
type ProjectionKind ¶
type ProjectionKind uint8
ProjectionKind selects perspective or orthographic camera projection.
const ( // ProjectionPerspective projects a perspective view frustum. ProjectionPerspective ProjectionKind = iota // ProjectionOrthographic projects an orthographic parallel view volume. ProjectionOrthographic )
type RayHit ¶
type RayHit struct {
Node *Node
T float32 // Parameter along the ray such that Point == ray.At(T)
Point math3d.Vec3 // Intersection point in world space
Normal math3d.Vec3 // Outward unit surface normal in world space
TriangleIndex int // Hit triangle index for MeshCollider, or -1 otherwise
}
RayHit describes an intersection between a ray and a scene node.
func Pick ¶
func Pick(scene *Scene, cam *Camera, screenX, screenY, viewW, viewH float32, layerMask uint32) (RayHit, bool)
Pick unprojects screen pixel coordinates (screenX, screenY) in a viewport of size (viewW, viewH) through cam and returns the closest hit visible node in scene matching layerMask.
Example ¶
Pick casts a ray from a point on the screen through the camera and returns the nearest node with a collider it hits.
package main
import (
"fmt"
"strconv"
"github.com/nsgo-dev/game/packages/game/math3d"
"github.com/nsgo-dev/game/packages/game/scene3d"
)
// v3 prints v to one decimal, writing a rounded negative zero as 0.
func v3(v math3d.Vec3) string {
num := func(f float32) string {
s := strconv.FormatFloat(float64(f), 'f', 1, 32)
if s == "-0.0" {
s = "0.0"
}
return s
}
return "(" + num(v.X) + ", " + num(v.Y) + ", " + num(v.Z) + ")"
}
func main() {
s := scene3d.NewScene()
barrel := scene3d.NewNode("barrel")
barrel.SetPosition(math3d.Vec3{Z: -10})
barrel.SetCollider(&scene3d.SphereCollider{Radius: 1})
s.Add(barrel)
s.UpdateTransforms()
cam := scene3d.NewPerspectiveCamera(math3d.Vec3Zero(), math3d.DegToRad(60), 16.0/9, 0.1, 100)
hit, ok := scene3d.Pick(s, cam, 640, 360, 1280, 720, scene3d.LayerAll)
fmt.Println(ok, hit.Node.Name, v3(hit.Point))
_, ok = scene3d.Pick(s, cam, 10, 10, 1280, 720, scene3d.LayerAll)
fmt.Println(ok)
}
Output: true barrel (0.0, 0.0, -9.0) false
func PickAll ¶
func PickAll(scene *Scene, cam *Camera, screenX, screenY, viewW, viewH float32, layerMask uint32) []RayHit
PickAll unprojects screen pixel coordinates (screenX, screenY) in a viewport of size (viewW, viewH) through cam and returns all hit visible nodes in scene matching layerMask sorted by ascending distance from the ray origin.
type Scene ¶
type Scene struct {
// contains filtered or unexported fields
}
Scene owns a root Node and a dynamic BVH spatial index for O(log N) frustum culling, volume queries, and raycasts over visible, enabled nodes.
func NewScene ¶
func NewScene() *Scene
NewScene returns a new Scene with an initialized root Node named "root" and an empty dynamic BVH spatial index.
func (*Scene) BVH ¶
BVH synchronizes pending node updates and returns the scene's underlying dynamic BVH.
func (*Scene) CullFrustum ¶
CullFrustum returns all visible, enabled nodes whose world bounds intersect frustum, accelerated by the scene's dynamic BVH.
func (*Scene) CullFrustumInto ¶
CullFrustumInto appends all visible, enabled nodes whose world bounds intersect frustum to out using the scene's dynamic BVH. Pass a reused slice (e.g. buf[:0]) for zero-allocation per-frame culling.
func (*Scene) DirtyUpdates ¶
DirtyUpdates returns the number of node world transforms recomputed during the most recent call to Scene.UpdateTransforms.
func (*Scene) FindByName ¶
FindByName searches the scene root and its descendants for the first node named name.
func (*Scene) QueryAABB ¶
QueryAABB returns all visible, enabled nodes whose world bounds overlap or touch box, accelerated by the scene's dynamic BVH.
func (*Scene) QueryFrustum ¶
QueryFrustum returns all visible, enabled nodes whose world bounds intersect the frustum extracted from view-projection matrix vp (assuming math3d's default [0, 1] NDC depth).
func (*Scene) QueryFrustumVolume ¶
QueryFrustumVolume returns all visible, enabled nodes whose world bounds intersect f.
func (*Scene) QuerySphere ¶
QuerySphere returns all visible, enabled nodes whose world bounds overlap or touch sphere, accelerated by the scene's dynamic BVH.
func (*Scene) Raycast ¶
Raycast casts ray against all visible, enabled nodes in s matching layerMask, performing BVH broad-phase world AABB culling and optional narrow-phase Collider tests. Hits are returned sorted by ascending ray parameter T.
func (*Scene) RaycastFirst ¶
RaycastFirst casts ray against all visible, enabled nodes in s matching layerMask and returns the closest intersection (smallest T >= 0), or false if nothing was hit. Uses BVH near-to-far traversal with dynamic distance pruning.
func (*Scene) RebuildBVH ¶
func (s *Scene) RebuildBVH()
RebuildBVH updates dirty node transforms, synchronizes all scene node bounds, and reconstructs the scene's BVH top-down using the Surface Area Heuristic (SAH) for optimal query performance.
func (*Scene) SyncBVH ¶
func (s *Scene) SyncBVH()
SyncBVH incrementally updates the scene's BVH for nodes whose transforms, bounds, or hierarchy membership changed since the last sync. When no nodes are dirty, SyncBVH runs in O(1) time.
func (*Scene) UpdateTransforms ¶
UpdateTransforms traverses the scene hierarchy top-down and recomputes cached world transforms and matrices only for dirty nodes (including nodes whose Local transform was mutated directly or whose ancestor changed). Clean nodes perform zero matrix recomputations.
It returns the number of nodes recomputed and records that count for Scene.DirtyUpdates.
type SphereCollider ¶
SphereCollider performs exact ray-sphere intersection in node-local space.
func (*SphereCollider) IntersectRay ¶
func (s *SphereCollider) IntersectRay(worldRay math3d.Ray, worldMat math3d.Mat4) (float32, math3d.Vec3, int, bool)
IntersectRay tests worldRay against s in local space (accurately supporting arbitrary rotation and non-uniform scale).
func (*SphereCollider) LocalBounds ¶
func (s *SphereCollider) LocalBounds() math3d.AABB
LocalBounds returns the tight local-space AABB enclosing s.
type ThirdPersonController ¶
type ThirdPersonController struct {
// Offset shifts the target pivot in target-local coordinates (+X right, +Y up, +Z forward).
Offset math3d.Vec3
// Distance is the trailing distance behind the target pivot.
Distance float32
// Height is the vertical elevation above the target pivot.
Height float32
// LookAhead shifts the look point forward along target facing from the pivot.
LookAhead float32
// PositionSmoothing is the exponential smoothing rate (1/s) for camera Pos (<= 0 snaps).
PositionSmoothing float32
// LookSmoothing is the exponential smoothing rate (1/s) for LookTarget (<= 0 snaps).
LookSmoothing float32
// ObstructionPadding keeps the pulled-back camera this distance in front of an obstacle.
ObstructionPadding float32
// MinDistance is the closest distance the camera pulls to the pivot when obstructed.
MinDistance float32
// ObstructionCheck tests the segment from the target pivot (from) to the camera
// position (to). When obstructed, it returns the normalized hit fraction t in [0, 1]
// along from->to and true.
ObstructionCheck func(from, to math3d.Vec3) (float32, bool)
// Pos is the current world-space camera position.
Pos math3d.Vec3
// LookTarget is the current world-space point the camera is looking at.
LookTarget math3d.Vec3
}
ThirdPersonController follows a moving target position and facing direction with configurable offset, trailing distance, height, look-ahead, exponential per-step smoothing, and optional raycast obstruction pullback.
func NewThirdPersonController ¶
func NewThirdPersonController() *ThirdPersonController
NewThirdPersonController returns a ThirdPersonController with balanced defaults.
func (*ThirdPersonController) Apply ¶
func (c *ThirdPersonController) Apply(cam *Camera)
Apply writes the controller's current Pos and orientation into cam.
func (*ThirdPersonController) Snap ¶
func (c *ThirdPersonController) Snap(targetPos, targetForward math3d.Vec3)
Snap immediately moves Pos and LookTarget to the ideal follow configuration for (targetPos, targetForward), respecting ObstructionCheck.